Compare commits

...
Author SHA1 Message Date
shadowdaoandClaude Opus 5.5 73eb507cfe feat(docker): tell "not running" apart from "not installed"
Secret Scan / scan (push) Successful in 15s
Build App (Preview) / compute-version (pull_request) Successful in 7s
Secret Scan / scan (pull_request) Successful in 15s
Build App (Preview) / test (pull_request) Successful in 11m20s
Build App (Preview) / create-release (pull_request) Successful in 5s
Build App (Preview) / build-macos (pull_request) Successful in 6m51s
Build App (Preview) / build-linux (pull_request) Successful in 13m0s
Build App (Preview) / build-windows (pull_request) Successful in 13m49s
Build App (Preview) / prune-previews (pull_request) Successful in 2s
The app told a user whose Docker daemon had hit systemd start-limit-hit
to install Docker. New check_docker_status command classifies the ping
failure (io error kind in the bollard/hyper chain) plus cheap installed-
ness probes into running / not_running / no_permission / not_installed,
reports the endpoint tried (DOCKER_HOST respected), and the dialog, top
bar, welcome checklist and Docker settings show per-state guidance. The
dialog updates live from polling and closes when Docker comes up.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:26:37 -08:00
shadowdao 67b80f73c3 Merge remote-tracking branch 'origin/feat/bundle-ssm-plugin' into fix/hosts-ui 2026-11-17 12:21:35 -08:00
shadowdaoandClaude Opus 5.5 90fae8451f fix(aws): review fixes for hosts settings
Secret Scan / scan (push) Successful in 8s
Build App (Preview) / compute-version (pull_request) Successful in 6s
Secret Scan / scan (pull_request) Successful in 14s
Build App (Preview) / create-release (pull_request) Successful in 2s
Build App (Preview) / test (pull_request) Successful in 9m36s
Build App (Preview) / build-macos (pull_request) Successful in 6m14s
Build App (Preview) / build-windows (pull_request) Successful in 11m11s
Build App (Preview) / build-linux (pull_request) Successful in 21m26s
Build App (Preview) / prune-previews (pull_request) Successful in 3s
- Runs carry an explicit kind (deploy, follow, repair, update, destroy,
  onboard, push, boundary); the admin-bundle offer after an AWS refusal
  keys on kind deploy/onboard, not the label, so a refused follow of an
  existing environment's deploy no longer offers a new-environment bundle.
- looksDenied no longer matches a bare "explicit deny" (SCP and bucket
  policy denies aren't fixed by a bundle); the hint says it may need an admin.
- The aws sso login hint breaks long profile names.
- The "Not an admin?" disclosure shows a ▸/▾ marker like the Environments
  toggle.
- Note: the previous commit's Modal footer flex-wrap is app-wide (every
  modal's buttons now wrap when the dialog is narrow); kept deliberately.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:19:04 -08:00
shadowdaoandClaude Opus 5.5 a93a8135be fix(aws): settings layout and deploy for anyone who can
Build App (Preview) / compute-version (pull_request) Successful in 5s
Secret Scan / scan (push) Successful in 23s
Secret Scan / scan (pull_request) Successful in 9s
Build App (Preview) / create-release (pull_request) Successful in 3s
Build App (Preview) / build-macos (pull_request) Successful in 6m24s
Build App (Preview) / build-windows (pull_request) Successful in 11m28s
Build App (Preview) / build-linux (pull_request) Successful in 23m6s
Build App (Preview) / test (pull_request) Successful in 26m21s
Build App (Preview) / prune-previews (pull_request) Successful in 5s
Hosts settings live in a 224-320px sidebar; nowrap buttons and long ARNs,
policy names and run summaries overflowed it. Button and StatusIndicator get
an opt-in wrap prop; host, environment, progress and policy rows wrap with
min-w-0 children; policy copy buttons sit in an auto-fill grid; pre blocks
scroll; the Modal footer wraps.

Deploy a new environment and self-join are offered to anyone after a scan.
When the permission check didn't confirm environment-admin rights a note
says AWS has the last word, and the policies and environment request sit
under a 'Not an admin?' disclosure. The boundary note shows whenever the
boundary is missing. AWS refusals show AWS's message (awsErrorMessage now
names the denied action) and offer the admin bundle: in the deploy and join
modals, and under a failed deploy/join run whose output reads as denied.
The backend already had no tier check on onboard_aws_user; its comment is
corrected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:16:55 -08:00
40 changed files with 1228 additions and 200 deletions

No files matched your search

+1
View File
@@ -9,6 +9,7 @@
"dialog:allow-open", "dialog:allow-open",
"dialog:allow-save", "dialog:allow-save",
"allow-check-docker", "allow-check-docker",
"allow-check-docker-status",
"allow-check-image-exists", "allow-check-image-exists",
"allow-build-image", "allow-build-image",
"allow-get-container-info", "allow-get-container-info",
+1 -1
View File
@@ -1 +1 @@
{"__app-acl__":{"default_permission":null,"permissions":{"allow-acquire-claude-token":{"identifier":"allow-acquire-claude-token","description":"Enables the acquire_claude_token command without any pre-configured scope.","commands":{"allow":["acquire_claude_token"],"deny":[]}},"allow-add-aws-keys-connection":{"identifier":"allow-add-aws-keys-connection","description":"Enables the add_aws_keys_connection command without any pre-configured scope.","commands":{"allow":["add_aws_keys_connection"],"deny":[]}},"allow-add-aws-profile-connection":{"identifier":"allow-add-aws-profile-connection","description":"Enables the add_aws_profile_connection command without any pre-configured scope.","commands":{"allow":["add_aws_profile_connection"],"deny":[]}},"allow-add-marketplace":{"identifier":"allow-add-marketplace","description":"Enables the add_marketplace command without any pre-configured scope.","commands":{"allow":["add_marketplace"],"deny":[]}},"allow-add-marketplace-gh-host-account":{"identifier":"allow-add-marketplace-gh-host-account","description":"Enables the add_marketplace_gh_host_account command without any pre-configured scope.","commands":{"allow":["add_marketplace_gh_host_account"],"deny":[]}},"allow-add-marketplace-token-account":{"identifier":"allow-add-marketplace-token-account","description":"Enables the add_marketplace_token_account command without any pre-configured scope.","commands":{"allow":["add_marketplace_token_account"],"deny":[]}},"allow-add-project":{"identifier":"allow-add-project","description":"Enables the add_project command without any pre-configured scope.","commands":{"allow":["add_project"],"deny":[]}},"allow-add-scheduled-task":{"identifier":"allow-add-scheduled-task","description":"Enables the add_scheduled_task command without any pre-configured scope.","commands":{"allow":["add_scheduled_task"],"deny":[]}},"allow-apply-marketplace-now":{"identifier":"allow-apply-marketplace-now","description":"Enables the apply_marketplace_now command without any pre-configured scope.","commands":{"allow":["apply_marketplace_now"],"deny":[]}},"allow-apply-settings-import":{"identifier":"allow-apply-settings-import","description":"Enables the apply_settings_import command without any pre-configured scope.","commands":{"allow":["apply_settings_import"],"deny":[]}},"allow-aws-connection-identity":{"identifier":"allow-aws-connection-identity","description":"Enables the aws_connection_identity command without any pre-configured scope.","commands":{"allow":["aws_connection_identity"],"deny":[]}},"allow-aws-connection-sso-login":{"identifier":"allow-aws-connection-sso-login","description":"Enables the aws_connection_sso_login command without any pre-configured scope.","commands":{"allow":["aws_connection_sso_login"],"deny":[]}},"allow-aws-cost-estimate":{"identifier":"allow-aws-cost-estimate","description":"Enables the aws_cost_estimate command without any pre-configured scope.","commands":{"allow":["aws_cost_estimate"],"deny":[]}},"allow-aws-ec2-capacity":{"identifier":"allow-aws-ec2-capacity","description":"Enables the aws_ec2_capacity command without any pre-configured scope.","commands":{"allow":["aws_ec2_capacity"],"deny":[]}},"allow-aws-environment-max-hours":{"identifier":"allow-aws-environment-max-hours","description":"Enables the aws_environment_max_hours command without any pre-configured scope.","commands":{"allow":["aws_environment_max_hours"],"deny":[]}},"allow-aws-policy-document":{"identifier":"allow-aws-policy-document","description":"Enables the aws_policy_document command without any pre-configured scope.","commands":{"allow":["aws_policy_document"],"deny":[]}},"allow-aws-sso-refresh":{"identifier":"allow-aws-sso-refresh","description":"Enables the aws_sso_refresh command without any pre-configured scope.","commands":{"allow":["aws_sso_refresh"],"deny":[]}},"allow-aws-task-log":{"identifier":"allow-aws-task-log","description":"Enables the aws_task_log command without any pre-configured scope.","commands":{"allow":["aws_task_log"],"deny":[]}},"allow-aws-workspace-status":{"identifier":"allow-aws-workspace-status","description":"Enables the aws_workspace_status command without any pre-configured scope.","commands":{"allow":["aws_workspace_status"],"deny":[]}},"allow-build-gateway-image":{"identifier":"allow-build-gateway-image","description":"Enables the build_gateway_image command without any pre-configured scope.","commands":{"allow":["build_gateway_image"],"deny":[]}},"allow-build-image":{"identifier":"allow-build-image","description":"Enables the build_image command without any pre-configured scope.","commands":{"allow":["build_image"],"deny":[]}},"allow-build-stt-image":{"identifier":"allow-build-stt-image","description":"Enables the build_stt_image command without any pre-configured scope.","commands":{"allow":["build_stt_image"],"deny":[]}},"allow-cancel-aws-deployment":{"identifier":"allow-cancel-aws-deployment","description":"Enables the cancel_aws_deployment command withoutLine truncated {"__app-acl__":{"default_permission":null,"permissions":{"allow-acquire-claude-token":{"identifier":"allow-acquire-claude-token","description":"Enables the acquire_claude_token command without any pre-configured scope.","commands":{"allow":["acquire_claude_token"],"deny":[]}},"allow-add-aws-keys-connection":{"identifier":"allow-add-aws-keys-connection","description":"Enables the add_aws_keys_connection command without any pre-configured scope.","commands":{"allow":["add_aws_keys_connection"],"deny":[]}},"allow-add-aws-profile-connection":{"identifier":"allow-add-aws-profile-connection","description":"Enables the add_aws_profile_connection command without any pre-configured scope.","commands":{"allow":["add_aws_profile_connection"],"deny":[]}},"allow-add-marketplace":{"identifier":"allow-add-marketplace","description":"Enables the add_marketplace command without any pre-configured scope.","commands":{"allow":["add_marketplace"],"deny":[]}},"allow-add-marketplace-gh-host-account":{"identifier":"allow-add-marketplace-gh-host-account","description":"Enables the add_marketplace_gh_host_account command without any pre-configured scope.","commands":{"allow":["add_marketplace_gh_host_account"],"deny":[]}},"allow-add-marketplace-token-account":{"identifier":"allow-add-marketplace-token-account","description":"Enables the add_marketplace_token_account command without any pre-configured scope.","commands":{"allow":["add_marketplace_token_account"],"deny":[]}},"allow-add-project":{"identifier":"allow-add-project","description":"Enables the add_project command without any pre-configured scope.","commands":{"allow":["add_project"],"deny":[]}},"allow-add-scheduled-task":{"identifier":"allow-add-scheduled-task","description":"Enables the add_scheduled_task command without any pre-configured scope.","commands":{"allow":["add_scheduled_task"],"deny":[]}},"allow-apply-marketplace-now":{"identifier":"allow-apply-marketplace-now","description":"Enables the apply_marketplace_now command without any pre-configured scope.","commands":{"allow":["apply_marketplace_now"],"deny":[]}},"allow-apply-settings-import":{"identifier":"allow-apply-settings-import","description":"Enables the apply_settings_import command without any pre-configured scope.","commands":{"allow":["apply_settings_import"],"deny":[]}},"allow-aws-connection-identity":{"identifier":"allow-aws-connection-identity","description":"Enables the aws_connection_identity command without any pre-configured scope.","commands":{"allow":["aws_connection_identity"],"deny":[]}},"allow-aws-connection-sso-login":{"identifier":"allow-aws-connection-sso-login","description":"Enables the aws_connection_sso_login command without any pre-configured scope.","commands":{"allow":["aws_connection_sso_login"],"deny":[]}},"allow-aws-cost-estimate":{"identifier":"allow-aws-cost-estimate","description":"Enables the aws_cost_estimate command without any pre-configured scope.","commands":{"allow":["aws_cost_estimate"],"deny":[]}},"allow-aws-ec2-capacity":{"identifier":"allow-aws-ec2-capacity","description":"Enables the aws_ec2_capacity command without any pre-configured scope.","commands":{"allow":["aws_ec2_capacity"],"deny":[]}},"allow-aws-environment-max-hours":{"identifier":"allow-aws-environment-max-hours","description":"Enables the aws_environment_max_hours command without any pre-configured scope.","commands":{"allow":["aws_environment_max_hours"],"deny":[]}},"allow-aws-policy-document":{"identifier":"allow-aws-policy-document","description":"Enables the aws_policy_document command without any pre-configured scope.","commands":{"allow":["aws_policy_document"],"deny":[]}},"allow-aws-sso-refresh":{"identifier":"allow-aws-sso-refresh","description":"Enables the aws_sso_refresh command without any pre-configured scope.","commands":{"allow":["aws_sso_refresh"],"deny":[]}},"allow-aws-task-log":{"identifier":"allow-aws-task-log","description":"Enables the aws_task_log command without any pre-configured scope.","commands":{"allow":["aws_task_log"],"deny":[]}},"allow-aws-workspace-status":{"identifier":"allow-aws-workspace-status","description":"Enables the aws_workspace_status command without any pre-configured scope.","commands":{"allow":["aws_workspace_status"],"deny":[]}},"allow-build-gateway-image":{"identifier":"allow-build-gateway-image","description":"Enables the build_gateway_image command without any pre-configured scope.","commands":{"allow":["build_gateway_image"],"deny":[]}},"allow-build-image":{"identifier":"allow-build-image","description":"Enables the build_image command without any pre-configured scope.","commands":{"allow":["build_image"],"deny":[]}},"allow-build-stt-image":{"identifier":"allow-build-stt-image","description":"Enables the build_stt_image command without any pre-configured scope.","commands":{"allow":["build_stt_image"],"deny":[]}},"allow-cancel-aws-deployment":{"identifier":"allow-cancel-aws-deployment","description":"Enables the cancel_aws_deployment command withoutLine truncated
+1 -1
View File
@@ -1 +1 @@
{"default":{"identifier":"default","description":"Default capabilities for Triple-C. Every entry here is an IPC command a compromised webview can call directly, so the set is an enumeration of what `app/src` actually invokes — plugin and core grants verified against tauri 2.11.0's `PLUGINS` table in tauri's own `build.rs` rather than assumed from a plugin's `default` set, app-command grants (the bare `allow-*` entries) cross-checked by this crate's `build.rs` against `generate_handler!`. `core:default` in particular is NOT used: it is an alias for `core:{path,event,window,webview,app,image,resources,menu,tray}:default`, and `core:image:default` carries `allow-from-path`, whose handler (`tauri-2.11.0/src/image/plugin.rs:41` → `src/image/mod.rs:96`) is a bare `std::fs::read(path)` with no scope mechanism of any kind. Nothing imports `@tauri-apps/api/image`, so the whole plugin is dropped rather than scoped — there is nothing to scope it with. `core:menu` and `core:tray` are dropped for the same reason (no menu, no tray icon); `core:window` and `core:path` because nothing imports them; `core:resources:allow-close` because no frontend value is a `Resource`; and `core:event`'s `allow-emit`/`allow-emit-to` because the frontend only ever *listens* — every emit in this app originates in Rust. Three notes on what is deliberately kept or accepted: (1) `core:webview:allow-internal-toggle-devtools` is not called by `app/src` at all — it is called by Tauri's own injected `toggle-devtools.js`, which binds Ctrl/Cmd+Shift+I. Both that script and the command behind it are `#[cfg(any(debug_assertions, feature = \"devtools\"))]`, so this grant is a `tauri dev` convenience that does not exist in a release bundle. (2) `opener:allow-open-url` is **gone**. It could not be narrowed by host — `TerminalView`'s `WebLinksAddon` opens links Claude printed inside the container, which are arbitrary by construction, so a host allowlist would have deleted the feature rather than bounded it — and it was carried here as an accepted residual risk: a compromised webview could make the OS open an attacker-chosen http(s) URL, an outbound channel. That risk is now closed rather than recorded. Every host-browser open in the app goes through the `open_url_external` command in `url_open.rs`, which exists because the AppImage environment leaks into a cold-launched browser on Linux (triple-c#34) and which re-validates the URL in Rust — scheme allowlist, no embedded credentials, no control characters, length cap, ASCII asserted before `execvp`. On macOS and Windows that command reaches the same plugin as before, via `OpenerExt::open_url`, whose desktop implementation calls `crate::open::open` directly and is therefore not gated by this file at all (`tauri-plugin-opener-2.5.3/src/lib.rs:60`). The plugin stays a dependency for exactly that reason; what is removed is the webview's ability to reach it without passing the Rust validation. (3) `drag:allow-start-drag` is **gone**, together with the OS drag-out it existed for. It could not be scoped — `tauri-plugin-drag` takes the item paths from the caller and has no scope mechanism, so a compromised webview could call `startDrag({ item: ['~/.ssh/id_rsa'] })` against any host path the user can read — and it was carried as an accepted residual risk for one gesture. Drag-out was held back for separate hardening (see branch `hold/disk-and-dragout`) and the plugin is no longer a dependency. Getting a file *out* of a container is either \"Back up container\" on the project's Overview tab, which archives a tree through the Docker API, or the Files tab's per-row \"Save to host…\", which copies one file; getting one *in* is a drop on the Terminal or the Files tab's \"Upload…\". None of the four touches this permission. The Files tab's two are worth separating out here, because they are the only host-path commands in the app whose dialog is opened by **Rust** rather than by the webview — `pick_save_path` and `pick_files_to_upload` in `commands/file_commands.rs` drive `tauri-plugin-dialog` from the backend, so a compromised webview can ask for a picker and nothing more: it cannot name a host path as an *input* to either command. Be precise about the limit of that claim — host paths do still travel outward in error text (`Failed to create /home/j/Documents/x.txt.triple-c-part-1a2b3c4d: Permission denied`), including canonicalized ones, which disclose symlink targets. That is accepted; the app already hands the webview the project paths. What is closed is the direction that mattered — the webview naming where bytes go. That is the shape an earlier revision of this file named as the honest one if the Files tab ever regained host I/O, and it is the shape it regained it in. The `dialog:allow-open` / `dialog:allow-save` grants below are therefore *not* what those two use; they remain for the frontend pickers in Add Project, the Config tab's workspace and access sections, the CA-certificate fielLine truncated {"default":{"identifier":"default","description":"Default capabilities for Triple-C. Every entry here is an IPC command a compromised webview can call directly, so the set is an enumeration of what `app/src` actually invokes — plugin and core grants verified against tauri 2.11.0's `PLUGINS` table in tauri's own `build.rs` rather than assumed from a plugin's `default` set, app-command grants (the bare `allow-*` entries) cross-checked by this crate's `build.rs` against `generate_handler!`. `core:default` in particular is NOT used: it is an alias for `core:{path,event,window,webview,app,image,resources,menu,tray}:default`, and `core:image:default` carries `allow-from-path`, whose handler (`tauri-2.11.0/src/image/plugin.rs:41` → `src/image/mod.rs:96`) is a bare `std::fs::read(path)` with no scope mechanism of any kind. Nothing imports `@tauri-apps/api/image`, so the whole plugin is dropped rather than scoped — there is nothing to scope it with. `core:menu` and `core:tray` are dropped for the same reason (no menu, no tray icon); `core:window` and `core:path` because nothing imports them; `core:resources:allow-close` because no frontend value is a `Resource`; and `core:event`'s `allow-emit`/`allow-emit-to` because the frontend only ever *listens* — every emit in this app originates in Rust. Three notes on what is deliberately kept or accepted: (1) `core:webview:allow-internal-toggle-devtools` is not called by `app/src` at all — it is called by Tauri's own injected `toggle-devtools.js`, which binds Ctrl/Cmd+Shift+I. Both that script and the command behind it are `#[cfg(any(debug_assertions, feature = \"devtools\"))]`, so this grant is a `tauri dev` convenience that does not exist in a release bundle. (2) `opener:allow-open-url` is **gone**. It could not be narrowed by host — `TerminalView`'s `WebLinksAddon` opens links Claude printed inside the container, which are arbitrary by construction, so a host allowlist would have deleted the feature rather than bounded it — and it was carried here as an accepted residual risk: a compromised webview could make the OS open an attacker-chosen http(s) URL, an outbound channel. That risk is now closed rather than recorded. Every host-browser open in the app goes through the `open_url_external` command in `url_open.rs`, which exists because the AppImage environment leaks into a cold-launched browser on Linux (triple-c#34) and which re-validates the URL in Rust — scheme allowlist, no embedded credentials, no control characters, length cap, ASCII asserted before `execvp`. On macOS and Windows that command reaches the same plugin as before, via `OpenerExt::open_url`, whose desktop implementation calls `crate::open::open` directly and is therefore not gated by this file at all (`tauri-plugin-opener-2.5.3/src/lib.rs:60`). The plugin stays a dependency for exactly that reason; what is removed is the webview's ability to reach it without passing the Rust validation. (3) `drag:allow-start-drag` is **gone**, together with the OS drag-out it existed for. It could not be scoped — `tauri-plugin-drag` takes the item paths from the caller and has no scope mechanism, so a compromised webview could call `startDrag({ item: ['~/.ssh/id_rsa'] })` against any host path the user can read — and it was carried as an accepted residual risk for one gesture. Drag-out was held back for separate hardening (see branch `hold/disk-and-dragout`) and the plugin is no longer a dependency. Getting a file *out* of a container is either \"Back up container\" on the project's Overview tab, which archives a tree through the Docker API, or the Files tab's per-row \"Save to host…\", which copies one file; getting one *in* is a drop on the Terminal or the Files tab's \"Upload…\". None of the four touches this permission. The Files tab's two are worth separating out here, because they are the only host-path commands in the app whose dialog is opened by **Rust** rather than by the webview — `pick_save_path` and `pick_files_to_upload` in `commands/file_commands.rs` drive `tauri-plugin-dialog` from the backend, so a compromised webview can ask for a picker and nothing more: it cannot name a host path as an *input* to either command. Be precise about the limit of that claim — host paths do still travel outward in error text (`Failed to create /home/j/Documents/x.txt.triple-c-part-1a2b3c4d: Permission denied`), including canonicalized ones, which disclose symlink targets. That is accepted; the app already hands the webview the project paths. What is closed is the direction that mattered — the webview naming where bytes go. That is the shape an earlier revision of this file named as the honest one if the Files tab ever regained host I/O, and it is the shape it regained it in. The `dialog:allow-open` / `dialog:allow-save` grants below are therefore *not* what those two use; they remain for the frontend pickers in Add Project, the Config tab's workspace and access sections, the CA-certificate fielLine truncated
@@ -512,6 +512,12 @@
"const": "allow-check-docker", "const": "allow-check-docker",
"markdownDescription": "Enables the check_docker command without any pre-configured scope." "markdownDescription": "Enables the check_docker command without any pre-configured scope."
}, },
{
"description": "Enables the check_docker_status command without any pre-configured scope.",
"type": "string",
"const": "allow-check-docker-status",
"markdownDescription": "Enables the check_docker_status command without any pre-configured scope."
},
{ {
"description": "Enables the check_for_updates command without any pre-configured scope.", "description": "Enables the check_for_updates command without any pre-configured scope.",
"type": "string", "type": "string",
@@ -1502,6 +1508,12 @@
"const": "deny-check-docker", "const": "deny-check-docker",
"markdownDescription": "Denies the check_docker command without any pre-configured scope." "markdownDescription": "Denies the check_docker command without any pre-configured scope."
}, },
{
"description": "Denies the check_docker_status command without any pre-configured scope.",
"type": "string",
"const": "deny-check-docker-status",
"markdownDescription": "Denies the check_docker_status command without any pre-configured scope."
},
{ {
"description": "Denies the check_for_updates command without any pre-configured scope.", "description": "Denies the check_for_updates command without any pre-configured scope.",
"type": "string", "type": "string",
@@ -512,6 +512,12 @@
"const": "allow-check-docker", "const": "allow-check-docker",
"markdownDescription": "Enables the check_docker command without any pre-configured scope." "markdownDescription": "Enables the check_docker command without any pre-configured scope."
}, },
{
"description": "Enables the check_docker_status command without any pre-configured scope.",
"type": "string",
"const": "allow-check-docker-status",
"markdownDescription": "Enables the check_docker_status command without any pre-configured scope."
},
{ {
"description": "Enables the check_for_updates command without any pre-configured scope.", "description": "Enables the check_for_updates command without any pre-configured scope.",
"type": "string", "type": "string",
@@ -1502,6 +1508,12 @@
"const": "deny-check-docker", "const": "deny-check-docker",
"markdownDescription": "Denies the check_docker command without any pre-configured scope." "markdownDescription": "Denies the check_docker command without any pre-configured scope."
}, },
{
"description": "Denies the check_docker_status command without any pre-configured scope.",
"type": "string",
"const": "deny-check-docker-status",
"markdownDescription": "Denies the check_docker_status command without any pre-configured scope."
},
{ {
"description": "Denies the check_for_updates command without any pre-configured scope.", "description": "Denies the check_for_updates command without any pre-configured scope.",
"type": "string", "type": "string",
@@ -9,6 +9,12 @@ pub async fn check_docker() -> Result<bool, String> {
docker::check_docker_available().await docker::check_docker_available().await
} }
/// Like `check_docker`, but says *why* Docker is unavailable.
#[tauri::command]
pub async fn check_docker_status() -> Result<docker::status::DockerStatus, String> {
Ok(docker::client::docker_status().await)
}
#[tauri::command] #[tauri::command]
pub async fn check_image_exists(state: State<'_, AppState>) -> Result<bool, String> { pub async fn check_image_exists(state: State<'_, AppState>) -> Result<bool, String> {
let settings = state.settings_store.get(); let settings = state.settings_store.get();
@@ -374,9 +374,10 @@ pub(crate) fn ec2_collision_refusal(
/// Everything a self-onboarding apply needs settled before it starts: the /// Everything a self-onboarding apply needs settled before it starts: the
/// caller's record, the capacity ([`resolve_ec2`]), the module variables /// caller's record, the capacity ([`resolve_ec2`]), the module variables
/// and, with EC2 capacity, the name check ([`ec2_collision_refusal`]). /// and, with EC2 capacity, the name check ([`ec2_collision_refusal`]).
/// Check-then-apply leaves a narrow race (another admin creating the same /// Check-then-apply leaves a narrow race (someone else creating the same
/// names in between); only admins apply, and the module would then fail on /// names in between); the module would then fail on create rather than
/// create rather than adopt. /// adopt. Anyone may start this: there is no tier check in the app, and AWS
/// refuses (mapped to `AccessDenied`) what the caller isn't permitted.
pub(crate) async fn prepare_onboarding<A: OnboardApi>( pub(crate) async fn prepare_onboarding<A: OnboardApi>(
api: &A, api: &A,
env: &str, env: &str,
+29 -10
View File
@@ -15,16 +15,35 @@ pub fn get_docker() -> Result<Docker, String> {
} }
pub async fn check_docker_available() -> Result<bool, String> { pub async fn check_docker_available() -> Result<bool, String> {
let docker = get_docker()?; Ok(docker_status().await.state == super::status::DockerState::Running)
match docker.ping().await { }
Ok(_) => Ok(true),
Err(_) => { /// Ping the daemon and, when it does not answer, say why: not installed, installed
// Connection object exists but daemon not responding — clear cache /// but not running, or running but refusing us. See `docker/status.rs`.
let mut guard = DOCKER.lock().map_err(|e| format!("Lock poisoned: {}", e))?; pub async fn docker_status() -> super::status::DockerStatus {
*guard = None; use super::status::{self, PingOutcome};
Ok(false) let docker_host = std::env::var("DOCKER_HOST").ok();
} let os = status::current_os();
} let endpoint = status::endpoint(docker_host.as_deref());
let (ping, detail) = match get_docker() {
Err(e) => (PingOutcome::Unreachable, Some(e)),
Ok(docker) => match docker.ping().await {
Ok(_) => (PingOutcome::Ok, None),
Err(e) => {
// Connection object exists but daemon not responding — clear cache
if let Ok(mut guard) = DOCKER.lock() {
*guard = None;
}
(status::ping_outcome_from_error(&e), Some(e.to_string()))
}
},
};
let installed = ping == PingOutcome::Unreachable
&& (status::docker_installed(os, docker_host.as_deref())
// An explicit DOCKER_HOST means the user has a daemon somewhere.
|| docker_host.as_deref().is_some_and(|h| !h.trim().is_empty()));
status::DockerStatus { state: status::classify(ping, installed), endpoint, detail, os }
} }
/// The daemon socket a project container gets bind-mounted when Docker access /// The daemon socket a project container gets bind-mounted when Docker access
+1
View File
@@ -1,5 +1,6 @@
pub mod ca_certs; pub mod ca_certs;
pub mod client; pub mod client;
pub mod status;
pub mod events; pub mod events;
pub mod container; pub mod container;
pub mod workspace_env; pub mod workspace_env;
+282
View File
@@ -0,0 +1,282 @@
//! Why Docker is unavailable, not just whether it is.
//!
//! A daemon that failed to start (systemd `start-limit-hit`, Docker Desktop
//! still booting) and a socket the user may not open both used to surface as
//! "Docker not detected — install it", which sends people to reinstall
//! something they already have. This module tells the cases apart from the
//! ping's error and a few cheap filesystem probes. It never runs a process
//! (no `systemctl`, no `docker info`).
use serde::Serialize;
use std::error::Error as StdError;
use std::io;
use std::path::{Path, PathBuf};
/// Mirrors `DockerStatus` in `src/lib/types.ts`.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct DockerStatus {
/// `running` | `not_running` | `no_permission` | `not_installed`
pub state: DockerState,
/// The endpoint that was tried — `DOCKER_HOST` when set, else the default socket/pipe.
pub endpoint: String,
/// The connection error, for the "details" line. `None` when running.
pub detail: Option<String>,
/// `linux` | `macos` | `windows` | `unknown` — picks the guidance to show.
pub os: &'static str,
}
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum DockerState {
Running,
NotRunning,
NoPermission,
NotInstalled,
}
/// What the ping told us, reduced to what matters for the classification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PingOutcome {
Ok,
/// The socket/pipe exists but the OS refused to let us open it.
PermissionDenied,
/// Nothing answered: socket missing, connection refused, timeout, other.
Unreachable,
}
/// The pure decision. `installed` is true when any installed-ness probe hit.
pub fn classify(ping: PingOutcome, installed: bool) -> DockerState {
match ping {
PingOutcome::Ok => DockerState::Running,
// Getting EACCES means something is listening on a socket we can't
// open — Docker is there; the user lacks access.
PingOutcome::PermissionDenied => DockerState::NoPermission,
PingOutcome::Unreachable if installed => DockerState::NotRunning,
PingOutcome::Unreachable => DockerState::NotInstalled,
}
}
/// Walk an error's `source()` chain for an `io::Error` and map its kind.
/// Falls back to the rendered message, since some layers (hyper-util's
/// connect errors, named pipes) only keep the OS error as text.
pub fn ping_outcome_from_error(err: &(dyn StdError + 'static)) -> PingOutcome {
let mut cur: Option<&(dyn StdError + 'static)> = Some(err);
let mut text = String::new();
while let Some(e) = cur {
if let Some(ioe) = e.downcast_ref::<io::Error>() {
if ioe.kind() == io::ErrorKind::PermissionDenied {
return PingOutcome::PermissionDenied;
}
}
text.push_str(&e.to_string().to_lowercase());
text.push('\n');
cur = e.source();
}
if text.contains("permission denied") || text.contains("access is denied") || text.contains("os error 13") {
PingOutcome::PermissionDenied
} else {
PingOutcome::Unreachable
}
}
/// The endpoint bollard's `connect_with_local_defaults` will use.
pub fn endpoint(docker_host: Option<&str>) -> String {
match docker_host.map(str::trim).filter(|h| !h.is_empty()) {
Some(h) => h.to_string(),
None if cfg!(windows) => "npipe:////./pipe/docker_engine".to_string(),
None => "unix:///var/run/docker.sock".to_string(),
}
}
pub fn current_os() -> &'static str {
if cfg!(target_os = "linux") {
"linux"
} else if cfg!(target_os = "macos") {
"macos"
} else if cfg!(windows) {
"windows"
} else {
"unknown"
}
}
/// Paths whose existence means Docker is installed on this OS. Pure so the
/// list can be tested; `docker_installed` does the filesystem checks.
pub fn install_markers(os: &str, home: Option<&Path>, docker_host: Option<&str>) -> Vec<PathBuf> {
let mut v: Vec<PathBuf> = Vec::new();
// A unix:// DOCKER_HOST whose socket file exists counts, whatever the OS.
if let Some(p) = docker_host.and_then(|h| h.trim().strip_prefix("unix://")) {
if !p.is_empty() {
v.push(PathBuf::from(p));
}
}
match os {
"linux" => {
v.extend(
["/usr/bin/dockerd", "/usr/local/bin/dockerd", "/usr/bin/docker", "/var/run/docker.sock", "/run/docker.sock"]
.iter()
.map(PathBuf::from),
);
if let Some(h) = home {
v.push(h.join(".docker/desktop"));
v.push(h.join("bin/dockerd")); // rootless install script
}
}
"macos" => {
v.push(PathBuf::from("/Applications/Docker.app"));
v.push(PathBuf::from("/var/run/docker.sock"));
v.push(PathBuf::from("/usr/local/bin/docker"));
if let Some(h) = home {
v.push(h.join("Applications/Docker.app"));
v.push(h.join(".docker/run/docker.sock"));
}
}
"windows" => {
v.push(PathBuf::from(r"C:\Program Files\Docker\Docker\Docker Desktop.exe"));
v.push(PathBuf::from(r"C:\Program Files\Docker\Docker\resources\bin\docker.exe"));
}
_ => {}
}
v
}
/// Executable names to look for on `PATH`.
pub fn path_binaries(os: &str) -> &'static [&'static str] {
match os {
"windows" => &["docker.exe"],
_ => &["docker", "dockerd"],
}
}
fn on_path(name: &str) -> bool {
std::env::var_os("PATH")
.map(|p| std::env::split_paths(&p).any(|dir| dir.join(name).is_file()))
.unwrap_or(false)
}
/// Cheap installed-ness probe: stats a handful of paths, runs nothing.
pub fn docker_installed(os: &str, docker_host: Option<&str>) -> bool {
let home = dirs::home_dir();
if install_markers(os, home.as_deref(), docker_host).iter().any(|p| p.exists()) {
return true;
}
if os == "linux" {
// Rootless Docker's socket lives in the user's runtime dir.
if let Some(rt) = std::env::var_os("XDG_RUNTIME_DIR") {
if Path::new(&rt).join("docker.sock").exists() {
return true;
}
}
}
path_binaries(os).iter().any(|b| on_path(b))
}
#[cfg(test)]
mod tests {
use super::*;
use std::fmt;
#[test]
fn ping_ok_is_running_regardless_of_probes() {
assert_eq!(classify(PingOutcome::Ok, false), DockerState::Running);
assert_eq!(classify(PingOutcome::Ok, true), DockerState::Running);
}
#[test]
fn unreachable_and_installed_is_not_running() {
// The reported case: dockerd present, systemd gave up restarting it.
assert_eq!(classify(PingOutcome::Unreachable, true), DockerState::NotRunning);
}
#[test]
fn unreachable_and_nothing_found_is_not_installed() {
assert_eq!(classify(PingOutcome::Unreachable, false), DockerState::NotInstalled);
}
#[test]
fn permission_denied_is_no_permission_even_without_probes() {
assert_eq!(classify(PingOutcome::PermissionDenied, false), DockerState::NoPermission);
assert_eq!(classify(PingOutcome::PermissionDenied, true), DockerState::NoPermission);
}
/// An error that wraps another, the way bollard → hyper → io do.
#[derive(Debug)]
struct Wrap(&'static str, Option<io::Error>);
impl fmt::Display for Wrap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.0)
}
}
impl StdError for Wrap {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
self.1.as_ref().map(|e| e as _)
}
}
#[test]
fn nested_io_permission_denied_is_found() {
let e = Wrap("error trying to connect", Some(io::Error::from(io::ErrorKind::PermissionDenied)));
assert_eq!(ping_outcome_from_error(&e), PingOutcome::PermissionDenied);
}
#[test]
fn nested_connection_refused_and_not_found_are_unreachable() {
let refused = Wrap("error trying to connect", Some(io::Error::from(io::ErrorKind::ConnectionRefused)));
let missing = Wrap("error trying to connect", Some(io::Error::from(io::ErrorKind::NotFound)));
assert_eq!(ping_outcome_from_error(&refused), PingOutcome::Unreachable);
assert_eq!(ping_outcome_from_error(&missing), PingOutcome::Unreachable);
}
#[test]
fn permission_denied_only_in_text_is_found() {
let e = Wrap("client error (Connect): Permission denied (os error 13)", None);
assert_eq!(ping_outcome_from_error(&e), PingOutcome::PermissionDenied);
}
#[test]
fn endpoint_respects_docker_host() {
assert_eq!(endpoint(Some("tcp://10.0.0.5:2375")), "tcp://10.0.0.5:2375");
assert_eq!(endpoint(Some(" ")), endpoint(None));
let default = endpoint(None);
assert!(default.starts_with("unix://") || default.starts_with("npipe://"), "{default}");
}
#[test]
fn install_markers_cover_each_os() {
let home = Path::new("/home/u");
let linux = install_markers("linux", Some(home), None);
assert!(linux.contains(&PathBuf::from("/usr/bin/dockerd")));
assert!(linux.contains(&PathBuf::from("/var/run/docker.sock")));
assert!(linux.contains(&home.join(".docker/desktop")));
let mac = install_markers("macos", Some(home), None);
assert!(mac.contains(&PathBuf::from("/Applications/Docker.app")));
assert!(mac.contains(&home.join(".docker/run/docker.sock")));
let win = install_markers("windows", None, None);
assert!(win.contains(&PathBuf::from(r"C:\Program Files\Docker\Docker\Docker Desktop.exe")));
assert_eq!(path_binaries("windows"), &["docker.exe"]);
assert!(path_binaries("linux").contains(&"dockerd"));
}
#[test]
fn unix_docker_host_socket_is_a_marker() {
let m = install_markers("linux", None, Some("unix:///run/user/1000/docker.sock"));
assert_eq!(m[0], PathBuf::from("/run/user/1000/docker.sock"));
let tcp = install_markers("linux", None, Some("tcp://host:2375"));
assert!(!tcp.iter().any(|p| p.to_string_lossy().contains("host")));
}
#[test]
fn status_serializes_with_snake_case_state() {
let s = DockerStatus {
state: DockerState::NotRunning,
endpoint: "unix:///var/run/docker.sock".into(),
detail: Some("refused".into()),
os: "linux",
};
let json = serde_json::to_value(&s).unwrap();
assert_eq!(json["state"], "not_running");
assert_eq!(json["os"], "linux");
}
}
+1
View File
@@ -542,6 +542,7 @@ pub fn run() {
.invoke_handler(tauri::generate_handler![ .invoke_handler(tauri::generate_handler![
// Docker // Docker
commands::docker_commands::check_docker, commands::docker_commands::check_docker,
commands::docker_commands::check_docker_status,
commands::docker_commands::check_image_exists, commands::docker_commands::check_image_exists,
commands::docker_commands::build_image, commands::docker_commands::build_image,
commands::docker_commands::get_container_info, commands::docker_commands::get_container_info,
+4 -2
View File
@@ -6,6 +6,7 @@ import TopBar from "./components/layout/TopBar";
import StatusBar from "./components/layout/StatusBar"; import StatusBar from "./components/layout/StatusBar";
import NotesDock from "./components/layout/NotesDock"; import NotesDock from "./components/layout/NotesDock";
import TerminalView from "./components/terminal/TerminalView"; import TerminalView from "./components/terminal/TerminalView";
import { dockerFailLabel } from "./lib/dockerStatus";
import DockerInstallDialog from "./components/DockerInstallDialog"; import DockerInstallDialog from "./components/DockerInstallDialog";
import ProjectHome from "./components/projects/home/ProjectHome"; import ProjectHome from "./components/projects/home/ProjectHome";
import AddProjectDialog from "./components/projects/AddProjectDialog"; import AddProjectDialog from "./components/projects/AddProjectDialog";
@@ -213,9 +214,10 @@ export default function App() {
* tracks and ends in a real button. * tracks and ends in a real button.
*/ */
function WelcomeScreen() { function WelcomeScreen() {
const { dockerAvailable, imageExists, projects, openProjectHome } = useAppState( const { dockerAvailable, dockerStatus, imageExists, projects, openProjectHome } = useAppState(
useShallow((s) => ({ useShallow((s) => ({
dockerAvailable: s.dockerAvailable, dockerAvailable: s.dockerAvailable,
dockerStatus: s.dockerStatus,
imageExists: s.imageExists, imageExists: s.imageExists,
projects: s.projects, projects: s.projects,
openProjectHome: s.openProjectHome, openProjectHome: s.openProjectHome,
@@ -233,7 +235,7 @@ function WelcomeScreen() {
label: "Docker detected", label: "Docker detected",
state: dockerAvailable, state: dockerAvailable,
pendingLabel: "Checking for Docker…", pendingLabel: "Checking for Docker…",
failLabel: "Docker not available", failLabel: dockerFailLabel(dockerStatus),
}, },
{ {
label: "Container image ready", label: "Container image ready",
@@ -0,0 +1,91 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, act } from "@testing-library/react";
import DockerInstallDialog from "./DockerInstallDialog";
import { useAppState } from "../store/appState";
import type { DockerStatus } from "../lib/types";
vi.mock("../lib/tauri-commands", () => ({
getDockerStatus: vi.fn(),
checkImageExists: vi.fn(),
buildImage: vi.fn(),
pullImage: vi.fn(),
openUrlExternal: vi.fn(),
}));
vi.mock("../hooks/useInstallHelper", () => ({
useInstallHelper: () => ({
options: {
os: "linux",
product_name: "Docker Engine",
can_auto_install: false,
auto_install_method: null,
auto_install_blocker: "no pkexec",
docs_url: "https://docs.docker.com",
manual_steps: [],
post_install_notes: [],
},
loadOptions: vi.fn(),
runInstall: vi.fn(),
}),
}));
const status = (state: DockerStatus["state"], os: DockerStatus["os"] = "linux"): DockerStatus => ({
state,
endpoint: "unix:///var/run/docker.sock",
detail: state === "running" ? null : "connection refused",
os,
});
function setStatus(s: DockerStatus) {
act(() => useAppState.getState().setDockerStatus(s));
}
describe("DockerInstallDialog", () => {
beforeEach(() => {
useAppState.setState({ dockerStatus: null, dockerAvailable: null });
});
it("offers install guidance when Docker is not installed", () => {
setStatus(status("not_installed"));
render(<DockerInstallDialog onClose={vi.fn()} />);
expect(screen.getByRole("dialog", { name: "Docker is not installed" })).toBeTruthy();
expect(screen.getByText(/AWS projects don't need local Docker/)).toBeTruthy();
expect(screen.getByText("unix:///var/run/docker.sock")).toBeTruthy();
});
it("says installed-but-not-running with systemd steps on Linux, and offers no install", () => {
setStatus(status("not_running"));
render(<DockerInstallDialog onClose={vi.fn()} />);
expect(screen.getByRole("dialog", { name: "Docker is installed but not running" })).toBeTruthy();
expect(screen.getByText("sudo systemctl start docker")).toBeTruthy();
expect(screen.getByText("sudo systemctl reset-failed docker")).toBeTruthy();
expect(screen.getByText("journalctl -u docker -b")).toBeTruthy();
expect(screen.queryByText(/Install Docker Engine/)).toBeNull();
expect(screen.getByText(/AWS projects don't need local Docker/)).toBeTruthy();
});
it("tells macOS/Windows users to start Docker Desktop", () => {
setStatus(status("not_running", "macos"));
render(<DockerInstallDialog onClose={vi.fn()} />);
expect(screen.getByText("Docker Desktop")).toBeTruthy();
expect(screen.queryByText("sudo systemctl start docker")).toBeNull();
});
it("explains the docker group on permission denied", () => {
setStatus(status("no_permission"));
render(<DockerInstallDialog onClose={vi.fn()} />);
expect(screen.getByRole("dialog", { name: "Docker is running but not accessible" })).toBeTruthy();
expect(screen.getByText("sudo usermod -aG docker $USER")).toBeTruthy();
});
it("updates live and closes itself when Docker becomes available", () => {
setStatus(status("not_installed"));
const onClose = vi.fn();
render(<DockerInstallDialog onClose={onClose} />);
setStatus(status("not_running"));
expect(screen.getByRole("dialog", { name: "Docker is installed but not running" })).toBeTruthy();
expect(onClose).not.toHaveBeenCalled();
setStatus(status("running"));
expect(onClose).toHaveBeenCalled();
});
});
+124 -2
View File
@@ -1,10 +1,79 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useInstallHelper } from "../hooks/useInstallHelper"; import { useInstallHelper } from "../hooks/useInstallHelper";
import { openUrlExternal } from "../lib/tauri-commands"; import { openUrlExternal } from "../lib/tauri-commands";
import type { DockerStatus } from "../lib/types";
import { useDocker } from "../hooks/useDocker"; import { useDocker } from "../hooks/useDocker";
import Modal from "./ui/Modal"; import Modal from "./ui/Modal";
import Button from "./ui/Button"; import Button from "./ui/Button";
const AWS_NOTE = "AWS projects don't need local Docker and still work.";
function Cmd({ children }: { children: string }) {
return (
<code className="block font-mono text-[var(--text-primary)] bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-[var(--radius-control)] px-2 py-1 my-1 select-all break-all">
{children}
</code>
);
}
/** Guidance for a Docker that is installed but not answering. */
function NotRunningHelp({ status }: { status: DockerStatus }) {
if (status.os === "linux") {
return (
<div className="text-xs text-[var(--text-secondary)] space-y-2">
<p>Start the daemon:</p>
<Cmd>sudo systemctl start docker</Cmd>
<p>
If systemd gave up restarting it (<span className="font-mono">start-limit-hit</span>),
clear that first, then start it again:
</p>
<Cmd>sudo systemctl reset-failed docker</Cmd>
<p>To see why it stopped:</p>
<Cmd>systemctl status docker</Cmd>
<Cmd>journalctl -u docker -b</Cmd>
<p>
To start it at every boot, use{" "}
<span className="font-mono">sudo systemctl enable --now docker</span>. Rootless Docker
runs as your user instead: <span className="font-mono">systemctl --user start docker</span>.
</p>
</div>
);
}
return (
<div className="text-xs text-[var(--text-secondary)] space-y-2">
<p>
Start <span className="text-[var(--text-primary)]">Docker Desktop</span> and wait until it
says the engine is running — the first start can take a minute. This dialog closes on its
own once Docker answers.
</p>
</div>
);
}
function NoPermissionHelp({ status }: { status: DockerStatus }) {
if (status.os === "linux") {
return (
<div className="text-xs text-[var(--text-secondary)] space-y-2">
<p>
Your user is not in the <span className="font-mono">docker</span> group, so the socket
refuses the connection. Add yourself:
</p>
<Cmd>sudo usermod -aG docker $USER</Cmd>
<p>Then log out and back in (or reboot) so the new group applies, and reopen Triple-C.</p>
</div>
);
}
return (
<div className="text-xs text-[var(--text-secondary)] space-y-2">
<p>
The Docker endpoint refused access. Make sure Docker Desktop is running for your user
{status.os === "windows" ? " and that your account is in the docker-users group" : ""}, then
re-check.
</p>
</div>
);
}
interface Props { interface Props {
onClose: () => void; onClose: () => void;
} }
@@ -13,7 +82,7 @@ type Phase = "idle" | "installing" | "done" | "error";
export default function DockerInstallDialog({ onClose }: Props) { export default function DockerInstallDialog({ onClose }: Props) {
const { options, loadOptions, runInstall } = useInstallHelper(); const { options, loadOptions, runInstall } = useInstallHelper();
const { checkDocker } = useDocker(); const { checkDocker, dockerStatus } = useDocker();
const [showManual, setShowManual] = useState(false); const [showManual, setShowManual] = useState(false);
const [phase, setPhase] = useState<Phase>("idle"); const [phase, setPhase] = useState<Phase>("idle");
const [log, setLog] = useState<string[]>([]); const [log, setLog] = useState<string[]>([]);
@@ -23,6 +92,13 @@ export default function DockerInstallDialog({ onClose }: Props) {
loadOptions(); loadOptions();
}, [loadOptions]); }, [loadOptions]);
// Docker came up while the dialog was open (polling keeps `dockerStatus`
// current): nothing left to say. Not mid-install, whose notes still matter.
const running = dockerStatus?.state === "running";
useEffect(() => {
if (running && (phase === "idle" || phase === "error")) onClose();
}, [running, phase, onClose]);
const handleInstall = async () => { const handleInstall = async () => {
setPhase("installing"); setPhase("installing");
setLog([]); setLog([]);
@@ -52,6 +128,50 @@ export default function DockerInstallDialog({ onClose }: Props) {
if (available) onClose(); if (available) onClose();
}; };
const state = dockerStatus?.state ?? "not_installed";
const endpointLine = dockerStatus && (
<p className="text-[11px] text-[var(--text-secondary)] mt-3 break-all">
Tried <span className="font-mono">{dockerStatus.endpoint}</span>
{dockerStatus.detail ? <> — {dockerStatus.detail}</> : null}
</p>
);
const awsLine = (
<p className="text-[11px] text-[var(--text-secondary)] mt-2">{AWS_NOTE}</p>
);
if (dockerStatus && (state === "not_running" || state === "no_permission")) {
return (
<Modal
title={state === "not_running" ? "Docker is installed but not running" : "Docker is running but not accessible"}
onClose={onClose}
widthClassName="w-[34rem]"
footer={
<>
<Button variant="ghost" onClick={onClose}>
Dismiss
</Button>
<Button variant="primary" onClick={handleRecheck}>
Re-check
</Button>
</>
}
>
<p className="text-[13px] text-[var(--text-secondary)] mb-3">
{state === "not_running"
? "Triple-C found Docker on this machine, but the Docker daemon is not answering. There is nothing to install."
: "The Docker daemon is up, but this user is not allowed to talk to it."}
</p>
{state === "not_running" ? (
<NotRunningHelp status={dockerStatus} />
) : (
<NoPermissionHelp status={dockerStatus} />
)}
{endpointLine}
{awsLine}
</Modal>
);
}
if (!options) { if (!options) {
return null; return null;
} }
@@ -61,7 +181,7 @@ export default function DockerInstallDialog({ onClose }: Props) {
return ( return (
<Modal <Modal
title="Docker not detected" title="Docker is not installed"
onClose={onClose} onClose={onClose}
widthClassName="w-[34rem]" widthClassName="w-[34rem]"
// Closing mid-install would orphan a privileged installer. // Closing mid-install would orphan a privileged installer.
@@ -80,6 +200,8 @@ export default function DockerInstallDialog({ onClose }: Props) {
<span className="text-[var(--text-primary)]">{options.product_name}</span> for <span className="text-[var(--text-primary)]">{options.product_name}</span> for
you, or you can follow the official instructions. you, or you can follow the official instructions.
</p> </p>
{awsLine}
<div className="mb-4">{endpointLine}</div>
{phase === "idle" && ( {phase === "idle" && (
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
+4 -2
View File
@@ -1,3 +1,4 @@
import { dockerFailLabel } from "../../lib/dockerStatus";
import { useState } from "react"; import { useState } from "react";
import { useShallow } from "zustand/react/shallow"; import { useShallow } from "zustand/react/shallow";
import MainTabs from "./MainTabs"; import MainTabs from "./MainTabs";
@@ -9,9 +10,10 @@ import HelpDialog from "./HelpDialog";
import StatusIndicator, { type StatusTone } from "../ui/StatusIndicator"; import StatusIndicator, { type StatusTone } from "../ui/StatusIndicator";
export default function TopBar() { export default function TopBar() {
const { dockerAvailable, imageExists, updateInfo, imageUpdateInfo, appVersion, setUpdateInfo, setImageUpdateInfo } = useAppState( const { dockerAvailable, dockerStatus, imageExists, updateInfo, imageUpdateInfo, appVersion, setUpdateInfo, setImageUpdateInfo } = useAppState(
useShallow(s => ({ useShallow(s => ({
dockerAvailable: s.dockerAvailable, dockerAvailable: s.dockerAvailable,
dockerStatus: s.dockerStatus,
imageExists: s.imageExists, imageExists: s.imageExists,
updateInfo: s.updateInfo, updateInfo: s.updateInfo,
imageUpdateInfo: s.imageUpdateInfo, imageUpdateInfo: s.imageUpdateInfo,
@@ -76,7 +78,7 @@ export default function TopBar() {
<HealthDot <HealthDot
state={dockerAvailable} state={dockerAvailable}
okLabel="Docker" okLabel="Docker"
failLabel="Docker unavailable" failLabel={dockerFailLabel(dockerStatus)}
pendingLabel="Docker — checking" pendingLabel="Docker — checking"
/> />
<HealthDot <HealthDot
@@ -1,3 +1,4 @@
import { dockerFailLabel } from "../../lib/dockerStatus";
import { useState } from "react"; import { useState } from "react";
import { useDocker } from "../../hooks/useDocker"; import { useDocker } from "../../hooks/useDocker";
import { useSettings } from "../../hooks/useSettings"; import { useSettings } from "../../hooks/useSettings";
@@ -13,7 +14,7 @@ const IMAGE_SOURCE_OPTIONS: { value: ImageSource; label: string; description: st
]; ];
export default function DockerSettings() { export default function DockerSettings() {
const { dockerAvailable, imageExists, checkDocker, checkImage, buildImage, pullImage } = const { dockerAvailable, dockerStatus, imageExists, checkDocker, checkImage, buildImage, pullImage } =
useDocker(); useDocker();
const { appSettings, saveSettings } = useSettings(); const { appSettings, saveSettings } = useSettings();
const [working, setWorking] = useState(false); const [working, setWorking] = useState(false);
@@ -82,7 +83,7 @@ export default function DockerSettings() {
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<span className="text-[var(--text-secondary)]">Docker Status</span> <span className="text-[var(--text-secondary)]">Docker Status</span>
<span className={dockerAvailable ? "text-[var(--success)]" : "text-[var(--error)]"}> <span className={dockerAvailable ? "text-[var(--success)]" : "text-[var(--error)]"}>
{dockerAvailable === null ? "Checking..." : dockerAvailable ? "Connected" : "Not Available"} {dockerAvailable === null ? "Checking..." : dockerAvailable ? "Connected" : dockerFailLabel(dockerStatus)}
</span> </span>
</div> </div>
+14 -14
View File
@@ -64,10 +64,10 @@ function ErrorLine({
}) { }) {
return ( return (
<div role="alert" className="text-xs text-[var(--error)] leading-snug flex items-center gap-2 flex-wrap"> <div role="alert" className="text-xs text-[var(--error)] leading-snug flex items-center gap-2 flex-wrap">
<span>{awsErrorMessage(failure.error)}</span> <span className="min-w-0 break-words">{awsErrorMessage(failure.error)}</span>
{failure.error.kind === "sso_expired" && !onSignIn && ( {failure.error.kind === "sso_expired" && !onSignIn && (
<span> <span>
Sign in with <code>aws sso login --profile {failure.error.profile}</code> and try again. Sign in with <code className="break-all">aws sso login --profile {failure.error.profile}</code> and try again.
</span> </span>
)} )}
{failure.error.kind === "sso_expired" && onSignIn && ( {failure.error.kind === "sso_expired" && onSignIn && (
@@ -124,7 +124,7 @@ function PermissionReportView({ report }: { report: PermissionReport }) {
> >
{badge} {badge}
</span> </span>
<span className="text-xs text-[var(--text-secondary)]"> <span className="min-w-0 break-all text-xs text-[var(--text-secondary)]" data-testid="report-identity">
{report.identity.arn} · {report.region} {report.identity.arn} · {report.region}
</span> </span>
</div> </div>
@@ -154,8 +154,8 @@ function PermissionReportView({ report }: { report: PermissionReport }) {
</summary> </summary>
<ul className="mt-1 space-y-0.5 pl-4"> <ul className="mt-1 space-y-0.5 pl-4">
{t.results.map((r) => ( {t.results.map((r) => (
<li key={r.action} className="text-[var(--text-secondary)]"> <li key={r.action} className="text-[var(--text-secondary)] break-words">
<span className="font-mono">{r.action}</span> — {r.verdict} <span className="font-mono break-all">{r.action}</span> — {r.verdict}
{r.note && ( {r.note && (
<> <>
{" "} {" "}
@@ -263,7 +263,7 @@ function ConnectionRow({ host }: { host: HostConnection }) {
<li <li
ref={rowRef} ref={rowRef}
data-testid={`host-${host.id}`} data-testid={`host-${host.id}`}
className="border border-[var(--border-color)] rounded-[var(--radius-control)] p-2.5 space-y-1.5" className="border border-[var(--border-color)] rounded-[var(--radius-control)] p-2.5 space-y-1.5 min-w-0"
> >
{editing ? ( {editing ? (
<div className="space-y-2"> <div className="space-y-2">
@@ -273,7 +273,7 @@ function ConnectionRow({ host }: { host: HostConnection }) {
<input id={id} className={inputClass} list="aws-regions" value={region} onChange={(e) => setRegion(e.target.value)} /> <input id={id} className={inputClass} list="aws-regions" value={region} onChange={(e) => setRegion(e.target.value)} />
)} )}
</Field> </Field>
<div className="flex gap-2"> <div className="flex gap-2 flex-wrap">
<Button size="sm" variant="primary" onClick={save} disabled={busy || !name.trim() || !region.trim()}> <Button size="sm" variant="primary" onClick={save} disabled={busy || !name.trim() || !region.trim()}>
Save changes Save changes
</Button> </Button>
@@ -283,16 +283,16 @@ function ConnectionRow({ host }: { host: HostConnection }) {
</div> </div>
</div> </div>
) : ( ) : (
<div className="flex items-start justify-between gap-2 flex-wrap"> <div className="flex items-start justify-between gap-2 flex-wrap" data-testid={`host-header-${host.id}`}>
<div className="min-w-0"> <div className="min-w-0">
<div className="text-[13px] font-medium text-[var(--text-primary)]">{host.name}</div> <div className="text-[13px] font-medium text-[var(--text-primary)] break-words">{host.name}</div>
<div className="text-xs text-[var(--text-secondary)]"> <div className="text-xs text-[var(--text-secondary)] break-words">
<span>{auth.method === "profile" ? `Profile: ${auth.name}` : "Access keys"}</span> <span>{auth.method === "profile" ? `Profile: ${auth.name}` : "Access keys"}</span>
{" · "} {" · "}
<span>{host.kind.default_region}</span> <span>{host.kind.default_region}</span>
</div> </div>
</div> </div>
<div className="flex gap-1.5"> <div className="flex gap-1.5 flex-wrap">
<Button size="sm" onClick={runCheck} disabled={busy} aria-label={`Check ${host.name}`}> <Button size="sm" onClick={runCheck} disabled={busy} aria-label={`Check ${host.name}`}>
Check Check
</Button> </Button>
@@ -309,7 +309,7 @@ function ConnectionRow({ host }: { host: HostConnection }) {
)} )}
{confirmRemove && ( {confirmRemove && (
<div role="alertdialog" aria-label={`Remove ${host.name}?`} className="flex items-center gap-2 flex-wrap text-xs"> <div role="alertdialog" aria-label={`Remove ${host.name}?`} className="flex items-center gap-2 flex-wrap text-xs">
<span>Remove {host.name}? Its stored credentials are deleted.</span> <span className="min-w-0 break-words">Remove {host.name}? Its stored credentials are deleted.</span>
<Button data-focus="confirm-remove" size="sm" variant="danger" onClick={remove} disabled={busy} aria-label={`Confirm remove ${host.name}`}> <Button data-focus="confirm-remove" size="sm" variant="danger" onClick={remove} disabled={busy} aria-label={`Confirm remove ${host.name}`}>
Confirm remove Confirm remove
</Button> </Button>
@@ -501,7 +501,7 @@ function AddConnectionForm() {
{busy ? "Adding…" : "Add connection"} {busy ? "Adding…" : "Add connection"}
</Button> </Button>
{signedInAs && ( {signedInAs && (
<p role="status" className="text-xs text-[var(--success)]"> <p role="status" className="text-xs text-[var(--success)] break-all">
Signed in as {signedInAs} Signed in as {signedInAs}
</p> </p>
)} )}
@@ -516,7 +516,7 @@ export default function HostsSettings() {
const { appSettings } = useSettings(); const { appSettings } = useSettings();
const hosts = appSettings?.hosts ?? []; const hosts = appSettings?.hosts ?? [];
return ( return (
<div className="space-y-3"> <div className="space-y-3 min-w-0">
<p className="text-xs text-[var(--text-secondary)] leading-snug"> <p className="text-xs text-[var(--text-secondary)] leading-snug">
Where project environments run. AWS connections check what your credentials can do, and find, deploy and join environments. Where project environments run. AWS connections check what your credentials can do, and find, deploy and join environments.
</p> </p>
@@ -177,7 +177,7 @@ export default function AdminBundleModal({
Saved to <code className="font-mono text-[var(--text-primary)] break-all">{saved}</code> Saved to <code className="font-mono text-[var(--text-primary)] break-all">{saved}</code>
</p> </p>
<p>From that folder, run:</p> <p>From that folder, run:</p>
<pre className="font-mono text-[var(--text-primary)] bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-[var(--radius-control)] p-2 whitespace-pre-wrap"> <pre className="font-mono text-[var(--text-primary)] bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-[var(--radius-control)] p-2 whitespace-pre-wrap break-all max-w-full overflow-x-auto">
{COMMANDS} {COMMANDS}
</pre> </pre>
<Button size="sm" onClick={copy}> <Button size="sm" onClick={copy}>
@@ -30,6 +30,7 @@ export default function DeployEnvironmentModal({
onClose, onClose,
onDeploy, onDeploy,
onDetect, onDetect,
onBundle,
}: { }: {
connectionId: string; connectionId: string;
region: string; region: string;
@@ -40,6 +41,8 @@ export default function DeployEnvironmentModal({
/** Starts the run; resolves to the command's error, or null once started. */ /** Starts the run; resolves to the command's error, or null once started. */
onDeploy: (name: string, network: NetworkChoice, maxWorkspaceHours: number) => Promise<AwsError | null>; onDeploy: (name: string, network: NetworkChoice, maxWorkspaceHours: number) => Promise<AwsError | null>;
onDetect: () => void; onDetect: () => void;
/** Switch to an environment bundle for an admin (offered when AWS refuses the deploy). */
onBundle?: () => void;
}) { }) {
const [name, setName] = useState("main"); const [name, setName] = useState("main");
const [draft, setDraft] = useState<NetworkDraft>(DEFAULT_NETWORK); const [draft, setDraft] = useState<NetworkDraft>(DEFAULT_NETWORK);
@@ -80,7 +83,7 @@ export default function DeployEnvironmentModal({
const createBoundary = async () => { const createBoundary = async () => {
setBoundaryError(null); setBoundaryError(null);
const err = await boundary.start(BOUNDARY_STATE_KEY, region, "Permissions boundary", () => const err = await boundary.start(BOUNDARY_STATE_KEY, region, "boundary", "Permissions boundary", () =>
deployAwsPermissionsBoundary(connectionId, region), deployAwsPermissionsBoundary(connectionId, region),
); );
if (err?.kind === "access_denied") setBundle({ reason: awsErrorMessage(err) }); if (err?.kind === "access_denied") setBundle({ reason: awsErrorMessage(err) });
@@ -125,18 +128,19 @@ export default function DeployEnvironmentModal({
<div className="flex gap-2 flex-wrap"> <div className="flex gap-2 flex-wrap">
<Button <Button
size="md" size="md"
wrap
variant="primary" variant="primary"
onClick={createBoundary} onClick={createBoundary}
disabled={!!boundaryRun && !boundaryRun.done} disabled={!!boundaryRun && !boundaryRun.done}
> >
Create the permissions boundary (needs an account administrator) Create the permissions boundary (needs an account administrator)
</Button> </Button>
<Button size="md" onClick={() => setBundle({})}> <Button size="md" wrap onClick={() => setBundle({})}>
Save a bundle for an administrator instead Save a bundle for an administrator instead
</Button> </Button>
</div> </div>
{boundaryError && ( {boundaryError && (
<p role="alert" className="text-[var(--error)]"> <p role="alert" className="text-[var(--error)] break-words">
{awsErrorMessage(boundaryError)} {awsErrorMessage(boundaryError)}
</p> </p>
)} )}
@@ -149,6 +153,7 @@ export default function DeployEnvironmentModal({
</p> </p>
<Button <Button
size="md" size="md"
wrap
onClick={() => onClick={() =>
setBundle({ setBundle({
reason: boundaryFailed.summary ?? `OpenTofu exited with code ${boundaryFailed.exit_code}`, reason: boundaryFailed.summary ?? `OpenTofu exited with code ${boundaryFailed.exit_code}`,
@@ -179,10 +184,18 @@ export default function DeployEnvironmentModal({
First deploy downloads OpenTofu (~30 MB) and the AWS provider (~150 MB). First deploy downloads OpenTofu (~30 MB) and the AWS provider (~150 MB).
</p> </p>
{error && ( {error && (
<p role="alert" className="text-xs text-[var(--error)] leading-snug"> <p role="alert" className="text-xs text-[var(--error)] leading-snug break-words">
{awsErrorMessage(error)} {awsErrorMessage(error)}
</p> </p>
)} )}
{error?.kind === "access_denied" && onBundle && !repair && (
<div className="space-y-1.5 text-xs text-[var(--text-secondary)] leading-snug">
<p>An admin can deploy this environment for you from a bundle.</p>
<Button size="sm" wrap onClick={onBundle}>
Save an environment bundle for an admin…
</Button>
</div>
)}
</div> </div>
)} )}
</Modal> </Modal>
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach } from "vitest"; import { describe, it, expect, vi, beforeEach } from "vitest";
import { act, renderHook } from "@testing-library/react"; import { act, render, renderHook, screen } from "@testing-library/react";
import { runKey, useDeployRuns } from "./DeployProgress"; import DeployProgressView, { runKey, useDeployRuns } from "./DeployProgress";
import type { DeployProgress } from "../../../lib/types"; import type { DeployProgress } from "../../../lib/types";
import { progress, tofuEvent } from "./testkit"; import { progress, tofuEvent } from "./testkit";
@@ -29,10 +29,10 @@ describe("useDeployRuns", () => {
const onDone = vi.fn(); const onDone = vi.fn();
const { result } = renderHook(() => useDeployRuns(onDone)); const { result } = renderHook(() => useDeployRuns(onDone));
await act(async () => { await act(async () => {
await result.current.start(KEY, "eu-west-1", "Deploy of main", async () => "eu"); await result.current.start(KEY, "eu-west-1", "deploy", "Deploy of main", async () => "eu");
}); });
await act(async () => { await act(async () => {
await result.current.start(KEY, "us-east-1", "Deploy of main", async () => "us"); await result.current.start(KEY, "us-east-1", "deploy", "Deploy of main", async () => "us");
}); });
expect(handlers.size).toBe(2); expect(handlers.size).toBe(2);
emit(progress({ op_id: "eu", state_key: KEY, events: [tofuEvent("eu line")] })); emit(progress({ op_id: "eu", state_key: KEY, events: [tofuEvent("eu line")] }));
@@ -54,8 +54,8 @@ describe("useDeployRuns", () => {
it("removes its progress listeners on unmount", async () => { it("removes its progress listeners on unmount", async () => {
const { result, unmount } = renderHook(() => useDeployRuns()); const { result, unmount } = renderHook(() => useDeployRuns());
await act(async () => { await act(async () => {
await result.current.start(KEY, "eu-west-1", "Deploy of main", async () => "a"); await result.current.start(KEY, "eu-west-1", "deploy", "Deploy of main", async () => "a");
await result.current.start("boundary/terraform.tfstate", "eu-west-1", "Boundary", async () => "b"); await result.current.start("boundary/terraform.tfstate", "eu-west-1", "deploy", "Boundary", async () => "b");
}); });
expect(handlers.size).toBe(2); expect(handlers.size).toBe(2);
unmount(); unmount();
@@ -66,7 +66,7 @@ describe("useDeployRuns", () => {
const { result } = renderHook(() => useDeployRuns()); const { result } = renderHook(() => useDeployRuns());
let err: unknown; let err: unknown;
await act(async () => { await act(async () => {
err = await result.current.start(KEY, "eu-west-1", "Deploy of main", async () => { err = await result.current.start(KEY, "eu-west-1", "deploy", "Deploy of main", async () => {
throw { kind: "other", message: "A deployment is already running" }; throw { kind: "other", message: "A deployment is already running" };
}); });
}); });
@@ -75,3 +75,28 @@ describe("useDeployRuns", () => {
expect(result.current.runs).toEqual({}); expect(result.current.runs).toEqual({});
}); });
}); });
describe("DeployProgress layout", () => {
it("wraps its header and a long failure summary", () => {
render(
<DeployProgressView
connectionId="h1"
run={{
stateKey: KEY,
region: "eu-west-1",
kind: "deploy",
label: "Deploy of main",
opId: "x",
events: [],
done: true,
cancellable: false,
result: { ok: false, exit_code: 1, summary: "a very long summary ".repeat(10) },
}}
/>,
);
const header = screen.getByTestId("deploy-progress-header");
expect(header.className).toContain("flex-wrap");
expect(header.firstElementChild?.className).toContain("min-w-0");
expect(screen.getByRole("status").firstElementChild?.className).toContain("whitespace-normal");
});
});
@@ -13,10 +13,18 @@ import Button from "../../ui/Button";
import Modal from "../../ui/Modal"; import Modal from "../../ui/Modal";
import StatusIndicator from "../../ui/StatusIndicator"; import StatusIndicator from "../../ui/StatusIndicator";
/**
* What a run does. Decisions about a run (such as offering an admin bundle
* when AWS refuses it) key on this, never on its label: a follow of an
* existing environment's deploy is labelled like a new deploy.
*/
export type RunKind = "deploy" | "follow" | "repair" | "update" | "destroy" | "onboard" | "push" | "boundary";
/** One OpenTofu run this view is showing: a start, or a follow of one already running. */ /** One OpenTofu run this view is showing: a start, or a follow of one already running. */
export interface DeployRun { export interface DeployRun {
stateKey: string; stateKey: string;
region: string; region: string;
kind: RunKind;
label: string; label: string;
/** Null until the starting command resolves. */ /** Null until the starting command resolves. */
opId: string | null; opId: string | null;
@@ -57,7 +65,13 @@ export function useDeployRuns(
}, []); }, []);
const start = useCallback( const start = useCallback(
async (stateKey: string, region: string, label: string, run: () => Promise<string>): Promise<AwsError | null> => { async (
stateKey: string,
region: string,
kind: RunKind,
label: string,
run: () => Promise<string>,
): Promise<AwsError | null> => {
const k = runKey(region, stateKey); const k = runKey(region, stateKey);
subs.current.get(k)?.unlisten?.(); subs.current.get(k)?.unlisten?.();
const sub: Subscription = { unlisten: null }; const sub: Subscription = { unlisten: null };
@@ -94,7 +108,7 @@ export function useDeployRuns(
setRuns((prev) => ({ setRuns((prev) => ({
...prev, ...prev,
[k]: { stateKey, region, label, opId: null, events: [], done: false, cancellable: false, result: null }, [k]: { stateKey, region, kind, label, opId: null, events: [], done: false, cancellable: false, result: null },
})); }));
const unlisten = await listen<ProgressPayload>(AWS_DEPLOY_PROGRESS_EVENT, ({ payload }) => { const unlisten = await listen<ProgressPayload>(AWS_DEPLOY_PROGRESS_EVENT, ({ payload }) => {
@@ -146,7 +160,7 @@ function EventLine({ e }: { e: TofuEvent }) {
return ( return (
<li className="text-xs leading-snug"> <li className="text-xs leading-snug">
{(e.resource || e.action) && ( {(e.resource || e.action) && (
<span className="mr-1.5"> <span className="mr-1.5 break-all">
{e.resource && <span className="font-mono text-[var(--text-primary)]">{e.resource}</span>} {e.resource && <span className="font-mono text-[var(--text-primary)]">{e.resource}</span>}
{e.action && <span className="ml-1 text-[var(--text-secondary)]">{e.action}</span>} {e.action && <span className="ml-1 text-[var(--text-secondary)]">{e.action}</span>}
</span> </span>
@@ -154,10 +168,10 @@ function EventLine({ e }: { e: TofuEvent }) {
{isError ? ( {isError ? (
<> <>
<span className="font-semibold text-[var(--error)]">Error: </span> <span className="font-semibold text-[var(--error)]">Error: </span>
<pre className="whitespace-pre-wrap break-words font-mono text-[var(--error)]">{e.message}</pre> <pre className="max-w-full overflow-x-auto whitespace-pre-wrap break-words font-mono text-[var(--error)]">{e.message}</pre>
</> </>
) : ( ) : (
<span className="text-[var(--text-secondary)]">{e.message}</span> <span className="text-[var(--text-secondary)] break-words">{e.message}</span>
)} )}
</li> </li>
); );
@@ -205,14 +219,14 @@ export default function DeployProgress({
return ( return (
<section <section
aria-label={`${run.label} progress`} aria-label={`${run.label} progress`}
className="space-y-1.5 border border-[var(--border-color)] rounded-[var(--radius-control)] p-2 bg-[var(--bg-primary)]" className="space-y-1.5 min-w-0 border border-[var(--border-color)] rounded-[var(--radius-control)] p-2 bg-[var(--bg-primary)]"
> >
<div className="flex items-center justify-between gap-2 flex-wrap"> <div className="flex items-center justify-between gap-2 flex-wrap" data-testid="deploy-progress-header">
<div className="flex items-center gap-2 text-xs"> <div className="flex items-center gap-2 text-xs flex-wrap min-w-0">
<span className="font-medium text-[var(--text-primary)]">{run.label}</span> <span className="font-medium text-[var(--text-primary)] break-words min-w-0">{run.label}</span>
{status && <StatusIndicator tone={status.tone} label={status.label} />} {status && <StatusIndicator tone={status.tone} label={status.label} />}
</div> </div>
<div className="flex gap-1.5"> <div className="flex gap-1.5 flex-wrap">
{!run.done && ( {!run.done && (
<Button <Button
size="sm" size="sm"
@@ -239,11 +253,12 @@ export default function DeployProgress({
</ol> </ol>
)} )}
{run.done && run.result && ( {run.done && run.result && (
<p role="status" className="text-xs"> <p role="status" className="text-xs break-words">
{run.result.ok ? ( {run.result.ok ? (
<StatusIndicator tone="ok" label={`Finished${run.result.summary ? `: ${run.result.summary}` : ""}`} /> <StatusIndicator wrap tone="ok" label={`Finished${run.result.summary ? `: ${run.result.summary}` : ""}`} />
) : ( ) : (
<StatusIndicator <StatusIndicator
wrap
tone="error" tone="error"
label={`Failed (exit ${run.result.exit_code})${run.result.summary ? `: ${run.result.summary}` : ""}`} label={`Failed (exit ${run.result.exit_code})${run.result.summary ? `: ${run.result.summary}` : ""}`}
/> />
@@ -251,7 +266,7 @@ export default function DeployProgress({
</p> </p>
)} )}
{cancelError && !confirming && ( {cancelError && !confirming && (
<p role="alert" className="text-xs text-[var(--error)]"> <p role="alert" className="text-xs text-[var(--error)] break-words">
{awsErrorMessage(cancelError)} {awsErrorMessage(cancelError)}
</p> </p>
)} )}
@@ -48,6 +48,7 @@ export default function Ec2CapacityFields({
<div className="text-[13px] font-medium text-[var(--text-primary)]">EC2 capacity</div> <div className="text-[13px] font-medium text-[var(--text-primary)]">EC2 capacity</div>
<SegmentedControl<"none" | "ec2"> <SegmentedControl<"none" | "ec2">
label="EC2 capacity" label="EC2 capacity"
className="flex-wrap max-w-full"
value={value.enabled ? "ec2" : "none"} value={value.enabled ? "ec2" : "none"}
onChange={(v) => set({ enabled: v === "ec2" })} onChange={(v) => set({ enabled: v === "ec2" })}
segments={[ segments={[
@@ -81,7 +81,7 @@ describe("EnvironmentsPanel", () => {
expect(within(screen.getByTestId("env-dev")).getByText("Joined")).toBeInTheDocument(); expect(within(screen.getByTestId("env-dev")).getByText("Joined")).toBeInTheDocument();
}); });
it("offers an admin bundle instead of deploy for a workspace user with nothing found", async () => { it("offers deploy to a workspace user too, with a note and the admin options under a disclosure", async () => {
backend( backend(
() => scan(), () => scan(),
(cmd) => { (cmd) => {
@@ -91,22 +91,162 @@ describe("EnvironmentsPanel", () => {
); );
render(<EnvironmentsPanel connection={conn} tier="workspace_user" />); render(<EnvironmentsPanel connection={conn} tier="workspace_user" />);
await open(); await open();
expect(await screen.findByText(/needs an environment admin/)).toBeInTheDocument(); const deploy = await screen.findByRole("button", { name: "Deploy a new environment" });
expect(screen.queryByRole("button", { name: "Deploy a new environment" })).toBeNull(); expect(deploy.className).toContain("--accent-emphasis");
fireEvent.click(screen.getByRole("button", { name: "Show the environment-admin policies" })); expect(screen.getByTestId("deploy-unconfirmed-note")).toHaveTextContent(
expect(await screen.findByText("environment-admin.json")).toBeInTheDocument(); "Your permission check didn't confirm environment-admin rights; the deploy will stop with AWS's message if a permission is missing.",
);
const options = screen.getByTestId("not-admin-options");
expect(options.tagName).toBe("DETAILS");
expect(within(options).getByText(/Not an admin\?/)).toBeInTheDocument();
fireEvent.click(within(options).getByRole("button", { name: "Show the environment-admin policies" }));
expect(await within(options).findByRole("button", { name: "Copy environment-admin.json" })).toBeInTheDocument();
expect(invoke).toHaveBeenCalledWith("aws_policy_document", { tier: "environment_admin" }); expect(invoke).toHaveBeenCalledWith("aws_policy_document", { tier: "environment_admin" });
fireEvent.click(screen.getByRole("button", { name: "Request an environment from an admin…" })); fireEvent.click(within(options).getByRole("button", { name: "Request an environment from an admin…" }));
const dialog = screen.getByRole("dialog"); const dialog = screen.getByRole("dialog");
expect(within(dialog).getByRole("button", { name: "Save bundle to folder…" })).toBeInTheDocument(); expect(within(dialog).getByRole("button", { name: "Save bundle to folder…" })).toBeInTheDocument();
}); });
it("treats a connection with no permission report as not an admin", async () => { it("opens the deploy form for a workspace user", async () => {
backend(() => scan());
render(<EnvironmentsPanel connection={conn} tier="workspace_user" />);
await open();
fireEvent.click(await screen.findByRole("button", { name: "Deploy a new environment" }));
expect(screen.getByRole("dialog", { name: "Deploy a new environment" })).toBeInTheDocument();
});
it("an admin sees deploy without the note or the not-an-admin options", async () => {
backend(() => scan());
render(<EnvironmentsPanel connection={conn} tier="environment_admin" />);
await open();
expect(await screen.findByRole("button", { name: "Deploy a new environment" })).toBeInTheDocument();
expect(screen.queryByTestId("deploy-unconfirmed-note")).toBeNull();
expect(screen.queryByTestId("not-admin-options")).toBeNull();
});
it("a connection with no permission report gets deploy with the note", async () => {
backend(() => scan()); backend(() => scan());
render(<EnvironmentsPanel connection={conn} />); render(<EnvironmentsPanel connection={conn} />);
await open(); await open();
expect(await screen.findByRole("button", { name: "Request an environment from an admin…" })).toBeInTheDocument(); expect(await screen.findByRole("button", { name: "Deploy a new environment" })).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Deploy a new environment" })).toBeNull(); expect(screen.getByTestId("deploy-unconfirmed-note")).toBeInTheDocument();
expect(screen.getByText(/Run Check to see what your credentials can do/)).toBeInTheDocument();
});
it("shows the boundary note to anyone when the account has no boundary", async () => {
backend(() => scan({ boundary: "no" }));
render(<EnvironmentsPanel connection={conn} tier="workspace_user" />);
await open();
expect(await screen.findByText(/no Triple-C permissions boundary yet/)).toBeInTheDocument();
});
it("offers a bundle when AWS refuses a deploy run's permission", async () => {
backend(
() => scan(),
(cmd) => {
if (cmd === "deploy_aws_environment") return "d1";
throw new Error(`unexpected ${cmd}`);
},
);
render(<EnvironmentsPanel connection={conn} tier="workspace_user" />);
await open();
fireEvent.click(await screen.findByRole("button", { name: "Deploy a new environment" }));
fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Deploy" }));
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
const key = "environments/main/terraform.tfstate";
emit(
progress({
op_id: "d1",
state_key: key,
events: [tofuEvent("creating IAM Role: AccessDenied: User is not authorized to perform iam:CreateRole", { level: "error" })],
}),
);
emit(progress({ op_id: "d1", state_key: key, done: true, cancellable: false, result: { ok: false, exit_code: 1, summary: null } }));
const hint = await screen.findByTestId("denied-hint");
expect(hint).toHaveTextContent("AWS refused a permission");
fireEvent.click(within(hint).getByRole("button", { name: "Save a bundle for an admin…" }));
expect(within(screen.getByRole("dialog")).getByRole("button", { name: "Save bundle to folder…" })).toBeInTheDocument();
});
it("never offers a new-environment bundle for a refused follow of an existing deploy", async () => {
const key = "environments/dev/terraform.tfstate";
backend(
() => scan({ environments: [env({ actions: ["follow"], state: { state: "ready" } })] }),
(cmd) => {
if (cmd === "follow_aws_deployment") return "f9";
throw new Error(`unexpected ${cmd}`);
},
);
render(<EnvironmentsPanel connection={conn} tier="workspace_user" />);
await open();
await waitFor(() => expect(invoke.mock.calls.some((c) => c[0] === "follow_aws_deployment")).toBe(true));
await screen.findByRole("region", { name: "Deploy of dev progress" });
emit(
progress({
op_id: "f9",
state_key: key,
events: [tofuEvent("AccessDenied: User is not authorized to perform ecs:UpdateService", { level: "error" })],
}),
);
emit(progress({ op_id: "f9", state_key: key, done: true, cancellable: false, result: { ok: false, exit_code: 1, summary: null } }));
expect(await screen.findByText(/Failed \(exit 1\)/)).toBeInTheDocument();
expect(screen.queryByTestId("denied-hint")).toBeNull();
});
it("marks the not-an-admin disclosure open or closed like the Environments toggle", async () => {
backend(() => scan());
render(<EnvironmentsPanel connection={conn} tier="workspace_user" />);
await open();
const options = await screen.findByTestId("not-admin-options");
const summary = options.querySelector("summary")!;
expect(summary).toHaveTextContent("▸");
(options as HTMLDetailsElement).open = true;
fireEvent(options, new Event("toggle"));
await waitFor(() => expect(summary).toHaveTextContent("▾"));
});
it("shows a refused deploy's AWS message and offers the bundle", async () => {
backend(
() => scan(),
(cmd) => {
if (cmd === "deploy_aws_environment")
throw { kind: "access_denied", action: "s3:CreateBucket", message: "User is not authorized" };
throw new Error(`unexpected ${cmd}`);
},
);
render(<EnvironmentsPanel connection={conn} tier="workspace_user" />);
await open();
fireEvent.click(await screen.findByRole("button", { name: "Deploy a new environment" }));
const dialog = screen.getByRole("dialog");
fireEvent.click(within(dialog).getByRole("button", { name: "Deploy" }));
expect(await within(dialog).findByText("AWS denied s3:CreateBucket: User is not authorized")).toBeInTheDocument();
fireEvent.click(within(dialog).getByRole("button", { name: "Save an environment bundle for an admin…" }));
expect(within(screen.getByRole("dialog")).getByRole("button", { name: "Save bundle to folder…" })).toBeInTheDocument();
});
it("keeps the key rows wrapping in a narrow sidebar", async () => {
backend(
() => scan({ environments: [env({ actions: ["join", "update", "repair"] })] }),
(cmd) => {
if (cmd === "aws_policy_document") return [{ name: "a.json", json: "{}" }, { name: "b.json", json: "{}" }];
throw new Error(`unexpected ${cmd}`);
},
);
render(<EnvironmentsPanel connection={conn} tier="workspace_user" />);
await open();
const row = await screen.findByTestId("env-row-dev");
expect(row.className).toContain("flex-wrap");
expect(row.firstElementChild?.className).toContain("min-w-0");
const actions = screen.getByTestId("env-actions-dev");
expect(actions.className).toContain("flex-wrap");
expect(actions.className).toContain("min-w-0");
expect(screen.getByTestId("region-row").className).toContain("flex-wrap");
expect(screen.getByRole("button", { name: "Deploy a new environment" }).className).toContain("whitespace-normal");
fireEvent.click(screen.getByRole("button", { name: "Show the environment-admin policies" }));
const grid = await screen.findByTestId("policy-copy-grid");
expect(grid.className).toContain("grid");
expect(grid.className).toContain("auto-fill");
for (const b of within(grid).getAllByRole("button")) expect(b.className).toContain("whitespace-normal");
}); });
it("an incomplete environment offers repair and destroy, destroy only after typing its name", async () => { it("an incomplete environment offers repair and destroy, destroy only after typing its name", async () => {
@@ -248,7 +388,43 @@ describe("EnvironmentsPanel", () => {
expect(await within(screen.getByTestId("env-dev")).findByText("Joined")).toBeInTheDocument(); expect(await within(screen.getByTestId("env-dev")).findByText("Joined")).toBeInTheDocument();
}); });
it("a workspace user's join opens the onboarding bundle and waits for an admin", async () => { it("a workspace user can join themselves, with the note", async () => {
backend(
() => scan({ environments: [env()] }),
(cmd) => {
if (cmd === "onboard_aws_user") return "j1";
throw new Error(`unexpected ${cmd}`);
},
);
render(<EnvironmentsPanel connection={conn} tier="workspace_user" />);
await open();
fireEvent.click(await screen.findByRole("button", { name: "Join dev" }));
const dialog = screen.getByRole("dialog", { name: "Join dev" });
expect(within(dialog).getByTestId("join-unconfirmed-note")).toBeInTheDocument();
fireEvent.click(within(dialog).getByRole("button", { name: "Join" }));
await waitFor(() =>
expect(invoke).toHaveBeenCalledWith("onboard_aws_user", expect.objectContaining({ environment: "dev" })),
);
});
it("a refused join shows AWS's message and offers the onboarding bundle", async () => {
backend(
() => scan({ environments: [env()] }),
(cmd) => {
if (cmd === "onboard_aws_user") throw { kind: "access_denied", action: "s3:PutObject", message: "explicit deny" };
throw new Error(`unexpected ${cmd}`);
},
);
render(<EnvironmentsPanel connection={conn} tier="workspace_user" />);
await open();
fireEvent.click(await screen.findByRole("button", { name: "Join dev" }));
const dialog = screen.getByRole("dialog", { name: "Join dev" });
fireEvent.click(within(dialog).getByRole("button", { name: "Join" }));
expect(await within(dialog).findByText("AWS denied s3:PutObject: explicit deny")).toBeInTheDocument();
expect(within(dialog).getByText(/AWS refused this with your permissions/)).toBeInTheDocument();
});
it("a workspace user can switch the join to an onboarding bundle and then waits for an admin", async () => {
backend( backend(
() => scan({ environments: [env()] }), () => scan({ environments: [env()] }),
(cmd) => { (cmd) => {
@@ -259,6 +435,11 @@ describe("EnvironmentsPanel", () => {
render(<EnvironmentsPanel connection={conn} tier="workspace_user" />); render(<EnvironmentsPanel connection={conn} tier="workspace_user" />);
await open(); await open();
fireEvent.click(await screen.findByRole("button", { name: "Join dev" })); fireEvent.click(await screen.findByRole("button", { name: "Join dev" }));
fireEvent.click(
within(screen.getByRole("dialog", { name: "Join dev" })).getByRole("button", {
name: "Save an onboarding bundle for an admin…",
}),
);
const dialog = screen.getByRole("dialog"); const dialog = screen.getByRole("dialog");
// Opening the bundle is not a request yet. // Opening the bundle is not a request yet.
expect(screen.queryByText("Waiting for an admin to onboard you")).toBeNull(); expect(screen.queryByText("Waiting for an admin to onboard you")).toBeNull();
@@ -280,6 +461,14 @@ describe("EnvironmentsPanel", () => {
expect(within(screen.getByTestId("env-dev")).getByText("Waiting for an admin to onboard you")).toBeInTheDocument(); expect(within(screen.getByTestId("env-dev")).getByText("Waiting for an admin to onboard you")).toBeInTheDocument();
}); });
it("an admin's join has no unconfirmed note", async () => {
backend(() => scan({ environments: [env()] }));
render(<EnvironmentsPanel connection={conn} tier="environment_admin" />);
await open();
fireEvent.click(await screen.findByRole("button", { name: "Join dev" }));
expect(within(screen.getByRole("dialog", { name: "Join dev" })).queryByTestId("join-unconfirmed-note")).toBeNull();
});
it("an admin joins with EC2 capacity: a type from the table, max instances and their triple-c-user value", async () => { it("an admin joins with EC2 capacity: a type from the table, max instances and their triple-c-user value", async () => {
backend( backend(
() => scan({ environments: [env()] }), () => scan({ environments: [env()] }),
@@ -422,7 +611,7 @@ describe("EnvironmentsPanel", () => {
expect(within(dialog).queryByText(/Choosing None removes/)).toBeNull(); expect(within(dialog).queryByText(/Choosing None removes/)).toBeNull();
}); });
it("a joined workspace user's capacity change is a bundle starting from their record", async () => { it("a joined workspace user's capacity bundle starts from their record", async () => {
backend( backend(
() => scan({ environments: [env({ onboarding: { state: "joined", ec2: compute({ max_instances: 1 }) } })] }), () => scan({ environments: [env({ onboarding: { state: "joined", ec2: compute({ max_instances: 1 }) } })] }),
(cmd) => { (cmd) => {
@@ -434,6 +623,7 @@ describe("EnvironmentsPanel", () => {
render(<EnvironmentsPanel connection={conn} tier="workspace_user" />); render(<EnvironmentsPanel connection={conn} tier="workspace_user" />);
await open(); await open();
fireEvent.click(await screen.findByRole("button", { name: "EC2 capacity in dev" })); fireEvent.click(await screen.findByRole("button", { name: "EC2 capacity in dev" }));
fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Save an onboarding bundle for an admin…" }));
const dialog = screen.getByRole("dialog", { name: "Onboarding bundle" }); const dialog = screen.getByRole("dialog", { name: "Onboarding bundle" });
fireEvent.click(within(dialog).getByRole("button", { name: "Save bundle to folder…" })); fireEvent.click(within(dialog).getByRole("button", { name: "Save bundle to folder…" }));
await waitFor(() => await waitFor(() =>
@@ -525,6 +715,7 @@ describe("EnvironmentsPanel", () => {
render(<EnvironmentsPanel connection={conn} tier="workspace_user" />); render(<EnvironmentsPanel connection={conn} tier="workspace_user" />);
await open(); await open();
fireEvent.click(await screen.findByRole("button", { name: "Join dev" })); fireEvent.click(await screen.findByRole("button", { name: "Join dev" }));
fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Save an onboarding bundle for an admin…" }));
fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Close" })); fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Close" }));
expect(screen.queryByText("Waiting for an admin to onboard you")).toBeNull(); expect(screen.queryByText("Waiting for an admin to onboard you")).toBeNull();
expect(within(screen.getByTestId("env-dev")).getByRole("button", { name: "Join dev" })).toHaveTextContent("Join"); expect(within(screen.getByTestId("env-dev")).getByRole("button", { name: "Join dev" })).toHaveTextContent("Join");
@@ -10,7 +10,7 @@ import {
unlockAwsState, unlockAwsState,
updateAwsEnvironment, updateAwsEnvironment,
} from "../../../lib/tauri-commands"; } from "../../../lib/tauri-commands";
import { awsErrorMessage, toAwsError } from "../../../lib/aws-error"; import { awsErrorMessage, looksDenied, toAwsError } from "../../../lib/aws-error";
import { clearEc2CapacityCache } from "../../../lib/ec2Capacity"; import { clearEc2CapacityCache } from "../../../lib/ec2Capacity";
import type { import type {
AwsError, AwsError,
@@ -34,7 +34,7 @@ import AdminBundleModal from "./AdminBundleModal";
import UpdateEnvironmentModal from "./UpdateEnvironmentModal"; import UpdateEnvironmentModal from "./UpdateEnvironmentModal";
import DeployEnvironmentModal from "./DeployEnvironmentModal"; import DeployEnvironmentModal from "./DeployEnvironmentModal";
import JoinEnvironmentModal from "./JoinEnvironmentModal"; import JoinEnvironmentModal from "./JoinEnvironmentModal";
import DeployProgress, { runKey, useDeployRuns, type DeployRun } from "./DeployProgress"; import DeployProgress, { runKey, useDeployRuns, type DeployRun, type RunKind } from "./DeployProgress";
import PolicyFiles from "./PolicyFiles"; import PolicyFiles from "./PolicyFiles";
import { import {
COMMON_REGIONS, COMMON_REGIONS,
@@ -45,6 +45,7 @@ import {
onboardingStateKey, onboardingStateKey,
stateLock, stateLock,
stateStatus, stateStatus,
UNCONFIRMED_NOTE,
} from "./environmentFormat"; } from "./environmentFormat";
/** A typed confirmation: the action runs only once the environment's name is typed. */ /** A typed confirmation: the action runs only once the environment's name is typed. */
@@ -118,6 +119,7 @@ type Bundle = {
type JoinOf = { type JoinOf = {
region: string; region: string;
name: string; name: string;
ownerId: string;
stateKey: string; stateKey: string;
recorded: UserCompute | null; recorded: UserCompute | null;
reapply: boolean; reapply: boolean;
@@ -131,6 +133,21 @@ const recordedEc2 = (e: DetectedEnvironment): UserCompute | null =>
/** A row-level key: the same environment name can exist in every region. */ /** A row-level key: the same environment name can exist in every region. */
const rowKey = (region: string, name: string) => `${region}:${name}`; const rowKey = (region: string, name: string) => `${region}:${name}`;
/**
* A failed new deploy or self-onboarding started here that AWS refused a
* permission for: the bundle for an admin is the way on. Only those two
* kinds: an environment bundle deploys a *new* environment, so a follow,
* repair or update of an existing one is never offered it.
*/
function deniedRun(r: DeployRun): "environment" | "user_onboard" | null {
if (r.kind !== "deploy" && r.kind !== "onboard") return null;
if (!r.done || !r.result || r.result.ok) return null;
const denied =
looksDenied(r.result.summary) || r.events.some((e) => e.level === "error" && looksDenied(e.message));
if (!denied) return null;
return r.kind === "deploy" ? "environment" : "user_onboard";
}
/** The environment a run's state key belongs to, if any. */ /** The environment a run's state key belongs to, if any. */
function runEnvironment(stateKey: string): string | null { function runEnvironment(stateKey: string): string | null {
const m = /^(?:environments|users)\/([^/]+)\//.exec(stateKey); const m = /^(?:environments|users)\/([^/]+)\//.exec(stateKey);
@@ -139,14 +156,16 @@ function runEnvironment(stateKey: string): string | null {
/** /**
* The environments a connection can reach in a region (spec §2): detection, * The environments a connection can reach in a region (spec §2): detection,
* each environment's state and actions, and deploy/join for this caller's tier. * each environment's state and actions, and deploy/join. Deploy and join are
* offered to anyone (AWS has the last word and its refusal is shown); an
* unconfirmed tier only adds a note and the bundle-for-an-admin alternative.
*/ */
export default function EnvironmentsPanel({ export default function EnvironmentsPanel({
connection, connection,
tier, tier,
}: { }: {
connection: HostConnection; connection: HostConnection;
/** The connection's last permission report; absent means unknown, treated as not an admin. */ /** The connection's last permission report; absent means unknown (not confirmed as an admin). */
tier?: PermissionSummary; tier?: PermissionSummary;
}) { }) {
const isAdmin = tier === "environment_admin"; const isAdmin = tier === "environment_admin";
@@ -176,6 +195,7 @@ export default function EnvironmentsPanel({
// onboarding that didn't finish has no record to start from. // onboarding that didn't finish has no record to start from.
const lastEc2 = useRef(new Map<string, Ec2Compute>()); const lastEc2 = useRef(new Map<string, Ec2Compute>());
const [copyNote, setCopyNote] = useState<string | null>(null); const [copyNote, setCopyNote] = useState<string | null>(null);
const [notAdminOpen, setNotAdminOpen] = useState(false);
const request = useRef(0); const request = useRef(0);
const followed = useRef(new Set<string>()); const followed = useRef(new Set<string>());
@@ -210,11 +230,18 @@ export default function EnvironmentsPanel({
/** Start a run in `runRegion` (always the region of the scan the action came from). */ /** Start a run in `runRegion` (always the region of the scan the action came from). */
const launch = useCallback( const launch = useCallback(
async (runRegion: string, envName: string, stateKey: string, label: string, run: () => Promise<string>) => { async (
runRegion: string,
envName: string,
stateKey: string,
kind: RunKind,
label: string,
run: () => Promise<string>,
) => {
const rk = rowKey(runRegion, envName); const rk = rowKey(runRegion, envName);
setRowErrors(({ [rk]: _gone, ...rest }) => rest); setRowErrors(({ [rk]: _gone, ...rest }) => rest);
setPending((p) => ({ ...p, [rk]: true })); setPending((p) => ({ ...p, [rk]: true }));
const err = await start(stateKey, runRegion, label, run); const err = await start(stateKey, runRegion, kind, label, run);
setPending(({ [rk]: _gone, ...rest }) => rest); setPending(({ [rk]: _gone, ...rest }) => rest);
if (err) setRowErrors((r) => ({ ...r, [rk]: err })); if (err) setRowErrors((r) => ({ ...r, [rk]: err }));
return err; return err;
@@ -230,7 +257,7 @@ export default function EnvironmentsPanel({
const seen = runKey(scan.region, key); const seen = runKey(scan.region, key);
if (!runs[seen] && !followed.current.has(seen)) { if (!runs[seen] && !followed.current.has(seen)) {
followed.current.add(seen); followed.current.add(seen);
void launch(scan.region, name, key, label, () => followAwsDeployment(connection.id, scan.region, key)); void launch(scan.region, name, key, "follow", label, () => followAwsDeployment(connection.id, scan.region, key));
} }
}; };
for (const e of scan.environments) { for (const e of scan.environments) {
@@ -261,50 +288,42 @@ export default function EnvironmentsPanel({
const stale = detecting || !current; const stale = detecting || !current;
const deploy = (runRegion: string, name: string, network: NetworkChoice, hours: number) => const deploy = (runRegion: string, name: string, network: NetworkChoice, hours: number) =>
launch(runRegion, name, environmentStateKey(name), `Deploy of ${name}`, () => launch(runRegion, name, environmentStateKey(name), "deploy", `Deploy of ${name}`, () =>
deployAwsEnvironment(connection.id, runRegion, name, network, hours), deployAwsEnvironment(connection.id, runRegion, name, network, hours),
); );
// Without `hours`, the environment's recorded cap is kept. // Without `hours`, the environment's recorded cap is kept.
const repair = (runRegion: string, name: string, network?: NetworkChoice, hours?: number) => const repair = (runRegion: string, name: string, network?: NetworkChoice, hours?: number) =>
launch(runRegion, name, environmentStateKey(name), `Repair of ${name}`, () => launch(runRegion, name, environmentStateKey(name), "repair", `Repair of ${name}`, () =>
repairAwsEnvironment(connection.id, runRegion, name, network, hours), repairAwsEnvironment(connection.id, runRegion, name, network, hours),
); );
const update = (runRegion: string, name: string, hours: number) => const update = (runRegion: string, name: string, hours: number) =>
launch(runRegion, name, environmentStateKey(name), `Update of ${name}`, () => launch(runRegion, name, environmentStateKey(name), "update", `Update of ${name}`, () =>
updateAwsEnvironment(connection.id, runRegion, name, hours), updateAwsEnvironment(connection.id, runRegion, name, hours),
); );
// Join (or, once joined, a change of EC2 capacity): admins choose the // Join (or, once joined, a change of EC2 capacity): anyone chooses the
// capacity and apply it themselves; others get a bundle for an admin. // capacity and applies it; the modal offers a bundle for an admin instead.
const join = (found: EnvironmentScan, e: DetectedEnvironment) => { const join = (found: EnvironmentScan, e: DetectedEnvironment) => {
const recorded = recordedEc2(e); setJoinOf({
if (isAdmin) { region: found.region,
setJoinOf({ name: e.name,
region: found.region, ownerId: found.owner_id,
name: e.name, stateKey: onboardingStateKey(e.name, found.owner_key),
stateKey: onboardingStateKey(e.name, found.owner_key), recorded: recordedEc2(e),
recorded, reapply: e.onboarding?.state === "joined",
reapply: e.onboarding?.state === "joined", incomplete: e.onboarding?.state === "incomplete",
incomplete: e.onboarding?.state === "incomplete", lastChoice: lastEc2.current.get(rowKey(found.region, e.name)) ?? null,
lastChoice: lastEc2.current.get(rowKey(found.region, e.name)) ?? null, });
});
} else {
setBundle({
kind: "user_onboard",
region: found.region,
environment: e.name,
ownerId: found.owner_id,
recordedEc2: recorded,
});
}
}; };
const onboardBundle = (region: string, environment: string, ownerId: string, recorded: UserCompute | null) =>
setBundle({ kind: "user_onboard", region, environment, ownerId, recordedEc2: recorded });
const runJoin = (j: JoinOf, ec2: Ec2Choice) => { const runJoin = (j: JoinOf, ec2: Ec2Choice) => {
const key = rowKey(j.region, j.name); const key = rowKey(j.region, j.name);
if (ec2.kind === "ec2") { if (ec2.kind === "ec2") {
const { kind: _kind, ...c } = ec2; const { kind: _kind, ...c } = ec2;
lastEc2.current.set(key, c); lastEc2.current.set(key, c);
} else lastEc2.current.delete(key); } else lastEc2.current.delete(key);
return launch(j.region, j.name, j.stateKey, `Joining ${j.name}`, () => onboardAwsUser(connection.id, j.region, j.name, ec2)); return launch(j.region, j.name, j.stateKey, "onboard", `Joining ${j.name}`, () => onboardAwsUser(connection.id, j.region, j.name, ec2));
}; };
const rowRuns = (name: string) => const rowRuns = (name: string) =>
@@ -313,14 +332,40 @@ export default function EnvironmentsPanel({
const looseRuns = Object.values(runs).filter( const looseRuns = Object.values(runs).filter(
(r) => r.region !== current?.region || !shown.has(runEnvironment(r.stateKey) ?? ""), (r) => r.region !== current?.region || !shown.has(runEnvironment(r.stateKey) ?? ""),
); );
const progress = (r: DeployRun) => ( const progress = (r: DeployRun) => {
<DeployProgress const denied = deniedRun(r);
key={runKey(r.region, r.stateKey)} const env = runEnvironment(r.stateKey);
run={r} const found = current?.region === r.region ? current : null;
connectionId={connection.id} const target = env && found ? found.environments.find((e) => e.name === env) : undefined;
onDismiss={() => dismiss(runKey(r.region, r.stateKey))} const offer =
/> denied === "environment" ? true : denied === "user_onboard" ? !!(found && target) : false;
); return (
<div key={runKey(r.region, r.stateKey)} className="space-y-1.5 min-w-0">
<DeployProgress run={r} connectionId={connection.id} onDismiss={() => dismiss(runKey(r.region, r.stateKey))} />
{offer && (
<div className="space-y-1.5 text-xs text-[var(--text-secondary)] leading-snug" data-testid="denied-hint">
<p className="break-words">
AWS refused a permission this run needs (its message is above). This may need an admin:{" "}
{denied === "environment"
? "An admin can deploy the environment for you from a bundle."
: "An admin can onboard you from a bundle."}
</p>
<Button
size="sm"
wrap
onClick={() =>
denied === "environment"
? setBundle({ kind: "environment", region: r.region })
: found && target && onboardBundle(r.region, target.name, found.owner_id, recordedEc2(target))
}
>
Save a bundle for an admin…
</Button>
</div>
)}
</div>
);
};
const envRow = (found: EnvironmentScan, e: DetectedEnvironment) => { const envRow = (found: EnvironmentScan, e: DetectedEnvironment) => {
const at = found.region; const at = found.region;
@@ -349,10 +394,10 @@ export default function EnvironmentsPanel({
data-testid={`env-${e.name}`} data-testid={`env-${e.name}`}
className="border border-[var(--border-color)] rounded-[var(--radius-control)] p-2 space-y-1.5" className="border border-[var(--border-color)] rounded-[var(--radius-control)] p-2 space-y-1.5"
> >
<div className="flex items-start justify-between gap-2 flex-wrap"> <div className="flex items-start justify-between gap-2 flex-wrap" data-testid={`env-row-${e.name}`}>
<div className="min-w-0 space-y-0.5 text-xs"> <div className="min-w-0 flex-1 basis-40 space-y-0.5 text-xs break-words">
<div className="flex items-center gap-2 flex-wrap"> <div className="flex items-center gap-2 flex-wrap min-w-0">
<span className="text-[13px] font-medium text-[var(--text-primary)]">{e.name}</span> <span className="text-[13px] font-medium text-[var(--text-primary)] break-all">{e.name}</span>
<StatusIndicator tone={status.tone} label={status.label} /> <StatusIndicator tone={status.tone} label={status.label} />
{onboarding === "joined" && <StatusIndicator tone="ok" label="Joined" />} {onboarding === "joined" && <StatusIndicator tone="ok" label="Joined" />}
{onboarding === "in_progress" && <StatusIndicator tone="busy" label="Onboarding in progress" />} {onboarding === "in_progress" && <StatusIndicator tone="busy" label="Onboarding in progress" />}
@@ -407,11 +452,11 @@ export default function EnvironmentsPanel({
})()} })()}
</div> </div>
)} )}
{!isAdmin && isWaiting && onboarding !== "joined" && ( {isWaiting && onboarding !== "joined" && (
<div className="text-[var(--text-secondary)]">Waiting for an admin to onboard you</div> <div className="text-[var(--text-secondary)]">Waiting for an admin to onboard you</div>
)} )}
</div> </div>
<div className="flex gap-1.5 flex-wrap"> <div className="flex gap-1.5 flex-wrap min-w-0 max-w-full" data-testid={`env-actions-${e.name}`}>
{has("join") && onboarding !== "joined" && onboarding !== "in_progress" && ( {has("join") && onboarding !== "joined" && onboarding !== "in_progress" && (
<Button <Button
size="sm" size="sm"
@@ -420,17 +465,18 @@ export default function EnvironmentsPanel({
aria-label={`Join ${e.name}`} aria-label={`Join ${e.name}`}
onClick={() => join(found, e)} onClick={() => join(found, e)}
> >
{!isAdmin && isWaiting ? "Show onboarding bundle" : "Join"} Join
</Button> </Button>
)} )}
{has("join") && onboarding === "joined" && ( {has("join") && onboarding === "joined" && (
<Button <Button
size="sm" size="sm"
wrap
disabled={busy || joinBlocked} disabled={busy || joinBlocked}
aria-label={`EC2 capacity in ${e.name}`} aria-label={`EC2 capacity in ${e.name}`}
onClick={() => join(found, e)} onClick={() => join(found, e)}
> >
{isAdmin ? "Change EC2 capacity" : "EC2 capacity bundle"} Change EC2 capacity
</Button> </Button>
)} )}
{mine("follow") && ( {mine("follow") && (
@@ -439,7 +485,7 @@ export default function EnvironmentsPanel({
disabled={busy} disabled={busy}
aria-label={`Follow my onboarding to ${e.name}`} aria-label={`Follow my onboarding to ${e.name}`}
onClick={() => onClick={() =>
void launch(at, e.name, myKey, `Joining ${e.name}`, () => followAwsDeployment(connection.id, at, myKey)) void launch(at, e.name, myKey, "follow", `Joining ${e.name}`, () => followAwsDeployment(connection.id, at, myKey))
} }
> >
Follow Follow
@@ -451,7 +497,7 @@ export default function EnvironmentsPanel({
disabled={busy} disabled={busy}
aria-label={`Push saved state of my onboarding to ${e.name}`} aria-label={`Push saved state of my onboarding to ${e.name}`}
onClick={() => onClick={() =>
void launch(at, e.name, myKey, `Push of the saved state of joining ${e.name}`, () => void launch(at, e.name, myKey, "push", `Push of the saved state of joining ${e.name}`, () =>
pushAwsSavedState(connection.id, at, myKey), pushAwsSavedState(connection.id, at, myKey),
) )
} }
@@ -477,7 +523,7 @@ export default function EnvironmentsPanel({
aria-label={`Push saved state of ${e.name}`} aria-label={`Push saved state of ${e.name}`}
onClick={() => { onClick={() => {
const key = environmentStateKey(e.name); const key = environmentStateKey(e.name);
void launch(at, e.name, key, `Push of the saved state of ${e.name}`, () => void launch(at, e.name, key, "push", `Push of the saved state of ${e.name}`, () =>
pushAwsSavedState(connection.id, at, key), pushAwsSavedState(connection.id, at, key),
); );
}} }}
@@ -492,7 +538,7 @@ export default function EnvironmentsPanel({
aria-label={`Follow ${e.name}`} aria-label={`Follow ${e.name}`}
onClick={() => { onClick={() => {
const key = environmentStateKey(e.name); const key = environmentStateKey(e.name);
void launch(at, e.name, key, `Deploy of ${e.name}`, () => followAwsDeployment(connection.id, at, key)); void launch(at, e.name, key, "follow", `Deploy of ${e.name}`, () => followAwsDeployment(connection.id, at, key));
}} }}
> >
Follow Follow
@@ -548,7 +594,7 @@ export default function EnvironmentsPanel({
</div> </div>
</div> </div>
{rowError && ( {rowError && (
<p role="alert" className="text-xs text-[var(--error)] leading-snug"> <p role="alert" className="text-xs text-[var(--error)] leading-snug break-words">
{awsErrorMessage(rowError)} {awsErrorMessage(rowError)}
</p> </p>
)} )}
@@ -560,14 +606,14 @@ export default function EnvironmentsPanel({
const nothingFound = !!current && current.environments.length === 0; const nothingFound = !!current && current.environments.length === 0;
return ( return (
<div className="pt-1.5 space-y-2"> <div className="pt-1.5 space-y-2 min-w-0">
<Button size="sm" variant="ghost" aria-expanded={open} onClick={() => setOpen((o) => !o)}> <Button size="sm" variant="ghost" aria-expanded={open} onClick={() => setOpen((o) => !o)}>
<span aria-hidden="true">{open ? "▾" : "▸"}</span> <span aria-hidden="true">{open ? "▾" : "▸"}</span>
Environments Environments
</Button> </Button>
{open && ( {open && (
<div className="space-y-2 pl-1"> <div className="space-y-2 pl-1 min-w-0">
<div className="flex items-end gap-2 flex-wrap"> <div className="flex items-end gap-2 flex-wrap min-w-0" data-testid="region-row">
<Field label="Region"> <Field label="Region">
{(id) => ( {(id) => (
<select id={id} className={selectClass} value={region} onChange={(e) => setRegion(e.target.value)}> <select id={id} className={selectClass} value={region} onChange={(e) => setRegion(e.target.value)}>
@@ -589,11 +635,11 @@ export default function EnvironmentsPanel({
</p> </p>
)} )}
{detectError && ( {detectError && (
<p role="alert" className="text-xs text-[var(--error)] leading-snug"> <p role="alert" className="text-xs text-[var(--error)] leading-snug break-words">
{awsErrorMessage(detectError)} {awsErrorMessage(detectError)}
</p> </p>
)} )}
{current && isAdmin && current.boundary === "no" && ( {current && current.boundary === "no" && (
<p className="text-xs text-[var(--text-secondary)] leading-snug"> <p className="text-xs text-[var(--text-secondary)] leading-snug">
This account has no Triple-C permissions boundary yet; deploying creates it first. This account has no Triple-C permissions boundary yet; deploying creates it first.
</p> </p>
@@ -604,32 +650,54 @@ export default function EnvironmentsPanel({
{nothingFound && ( {nothingFound && (
<p className="text-xs text-[var(--text-secondary)] leading-snug"> <p className="text-xs text-[var(--text-secondary)] leading-snug">
No Triple-C environment in {current.region}. No Triple-C environment in {current.region}.
{!isAdmin && {!tier && " Run Check to see what your credentials can do."}
" Deploying one needs an environment admin: attach the environment-admin policies to an identity, or send an admin a bundle to deploy."}
{!tier && " Run Check to find out whether you can deploy one yourself."}
</p> </p>
)} )}
{current && isAdmin && ( {current && (
<Button <div className="space-y-1.5 min-w-0" data-testid="deploy-section">
size="md" <Button
variant={nothingFound ? "primary" : "secondary"} size="md"
disabled={stale} wrap
onClick={() => setDeployOpen(true)} variant={nothingFound ? "primary" : "secondary"}
> disabled={stale}
Deploy a new environment onClick={() => setDeployOpen(true)}
</Button> >
)} Deploy a new environment
{nothingFound && !isAdmin && (
<div className="space-y-2">
<PolicyFiles tier="environment_admin" label="Show the environment-admin policies" onCopy={copy} />
<Button size="md" disabled={stale} onClick={() => setBundle({ kind: "environment", region: current.region })}>
Request an environment from an admin…
</Button> </Button>
{copyNote && ( {!isAdmin && (
<p role="status" className="text-xs text-[var(--text-secondary)]"> <p className="text-xs text-[var(--text-secondary)] leading-snug break-words" data-testid="deploy-unconfirmed-note">
{copyNote} {UNCONFIRMED_NOTE}
</p> </p>
)} )}
{!isAdmin && (
<details
className="text-xs min-w-0"
data-testid="not-admin-options"
open={notAdminOpen}
onToggle={(ev) => setNotAdminOpen(ev.currentTarget.open)}
>
<summary className="cursor-pointer list-none [&::-webkit-details-marker]:hidden text-[var(--text-primary)] break-words">
<span aria-hidden="true" className="mr-1">{notAdminOpen ? "▾" : "▸"}</span>
Not an admin? Ask one to deploy it
</summary>
<div className="mt-1.5 space-y-2 min-w-0">
<Button
size="sm"
wrap
disabled={stale}
onClick={() => setBundle({ kind: "environment", region: current.region })}
>
Request an environment from an admin…
</Button>
<PolicyFiles tier="environment_admin" label="Show the environment-admin policies" onCopy={copy} />
{copyNote && (
<p role="status" className="text-xs text-[var(--text-secondary)] break-words">
{copyNote}
</p>
)}
</div>
</details>
)}
</div> </div>
)} )}
{looseRuns.map(progress)} {looseRuns.map(progress)}
@@ -649,6 +717,12 @@ export default function EnvironmentsPanel({
repairOf ? repair(current.region, name, network, hours) : deploy(current.region, name, network, hours) repairOf ? repair(current.region, name, network, hours) : deploy(current.region, name, network, hours)
} }
onDetect={() => void detect()} onDetect={() => void detect()}
onBundle={() => {
const at = current.region;
setDeployOpen(false);
setRepairOf(null);
setBundle({ kind: "environment", region: at });
}}
/> />
)} )}
{updateOf && ( {updateOf && (
@@ -667,7 +741,7 @@ export default function EnvironmentsPanel({
confirmLabel="Destroy" confirmLabel="Destroy"
onClose={() => setDestroyOf(null)} onClose={() => setDestroyOf(null)}
onConfirm={() => onConfirm={() =>
launch(destroyOf.region, destroyOf.name, environmentStateKey(destroyOf.name), `Destroy of ${destroyOf.name}`, () => launch(destroyOf.region, destroyOf.name, environmentStateKey(destroyOf.name), "destroy", `Destroy of ${destroyOf.name}`, () =>
destroyIncompleteAwsEnvironment(connection.id, destroyOf.region, destroyOf.name), destroyIncompleteAwsEnvironment(connection.id, destroyOf.region, destroyOf.name),
) )
} }
@@ -718,6 +792,12 @@ export default function EnvironmentsPanel({
reapply={joinOf.reapply} reapply={joinOf.reapply}
incomplete={joinOf.incomplete} incomplete={joinOf.incomplete}
lastChoice={joinOf.lastChoice} lastChoice={joinOf.lastChoice}
confirmedAdmin={isAdmin}
onBundle={() => {
const j = joinOf;
setJoinOf(null);
onboardBundle(j.region, j.name, j.ownerId, j.recorded);
}}
onJoin={(ec2) => runJoin(joinOf, ec2)} onJoin={(ec2) => runJoin(joinOf, ec2)}
onClose={() => setJoinOf(null)} onClose={() => setJoinOf(null)}
/> />
@@ -4,12 +4,13 @@ import type { AwsError, Ec2Choice, Ec2Compute, UserCompute } from "../../../lib/
import Button from "../../ui/Button"; import Button from "../../ui/Button";
import Modal from "../../ui/Modal"; import Modal from "../../ui/Modal";
import Ec2CapacityFields from "./Ec2CapacityFields"; import Ec2CapacityFields from "./Ec2CapacityFields";
import { ec2DraftFrom, ec2FromDraft, type Ec2Draft } from "./environmentFormat"; import { ec2DraftFrom, ec2FromDraft, UNCONFIRMED_NOTE, type Ec2Draft } from "./environmentFormat";
/** /**
* Self-onboarding (environment admins): join an environment, or re-apply an * Self-onboarding: join an environment, or re-apply an onboarding to change
* onboarding to change its EC2 capacity. Starts from the recorded capacity, * its EC2 capacity. Starts from the recorded capacity, so a re-apply keeps it
* so a re-apply keeps it unless changed. * unless changed. Open to anyone: AWS refuses the run when a permission is
* missing, and an onboarding bundle for an admin is the alternative.
*/ */
export default function JoinEnvironmentModal({ export default function JoinEnvironmentModal({
environment, environment,
@@ -18,6 +19,8 @@ export default function JoinEnvironmentModal({
reapply, reapply,
incomplete = false, incomplete = false,
lastChoice = null, lastChoice = null,
confirmedAdmin = true,
onBundle,
onJoin, onJoin,
onClose, onClose,
}: { }: {
@@ -33,6 +36,10 @@ export default function JoinEnvironmentModal({
/** The EC2 capacity last chosen here in this run of the app, if any: /** The EC2 capacity last chosen here in this run of the app, if any:
* the starting point when there is no record. */ * the starting point when there is no record. */
lastChoice?: Ec2Compute | null; lastChoice?: Ec2Compute | null;
/** The permission check confirmed environment-admin rights; otherwise a note says AWS may refuse. */
confirmedAdmin?: boolean;
/** Switch to an onboarding bundle for an admin instead. */
onBundle?: () => void;
/** Starts the run; resolves to the command's error, or null once started. */ /** Starts the run; resolves to the command's error, or null once started. */
onJoin: (ec2: Ec2Choice) => Promise<AwsError | null>; onJoin: (ec2: Ec2Choice) => Promise<AwsError | null>;
onClose: () => void; onClose: () => void;
@@ -73,6 +80,7 @@ export default function JoinEnvironmentModal({
> >
<div className="space-y-3 text-xs text-[var(--text-secondary)] leading-snug"> <div className="space-y-3 text-xs text-[var(--text-secondary)] leading-snug">
{!reapply && <p>Joining creates your own task role and file system in {environment}.</p>} {!reapply && <p>Joining creates your own task role and file system in {environment}.</p>}
{!confirmedAdmin && <p data-testid="join-unconfirmed-note">{UNCONFIRMED_NOTE}</p>}
{recorded && ( {recorded && (
<p>Stop your EC2 workspaces before removing EC2 capacity or changing your triple-c-user value: that change can't finish while one runs.</p> <p>Stop your EC2 workspaces before removing EC2 capacity or changing your triple-c-user value: that change can't finish while one runs.</p>
)} )}
@@ -89,10 +97,22 @@ export default function JoinEnvironmentModal({
</p> </p>
)} )}
{error && ( {error && (
<p role="alert" className="text-[var(--error)]"> <p role="alert" className="text-[var(--error)] break-words">
{awsErrorMessage(error)} {awsErrorMessage(error)}
</p> </p>
)} )}
{onBundle && (
<div className="space-y-1.5 pt-1 border-t border-[var(--border-color)]">
<p>
{error?.kind === "access_denied"
? "AWS refused this with your permissions. An admin can onboard you from a bundle instead."
: "Can't onboard yourself? An admin can onboard you from a bundle."}
</p>
<Button size="sm" wrap onClick={onBundle}>
Save an onboarding bundle for an admin…
</Button>
</div>
)}
</div> </div>
</Modal> </Modal>
); );
@@ -28,6 +28,7 @@ export default function NetworkFields({
<div className="text-[13px] font-medium text-[var(--text-primary)]">Network</div> <div className="text-[13px] font-medium text-[var(--text-primary)]">Network</div>
<SegmentedControl<NetworkChoice["mode"]> <SegmentedControl<NetworkChoice["mode"]>
label="Network" label="Network"
className="flex-wrap max-w-full"
value={value.mode} value={value.mode}
onChange={(mode) => set({ mode })} onChange={(mode) => set({ mode })}
segments={[ segments={[
@@ -28,12 +28,12 @@ export default function PolicyFiles({
if (!files) { if (!files) {
return ( return (
<div className="space-y-1"> <div className="space-y-1 min-w-0">
<Button size="sm" onClick={load}> <Button size="sm" wrap onClick={load}>
{label} {label}
</Button> </Button>
{error && ( {error && (
<p role="alert" className="text-xs text-[var(--error)]"> <p role="alert" className="text-xs text-[var(--error)] break-words">
{error} {error}
</p> </p>
)} )}
@@ -41,30 +41,38 @@ export default function PolicyFiles({
); );
} }
return ( return (
<div className="space-y-1 text-xs"> <div className="space-y-1.5 text-xs min-w-0">
<p className="text-[var(--text-secondary)]"> <p className="text-[var(--text-secondary)] leading-snug break-words">
{tier === "workspace_user" ? "Workspace user" : "Environment admin"}:{" "} {tier === "workspace_user" ? "Workspace user" : "Environment admin"}:{" "}
{files.length === 1 {files.length === 1
? "attach this file as a customer managed policy." ? "attach this file as a customer managed policy."
: `Attach all ${files.length} files, each as its own customer managed policy.`} : `Attach all ${files.length} files, each as its own customer managed policy.`}
</p> </p>
{/* One copy button per file, in a grid that drops to one column when narrow. */}
<div data-testid="policy-copy-grid" className="grid gap-1.5 grid-cols-[repeat(auto-fill,minmax(9rem,1fr))]">
{files.map((f) => (
<Button
key={f.name}
size="sm"
wrap
className="w-full justify-start break-all"
aria-label={`Copy ${f.name}`}
onClick={() => onCopy(f)}
>
Copy <span className="font-mono">{f.name}</span>
</Button>
))}
</div>
{files.map((f) => ( {files.map((f) => (
<div key={f.name} className="space-y-1"> <details key={f.name} className="min-w-0">
<div className="flex items-center gap-2"> <summary className="cursor-pointer text-[var(--text-secondary)] break-all">
<span className="font-mono text-[var(--text-primary)]">{f.name}</span> Show JSON of <span className="font-mono">{f.name}</span>
<Button size="sm" aria-label={`Copy ${f.name}`} onClick={() => onCopy(f)}> </summary>
Copy <pre className="mt-1 max-h-48 max-w-full overflow-auto whitespace-pre-wrap break-all text-[var(--text-secondary)]">
</Button> {f.json}
</div> </pre>
<details> </details>
<summary className="cursor-pointer text-[var(--text-secondary)]">Show JSON</summary>
<pre className="mt-1 max-h-48 overflow-auto whitespace-pre-wrap break-all text-[var(--text-secondary)]">
{f.json}
</pre>
</details>
</div>
))} ))}
</div> </div>
); );
} }
@@ -143,3 +143,7 @@ export function computeLine(c: UserCompute): string {
const n = c.max_instances === 1 ? "1 instance" : `up to ${c.max_instances} instances`; const n = c.max_instances === 1 ? "1 instance" : `up to ${c.max_instances} instances`;
return `${c.instance_type}, ${n} (triple-c-user ${c.user_tag})`; return `${c.instance_type}, ${n} (triple-c-user ${c.user_tag})`;
} }
/** Shown under an action whose permissions the check didn't confirm: AWS has the last word. */
export const UNCONFIRMED_NOTE =
"Your permission check didn't confirm environment-admin rights; the deploy will stop with AWS's message if a permission is missing.";
+19
View File
@@ -74,4 +74,23 @@ describe("Button", () => {
fireEvent.click(button); fireEvent.click(button);
expect(onClick).toHaveBeenCalledTimes(1); expect(onClick).toHaveBeenCalledTimes(1);
}); });
it("wraps a long label only when asked", () => {
render(
<>
<Button>Short</Button>
<Button wrap size="md">
Request an environment from an admin…
</Button>
</>,
);
const plain = screen.getByRole("button", { name: "Short" });
expect(plain.className).toContain("whitespace-nowrap");
expect(plain.className).toContain("h-6");
const long = screen.getByRole("button", { name: "Request an environment from an admin…" });
expect(long.className).toContain("whitespace-normal");
expect(long.className).toContain("min-h-8");
expect(long.className).toContain("max-w-full");
expect(long.className).not.toMatch(/(^|\s)h-8(\s|$)/);
});
}); });
+13 -1
View File
@@ -19,6 +19,11 @@ interface Props extends ButtonHTMLAttributes<HTMLButtonElement> {
unavailable?: boolean; unavailable?: boolean;
/** Why the button cannot be used. Required for `unavailable` to say anything. */ /** Why the button cannot be used. Required for `unavailable` to say anything. */
unavailableReason?: string; unavailableReason?: string;
/**
* Let a long label wrap onto more lines instead of forcing the button (and
* its row) wider than a narrow container, such as the settings sidebar.
*/
wrap?: boolean;
/** React 19 passes `ref` as a prop; it lands on the `<button>` via `rest`. */ /** React 19 passes `ref` as a prop; it lands on the `<button>` via `rest`. */
ref?: Ref<HTMLButtonElement>; ref?: Ref<HTMLButtonElement>;
} }
@@ -48,6 +53,12 @@ const SIZES: Record<ButtonSize, string> = {
md: "h-8 px-3 text-[13px] gap-1.5", md: "h-8 px-3 text-[13px] gap-1.5",
}; };
/** `wrap`: the same sizes as a minimum height, so a second line can grow the button. */
const WRAP_SIZES: Record<ButtonSize, string> = {
sm: "min-h-6 py-0.5 px-2 text-xs gap-1",
md: "min-h-8 py-1 px-3 text-[13px] gap-1.5",
};
export default function Button({ export default function Button({
variant = "secondary", variant = "secondary",
size = "sm", size = "sm",
@@ -55,6 +66,7 @@ export default function Button({
type = "button", type = "button",
unavailable = false, unavailable = false,
unavailableReason = "", unavailableReason = "",
wrap = false,
children, children,
...rest ...rest
}: Props) { }: Props) {
@@ -71,7 +83,7 @@ export default function Button({
type={type} type={type}
{...rest} {...rest}
{...controlProps} {...controlProps}
className={`inline-flex items-center justify-center whitespace-nowrap rounded-[var(--radius-control)] font-medium transition-colors disabled:cursor-not-allowed aria-disabled:cursor-not-allowed ${SIZES[size]} ${VARIANTS[variant]} ${className}`} className={`inline-flex items-center justify-center ${wrap ? `whitespace-normal break-words text-left max-w-full min-w-0 ${WRAP_SIZES[size]}` : `whitespace-nowrap ${SIZES[size]}`} rounded-[var(--radius-control)] font-medium transition-colors disabled:cursor-not-allowed aria-disabled:cursor-not-allowed ${VARIANTS[variant]} ${className}`}
> >
{children} {children}
</button> </button>
+1 -1
View File
@@ -208,7 +208,7 @@ export default function Modal({
</div> </div>
{footer && ( {footer && (
<div className="flex items-center justify-end gap-2 px-5 py-3 border-t border-[var(--border-color)] flex-shrink-0"> <div className="flex flex-wrap items-center justify-end gap-2 px-5 py-3 border-t border-[var(--border-color)] flex-shrink-0">
{footer} {footer}
</div> </div>
)} )}
+4 -1
View File
@@ -53,6 +53,8 @@ interface Props {
iconOnly?: boolean; iconOnly?: boolean;
className?: string; className?: string;
title?: string; title?: string;
/** Let a long label (a failure summary) wrap instead of overflowing its container. */
wrap?: boolean;
} }
export default function StatusIndicator({ export default function StatusIndicator({
@@ -61,11 +63,12 @@ export default function StatusIndicator({
iconOnly = false, iconOnly = false,
className = "", className = "",
title, title,
wrap = false,
}: Props) { }: Props) {
const style = TONES[tone]; const style = TONES[tone];
return ( return (
<span <span
className={`inline-flex items-center gap-1 whitespace-nowrap ${className}`} className={`inline-flex gap-1 ${wrap ? "items-baseline whitespace-normal break-words min-w-0 max-w-full" : "items-center whitespace-nowrap"} ${className}`}
title={title ?? label} title={title ?? label}
> >
<span <span
+13 -7
View File
@@ -2,11 +2,11 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { act, renderHook } from "@testing-library/react"; import { act, renderHook } from "@testing-library/react";
import { useDocker } from "./useDocker"; import { useDocker } from "./useDocker";
const checkDocker = vi.fn(); const getDockerStatus = vi.fn();
const checkImageExists = vi.fn(); const checkImageExists = vi.fn();
vi.mock("../lib/tauri-commands", () => ({ vi.mock("../lib/tauri-commands", () => ({
checkDocker: () => checkDocker(), getDockerStatus: () => getDockerStatus(),
checkImageExists: () => checkImageExists(), checkImageExists: () => checkImageExists(),
buildImage: vi.fn(), buildImage: vi.fn(),
pullImage: vi.fn(), pullImage: vi.fn(),
@@ -15,6 +15,8 @@ vi.mock("../lib/tauri-commands", () => ({
vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => vi.fn()) })); vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => vi.fn()) }));
const setDockerAvailable = vi.fn(); const setDockerAvailable = vi.fn();
const setDockerStatus = vi.fn();
const status = (state: string) => ({ state, endpoint: "unix:///var/run/docker.sock", detail: null, os: "linux" });
const setImageExists = vi.fn(); const setImageExists = vi.fn();
vi.mock("../store/appState", () => ({ vi.mock("../store/appState", () => ({
@@ -22,6 +24,8 @@ vi.mock("../store/appState", () => ({
selector({ selector({
dockerAvailable: false, dockerAvailable: false,
setDockerAvailable, setDockerAvailable,
dockerStatus: null,
setDockerStatus,
imageExists: false, imageExists: false,
setImageExists, setImageExists,
}), }),
@@ -49,7 +53,7 @@ describe("useDocker.startDockerPolling", () => {
}); });
it("runs onAvailable once, after Docker is marked available and the image re-checked", async () => { it("runs onAvailable once, after Docker is marked available and the image re-checked", async () => {
checkDocker.mockResolvedValueOnce(false).mockResolvedValue(true); getDockerStatus.mockResolvedValueOnce(status("not_running")).mockResolvedValue(status("running"));
const onAvailable = vi.fn(); const onAvailable = vi.fn();
const { result } = renderHook(() => useDocker()); const { result } = renderHook(() => useDocker());
@@ -59,9 +63,11 @@ describe("useDocker.startDockerPolling", () => {
await tick(); await tick();
expect(onAvailable).not.toHaveBeenCalled(); expect(onAvailable).not.toHaveBeenCalled();
// The not-running state is published so the dialog can show it live.
expect(setDockerStatus).toHaveBeenLastCalledWith(status("not_running"));
await tick(); await tick();
expect(setDockerAvailable).toHaveBeenCalledWith(true); expect(setDockerStatus).toHaveBeenLastCalledWith(status("running"));
expect(setImageExists).toHaveBeenCalledWith(true); expect(setImageExists).toHaveBeenCalledWith(true);
expect(onAvailable).toHaveBeenCalledTimes(1); expect(onAvailable).toHaveBeenCalledTimes(1);
@@ -71,7 +77,7 @@ describe("useDocker.startDockerPolling", () => {
}); });
it("still works without a callback and can be cancelled by its cleanup", async () => { it("still works without a callback and can be cancelled by its cleanup", async () => {
checkDocker.mockResolvedValue(true); getDockerStatus.mockResolvedValue(status("running"));
const { result } = renderHook(() => useDocker()); const { result } = renderHook(() => useDocker());
let stop: () => void = () => {}; let stop: () => void = () => {};
@@ -81,7 +87,7 @@ describe("useDocker.startDockerPolling", () => {
act(() => stop()); act(() => stop());
await tick(); await tick();
expect(checkDocker).not.toHaveBeenCalled(); expect(getDockerStatus).not.toHaveBeenCalled();
expect(setDockerAvailable).not.toHaveBeenCalled(); expect(setDockerStatus).not.toHaveBeenCalled();
}); });
}); });
+18 -9
View File
@@ -7,12 +7,16 @@ import * as commands from "../lib/tauri-commands";
export function useDocker() { export function useDocker() {
const { const {
dockerAvailable, dockerAvailable,
dockerStatus,
setDockerStatus,
setDockerAvailable, setDockerAvailable,
imageExists, imageExists,
setImageExists, setImageExists,
} = useAppState( } = useAppState(
useShallow(s => ({ useShallow(s => ({
dockerAvailable: s.dockerAvailable, dockerAvailable: s.dockerAvailable,
dockerStatus: s.dockerStatus,
setDockerStatus: s.setDockerStatus,
setDockerAvailable: s.setDockerAvailable, setDockerAvailable: s.setDockerAvailable,
imageExists: s.imageExists, imageExists: s.imageExists,
setImageExists: s.setImageExists, setImageExists: s.setImageExists,
@@ -21,14 +25,14 @@ export function useDocker() {
const checkDocker = useCallback(async () => { const checkDocker = useCallback(async () => {
try { try {
const available = await commands.checkDocker(); const status = await commands.getDockerStatus();
setDockerAvailable(available); setDockerStatus(status);
return available; return status.state === "running";
} catch { } catch {
setDockerAvailable(false); setDockerAvailable(false);
return false; return false;
} }
}, [setDockerAvailable]); }, [setDockerStatus, setDockerAvailable]);
const checkImage = useCallback(async () => { const checkImage = useCallback(async () => {
try { try {
@@ -62,7 +66,9 @@ export function useDocker() {
const pollingRef = useRef<ReturnType<typeof setInterval> | null>(null); const pollingRef = useRef<ReturnType<typeof setInterval> | null>(null);
/** /**
* Poll until Docker appears, then stop. * Poll until Docker appears, then stop. Every tick stores the latest
* `dockerStatus`, so the Docker dialog follows "not running" → "no
* permission" → running live and closes itself.
* *
* `onAvailable` runs exactly once, after `dockerAvailable` is set and the * `onAvailable` runs exactly once, after `dockerAvailable` is set and the
* image has been re-checked. It exists because a session that started before * image has been re-checked. It exists because a session that started before
@@ -75,11 +81,11 @@ export function useDocker() {
const interval = setInterval(async () => { const interval = setInterval(async () => {
try { try {
const available = await commands.checkDocker(); const status = await commands.getDockerStatus();
if (available) { if (status.state === "running") {
clearInterval(interval); clearInterval(interval);
pollingRef.current = null; pollingRef.current = null;
setDockerAvailable(true); setDockerStatus(status);
// Also check image once Docker is available // Also check image once Docker is available
try { try {
const exists = await commands.checkImageExists(); const exists = await commands.checkImageExists();
@@ -92,6 +98,8 @@ export function useDocker() {
} catch (e) { } catch (e) {
console.error("Docker-available callback failed:", e); console.error("Docker-available callback failed:", e);
} }
} else {
setDockerStatus(status);
} }
} catch { } catch {
// Still not available, keep polling // Still not available, keep polling
@@ -103,7 +111,7 @@ export function useDocker() {
clearInterval(interval); clearInterval(interval);
pollingRef.current = null; pollingRef.current = null;
}; };
}, [setDockerAvailable, setImageExists]); }, [setDockerStatus, setImageExists]);
const pullImage = useCallback( const pullImage = useCallback(
async (imageName: string, onProgress?: (msg: string) => void) => { async (imageName: string, onProgress?: (msg: string) => void) => {
@@ -125,6 +133,7 @@ export function useDocker() {
return { return {
dockerAvailable, dockerAvailable,
dockerStatus,
imageExists, imageExists,
checkDocker, checkDocker,
checkImage, checkImage,
+19 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest"; import { describe, it, expect } from "vitest";
import { awsErrorMessage, toAwsError } from "./aws-error"; import { awsErrorMessage, looksDenied, toAwsError } from "./aws-error";
describe("toAwsError", () => { describe("toAwsError", () => {
it("passes a tagged AwsError through", () => { it("passes a tagged AwsError through", () => {
@@ -21,3 +21,21 @@ describe("toAwsError", () => {
expect(toAwsError(null).kind).toBe("other"); expect(toAwsError(null).kind).toBe("other");
}); });
}); });
describe("access denied", () => {
it("shows AWS's message, naming the action when the message doesn't", () => {
expect(awsErrorMessage({ kind: "access_denied", action: "iam:CreateRole", message: "User: x is not authorized" })).toBe(
"AWS denied iam:CreateRole: User: x is not authorized",
);
expect(awsErrorMessage({ kind: "access_denied", action: "s3:PutObject", message: "denied s3:PutObject" })).toBe(
"AWS denied this request: denied s3:PutObject",
);
});
it("recognises refusals in OpenTofu output", () => {
expect(looksDenied("Error: creating IAM Role: AccessDenied: User is not authorized")).toBe(true);
expect(looksDenied("api error UnauthorizedOperation: You are not authorized")).toBe(true);
expect(looksDenied("Error: creating VPC: VpcLimitExceeded")).toBe(false);
expect(looksDenied(null)).toBe(false);
expect(looksDenied("blocked by an explicit deny in a service control policy")).toBe(false);
});
});
+15
View File
@@ -34,7 +34,22 @@ export function awsErrorMessage(e: AwsError): string {
return "The access keys for this connection are missing from the keychain. Remove and re-add the connection."; return "The access keys for this connection are missing from the keychain. Remove and re-add the connection.";
case "state_bucket_taken": case "state_bucket_taken":
return `The state bucket name ${e.bucket} is already taken by another AWS account.`; return `The state bucket name ${e.bucket} is already taken by another AWS account.`;
case "access_denied":
// AWS's own message, named by the action when it doesn't already say it.
return e.action && !e.message.includes(e.action)
? `AWS denied ${e.action}: ${e.message}`
: `AWS denied this request: ${e.message}`;
default: default:
return e.message; return e.message;
} }
} }
// The codes `aws::error` maps to access_denied, and how AWS words a refusal in
// OpenTofu's output. A bare "explicit deny" is left out: an SCP or bucket
// policy deny isn't something an admin bundle fixes.
const DENIED = /AccessDenied|UnauthorizedOperation|not authorized to perform/i;
/** Whether a line of OpenTofu output (or a run's summary) reads as AWS refusing a permission. */
export function looksDenied(text: string | null | undefined): boolean {
return !!text && DENIED.test(text);
}
+15
View File
@@ -0,0 +1,15 @@
import type { DockerStatus } from "./types";
/** Short label for status dots and checklists. */
export function dockerFailLabel(status: DockerStatus | null): string {
switch (status?.state) {
case "not_running":
return "Docker not running";
case "no_permission":
return "Docker access denied";
case "not_installed":
return "Docker not installed";
default:
return "Docker unavailable";
}
}
+2 -1
View File
@@ -1,8 +1,9 @@
import { invoke } from "@tauri-apps/api/core"; import { invoke } from "@tauri-apps/api/core";
import type { Project, ProjectPath, NewProjectHost, RemoveProjectOptions, WipChoice, UnsavedWork, WorkspaceStatus, ProjectRemovalReport, ProjectResetOutcome, ContainerInfo, AppSettings, SettingsImportPreview, SettingsImportOutcome, UpdateInfo, ImageUpdateInfo, FileEntry, FileContents, WebTerminalInfo, SttStatus, GatewayStatus, InstallOptions, ClaudeSession, ContainerCapabilities, ScheduledTask, ScheduledTaskInput, SchedulerNotification, AuthBridgeStatus, BrowserViewStatus, BrowserViewPopoutState, BrowserPageState, PlaywrightDetection, BrowserSetupOutcome, BrowserInstallTarget, ContainerStaleness, MigrationOptions, MigrationReport, MigrationState, ClearTokenOutcome, CaCertInfo, UploadOutcome, Note, ViewerFile, ViewerPoll, ViewerSaved, ViewerState, FileDiff, InstallScope, ItemUpdate, Marketplace, MarketplaceAccount, MarketplaceItemRef, MarketplaceSnapshot, ProjectSyncResult, SyncReport, HostConnection, CallerIdentity, PermissionReport, PolicyFile, HourlyEstimate, AwsWorkspaceConfig, Tier, EnvironmentScan, NetworkChoice, ModuleKind, Ec2Choice, Ec2Compute, Ec2InstanceTable, Ec2Capacity, SavedBundle } from "./types"; import type { Project, ProjectPath, NewProjectHost, RemoveProjectOptions, WipChoice, UnsavedWork, WorkspaceStatus, ProjectRemovalReport, ProjectResetOutcome, ContainerInfo, AppSettings, SettingsImportPreview, SettingsImportOutcome, UpdateInfo, ImageUpdateInfo, FileEntry, FileContents, WebTerminalInfo, SttStatus, GatewayStatus, InstallOptions, DockerStatus, ClaudeSession, ContainerCapabilities, ScheduledTask, ScheduledTaskInput, SchedulerNotification, AuthBridgeStatus, BrowserViewStatus, BrowserViewPopoutState, BrowserPageState, PlaywrightDetection, BrowserSetupOutcome, BrowserInstallTarget, ContainerStaleness, MigrationOptions, MigrationReport, MigrationState, ClearTokenOutcome, CaCertInfo, UploadOutcome, Note, ViewerFile, ViewerPoll, ViewerSaved, ViewerState, FileDiff, InstallScope, ItemUpdate, Marketplace, MarketplaceAccount, MarketplaceItemRef, MarketplaceSnapshot, ProjectSyncResult, SyncReport, HostConnection, CallerIdentity, PermissionReport, PolicyFile, HourlyEstimate, AwsWorkspaceConfig, Tier, EnvironmentScan, NetworkChoice, ModuleKind, Ec2Choice, Ec2Compute, Ec2InstanceTable, Ec2Capacity, SavedBundle } from "./types";
// Docker // Docker
export const checkDocker = () => invoke<boolean>("check_docker"); export const checkDocker = () => invoke<boolean>("check_docker");
export const getDockerStatus = () => invoke<DockerStatus>("check_docker_status");
export const checkImageExists = () => invoke<boolean>("check_image_exists"); export const checkImageExists = () => invoke<boolean>("check_image_exists");
export const buildImage = () => invoke<void>("build_image"); export const buildImage = () => invoke<void>("build_image");
export const getContainerInfo = (projectId: string) => export const getContainerInfo = (projectId: string) =>
+11
View File
@@ -702,6 +702,17 @@ export interface FileContents {
size: number; size: number;
} }
/** Mirrors `docker::status::DockerStatus` (src-tauri/src/docker/status.rs). */
export type DockerState = "running" | "not_running" | "no_permission" | "not_installed";
export interface DockerStatus {
state: DockerState;
/** The endpoint that was tried: `DOCKER_HOST` when set, else the default socket/pipe. */
endpoint: string;
detail: string | null;
os: "linux" | "macos" | "windows" | "unknown";
}
export interface InstallOptions { export interface InstallOptions {
os: "linux" | "macos" | "windows" | "unknown"; os: "linux" | "macos" | "windows" | "unknown";
product_name: string; product_name: string;
+8
View File
@@ -3,6 +3,7 @@ import type {
Project, Project,
TerminalSession, TerminalSession,
AppSettings, AppSettings,
DockerStatus,
UpdateInfo, UpdateInfo,
ImageUpdateInfo, ImageUpdateInfo,
Note, Note,
@@ -243,6 +244,10 @@ interface AppState {
setNotesDockWidth: (width: number) => void; setNotesDockWidth: (width: number) => void;
dockerAvailable: boolean | null; dockerAvailable: boolean | null;
setDockerAvailable: (available: boolean | null) => void; setDockerAvailable: (available: boolean | null) => void;
/** Why Docker is (un)available; `null` until the first check. */
dockerStatus: DockerStatus | null;
/** Sets `dockerStatus` and derives `dockerAvailable` from it. */
setDockerStatus: (status: DockerStatus) => void;
imageExists: boolean | null; imageExists: boolean | null;
setImageExists: (exists: boolean | null) => void; setImageExists: (exists: boolean | null) => void;
// App settings // App settings
@@ -569,6 +574,9 @@ export const useAppState = create<AppState>((set) => ({
}, },
dockerAvailable: null, dockerAvailable: null,
setDockerAvailable: (available) => set({ dockerAvailable: available }), setDockerAvailable: (available) => set({ dockerAvailable: available }),
dockerStatus: null,
setDockerStatus: (status) =>
set({ dockerStatus: status, dockerAvailable: status.state === "running" }),
imageExists: null, imageExists: null,
setImageExists: (exists) => set({ imageExists: exists }), setImageExists: (exists) => set({ imageExists: exists }),
// App settings // App settings