Compare commits

...
Author SHA1 Message Date
shadowdaoandClaude Opus 5.5 ac0bb456d3 fix(aws): persistent terminals review fixes
Secret Scan / scan (push) Successful in 7s
Build App (Preview) / test (pull_request) In progress
Build App (Preview) / compute-version (pull_request) Successful in 12s
Secret Scan / scan (pull_request) Successful in 10s
Build App (Preview) / create-release (pull_request) Successful in 2s
Build App (Preview) / build-macos (pull_request) Successful in 6m50s
Build Container / build-container (pull_request) Successful in 7m27s
Build App (Preview) / build-windows (pull_request) Successful in 15m59s
Build App (Preview) / build-linux (pull_request) Successful in 23m19s
Build App (Preview) / prune-previews (pull_request) Successful in 3s
- Probe is three-state: an unanswered probe is an Err (tab retries), never
  "no tmux" — nothing is pruned or ended on it, opens fail rather than
  silently losing persistence.
- Web terminal execs are web-<key>: a desktop reattach no longer
  supersedes the web exec, nor does a web close/disconnect touch the
  desktop's.
- A tab closed while disconnected is queued (pending_end) and ended at
  the next connect; a reattach of a closed/queued id is Ended and is not
  remembered again.
- Cost ruling documented: a detached Claude keeps the workspace up
  (HostSection note, Sessions flags detached Claude sessions).
- end_all waits for pane pids; the same script runs in the entrypoint's
  TERM hook and before the idle watcher's lifetime-cap push.
- TMUX/TMUX_TMPDIR dropped from the client env and reserved.
- Store cleared on a move to Docker and on a death-watch stop.
- Frontend: no duplicate reopen of a tab still opening; quick-exit
  backoff then stop; the replay is exactly one chunk, so live output
  keeps its URL/OSC/SSO handling.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:09:09 -08:00
shadowdaoandClaude Opus 5.5 9211d06cef docs: persistent AWS terminals in CLAUDE.md
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:09:09 -08:00
shadowdaoandClaude Opus 5.5 5284a527fb feat(ui): reopen and reattach persistent AWS terminals
- A tab on a persistent terminal reattaches when its connection drops
  (retrying while the tunnel comes back, "[Session ended]" only when the
  workspace says it is gone, or the project stopped); closing a tab ends it.
- usePersistentTerminals: once per AWS connection (project id + endpoint)
  the terminals this app opened that still run are reopened as tabs, in
  order, without taking focus; a reopened tab attaches only after its
  listeners are up, so its replayed history and tmux's first draw land.
- Project Home -> Sessions lists the workspace's terminals (open here,
  detached, attached elsewhere, opened elsewhere) with Reattach and End.
- The one-time "no tmux in this image" notice is a toast.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:09:09 -08:00
shadowdaoandClaude Opus 5.5 ce0198203a fix(container): keep a persistent terminal's last screen when it exits
tmux sends terminfo's clear when its client exits; without an alternate
screen that wiped Claude's or the shell's last output from the tab.
clear=\E[H keeps it. Checked by feeding tmux's real output into xterm.js:
bash clear, ED 2, a curses alternate screen, a re-attach over an old
screen and Claude Code's TUI all match tmux's own view of the pane, and
300 fast lines all reach the scrollback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:09:09 -08:00
shadowdaoandClaude Opus 5.5 21bd7f5347 feat(aws): terminals outlive the app in tmux and reattach on connect
On an AWS project whose image has tmux and /etc/triple-c/tmux.conf, each
tab (Claude and bash, desktop and web terminal) runs its unchanged
command inside its own tmux server, tmux -L triple-c-<session id>, so the
server inherits only that exec's environment (copy-at-connect pairs stay
off argv). App exit, a dropped tunnel and the agent's SIGHUP only detach;
closing a tab ends the session (kill-server).

- host/persistent.rs: command construction, probe cached per tunnel
  (forgotten when a tunnel registers), list/history/end/end_all, replay.
- storage/terminal_store.rs: per-project open terminals (id = tmux key,
  kind, label) in terminal-sessions.json; pruned by the workspace listing,
  cleared on Stop and Remove.
- New commands list_workspace_terminals, reattach_terminal_session
  (attach-session, never creates; optional history replay),
  end_workspace_terminal; open_terminal_session returns
  {persistent, notice} (one-time no-tmux notice).
- Stop ends every tmux server in the step that closes the terminals,
  before the WIP push's snapshot.
- ExecSessionManager: an exec that takes a session id over ends the old
  one without its exit callback.
- Ignored live test through the real agent (host::persistent::live_tests).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:09:09 -08:00
shadowdaoandClaude Opus 5.5 7951da008e feat(container): tmux and its config for persistent AWS terminals
tmux rides the Python apt layer (the last, cheapest one) and
/etc/triple-c/tmux.conf (outside the seed-only home) makes it invisible
behind xterm.js: no prefix, no status line, escape-time 0, truecolor,
OSC 8/52, and smcup@/rmcup@/indn@ so output lands in xterm.js's own
scrollback (xterm.js's CSI S drops lines instead of keeping them).

The entrypoint's TERM hook ends the app's tmux servers before its own
WIP push, so nothing writes after the push's snapshot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:09:09 -08:00
jknapp 8359135432 Merge pull request 'Test-feedback fixes: hosts settings layout, deploy/join for anyone, Docker status, bundled SSM plugin' (#86) from fix/hosts-ui into main
Secret Scan / scan (push) Successful in 25s
2026-11-17 23:08:56 +00:00
shadowdaoandClaude Opus 5.5 42c329ed24 fix(ports): keep typed port mappings; never save or skip a half-filled row silently
Secret Scan / scan (push) Successful in 31s
Secret Scan / scan (pull_request) Successful in 12s
Build App (Preview) / compute-version (pull_request) Successful in 5s
Build App (Preview) / create-release (pull_request) Successful in 3s
Build App (Preview) / test (pull_request) Successful in 8m21s
Build App (Preview) / build-macos (pull_request) Successful in 7m2s
Build App (Preview) / build-windows (pull_request) Successful in 14m4s
Build App (Preview) / build-linux (pull_request) Successful in 13m16s
Build App (Preview) / prune-previews (pull_request) Successful in 5s
The empty row's "8080" placeholders looked like a typed 8080 -> 8080, and
+ Add saved it as 0 -> 0 at once; a project refresh with a new-but-equal
array also reset in-progress edits. The editor now keeps ports as text,
saves only complete rows, marks incomplete ones inline, uses word
placeholders, and resyncs only on a by-value change while unfocused. A
connect reports a stored incomplete row as a ports warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 14:37:37 -08:00
shadowdaoandClaude Opus 5.5 ff872f34a1 fix(aws): port mappings reach [::1]-only servers, never fail silently; clearer silent-agent error
Secret Scan / scan (push) Successful in 13s
Build App (Preview) / compute-version (pull_request) Successful in 8s
Secret Scan / scan (pull_request) Successful in 9s
Build App (Preview) / create-release (pull_request) Successful in 12s
Build App (Preview) / build-macos (pull_request) Successful in 7m30s
Build App (Preview) / test (pull_request) Successful in 11m4s
Build App (Preview) / build-windows (pull_request) Successful in 14m12s
Build App (Preview) / build-linux (pull_request) Successful in 15m52s
Build App (Preview) / prune-previews (pull_request) Successful in 5s
Port mappings (AWS):
- In the workspace each connection now picks 127.0.0.1 or [::1] from
  /proc/net/tcp{,6} (tunnel::mapping_command): a server bound to ::1 only
  (Vite, Node `localhost`) was unreachable through a mapping. No probe
  connection is made; nothing found falls back to 127.0.0.1.
- The first socat "Connection refused" per mapping is a `ports`
  workspace-warning: "nothing is listening on port N in the workspace
  (127.0.0.1 or ::1)".
- open_for_project warns instead of returning None when a Running project's
  mappings can't be opened (no tunnel, or the tunnel changed under the open).
- Info/warn logs at each step (mappings read, each opened/failed, set closed
  and why) so the next report shows where it stopped.
- Tests: start-path sequence (mapping saved while stopped, tunnel, Running,
  open) with IPv4 and ::1 clients; refusal reported once; never-silent cases;
  an ignored live test against a real agent container (0.0.0.0, [::1] and
  nothing-listening servers).

Silent agent: the error now says the image (named, escaped) may predate the
app's AWS support, that :latest moves only on a release, and to set
Settings → Docker → Custom image to ghcr.io/shadowdao/triple-c-sandbox:edge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 14:22:28 -08:00
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
shadowdaoandClaude Opus 5.5 614e89bef4 fix(ssm-plugin): lock down the Windows work root; re-hash the output in place
Secret Scan / scan (push) Successful in 14s
Build App (Preview) / compute-version (pull_request) Successful in 14s
Secret Scan / scan (pull_request) Successful in 7s
Build App (Preview) / test (pull_request) Successful in 9m25s
Build App (Preview) / create-release (pull_request) Successful in 1s
Build App (Preview) / build-macos (pull_request) Successful in 6m40s
Build App (Preview) / build-linux (pull_request) Successful in 17m3s
Build App (Preview) / build-windows (pull_request) Successful in 13m53s
Build App (Preview) / prune-previews (pull_request) Successful in 2s
The short %SystemDrive%\ssm-<8hex> root inherited the drive root's ACL,
where Authenticated Users can write, so another local user could swap the
source, toolchain or output between verification and use. Right after
creating it, icacls removes inheritance and grants full control only to
SYSTEM, Administrators and the current user's SID; failure aborts. It is
mandatory on Windows and skipped only off Windows (the pwsh test path).
The binary is hashed again at its final location.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 08:21:55 -08:00
shadowdaoandClaude Opus 5.5 b62f472d79 fix(ssm-plugin): review fixes for the source build and signing checks
Secret Scan / scan (push) Successful in 11s
Build App (Preview) / compute-version (pull_request) Successful in 11s
Secret Scan / scan (pull_request) Successful in 12s
Build App (Preview) / create-release (pull_request) Successful in 1s
Build App (Preview) / build-macos (pull_request) Successful in 6m42s
Build App (Preview) / test (pull_request) Successful in 15m11s
Build App (Preview) / build-linux (pull_request) Successful in 13m45s
Build App (Preview) / build-windows (pull_request) Successful in 13m59s
Build App (Preview) / prune-previews (pull_request) Successful in 2s
- build-ssm-plugin.{sh,ps1}: skip the vendored SDK's Java codegen/ and
  test snapshot/ trees when extracting (codegen paths reach 258 chars,
  past MAX_PATH on Windows); the .ps1 works under a short
  %SystemDrive%\ssm-<8hex> root and falls back to rd /s /q on cleanup.
  Pinned output hashes unchanged (rebuilt every target).
- build-ssm-plugin.sh: the header no longer claims a git commit-id check.
- windows-verify-signatures.ps1: compare signer Subject + Issuer, not the
  thumbprint (Artifact Signing certificates rotate); require
  THIRD_PARTY_NOTICES in the MSI.
- windows-sign.ps1: allowlist exactly
  src-tauri\binaries\session-manager-plugin-x86_64-pc-windows-msvc.exe.
- macOS jobs: check the .app carries the two-slice plugin and
  Contents/Resources/THIRD_PARTY_NOTICES.
- CLAUDE.md: a local release build must re-run the build script.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 08:20:09 -08:00
shadowdaoandClaude Opus 5.5 5b23dc1aec build: build session-manager-plugin from source, not AWS's binaries
Build App (Preview) / compute-version (pull_request) Successful in 5s
Secret Scan / scan (push) Successful in 8s
Secret Scan / scan (pull_request) Successful in 7s
Build App (Preview) / create-release (pull_request) Successful in 2s
Build App (Preview) / build-macos (pull_request) Successful in 6m42s
Build App (Preview) / build-linux (pull_request) Successful in 12m41s
Build App (Preview) / build-windows (pull_request) Successful in 13m57s
Build App (Preview) / test (pull_request) Successful in 23m29s
Build App (Preview) / prune-previews (pull_request) Successful in 3s
AWS ships its prebuilt plugin as "AWS Content" under the AWS Customer
Agreement; the source is Apache-2.0. Replace the binary fetch with
scripts/build-ssm-plugin.sh (any triple, cross-compiles; universal via
lipo) and build-ssm-plugin.ps1 (Windows runner):

- source: tag 1.2.896.0 at commit 6430675a, GitHub archive SHA-256
  checked before extraction;
- Go 1.26.11 from go.dev, published SHA-256 checked before use;
- the repo's own build (GOPATH mode, vendored deps, -s -w,
  sessionmanagerplugin-main) with VERSION stamped to the tag, plus
  -trimpath, no VCS stamp, empty build id, CGO off;
- output must equal a pinned SHA-256 per target (reproducible builds).

Each platform job builds its own targets. Windows: the exe is now ours
and unsigned, so windows-sign.ps1 allowlists it and
windows-verify-signatures.ps1 requires it signed by the installer's own
certificate in the MSI and NSIS. THIRD_PARTY_NOTICES now carries the
source's LICENSE/NOTICE/THIRD-PARTY, the commit, every linked vendored
module's licence and Go's. AWS's GPG key and the AWS-signature checks
are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 08:12:11 -08:00
shadowdaoandClaude Opus 5.5 381158cca0 docs: the bundled AWS session-manager-plugin
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 06:44:30 -08:00
shadowdaoandClaude Opus 5.5 cb28d1da39 ci: fetch the SSM plugin before every build; check it ships
Both build workflows fetch the pinned plugin before tauri build on Linux,
macOS (universal: both slices plus the lipo'd file) and Windows. The test
job needs no fetch: debug builds get build.rs's placeholder.

finalize-appimage.sh asserts usr/bin/session-manager-plugin is a running
ELF and THIRD_PARTY_NOTICES is in the image.

Windows: the plugin ships under AWS's Authenticode signature and is not
re-signed (Tauri skips a sidecar signtool verify accepts).
windows-sign.ps1 refuses it if it is ever presented rather than letting the
allowlist skip it unsigned; windows-verify-signatures.ps1 requires it in
the MSI, valid, timestamped and signed by Amazon Web Services, Inc.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 06:44:30 -08:00
shadowdaoandClaude Opus 5.5 39f502dcdf feat(ssm): bundle session-manager-plugin as a sidecar and prefer it
bundle.externalBin ships the plugin beside the app binary (usr/bin in the
AppImage, Contents/MacOS, the Windows install dir) and THIRD_PARTY_NOTICES as
a resource. find_plugin() now resolves TRIPLEC_SSM_PLUGIN, then the bundled
sidecar next to current_exe(), then PATH and AWS's install locations, then
the install hint; the order is unit-tested against temp dirs.

tauri-build fails any build whose externalBin file is missing, so build.rs
writes a marked placeholder in debug builds (cargo test/check, tauri dev)
and refuses a missing file or a placeholder in release builds.
find_plugin() skips the placeholder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 06:43:41 -08:00
shadowdaoandClaude Opus 5.5 05ac6b3e8c build: fetch a pinned, verified AWS session-manager-plugin
scripts/fetch-ssm-plugin.sh (Linux/macOS, incl. universal via lipo) and
scripts/fetch-ssm-plugin.ps1 (Windows) download plugin 1.2.896.0 from AWS's
S3 path into app/src-tauri/binaries/session-manager-plugin-<triple>[.exe],
checking a pinned SHA-256 of each artifact before extraction, AWS's GPG
signature on the Linux .deb (key committed, fingerprint pinned) or AWS's
Authenticode signature on Windows, and a pinned SHA-256 of the binary.

THIRD_PARTY_NOTICES reproduces the plugin's LICENSE (Apache-2.0), NOTICE
and AWS's THIRD-PARTY statement. The binaries directory is never committed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 06:43:41 -08:00
jknapp fe7c474070 Merge pull request 'AWS host phase 7: ECS on EC2 (per-user capacity, Docker access, VPN)' (#84) from feat/aws-ec2 into main
Secret Scan / scan (push) Successful in 7s
Build Container / build-container (push) Successful in 1m9s
2026-11-17 14:28:45 +00:00
95 changed files with 7182 additions and 403 deletions

No files matched your search

+42 -1
View File
@@ -334,7 +334,9 @@ jobs:
run: npx vitest run
# `--locked`: test against the committed Cargo.lock, never a re-resolved
# one, for the same reason the frontend uses `npm ci`.
# one, for the same reason the frontend uses `npm ci`. No plugin fetch
# here: a debug build gets a placeholder for the session-manager-plugin
# sidecar from build.rs, so tests never build Go or download anything.
- name: Backend tests (cargo test)
working-directory: ./app/src-tauri
run: |
@@ -468,6 +470,14 @@ jobs:
export PATH="$HOME/.cargo/bin:$PATH"
npx tauri --version || npm install @tauri-apps/cli
# The AWS Session Manager plugin, bundled as a sidecar (bundle.externalBin)
# so AWS workspaces work without the user installing it. Built here from
# AWS's Apache-2.0 source (pinned commit + archive SHA-256) with a pinned,
# hash-checked Go; the output must match a pinned SHA-256 (reproducible
# build). A release build refuses to start without it (build.rs).
- name: Build the AWS Session Manager plugin
run: bash scripts/build-ssm-plugin.sh x86_64-unknown-linux-gnu
- name: Build Tauri app
working-directory: ./app
env:
@@ -597,6 +607,15 @@ jobs:
export PATH="$HOME/.cargo/bin:$PATH"
npx tauri --version || npm install @tauri-apps/cli
# The AWS Session Manager plugin sidecar (bundle.externalBin), built from
# source (see build-ssm-plugin.sh): both thin slices (tauri-build checks
# each arch it compiles) and the lipo'd universal one the bundler copies
# into Contents/MacOS. Each must match its pinned SHA-256. Signed exactly
# like the app: Go ad-hoc signs the arm64 slice, and with APPLE_* signing
# configured Tauri would sign the sidecar with the app's identity.
- name: Build the AWS Session Manager plugin
run: bash scripts/build-ssm-plugin.sh universal-apple-darwin
- name: Build Tauri app (universal)
working-directory: ./app
env:
@@ -606,6 +625,21 @@ jobs:
export PATH="$HOME/.cargo/bin:$PATH"
npx tauri build --target universal-apple-darwin
# The sidecar and its notices must be in the bundle Tauri made: the
# plugin in Contents/MacOS with both slices, THIRD_PARTY_NOTICES in
# Contents/Resources (bundle.resources).
- name: Check the bundled Session Manager plugin
run: |
app_dir="$(ls -d app/src-tauri/target/universal-apple-darwin/release/bundle/macos/*.app | head -n1)"
[ -n "$app_dir" ] || { echo "no .app bundle"; exit 1; }
plugin="$app_dir/Contents/MacOS/session-manager-plugin"
[ -x "$plugin" ] || { echo "missing $plugin"; exit 1; }
archs="$(lipo -archs "$plugin")"
case " $archs " in *" x86_64 "*) ;; *) echo "plugin lacks x86_64 ($archs)"; exit 1 ;; esac
case " $archs " in *" arm64 "*) ;; *) echo "plugin lacks arm64 ($archs)"; exit 1 ;; esac
"$plugin" --version
[ -f "$app_dir/Contents/Resources/THIRD_PARTY_NOTICES" ] || { echo "missing Contents/Resources/THIRD_PARTY_NOTICES"; exit 1; }
- name: Collect artifacts
run: |
mkdir -p artifacts
@@ -729,6 +763,13 @@ jobs:
set "PATH=%USERPROFILE%\.cargo\bin;C:\Program Files\nodejs;%PATH%"
npm run build
# The AWS Session Manager plugin sidecar (bundle.externalBin), built from
# source (see build-ssm-plugin.ps1); must match its pinned SHA-256. It
# comes out unsigned, so it ships unsigned in previews, like the
# app (releases sign it: see build-app.yml).
- name: Build the AWS Session Manager plugin
run: powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File scripts\build-ssm-plugin.ps1
- name: Build Tauri app
working-directory: ./app
# Previews are not code-signed: signing is metered, previews are built
+39
View File
@@ -227,6 +227,14 @@ jobs:
export PATH="$HOME/.cargo/bin:$PATH"
npx tauri --version || npm install @tauri-apps/cli
# The AWS Session Manager plugin, bundled as a sidecar (bundle.externalBin)
# so AWS workspaces work without the user installing it. Built here from
# AWS's Apache-2.0 source (pinned commit + archive SHA-256) with a pinned,
# hash-checked Go; the output must match a pinned SHA-256 (reproducible
# build). A release build refuses to start without it (build.rs).
- name: Build the AWS Session Manager plugin
run: bash scripts/build-ssm-plugin.sh x86_64-unknown-linux-gnu
- name: Build Tauri app
working-directory: ./app
run: |
@@ -417,12 +425,36 @@ jobs:
export PATH="$HOME/.cargo/bin:$PATH"
npx tauri --version || npm install @tauri-apps/cli
# The AWS Session Manager plugin sidecar (bundle.externalBin), built from
# source (see build-ssm-plugin.sh): both thin slices (tauri-build checks
# each arch it compiles) and the lipo'd universal one the bundler copies
# into Contents/MacOS. Each must match its pinned SHA-256. Signed exactly
# like the app: Go ad-hoc signs the arm64 slice, and with APPLE_* signing
# configured Tauri would sign the sidecar with the app's identity.
- name: Build the AWS Session Manager plugin
run: bash scripts/build-ssm-plugin.sh universal-apple-darwin
- name: Build Tauri app (universal)
working-directory: ./app
run: |
export PATH="$HOME/.cargo/bin:$PATH"
npx tauri build --target universal-apple-darwin
# The sidecar and its notices must be in the bundle Tauri made: the
# plugin in Contents/MacOS with both slices, THIRD_PARTY_NOTICES in
# Contents/Resources (bundle.resources).
- name: Check the bundled Session Manager plugin
run: |
app_dir="$(ls -d app/src-tauri/target/universal-apple-darwin/release/bundle/macos/*.app | head -n1)"
[ -n "$app_dir" ] || { echo "no .app bundle"; exit 1; }
plugin="$app_dir/Contents/MacOS/session-manager-plugin"
[ -x "$plugin" ] || { echo "missing $plugin"; exit 1; }
archs="$(lipo -archs "$plugin")"
case " $archs " in *" x86_64 "*) ;; *) echo "plugin lacks x86_64 ($archs)"; exit 1 ;; esac
case " $archs " in *" arm64 "*) ;; *) echo "plugin lacks arm64 ($archs)"; exit 1 ;; esac
"$plugin" --version
[ -f "$app_dir/Contents/Resources/THIRD_PARTY_NOTICES" ] || { echo "missing Contents/Resources/THIRD_PARTY_NOTICES"; exit 1; }
- name: Collect artifacts
run: |
mkdir -p artifacts
@@ -656,6 +688,13 @@ jobs:
set "PATH=%USERPROFILE%\.cargo\bin;C:\Program Files\nodejs;%PATH%"
npm run build
# The AWS Session Manager plugin sidecar (bundle.externalBin), built from
# source (see build-ssm-plugin.ps1); must match its pinned SHA-256. It
# comes out unsigned, so Tauri hands it to the sign command and
# "Verify signatures" requires our signature on it in both installers.
- name: Build the AWS Session Manager plugin
run: powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File scripts\build-ssm-plugin.ps1
# Releases are signed with Azure Artifact Signing (scripts/windows-*.ps1).
# The setup fetches the signing client and a job-local .NET runtime, and
# writes the Tauri config holding the sign command, which "Build Tauri
+4
View File
@@ -27,3 +27,7 @@ screenshot_for_fix/
*.tfstate
*.tfstate.*
.terraform.tfstate.lock.info
# The bundled AWS session-manager-plugin sidecar (scripts/build-ssm-plugin.*, built from source) and the
# debug-build placeholder build.rs writes there. Never committed.
app/src-tauri/binaries/
+152 -7
View File
@@ -14,7 +14,8 @@ All frontend/tauri commands run from the `app/` directory:
cd app
npm ci # Install dependencies (required first time)
npx tauri dev # Launch app in dev mode with hot reload (Vite on port 1420)
npx tauri build # Production build (outputs to src-tauri/target/release/bundle/)
npx tauri build # Production build (outputs to src-tauri/target/release/bundle/);
# run ../scripts/build-ssm-plugin.sh first (bundled AWS plugin, see Packaging)
npm run build # Frontend-only build (tsc + vite)
npm run test # Run Vitest once
npm run test:watch # Run Vitest in watch mode
@@ -309,8 +310,69 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li
that would be refused is skipped with a warning at connect. Opens are serialised per project and
re-read the stored mappings under that lock; unchanged forwards are kept with their connections.
Opened after every connect and on a save while connected; closed by every `tunnels::close*`
path. A failing mapping is a `workspace-warning` (`topic: "ports"`). An idle listener makes no
path. A failing mapping is a `workspace-warning` (`topic: "ports"`), and so is a Running project
whose mappings could not be opened at all (no tunnel / tunnel replaced) — never silent; a stored
row missing a port (0) is skipped with one too ("incomplete, both ports are needed").
`PortMappingsEditor` saves only complete rows (half-filled ones stay local, marked), adopts a
stored value only when it differs by value and no field in it has focus, and uses word
placeholders — a "8080" placeholder once read as a typed 8080 → 8080 that was saved as 0 → 0. In the
workspace each connection picks `127.0.0.1` or `[::1]` from `/proc/net/tcp{,6}`
(`tunnel::mapping_command`; no probe connection), and the first socat "Connection refused" per
mapping is a `ports` warning ("nothing is listening on port N"). An idle listener makes no
agent request; a connection carrying traffic is activity (keeps the workspace from idling).
**`persistent.rs` is persistent AWS terminals** (Docker projects never reach it): every tab on an
AWS project — Claude and bash, desktop and web terminal — runs its **unchanged** launch command
(update prelude and all, or `bash -l`) inside **its own tmux server**,
`tmux -L triple-c-<session id> -f /etc/triple-c/tmux.conf new-session -A -s <claude|bash> -- <cmd>`.
Rules, each for a reason:
- **One server per tab, never one shared server**: a server takes its environment from the
client that started it, so each tab keeps exactly its own `ExecSpec.env` (copy-at-connect
`terminal_env` pairs). Never `new-session -e` — that puts the values on argv (`ps`). A later
connect's new credentials do not reach a session already running (like any running process).
The client gets `TERM=xterm-256color` (the agent would default a tty to `xterm`, 8 colours).
- **The tab's session id is the tmux key** (validated `[A-Za-z0-9-]{1,64}`), remembered per
project in `storage/terminal_store.rs` (`terminal-sessions.json` beside `projects.json`; a
hint pruned by the workspace's own listing, cleared on Stop/Remove; not a `Project` field, for
the reason notes aren't). Same id after a restart, so `renamed_session_names` still applies.
- **Closing a tab ends the session** (`kill-server`); app exit, a dropped tunnel and the agent's
SIGHUP on a vanished client only **detach** (the server daemonised out of the client's
process group). **Reattach is `attach-session`, never `new-session -A`**: a session that
ended while the app was away must not come back as a fresh `claude` (and the update prelude
runs once, inside, never again on reattach).
- **Stop ends every tmux server** (`persistent::END_ALL_SCRIPT`: the panes' pids are taken
before `kill-server`, then a bounded 5 s wait for them and the servers) in the same
`close_first` step that closes the tabs, **before** the stop guard's push snapshot. The
entrypoint's TERM hook (`aws_end_terminals`) and the idle watcher's lifetime-cap push run the
same script verbatim (a test pins all three). The store is cleared on Stop, Remove, a move to
Docker and a death-watch stop.
- **The probe** (`command -v tmux` + the config) runs once per tunnel, cached by target id and
forgotten in `tunnels::register*`, and is **three-state**: yes → persistent; a real no (an
image without tmux) → the old launch plus a one-time notice; **unanswered → `Err`**, never
"no" — read as no, a listing would prune every remembered tab and a reattach would end tabs
whose Claude still runs. Nothing is pruned or ended on an `Err`; the frontend asks again.
Every tmux exec except the attach goes through `exec_oneshot_background` (never idle-stop
activity). `TMUX`/`TMUX_TMPDIR` are dropped from the client env and reserved custom names.
- **A tab closed while disconnected** is queued (`terminal_store` `pending_end`) and ended at the
next connect (`list_workspace_terminals` runs it first); a reattach of a closed or queued id
is `Ended`, and a reattach that finishes after its tab closed does not remember it again.
- **The web terminal's exec ids are `web-<tmux key>`**, never the bare key the desktop uses:
sharing one `ExecSessionManager` id would let either front end's attach supersede the
other's exec (no exit callback, a frozen tab) or its close/disconnect end the other's.
- **Cost, by ruling:** a detached `claude` still counts for the idle watcher — that *is* the
feature (remote control keeps working with the app closed) — so a Claude left running keeps
the workspace up and billed until it ends, it is ended (Project Home → Sessions flags
detached Claude sessions, with End), Stop, or the lifetime cap. HostSection's notes say so
(`PERSISTENT_TERMINALS_NOTE`). A detached shell does not keep it up.
- Frontend: a persistent tab reattaches on exit (retrying while the tunnel comes back) and shows
"[Session ended]" only when the workspace says the session is gone or the project stopped;
`usePersistentTerminals` reopens this app's sessions once per connection (`id|container_id`)
without taking focus; a reopened tab calls `reattach_terminal_session` only after its output
*and* exit listeners are registered (history replay + tmux's first draw would be lost). Project
Home → Sessions lists every session in the workspace (web terminal and other machines too:
those are never auto-opened) with Reattach / End. `ExecSessionManager` ends an exec whose
session id was taken over without its exit callback (else a reattach loops on its own exit).
- The live check is `host::persistent::live_tests` (ignored; an agent image with tmux,
`TRIPLEC_PERSIST_E2E_IMAGE`).
`agent.rs` reuses `docker/exec.rs`'s `OneshotOutput`, host-file reader and uid probe so the two
variants cannot drift; an `Agent` target's token never appears in `Debug` or error text.
**Container-interior code must go through `ContainerTarget`, never `docker::exec`, bollard or
@@ -562,6 +624,18 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li
The re-clone closes the apply lock's fd (a later connect never waits for it); `--prepare` takes it.
The functions both scripts use live in `container/entrypoint-lib.sh`
(`/usr/local/lib/triple-c/`), sourced by the entrypoint first; it only defines things.
**Persistent terminals** (`host/persistent.rs`): the image has `tmux` (in the Python apt layer)
and `/etc/triple-c/tmux.conf` (`container/triple-c-tmux.conf`, outside the seed-only home): no
prefix key (Ctrl+B reaches Claude/readline), no status line, `escape-time 0` (ESC+CR stays one
Meta-Enter), no mouse, `window-size latest`, and three outer-terminal overrides that were each
**measured by feeding tmux's real output into xterm.js** — keep all three: `smcup@:rmcup@`
(draw in xterm.js's normal screen, so its scrollback, copy cleanup and link detection work),
`indn@` (tmux's CSI S scroll is a *delete* in xterm.js: 4 of 300 fast lines reached scrollback
with it, 300 without) and `clear=\E[H` (tmux sends `clear` when its client exits, which wiped
the session's last screen from the tab; its full redraws repaint every row anyway). The idle
watcher still sees `claude` inside tmux (`pgrep -x claude`; tmux's processes are `tmux:
server`/`tmux: client`), so a running Claude keeps the workspace up and a detached shell does
not; the lifetime cap still applies.
**The Docker-socket group step** (`# >>> docker_socket`) runs in aws mode as well as Docker mode: an
EC2 project with Docker access mounts the instance's `/var/run/docker.sock`, and the step adds
`claude` to a group with the socket's gid (`docker-host` if none exists). Fargate never has the
@@ -758,7 +832,10 @@ friendly message one line before `exec claude` ran it. `-E 0` makes losing the r
because the holder just did the work. The per-session copy is what forced the non-Bedrock path from a bare `["claude", ...]`
argv into a `bash -c` wrapper — the flags and the session name are interpolated into a shell
string now, so **anything added there must go through `shell_quote_arg`**. Bash sessions are
deliberately untouched.
deliberately untouched. On AWS that whole command (not a copy of it) becomes the argv of a tmux
`new-session` (`host::persistent::new_session_cmd`), so it runs once per session, never on a
reattach; tmux reads an argument that *ends* in `;` as a command separator, so the scripts keep
ending in a newline (`new_session_cmd` refuses otherwise).
### Container Lifecycle
@@ -1225,10 +1302,77 @@ verbatim copy yields a launcher entry that starts nothing. It keeps `StartupWMCl
the bundle sets it, which is what lets the shell match the window to the entry. Extraction uses
`--appimage-extract`, which needs no FUSE, so the script works before `fuse2` is installed.
### The bundled AWS Session Manager plugin
AWS workspaces connect through AWS's `session-manager-plugin` (`host/ssm.rs`), and the app
**bundles it as a Tauri sidecar** (`bundle.externalBin: binaries/session-manager-plugin`) so users
need not install it. Tauri copies it beside the app binary with the `-<target-triple>` suffix
stripped — `usr/bin/session-manager-plugin` in the AppImage, `Contents/MacOS/` on macOS, the
install directory on Windows (`session-manager-plugin.exe`), and `target/<profile>/` under
`tauri dev`. `find_plugin()` resolves `TRIPLEC_SSM_PLUGIN` → **that sidecar (beside
`current_exe()`)** → `PATH` → AWS's install locations → the install hint; the order is
unit-tested (`host/ssm/tests.rs`, `plugin_resolution`).
- **We build it from source; we never ship AWS's binaries.** AWS distributes its prebuilt plugin
as "AWS Content" under the AWS Customer Agreement; the source (github.com/aws/session-manager-plugin)
is Apache-2.0. `scripts/build-ssm-plugin.sh <triple>…` (Linux/macOS; any triple, it
cross-compiles) and `scripts/build-ssm-plugin.ps1` (the Windows runner, which has no bash) take
the tag's **commit** as GitHub's archive (pinned SHA-256, checked before extraction; the
vendored SDK's Java `codegen/` and test `snapshot/` trees are not extracted — they reach 258
characters, past Windows' MAX_PATH, so the `.ps1` also works under a short `C:\ssm-<8hex>` root)
and a
**pinned Go** from go.dev (go.dev's published SHA-256), and run the repo's own build — GOPATH
mode over its vendored deps, `-ldflags "-s -w"`, `sessionmanagerplugin-main` — with `VERSION`
stamped to the tag (the repo's file says `1.3.0.0`; AWS's pipeline stamps the real one, so
`--version` would otherwise lie), plus `-trimpath`, no VCS stamp, empty build id, `CGO_ENABLED=0`
and a scrubbed Go environment. **The output must equal a pinned SHA-256 per target**: Go builds
are reproducible across hosts, so every runner must produce the exact bytes recorded in the
scripts (verified locally: Linux-hosted builds of every target, repeated in fresh directories,
and the `.ps1` flow, are identical). A mismatch fails the build and means the source, toolchain
or flags changed — never "update the hash" without knowing which.
- **Each platform job builds its own targets** before `tauri build` (Linux: `x86_64-unknown-linux-gnu`;
macOS: `universal-apple-darwin`, i.e. both thin slices — tauri-build checks the arch it compiles —
plus the `lipo`'d universal file the bundler wants, whose slices must thin back out byte-identical
to the pins; Windows: the `.ps1`). Not one Linux job feeding the others: workflow artifacts do
not work on this Gitea (see `build-app-preview.yml`'s header), and with reproducible output and
pinned hashes nothing is gained by building once.
- **Bumping** the plugin or Go: new pins in **both** scripts, rebuild every target, record the new
output hashes, and update `app/src-tauri/THIRD_PARTY_NOTICES` (the scripts refuse to run unless
its `Version:`/`Commit:` lines match) including its dependency licences.
- **Debug builds get a placeholder; release builds refuse one.** tauri-build fails *any* build
whose externalBin file is missing, `cargo test` included. `build.rs` (`ensure_ssm_sidecar`)
writes a marked placeholder (`src/sidecar_placeholder.rs`) for a missing file when
`PROFILE=debug`, so `cargo test`/`cargo check`/`tauri dev` and CI's `test` job need neither Go
nor the network, and `find_plugin()` skips it (falling back to an installed plugin). With
`PROFILE=release` a missing file **or** a placeholder stops the build, so a local `cargo build
--release` needs the build script first. **build.rs rejects only a missing file or the
placeholder, not a stale or wrong binary**: re-run `scripts/build-ssm-plugin.sh` before every
local release build (it is a no-op when the file already matches the pin, and rebuilds it
otherwise — e.g. after a pin bump, or after a Windows release build signed it in place). `finalize-appimage.sh` asserts the shipped
`usr/bin/session-manager-plugin` is an ELF that runs `--version`.
- **Windows: our build is unsigned, so the release signs it with our certificate.** Tauri runs
`signtool verify /pa` on each sidecar and hands the unsigned one to the sign command, in place
under `app\src-tauri\binaries` before any bundle (both MSI and NSIS pack that file);
`windows-sign.ps1`'s allowlist includes it (one more metered signature per release: 6).
`windows-verify-signatures.ps1` requires exactly one `session-manager-plugin.exe` in the MSI and
the file NSIS packed to be validly signed, timestamped, **by the same signing identity
(subject + issuer) as the installer** — not the thumbprint: Artifact Signing certificates are
short-lived and rotate — and the signing log to show it. The MSI must also carry
`THIRD_PARTY_NOTICES`; on macOS a workflow step checks the `.app` holds the two-slice plugin in
`Contents/MacOS` and the notices in `Contents/Resources`. Previews ship it unsigned, like the app.
- **macOS: signed exactly like the app.** The app is not code-signed (no `APPLE_*`/`signingIdentity`
in the workflows); Go's linker ad-hoc signs the arm64 slice (needed to run on Apple Silicon). If
signing is ever configured, Tauri signs externalBin with the app's identity, inside-out.
- **Licence:** `app/src-tauri/THIRD_PARTY_NOTICES` (bundled as a resource; `usr/lib/Triple-C/` in
the AppImage, asserted by `finalize-appimage.sh`) carries the plugin's Apache-2.0 LICENSE and
NOTICE, the commit we build, the repo's own `THIRD-PARTY` file verbatim, the licence of every
vendored module linked in (`go list -deps` for linux/darwin/windows) and Go's own. Note that the
repo's `THIRD-PARTY` file opens with the same "AWS Content" sentence as the binary packages.
### Windows code signing
Windows **releases** (`build-app.yml`) are signed with **Azure Artifact Signing**: the app binary,
the MSI, the NSIS installer and its uninstaller. Three scripts do it, and "Verify signatures"
the bundled `session-manager-plugin`, the MSI, the NSIS installer and its uninstaller. Three scripts do it, and "Verify signatures"
fails the job if any of them is unsigned or untimestamped, so an unsigned installer cannot ship
quietly. **PR previews are deliberately not signed**, and `build-app-preview.yml` must not
reference the signing secrets. Two reasons: signing is metered (about 1000 signatures a month,
@@ -1246,12 +1390,13 @@ without releasing (see Releases above).
- `scripts/windows-sign.ps1` is the sign command: `signtool sign /dlib` with SHA-256 and the
Microsoft timestamp server, retried. Credentials never reach a command line — the dlib reads
`AZURE_TENANT_ID` / `AZURE_CLIENT_ID` / `AZURE_CLIENT_SECRET` from the environment.
**It signs only an allowlist of what ships**: 5 signatures per release (the app binary twice,
**It signs only an allowlist of what ships**: 6 signatures per release (the app binary twice,
because Tauri re-patches it between the MSI and NSIS bundles; the MSI; the NSIS installer;
and its uninstaller). Tauri also presents build-time tools, the WiX extension DLLs and NSIS
its uninstaller; and the `session-manager-plugin` sidecar we build from source). Tauri also presents build-time tools, the WiX extension DLLs and NSIS
plugins, and signing those would more than double the metered count for no user-visible
benefit. If the app ever ships resource DLLs or sidecars, extend the
allowlist, or they will go out unsigned. Tauri reports a failed sign command only as
allowlist, or they will go out unsigned (as `session-manager-plugin`'s entry does; see the
section above). Tauri reports a failed sign command only as
"failed to run powershell", so the script keeps a transcript (`.code-signing/sign-output.log`,
`signtool /debug` included), and the job prints it on failure.
- `scripts/windows-verify-signatures.ps1` checks `signtool verify /pa` plus a timestamp on the
File diff suppressed because it is too large. Load diff
+50
View File
@@ -14,6 +14,8 @@
#[path = "src/command_census.rs"]
mod command_census;
#[path = "src/sidecar_placeholder.rs"]
mod sidecar_placeholder;
use std::path::Path;
@@ -79,6 +81,7 @@ fn main() {
}
prune_permissions(&commands);
ensure_ssm_sidecar();
// `AppManifest::commands` takes `&'static [&'static str]` and the struct is `Copy`, so
// there is no owned form; leaking is fine in a process that exits right after.
@@ -206,3 +209,50 @@ fn check_tauri_config() {
fail("capabilities declared outside capabilities/", &problems, LAYOUT_HINT);
}
}
/// `bundle.externalBin` names `binaries/session-manager-plugin`, and tauri-build stops on a
/// missing `binaries/session-manager-plugin-<target-triple>[.exe]` for every build, tests
/// included. The real one is built from AWS's source by `scripts/build-ssm-plugin.sh` (`.ps1` on
/// Windows), which CI runs before `tauri build`.
///
/// - **Release profile:** the real plugin is required. A missing file or a placeholder stops
/// the build here, so a placeholder can never ship.
/// - **Debug profile** (`cargo test`, `cargo check`, `tauri dev`): a missing file is replaced
/// by a placeholder (`src/sidecar_placeholder.rs`) so no test run needs Go or the network. The app's
/// `find_plugin` skips a placeholder and falls back to an installed plugin.
fn ensure_ssm_sidecar() {
let target = std::env::var("TARGET").expect("cargo sets TARGET");
let ext = if target.contains("windows") { ".exe" } else { "" };
let path = Path::new("binaries").join(format!("session-manager-plugin-{target}{ext}"));
println!("cargo:rerun-if-changed={}", path.display());
let release = std::env::var("PROFILE").as_deref() == Ok("release");
let head = std::fs::read(&path).ok().map(|b| sidecar_placeholder::is_placeholder(&b));
let build = if target.contains("windows") {
"scripts\\build-ssm-plugin.ps1"
} else {
"scripts/build-ssm-plugin.sh"
};
match (head, release) {
(Some(false), _) => {}
(state, true) => fail(
"the AWS Session Manager plugin sidecar is missing",
&[format!(
"{} is {} (release builds bundle the real plugin)",
path.display(),
if state.is_some() { "a debug-build placeholder" } else { "missing" }
)],
&format!("Run {build} {target} from the repository root first."),
),
(None, false) => {
std::fs::create_dir_all("binaries").expect("create src-tauri/binaries");
std::fs::write(&path, sidecar_placeholder::contents())
.unwrap_or_else(|e| panic!("cannot write {}: {e}", path.display()));
println!(
"cargo:warning=no {} - wrote a placeholder (debug only; AWS workspaces use an \
installed plugin). Run {build} to build the real one.",
path.display()
);
}
(Some(true), false) => {}
}
}
+4
View File
@@ -9,6 +9,7 @@
"dialog:allow-open",
"dialog:allow-save",
"allow-check-docker",
"allow-check-docker-status",
"allow-check-image-exists",
"allow-build-image",
"allow-get-container-info",
@@ -95,6 +96,9 @@
"allow-terminal-input",
"allow-terminal-resize",
"allow-close-terminal-session",
"allow-list-workspace-terminals",
"allow-reattach-terminal-session",
"allow-end-workspace-terminal",
"allow-paste-image-to-terminal",
"allow-upload-host-file-to-terminal",
"allow-start-audio-bridge",
+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",
"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.",
"type": "string",
@@ -656,6 +662,12 @@
"const": "allow-ec2-fit-problem",
"markdownDescription": "Enables the ec2_fit_problem command without any pre-configured scope."
},
{
"description": "Enables the end_workspace_terminal command without any pre-configured scope.",
"type": "string",
"const": "allow-end-workspace-terminal",
"markdownDescription": "Enables the end_workspace_terminal command without any pre-configured scope."
},
{
"description": "Enables the export_settings command without any pre-configured scope.",
"type": "string",
@@ -872,6 +884,12 @@
"const": "allow-list-scheduled-tasks",
"markdownDescription": "Enables the list_scheduled_tasks command without any pre-configured scope."
},
{
"description": "Enables the list_workspace_terminals command without any pre-configured scope.",
"type": "string",
"const": "allow-list-workspace-terminals",
"markdownDescription": "Enables the list_workspace_terminals command without any pre-configured scope."
},
{
"description": "Enables the marketplace_gh_host_available command without any pre-configured scope.",
"type": "string",
@@ -968,6 +986,12 @@
"const": "allow-read-container-file",
"markdownDescription": "Enables the read_container_file command without any pre-configured scope."
},
{
"description": "Enables the reattach_terminal_session command without any pre-configured scope.",
"type": "string",
"const": "allow-reattach-terminal-session",
"markdownDescription": "Enables the reattach_terminal_session command without any pre-configured scope."
},
{
"description": "Enables the rebuild_project_container command without any pre-configured scope.",
"type": "string",
@@ -1502,6 +1526,12 @@
"const": "deny-check-docker",
"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.",
"type": "string",
@@ -1646,6 +1676,12 @@
"const": "deny-ec2-fit-problem",
"markdownDescription": "Denies the ec2_fit_problem command without any pre-configured scope."
},
{
"description": "Denies the end_workspace_terminal command without any pre-configured scope.",
"type": "string",
"const": "deny-end-workspace-terminal",
"markdownDescription": "Denies the end_workspace_terminal command without any pre-configured scope."
},
{
"description": "Denies the export_settings command without any pre-configured scope.",
"type": "string",
@@ -1862,6 +1898,12 @@
"const": "deny-list-scheduled-tasks",
"markdownDescription": "Denies the list_scheduled_tasks command without any pre-configured scope."
},
{
"description": "Denies the list_workspace_terminals command without any pre-configured scope.",
"type": "string",
"const": "deny-list-workspace-terminals",
"markdownDescription": "Denies the list_workspace_terminals command without any pre-configured scope."
},
{
"description": "Denies the marketplace_gh_host_available command without any pre-configured scope.",
"type": "string",
@@ -1958,6 +2000,12 @@
"const": "deny-read-container-file",
"markdownDescription": "Denies the read_container_file command without any pre-configured scope."
},
{
"description": "Denies the reattach_terminal_session command without any pre-configured scope.",
"type": "string",
"const": "deny-reattach-terminal-session",
"markdownDescription": "Denies the reattach_terminal_session command without any pre-configured scope."
},
{
"description": "Denies the rebuild_project_container command without any pre-configured scope.",
"type": "string",
@@ -512,6 +512,12 @@
"const": "allow-check-docker",
"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.",
"type": "string",
@@ -656,6 +662,12 @@
"const": "allow-ec2-fit-problem",
"markdownDescription": "Enables the ec2_fit_problem command without any pre-configured scope."
},
{
"description": "Enables the end_workspace_terminal command without any pre-configured scope.",
"type": "string",
"const": "allow-end-workspace-terminal",
"markdownDescription": "Enables the end_workspace_terminal command without any pre-configured scope."
},
{
"description": "Enables the export_settings command without any pre-configured scope.",
"type": "string",
@@ -872,6 +884,12 @@
"const": "allow-list-scheduled-tasks",
"markdownDescription": "Enables the list_scheduled_tasks command without any pre-configured scope."
},
{
"description": "Enables the list_workspace_terminals command without any pre-configured scope.",
"type": "string",
"const": "allow-list-workspace-terminals",
"markdownDescription": "Enables the list_workspace_terminals command without any pre-configured scope."
},
{
"description": "Enables the marketplace_gh_host_available command without any pre-configured scope.",
"type": "string",
@@ -968,6 +986,12 @@
"const": "allow-read-container-file",
"markdownDescription": "Enables the read_container_file command without any pre-configured scope."
},
{
"description": "Enables the reattach_terminal_session command without any pre-configured scope.",
"type": "string",
"const": "allow-reattach-terminal-session",
"markdownDescription": "Enables the reattach_terminal_session command without any pre-configured scope."
},
{
"description": "Enables the rebuild_project_container command without any pre-configured scope.",
"type": "string",
@@ -1502,6 +1526,12 @@
"const": "deny-check-docker",
"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.",
"type": "string",
@@ -1646,6 +1676,12 @@
"const": "deny-ec2-fit-problem",
"markdownDescription": "Denies the ec2_fit_problem command without any pre-configured scope."
},
{
"description": "Denies the end_workspace_terminal command without any pre-configured scope.",
"type": "string",
"const": "deny-end-workspace-terminal",
"markdownDescription": "Denies the end_workspace_terminal command without any pre-configured scope."
},
{
"description": "Denies the export_settings command without any pre-configured scope.",
"type": "string",
@@ -1862,6 +1898,12 @@
"const": "deny-list-scheduled-tasks",
"markdownDescription": "Denies the list_scheduled_tasks command without any pre-configured scope."
},
{
"description": "Denies the list_workspace_terminals command without any pre-configured scope.",
"type": "string",
"const": "deny-list-workspace-terminals",
"markdownDescription": "Denies the list_workspace_terminals command without any pre-configured scope."
},
{
"description": "Denies the marketplace_gh_host_available command without any pre-configured scope.",
"type": "string",
@@ -1958,6 +2000,12 @@
"const": "deny-read-container-file",
"markdownDescription": "Denies the read_container_file command without any pre-configured scope."
},
{
"description": "Denies the reattach_terminal_session command without any pre-configured scope.",
"type": "string",
"const": "deny-reattach-terminal-session",
"markdownDescription": "Denies the reattach_terminal_session command without any pre-configured scope."
},
{
"description": "Denies the rebuild_project_container command without any pre-configured scope.",
"type": "string",
+138 -13
View File
@@ -54,6 +54,8 @@
//! ([`IDLE_TIMEOUT`]).
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
use crate::host::{AttachedExec, ContainerTarget, ExecChunk};
@@ -158,19 +160,25 @@ impl PortForward {
container_port: u16,
family: PortFamily,
) -> Result<Self, std::io::Error> {
Self::bind_with(container, host_port, container_port, family, Gate::SignInCallback).await
Self::bind_with(container, host_port, container_port, family, Gate::SignInCallback, None).await
}
/// As [`bind`](Self::bind), for a project's port mapping on a host with
/// no Docker port publishing (AWS): every connection is carried as is
/// (see [`Gate::None`]).
///
/// Inside the workspace each connection goes to whichever loopback
/// family has a listener on `container_port` ([`mapping_command`]), so a
/// server bound to `[::1]` only is reached as well as one on
/// `127.0.0.1`/`0.0.0.0`. `on_refused` is called (once per forward) the
/// first time a connection finds nothing listening there.
pub async fn bind_mapping(
container: ContainerTarget,
host_port: u16,
container_port: u16,
family: PortFamily,
on_refused: Option<RefusedNotice>,
) -> Result<Self, std::io::Error> {
Self::bind_with(container, host_port, container_port, family, Gate::None).await
Self::bind_with(container, host_port, container_port, PortFamily::Dual, Gate::None, on_refused).await
}
async fn bind_with(
@@ -179,6 +187,7 @@ impl PortForward {
container_port: u16,
family: PortFamily,
gate: Gate,
on_refused: Option<RefusedNotice>,
) -> Result<Self, std::io::Error> {
// SECURITY BOUNDARY: the host side binds loopback ONLY — 127.0.0.1 and
// ::1, never 0.0.0.0 / ::. Everything reachable through this socket is
@@ -222,8 +231,12 @@ impl PortForward {
}
};
let target = family.socat_target(container_port);
let task = tokio::spawn(accept_loop(container, port, target, v4, v6, gate));
let cmd = match gate {
Gate::SignInCallback => socat_command(&family.socat_target(container_port)),
Gate::None => mapping_command(container_port),
};
let refused = on_refused.map(|f| Arc::new(RefusedOnce { notice: f, fired: AtomicBool::new(false) }));
let task = tokio::spawn(accept_loop(container, port, cmd, v4, v6, gate, refused));
Ok(Self {
port,
@@ -273,10 +286,11 @@ impl Gate {
async fn accept_loop(
container: ContainerTarget,
port: u16,
target: String,
cmd: Vec<String>,
v4: TcpListener,
v6: Option<TcpListener>,
gate: Gate,
refused: Option<Arc<RefusedOnce>>,
) {
let mut conns: JoinSet<()> = JoinSet::new();
@@ -313,17 +327,18 @@ async fn accept_loop(
match gate {
Gate::SignInCallback => conns.spawn(tunnel_connection(
container.clone(),
target.clone(),
cmd.clone(),
stream,
port,
)),
Gate::None => conns.spawn(tunnel_labelled(
gate.label(),
container.clone(),
target.clone(),
cmd.clone(),
stream,
port,
Vec::new(),
refused.clone(),
)),
};
}
@@ -353,7 +368,7 @@ async fn accept_optional(
/// reaches the container at all — not even a `docker exec`.
async fn tunnel_connection(
container: ContainerTarget,
target: String,
cmd: Vec<String>,
mut stream: TcpStream,
port: u16,
) {
@@ -387,7 +402,7 @@ async fn tunnel_connection(
}
// The bytes already off the socket go back on the wire first, byte-exact.
tunnel_connection_with_prelude(container, target, stream, port, head.into_buffer()).await
tunnel_labelled("Auth bridge", container, cmd, stream, port, head.into_buffer(), None).await
}
/// What the first bytes of an accepted connection turned out to be.
@@ -586,19 +601,20 @@ pub async fn tunnel_connection_with_prelude(
port: u16,
prelude: Vec<u8>,
) {
tunnel_labelled("Auth bridge", container, target, stream, port, prelude).await
tunnel_labelled("Auth bridge", container, socat_command(&target), stream, port, prelude, None).await
}
/// [`tunnel_connection_with_prelude`], logging under `label`.
async fn tunnel_labelled(
label: &'static str,
container: ContainerTarget,
target: String,
cmd: Vec<String>,
stream: TcpStream,
port: u16,
prelude: Vec<u8>,
refused: Option<Arc<RefusedOnce>>,
) {
let cmd = vec!["socat".to_string(), "-".to_string(), target.clone()];
let target = cmd.last().cloned().unwrap_or_default();
let AttachedExec {
mut output,
@@ -673,6 +689,12 @@ async fn tunnel_labelled(
}
}
Ok(ExecChunk::StdErr(message)) => {
if let Some(r) = &refused {
if is_connection_refused(&message) {
log::warn!("{}: host port {}: nothing is listening in the workspace", label, port);
r.fire();
}
}
log::debug!(
"{}: socat stderr for port {}: {}", label,
port,
@@ -692,10 +714,113 @@ async fn tunnel_labelled(
drop(upstream);
}
/// Called the first time a port mapping's connection finds nothing
/// listening on its workspace port.
pub type RefusedNotice = Arc<dyn Fn() + Send + Sync>;
/// A [`RefusedNotice`] that fires once per forward.
struct RefusedOnce {
notice: RefusedNotice,
fired: AtomicBool,
}
impl RefusedOnce {
fn fire(&self) {
if !self.fired.swap(true, Ordering::SeqCst) {
(self.notice)();
}
}
}
/// `socat` relaying stdio to `target`.
fn socat_command(target: &str) -> Vec<String> {
vec!["socat".to_string(), "-".to_string(), target.to_string()]
}
/// Whether socat's stderr says the connect was refused (nothing listening).
fn is_connection_refused(stderr: &[u8]) -> bool {
String::from_utf8_lossy(stderr).contains("Connection refused")
}
/// The in-workspace command of one port-mapping connection.
///
/// Docker publishes to the container's interface; a mapping reaches its
/// loopback instead, where a server may listen on either family (Vite, or
/// Node's `localhost` where it resolves to `::1`, listen on `[::1]` only).
/// So the command picks, from `/proc/net/tcp{,6}` (the image has no `ss`),
/// the family with a listener on `port`: `127.0.0.1` when one listens on
/// `127.0.0.1` or `0.0.0.0`, else `[::1]` when one listens on `::1` or `::`.
/// Nothing found: `127.0.0.1` anyway, and socat's "Connection refused" is
/// what tells the host nothing listens. Reading `/proc` rather than trying
/// a connect first means a server never sees a probe connection.
pub(crate) fn mapping_command(port: u16) -> Vec<String> {
// `port` is a u16: interpolating it into the script is safe.
let script = format!(
"h=$(printf ':%04X' {port}); \
l() {{ awk -v a=\"$2$h\" -v b=\"$3$h\" '$4==\"0A\" && ($2==a || $2==b) {{f=1}} END {{exit !f}}' \"$1\" 2>/dev/null; }}; \
if l /proc/net/tcp 0100007F 00000000; then exec socat - TCP:127.0.0.1:{port}; fi; \
if l /proc/net/tcp6 00000000000000000000000001000000 00000000000000000000000000000000; \
then exec socat - TCP6:[::1]:{port}; fi; \
exec socat - TCP:127.0.0.1:{port}"
);
vec!["sh".to_string(), "-c".to_string(), script]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_mapping_command_names_only_its_port_and_both_loopbacks() {
let cmd = mapping_command(8080);
assert_eq!(&cmd[..2], ["sh", "-c"]);
let s = &cmd[2];
assert!(s.contains("printf ':%04X' 8080"), "{s}");
assert!(s.contains("TCP:127.0.0.1:8080") && s.contains("TCP6:[::1]:8080"), "{s}");
// v4 first; the last resort is v4 too.
assert!(s.find("TCP:127.0.0.1").unwrap() < s.find("TCP6:[::1]").unwrap());
assert!(s.trim_end().ends_with("exec socat - TCP:127.0.0.1:8080"), "{s}");
}
#[test]
fn socats_refusal_is_recognised() {
assert!(is_connection_refused(
b"2026/11/17 10:00:00 socat[42] E connect(5, AF=2 127.0.0.1:8080, 16): Connection refused\n"
));
assert!(!is_connection_refused(b"socat[42] N exiting with status 0"));
}
/// The command picks the family from `/proc/net/tcp{,6}`: run it against
/// real listeners where `sh`, `awk` and `socat` exist (skipped elsewhere).
#[tokio::test]
async fn a_mapping_command_reaches_a_v4_or_a_v6_only_listener() {
let have = |b: &str| std::process::Command::new("sh").args(["-c", &format!("command -v {b}")]).output()
.is_ok_and(|o| o.status.success());
if !(have("awk") && have("socat") && std::path::Path::new("/proc/net/tcp").exists()) {
eprintln!("skipped: needs sh, awk, socat and /proc/net");
return;
}
for addr in ["127.0.0.1:0", "[::1]:0"] {
let Ok(l) = TcpListener::bind(addr).await else { continue };
let port = l.local_addr().unwrap().port();
tokio::spawn(async move {
if let Ok((mut s, _)) = l.accept().await {
let _ = s.write_all(b"hello").await;
}
});
let cmd = mapping_command(port);
let out = tokio::process::Command::new(&cmd[0]).args(&cmd[1..])
.stdin(std::process::Stdio::null()).output().await.unwrap();
assert_eq!(String::from_utf8_lossy(&out.stdout), "hello", "{addr}: {}", String::from_utf8_lossy(&out.stderr));
}
// Nothing listening: refused, in socat's words.
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let cmd = mapping_command(port);
let out = tokio::process::Command::new(&cmd[0]).args(&cmd[1..])
.stdin(std::process::Stdio::null()).output().await.unwrap();
assert!(is_connection_refused(&out.stderr), "{}", String::from_utf8_lossy(&out.stderr));
}
fn head(lines: &[&str]) -> String {
format!("{}\r\n\r\n", lines.join("\r\n"))
}
@@ -9,6 +9,12 @@ pub async fn check_docker() -> Result<bool, String> {
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]
pub async fn check_image_exists(state: State<'_, AppState>) -> Result<bool, String> {
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
/// caller's record, the capacity ([`resolve_ec2`]), the module variables
/// and, with EC2 capacity, the name check ([`ec2_collision_refusal`]).
/// Check-then-apply leaves a narrow race (another admin creating the same
/// names in between); only admins apply, and the module would then fail on
/// create rather than adopt.
/// Check-then-apply leaves a narrow race (someone else creating the same
/// names in between); the module would then fail on create rather than
/// 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>(
api: &A,
env: &str,
+40 -7
View File
@@ -724,6 +724,7 @@ pub async fn remove_project(
if let Some(target) = ContainerTarget::for_project(&project) {
state.exec_manager.close_sessions_for_container(target.id()).await;
}
crate::storage::terminal_store::clear(&project_id);
let connection_exists = project
.host_id
.as_deref()
@@ -1152,14 +1153,20 @@ pub async fn update_project(
// status change or a container id landing since `stored` was read is kept
// rather than written over.
let mappings_changed = stored.port_mappings != project.port_mappings;
let left_aws = stored.is_aws() && !project.is_aws();
let saved = state
.projects_store
.update_restoring(project, restore_store_owned_fields)?;
// AWS (Q6): a connected workspace's forwards follow the saved mappings
// now — there is no container to recreate. Nothing when not connected.
if left_aws {
// Moved to Docker: its workspace terminals went with the task.
crate::storage::terminal_store::clear(&saved.id);
}
if saved.is_aws() && mappings_changed {
if let Some(detail) = crate::host::port_forwards::open_for_project(&state.projects_store, &saved.id).await {
let warn = ports_warner(&app_handle, &saved.id, &saved.name);
if let Some(detail) = crate::host::port_forwards::open_for_project(&state.projects_store, &saved.id, Some(warn)).await {
emit_ports_warning(&app_handle, &saved.id, &saved.name, &detail);
}
}
@@ -1551,7 +1558,8 @@ async fn start_project_container_locked(
// AWS (Q6): the project's port mappings become loopback forwards into
// the workspace; a mapping that can't open is a warning, the rest work.
if project.is_aws() {
if let Some(detail) = crate::host::port_forwards::open_for_project(&state.projects_store, &project_id).await {
let warn = ports_warner(&app_handle, &project_id, &project.name);
if let Some(detail) = crate::host::port_forwards::open_for_project(&state.projects_store, &project_id, Some(warn)).await {
emit_ports_warning(&app_handle, &project_id, &project.name, &detail);
}
}
@@ -1628,12 +1636,23 @@ fn connect_warning_payload(project_id: &str, name: &str, detail: &str) -> serde_
/// Port mappings that could not be forwarded to a connected AWS workspace
/// (Q6): a busy host port, a host port mapped twice. Same `workspace-warning`
/// event, with its own `topic` so it does not replace the other warnings.
/// Where a port mapping's later notices ("nothing is listening") go: the
/// same `ports` warning toast.
fn ports_warner(app_handle: &tauri::AppHandle, project_id: &str, name: &str) -> crate::host::port_forwards::PortsWarn {
let (handle, id, name) = (app_handle.clone(), project_id.to_string(), name.to_string());
std::sync::Arc::new(move |detail: String| emit_ports_warning(&handle, &id, &name, &detail))
}
fn emit_ports_warning(app_handle: &tauri::AppHandle, project_id: &str, name: &str, detail: &str) {
let _ = app_handle.emit(
"workspace-warning",
serde_json::json!({
"project_id": project_id,
"message": format!("“{name}”: some port mappings could not be opened"),
"message": if detail.contains("nothing is listening") {
format!("“{name}”: a port mapping found nothing listening in the workspace")
} else {
format!("“{name}”: some port mappings could not be opened")
},
"detail": detail,
"topic": "ports",
}),
@@ -1739,6 +1758,9 @@ pub async fn stop_project_container(
state.auth_bridge.stop(&project_id).await;
if let Some(container) = guard_target.as_ref() {
state.exec_manager.close_sessions_for_container(container.id()).await;
// Closing the tabs only detaches persistent terminals: end
// their tmux servers too, before the push's snapshot.
crate::host::persistent::end_all(container).await;
}
if wip == Some(WipChoice::Push) {
emit_progress(&app_handle, &project_id, "Pushing unsaved work...");
@@ -1797,6 +1819,8 @@ pub async fn stop_project_container(
)?;
}
state.projects_store.set_container_id(&project_id, None)?;
// Its terminals ended with the task.
crate::storage::terminal_store::clear(&project_id);
} else if let Some(container) = ContainerTarget::for_project(&project) {
// Close exec sessions for this project
emit_progress(&app_handle, &project_id, "Stopping container...");
@@ -3218,6 +3242,14 @@ mod tests {
let stop = &stop[..stop.find("\n}\n").unwrap()];
let close = stop.find("close_sessions_for_container").unwrap();
assert!(close < stop.find("aws_guard_before_stop(").unwrap());
// Closing a tab only detaches a persistent terminal: its tmux server
// is ended in the same step, before the push's snapshot.
let end_all = stop.find("persistent::end_all(container)").unwrap();
assert!(close < end_all && end_all < stop.find("aws_guard_before_stop(").unwrap());
let close_first = &stop[stop.find("let close_first = async").unwrap()..stop.find("let guarded").unwrap()];
assert!(close_first.contains("persistent::end_all"), "inside the step that runs first");
// A stopped task's terminals are gone: forgotten.
assert!(stop.find("terminal_store::clear").unwrap() > stop.find("stop_project(&project").unwrap());
assert!(stop.find("auth_bridge.stop").unwrap() < stop.find("aws_guard_before_stop(").unwrap());
}
@@ -3344,20 +3376,21 @@ mod tests {
let start = fn_body(src, "start_project_container_locked");
let running = start.find("update_status(&project_id, ProjectStatus::Running)").unwrap();
let open = start
.find("port_forwards::open_for_project(&state.projects_store, &project_id)")
.find("port_forwards::open_for_project(&state.projects_store, &project_id, Some(warn))")
.expect("the start opens them");
assert!(open > running);
let guard = start[..open].rfind("if project.is_aws() {").expect("AWS-only");
assert!(start[guard..open].lines().count() <= 2);
assert!(start[guard..open].lines().count() <= 3);
assert!(start[guard..open].contains("let warn = ports_warner(&app_handle, &project_id, &project.name);"));
assert!(start[open..].lines().nth(1).unwrap().contains("emit_ports_warning("));
let update = fn_body(src, "update_project");
assert!(update.contains("port_forwards::open_for_project(&state.projects_store, &saved.id)"));
assert!(update.contains("port_forwards::open_for_project(&state.projects_store, &saved.id, Some(warn))"));
let reconcile = fn_body(src, "reconcile_aws_projects");
assert!(reconcile.contains("on_ports_warning,"));
assert!(reconcile.contains("emit_ports_warning(&ports_handle, &ports_id, &ports_name, &detail)"));
let aws_host = include_str!("../host/aws_host.rs");
let reattached = aws_host.find("Ok(true) => {").unwrap();
let opened = aws_host.find("port_forwards::open_for_project(&store, &project.id)").unwrap();
let opened = aws_host.find("port_forwards::open_for_project(&store, &project.id, Some(warn.clone()))").unwrap();
let pushed = aws_host[reattached..].find("connect::apply_connect(").unwrap() + reattached;
assert!(reattached < opened && opened < pushed);
}
+320 -5
View File
@@ -1,8 +1,13 @@
use tauri::{AppHandle, Emitter, State};
use crate::commands::aws_commands;
use crate::host::persistent::{self, TerminalKind};
use crate::host::ContainerTarget;
use crate::models::{Backend, BedrockAuthMethod, Project};
use crate::models::{
Backend, BedrockAuthMethod, OpenedTerminal, Project, ProjectStatus, ReattachOutcome,
WorkspaceTerminal,
};
use crate::storage::terminal_store::{self, PersistedTerminal};
use crate::AppState;
/// Build the command to run in the container terminal.
@@ -145,6 +150,10 @@ fi
]
}
/// Open a terminal tab. On an AWS project whose image has tmux the command
/// runs inside its own tmux server keyed by `session_id`
/// (`host::persistent`), so it outlives the app; the tab is remembered so the
/// app reopens it on its next connect.
#[tauri::command]
pub async fn open_terminal_session(
project_id: String,
@@ -154,7 +163,7 @@ pub async fn open_terminal_session(
resume_session_id: Option<String>,
app_handle: AppHandle,
state: State<'_, AppState>,
) -> Result<(), String> {
) -> Result<OpenedTerminal, String> {
let project = state
.projects_store
.get(&project_id)
@@ -169,6 +178,7 @@ pub async fn open_terminal_session(
crate::commands::inspect_commands::validate_session_id(id)?;
}
let kind = if session_type.as_deref() == Some("bash") { TerminalKind::Bash } else { TerminalKind::Claude };
let cmd = match session_type.as_deref() {
Some("bash") if resume_session_id.is_some() => {
return Err("Only a Claude session can resume a conversation".to_string());
@@ -186,6 +196,17 @@ pub async fn open_terminal_session(
// environment (never the agent's). Empty for everything else.
let env = crate::host::aws_host::terminal_env(&project, &state.settings_store.get()).await;
let plan = persistent::plan(
project.is_aws(),
&target,
&session_id,
kind,
session_name.as_deref(),
cmd,
env,
)
.await?;
let output_event = format!("terminal-output-{}", session_id);
let exit_event = format!("terminal-exit-{}", session_id);
let app_handle_output = app_handle.clone();
@@ -196,8 +217,8 @@ pub async fn open_terminal_session(
.create_session(
&target,
&session_id,
cmd,
env,
plan.cmd,
plan.env,
move |data| {
let _ = app_handle_output.emit(&output_event, data);
},
@@ -205,7 +226,19 @@ pub async fn open_terminal_session(
let _ = app_handle_exit.emit(&exit_event, ());
}),
)
.await
.await?;
if plan.persistent {
let entry = PersistedTerminal {
id: session_id.clone(),
kind,
name: persistent::clean_name(session_name.as_deref()),
};
if let Err(e) = terminal_store::add(&project_id, entry) {
log::warn!("Could not remember terminal {session_id}: {e}");
}
}
Ok(OpenedTerminal { persistent: plan.persistent, notice: plan.notice })
}
#[tauri::command]
@@ -227,6 +260,8 @@ pub async fn terminal_resize(
state.exec_manager.resize(&session_id, cols, rows).await
}
/// Close a tab. A persistent AWS terminal is *ended* (its tmux server
/// killed) and forgotten: closing a tab is the one gesture that ends one.
#[tauri::command]
pub async fn close_terminal_session(
session_id: String,
@@ -235,8 +270,254 @@ pub async fn close_terminal_session(
// Close audio bridge if it exists
let audio_session_id = format!("audio-{}", session_id);
state.exec_manager.close_session(&audio_session_id).await;
let session_target = state.exec_manager.get_target(&session_id).await.ok();
// Close terminal session
state.exec_manager.close_session(&session_id).await;
if let Some((project_id, _)) = terminal_store::find(&session_id) {
// A reattach of this tab still in flight must not remember it again.
mark_closed(&session_id);
if let Err(e) = terminal_store::remove(&session_id) {
log::warn!("Could not forget terminal {session_id}: {e}");
}
// The project's current tunnel first: the session's own endpoint is
// stale after a re-attach on a new port.
let target = state
.projects_store
.get(&project_id)
.and_then(|p| ContainerTarget::for_project(&p))
.or(session_target);
let ended = match target {
Some(t) => persistent::end(&t, &session_id).await,
None => Err("not connected".to_string()),
};
if let Err(e) = ended {
// Still running in the workspace (a leftover Claude would keep
// it up): end it at the next connect.
log::warn!("Terminal {session_id}: could not end it now ({e}); ending it at the next connect");
if let Err(e) = terminal_store::add_pending_end(&project_id, &session_id) {
log::warn!("Could not remember to end terminal {session_id}: {e}");
}
}
}
Ok(())
}
/// Session ids whose tab was closed in this run of the app.
fn closed_ids() -> &'static std::sync::Mutex<std::collections::HashSet<String>> {
static C: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> =
std::sync::OnceLock::new();
C.get_or_init(Default::default)
}
fn mark_closed(session_id: &str) {
closed_ids().lock().unwrap_or_else(|e| e.into_inner()).insert(session_id.to_string());
}
fn was_closed(session_id: &str) -> bool {
closed_ids().lock().unwrap_or_else(|e| e.into_inner()).contains(session_id)
}
/// End the project's sessions whose tabs were closed while it could not be
/// reached; returns the ones ended (or found gone).
async fn end_pending(project_id: &str, target: &ContainerTarget, running: &[persistent::RunningSession]) -> Vec<String> {
let pending = terminal_store::pending_end(project_id);
let mut done = Vec::new();
for key in pending {
if !running.iter().any(|r| r.key == key) {
done.push(key);
continue;
}
match persistent::end(target, &key).await {
Ok(()) => done.push(key),
Err(e) => log::warn!("Could not end closed terminal {key}: {e}"),
}
}
if !done.is_empty() {
if let Err(e) = terminal_store::done_pending_end(project_id, &done) {
log::warn!("Could not update the terminals to end: {e}");
}
}
done
}
/// A connected AWS project's target, waiting for a re-attach in progress.
async fn aws_target(project: &Project) -> Result<ContainerTarget, String> {
if !project.is_aws() {
return Err("Only AWS workspaces keep terminals".into());
}
if project.status != ProjectStatus::Running {
return Err(format!("“{}” is not running", project.name));
}
ContainerTarget::for_project_waiting(project)
.await
.ok_or_else(|| "Triple-C is not connected to the workspace".to_string())
}
/// The workspace's running terminals with what the app remembers of them,
/// remembered ones first in the order they were opened. Prunes remembered
/// entries the workspace no longer runs. Empty for a Docker project, a
/// stopped one and an image without tmux.
#[tauri::command]
pub async fn list_workspace_terminals(
project_id: String,
state: State<'_, AppState>,
) -> Result<Vec<WorkspaceTerminal>, String> {
let project = state
.projects_store
.get(&project_id)
.ok_or_else(|| format!("Project {} not found", project_id))?;
if !project.is_aws() || project.status != ProjectStatus::Running {
return Ok(Vec::new());
}
let target = aws_target(&project).await?;
// An `Err` (an unanswered probe or listing) says nothing about what runs:
// nothing is pruned or ended on it, and the caller asks again.
let mut running = persistent::list(&target).await?;
let ended = end_pending(&project_id, &target, &running).await;
running.retain(|r| !ended.contains(&r.key));
let keys = running.iter().map(|r| r.key.clone()).collect();
if let Err(e) = terminal_store::retain(&project_id, &keys) {
log::warn!("Could not prune remembered terminals: {e}");
}
Ok(merge_terminals(&terminal_store::list(&project_id), running))
}
/// Remembered sessions first (in their order), then the others oldest first.
pub(crate) fn merge_terminals(
remembered: &[PersistedTerminal],
mut running: Vec<persistent::RunningSession>,
) -> Vec<WorkspaceTerminal> {
running.sort_by_key(|r| {
(
remembered.iter().position(|m| m.id == r.key).unwrap_or(usize::MAX),
r.created_unix,
)
});
running
.into_iter()
.map(|r| {
let mine = remembered.iter().find(|m| m.id == r.key);
WorkspaceTerminal {
kind: mine.map(|m| m.kind).unwrap_or(r.kind),
name: mine.map(|m| m.name.clone()).unwrap_or(r.name),
known: mine.is_some(),
session_id: r.key,
created_unix: r.created_unix,
attached: r.attached,
}
})
.collect()
}
/// Attach a tab to a terminal still running in the workspace: a tab the app
/// reopens after a restart or a dropped connection, or one picked in Project
/// Home → Sessions. Never starts anything: a session that is gone is
/// `Ended` (and forgotten). With `rows` (a fresh xterm), the pane's history
/// is replayed into the tab's output first, so its scrollback comes back.
/// The tab's output listener must be registered before this is called.
#[tauri::command]
pub async fn reattach_terminal_session(
project_id: String,
session_id: String,
rows: Option<u16>,
app_handle: AppHandle,
state: State<'_, AppState>,
) -> Result<ReattachOutcome, String> {
persistent::validate_key(&session_id)?;
let project = state
.projects_store
.get(&project_id)
.ok_or_else(|| format!("Project {} not found", project_id))?;
if was_closed(&session_id) {
return Ok(ReattachOutcome::Ended);
}
let target = aws_target(&project).await?;
// Unanswered → `Err` (the tab retries); only a real "no tmux" ends it.
if !persistent::supported(&target).await? {
terminal_store::remove(&session_id).ok();
return Ok(ReattachOutcome::Ended);
}
if terminal_store::pending_end(&project_id).contains(&session_id) {
return Ok(ReattachOutcome::Ended);
}
let running = persistent::list(&target).await?;
let Some(found) = running.into_iter().find(|r| r.key == session_id) else {
if let Err(e) = terminal_store::remove(&session_id) {
log::warn!("Could not forget terminal {session_id}: {e}");
}
return Ok(ReattachOutcome::Ended);
};
let remembered = terminal_store::find(&session_id).filter(|(p, _)| *p == project_id);
let (kind, name) = match remembered {
Some((_, m)) => (m.kind, m.name),
None => (found.kind, found.name),
};
let output_event = format!("terminal-output-{}", session_id);
if let Some(rows) = rows {
// Exactly one chunk, empty when there is no history: the tab treats
// the first chunk after asking for a replay as the replay, so live
// output after it gets its URL/OSC/SSO handling again.
let bytes = persistent::history(&target, &session_id)
.await
.map(|h| persistent::replay_bytes(&h, rows))
.unwrap_or_default();
let _ = app_handle.emit(&output_event, bytes);
}
let exit_event = format!("terminal-exit-{}", session_id);
let app_handle_output = app_handle.clone();
let app_handle_exit = app_handle.clone();
state
.exec_manager
.create_session(
&target,
&session_id,
persistent::attach_cmd(&session_id)?,
persistent::client_env(Vec::new()),
move |data| {
let _ = app_handle_output.emit(&output_event, data);
},
Box::new(move || {
let _ = app_handle_exit.emit(&exit_event, ());
}),
)
.await?;
// Closed while this attach was under way: its close already ended (or
// queued the end of) the session; don't remember it again.
if was_closed(&session_id) {
state.exec_manager.close_session(&session_id).await;
return Ok(ReattachOutcome::Ended);
}
let entry = PersistedTerminal { id: session_id.clone(), kind, name: name.clone() };
if let Err(e) = terminal_store::add(&project_id, entry) {
log::warn!("Could not remember terminal {session_id}: {e}");
}
Ok(ReattachOutcome::Reattached { kind, name })
}
/// End a terminal running in the workspace that has no tab here (Project
/// Home → Sessions → End). A tab's own close goes through
/// `close_terminal_session`.
#[tauri::command]
pub async fn end_workspace_terminal(
project_id: String,
session_id: String,
state: State<'_, AppState>,
) -> Result<(), String> {
persistent::validate_key(&session_id)?;
let project = state
.projects_store
.get(&project_id)
.ok_or_else(|| format!("Project {} not found", project_id))?;
let target = aws_target(&project).await?;
state.exec_manager.close_session(&session_id).await;
persistent::end(&target, &session_id).await?;
if let Err(e) = terminal_store::remove(&session_id) {
log::warn!("Could not forget terminal {session_id}: {e}");
}
Ok(())
}
@@ -571,6 +852,40 @@ mod tests {
assert!(!cmd[2].contains(" -n "), "resume must not rename: {}", cmd[2]);
}
/// The app's own tabs come first in the order they were opened, with
/// the app's labels; sessions from elsewhere follow, oldest first, and
/// are not "known" (so they are listed, never auto-opened).
#[test]
fn workspace_terminals_merge_what_the_app_remembers_with_what_runs() {
use super::merge_terminals;
use crate::host::persistent::{RunningSession, TerminalKind};
use crate::storage::terminal_store::PersistedTerminal;
let run = |key: &str, kind, created, name: Option<&str>| RunningSession {
key: key.into(),
kind,
created_unix: created,
attached: false,
name: name.map(str::to_string),
};
let remembered = vec![
PersistedTerminal { id: "b".into(), kind: TerminalKind::Claude, name: Some("second".into()) },
PersistedTerminal { id: "a".into(), kind: TerminalKind::Bash, name: None },
PersistedTerminal { id: "gone".into(), kind: TerminalKind::Bash, name: None },
];
let running = vec![
run("x", TerminalKind::Bash, 50, Some("web terminal")),
run("a", TerminalKind::Bash, 10, None),
run("w", TerminalKind::Claude, 5, None),
run("b", TerminalKind::Claude, 20, Some("tmux label")),
];
let got = merge_terminals(&remembered, running);
let ids: Vec<_> = got.iter().map(|t| t.session_id.as_str()).collect();
assert_eq!(ids, ["b", "a", "w", "x"]);
assert!(got[0].known && got[1].known && !got[2].known && !got[3].known);
assert_eq!(got[0].name.as_deref(), Some("second"), "the app's label wins");
assert_eq!(got[3].name.as_deref(), Some("web terminal"));
}
#[test]
fn a_dropped_file_keeps_the_name_the_user_dropped() {
use crate::commands::file_commands::host_upload_name;
+8 -1
View File
@@ -117,7 +117,14 @@ async fn settle(store: &ProjectsStore, container: &ContainerTarget) -> Option<Pr
return None;
}
match store.mark_exited(container_id, &seen, project_busy) {
ExitMark::Flipped(p) => return Some(*p),
ExitMark::Flipped(p) => {
// An AWS task that stopped by itself (idle, lifetime cap,
// crash) took its persistent terminals with it.
if p.is_aws() {
crate::storage::terminal_store::clear(&p.id);
}
return Some(*p);
}
ExitMark::NotApplicable => return None,
// The store moved while the host was answering — possibly a stop and
// start of this very container. The inspect is stale; ask again.
@@ -1321,6 +1321,59 @@ fn aws_stop_skips_its_push_when_the_app_already_pushed_or_the_user_declined() {
assert_eq!(fs::read_to_string(&log).unwrap(), "--reason sigterm\n");
}
/// Persistent terminals (tmux) end before the hook's own push takes its
/// snapshot, and only their servers: the socket prefix is the app's.
#[test]
fn aws_stop_ends_the_persistent_terminals_before_its_push() {
let tmp = tempfile::tempdir().unwrap();
let log = tmp.path().join("calls");
let bin = tmp.path().join("bin");
fs::create_dir_all(&bin).unwrap();
let fake_push = write_script(
tmp.path(),
"triple-c-wip-push",
&format!("#!/bin/bash\necho \"push $*\" >> '{}'\n", log.display()),
);
write_script(&bin, "tmux", &format!("#!/bin/bash\necho \"tmux $*\" >> '{}'\n", log.display()));
// Two of ours and someone else's server in the same socket directory.
let socks = tmp.path().join("socks");
let dir = socks.join(format!("tmux-{}", unsafe { libc::getuid() }));
fs::create_dir_all(&dir).unwrap();
let mut keep = Vec::new();
for name in ["triple-c-aaa", "triple-c-bbb", "mine"] {
keep.push(std::os::unix::net::UnixListener::bind(dir.join(name)).unwrap());
}
let blocks = aws_blocks(&["aws_env", "aws_stop"])
.replace("/usr/local/bin/triple-c-wip-push", fake_push.to_str().unwrap())
.replace("/run/triple-c/stop-reason", tmp.path().join("reason").to_str().unwrap());
let path = format!("{}:{}", bin.display(), std::env::var("PATH").unwrap());
let script = format!("{blocks}\naws_before_stop\n");
let env = [
("TRIPLEC_HOST", "aws"),
("TRIPLEC_WIP_PUSH", "1"),
("PATH", path.as_str()),
("TMUX_TMPDIR", socks.to_str().unwrap()),
];
let out = bash(&script, &[], &env, &[]);
assert!(out.status.success(), "{}", text(&out));
let calls = fs::read_to_string(&log).unwrap();
assert_eq!(
calls,
"tmux -L triple-c-aaa list-panes -a -F #{pane_pid}\ntmux -L triple-c-aaa kill-server\n\
tmux -L triple-c-bbb list-panes -a -F #{pane_pid}\ntmux -L triple-c-bbb kill-server\n\
push --reason sigterm\n"
);
drop(keep);
// The app's own Stop and the idle watcher's lifetime stop run the very
// same script.
let script = crate::host::persistent::END_ALL_SCRIPT;
assert!(block(ENTRYPOINT, "aws_stop").contains(script));
assert!(IDLE_WATCH.contains(script));
assert_eq!(crate::host::persistent::end_all_cmd()[2], script);
let lifetime = &IDLE_WATCH[IDLE_WATCH.find("lifetime_stop() {").unwrap()..];
assert!(lifetime.find("end_terminals").unwrap() < lifetime.find("--reason lifetime").unwrap());
}
#[test]
fn the_idle_exit_status_is_the_one_the_app_reads() {
assert!(
+29 -10
View File
@@ -15,16 +15,35 @@ pub fn get_docker() -> Result<Docker, String> {
}
pub async fn check_docker_available() -> Result<bool, String> {
let docker = get_docker()?;
match docker.ping().await {
Ok(_) => Ok(true),
Err(_) => {
// Connection object exists but daemon not responding — clear cache
let mut guard = DOCKER.lock().map_err(|e| format!("Lock poisoned: {}", e))?;
*guard = None;
Ok(false)
}
}
Ok(docker_status().await.state == super::status::DockerState::Running)
}
/// Ping the daemon and, when it does not answer, say why: not installed, installed
/// but not running, or running but refusing us. See `docker/status.rs`.
pub async fn docker_status() -> super::status::DockerStatus {
use super::status::{self, PingOutcome};
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
+4
View File
@@ -260,6 +260,10 @@ const RESERVED_ENV_PREFIXES: &[&str] = &["ANTHROPIC_", "AWS_", "GIT_", "HOST_",
/// value would silently outrank the keychain-held shared token and be invisible
/// to the auth UI.
const RESERVED_ENV_EXACT: &[&str] = &[
// Persistent AWS terminals (`host::persistent`): either would point a
// tab's tmux at another socket than the one the app lists and ends.
"TMUX",
"TMUX_TMPDIR",
"CLAUDE_INSTRUCTIONS",
"MCP_SERVERS_JSON",
"CLAUDE_CODE_SETTINGS_JSON",
+3
View File
@@ -14,6 +14,8 @@ const ENTRYPOINT: &str = include_str!("../../../../container/entrypoint.sh");
/// `sync_host_ssh` block the tests below run.
const ENTRYPOINT_LIB: &str = include_str!("../../../../container/entrypoint-lib.sh");
const APPLY_CONNECT: &str = include_str!("../../../../container/triple-c-apply-connect");
/// `/etc/triple-c/tmux.conf`: persistent AWS terminals (`host::persistent`).
const TMUX_CONF: &str = include_str!("../../../../container/triple-c-tmux.conf");
const SCHEDULER: &str = include_str!("../../../../container/triple-c-scheduler");
const TASK_RUNNER: &str = include_str!("../../../../container/triple-c-task-runner");
const OSC52_CLIPBOARD: &str = include_str!("../../../../container/osc52-clipboard");
@@ -247,6 +249,7 @@ fn create_build_context() -> Result<Vec<u8>, std::io::Error> {
append_file_to_archive(&mut archive, "entrypoint.sh", ENTRYPOINT.as_bytes(), 0o755)?;
append_file_to_archive(&mut archive, "entrypoint-lib.sh", ENTRYPOINT_LIB.as_bytes(), 0o644)?;
append_file_to_archive(&mut archive, "triple-c-apply-connect", APPLY_CONNECT.as_bytes(), 0o755)?;
append_file_to_archive(&mut archive, "triple-c-tmux.conf", TMUX_CONF.as_bytes(), 0o644)?;
append_file_to_archive(&mut archive, "triple-c-scheduler", SCHEDULER.as_bytes(), 0o755)?;
append_file_to_archive(&mut archive, "triple-c-task-runner", TASK_RUNNER.as_bytes(), 0o755)?;
append_file_to_archive(&mut archive, "osc52-clipboard", OSC52_CLIPBOARD.as_bytes(), 0o755)?;
+1
View File
@@ -1,5 +1,6 @@
pub mod ca_certs;
pub mod client;
pub mod status;
pub mod events;
pub mod container;
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");
}
}
+28 -9
View File
@@ -374,6 +374,25 @@ fn refusal_message(e: &str) -> String {
}
}
/// The edge image: what `main` builds, ahead of `:latest` between releases.
const EDGE_IMAGE: &str = "ghcr.io/shadowdao/triple-c-sandbox:edge";
/// What the user is told when the agent never answers through the tunnel.
/// The usual cause is an image whose entrypoint predates AWS mode and never
/// starts the agent: the registry's `:latest` moves only on a release.
/// `image` is the one the task ran, when the caller knows it.
fn agent_silent_message(image: Option<&str>) -> String {
let which = match image {
Some(i) => format!("The image \"{}\"", i.escape_debug()),
None => "The workspace's image".to_string(),
};
format!(
"The workspace's agent did not answer through the tunnel. {which} may be older than this \
app's AWS support: the registry's :latest moves only when a release is cut. Until then, \
set Settings → Docker → Custom image to {EDGE_IMAGE}, then start the project again."
)
}
/// Wait for the agent behind `ep` to answer. A refusal (wrong token) is
/// final; silence is retried until [`HEALTH_TIMEOUT`].
async fn wait_healthy(ep: &AgentEndpoint) -> Result<(), String> {
@@ -385,11 +404,7 @@ async fn wait_healthy(ep: &AgentEndpoint) -> Result<(), String> {
Err(e) => return Err(refusal_message(&e)),
}
if tokio::time::Instant::now() + HEALTH_INTERVAL > deadline {
return Err(
"The workspace's agent did not answer through the tunnel. Check that the image \
includes triple-c-agent, then start the project again."
.into(),
);
return Err(agent_silent_message(None));
}
tokio::time::sleep(HEALTH_INTERVAL).await;
}
@@ -967,7 +982,8 @@ pub async fn start_core<T: TaskApi, W: WorkspaceApi, R: RuntimeApi, C: Connector
if created && stop_created(tasks, &task_cluster(&env, &task.arn), &task.arn).await {
(inp.on_task)(None);
}
Err(e)
// Name the image this start ran (the connector doesn't know it).
Err(if e == agent_silent_message(None) { agent_silent_message(Some(inp.image)) } else { e })
}
}
}
@@ -1621,7 +1637,7 @@ pub async fn reconcile(
settings: &AppSettings,
store: Arc<ProjectsStore>,
on_connect_warning: impl FnOnce(String) + Send + 'static,
on_ports_warning: impl FnOnce(String) + Send + 'static,
on_ports_warning: impl Fn(String) + Send + Sync + 'static,
on_interrupted_warning: impl FnOnce(String) + Send + 'static,
) {
let (connection_id, region, sdk) = match project_sdk(project, settings).await {
@@ -1652,8 +1668,11 @@ pub async fn reconcile(
Ok(true) => {
// Q6: the port mappings' forwards, before the
// (slower) credential copy.
if let Some(detail) = super::port_forwards::open_for_project(&store, &project.id).await {
on_ports_warning(detail);
let warn: super::port_forwards::PortsWarn = Arc::new(on_ports_warning);
if let Some(detail) =
super::port_forwards::open_for_project(&store, &project.id, Some(warn.clone())).await
{
warn(detail);
}
if let Err(e) = connect::apply_connect(&project, &settings).await {
log::warn!("Project {}: could not copy the credentials in: {e}", project.id);
+24
View File
@@ -93,6 +93,8 @@ struct Fake {
logs: Vec<String>,
role: Option<Knowable>,
connect_fails: bool,
/// The connector times out waiting for the agent (an image without it).
agent_silent: bool,
connect_tokens: Mutex<Vec<String>>,
secret_json: Mutex<Option<String>>,
/// A losing start rotates the secret's token while this one connects.
@@ -309,6 +311,9 @@ impl Connector for Fake {
v["TRIPLEC_AGENT_TOKEN"] = "the-losers-token".into();
*j = Some(v.to_string());
}
if self.agent_silent {
return Err(agent_silent_message(None));
}
if self.connect_fails {
return Err("session-manager-plugin was not found".into());
}
@@ -586,6 +591,25 @@ async fn a_tunnel_failure_stops_a_task_this_start_ran_but_never_an_attached_one(
);
}
#[tokio::test]
async fn a_silent_agent_names_the_image_and_the_edge_tag() {
let p = aws_project(StorageMode::Ephemeral);
let fake = Fake { run: Some(task(&p, "new", "RUNNING", true)), agent_silent: true, ..Default::default() };
let e = start(&fake, &p).await.0.err().unwrap();
assert!(e.contains(&format!("\"{REGISTRY_IMAGE}\"")), "{e}");
assert!(e.contains("older than this app's AWS support"), "{e}");
assert!(e.contains(":latest moves only when a release is cut"), "{e}");
assert!(e.contains("Settings → Docker → Custom image to ghcr.io/shadowdao/triple-c-sandbox:edge"), "{e}");
}
#[test]
fn the_silent_agent_message_escapes_the_image_name() {
let m = agent_silent_message(Some("evil\"\nimage"));
assert!(m.contains(r#""evil\"\nimage""#), "{m}");
assert!(!m.contains('\n'));
assert!(agent_silent_message(None).contains("The workspace's image may be older"));
}
#[tokio::test]
async fn a_user_who_has_not_joined_is_told_before_anything_is_written() {
let p = aws_project(StorageMode::Hybrid);
+1
View File
@@ -30,6 +30,7 @@
pub mod agent;
pub mod aws_host;
pub mod lifecycle;
pub mod persistent;
pub mod port_forwards;
pub mod sessions;
pub mod ssm;
+509
View File
@@ -0,0 +1,509 @@
//! Persistent terminals on AWS workspaces: every terminal tab (Claude and
//! bash) runs inside its own tmux server in the workspace, so it outlives the
//! app closing or the SSM tunnel dropping, and the app attaches to it again on
//! its next connect. Docker projects never come here.
//!
//! The rules, and why:
//!
//! * **One tmux server per tab**, `tmux -L triple-c-<session id>`. A server
//! takes its environment from the client that started it, so each tab's
//! server has exactly that tab's exec environment — the copy-at-connect
//! credential pairs (`aws_host::terminal_env`) travel in `ExecSpec.env` as
//! before and never on argv (`new-session -e` would put them in `ps`).
//! * **The tab's session id is the key.** The frontend's UUID, persisted per
//! project by `storage::terminal_store`, so a tab reopened after an app
//! restart gets the same id (its rename, `renamed_session_names`, too).
//! * **Opening** a tab is `new-session -A` (attach when it already exists);
//! **reattaching** is `attach-session`, which never creates: a session that
//! ended while the app was away must not come back as a fresh `claude`.
//! * **Closing a tab ends the session** (`kill-server`), as today. App exit, a
//! dropped tunnel and the agent's SIGHUP on a client that went away only
//! **detach** — the server daemonised into its own session, so the hangup
//! reaches the client alone.
//! * The tmux config is `/etc/triple-c/tmux.conf` (`container/triple-c-tmux.conf`):
//! no prefix key, no status line, output in xterm.js's own scrollback.
//! * An image without tmux or that config runs terminals the old way, with a
//! one-time notice per tunnel ([`plan`]).
//!
//! Everything in here runs through [`ContainerTarget`].
use std::collections::HashMap;
use std::sync::Mutex;
use std::time::Duration;
use serde::{Deserialize, Serialize};
use super::ContainerTarget;
/// The tmux config baked into the image (outside the seed-only home).
pub const TMUX_CONF: &str = "/etc/triple-c/tmux.conf";
/// Socket name prefix (`-L`): `/tmp/tmux-<uid>/triple-c-<key>`.
pub const SOCKET_PREFIX: &str = "triple-c-";
/// The outer terminal the tmux client talks to: xterm.js. The agent would
/// otherwise default a tty exec to `TERM=xterm`, and tmux would then
/// downsample every colour to 8.
pub const OUTER_TERM: &str = "TERM=xterm-256color";
/// tmux user option holding the tab's label, for a session another machine
/// opened (the app's own sessions keep theirs in the store).
pub const NAME_OPTION: &str = "@triple_c_name";
/// How much pane history a re-opened tab gets replayed.
pub const HISTORY_LINES: u32 = 5000;
/// Byte cap on that replay (escape sequences included).
pub const HISTORY_LIMIT: usize = 4 * 1024 * 1024;
/// Every small tmux exec (probe, list, has-session, kill).
pub const SMALL_EXEC_TIMEOUT: Duration = Duration::from_secs(20);
/// The notice an image without tmux gets, once per tunnel.
pub const NO_TMUX_NOTICE: &str = "This workspace image has no tmux, so terminals end when the app \
closes. Use an image built after persistent terminals were added (e.g. \
ghcr.io/shadowdao/triple-c-sandbox:edge).";
/// The longest tab label kept in tmux.
const MAX_NAME_CHARS: usize = 80;
/// What a terminal runs. Also the tmux session name (`-s`), so a session the
/// app does not know still says what it is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TerminalKind {
Claude,
Bash,
}
impl TerminalKind {
pub fn as_str(self) -> &'static str {
match self {
TerminalKind::Claude => "claude",
TerminalKind::Bash => "bash",
}
}
pub fn parse(s: &str) -> Option<Self> {
match s {
"claude" => Some(TerminalKind::Claude),
"bash" => Some(TerminalKind::Bash),
_ => None,
}
}
}
/// A session key is a socket name and an argv element: UUID characters only.
pub fn validate_key(key: &str) -> Result<(), String> {
if key.is_empty()
|| key.len() > 64
|| !key.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
{
return Err("Invalid terminal session id".to_string());
}
Ok(())
}
pub fn socket_name(key: &str) -> String {
format!("{SOCKET_PREFIX}{key}")
}
/// A tab label as tmux keeps it: no control characters (the listing is one
/// tab-separated line per session), at most [`MAX_NAME_CHARS`], and no
/// trailing `;` or `\` — tmux splits its argv into commands at an argument
/// that *ends* in `;`.
pub fn clean_name(name: Option<&str>) -> Option<String> {
let cleaned: String = name?
.chars()
.filter(|c| !c.is_control())
.take(MAX_NAME_CHARS)
.collect();
let cleaned = cleaned.trim().trim_end_matches([';', '\\']).trim().to_string();
(!cleaned.is_empty()).then_some(cleaned)
}
fn tmux_base(key: &str) -> Vec<String> {
vec![
"tmux".into(),
"-L".into(),
socket_name(key),
"-f".into(),
TMUX_CONF.into(),
]
}
/// The attached exec of a tab: `inner` (the unchanged command — the Claude
/// launch with its update prelude, or `bash -l`) as the only window of a new
/// tmux server, or an attach to it if it is already there. The label goes in
/// [`NAME_OPTION`] as a second tmux command. No environment value is ever an
/// argument here.
pub fn new_session_cmd(
key: &str,
kind: TerminalKind,
name: Option<&str>,
inner: Vec<String>,
) -> Result<Vec<String>, String> {
validate_key(key)?;
if inner.is_empty() {
return Err("No command to run".into());
}
// tmux would read an argument ending in `;` as the end of a command and
// run the rest as tmux commands. Our scripts end in a newline; refuse
// rather than guess if that ever changes.
if inner.iter().any(|a| a.ends_with(';')) {
return Err("A terminal command argument may not end with ';'".into());
}
let mut cmd = tmux_base(key);
cmd.extend([
"new-session".into(),
"-A".into(),
"-s".into(),
kind.as_str().into(),
"--".into(),
]);
cmd.extend(inner);
if let Some(n) = clean_name(name) {
cmd.extend([";".into(), "set-option".into(), "-q".into(), NAME_OPTION.into(), n]);
}
Ok(cmd)
}
/// Attach to an existing session; fails (and creates nothing) when it is gone.
pub fn attach_cmd(key: &str) -> Result<Vec<String>, String> {
validate_key(key)?;
let mut cmd = tmux_base(key);
cmd.push("attach-session".into());
Ok(cmd)
}
/// End one session: its server and everything in it (SIGHUP to the panes).
pub fn kill_cmd(key: &str) -> Result<Vec<String>, String> {
validate_key(key)?;
Ok(vec!["tmux".into(), "-L".into(), socket_name(key), "kill-server".into()])
}
/// The pane's history above the screen, colours kept, wrapped lines joined
/// (xterm.js rewraps them at its own width).
pub fn history_cmd(key: &str) -> Result<Vec<String>, String> {
validate_key(key)?;
Ok(vec![
"tmux".into(),
"-L".into(),
socket_name(key),
"capture-pane".into(),
"-p".into(),
"-e".into(),
"-J".into(),
"-S".into(),
format!("-{HISTORY_LINES}"),
"-E".into(),
"-1".into(),
])
}
/// Exit 0 when the image can keep terminals: tmux and our config.
pub fn probe_cmd() -> Vec<String> {
vec![
"sh".into(),
"-c".into(),
format!("command -v tmux >/dev/null 2>&1 && [ -r {TMUX_CONF} ]"),
]
}
/// The tmux socket directory of the exec's user, as tmux computes it.
const SOCKET_DIR: &str = r#"d="${TMUX_TMPDIR:-/tmp}/tmux-$(id -u)""#;
/// One line per running session: `key \t kind \t created \t attached \t name`.
/// A socket whose server is gone (tmux leaves the file) answers nothing and
/// is skipped.
pub fn list_cmd() -> Vec<String> {
vec![
"sh".into(),
"-c".into(),
format!(
r#"{SOCKET_DIR}
command -v tmux >/dev/null 2>&1 || exit 0
for s in "$d"/{SOCKET_PREFIX}*; do
[ -S "$s" ] || continue
n=${{s##*/}}
line=$(tmux -L "$n" display-message -p '#{{session_name}} #{{session_created}} #{{session_attached}} #{{{NAME_OPTION}}}' 2>/dev/null) || continue
printf '%s\t%s\n' "${{n#{SOCKET_PREFIX}}}" "$line"
done
exit 0"#
),
]
}
/// End every session (Stop, before the WIP push's snapshot), then wait —
/// bounded, 5 s — until the panes' processes (taken before the kill) and
/// the servers are gone, so a pane's last writes land before the snapshot.
/// The same script is `entrypoint.sh`'s `aws_end_terminals` and the idle
/// watcher's (a test pins them together).
pub fn end_all_cmd() -> Vec<String> {
vec!["sh".into(), "-c".into(), END_ALL_SCRIPT.into()]
}
/// See [`end_all_cmd`].
pub const END_ALL_SCRIPT: &str = r#"d="${TMUX_TMPDIR:-/tmp}/tmux-$(id -u)"
command -v tmux >/dev/null 2>&1 || exit 0
pids=""
for s in "$d"/triple-c-*; do
[ -S "$s" ] || continue
pids="$pids $(tmux -L "${s##*/}" list-panes -a -F '#{pane_pid}' 2>/dev/null)"
tmux -L "${s##*/}" kill-server 2>/dev/null
done
i=0
while [ $i -lt 50 ]; do
alive=""
for p in $pids; do kill -0 "$p" 2>/dev/null && alive=1; done
pgrep -u "$(id -u)" -f '^tmux -L triple-c-' >/dev/null 2>&1 && alive=1
[ -n "$alive" ] || break
sleep 0.1; i=$((i + 1))
done
exit 0"#;
/// A session found running in the workspace.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RunningSession {
pub key: String,
pub kind: TerminalKind,
pub created_unix: u64,
pub attached: bool,
pub name: Option<String>,
}
/// [`list_cmd`]'s output; lines that do not parse (a session someone made by
/// hand under our prefix) are skipped.
pub fn parse_list(out: &str) -> Vec<RunningSession> {
out.lines()
.filter_map(|line| {
let mut f = line.splitn(5, '\t');
let key = f.next()?.to_string();
validate_key(&key).ok()?;
let kind = TerminalKind::parse(f.next()?)?;
let created_unix = f.next()?.trim().parse().ok()?;
let attached = f.next()?.trim().parse::<u32>().ok()? > 0;
let name = clean_name(f.next());
Some(RunningSession { key, kind, created_unix, attached, name })
})
.collect()
}
/// The exec environment of a tmux client: the caller's pairs (copy-at-connect
/// credentials, which the server it starts inherits) plus [`OUTER_TERM`].
/// `TMUX`/`TMUX_TMPDIR` are dropped (and reserved as custom variable
/// names): either would point the client at another socket than the one the
/// app lists and ends.
pub fn client_env(mut env: Vec<String>) -> Vec<String> {
env.retain(|e| {
!e.starts_with("TERM=") && !e.starts_with("TMUX=") && !e.starts_with("TMUX_TMPDIR=")
});
env.push(OUTER_TERM.to_string());
env
}
// ───────────────────────────────────────────────────────────── probe cache
/// Per target id (an endpoint URL, new for every tunnel): does the image
/// keep terminals, and was the "no tmux" notice given yet.
#[derive(Debug, Clone, Copy, Default)]
struct Probe {
supported: bool,
noticed: bool,
}
fn probes() -> &'static Mutex<HashMap<String, Probe>> {
static P: std::sync::OnceLock<Mutex<HashMap<String, Probe>>> = std::sync::OnceLock::new();
P.get_or_init(Default::default)
}
/// Forget what was probed through `target_id` — a new tunnel registered on
/// it (`tunnels::register`), which may reach another task's image.
pub fn forget_probe(target_id: &str) {
probes().lock().unwrap_or_else(|e| e.into_inner()).remove(target_id);
}
/// Whether `target`'s image has tmux and the config; asked once per tunnel.
/// `None` when the probe could not run (asked again next time).
pub async fn probe(target: &ContainerTarget) -> Option<bool> {
if let Some(p) = probes().lock().unwrap_or_else(|e| e.into_inner()).get(target.id()) {
return Some(p.supported);
}
let res = tokio::time::timeout(
SMALL_EXEC_TIMEOUT,
target.exec_oneshot_background("claude", probe_cmd(), 4096),
)
.await;
let supported = match res {
Ok(Ok((_, code))) => code == 0,
Ok(Err(e)) => {
log::warn!("Could not ask the workspace whether it has tmux: {e}");
return None;
}
Err(_) => {
log::warn!("Asking the workspace whether it has tmux timed out");
return None;
}
};
probes()
.lock()
.unwrap_or_else(|e| e.into_inner())
.entry(target.id().to_string())
.or_insert(Probe { supported, noticed: false });
Some(supported)
}
/// [`probe`] for callers that must not guess: an unanswered probe is an
/// error (the caller retries), never "no tmux" — reading it as no would
/// prune remembered sessions and end tabs whose Claude still runs.
pub async fn supported(target: &ContainerTarget) -> Result<bool, String> {
probe(target)
.await
.ok_or_else(|| "The workspace did not answer whether it can keep terminals".to_string())
}
/// The "no tmux" notice, the first time it is asked for on a tunnel whose
/// probe said no (never for a probe that could not run).
fn take_notice(target_id: &str) -> Option<String> {
let mut p = probes().lock().unwrap_or_else(|e| e.into_inner());
let entry = p.get_mut(target_id)?;
if entry.supported || entry.noticed {
return None;
}
entry.noticed = true;
Some(NO_TMUX_NOTICE.to_string())
}
// ───────────────────────────────────────────────────────────────── launch
/// How a terminal is launched.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LaunchPlan {
pub cmd: Vec<String>,
pub env: Vec<String>,
/// Runs in tmux and outlives the app.
pub persistent: bool,
/// Say this once (no tmux in the image).
pub notice: Option<String>,
}
/// The pure decision: a persistent launch for an AWS project whose image
/// keeps terminals, the old launch otherwise.
#[allow(clippy::too_many_arguments)]
pub fn plan_with(
is_aws: bool,
supported: bool,
notice: Option<String>,
key: &str,
kind: TerminalKind,
name: Option<&str>,
inner: Vec<String>,
env: Vec<String>,
) -> Result<LaunchPlan, String> {
if !is_aws {
return Ok(LaunchPlan { cmd: inner, env, persistent: false, notice: None });
}
if !supported {
return Ok(LaunchPlan { cmd: inner, env, persistent: false, notice });
}
Ok(LaunchPlan {
cmd: new_session_cmd(key, kind, name, inner)?,
env: client_env(env),
persistent: true,
notice: None,
})
}
/// [`plan_with`] for a real target: probes (cached per tunnel) on AWS only.
pub async fn plan(
is_aws: bool,
target: &ContainerTarget,
key: &str,
kind: TerminalKind,
name: Option<&str>,
inner: Vec<String>,
env: Vec<String>,
) -> Result<LaunchPlan, String> {
if !is_aws {
return plan_with(false, false, None, key, kind, name, inner, env);
}
validate_key(key)?;
let ok = supported(target).await?;
let notice = if ok { None } else { take_notice(target.id()) };
plan_with(true, ok, notice, key, kind, name, inner, env)
}
// ─────────────────────────────────────────────────────── workspace actions
async fn small(target: &ContainerTarget, cmd: Vec<String>) -> Result<(String, i64), String> {
tokio::time::timeout(SMALL_EXEC_TIMEOUT, target.exec_oneshot_background("claude", cmd, 256 * 1024))
.await
.map_err(|_| "The workspace did not answer in time".to_string())?
}
/// The sessions running in the workspace (none on an image without tmux).
/// An `Err` (including an unanswered probe) says nothing about what runs.
pub async fn list(target: &ContainerTarget) -> Result<Vec<RunningSession>, String> {
if !supported(target).await? {
return Ok(Vec::new());
}
let (out, code) = small(target, list_cmd()).await?;
if code != 0 {
return Err(format!("Listing the workspace's terminals failed (exit {code})"));
}
Ok(parse_list(&out))
}
/// End the session `key` (closing its tab). Gone already is success.
pub async fn end(target: &ContainerTarget, key: &str) -> Result<(), String> {
small(target, kill_cmd(key)?).await.map(|_| ())
}
/// End every session in the workspace, bounded; logged, never an error (a
/// Stop must go on).
pub async fn end_all(target: &ContainerTarget) {
let res = tokio::time::timeout(
SMALL_EXEC_TIMEOUT,
target.exec_oneshot_as("claude", end_all_cmd(), Vec::new()),
)
.await;
match res {
Ok(Ok(_)) => {}
Ok(Err(e)) => log::warn!("Could not end the workspace's terminals: {e}"),
Err(_) => log::warn!("Ending the workspace's terminals timed out"),
}
}
/// The pane history of `key`, for a freshly opened tab; `None` when it can't
/// be read (the attach still goes ahead).
pub async fn history(target: &ContainerTarget, key: &str) -> Option<String> {
let cmd = history_cmd(key).ok()?;
let res = tokio::time::timeout(
SMALL_EXEC_TIMEOUT,
target.exec_oneshot_background("claude", cmd, HISTORY_LIMIT),
)
.await;
match res {
Ok(Ok((out, 0))) => Some(out),
_ => None,
}
}
/// What a fresh xterm is fed before the attach: the history, one line per
/// row, then `rows` newlines so all of it scrolls into xterm.js's scrollback
/// before tmux clears and draws the screen (an erase does not push lines
/// into xterm.js's scrollback).
pub fn replay_bytes(history: &str, rows: u16) -> Vec<u8> {
let body = history.trim_end_matches('\n');
if body.is_empty() {
return Vec::new();
}
let mut out = String::with_capacity(body.len() + rows as usize * 2 + 16);
for line in body.split('\n') {
out.push_str(line);
// A captured line ends with its own SGR state; reset so colour
// never bleeds into the padding.
out.push_str("\x1b[0m\r\n");
}
for _ in 0..rows {
out.push_str("\r\n");
}
out.into_bytes()
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod live_tests;
@@ -0,0 +1,157 @@
//! Persistent terminals end to end, through the real agent in a real
//! container: a tab's tmux server survives its client going away (the
//! agent's SIGHUP), is listed, keeps its own environment (and nothing secret
//! on argv), replays its history, reattaches, and ends.
//!
//! Needs a Docker daemon and an image whose entrypoint starts the agent and
//! that has tmux and `/etc/triple-c/tmux.conf`: `TRIPLEC_PERSIST_E2E_IMAGE`,
//! default `tc-tmux-e2e:latest` (e.g. the sandbox `:edge` image plus
//! `apt-get install tmux` and `COPY triple-c-tmux.conf /etc/triple-c/tmux.conf`).
//!
//! `cargo test host::persistent::live_tests -- --ignored`
use super::*;
use crate::host::{AgentEndpoint, ContainerTarget, ExecSpec};
use futures_util::StreamExt;
use std::process::Command;
use std::time::Duration;
use tokio::io::AsyncWriteExt;
fn docker_cli(args: &[&str]) -> String {
let out = Command::new("docker").args(args).output().expect("docker cli");
assert!(out.status.success(), "docker {:?}: {}", args, String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
/// Read an attached exec's output until `needle` shows up (or time runs out).
async fn read_until(out: &mut crate::host::ExecOutputStream, needle: &str, secs: u64) -> String {
let mut seen = String::new();
let deadline = tokio::time::Instant::now() + Duration::from_secs(secs);
while !seen.contains(needle) {
match tokio::time::timeout_at(deadline, out.next()).await {
Ok(Some(Ok(c))) => seen.push_str(&String::from_utf8_lossy(&c.into_bytes())),
_ => break,
}
}
seen
}
async fn start_agent_container(image: &str) -> (String, ContainerTarget) {
let token = format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple());
let name = format!("tc-persist-e2e-{}", uuid::Uuid::new_v4().simple());
docker_cli(&[
"run", "-d", "--init", "--name", &name, "-w", "/workspace",
"-e", &format!("TRIPLEC_AGENT_TOKEN={token}"),
"-e", "TRIPLEC_AGENT_ADDR=0.0.0.0:47900",
"-p", "127.0.0.1::47900",
image,
]);
let mapped = docker_cli(&["port", &name, "47900/tcp"]);
let port: u16 = mapped.lines().next().and_then(|l| l.rsplit(':').next()).and_then(|p| p.parse().ok()).unwrap();
let ip = docker_cli(&["inspect", "-f", "{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}", &name]);
let mut candidates = vec![AgentEndpoint::loopback(port, token.clone())];
for addr in ip.split_whitespace() {
let url = url::Url::parse(&format!("http://{addr}:47900/")).unwrap();
candidates.push(AgentEndpoint::new(url, token.clone()).unwrap());
}
for _ in 0..240 {
for ep in &candidates {
let t = ContainerTarget::Agent(ep.clone());
if t.is_running().await.unwrap_or(false) {
return (name, t);
}
}
tokio::time::sleep(Duration::from_millis(500)).await;
}
let logs = docker_cli(&["logs", "--tail", "40", &name]);
let _ = Command::new("docker").args(["rm", "-f", &name]).output();
panic!("agent never answered; logs:\n{logs}");
}
async fn scenario(t: &ContainerTarget) -> Result<(), String> {
let check = |ok: bool, what: &str| if ok { Ok(()) } else { Err(what.to_string()) };
check(probe(t).await == Some(true), "the image has tmux and the config")?;
let k1 = uuid::Uuid::new_v4().to_string();
let k2 = uuid::Uuid::new_v4().to_string();
let inner = |marker: &str| {
vec![
"bash".to_string(),
"-c".to_string(),
format!("printf 'secret=%s\\n' \"$TC_SECRET\"; for i in $(seq 1 300); do echo hist$i; done; echo {marker}; exec bash --norc\n"),
]
};
let p1 = plan_with(true, true, None, &k1, TerminalKind::Bash, Some("first"), inner("READY1"), vec!["TC_SECRET=alpha-not-real".into()])?;
let p2 = plan_with(true, true, None, &k2, TerminalKind::Claude, None, inner("READY2"), vec!["TC_SECRET=beta-not-real".into()])?;
// Open both tabs.
let mut a1 = t.attach(ExecSpec::new(p1.cmd.clone()).tty(true).env(p1.env.clone())).await?;
let seen = read_until(&mut a1.output, "READY1", 20).await;
check(seen.contains("secret=alpha-not-real"), &format!("tab 1 has its own env: {seen:?}"))?;
let mut a2 = t.attach(ExecSpec::new(p2.cmd.clone()).tty(true).env(p2.env.clone())).await?;
let seen = read_until(&mut a2.output, "READY2", 20).await;
check(seen.contains("secret=beta-not-real"), &format!("tab 2 has its own env: {seen:?}"))?;
// No secret on any command line in the workspace.
let (ps, _) = t.exec_oneshot_as("claude", vec!["ps".into(), "-eo".into(), "args".into()], vec![]).await?;
check(!ps.contains("alpha-not-real") && !ps.contains("beta-not-real"), &format!("secret on argv: {ps}"))?;
// The app goes away: drop the client. The agent SIGHUPs its process group.
drop(a1);
tokio::time::sleep(Duration::from_secs(2)).await;
let listed = list(t).await?;
let s1 = listed.iter().find(|s| s.key == k1).ok_or(format!("tab 1 survived its client: {listed:?}"))?;
check(!s1.attached && s1.kind == TerminalKind::Bash && s1.name.as_deref() == Some("first"), &format!("{s1:?}"))?;
let s2 = listed.iter().find(|s| s.key == k2).ok_or("tab 2 listed")?;
check(s2.attached && s2.kind == TerminalKind::Claude, &format!("{s2:?}"))?;
// History for a fresh tab, then reattach (never creating).
let h = history(t, &k1).await.ok_or("history readable")?;
check(h.contains("hist1\n") && h.contains("hist250"), &format!("history: {} bytes", h.len()))?;
let mut r1 = t.attach(ExecSpec::new(attach_cmd(&k1)?).tty(true).env(client_env(vec![]))).await?;
r1.input.write_all(b"echo back-$((40+2))\r").await.map_err(|e| e.to_string())?;
let seen = read_until(&mut r1.output, "back-42", 20).await;
check(seen.contains("back-42"), &format!("reattached and typing works: {seen:?}"))?;
// Still the original server's environment.
r1.input.write_all(b"echo env-$TC_SECRET\r").await.map_err(|e| e.to_string())?;
let seen = read_until(&mut r1.output, "env-alpha-not-real", 20).await;
check(seen.contains("env-alpha-not-real"), "the server kept its env")?;
// Attaching to a key that is gone fails and creates nothing.
let ghost = uuid::Uuid::new_v4().to_string();
let mut g = t.attach(ExecSpec::new(attach_cmd(&ghost)?).tty(true).env(client_env(vec![]))).await?;
let _ = read_until(&mut g.output, "\u{0}", 5).await;
check(!list(t).await?.iter().any(|s| s.key == ghost), "attach-session created nothing")?;
// A `claude` inside tmux is what the idle watcher sees; tmux is not.
r1.input.write_all(b"cp /bin/sleep /tmp/claude && /tmp/claude 30 &\r").await.map_err(|e| e.to_string())?;
tokio::time::sleep(Duration::from_secs(1)).await;
let (pg, code) = t.exec_oneshot_as("claude", vec!["pgrep".into(), "-x".into(), "claude".into()], vec![]).await?;
check(code == 0 && !pg.trim().is_empty(), "pgrep -x claude sees it")?;
let (_, code) = t.exec_oneshot_as("claude", vec!["pgrep".into(), "-x".into(), "tmux".into()], vec![]).await?;
check(code != 0, "no process is named plain `tmux` (servers are `tmux: server`)")?;
// Closing a tab ends it; Stop ends the rest.
end(t, &k1).await?;
let _ = read_until(&mut r1.output, "\u{0}", 5).await;
check(!list(t).await?.iter().any(|s| s.key == k1), "tab 1 ended")?;
end_all(t).await;
check(list(t).await?.is_empty(), "every terminal ended")?;
let (pg, _) = t.exec_oneshot_as("claude", vec!["sh".into(), "-c".into(), "pgrep -f '^tmux -L triple-c-' || true".into()], vec![]).await?;
check(pg.trim().is_empty(), &format!("no tmux left: {pg}"))?;
drop(a2);
Ok(())
}
#[tokio::test]
#[ignore = "needs a Docker daemon and an agent image with tmux (TRIPLEC_PERSIST_E2E_IMAGE)"]
async fn a_terminal_outlives_its_client_and_reattaches_through_the_agent() {
let image = std::env::var("TRIPLEC_PERSIST_E2E_IMAGE").unwrap_or_else(|_| "tc-tmux-e2e:latest".into());
let (name, target) = start_agent_container(&image).await;
let outcome = scenario(&target).await;
let logs = docker_cli(&["logs", "--tail", "20", &name]);
let _ = Command::new("docker").args(["rm", "-f", &name]).output();
if let Err(e) = outcome {
panic!("{e}\n--- container log tail ---\n{logs}");
}
}
+186
View File
@@ -0,0 +1,186 @@
use super::*;
const KEY: &str = "0b9c6f7e-1d2a-4c3b-9e8f-7a6b5c4d3e2f";
fn claude_inner() -> Vec<String> {
vec!["bash".into(), "-c".into(), "flock … claude update\nexec claude '-n' 'x'\n".into()]
}
#[test]
fn a_new_tab_runs_its_unchanged_command_as_the_only_window_of_its_own_server() {
let cmd = new_session_cmd(KEY, TerminalKind::Claude, Some("main"), claude_inner()).unwrap();
assert_eq!(
&cmd[..10],
&[
"tmux", "-L", &format!("triple-c-{KEY}"), "-f", "/etc/triple-c/tmux.conf",
"new-session", "-A", "-s", "claude", "--",
]
.map(String::from)
);
// The inner command is passed through as argv, untouched.
assert_eq!(&cmd[10..13], claude_inner().as_slice());
assert_eq!(&cmd[13..], &[";", "set-option", "-q", "@triple_c_name", "main"].map(String::from));
// Bash tabs say so in the session name; no label, no second command.
let bash = new_session_cmd(KEY, TerminalKind::Bash, None, vec!["bash".into(), "-l".into()]).unwrap();
assert_eq!(bash[8], "bash");
assert_eq!(bash.last().unwrap(), "-l");
assert!(!bash.contains(&";".to_string()));
}
#[test]
fn keys_are_socket_safe_and_an_argument_ending_in_a_semicolon_is_refused() {
for bad in ["", "../x", "a b", "a;b", "x/y", &"a".repeat(65)] {
assert!(validate_key(bad).is_err(), "{bad:?}");
assert!(new_session_cmd(bad, TerminalKind::Bash, None, vec!["bash".into()]).is_err());
assert!(attach_cmd(bad).is_err() && kill_cmd(bad).is_err() && history_cmd(bad).is_err());
}
assert!(validate_key(KEY).is_ok());
// tmux would run what follows as tmux commands.
let e = new_session_cmd(KEY, TerminalKind::Bash, None, vec!["sh".into(), "-c".into(), "x;".into()]);
assert!(e.is_err());
}
#[test]
fn a_label_is_cleaned_so_it_cannot_split_the_tmux_command_or_the_listing() {
assert_eq!(clean_name(Some("Bob's tab")).as_deref(), Some("Bob's tab"));
assert_eq!(clean_name(Some("a\tb\nc")).as_deref(), Some("abc"));
assert_eq!(clean_name(Some("x;")).as_deref(), Some("x"));
assert_eq!(clean_name(Some(r"x \;; ")).as_deref(), Some("x"));
assert_eq!(clean_name(Some(" ;; ")), None);
assert_eq!(clean_name(None), None);
assert_eq!(clean_name(Some(&"é".repeat(200))).unwrap().chars().count(), 80);
let cmd = new_session_cmd(KEY, TerminalKind::Claude, Some("evil;"), claude_inner()).unwrap();
assert_eq!(cmd.last().unwrap(), "evil");
assert!(cmd.iter().filter(|a| a.ends_with(';')).count() == 1, "only our separator: {cmd:?}");
}
#[test]
fn secrets_travel_in_the_exec_environment_never_on_argv() {
let env = vec!["ANTHROPIC_API_KEY=sk-test-not-real".to_string(), "TERM=xterm".to_string()];
let plan = plan_with(true, true, None, KEY, TerminalKind::Claude, None, claude_inner(), env).unwrap();
assert!(plan.persistent);
assert!(plan.cmd.iter().all(|a| !a.contains("sk-test-not-real")), "{:?}", plan.cmd);
assert!(!plan.cmd.iter().any(|a| a == "-e"), "no new-session -e");
// The server inherits the client's environment; the outer TERM is xterm.js's.
assert_eq!(plan.env, vec!["ANTHROPIC_API_KEY=sk-test-not-real".to_string(), OUTER_TERM.to_string()]);
}
#[test]
fn docker_projects_and_images_without_tmux_launch_as_before() {
let inner = claude_inner();
let env = vec!["A=1".to_string()];
// Docker: untouched, whatever the key looks like.
let docker = plan_with(false, true, None, "not a key", TerminalKind::Claude, None, inner.clone(), env.clone()).unwrap();
assert_eq!((docker.cmd, docker.env, docker.persistent, docker.notice), (inner.clone(), env.clone(), false, None));
// AWS without tmux: the old launch, plus the notice when it is due.
let old = plan_with(true, false, Some(NO_TMUX_NOTICE.into()), KEY, TerminalKind::Claude, None, inner.clone(), env.clone()).unwrap();
assert_eq!((old.cmd, old.env, old.persistent), (inner, env, false));
assert!(old.notice.unwrap().contains("no tmux"));
}
#[test]
fn the_no_tmux_notice_is_given_once_per_tunnel_and_never_for_an_unanswered_probe() {
let id = format!("http://127.0.0.1:1/{}/", uuid::Uuid::new_v4());
assert_eq!(take_notice(&id), None, "nothing probed: no notice");
probes().lock().unwrap().insert(id.clone(), Probe { supported: false, noticed: false });
assert!(take_notice(&id).is_some());
assert_eq!(take_notice(&id), None, "once");
// A new tunnel on the same port probes (and may notice) again.
forget_probe(&id);
assert!(probes().lock().unwrap().get(&id).is_none());
probes().lock().unwrap().insert(id.clone(), Probe { supported: true, noticed: false });
assert_eq!(take_notice(&id), None, "tmux present");
forget_probe(&id);
}
#[test]
fn the_listing_parses_and_skips_what_is_not_ours() {
let out = format!(
"{KEY}\tclaude\t1794954824\t1\tmain tab\n\
11111111-2222-3333-4444-555555555555\tbash\t1794954800\t0\t\n\
bad key!\tbash\t1\t0\t\n\
abc\tvim\t1\t0\t\n\
abc\tbash\tnot-a-time\t0\t\n"
);
let got = parse_list(&out);
assert_eq!(got.len(), 2);
assert_eq!(
got[0],
RunningSession { key: KEY.into(), kind: TerminalKind::Claude, created_unix: 1794954824, attached: true, name: Some("main tab".into()) }
);
assert!(!got[1].attached && got[1].name.is_none() && got[1].kind == TerminalKind::Bash);
}
#[test]
fn the_workspace_scripts_only_touch_our_sockets() {
for script in [list_cmd(), end_all_cmd()] {
assert_eq!(&script[..2], &["sh".to_string(), "-c".to_string()]);
assert!(script[2].contains("\"$d\"/triple-c-*"), "{}", script[2]);
assert!(script[2].contains("${TMUX_TMPDIR:-/tmp}/tmux-$(id -u)"));
}
let list = &list_cmd()[2];
assert!(list.contains("display-message -p '#{session_name}\t#{session_created}\t#{session_attached}\t#{@triple_c_name}'"), "{list}");
let end = &end_all_cmd()[2];
assert!(end.contains("kill-server") && end.contains("pgrep -u \"$(id -u)\" -f '^tmux -L triple-c-'"));
assert!(end.contains("[ $i -lt 50 ]"), "bounded wait");
assert_eq!(probe_cmd()[2], "command -v tmux >/dev/null 2>&1 && [ -r /etc/triple-c/tmux.conf ]");
// Reattach never creates; history is the part above the screen.
assert_eq!(attach_cmd(KEY).unwrap()[5], "attach-session");
assert!(!attach_cmd(KEY).unwrap().contains(&"-A".to_string()));
let h = history_cmd(KEY).unwrap();
assert!(h.ends_with(&["-S".into(), format!("-{HISTORY_LINES}"), "-E".into(), "-1".into()]));
}
#[test]
fn a_replay_pushes_the_whole_history_into_scrollback_before_tmux_draws() {
assert!(replay_bytes("", 30).is_empty());
assert!(replay_bytes("\n\n", 30).is_empty());
let b = String::from_utf8(replay_bytes("one\n\x1b[31mtwo\n", 3)).unwrap();
assert_eq!(b, "one\x1b[0m\r\n\x1b[31mtwo\x1b[0m\r\n\r\n\r\n\r\n");
}
/// The config tmux is started with, as the image ships it.
#[test]
fn the_image_ships_the_config_and_tmux() {
let conf = include_str!("../../../../../container/triple-c-tmux.conf");
for line in [
"set -g prefix None",
"unbind-key C-b",
"set -g status off",
"set -s escape-time 0",
"set -g mouse off",
"set -g remain-on-exit off",
"set -g destroy-unattached off",
"set -g window-size latest",
"set -g default-terminal \"tmux-256color\"",
r#"set -as terminal-overrides ",xterm*:smcup@:rmcup@:indn@:clear=\\E[H""#,
] {
assert!(conf.lines().any(|l| l == line), "missing: {line}");
}
let df = include_str!("../../../../../container/Dockerfile");
assert!(df.contains("COPY triple-c-tmux.conf /etc/triple-c/tmux.conf"));
assert!(df.lines().any(|l| l.trim() == "tmux \\"), "tmux in an apt layer");
}
/// An unanswered probe (a tunnel reopening) is an error, never "no tmux":
/// read as no, the listing would prune every remembered tab and a reattach
/// would end tabs whose Claude still runs.
#[tokio::test]
async fn an_unanswered_probe_is_an_error_not_a_no() {
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let target = ContainerTarget::Agent(
crate::host::AgentEndpoint::loopback(port, "x".repeat(64)),
);
assert_eq!(probe(&target).await, None);
assert!(supported(&target).await.is_err());
assert!(list(&target).await.is_err(), "no listing, so nothing to prune");
let planned = plan(true, &target, KEY, TerminalKind::Claude, None, claude_inner(), vec![]).await;
assert!(planned.is_err(), "not silently a non-persistent tab");
assert!(probes().lock().unwrap().get(target.id()).is_none(), "asked again next time");
}
#[test]
fn the_client_env_drops_what_would_point_tmux_elsewhere() {
let env = client_env(vec!["TMUX=/tmp/x,1,0".into(), "TMUX_TMPDIR=/elsewhere".into(), "A=1".into()]);
assert_eq!(env, vec!["A=1".to_string(), OUTER_TERM.to_string()]);
}
+89 -15
View File
@@ -11,7 +11,9 @@
//! ## Two differences from Docker, both deliberate
//!
//! * **It reaches the workspace's loopback, not its network interface**
//! (`socat … TCP:127.0.0.1:<port>` inside the task). So a mapping can
//! (`socat` to `127.0.0.1:<port>`, or `[::1]:<port>` when only an IPv6
//! loopback/wildcard socket listens there — see
//! [`crate::auth_bridge::tunnel::mapping_command`]). So a mapping can
//! reach a service that bound loopback precisely to be private — which is
//! why the agent's port, the browser view's range and (when the project
//! runs it) the gateway sidecar's [`GATEWAY_SIDECAR_PORT`] are refused.
@@ -46,7 +48,6 @@
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};
use crate::auth_bridge::proc_net::PortFamily;
use crate::auth_bridge::tunnel::PortForward;
use crate::auth_bridge::{RESERVED_CONTAINER_PORTS, RESERVED_HOST_PORTS};
use crate::models::PortMapping;
@@ -54,6 +55,18 @@ use crate::storage::projects_store::ProjectsStore;
use super::ContainerTarget;
/// Where a warning about a mapping goes after the open has returned: the
/// first connection that finds nothing listening in the workspace.
pub type PortsWarn = Arc<dyn Fn(String) + Send + Sync>;
/// What the user is told when a mapping's workspace port has no listener.
pub fn nothing_listening(host_port: u16, container_port: u16) -> String {
format!(
"localhost:{host_port}: nothing is listening on port {container_port} in the workspace \
(127.0.0.1 or ::1)"
)
}
/// What became of one mapping: `error` is `None` when its forward is open.
#[derive(Debug, Clone, PartialEq)]
pub struct PortForwardResult {
@@ -137,12 +150,23 @@ fn mapping_problem(m: &PortMapping, gateway_sidecar: bool) -> Option<String> {
None
}
/// A row the editor saved before both its ports were typed (the editor
/// saves on blur): nothing to check or forward yet, and nothing to say.
/// A row stored without both its ports (an older editor saved a new row as
/// 0 → 0 before anything was typed): nothing to check on save, and nothing
/// to forward — but a connect says so ([`incomplete_warning`]), never silent.
fn incomplete(m: &PortMapping) -> bool {
m.host_port == 0 || m.container_port == 0
}
/// The `ports` warning line for a stored row a connect skips as incomplete.
pub fn incomplete_warning(m: &PortMapping) -> String {
let port = |p: u16| if p == 0 { "?".to_string() } else { p.to_string() };
format!(
"{} → {}: incomplete, both ports are needed",
port(m.host_port),
port(m.container_port)
)
}
/// An AWS project's port mappings, checked in full: TCP only, no reserved
/// port (the browser view's two ranges, the agent's port, the gateway
/// sidecar's when it runs), and no host port twice. The first problem,
@@ -215,7 +239,7 @@ pub async fn open_for(
mappings: &[PortMapping],
) -> Vec<PortForwardResult> {
let mappings = mappings.to_vec();
open_latest(project_id, target, move || Some((mappings, false))).await
open_latest(project_id, target, None, move || Some((mappings, false))).await
}
/// Open the project's mappings into `target`, replacing the set it had.
@@ -232,21 +256,31 @@ pub async fn open_for(
pub async fn open_latest(
project_id: &str,
target: &ContainerTarget,
warn: Option<PortsWarn>,
read: impl FnOnce() -> Option<(Vec<PortMapping>, bool)> + Send,
) -> Vec<PortForwardResult> {
let plock = project_lock(project_id);
let _held = plock.lock().await;
let Some((mappings, gateway_sidecar)) = read() else {
log::info!("Project {project_id}: no longer an AWS project; closing its port forwards");
close_unlocked(project_id).await;
return Vec::new();
};
log::info!(
"Project {project_id}: opening port mappings into {} ({} stored, {} incomplete)",
target.id(),
mappings.len(),
mappings.iter().filter(|m| incomplete(m)).count()
);
// What can be forwarded, in order; the first row wins a host port.
let mut results: Vec<PortForwardResult> = Vec::new();
let mut wanted: Vec<(usize, u16, u16)> = Vec::new();
let mut taken = HashSet::new();
for m in mappings.iter().filter(|m| !incomplete(m)) {
let error = if let Some(problem) = mapping_problem(m, gateway_sidecar) {
for m in &mappings {
let error = if incomplete(m) {
Some(incomplete_warning(m))
} else if let Some(problem) = mapping_problem(m, gateway_sidecar) {
Some(problem)
} else if !taken.insert(m.host_port) {
Some(format!(
@@ -284,7 +318,12 @@ pub async fn open_latest(
opened.push(f);
continue;
}
match PortForward::bind_mapping(target.clone(), host_port, container_port, PortFamily::V4).await {
let on_refused = warn.clone().map(|w| {
let notice: crate::auth_bridge::tunnel::RefusedNotice =
Arc::new(move || w(nothing_listening(host_port, container_port)));
notice
});
match PortForward::bind_mapping(target.clone(), host_port, container_port, on_refused).await {
Ok(fwd) => {
if let Some(w) = &fwd.ipv6_warning {
log::warn!("Project {project_id}: port mapping {host_port}: {w}");
@@ -313,11 +352,25 @@ pub async fn open_latest(
// Checked *after* the set is registered: a tunnel close that ran before
// this sees it gone here; one that runs after removes it itself.
if !still_connected(project_id, target) {
log::warn!(
"Project {project_id}: the workspace's tunnel is no longer {} — closing the port forwards just opened",
target.id()
);
close_unlocked(project_id).await;
for r in results.iter_mut().filter(|r| r.error.is_none()) {
r.error = Some("the workspace disconnected".into());
}
}
for r in &results {
match &r.error {
None => log::info!(
"Project {project_id}: port mapping localhost:{} → workspace port {} is open",
r.mapping.host_port,
r.mapping.container_port
),
Some(e) => log::warn!("Project {project_id}: port mapping not open: {e}"),
}
}
results
}
@@ -337,6 +390,9 @@ pub async fn close(project_id: &str) {
async fn close_unlocked(project_id: &str) {
let set = lock().remove(project_id);
if let Some(set) = set {
if !set.forwards.is_empty() {
log::info!("Project {project_id}: closing {} port forward(s)", set.forwards.len());
}
shutdown_all(set.forwards).await;
}
}
@@ -352,20 +408,38 @@ pub async fn close_all() {
/// After a connect (or a save of the mappings while connected): open an
/// AWS project's mappings, **as stored when the open runs**, into its
/// connected workspace. The warning detail for the mappings that failed, if
/// any did; `None` as well for a local project (Docker publishes its own) or
/// a workspace that is not (or no longer) connected.
pub async fn open_for_project(store: &ProjectsStore, project_id: &str) -> Option<String> {
/// any did; `None` for a local project (Docker publishes its own), and for a
/// workspace that is not (or no longer) connected **unless the project is
/// Running** — mappings that should be open and aren't are never silent.
/// `warn` receives the later "nothing is listening" notices.
pub async fn open_for_project(
store: &ProjectsStore,
project_id: &str,
warn: Option<PortsWarn>,
) -> Option<String> {
let project = store.get(project_id).filter(|p| p.is_aws())?;
let target = ContainerTarget::Agent(super::tunnels::get_endpoint(&project.id)?);
let results = open_latest(project_id, &target, || {
let wanted = project.port_mappings.iter().filter(|m| !incomplete(m)).count();
let running = || {
store.get(project_id).is_some_and(|p| p.status == crate::models::ProjectStatus::Running)
};
let Some(endpoint) = super::tunnels::get_endpoint(&project.id) else {
log::info!("Project {project_id}: no tunnel to the workspace; {wanted} port mapping(s) not opened");
return (wanted > 0 && running()).then(|| {
"The workspace is not connected, so its port mappings were not opened. Start the \
project again."
.to_string()
});
};
let target = ContainerTarget::Agent(endpoint);
let results = open_latest(project_id, &target, warn, || {
store.get(project_id).filter(|p| p.is_aws()).map(|p| {
let gateway = p.aws.as_ref().is_some_and(|a| a.gateway_sidecar);
(p.port_mappings, gateway)
})
})
.await;
if !still_connected(project_id, &target) {
return None;
if !still_connected(project_id, &target) && !running() {
return None; // a Stop raced the open: nothing to say
}
failure_detail(&results)
}
+217 -7
View File
@@ -23,6 +23,8 @@ struct Fake {
requests: AtomicUsize,
/// The command of each attach.
cmds: std::sync::Mutex<Vec<Vec<String>>>,
/// Answer every attach as socat finding nothing listening.
refuse: std::sync::atomic::AtomicBool,
}
async fn attach_ws(State(f): State<Arc<Fake>>, ws: WebSocketUpgrade) -> Response {
@@ -41,6 +43,14 @@ async fn echo(f: Arc<Fake>, mut ws: WebSocket) {
.collect();
f.cmds.lock().unwrap().push(cmd);
let _ = ws.send(WsMessage::Text(r#"{"type":"started","exec_id":"a1"}"#.into())).await;
if f.refuse.load(Ordering::SeqCst) {
let mut err = vec![2u8];
err.extend_from_slice(b"socat[7] E connect(5, AF=2 127.0.0.1:8080, 16): Connection refused\n");
let _ = ws.send(WsMessage::Binary(err.into())).await;
let _ = ws.send(WsMessage::Text(r#"{"type":"exit","code":1}"#.into())).await;
let _ = ws.close().await;
return;
}
while let Some(Ok(msg)) = ws.recv().await {
match msg {
WsMessage::Binary(b) => {
@@ -129,7 +139,7 @@ async fn a_busy_host_port_fails_its_mapping_alone_and_the_other_forwards() {
assert_eq!(round_trip(free, b"ping").await, b"ping");
assert_eq!(
fake.cmds.lock().unwrap().as_slice(),
[vec!["socat".to_string(), "-".into(), "TCP:127.0.0.1:5432".into()]]
[crate::auth_bridge::tunnel::mapping_command(5432)]
);
// Stop / Remove / task death all close the tunnel: the mappings go too.
@@ -188,7 +198,8 @@ async fn udp_reserved_and_duplicate_mappings_are_refused_per_mapping() {
)
.await;
let errors: Vec<Option<&str>> = results.iter().map(|r| r.error.as_deref()).collect();
assert_eq!(errors.len(), 6, "an unfinished row is skipped: {errors:?}");
assert_eq!(errors.len(), 7, "{errors:?}");
assert_eq!(errors[6], Some("? → ?: incomplete, both ports are needed"), "skipped, not silently");
assert!(errors[0].unwrap().contains("only TCP"), "{errors:?}");
assert!(errors[1].is_none());
assert!(errors[2].unwrap().contains("another mapping"), "{errors:?}");
@@ -310,7 +321,7 @@ async fn overlapping_opens_converge_on_the_last_stored_set_without_false_errors(
let mine = sets[i % sets.len()].clone();
opens.push(tokio::spawn(async move {
go2.wait().await;
open_latest(&p2, &t2, move || {
open_latest(&p2, &t2, None, move || {
let mut s = s2.lock().unwrap();
*s = mine; // this save lands, then its open reads the store
Some((s.clone(), false))
@@ -352,7 +363,7 @@ async fn a_save_keeps_unchanged_forwards_and_their_live_connections() {
let r = open_for(&p, &target, &[tcp(a, 9090)]).await;
assert!(r[0].error.is_none(), "{:?}", r[0].error);
assert_eq!(round_trip(a, b"x").await, b"x");
assert_eq!(fake.cmds.lock().unwrap().last().unwrap()[2], "TCP:127.0.0.1:9090");
assert_eq!(fake.cmds.lock().unwrap().last().unwrap(), &crate::auth_bridge::tunnel::mapping_command(9090));
assert!(port_is_free(b));
tunnels::close(&p).await;
}
@@ -371,9 +382,9 @@ async fn a_stored_project_is_read_when_the_open_runs() {
let busy_port = busy.local_addr().unwrap().port();
project.port_mappings = vec![tcp(port, 8080), tcp(busy_port, 8081)];
let store = ProjectsStore::over_file_for_test(dir.path().join("projects.json"), vec![project]);
assert_eq!(open_for_project(&store, &p).await, None, "not connected: nothing, no warning");
assert_eq!(open_for_project(&store, &p, None).await, None, "not connected: nothing, no warning");
let (_target, _, _) = connected_agent(&p).await;
let warning = open_for_project(&store, &p).await.expect("the busy port is reported");
let warning = open_for_project(&store, &p, None).await.expect("the busy port is reported");
assert!(warning.contains(&busy_port.to_string()) && warning.contains("already in use"), "{warning}");
assert_eq!(open_ports(&p), vec![port]);
tunnels::close(&p).await;
@@ -386,7 +397,7 @@ async fn the_auth_bridges_forward_still_waits_for_a_client_to_speak() {
let p = pid("bridge");
let (target, fake, _) = connected_agent(&p).await;
let port = free_port();
let mut fwd = PortForward::bind(target, port, port, PortFamily::V4).await.unwrap();
let mut fwd = PortForward::bind(target, port, port, crate::auth_bridge::proc_net::PortFamily::V4).await.unwrap();
assert_eq!((fwd.port, fwd.container_port), (port, port));
let _client = TcpStream::connect(("127.0.0.1", port)).await.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
@@ -394,3 +405,202 @@ async fn the_auth_bridges_forward_still_waits_for_a_client_to_speak() {
fwd.shutdown().await;
tunnels::close(&p).await;
}
fn aws_project_in_store(p: &str, status: crate::models::ProjectStatus, mappings: Vec<PortMapping>) -> (tempfile::TempDir, ProjectsStore) {
let dir = tempfile::tempdir().unwrap();
let mut project = crate::models::Project::new("x".into(), vec![]);
project.id = p.to_string();
project.host_id = Some("h1".into());
project.aws_placement =
Some(crate::models::AwsPlacement { region: "us-west-2".into(), environment: "dev".into() });
project.aws = Some(Default::default());
project.status = status;
project.port_mappings = mappings;
let store = ProjectsStore::over_file_for_test(dir.path().join("projects.json"), vec![project]);
(dir, store)
}
#[tokio::test]
async fn a_running_project_whose_mappings_cannot_open_is_never_silent() {
use crate::models::ProjectStatus;
let p = pid("silent");
// Stopped (a save while stopped): nothing to open, nothing to say.
let (_d, store) = aws_project_in_store(&p, ProjectStatus::Stopped, vec![tcp(free_port(), 8080)]);
assert_eq!(open_for_project(&store, &p, None).await, None);
// Running with no tunnel: the mappings should be open and are not.
let (_d, store) = aws_project_in_store(&p, ProjectStatus::Running, vec![tcp(free_port(), 8080)]);
let w = open_for_project(&store, &p, None).await.expect("a warning");
assert!(w.contains("not connected"), "{w}");
// Only incomplete rows: nothing to say.
let (_d, store) = aws_project_in_store(&p, ProjectStatus::Running, vec![tcp(0, 8080)]);
assert_eq!(open_for_project(&store, &p, None).await, None);
}
#[tokio::test]
async fn a_connect_warns_about_an_incomplete_row_and_opens_the_rest() {
use crate::models::ProjectStatus;
// The reported case: an older editor stored a new row as 0 → 0. The
// connect used to skip it in silence.
let p = pid("incomplete");
let port = free_port();
let (_d, store) =
aws_project_in_store(&p, ProjectStatus::Stopped, vec![tcp(0, 0), tcp(port, 8080), tcp(9000, 0)]);
let (_target, _fake, _) = connected_agent(&p).await;
store.update_status(&p, ProjectStatus::Running).unwrap();
let w = open_for_project(&store, &p, None).await.expect("a ports warning");
assert_eq!(
w,
"? → ?: incomplete, both ports are needed\n9000 → ?: incomplete, both ports are needed"
);
assert_eq!(open_ports(&p), vec![port]);
tunnels::close(&p).await;
}
#[tokio::test]
async fn a_start_opens_a_listener_for_a_mapping_saved_before_it() {
use crate::models::ProjectStatus;
// The reported case: 8080 → 8080 saved while stopped, then a start
// registers the tunnel, sets Running and opens the mappings.
let p = pid("start");
let port = free_port();
let (_d, store) = aws_project_in_store(&p, ProjectStatus::Stopped, vec![tcp(port, 8080)]);
let (_target, fake, _) = connected_agent(&p).await;
store.update_status(&p, ProjectStatus::Running).unwrap();
assert_eq!(open_for_project(&store, &p, None).await, None);
assert_eq!(open_ports(&p), vec![port]);
assert_eq!(round_trip(port, b"ping").await, b"ping");
// Over IPv6 loopback too (`localhost` may resolve to ::1 first).
if let Ok(mut c) = TcpStream::connect(("::1", port)).await {
c.write_all(b"six").await.unwrap();
let mut buf = [0u8; 3];
c.read_exact(&mut buf).await.unwrap();
assert_eq!(&buf, b"six");
}
assert_eq!(fake.cmds.lock().unwrap()[0], crate::auth_bridge::tunnel::mapping_command(8080));
tunnels::close(&p).await;
assert!(port_is_free(port));
}
#[tokio::test]
async fn nothing_listening_in_the_workspace_is_reported_once_per_mapping() {
use crate::models::ProjectStatus;
let p = pid("refused");
let port = free_port();
let (_d, store) = aws_project_in_store(&p, ProjectStatus::Running, vec![tcp(port, 8080)]);
let (_target, fake, _) = connected_agent(&p).await;
fake.refuse.store(true, Ordering::SeqCst);
let seen = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
let s2 = seen.clone();
let warn: PortsWarn = Arc::new(move |d| s2.lock().unwrap().push(d));
assert_eq!(open_for_project(&store, &p, Some(warn)).await, None);
for _ in 0..3 {
let mut c = TcpStream::connect(("127.0.0.1", port)).await.unwrap();
let mut buf = Vec::new();
let _ = tokio::time::timeout(std::time::Duration::from_secs(5), c.read_to_end(&mut buf)).await;
}
let seen = seen.lock().unwrap().clone();
assert_eq!(seen, vec![nothing_listening(port, 8080)]);
assert!(seen[0].contains("nothing is listening on port 8080 in the workspace (127.0.0.1 or ::1)"));
tunnels::close(&p).await;
}
/// The reported case end to end against a **real** agent in a real
/// container (no SSM; the tunnel is registered by hand): a mapping saved
/// before the start, a Python server on `0.0.0.0:8080` (the user's), one on
/// `[::1]` only, and a port nothing listens on. Needs Docker and an image
/// whose entrypoint starts the agent (`TRIPLEC_AGENT_E2E_IMAGE`, default
/// `ghcr.io/shadowdao/triple-c-sandbox:edge`).
#[tokio::test]
#[ignore = "needs a Docker daemon and an image whose entrypoint starts triple-c-agent"]
async fn live_a_mapping_reaches_v4_and_v6_servers_in_a_real_workspace() {
use crate::models::ProjectStatus;
use std::process::Command;
use std::time::Duration;
let docker = |args: &[&str]| -> String {
let out = Command::new("docker").args(args).output().expect("docker cli");
assert!(out.status.success(), "docker {args:?}: {}", String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout).trim().to_string()
};
let image = std::env::var("TRIPLEC_AGENT_E2E_IMAGE")
.unwrap_or_else(|_| "ghcr.io/shadowdao/triple-c-sandbox:edge".into());
let token = format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple());
let name = format!("tc-ports-e2e-{}", uuid::Uuid::new_v4().simple());
docker(&[
"run", "-d", "--name", &name, "-w", "/workspace",
"-e", &format!("TRIPLEC_AGENT_TOKEN={token}"),
"-e", "TRIPLEC_AGENT_ADDR=0.0.0.0:47900",
"-p", "127.0.0.1::47900",
&image,
]);
let p = pid("live");
let outcome = async {
let mapped = docker(&["port", &name, "47900/tcp"]);
let lport: u16 = mapped.lines().next().and_then(|l| l.rsplit(':').next()).and_then(|x| x.parse().ok()).unwrap();
let ip = docker(&["inspect", "-f", "{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}", &name]);
let mut candidates = vec![AgentEndpoint::loopback(lport, token.clone())];
for a in ip.split_whitespace() {
candidates.push(AgentEndpoint::new(url::Url::parse(&format!("http://{a}:47900/")).unwrap(), token.clone()).unwrap());
}
let mut ep = None;
'wait: for _ in 0..240 {
for c in &candidates {
if ContainerTarget::Agent(c.clone()).is_running().await.unwrap_or(false) {
ep = Some(c.clone());
break 'wait;
}
}
tokio::time::sleep(Duration::from_millis(500)).await;
}
let ep = ep.ok_or("agent never answered")?;
docker(&["exec", "-d", "-u", "claude", &name, "python3", "-m", "http.server", "8080", "--bind", "0.0.0.0"]);
docker(&["exec", "-d", "-u", "claude", &name, "python3", "-m", "http.server", "8081", "--bind", "::1"]);
tokio::time::sleep(Duration::from_secs(2)).await;
let (h80, h81, h82) = (free_port(), free_port(), free_port());
let (_d, store) = aws_project_in_store(&p, ProjectStatus::Stopped, vec![tcp(h80, 8080), tcp(h81, 8081), tcp(h82, 8082)]);
// The start: tunnel registered, Running, then the open.
let mut t = tunnels::tests::fake_tunnel(lport, Arc::new(AtomicUsize::new(0)));
t.endpoint = ep;
tunnels::register(&p, t);
store.update_status(&p, ProjectStatus::Running).unwrap();
let seen = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
let s2 = seen.clone();
let warn: PortsWarn = Arc::new(move |d| s2.lock().unwrap().push(d));
if let Some(w) = open_for_project(&store, &p, Some(warn)).await {
return Err(format!("open warned: {w}"));
}
async fn get(addr: (&str, u16)) -> Result<String, String> {
let mut c = TcpStream::connect(addr).await.map_err(|e| format!("{addr:?}: {e}"))?;
c.write_all(b"GET / HTTP/1.0\r\nHost: localhost\r\n\r\n").await.map_err(|e| e.to_string())?;
let mut buf = Vec::new();
tokio::time::timeout(Duration::from_secs(20), c.read_to_end(&mut buf)).await.map_err(|_| "timeout".to_string())?.map_err(|e| e.to_string())?;
Ok(String::from_utf8_lossy(&buf).into_owned())
}
for (port, what) in [(h80, "0.0.0.0:8080"), (h81, "[::1]:8081")] {
for host in ["127.0.0.1", "::1"] {
let r = get((host, port)).await?;
if !r.starts_with("HTTP/1.0 200") {
return Err(format!("{what} via {host}:{port}: {r:?}"));
}
eprintln!("{what} via {host}:{port}: 200");
}
}
let r = get(("127.0.0.1", h82)).await?;
if !r.is_empty() {
return Err(format!("nothing listens on 8082, yet: {r:?}"));
}
tokio::time::sleep(Duration::from_millis(500)).await;
let seen = seen.lock().unwrap().clone();
if seen != vec![nothing_listening(h82, 8082)] {
return Err(format!("warnings: {seen:?}"));
}
Ok::<(), String>(())
}
.await;
tunnels::close(&p).await;
let logs = Command::new("docker").args(["logs", "--tail", "20", &name]).output().map(|o| String::from_utf8_lossy(&o.stdout).into_owned()).unwrap_or_default();
let _ = Command::new("docker").args(["rm", "-f", &name]).output();
if let Err(e) = outcome {
panic!("{e}\n--- container log tail ---\n{logs}");
}
}
+17 -2
View File
@@ -5,6 +5,7 @@
use futures_util::StreamExt;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tokio::io::AsyncWriteExt;
use tokio::sync::{mpsc, Mutex};
@@ -22,6 +23,10 @@ pub struct ExecSession {
pub target: ContainerTarget,
pub input_tx: mpsc::UnboundedSender<Vec<u8>>,
shutdown_tx: mpsc::Sender<()>,
/// Set when a new exec took this session id over (a persistent AWS
/// terminal re-attached): this one then ends without its exit callback,
/// so the tab is not told its session ended.
superseded: Arc<AtomicBool>,
}
impl ExecSession {
@@ -106,6 +111,8 @@ impl ExecSessionManager {
let (input_tx, mut input_rx) = mpsc::unbounded_channel::<Vec<u8>>();
let (shutdown_tx, mut shutdown_rx) = mpsc::channel::<()>(1);
let superseded = Arc::new(AtomicBool::new(false));
let superseded_reader = superseded.clone();
// Output reader task
let session_id_clone = session_id.to_string();
@@ -134,7 +141,9 @@ impl ExecSessionManager {
}
}
}
on_exit();
if !superseded_reader.load(Ordering::SeqCst) {
on_exit();
}
let _ = shutdown_tx_clone;
});
@@ -153,12 +162,18 @@ impl ExecSessionManager {
target: target.clone(),
input_tx,
shutdown_tx,
superseded,
};
self.sessions
let old = self
.sessions
.lock()
.await
.insert(session_id.to_string(), session);
if let Some(old) = old {
old.superseded.store(true, Ordering::SeqCst);
old.shutdown();
}
Ok(())
}
+82 -26
View File
@@ -198,27 +198,48 @@ fn sdk_error(e: &(dyn std::error::Error + 'static)) -> String {
// ── The plugin ───────────────────────────────────────────────────────────────
/// Find `session-manager-plugin`: `TRIPLEC_SSM_PLUGIN` if set, then `PATH`,
/// then where AWS's installers put it (the GUI app on macOS does not get the
/// shell's `PATH`, so the install locations are not optional).
/// The plugin's file name on this platform: what the bundle holds (Tauri strips the
/// `-<target-triple>` suffix of `bundle.externalBin` when it copies the sidecar in) and what
/// AWS's installers put on `PATH`.
const PLUGIN_FILE: &str =
if cfg!(windows) { "session-manager-plugin.exe" } else { "session-manager-plugin" };
const PLUGIN_INSTALL_HINT: &str = "The AWS Session Manager plugin (session-manager-plugin) is \
not installed. It is what connects to a workspace on AWS; install it from \
https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html";
/// Find `session-manager-plugin`, in this order:
///
/// 1. `TRIPLEC_SSM_PLUGIN`, if set (an error if it names no file — an explicit choice is never
/// silently replaced by another plugin);
/// 2. **the copy bundled with the app** (`bundle.externalBin`), beside the app's own
/// executable: `usr/bin` in the AppImage, `Contents/MacOS` in the macOS bundle, the install
/// directory on Windows (and `target/<profile>` under `tauri dev`, where tauri-build copies
/// it). A debug build's placeholder (`sidecar_placeholder`) is skipped;
/// 3. `PATH`;
/// 4. where AWS's installers put it (the GUI app on macOS does not get the shell's `PATH`, so
/// the install locations are not optional).
///
/// 3 and 4 remain for dev builds without a fetched sidecar.
pub fn find_plugin() -> Result<PathBuf, String> {
if let Some(p) = std::env::var_os("TRIPLEC_SSM_PLUGIN").filter(|p| !p.is_empty()) {
let p = PathBuf::from(p);
return if p.is_file() {
Ok(p)
} else {
Err(format!("TRIPLEC_SSM_PLUGIN names {}, which is not a file", p.display()))
};
}
let name = if cfg!(windows) { "session-manager-plugin.exe" } else { "session-manager-plugin" };
let on_path = std::env::var_os("PATH")
.map(|paths| std::env::split_paths(&paths).map(|d| d.join(name)).collect::<Vec<_>>())
.unwrap_or_default();
let installed: Vec<PathBuf> = if cfg!(windows) {
let exe_dir = std::env::current_exe()
.ok()
.and_then(|exe| exe.parent().map(Path::to_path_buf));
resolve_plugin(&PluginSearch {
override_path: std::env::var_os("TRIPLEC_SSM_PLUGIN"),
exe_dir,
path_var: std::env::var_os("PATH"),
install_dirs: plugin_install_dirs(),
})
}
/// Where AWS's installers put the plugin, in the order they are tried.
fn plugin_install_dirs() -> Vec<PathBuf> {
if cfg!(windows) {
["ProgramFiles", "ProgramFiles(x86)"]
.iter()
.filter_map(|v| std::env::var_os(v))
.map(|d| PathBuf::from(d).join(r"Amazon\SessionManagerPlugin\bin").join(name))
.map(|d| PathBuf::from(d).join(r"Amazon\SessionManagerPlugin\bin"))
.collect()
} else {
[
@@ -228,19 +249,54 @@ pub fn find_plugin() -> Result<PathBuf, String> {
"/usr/bin",
]
.iter()
.map(|d| Path::new(d).join(name))
.map(PathBuf::from)
.collect()
};
}
}
/// Everything [`find_plugin`] reads from the process, so the order is testable.
struct PluginSearch {
override_path: Option<std::ffi::OsString>,
exe_dir: Option<PathBuf>,
path_var: Option<std::ffi::OsString>,
install_dirs: Vec<PathBuf>,
}
fn resolve_plugin(search: &PluginSearch) -> Result<PathBuf, String> {
if let Some(p) = search.override_path.as_ref().filter(|p| !p.is_empty()) {
let p = PathBuf::from(p);
return if p.is_file() {
Ok(p)
} else {
Err(format!("TRIPLEC_SSM_PLUGIN names {}, which is not a file", p.display()))
};
}
if let Some(bundled) = search.exe_dir.as_ref().map(|d| d.join(PLUGIN_FILE)) {
if bundled.is_file() && !is_sidecar_placeholder(&bundled) {
return Ok(bundled);
}
}
let on_path = search
.path_var
.as_ref()
.map(|paths| std::env::split_paths(paths).map(|d| d.join(PLUGIN_FILE)).collect::<Vec<_>>())
.unwrap_or_default();
on_path
.into_iter()
.chain(installed)
.chain(search.install_dirs.iter().map(|d| d.join(PLUGIN_FILE)))
.find(|p| p.is_file())
.ok_or_else(|| {
"The AWS Session Manager plugin (session-manager-plugin) is not installed. It is \
what connects to a workspace on AWS; install it from \
https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html"
.to_string()
})
.ok_or_else(|| PLUGIN_INSTALL_HINT.to_string())
}
/// Whether `path` is the stand-in a debug build bundles when no real plugin was fetched.
/// Unreadable counts as "not a placeholder": the spawn then reports the real error.
fn is_sidecar_placeholder(path: &Path) -> bool {
use std::io::Read;
let mut head = [0u8; crate::sidecar_placeholder::MARKER.len()];
std::fs::File::open(path)
.and_then(|mut f| f.read_exact(&mut head))
.map(|()| crate::sidecar_placeholder::is_placeholder(&head))
.unwrap_or(false)
}
/// A running plugin process with a listener on the local port.
+132
View File
@@ -400,3 +400,135 @@ async fn the_keepalive_asks_for_health_without_a_token() {
assert!(req.starts_with("GET /v1/health HTTP/1.1\r\n"), "{req}");
assert!(!req.to_ascii_lowercase().contains("authorization"), "{req}");
}
// ── Finding the plugin ───────────────────────────────────────────────────────
mod plugin_resolution {
use super::super::{resolve_plugin, PluginSearch, PLUGIN_FILE, PLUGIN_INSTALL_HINT};
use std::path::{Path, PathBuf};
/// A directory holding a fake plugin (contents are never run).
fn dir_with_plugin(root: &Path, name: &str) -> PathBuf {
let d = root.join(name);
std::fs::create_dir_all(&d).unwrap();
std::fs::write(d.join(PLUGIN_FILE), b"\x7fELF fake plugin").unwrap();
d
}
fn search(
override_path: Option<&Path>,
exe_dir: Option<&Path>,
path: &[&Path],
install: &[&Path],
) -> PluginSearch {
PluginSearch {
override_path: override_path.map(|p| p.as_os_str().to_owned()),
exe_dir: exe_dir.map(Path::to_path_buf),
path_var: Some(std::env::join_paths(path).unwrap()),
install_dirs: install.iter().map(|p| p.to_path_buf()).collect(),
}
}
#[test]
fn the_override_wins_over_everything() {
let t = tempfile::tempdir().unwrap();
let chosen = t.path().join("my-plugin");
std::fs::write(&chosen, b"x").unwrap();
let bundled = dir_with_plugin(t.path(), "app");
let on_path = dir_with_plugin(t.path(), "path");
let s = search(Some(&chosen), Some(&bundled), &[&on_path], &[]);
assert_eq!(resolve_plugin(&s).unwrap(), chosen);
}
#[test]
fn an_override_naming_no_file_is_an_error_not_a_fallback() {
let t = tempfile::tempdir().unwrap();
let bundled = dir_with_plugin(t.path(), "app");
let s = search(Some(&t.path().join("missing")), Some(&bundled), &[], &[]);
let e = resolve_plugin(&s).unwrap_err();
assert!(e.contains("TRIPLEC_SSM_PLUGIN names"), "{e}");
}
#[test]
fn an_empty_override_is_ignored() {
let t = tempfile::tempdir().unwrap();
let bundled = dir_with_plugin(t.path(), "app");
let mut s = search(None, Some(&bundled), &[], &[]);
s.override_path = Some(std::ffi::OsString::new());
assert_eq!(resolve_plugin(&s).unwrap(), bundled.join(PLUGIN_FILE));
}
#[test]
fn the_bundled_sidecar_wins_over_path_and_installs() {
let t = tempfile::tempdir().unwrap();
let bundled = dir_with_plugin(t.path(), "app");
let on_path = dir_with_plugin(t.path(), "path");
let installed = dir_with_plugin(t.path(), "installed");
let s = search(None, Some(&bundled), &[&on_path], &[&installed]);
assert_eq!(resolve_plugin(&s).unwrap(), bundled.join(PLUGIN_FILE));
}
#[test]
fn without_a_sidecar_path_comes_before_the_install_locations() {
let t = tempfile::tempdir().unwrap();
let empty_app = t.path().join("app");
std::fs::create_dir_all(&empty_app).unwrap();
let first = t.path().join("path-first-empty");
std::fs::create_dir_all(&first).unwrap();
let on_path = dir_with_plugin(t.path(), "path");
let installed = dir_with_plugin(t.path(), "installed");
let s = search(None, Some(&empty_app), &[&first, &on_path], &[&installed]);
assert_eq!(resolve_plugin(&s).unwrap(), on_path.join(PLUGIN_FILE));
let s = search(None, Some(&empty_app), &[&first], &[&installed]);
assert_eq!(resolve_plugin(&s).unwrap(), installed.join(PLUGIN_FILE));
}
#[test]
fn a_debug_placeholder_beside_the_exe_is_skipped() {
let t = tempfile::tempdir().unwrap();
let app = t.path().join("app");
std::fs::create_dir_all(&app).unwrap();
std::fs::write(app.join(PLUGIN_FILE), crate::sidecar_placeholder::contents()).unwrap();
let on_path = dir_with_plugin(t.path(), "path");
let s = search(None, Some(&app), &[&on_path], &[]);
assert_eq!(resolve_plugin(&s).unwrap(), on_path.join(PLUGIN_FILE));
// And with nothing else installed, the install hint, not the placeholder.
let s = search(None, Some(&app), &[], &[]);
assert_eq!(resolve_plugin(&s).unwrap_err(), PLUGIN_INSTALL_HINT);
}
#[test]
fn a_directory_named_like_the_plugin_is_not_a_plugin() {
let t = tempfile::tempdir().unwrap();
let app = t.path().join("app");
std::fs::create_dir_all(app.join(PLUGIN_FILE)).unwrap();
let installed = dir_with_plugin(t.path(), "installed");
let s = search(None, Some(&app), &[], &[&installed]);
assert_eq!(resolve_plugin(&s).unwrap(), installed.join(PLUGIN_FILE));
}
#[test]
fn nothing_anywhere_is_the_install_hint() {
let t = tempfile::tempdir().unwrap();
let s = search(None, None, &[t.path()], &[t.path()]);
let e = resolve_plugin(&s).unwrap_err();
assert!(e.contains("is not installed") && e.contains("docs.aws.amazon.com"), "{e}");
}
#[test]
fn the_bundled_name_is_what_tauri_gives_the_sidecar() {
// tauri-build/-bundler strip "-<target-triple>" from bundle.externalBin's
// "binaries/session-manager-plugin"; the .exe stays on Windows.
let conf: serde_json::Value =
serde_json::from_str(include_str!("../../../tauri.conf.json")).unwrap();
let bins = conf["bundle"]["externalBin"].as_array().expect("bundle.externalBin");
let stems: Vec<&str> = bins
.iter()
.map(|b| b.as_str().unwrap().rsplit('/').next().unwrap())
.collect();
let expected = PLUGIN_FILE.trim_end_matches(".exe");
assert!(stems.contains(&expected), "{stems:?} has no {expected}");
}
}
+4
View File
@@ -125,6 +125,8 @@ pub fn register(project_id: &str, tunnel: LiveTunnel) -> Option<LiveTunnel> {
r.stopped.remove(tunnel.endpoint.base_url.as_str());
r.stopped.remove(&unattached_id(project_id));
r.pending.remove(project_id);
// A port reused by a new tunnel may reach another task's image.
super::persistent::forget_probe(tunnel.endpoint.base_url.as_str());
r.live.insert(project_id.to_string(), tunnel)
};
notify();
@@ -197,6 +199,8 @@ pub fn register_if_current(
r.stopped.remove(tunnel.endpoint.base_url.as_str());
r.stopped.remove(&unattached_id(project_id));
r.pending.remove(project_id);
// A port reused by a new tunnel may reach another task's image.
super::persistent::forget_probe(tunnel.endpoint.base_url.as_str());
r.live.insert(project_id.to_string(), tunnel)
};
notify();
+5
View File
@@ -15,6 +15,7 @@ mod logging;
mod marketplace;
mod models;
mod project_lock;
mod sidecar_placeholder;
mod storage;
pub mod url_open;
pub mod web_terminal;
@@ -541,6 +542,7 @@ pub fn run() {
.invoke_handler(tauri::generate_handler![
// Docker
commands::docker_commands::check_docker,
commands::docker_commands::check_docker_status,
commands::docker_commands::check_image_exists,
commands::docker_commands::build_image,
commands::docker_commands::get_container_info,
@@ -659,6 +661,9 @@ pub fn run() {
commands::terminal_commands::terminal_input,
commands::terminal_commands::terminal_resize,
commands::terminal_commands::close_terminal_session,
commands::terminal_commands::list_workspace_terminals,
commands::terminal_commands::reattach_terminal_session,
commands::terminal_commands::end_workspace_terminal,
commands::terminal_commands::paste_image_to_terminal,
commands::terminal_commands::upload_host_file_to_terminal,
commands::terminal_commands::start_audio_bridge,
+2
View File
@@ -7,6 +7,7 @@ pub mod migration;
pub mod note;
pub mod project;
pub mod settings_export;
pub mod terminal;
pub mod update_info;
pub use app_settings::*;
@@ -17,4 +18,5 @@ pub use migration::*;
pub use note::*;
pub use project::*;
pub use settings_export::*;
pub use terminal::*;
pub use update_info::*;
+40
View File
@@ -0,0 +1,40 @@
//! IPC shapes of persistent AWS terminals (`host::persistent`); mirrored in
//! `lib/types.ts`.
use serde::Serialize;
pub use crate::host::persistent::TerminalKind;
/// What `open_terminal_session` tells the tab it opened.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct OpenedTerminal {
/// Runs in tmux in the workspace and outlives the app (AWS only).
pub persistent: bool,
/// Something to say once (the image has no tmux).
pub notice: Option<String>,
}
/// A terminal session running in an AWS workspace.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct WorkspaceTerminal {
pub session_id: String,
pub kind: TerminalKind,
/// The app's label for it when it opened it, else the label tmux keeps.
pub name: Option<String>,
pub created_unix: u64,
/// A client (this app, another machine, the web terminal) is attached.
pub attached: bool,
/// This app opened it and reopens it on connect.
pub known: bool,
}
/// What `reattach_terminal_session` did.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case", tag = "outcome")]
pub enum ReattachOutcome {
/// Attached again; the tab keeps running.
Reattached { kind: TerminalKind, name: Option<String> },
/// The session is no longer running in the workspace (it ended, or the
/// workspace was replaced); it has been forgotten.
Ended,
}
+32
View File
@@ -0,0 +1,32 @@
//! The stand-in `build.rs` writes for the bundled `session-manager-plugin` sidecar in a
//! **debug** build that has no real one, and how the app recognises it.
//!
//! `bundle.externalBin` makes tauri-build fail outright when the per-target file is missing,
//! for `cargo test`, `cargo check` and `tauri dev` as much as for a release. The real binary
//! is built from AWS's pinned source by `scripts/build-ssm-plugin.sh` (`.ps1` on Windows), with
//! a downloaded Go toolchain; requiring that for every test run would put a Go build and the
//! network on the path of every `cargo test`. So debug builds get this placeholder instead, a
//! release build refuses it (`build.rs`), and `host::ssm::find_plugin` skips it and falls back to
//! an installed plugin.
//!
//! Shared by `build.rs` (through `#[path]`) and the app, so the two cannot disagree.
/// The first bytes of a placeholder. Not an executable format on any platform.
pub const MARKER: &[u8] = b"TRIPLE-C SSM PLUGIN PLACEHOLDER";
/// The whole placeholder file.
#[allow(dead_code)] // build.rs only
pub fn contents() -> Vec<u8> {
let mut v = MARKER.to_vec();
v.extend_from_slice(
b"\nNot the AWS Session Manager plugin. Debug builds get this when \
app/src-tauri/binaries has no real one; run scripts/build-ssm-plugin.sh \
(scripts/build-ssm-plugin.ps1 on Windows) to build the real plugin.\n",
);
v
}
/// Whether `bytes` (the start of a file) is a placeholder.
pub fn is_placeholder(bytes: &[u8]) -> bool {
bytes.starts_with(MARKER)
}
+1
View File
@@ -5,6 +5,7 @@ pub mod projects_store;
pub mod secure;
pub mod settings_crypto;
pub mod settings_store;
pub mod terminal_store;
#[allow(unused_imports)]
pub use projects_store::*;
+302
View File
@@ -0,0 +1,302 @@
//! Which persistent AWS terminals (`host::persistent`) the app has open, per
//! project: `<data_dir>/triple-c/terminal-sessions.json`.
//!
//! The session id is the tmux key, so this is what lets the app reopen a
//! project's tabs — same ids, kinds and labels — after it was closed. It is
//! a hint, never the truth: the workspace's own listing decides what is
//! running, and an entry it does not list is forgotten (`retain`).
//!
//! Not a `Project` field, for the reason notes are not: the webview saves
//! whole projects, and a tab opening while a Config save is in flight would
//! lose one of the two. Same free-function shape as `notes_store`, with
//! `_in` variants the tests drive against a temp directory. An unreadable
//! file is treated as empty: losing it costs only the automatic reopen (the
//! sessions still show in Project Home → Sessions).
use std::collections::{BTreeMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
use serde::{Deserialize, Serialize};
use crate::host::persistent::{validate_key, TerminalKind};
const FORMAT_VERSION: u32 = 1;
/// More tabs than anyone keeps open: a bound on what a bug could grow.
const MAX_PER_PROJECT: usize = 64;
/// One open persistent terminal.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PersistedTerminal {
/// The tab's session id, which is also the tmux key.
pub id: String,
pub kind: TerminalKind,
/// The label the tab was opened with (a rename lives in
/// `Project::renamed_session_names`, keyed by the same id).
pub name: Option<String>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
struct File {
version: u32,
#[serde(default)]
projects: BTreeMap<String, Vec<PersistedTerminal>>,
/// Tabs closed while the workspace could not be reached: their tmux
/// servers still run (a leftover Claude would keep a billed workspace
/// up), so they are ended at the next connect.
#[serde(default)]
pending_end: BTreeMap<String, Vec<String>>,
}
fn lock() -> &'static Mutex<()> {
static L: OnceLock<Mutex<()>> = OnceLock::new();
L.get_or_init(|| Mutex::new(()))
}
fn data_dir() -> Result<PathBuf, String> {
let dir = dirs::data_dir()
.ok_or_else(|| "Could not determine data directory".to_string())?
.join("triple-c");
fs::create_dir_all(&dir).map_err(|e| format!("Failed to create data directory: {e}"))?;
Ok(dir)
}
fn path_in(dir: &Path) -> PathBuf {
dir.join("terminal-sessions.json")
}
fn load_file(dir: &Path) -> File {
let path = path_in(dir);
let Ok(data) = fs::read_to_string(&path) else {
return File::default();
};
match serde_json::from_str::<File>(&data) {
Ok(f) => f,
Err(e) => {
log::warn!("{} is unreadable ({e}); starting with no remembered terminals", path.display());
File::default()
}
}
}
fn save_file(dir: &Path, mut file: File) -> Result<(), String> {
file.version = FORMAT_VERSION;
file.projects.retain(|_, v| !v.is_empty());
file.pending_end.retain(|_, v| !v.is_empty());
let path = path_in(dir);
let tmp = path.with_extension("json.tmp");
let data = serde_json::to_string_pretty(&file).map_err(|e| e.to_string())?;
fs::write(&tmp, data).map_err(|e| format!("Failed to write {}: {e}", tmp.display()))?;
fs::rename(&tmp, &path).map_err(|e| format!("Failed to commit {}: {e}", path.display()))
}
fn edit_in<T>(dir: &Path, f: impl FnOnce(&mut File) -> T) -> Result<T, String> {
let _g = lock().lock().unwrap_or_else(|e| e.into_inner());
let mut file = load_file(dir);
let out = f(&mut file);
save_file(dir, file)?;
Ok(out)
}
// ── `_in` variants (tests) ────────────────────────────────────────────────
pub fn list_in(dir: &Path, project_id: &str) -> Vec<PersistedTerminal> {
let _g = lock().lock().unwrap_or_else(|e| e.into_inner());
load_file(dir).projects.remove(project_id).unwrap_or_default()
}
pub fn add_in(dir: &Path, project_id: &str, t: PersistedTerminal) -> Result<(), String> {
validate_key(&t.id)?;
edit_in(dir, |f| {
let list = f.projects.entry(project_id.to_string()).or_default();
if let Some(existing) = list.iter_mut().find(|e| e.id == t.id) {
*existing = t;
} else if list.len() < MAX_PER_PROJECT {
list.push(t);
} else {
log::warn!("Project {project_id}: too many remembered terminals; not remembering another");
}
})
}
/// Forget `session_id`; returns the project it belonged to.
pub fn remove_in(dir: &Path, session_id: &str) -> Result<Option<String>, String> {
edit_in(dir, |f| {
let mut owner = None;
for (pid, list) in f.projects.iter_mut() {
let before = list.len();
list.retain(|e| e.id != session_id);
if list.len() != before {
owner = Some(pid.clone());
}
}
owner
})
}
/// The project and record of `session_id`, if remembered.
pub fn find_in(dir: &Path, session_id: &str) -> Option<(String, PersistedTerminal)> {
let _g = lock().lock().unwrap_or_else(|e| e.into_inner());
load_file(dir).projects.into_iter().find_map(|(pid, list)| {
list.into_iter().find(|e| e.id == session_id).map(|e| (pid, e))
})
}
/// Keep only the project's entries the workspace still runs.
pub fn retain_in(dir: &Path, project_id: &str, running: &HashSet<String>) -> Result<(), String> {
edit_in(dir, |f| {
if let Some(list) = f.projects.get_mut(project_id) {
list.retain(|e| running.contains(&e.id));
}
})
}
/// Forget all of a project's terminals (stopped, removed, moved off AWS):
/// remembered and pending-end alike.
pub fn clear_in(dir: &Path, project_id: &str) -> Result<(), String> {
edit_in(dir, |f| {
f.projects.remove(project_id);
f.pending_end.remove(project_id);
})
}
/// Remember to end `session_id` at the project's next connect.
pub fn add_pending_end_in(dir: &Path, project_id: &str, session_id: &str) -> Result<(), String> {
validate_key(session_id)?;
edit_in(dir, |f| {
let list = f.pending_end.entry(project_id.to_string()).or_default();
if !list.iter().any(|k| k == session_id) && list.len() < MAX_PER_PROJECT {
list.push(session_id.to_string());
}
})
}
/// The project's sessions waiting to be ended.
pub fn pending_end_in(dir: &Path, project_id: &str) -> Vec<String> {
let _g = lock().lock().unwrap_or_else(|e| e.into_inner());
load_file(dir).pending_end.remove(project_id).unwrap_or_default()
}
/// They were ended (or are gone): stop remembering them.
pub fn done_pending_end_in(dir: &Path, project_id: &str, ended: &[String]) -> Result<(), String> {
edit_in(dir, |f| {
if let Some(list) = f.pending_end.get_mut(project_id) {
list.retain(|k| !ended.contains(k));
}
})
}
// ── Public API ────────────────────────────────────────────────────────────
pub fn list(project_id: &str) -> Vec<PersistedTerminal> {
data_dir().map(|d| list_in(&d, project_id)).unwrap_or_default()
}
pub fn add(project_id: &str, t: PersistedTerminal) -> Result<(), String> {
add_in(&data_dir()?, project_id, t)
}
pub fn remove(session_id: &str) -> Result<Option<String>, String> {
remove_in(&data_dir()?, session_id)
}
pub fn find(session_id: &str) -> Option<(String, PersistedTerminal)> {
data_dir().ok().and_then(|d| find_in(&d, session_id))
}
pub fn retain(project_id: &str, running: &HashSet<String>) -> Result<(), String> {
retain_in(&data_dir()?, project_id, running)
}
pub fn add_pending_end(project_id: &str, session_id: &str) -> Result<(), String> {
add_pending_end_in(&data_dir()?, project_id, session_id)
}
pub fn pending_end(project_id: &str) -> Vec<String> {
data_dir().map(|d| pending_end_in(&d, project_id)).unwrap_or_default()
}
pub fn done_pending_end(project_id: &str, ended: &[String]) -> Result<(), String> {
done_pending_end_in(&data_dir()?, project_id, ended)
}
/// Best effort: a failure is logged (the next listing prunes anyway).
pub fn clear(project_id: &str) {
match data_dir().and_then(|d| clear_in(&d, project_id)) {
Ok(()) => {}
Err(e) => log::warn!("Could not forget project {project_id}'s terminals: {e}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn dir(tag: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("tc-term-store-{tag}-{}", uuid::Uuid::new_v4()));
fs::create_dir_all(&d).unwrap();
d
}
fn t(id: &str, kind: TerminalKind, name: Option<&str>) -> PersistedTerminal {
PersistedTerminal { id: id.into(), kind, name: name.map(str::to_string) }
}
#[test]
fn terminals_are_remembered_per_project_in_order_and_survive_a_reload() {
let d = dir("order");
add_in(&d, "p1", t("a-1", TerminalKind::Claude, Some("main"))).unwrap();
add_in(&d, "p1", t("b-2", TerminalKind::Bash, None)).unwrap();
add_in(&d, "p2", t("c-3", TerminalKind::Bash, None)).unwrap();
// Re-adding replaces in place (a reattach records it again).
add_in(&d, "p1", t("a-1", TerminalKind::Claude, Some("renamed"))).unwrap();
let p1 = list_in(&d, "p1");
assert_eq!(p1.iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), ["a-1", "b-2"]);
assert_eq!(p1[0].name.as_deref(), Some("renamed"));
assert_eq!(find_in(&d, "c-3").unwrap().0, "p2");
let raw = fs::read_to_string(path_in(&d)).unwrap();
assert!(raw.contains("\"version\": 1") && raw.contains("\"kind\": \"claude\""), "{raw}");
}
#[test]
fn closing_pruning_and_stopping_forget_entries() {
let d = dir("forget");
for id in ["a", "b", "c"] {
add_in(&d, "p", t(id, TerminalKind::Bash, None)).unwrap();
}
assert_eq!(remove_in(&d, "b").unwrap().as_deref(), Some("p"));
assert_eq!(remove_in(&d, "zzz").unwrap(), None);
retain_in(&d, "p", &HashSet::from(["c".to_string()])).unwrap();
assert_eq!(list_in(&d, "p"), vec![t("c", TerminalKind::Bash, None)]);
clear_in(&d, "p").unwrap();
assert!(list_in(&d, "p").is_empty());
}
#[test]
fn a_tab_closed_while_disconnected_is_ended_at_the_next_connect() {
let d = dir("pending");
add_pending_end_in(&d, "p", "a-1").unwrap();
add_pending_end_in(&d, "p", "a-1").unwrap();
add_pending_end_in(&d, "p", "b-2").unwrap();
add_pending_end_in(&d, "q", "c-3").unwrap();
assert!(add_pending_end_in(&d, "p", "../x").is_err());
assert_eq!(pending_end_in(&d, "p"), ["a-1", "b-2"]);
done_pending_end_in(&d, "p", &["a-1".to_string()]).unwrap();
assert_eq!(pending_end_in(&d, "p"), ["b-2"]);
clear_in(&d, "p").unwrap();
assert!(pending_end_in(&d, "p").is_empty());
assert_eq!(pending_end_in(&d, "q"), ["c-3"], "per project");
}
#[test]
fn a_bad_key_is_refused_and_a_corrupt_file_reads_as_empty() {
let d = dir("bad");
assert!(add_in(&d, "p", t("../x", TerminalKind::Bash, None)).is_err());
fs::write(path_in(&d), "{not json").unwrap();
assert!(list_in(&d, "p").is_empty());
// …and is replaced by the next write.
add_in(&d, "p", t("ok", TerminalKind::Bash, None)).unwrap();
assert_eq!(list_in(&d, "p").len(), 1);
}
}
+94 -15
View File
@@ -85,8 +85,9 @@ pub async fn handle_connection(socket: WebSocket, state: Arc<WebTerminalState>)
// Channel for sending messages from session output tasks → WS writer
let (out_tx, mut out_rx) = mpsc::unbounded_channel::<ServerMessage>();
// Track session IDs owned by this connection for cleanup
let owned_sessions: Arc<tokio::sync::Mutex<Vec<String>>> =
// Session ids owned by this connection, with whether each is a
// persistent AWS terminal (tmux). A disconnect only detaches those.
let owned_sessions: Arc<tokio::sync::Mutex<Vec<(String, bool)>>> =
Arc::new(tokio::sync::Mutex::new(Vec::new()));
// Writer task: serializes ServerMessages and sends as WS text frames
@@ -186,20 +187,27 @@ pub async fn handle_connection(socket: WebSocket, state: Arc<WebTerminalState>)
}
ClientMessage::Close { session_id } => {
state.exec_manager.close_session(&session_id).await;
// Remove from owned list
owned_sessions
.lock()
.await
.retain(|id| id != &session_id);
// Only a session this connection opened: the id is the tmux
// key of a persistent AWS terminal, which a close ends.
let owned = {
let mut owned = owned_sessions.lock().await;
let found = owned.iter().find(|(id, _)| id == &session_id).map(|(_, p)| *p);
owned.retain(|(id, _)| id != &session_id);
found
};
if let Some(persistent) = owned {
close_owned(&state, &session_id, persistent).await;
}
}
}
}
// Connection closed — clean up all owned sessions
// Connection closed — clean up all owned sessions. A persistent AWS
// terminal is only detached, like the desktop app's on exit: it keeps
// running and Project Home → Sessions lists it.
log::info!("Web terminal WebSocket disconnected, cleaning up sessions");
let sessions = owned_sessions.lock().await.clone();
for session_id in sessions {
for (session_id, _) in sessions {
state.exec_manager.close_session(&session_id).await;
}
@@ -278,13 +286,41 @@ fi
vec!["bash".to_string(), "-c".to_string(), script]
}
/// A Close from the client: detach, and end a persistent terminal's tmux
/// server (closing a tab is what ends one, as in the desktop app).
async fn close_owned(state: &WebTerminalState, session_id: &str, persistent: bool) {
let target = state.exec_manager.get_target(session_id).await.ok();
state.exec_manager.close_session(session_id).await;
let Some(target) = target else { return };
let Some(key) = tmux_key_of(session_id) else { return };
if persistent {
if let Err(e) = crate::host::persistent::end(&target, key).await {
log::warn!("Web terminal: could not end terminal {session_id}: {e}");
}
}
}
/// The web terminal's exec ids are `web-<tmux key>`, never the bare key: the
/// desktop app attaches to a workspace terminal under the bare key in the
/// same `ExecSessionManager`, and sharing the id would make either front
/// end's attach take over (or its close/disconnect end) the other's exec.
const WEB_EXEC_PREFIX: &str = "web-";
fn web_exec_id(key: &str) -> String {
format!("{WEB_EXEC_PREFIX}{key}")
}
fn tmux_key_of(exec_id: &str) -> Option<&str> {
exec_id.strip_prefix(WEB_EXEC_PREFIX)
}
/// Open a new terminal session for a project.
async fn handle_open(
state: &WebTerminalState,
project_id: &str,
session_type: Option<&str>,
out_tx: &mpsc::UnboundedSender<ServerMessage>,
owned_sessions: &Arc<tokio::sync::Mutex<Vec<String>>>,
owned_sessions: &Arc<tokio::sync::Mutex<Vec<(String, bool)>>>,
) -> Result<(), String> {
let project = state
.projects_store
@@ -308,9 +344,33 @@ async fn handle_open(
// environment (never the agent's). Empty for everything else.
let env = crate::host::aws_host::terminal_env(&project, &state.settings_store.get()).await;
let session_id = uuid::Uuid::new_v4().to_string();
let key = uuid::Uuid::new_v4().to_string();
let session_id = web_exec_id(&key);
let project_name = project.name.clone();
// AWS: in its own tmux server, like the desktop app's tabs
// (`host::persistent`), so a dropped connection only detaches it. Not
// remembered for the desktop app to reopen: it shows in Project Home →
// Sessions as a session running in the workspace.
let kind = if session_type == Some("bash") {
crate::host::persistent::TerminalKind::Bash
} else {
crate::host::persistent::TerminalKind::Claude
};
let plan = crate::host::persistent::plan(
project.is_aws(),
&container,
&key,
kind,
Some("web terminal"),
cmd,
env,
)
.await?;
if let Some(notice) = plan.notice.clone() {
let _ = out_tx.send(ServerMessage::Error { message: notice });
}
// Set up output routing through the WS channel
let out_tx_output = out_tx.clone();
let session_id_output = session_id.clone();
@@ -335,15 +395,15 @@ async fn handle_open(
.create_session(
&container,
&session_id,
cmd,
env,
plan.cmd,
plan.env,
on_output,
on_exit,
)
.await?;
// Track this session for cleanup on disconnect
owned_sessions.lock().await.push(session_id.clone());
owned_sessions.lock().await.push((session_id.clone(), plan.persistent));
let _ = out_tx.send(ServerMessage::Opened {
session_id,
@@ -357,3 +417,22 @@ async fn handle_open(
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
/// A desktop reattach (exec id = the bare key) and the web terminal's own
/// exec of the same tmux session never share an `ExecSessionManager` id,
/// in either direction, and the web side maps back to the right key.
#[test]
fn web_and_desktop_execs_of_one_terminal_never_share_an_id() {
let key = "0b9c6f7e-1d2a-4c3b-9e8f-7a6b5c4d3e2f";
let web = web_exec_id(key);
assert_ne!(web, key, "a desktop reattach must not supersede the web exec");
assert_eq!(tmux_key_of(&web), Some(key));
// A desktop exec id is not one the web side would end or detach.
assert_eq!(tmux_key_of(key), None);
crate::host::persistent::validate_key(&web).unwrap();
}
}
+6
View File
@@ -36,6 +36,12 @@
"icons/icon.icns",
"icons/icon.png"
],
"externalBin": [
"binaries/session-manager-plugin"
],
"resources": {
"THIRD_PARTY_NOTICES": "THIRD_PARTY_NOTICES"
},
"linux": {
"appimage": {
"bundleMediaFramework": true
+6 -2
View File
@@ -6,6 +6,7 @@ import TopBar from "./components/layout/TopBar";
import StatusBar from "./components/layout/StatusBar";
import NotesDock from "./components/layout/NotesDock";
import TerminalView from "./components/terminal/TerminalView";
import { dockerFailLabel } from "./lib/dockerStatus";
import DockerInstallDialog from "./components/DockerInstallDialog";
import ProjectHome from "./components/projects/home/ProjectHome";
import AddProjectDialog from "./components/projects/AddProjectDialog";
@@ -24,6 +25,7 @@ import { useKeyboardShortcuts } from "./hooks/useKeyboardShortcuts";
import { useMarketplaceSyncToasts } from "./hooks/useMarketplace";
import { useProjectStatusEvents } from "./hooks/useProjectStatusEvents";
import { useWorkspaceWarnings } from "./hooks/useWorkspaceWarnings";
import { usePersistentTerminals } from "./hooks/usePersistentTerminals";
import MarketplaceView from "./components/marketplace/MarketplaceView";
import { useAppState, isHomeTab, tabKeyId, homeTabKey, MARKETPLACE_TAB_KEY } from "./store/appState";
import { reconcileAwsProjects, reconcileProjectStatuses } from "./lib/tauri-commands";
@@ -79,6 +81,7 @@ export default function App() {
useMarketplaceSyncToasts();
useProjectStatusEvents();
useWorkspaceWarnings();
usePersistentTerminals();
// Initialize on mount
useEffect(() => {
@@ -213,9 +216,10 @@ export default function App() {
* tracks and ends in a real button.
*/
function WelcomeScreen() {
const { dockerAvailable, imageExists, projects, openProjectHome } = useAppState(
const { dockerAvailable, dockerStatus, imageExists, projects, openProjectHome } = useAppState(
useShallow((s) => ({
dockerAvailable: s.dockerAvailable,
dockerStatus: s.dockerStatus,
imageExists: s.imageExists,
projects: s.projects,
openProjectHome: s.openProjectHome,
@@ -233,7 +237,7 @@ function WelcomeScreen() {
label: "Docker detected",
state: dockerAvailable,
pendingLabel: "Checking for Docker…",
failLabel: "Docker not available",
failLabel: dockerFailLabel(dockerStatus),
},
{
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 { useInstallHelper } from "../hooks/useInstallHelper";
import { openUrlExternal } from "../lib/tauri-commands";
import type { DockerStatus } from "../lib/types";
import { useDocker } from "../hooks/useDocker";
import Modal from "./ui/Modal";
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 {
onClose: () => void;
}
@@ -13,7 +82,7 @@ type Phase = "idle" | "installing" | "done" | "error";
export default function DockerInstallDialog({ onClose }: Props) {
const { options, loadOptions, runInstall } = useInstallHelper();
const { checkDocker } = useDocker();
const { checkDocker, dockerStatus } = useDocker();
const [showManual, setShowManual] = useState(false);
const [phase, setPhase] = useState<Phase>("idle");
const [log, setLog] = useState<string[]>([]);
@@ -23,6 +92,13 @@ export default function DockerInstallDialog({ onClose }: Props) {
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 () => {
setPhase("installing");
setLog([]);
@@ -52,6 +128,50 @@ export default function DockerInstallDialog({ onClose }: Props) {
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) {
return null;
}
@@ -61,7 +181,7 @@ export default function DockerInstallDialog({ onClose }: Props) {
return (
<Modal
title="Docker not detected"
title="Docker is not installed"
onClose={onClose}
widthClassName="w-[34rem]"
// 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
you, or you can follow the official instructions.
</p>
{awsLine}
<div className="mb-4">{endpointLine}</div>
{phase === "idle" && (
<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 { useShallow } from "zustand/react/shallow";
import MainTabs from "./MainTabs";
@@ -9,9 +10,10 @@ import HelpDialog from "./HelpDialog";
import StatusIndicator, { type StatusTone } from "../ui/StatusIndicator";
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 => ({
dockerAvailable: s.dockerAvailable,
dockerStatus: s.dockerStatus,
imageExists: s.imageExists,
updateInfo: s.updateInfo,
imageUpdateInfo: s.imageUpdateInfo,
@@ -76,7 +78,7 @@ export default function TopBar() {
<HealthDot
state={dockerAvailable}
okLabel="Docker"
failLabel="Docker unavailable"
failLabel={dockerFailLabel(dockerStatus)}
pendingLabel="Docker — checking"
/>
<HealthDot
@@ -0,0 +1,130 @@
import { describe, it, expect, vi } from "vitest";
import { render, screen, fireEvent, act } from "@testing-library/react";
import PortMappingsEditor from "./PortMappingsEditor";
import type { PortMapping } from "../../lib/types";
const tcp = (host_port: number, container_port: number): PortMapping => ({
host_port,
container_port,
protocol: "tcp",
});
function setup(initial: PortMapping[], extra: { tcpOnly?: boolean } = {}) {
const onSave = vi.fn().mockResolvedValue(true);
const view = render(
<PortMappingsEditor portMappings={initial} disabled={false} onSave={onSave} {...extra} />,
);
const rerender = (next: PortMapping[]) =>
view.rerender(
<PortMappingsEditor portMappings={next} disabled={false} onSave={onSave} {...extra} />,
);
return { onSave, rerender };
}
const host = (n = 1) => screen.getByLabelText(`Host port ${n}`) as HTMLInputElement;
const container = (n = 1) => screen.getByLabelText(`Container port ${n}`) as HTMLInputElement;
function type(el: HTMLInputElement, value: string) {
act(() => el.focus());
fireEvent.change(el, { target: { value } });
}
describe("PortMappingsEditor", () => {
it("keeps typed ports when the project refreshes mid-edit (the reported 0/0 save)", () => {
// A stored half-row, as the old "+ Add" saved it, then a project refresh
// (status event, save response, list reload) hands over a new-but-equal
// array while the user is typing.
const { onSave, rerender } = setup([tcp(0, 0)]);
type(host(), "8080");
rerender([tcp(0, 0)]);
type(container(), "8080");
rerender([tcp(0, 0)]);
expect(host().value).toBe("8080");
expect(container().value).toBe("8080");
fireEvent.blur(container());
expect(onSave).toHaveBeenLastCalledWith([tcp(8080, 8080)]);
});
it("keeps typed ports when its own earlier save's response arrives mid-edit", () => {
const { onSave, rerender } = setup([]);
fireEvent.click(screen.getByRole("button", { name: /add port mapping/i }));
type(host(), "8080");
fireEvent.blur(host());
type(container(), "80");
// A stale echo of an older stored value must not replace the edit in focus.
rerender([]);
type(container(), "8080");
fireEvent.blur(container());
expect(onSave).toHaveBeenLastCalledWith([tcp(8080, 8080)]);
expect(container().value).toBe("8080");
});
it("does not save a newly added empty row", () => {
const { onSave } = setup([]);
fireEvent.click(screen.getByRole("button", { name: /add port mapping/i }));
expect(onSave).not.toHaveBeenCalled();
expect(host()).toHaveFocus();
expect(screen.getByText(/fill in both ports/i)).toBeInTheDocument();
});
it("does not present an empty row as a filled-in mapping (no port-number placeholder)", () => {
// The reported case: the empty row's "8080" placeholders read as 8080 → 8080.
setup([]);
fireEvent.click(screen.getByRole("button", { name: /add port mapping/i }));
for (const el of [host(), container()]) {
expect(el.value).toBe("");
expect(el.placeholder).not.toMatch(/\d/);
}
expect(screen.getByText(/isn't saved or active/i)).toBeInTheDocument();
});
it("never saves a half-filled row, and saves it once both ports are in", () => {
const { onSave } = setup([tcp(3000, 3000)]);
fireEvent.click(screen.getByRole("button", { name: /add port mapping/i }));
type(host(2), "8080");
fireEvent.blur(host(2));
expect(onSave).not.toHaveBeenCalled();
expect(screen.getByText(/fill in both ports/i)).toBeInTheDocument();
type(container(2), "9090");
fireEvent.blur(container(2));
expect(onSave).toHaveBeenLastCalledWith([tcp(3000, 3000), tcp(8080, 9090)]);
expect(screen.queryByText(/fill in both ports/i)).not.toBeInTheDocument();
});
it("shows a stored incomplete row as incomplete", () => {
setup([tcp(0, 0), tcp(8080, 8080)]);
expect(screen.getAllByText(/fill in both ports/i)).toHaveLength(1);
expect(host(1).value).toBe("");
});
it("refuses an out-of-range port without saving it", () => {
const { onSave } = setup([]);
fireEvent.click(screen.getByRole("button", { name: /add port mapping/i }));
type(host(), "70000");
type(container(), "80");
fireEvent.blur(container());
expect(onSave).not.toHaveBeenCalled();
expect(screen.getByText(/1 and 65535/)).toBeInTheDocument();
});
it("takes a changed stored value once the editor is not being edited", () => {
const { rerender } = setup([tcp(3000, 3000)]);
rerender([tcp(4000, 4000)]);
expect(host().value).toBe("4000");
});
it("removing a row saves the rest; the protocol saves at once (Docker keeps UDP)", () => {
const { onSave } = setup([tcp(3000, 3000), tcp(4000, 4000)]);
fireEvent.change(screen.getByLabelText("Protocol 2"), { target: { value: "udp" } });
expect(onSave).toHaveBeenLastCalledWith([tcp(3000, 3000), { ...tcp(4000, 4000), protocol: "udp" }]);
fireEvent.click(screen.getByRole("button", { name: "Remove port mapping 1" }));
expect(onSave).toHaveBeenLastCalledWith([{ ...tcp(4000, 4000), protocol: "udp" }]);
});
it("does not save when nothing changed", () => {
const { onSave } = setup([tcp(3000, 3000)]);
act(() => host().focus());
fireEvent.blur(host());
expect(onSave).not.toHaveBeenCalled();
});
});
@@ -1,4 +1,4 @@
import { useEffect, useState } from "react";
import { useEffect, useRef, useState } from "react";
import type { PortMapping } from "../../lib/types";
import Button from "../ui/Button";
import { monoInputClass, selectClass } from "../ui/Field";
@@ -12,43 +12,158 @@ interface Props {
onSave: (mappings: PortMapping[]) => Promise<unknown>;
}
/** One row as typed: ports stay text until they are valid, so a half-typed
* row is never turned into a 0. */
interface Row {
key: number;
host: string;
container: string;
protocol: string;
}
/** Placeholders are words, not port numbers: a "8080" placeholder in an
* empty row read as a filled-in 8080 → 8080 mapping that was never typed. */
const placeholderClass = "placeholder:italic placeholder:text-[var(--text-disabled)]";
function parsePort(text: string): number | null {
if (!/^\d+$/.test(text.trim())) return null;
const n = Number(text.trim());
return n >= 1 && n <= 65535 ? n : null;
}
/** Why a row is not a mapping yet, or `null` when it is one. */
export function rowProblem(row: Pick<Row, "host" | "container">): string | null {
if (row.host.trim() === "" || row.container.trim() === "") return "Fill in both ports";
if (parsePort(row.host) === null || parsePort(row.container) === null) {
return "Ports must be whole numbers between 1 and 65535";
}
return null;
}
/** The rows that are complete mappings — the only ones ever saved. */
function completeMappings(rows: Row[]): PortMapping[] {
return rows.flatMap((r) => {
const host_port = parsePort(r.host);
const container_port = parsePort(r.container);
return host_port !== null && container_port !== null && rowProblem(r) === null
? [{ host_port, container_port, protocol: r.protocol }]
: [];
});
}
let nextKey = 1;
const portText = (n: number) => (n > 0 ? String(n) : "");
function toRows(mappings: PortMapping[]): Row[] {
return mappings.map((m) => ({
key: nextKey++,
host: portText(m.host_port),
container: portText(m.container_port),
protocol: m.protocol,
}));
}
export default function PortMappingsEditor({
portMappings: initial,
portMappings: stored,
disabled,
disabledReason,
tcpOnly = false,
onSave,
}: Props) {
const [mappings, setMappings] = useState<PortMapping[]>(initial);
const [rows, setRowsState] = useState<Row[]>(() => toRows(stored));
// The latest rows, for blur handlers that run before a re-render.
const rowsRef = useRef(rows);
const setRows = (next: Row[]) => {
rowsRef.current = next;
setRowsState(next);
};
// What is stored, as this editor last loaded or saved it. A project refresh
// hands over a new array on every update (status events, save responses,
// list reloads); only a value that differs from this is a real change.
const storedKey = JSON.stringify(stored);
const syncedKey = useRef(storedKey);
const wrapper = useRef<HTMLDivElement>(null);
const [focusLeft, setFocusLeft] = useState(0);
const focusHost = useRef<number | null>(null);
useEffect(() => {
setMappings(initial);
}, [initial]);
if (storedKey === syncedKey.current) return;
// Never replace what the user is typing; this runs again when focus
// leaves the editor.
if (wrapper.current?.contains(document.activeElement)) return;
syncedKey.current = storedKey;
const fresh = toRows(JSON.parse(storedKey) as PortMapping[]);
// Rows still being filled in are not stored; keep them.
const drafts = rowsRef.current.filter((r) => rowProblem(r) !== null);
const freshKeys = new Set(fresh.map((r) => `${r.host}|${r.container}`));
setRows([...fresh, ...drafts.filter((r) => !freshKeys.has(`${r.host}|${r.container}`))]);
}, [storedKey, focusLeft]);
const updatePort = (
index: number,
field: "host_port" | "container_port",
value: string,
) => {
const updated = [...mappings];
const num = parseInt(value, 10);
updated[index] = { ...updated[index], [field]: isNaN(num) ? 0 : num };
setMappings(updated);
useEffect(() => {
if (focusHost.current === null) return;
const el = wrapper.current?.querySelector<HTMLInputElement>(
`[data-row="${focusHost.current}"][data-field="host"]`,
);
focusHost.current = null;
el?.focus();
}, [rows]);
/** Save the complete rows, if they differ from what is stored. */
const commit = (next: Row[]) => {
const mappings = completeMappings(next);
const key = JSON.stringify(mappings);
if (key === syncedKey.current) return;
syncedKey.current = key;
void onSave(mappings);
};
const edit = (index: number, field: "host" | "container", value: string) => {
const next = [...rowsRef.current];
next[index] = { ...next[index], [field]: value };
setRows(next);
};
const portInput = (row: Row, i: number, field: "host" | "container") => {
const value = row[field];
const missing = rowProblem(row) !== null && parsePort(value) === null;
return (
<input
type="text"
inputMode="numeric"
value={value}
onChange={(e) => edit(i, field, e.target.value)}
onBlur={() => commit(rowsRef.current)}
placeholder={field === "host" ? "Host port" : "Container port"}
aria-label={`${field === "host" ? "Host" : "Container"} port ${i + 1}`}
aria-invalid={missing || undefined}
aria-describedby={rowProblem(row) ? `pm-problem-${row.key}` : undefined}
data-row={row.key}
data-field={field}
disabled={disabled}
className={`w-[28%] ${monoInputClass} ${placeholderClass}`}
/>
);
};
return (
<div className="space-y-2">
<div
ref={wrapper}
className="space-y-2"
onBlur={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setFocusLeft((n) => n + 1);
}}
>
{disabled && disabledReason && (
<p className="px-2 py-1.5 bg-[var(--warning-muted)] border border-[var(--warning)]/30 rounded-[var(--radius-control)] text-xs text-[var(--warning)]">
{disabledReason}
</p>
)}
{mappings.length === 0 && (
{rows.length === 0 && (
<p className="text-xs text-[var(--text-secondary)]">No port mappings configured.</p>
)}
{mappings.length > 0 && (
{rows.length > 0 && (
<div className="flex gap-2 items-center text-xs text-[var(--text-secondary)] px-0.5">
<span className="w-[28%]">Host port</span>
<span className="w-[28%]">Container port</span>
@@ -57,71 +172,58 @@ export default function PortMappingsEditor({
</div>
)}
{mappings.map((pm, i) => (
<div key={i} className="flex gap-2 items-center">
<input
type="number"
min="1"
max="65535"
value={pm.host_port || ""}
onChange={(e) => updatePort(i, "host_port", e.target.value)}
onBlur={() => onSave(mappings)}
placeholder="8080"
aria-label={`Host port ${i + 1}`}
disabled={disabled}
className={`w-[28%] ${monoInputClass}`}
/>
<input
type="number"
min="1"
max="65535"
value={pm.container_port || ""}
onChange={(e) => updatePort(i, "container_port", e.target.value)}
onBlur={() => onSave(mappings)}
placeholder="8080"
aria-label={`Container port ${i + 1}`}
disabled={disabled}
className={`w-[28%] ${monoInputClass}`}
/>
<select
value={pm.protocol}
aria-label={`Protocol ${i + 1}`}
onChange={(e) => {
const updated = [...mappings];
updated[i] = { ...updated[i], protocol: e.target.value };
setMappings(updated);
onSave(updated);
}}
disabled={disabled}
className={`w-[22%] ${selectClass}`}
>
<option value="tcp">TCP</option>
{(!tcpOnly || pm.protocol === "udp") && <option value="udp">UDP</option>}
</select>
<Button
variant="danger"
disabled={disabled}
aria-label={`Remove port mapping ${i + 1}`}
onClick={() => {
const updated = mappings.filter((_, j) => j !== i);
setMappings(updated);
onSave(updated);
}}
>
Remove
</Button>
</div>
))}
{rows.map((row, i) => {
const problem = rowProblem(row);
return (
<div key={row.key} className="space-y-1">
<div className="flex gap-2 items-center">
{portInput(row, i, "host")}
{portInput(row, i, "container")}
<select
value={row.protocol}
aria-label={`Protocol ${i + 1}`}
onChange={(e) => {
const next = [...rowsRef.current];
next[i] = { ...next[i], protocol: e.target.value };
setRows(next);
commit(next);
}}
disabled={disabled}
className={`w-[22%] ${selectClass}`}
>
<option value="tcp">TCP</option>
{(!tcpOnly || row.protocol === "udp") && <option value="udp">UDP</option>}
</select>
<Button
variant="danger"
disabled={disabled}
aria-label={`Remove port mapping ${i + 1}`}
onClick={() => {
const next = rowsRef.current.filter((_, j) => j !== i);
setRows(next);
commit(next);
}}
>
Remove
</Button>
</div>
{problem && (
<p id={`pm-problem-${row.key}`} className="text-xs text-[var(--warning)] px-0.5">
⚠ {problem} — this mapping isn't saved or active.
</p>
)}
</div>
);
})}
<Button
disabled={disabled}
onClick={() => {
const updated = [
...mappings,
{ host_port: 0, container_port: 0, protocol: "tcp" },
];
setMappings(updated);
onSave(updated);
// Kept here until both ports are filled in: an empty row is never
// saved (it used to be stored as 0 → 0 and silently skipped).
const row: Row = { key: nextKey++, host: "", container: "", protocol: "tcp" };
focusHost.current = row.key;
setRows([...rowsRef.current, row]);
}}
>
+ Add port mapping
@@ -0,0 +1,88 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import type { Project, WorkspaceTerminal } from "../../../lib/types";
const listWorkspaceTerminals = vi.fn();
const endWorkspaceTerminal = vi.fn(async () => {});
const closeTerminalSession = vi.fn(async () => {});
vi.mock("../../../lib/tauri-commands", () => ({
listClaudeSessions: vi.fn(async () => []),
listWorkspaceTerminals: (id: string) => listWorkspaceTerminals(id),
endWorkspaceTerminal: (p: string, s: string) => endWorkspaceTerminal(p, s),
closeTerminalSession: (s: string) => closeTerminalSession(s),
updateProject: vi.fn(),
}));
vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn() }));
import SessionsTab from "./SessionsTab";
import { useAppState } from "../../../store/appState";
const actions = { resumeClaudeSession: vi.fn() } as never;
const aws = { id: "p1", name: "api", host_id: "h1", status: "running", container_id: "http://x/" } as unknown as Project;
const t = (id: string, over: Partial<WorkspaceTerminal> = {}): WorkspaceTerminal => ({
session_id: id,
kind: "claude",
name: null,
created_unix: Math.floor(Date.now() / 1000) - 600,
attached: false,
known: true,
...over,
});
beforeEach(() => {
listWorkspaceTerminals.mockReset();
endWorkspaceTerminal.mockClear();
closeTerminalSession.mockClear();
useAppState.setState({ projects: [aws], sessions: [], tabOrder: [], activeTabKey: null } as never);
});
describe("SessionsTab — terminals in an AWS workspace", () => {
it("lists them with their state and reattaches one in a tab", async () => {
listWorkspaceTerminals.mockResolvedValue([
t("open-1", { name: "main" }),
t("det-2", { kind: "bash" }),
t("web-3", { known: false, attached: true, name: "web terminal" }),
]);
useAppState.getState().addSession({ id: "open-1", projectId: "p1", projectName: "api", sessionType: "claude", sessionName: "main", persistent: true });
render(<SessionsTab project={aws} actions={actions} />);
const list = await screen.findByRole("list", { name: "Terminals in the workspace" });
expect(list.textContent).toContain("main");
expect(list.textContent).toContain("Open here");
expect(list.textContent).toContain("Shell · Detached");
expect(list.textContent).toContain("Attached elsewhere");
expect(list.textContent).toContain("opened elsewhere");
// Open tabs have nothing to reattach.
expect(screen.getAllByRole("button", { name: "Reattach" })).toHaveLength(2);
fireEvent.click(screen.getAllByRole("button", { name: "Reattach" })[0]);
const tab = useAppState.getState().sessions.find((s) => s.id === "det-2");
expect(tab).toMatchObject({ sessionType: "bash", persistent: true, pendingReattach: true, projectId: "p1" });
expect(useAppState.getState().activeSessionId).toBe("det-2");
});
it("ends a detached terminal in the workspace and an open one by closing its tab, after a confirm", async () => {
listWorkspaceTerminals.mockResolvedValue([t("open-1"), t("det-2")]);
useAppState.getState().addSession({ id: "open-1", projectId: "p1", projectName: "api", sessionType: "claude", sessionName: null, persistent: true });
render(<SessionsTab project={aws} actions={actions} />);
await screen.findByRole("list", { name: "Terminals in the workspace" });
fireEvent.click(screen.getAllByRole("button", { name: "End" })[1]);
expect(endWorkspaceTerminal).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Confirm end" }));
await waitFor(() => expect(endWorkspaceTerminal).toHaveBeenCalledWith("p1", "det-2"));
fireEvent.click(screen.getAllByRole("button", { name: "End" })[0]);
fireEvent.click(screen.getByRole("button", { name: "Confirm end" }));
await waitFor(() => expect(closeTerminalSession).toHaveBeenCalledWith("open-1"));
expect(useAppState.getState().sessions.find((s) => s.id === "open-1")).toBeUndefined();
});
it("is not shown for a Docker project", async () => {
const docker = { ...aws, host_id: null } as unknown as Project;
render(<SessionsTab project={docker} actions={actions} />);
await screen.findByText(/No sessions recorded yet/);
expect(screen.queryByText("Terminals in the workspace")).toBeNull();
expect(listWorkspaceTerminals).not.toHaveBeenCalled();
});
});
@@ -1,9 +1,18 @@
import { useCallback, useEffect, useState } from "react";
import type { ClaudeSession, Project } from "../../../lib/types";
import { listClaudeSessions } from "../../../lib/tauri-commands";
import { useShallow } from "zustand/react/shallow";
import type { ClaudeSession, Project, WorkspaceTerminal } from "../../../lib/types";
import {
endWorkspaceTerminal,
listClaudeSessions,
listWorkspaceTerminals,
} from "../../../lib/tauri-commands";
import type { useProjectActions } from "../../../hooks/useProjectActions";
import { useTerminal } from "../../../hooks/useTerminal";
import { useAppState } from "../../../store/appState";
import { isAwsProject } from "../../../lib/awsWorkspace";
import { reattachTab, terminalLabel } from "../../../lib/persistentTerminals";
import Button from "../../ui/Button";
import { formatAge, formatBytes } from "./format";
import { formatAge, formatBytes, formatElapsed } from "./format";
interface Props {
project: Project;
@@ -38,6 +47,7 @@ export default function SessionsTab({ project, actions }: Props) {
return (
<div className="p-4 max-w-4xl">
{isAwsProject(project) && running && <WorkspaceTerminals project={project} />}
<div className="flex items-center justify-between mb-3">
<p className="text-xs text-[var(--text-secondary)]">
Conversations stored on this project&rsquo;s config volume. Resume opens a
@@ -88,3 +98,117 @@ export default function SessionsTab({ project, actions }: Props) {
</div>
);
}
/**
* AWS: the terminals running in the workspace — the ones open here, the ones
* this app left detached, and any another machine or the web terminal
* opened. Reattach opens one in a tab; End stops it (and closes its tab).
*/
function WorkspaceTerminals({ project }: { project: Project }) {
const [terminals, setTerminals] = useState<WorkspaceTerminal[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [confirmEnd, setConfirmEnd] = useState<string | null>(null);
const openIds = useAppState(useShallow((s) => s.sessions.map((x) => x.id)));
const { close } = useTerminal();
const pushToast = useAppState((s) => s.pushToast);
const load = useCallback(() => {
setLoading(true);
setError(null);
listWorkspaceTerminals(project.id)
.then(setTerminals)
.catch((e) => {
setTerminals([]);
setError(String(e));
})
.finally(() => setLoading(false));
}, [project.id]);
useEffect(load, [load]);
const isOpen = (id: string) => openIds.includes(id);
const reattach = (t: WorkspaceTerminal) => {
useAppState.getState().addSession(reattachTab(project.id, project.name, t));
};
const end = async (t: WorkspaceTerminal) => {
setConfirmEnd(null);
try {
if (isOpen(t.session_id)) await close(t.session_id);
else await endWorkspaceTerminal(project.id, t.session_id);
} catch (e) {
pushToast({ kind: "error", message: "Could not end that terminal", detail: String(e) });
}
load();
};
return (
<section className="mb-6" aria-labelledby="workspace-terminals-heading">
<div className="flex items-center justify-between mb-2">
<div>
<h3 id="workspace-terminals-heading" className="text-[13px] font-medium text-[var(--text-primary)]">
Terminals in the workspace
</h3>
<p className="text-xs text-[var(--text-secondary)]">
Terminals keep running in the workspace when Triple-C closes or loses its
connection. Closing a tab ends its terminal. A Claude session left running keeps
the workspace up until it ends, you end it here, you Stop, or the lifetime cap.
</p>
</div>
<Button onClick={load} disabled={loading}>
{loading ? "Refreshing…" : "Refresh"}
</Button>
</div>
{error ? (
<p className="text-[13px] text-[var(--text-secondary)]">{error}</p>
) : terminals.length === 0 && !loading ? (
<p className="text-[13px] text-[var(--text-secondary)]">No terminals are running in the workspace.</p>
) : (
<ul className="space-y-1" aria-label="Terminals in the workspace">
{terminals.map((t) => {
const open = isOpen(t.session_id);
const state = open ? "Open here" : t.attached ? "Attached elsewhere" : "Detached";
// The cost of a Claude that outlives the app: it keeps the
// workspace up (and billed) until it ends or is ended.
const keepsUp = !open && !t.attached && t.kind === "claude";
return (
<li
key={t.session_id}
className="flex items-center gap-3 px-3 py-2 bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-[var(--radius-control)]"
>
<div className="flex-1 min-w-0">
<div className="text-[13px] text-[var(--text-primary)] truncate">{terminalLabel(t)}</div>
<div className="text-xs text-[var(--text-secondary)] truncate">
{t.kind === "claude" ? "Claude Code" : "Shell"} · {state} · started{" "}
{formatElapsed(Date.now() - t.created_unix * 1000)}
{t.known ? "" : " · opened elsewhere"}
</div>
{keepsUp && (
<div className="text-xs text-[var(--warning)]">
Keeps the workspace running while it runs — End it if you no longer need it.
</div>
)}
</div>
{!open && (
<Button variant="primary" onClick={() => reattach(t)}>
Reattach
</Button>
)}
{confirmEnd === t.session_id ? (
<>
<Button variant="danger" onClick={() => void end(t)}>Confirm end</Button>
<Button onClick={() => setConfirmEnd(null)}>Cancel</Button>
</>
) : (
<Button onClick={() => setConfirmEnd(t.session_id)}>End</Button>
)}
</li>
);
})}
</ul>
)}
</section>
);
}
@@ -28,6 +28,7 @@ import {
EC2_NO_CAPACITY,
EC2_NO_SIDECAR,
EC2_SCALE_TO_ZERO_NOTE,
PERSISTENT_TERMINALS_NOTE,
launchTypeChanges,
launchTypePatch,
type Ec2Limits,
@@ -317,6 +318,7 @@ export default function HostSection({ project, save, disabled }: Props) {
This environment stops workspaces after {maxHours} h (advisory).
</p>
)}
<p className="text-xs text-[var(--text-secondary)]">{PERSISTENT_TERMINALS_NOTE}</p>
<div>
<span className="block text-[13px] font-medium text-[var(--text-primary)] mb-1">
@@ -1,3 +1,4 @@
import { dockerFailLabel } from "../../lib/dockerStatus";
import { useState } from "react";
import { useDocker } from "../../hooks/useDocker";
import { useSettings } from "../../hooks/useSettings";
@@ -13,7 +14,7 @@ const IMAGE_SOURCE_OPTIONS: { value: ImageSource; label: string; description: st
];
export default function DockerSettings() {
const { dockerAvailable, imageExists, checkDocker, checkImage, buildImage, pullImage } =
const { dockerAvailable, dockerStatus, imageExists, checkDocker, checkImage, buildImage, pullImage } =
useDocker();
const { appSettings, saveSettings } = useSettings();
const [working, setWorking] = useState(false);
@@ -82,7 +83,7 @@ export default function DockerSettings() {
<div className="flex items-center justify-between">
<span className="text-[var(--text-secondary)]">Docker Status</span>
<span className={dockerAvailable ? "text-[var(--success)]" : "text-[var(--error)]"}>
{dockerAvailable === null ? "Checking..." : dockerAvailable ? "Connected" : "Not Available"}
{dockerAvailable === null ? "Checking..." : dockerAvailable ? "Connected" : dockerFailLabel(dockerStatus)}
</span>
</div>
+14 -14
View File
@@ -64,10 +64,10 @@ function ErrorLine({
}) {
return (
<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 && (
<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>
)}
{failure.error.kind === "sso_expired" && onSignIn && (
@@ -124,7 +124,7 @@ function PermissionReportView({ report }: { report: PermissionReport }) {
>
{badge}
</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}
</span>
</div>
@@ -154,8 +154,8 @@ function PermissionReportView({ report }: { report: PermissionReport }) {
</summary>
<ul className="mt-1 space-y-0.5 pl-4">
{t.results.map((r) => (
<li key={r.action} className="text-[var(--text-secondary)]">
<span className="font-mono">{r.action}</span> — {r.verdict}
<li key={r.action} className="text-[var(--text-secondary)] break-words">
<span className="font-mono break-all">{r.action}</span> — {r.verdict}
{r.note && (
<>
{" "}
@@ -263,7 +263,7 @@ function ConnectionRow({ host }: { host: HostConnection }) {
<li
ref={rowRef}
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 ? (
<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)} />
)}
</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()}>
Save changes
</Button>
@@ -283,16 +283,16 @@ function ConnectionRow({ host }: { host: HostConnection }) {
</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="text-[13px] font-medium text-[var(--text-primary)]">{host.name}</div>
<div className="text-xs text-[var(--text-secondary)]">
<div className="text-[13px] font-medium text-[var(--text-primary)] break-words">{host.name}</div>
<div className="text-xs text-[var(--text-secondary)] break-words">
<span>{auth.method === "profile" ? `Profile: ${auth.name}` : "Access keys"}</span>
{" · "}
<span>{host.kind.default_region}</span>
</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}`}>
Check
</Button>
@@ -309,7 +309,7 @@ function ConnectionRow({ host }: { host: HostConnection }) {
)}
{confirmRemove && (
<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}`}>
Confirm remove
</Button>
@@ -501,7 +501,7 @@ function AddConnectionForm() {
{busy ? "Adding…" : "Add connection"}
</Button>
{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}
</p>
)}
@@ -516,7 +516,7 @@ export default function HostsSettings() {
const { appSettings } = useSettings();
const hosts = appSettings?.hosts ?? [];
return (
<div className="space-y-3">
<div className="space-y-3 min-w-0">
<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.
</p>
@@ -177,7 +177,7 @@ export default function AdminBundleModal({
Saved to <code className="font-mono text-[var(--text-primary)] break-all">{saved}</code>
</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}
</pre>
<Button size="sm" onClick={copy}>
@@ -30,6 +30,7 @@ export default function DeployEnvironmentModal({
onClose,
onDeploy,
onDetect,
onBundle,
}: {
connectionId: string;
region: string;
@@ -40,6 +41,8 @@ export default function DeployEnvironmentModal({
/** Starts the run; resolves to the command's error, or null once started. */
onDeploy: (name: string, network: NetworkChoice, maxWorkspaceHours: number) => Promise<AwsError | null>;
onDetect: () => void;
/** Switch to an environment bundle for an admin (offered when AWS refuses the deploy). */
onBundle?: () => void;
}) {
const [name, setName] = useState("main");
const [draft, setDraft] = useState<NetworkDraft>(DEFAULT_NETWORK);
@@ -80,7 +83,7 @@ export default function DeployEnvironmentModal({
const createBoundary = async () => {
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),
);
if (err?.kind === "access_denied") setBundle({ reason: awsErrorMessage(err) });
@@ -125,18 +128,19 @@ export default function DeployEnvironmentModal({
<div className="flex gap-2 flex-wrap">
<Button
size="md"
wrap
variant="primary"
onClick={createBoundary}
disabled={!!boundaryRun && !boundaryRun.done}
>
Create the permissions boundary (needs an account administrator)
</Button>
<Button size="md" onClick={() => setBundle({})}>
<Button size="md" wrap onClick={() => setBundle({})}>
Save a bundle for an administrator instead
</Button>
</div>
{boundaryError && (
<p role="alert" className="text-[var(--error)]">
<p role="alert" className="text-[var(--error)] break-words">
{awsErrorMessage(boundaryError)}
</p>
)}
@@ -149,6 +153,7 @@ export default function DeployEnvironmentModal({
</p>
<Button
size="md"
wrap
onClick={() =>
setBundle({
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).
</p>
{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)}
</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>
)}
</Modal>
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { act, renderHook } from "@testing-library/react";
import { runKey, useDeployRuns } from "./DeployProgress";
import { act, render, renderHook, screen } from "@testing-library/react";
import DeployProgressView, { runKey, useDeployRuns } from "./DeployProgress";
import type { DeployProgress } from "../../../lib/types";
import { progress, tofuEvent } from "./testkit";
@@ -29,10 +29,10 @@ describe("useDeployRuns", () => {
const onDone = vi.fn();
const { result } = renderHook(() => useDeployRuns(onDone));
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 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);
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 () => {
const { result, unmount } = renderHook(() => useDeployRuns());
await act(async () => {
await result.current.start(KEY, "eu-west-1", "Deploy of main", async () => "a");
await result.current.start("boundary/terraform.tfstate", "eu-west-1", "Boundary", async () => "b");
await result.current.start(KEY, "eu-west-1", "deploy", "Deploy of main", async () => "a");
await result.current.start("boundary/terraform.tfstate", "eu-west-1", "deploy", "Boundary", async () => "b");
});
expect(handlers.size).toBe(2);
unmount();
@@ -66,7 +66,7 @@ describe("useDeployRuns", () => {
const { result } = renderHook(() => useDeployRuns());
let err: unknown;
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" };
});
});
@@ -75,3 +75,28 @@ describe("useDeployRuns", () => {
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 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. */
export interface DeployRun {
stateKey: string;
region: string;
kind: RunKind;
label: string;
/** Null until the starting command resolves. */
opId: string | null;
@@ -57,7 +65,13 @@ export function useDeployRuns(
}, []);
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);
subs.current.get(k)?.unlisten?.();
const sub: Subscription = { unlisten: null };
@@ -94,7 +108,7 @@ export function useDeployRuns(
setRuns((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 }) => {
@@ -146,7 +160,7 @@ function EventLine({ e }: { e: TofuEvent }) {
return (
<li className="text-xs leading-snug">
{(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.action && <span className="ml-1 text-[var(--text-secondary)]">{e.action}</span>}
</span>
@@ -154,10 +168,10 @@ function EventLine({ e }: { e: TofuEvent }) {
{isError ? (
<>
<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>
);
@@ -205,14 +219,14 @@ export default function DeployProgress({
return (
<section
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 gap-2 text-xs">
<span className="font-medium text-[var(--text-primary)]">{run.label}</span>
<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 flex-wrap min-w-0">
<span className="font-medium text-[var(--text-primary)] break-words min-w-0">{run.label}</span>
{status && <StatusIndicator tone={status.tone} label={status.label} />}
</div>
<div className="flex gap-1.5">
<div className="flex gap-1.5 flex-wrap">
{!run.done && (
<Button
size="sm"
@@ -239,11 +253,12 @@ export default function DeployProgress({
</ol>
)}
{run.done && run.result && (
<p role="status" className="text-xs">
<p role="status" className="text-xs break-words">
{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
wrap
tone="error"
label={`Failed (exit ${run.result.exit_code})${run.result.summary ? `: ${run.result.summary}` : ""}`}
/>
@@ -251,7 +266,7 @@ export default function DeployProgress({
</p>
)}
{cancelError && !confirming && (
<p role="alert" className="text-xs text-[var(--error)]">
<p role="alert" className="text-xs text-[var(--error)] break-words">
{awsErrorMessage(cancelError)}
</p>
)}
@@ -48,6 +48,7 @@ export default function Ec2CapacityFields({
<div className="text-[13px] font-medium text-[var(--text-primary)]">EC2 capacity</div>
<SegmentedControl<"none" | "ec2">
label="EC2 capacity"
className="flex-wrap max-w-full"
value={value.enabled ? "ec2" : "none"}
onChange={(v) => set({ enabled: v === "ec2" })}
segments={[
@@ -81,7 +81,7 @@ describe("EnvironmentsPanel", () => {
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(
() => scan(),
(cmd) => {
@@ -91,22 +91,162 @@ describe("EnvironmentsPanel", () => {
);
render(<EnvironmentsPanel connection={conn} tier="workspace_user" />);
await open();
expect(await screen.findByText(/needs an environment admin/)).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Deploy a new environment" })).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Show the environment-admin policies" }));
expect(await screen.findByText("environment-admin.json")).toBeInTheDocument();
const deploy = await screen.findByRole("button", { name: "Deploy a new environment" });
expect(deploy.className).toContain("--accent-emphasis");
expect(screen.getByTestId("deploy-unconfirmed-note")).toHaveTextContent(
"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" });
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");
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());
render(<EnvironmentsPanel connection={conn} />);
await open();
expect(await screen.findByRole("button", { name: "Request an environment from an admin…" })).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Deploy a new environment" })).toBeNull();
expect(await screen.findByRole("button", { name: "Deploy a new environment" })).toBeInTheDocument();
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 () => {
@@ -248,7 +388,43 @@ describe("EnvironmentsPanel", () => {
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(
() => scan({ environments: [env()] }),
(cmd) => {
@@ -259,6 +435,11 @@ describe("EnvironmentsPanel", () => {
render(<EnvironmentsPanel connection={conn} tier="workspace_user" />);
await open();
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");
// Opening the bundle is not a request yet.
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();
});
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 () => {
backend(
() => scan({ environments: [env()] }),
@@ -422,7 +611,7 @@ describe("EnvironmentsPanel", () => {
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(
() => scan({ environments: [env({ onboarding: { state: "joined", ec2: compute({ max_instances: 1 }) } })] }),
(cmd) => {
@@ -434,6 +623,7 @@ describe("EnvironmentsPanel", () => {
render(<EnvironmentsPanel connection={conn} tier="workspace_user" />);
await open();
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" });
fireEvent.click(within(dialog).getByRole("button", { name: "Save bundle to folder…" }));
await waitFor(() =>
@@ -525,6 +715,7 @@ describe("EnvironmentsPanel", () => {
render(<EnvironmentsPanel connection={conn} tier="workspace_user" />);
await open();
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" }));
expect(screen.queryByText("Waiting for an admin to onboard you")).toBeNull();
expect(within(screen.getByTestId("env-dev")).getByRole("button", { name: "Join dev" })).toHaveTextContent("Join");
@@ -10,7 +10,7 @@ import {
unlockAwsState,
updateAwsEnvironment,
} 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 type {
AwsError,
@@ -34,7 +34,7 @@ import AdminBundleModal from "./AdminBundleModal";
import UpdateEnvironmentModal from "./UpdateEnvironmentModal";
import DeployEnvironmentModal from "./DeployEnvironmentModal";
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 {
COMMON_REGIONS,
@@ -45,6 +45,7 @@ import {
onboardingStateKey,
stateLock,
stateStatus,
UNCONFIRMED_NOTE,
} from "./environmentFormat";
/** A typed confirmation: the action runs only once the environment's name is typed. */
@@ -118,6 +119,7 @@ type Bundle = {
type JoinOf = {
region: string;
name: string;
ownerId: string;
stateKey: string;
recorded: UserCompute | null;
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. */
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. */
function runEnvironment(stateKey: string): string | null {
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,
* 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({
connection,
tier,
}: {
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;
}) {
const isAdmin = tier === "environment_admin";
@@ -176,6 +195,7 @@ export default function EnvironmentsPanel({
// onboarding that didn't finish has no record to start from.
const lastEc2 = useRef(new Map<string, Ec2Compute>());
const [copyNote, setCopyNote] = useState<string | null>(null);
const [notAdminOpen, setNotAdminOpen] = useState(false);
const request = useRef(0);
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). */
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);
setRowErrors(({ [rk]: _gone, ...rest }) => rest);
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);
if (err) setRowErrors((r) => ({ ...r, [rk]: err }));
return err;
@@ -230,7 +257,7 @@ export default function EnvironmentsPanel({
const seen = runKey(scan.region, key);
if (!runs[seen] && !followed.current.has(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) {
@@ -261,50 +288,42 @@ export default function EnvironmentsPanel({
const stale = detecting || !current;
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),
);
// Without `hours`, the environment's recorded cap is kept.
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),
);
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),
);
// Join (or, once joined, a change of EC2 capacity): admins choose the
// capacity and apply it themselves; others get a bundle for an admin.
// Join (or, once joined, a change of EC2 capacity): anyone chooses the
// capacity and applies it; the modal offers a bundle for an admin instead.
const join = (found: EnvironmentScan, e: DetectedEnvironment) => {
const recorded = recordedEc2(e);
if (isAdmin) {
setJoinOf({
region: found.region,
name: e.name,
stateKey: onboardingStateKey(e.name, found.owner_key),
recorded,
reapply: e.onboarding?.state === "joined",
incomplete: e.onboarding?.state === "incomplete",
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,
});
}
setJoinOf({
region: found.region,
name: e.name,
ownerId: found.owner_id,
stateKey: onboardingStateKey(e.name, found.owner_key),
recorded: recordedEc2(e),
reapply: e.onboarding?.state === "joined",
incomplete: e.onboarding?.state === "incomplete",
lastChoice: lastEc2.current.get(rowKey(found.region, e.name)) ?? null,
});
};
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 key = rowKey(j.region, j.name);
if (ec2.kind === "ec2") {
const { kind: _kind, ...c } = ec2;
lastEc2.current.set(key, c);
} 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) =>
@@ -313,14 +332,40 @@ export default function EnvironmentsPanel({
const looseRuns = Object.values(runs).filter(
(r) => r.region !== current?.region || !shown.has(runEnvironment(r.stateKey) ?? ""),
);
const progress = (r: DeployRun) => (
<DeployProgress
key={runKey(r.region, r.stateKey)}
run={r}
connectionId={connection.id}
onDismiss={() => dismiss(runKey(r.region, r.stateKey))}
/>
);
const progress = (r: DeployRun) => {
const denied = deniedRun(r);
const env = runEnvironment(r.stateKey);
const found = current?.region === r.region ? current : null;
const target = env && found ? found.environments.find((e) => e.name === env) : undefined;
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 at = found.region;
@@ -349,10 +394,10 @@ export default function EnvironmentsPanel({
data-testid={`env-${e.name}`}
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="min-w-0 space-y-0.5 text-xs">
<div className="flex items-center gap-2 flex-wrap">
<span className="text-[13px] font-medium text-[var(--text-primary)]">{e.name}</span>
<div className="flex items-start justify-between gap-2 flex-wrap" data-testid={`env-row-${e.name}`}>
<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 min-w-0">
<span className="text-[13px] font-medium text-[var(--text-primary)] break-all">{e.name}</span>
<StatusIndicator tone={status.tone} label={status.label} />
{onboarding === "joined" && <StatusIndicator tone="ok" label="Joined" />}
{onboarding === "in_progress" && <StatusIndicator tone="busy" label="Onboarding in progress" />}
@@ -407,11 +452,11 @@ export default function EnvironmentsPanel({
})()}
</div>
)}
{!isAdmin && isWaiting && onboarding !== "joined" && (
{isWaiting && onboarding !== "joined" && (
<div className="text-[var(--text-secondary)]">Waiting for an admin to onboard you</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" && (
<Button
size="sm"
@@ -420,17 +465,18 @@ export default function EnvironmentsPanel({
aria-label={`Join ${e.name}`}
onClick={() => join(found, e)}
>
{!isAdmin && isWaiting ? "Show onboarding bundle" : "Join"}
Join
</Button>
)}
{has("join") && onboarding === "joined" && (
<Button
size="sm"
wrap
disabled={busy || joinBlocked}
aria-label={`EC2 capacity in ${e.name}`}
onClick={() => join(found, e)}
>
{isAdmin ? "Change EC2 capacity" : "EC2 capacity bundle"}
Change EC2 capacity
</Button>
)}
{mine("follow") && (
@@ -439,7 +485,7 @@ export default function EnvironmentsPanel({
disabled={busy}
aria-label={`Follow my onboarding to ${e.name}`}
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
@@ -451,7 +497,7 @@ export default function EnvironmentsPanel({
disabled={busy}
aria-label={`Push saved state of my onboarding to ${e.name}`}
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),
)
}
@@ -477,7 +523,7 @@ export default function EnvironmentsPanel({
aria-label={`Push saved state of ${e.name}`}
onClick={() => {
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),
);
}}
@@ -492,7 +538,7 @@ export default function EnvironmentsPanel({
aria-label={`Follow ${e.name}`}
onClick={() => {
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
@@ -548,7 +594,7 @@ export default function EnvironmentsPanel({
</div>
</div>
{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)}
</p>
)}
@@ -560,14 +606,14 @@ export default function EnvironmentsPanel({
const nothingFound = !!current && current.environments.length === 0;
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)}>
<span aria-hidden="true">{open ? "▾" : "▸"}</span>
Environments
</Button>
{open && (
<div className="space-y-2 pl-1">
<div className="flex items-end gap-2 flex-wrap">
<div className="space-y-2 pl-1 min-w-0">
<div className="flex items-end gap-2 flex-wrap min-w-0" data-testid="region-row">
<Field label="Region">
{(id) => (
<select id={id} className={selectClass} value={region} onChange={(e) => setRegion(e.target.value)}>
@@ -589,11 +635,11 @@ export default function EnvironmentsPanel({
</p>
)}
{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)}
</p>
)}
{current && isAdmin && current.boundary === "no" && (
{current && current.boundary === "no" && (
<p className="text-xs text-[var(--text-secondary)] leading-snug">
This account has no Triple-C permissions boundary yet; deploying creates it first.
</p>
@@ -604,32 +650,54 @@ export default function EnvironmentsPanel({
{nothingFound && (
<p className="text-xs text-[var(--text-secondary)] leading-snug">
No Triple-C environment in {current.region}.
{!isAdmin &&
" 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."}
{!tier && " Run Check to see what your credentials can do."}
</p>
)}
{current && isAdmin && (
<Button
size="md"
variant={nothingFound ? "primary" : "secondary"}
disabled={stale}
onClick={() => setDeployOpen(true)}
>
Deploy a new environment
</Button>
)}
{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…
{current && (
<div className="space-y-1.5 min-w-0" data-testid="deploy-section">
<Button
size="md"
wrap
variant={nothingFound ? "primary" : "secondary"}
disabled={stale}
onClick={() => setDeployOpen(true)}
>
Deploy a new environment
</Button>
{copyNote && (
<p role="status" className="text-xs text-[var(--text-secondary)]">
{copyNote}
{!isAdmin && (
<p className="text-xs text-[var(--text-secondary)] leading-snug break-words" data-testid="deploy-unconfirmed-note">
{UNCONFIRMED_NOTE}
</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>
)}
{looseRuns.map(progress)}
@@ -649,6 +717,12 @@ export default function EnvironmentsPanel({
repairOf ? repair(current.region, name, network, hours) : deploy(current.region, name, network, hours)
}
onDetect={() => void detect()}
onBundle={() => {
const at = current.region;
setDeployOpen(false);
setRepairOf(null);
setBundle({ kind: "environment", region: at });
}}
/>
)}
{updateOf && (
@@ -667,7 +741,7 @@ export default function EnvironmentsPanel({
confirmLabel="Destroy"
onClose={() => setDestroyOf(null)}
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),
)
}
@@ -718,6 +792,12 @@ export default function EnvironmentsPanel({
reapply={joinOf.reapply}
incomplete={joinOf.incomplete}
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)}
onClose={() => setJoinOf(null)}
/>
@@ -4,12 +4,13 @@ import type { AwsError, Ec2Choice, Ec2Compute, UserCompute } from "../../../lib/
import Button from "../../ui/Button";
import Modal from "../../ui/Modal";
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
* onboarding to change its EC2 capacity. Starts from the recorded capacity,
* so a re-apply keeps it unless changed.
* Self-onboarding: join an environment, or re-apply an onboarding to change
* its EC2 capacity. Starts from the recorded capacity, so a re-apply keeps it
* 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({
environment,
@@ -18,6 +19,8 @@ export default function JoinEnvironmentModal({
reapply,
incomplete = false,
lastChoice = null,
confirmedAdmin = true,
onBundle,
onJoin,
onClose,
}: {
@@ -33,6 +36,10 @@ export default function JoinEnvironmentModal({
/** The EC2 capacity last chosen here in this run of the app, if any:
* the starting point when there is no record. */
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. */
onJoin: (ec2: Ec2Choice) => Promise<AwsError | null>;
onClose: () => void;
@@ -73,6 +80,7 @@ export default function JoinEnvironmentModal({
>
<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>}
{!confirmedAdmin && <p data-testid="join-unconfirmed-note">{UNCONFIRMED_NOTE}</p>}
{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>
)}
@@ -89,10 +97,22 @@ export default function JoinEnvironmentModal({
</p>
)}
{error && (
<p role="alert" className="text-[var(--error)]">
<p role="alert" className="text-[var(--error)] break-words">
{awsErrorMessage(error)}
</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>
</Modal>
);
@@ -28,6 +28,7 @@ export default function NetworkFields({
<div className="text-[13px] font-medium text-[var(--text-primary)]">Network</div>
<SegmentedControl<NetworkChoice["mode"]>
label="Network"
className="flex-wrap max-w-full"
value={value.mode}
onChange={(mode) => set({ mode })}
segments={[
@@ -28,12 +28,12 @@ export default function PolicyFiles({
if (!files) {
return (
<div className="space-y-1">
<Button size="sm" onClick={load}>
<div className="space-y-1 min-w-0">
<Button size="sm" wrap onClick={load}>
{label}
</Button>
{error && (
<p role="alert" className="text-xs text-[var(--error)]">
<p role="alert" className="text-xs text-[var(--error)] break-words">
{error}
</p>
)}
@@ -41,30 +41,38 @@ export default function PolicyFiles({
);
}
return (
<div className="space-y-1 text-xs">
<p className="text-[var(--text-secondary)]">
<div className="space-y-1.5 text-xs min-w-0">
<p className="text-[var(--text-secondary)] leading-snug break-words">
{tier === "workspace_user" ? "Workspace user" : "Environment admin"}:{" "}
{files.length === 1
? "attach this file as a customer managed policy."
: `Attach all ${files.length} files, each as its own customer managed policy.`}
</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) => (
<div key={f.name} className="space-y-1">
<div className="flex items-center gap-2">
<span className="font-mono text-[var(--text-primary)]">{f.name}</span>
<Button size="sm" aria-label={`Copy ${f.name}`} onClick={() => onCopy(f)}>
Copy
</Button>
</div>
<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>
<details key={f.name} className="min-w-0">
<summary className="cursor-pointer text-[var(--text-secondary)] break-all">
Show JSON of <span className="font-mono">{f.name}</span>
</summary>
<pre className="mt-1 max-h-48 max-w-full overflow-auto whitespace-pre-wrap break-all text-[var(--text-secondary)]">
{f.json}
</pre>
</details>
))}
</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`;
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.";
@@ -116,6 +116,8 @@ vi.mock("@xterm/addon-web-links", async (importOriginal) => {
*/
const terminalInput = vi.fn(async () => {});
/** `reattach_terminal_session`, for the persistent-terminal cases. */
const reattachTerminalSession = vi.hoisted(() => vi.fn());
vi.mock("../../lib/tauri-commands", () => ({
terminalInput: (sessionId: string, bytes: number[]) =>
@@ -132,6 +134,7 @@ vi.mock("../../lib/tauri-commands", () => ({
checkBrowserViewSupport: vi.fn(async () => containerEnv.detection),
openUrlExternal: vi.fn(async () => {}),
openFileViewer: vi.fn(async () => {}),
reattachTerminalSession: (...a: unknown[]) => reattachTerminalSession(...a),
}));
vi.mock("@tauri-apps/api/event", () => ({
@@ -2128,3 +2131,125 @@ describe("TerminalView — copying text out", () => {
expect(writeText.mock.calls[0][0]).toContain("● The café’s");
});
});
describe("persistent AWS terminals", () => {
/** What the xterm shows, all rows of the active buffer. */
function screenText(): string {
const term = xterm.instances[0] as Terminal;
const b = term.buffer.active;
const rows: string[] = [];
for (let i = 0; i < b.length; i++) rows.push(b.getLine(i)?.translateToString(true) ?? "");
return rows.join("\n");
}
async function settle() {
await act(async () => {
for (let i = 0; i < 5; i++) await new Promise((r) => setTimeout(r, 0));
});
}
function mountPersistent(pendingReattach: boolean) {
useAppState.setState({
projects: [{ id: "p1", name: "api", status: "running", host_id: "h1" }] as never,
sessions: [
{ id: "s1", projectId: "p1", projectName: "api", sessionType: "claude", sessionName: null, persistent: true, pendingReattach },
],
});
return render(<TerminalView sessionId="s1" active />);
}
beforeEach(() => {
reattachTerminalSession.mockReset();
});
it("a reopened tab attaches only once its listeners are up, replaying history", async () => {
reattachTerminalSession.mockImplementation(async () => {
// The listener must already be there when the backend emits history.
expect(ptyOutput.listeners.has("terminal-output-s1")).toBe(true);
expect(ptyOutput.listeners.has("terminal-exit-s1")).toBe(true);
return { outcome: "reattached", kind: "claude", name: null };
});
mountPersistent(true);
await settle();
expect(reattachTerminalSession).toHaveBeenCalledTimes(1);
const [pid, sid, rows] = reattachTerminalSession.mock.calls[0];
expect([pid, sid]).toEqual(["p1", "s1"]);
expect(typeof rows).toBe("number");
expect(useAppState.getState().sessions[0].pendingReattach).toBe(false);
});
it("a lost connection reattaches without replaying, and a gone session ends the tab", async () => {
reattachTerminalSession.mockResolvedValue({ outcome: "reattached", kind: "claude", name: null });
mountPersistent(false);
await settle();
expect(reattachTerminalSession).not.toHaveBeenCalled();
const exit = ptyOutput.listeners.get("terminal-exit-s1");
if (!exit) throw new Error("no exit listener");
await act(async () => exit({ payload: [] }));
await settle();
expect(reattachTerminalSession).toHaveBeenCalledWith("p1", "s1", null);
expect(screenText()).not.toContain("[Session ended]");
// Long after that attach (a quick drop would back off first).
const later = Date.now() + 60_000;
const now = vi.spyOn(Date, "now").mockReturnValue(later);
reattachTerminalSession.mockResolvedValue({ outcome: "ended" });
await act(async () => exit({ payload: [] }));
await settle();
expect(screenText()).toContain("[Session ended]");
expect(useAppState.getState().sessions[0].persistent).toBe(false);
now.mockRestore();
});
it("stops reattaching a session that keeps dropping right after it attaches", async () => {
reattachTerminalSession.mockResolvedValue({ outcome: "reattached", kind: "claude", name: null });
vi.useFakeTimers({ shouldAdvanceTime: true });
mountPersistent(false);
await settle();
const exit = ptyOutput.listeners.get("terminal-exit-s1");
if (!exit) throw new Error("no exit listener");
for (let i = 0; i < 4; i++) {
await act(async () => exit({ payload: [] }));
await act(async () => {
await vi.advanceTimersByTimeAsync(i === 0 ? 100 : 3000 * i + 100);
});
await settle();
}
// First drop reattaches at once; the next two are quick and back off;
// the third quick one stops.
expect(reattachTerminalSession).toHaveBeenCalledTimes(3);
expect(screenText()).toContain("keeps dropping");
vi.useRealTimers();
});
it("only the first chunk after a replay request is the replay", async () => {
reattachTerminalSession.mockImplementation(async () => {
const emit = ptyOutput.listeners.get("terminal-output-s1")!;
emit({ payload: Array.from(new TextEncoder().encode("old history\r\n")) });
return { outcome: "reattached", kind: "claude", name: null };
});
mountPersistent(true);
await settle();
expect(screenText()).toContain("old history");
// Live output now gets the URL detector again.
const emit = ptyOutput.listeners.get("terminal-output-s1")!;
await act(async () => {
emit({ payload: Array.from(new TextEncoder().encode(`\x1b]7777;open;${btoa("https://example.com/live")}\x07`)) });
await new Promise((r) => setTimeout(r, 0));
});
await settle();
expect(document.querySelector(URL_TOAST_SELECTOR)).not.toBeNull();
});
it("an ordinary tab's exit just ends it", async () => {
mountSession("bash");
await settle();
const exit = ptyOutput.listeners.get("terminal-exit-s1");
if (!exit) throw new Error("no exit listener");
await act(async () => exit({ payload: [] }));
await settle();
expect(reattachTerminalSession).not.toHaveBeenCalled();
expect(screenText()).toContain("[Session ended]");
});
});
+117 -1
View File
@@ -37,6 +37,8 @@ import { decodeOsc52 } from "./osc52";
import { resolveTerminalGpuRendering } from "../../lib/terminalRenderer";
import TerminalContextMenu from "./TerminalContextMenu";
import { createFilePathLinkProvider } from "./filePathLinkProvider";
import { reattachTerminalSession } from "../../lib/tauri-commands";
import { nextReconnect, reattachWithRetry } from "../../lib/persistentTerminals";
import type { FilePathMatch } from "../../lib/filePathLinks";
interface Props {
@@ -751,6 +753,19 @@ export default function TerminalView({ sessionId, active }: Props) {
const sessionTypeRef = useRef(sessionType);
sessionTypeRef.current = sessionType;
// A persistent AWS terminal (tmux in the workspace): a lost connection
// reattaches rather than ending the tab, and a tab opened for a session
// already running attaches once its listeners are up. Refs, for the same
// reason as `sessionTypeRef`.
const persistent = useAppState(
(s) => s.sessions.find((sess) => sess.id === sessionId)?.persistent ?? false
);
const persistentRef = useRef(persistent);
persistentRef.current = persistent;
const pendingReattachRef = useRef(
useAppState.getState().sessions.find((sess) => sess.id === sessionId)?.pendingReattach ?? false
);
// One toast slot, three producers: the container's explicit "open this in the
// host browser" relay (OSC 7777), OSC 8 hyperlink targets, and the heuristic
// long-URL detector. Sharing the slot keeps them from stacking on top of each
@@ -1342,8 +1357,19 @@ export default function TerminalView({ sessionId, active }: Props) {
const SSO_MARKER = "###TRIPLE_C_SSO_REFRESH###";
const textDecoder = new TextDecoder();
// While a reattach replays a session's history, its old URLs and markers
// must not pop toasts or trigger an SSO refresh again.
let replaying = false;
const outputPromise = onOutput(sessionId, (data) => {
if (aborted) return;
if (replaying) {
// The backend sends a replay as exactly one chunk (empty when there
// is no history) before attaching: everything after it is live.
replaying = false;
term.write(data, syncMouseCapture);
return;
}
// Scrolling on new output is xterm's own job, and it already gets it
// right: it follows the tail while the viewport is at the bottom and
// holds position while you are reading further up. The manual
@@ -1372,14 +1398,104 @@ export default function TerminalView({ sessionId, active }: Props) {
return unlisten;
});
const ended = () => term.write("\r\n\x1b[33m[Session ended]\x1b[0m\r\n");
// Attach to the session in the workspace again: after a lost connection
// (`rows` null: the screen is still here) or for a freshly opened tab
// (`rows`: replay the history into scrollback first).
let reconnecting = false;
const reconnect = async (rows: number | null) => {
const pid = projectIdRef.current;
if (reconnecting || !pid) return;
reconnecting = true;
replaying = rows !== null;
let said = false;
const result = await reattachWithRetry({
reattach: () => reattachTerminalSession(pid, sessionId, rows),
stillWanted: () => {
const st = useAppState.getState();
return (
!aborted &&
(st.sessions.find((x) => x.id === sessionId)?.persistent ?? false) &&
st.projects.find((p) => p.id === pid)?.status === "running"
);
},
onRetrying: () => {
if (said || aborted) return;
said = true;
term.write("\r\n\x1b[33m[Connection lost — reconnecting…]\x1b[0m\r\n");
},
});
replaying = false;
reconnecting = false;
pendingReattachRef.current = false;
if (aborted) return;
const update = useAppState.getState().updateSession;
switch (result) {
case "reattached":
lastReattachAt = Date.now();
update(sessionId, { pendingReattach: false });
// tmux follows the newest client's size.
resize(sessionId, term.cols, term.rows).catch(() => {});
break;
case "ended":
case "cancelled":
update(sessionId, { persistent: false, pendingReattach: false });
ended();
break;
case "gave_up":
term.write(
"\r\n\x1b[33m[Disconnected. The session may still be running in the workspace: " +
"Project Home → Sessions can reattach it.]\x1b[0m\r\n",
);
break;
}
};
// An attach that keeps dropping right after it succeeds (a client that
// cannot stay attached) must not loop: back off, then stop.
let lastReattachAt = 0;
let quickExits = 0;
const exitPromise = onExit(sessionId, () => {
if (aborted) return;
term.write("\r\n\x1b[33m[Session ended]\x1b[0m\r\n");
if (persistentRef.current) {
const plan = nextReconnect(lastReattachAt, Date.now(), quickExits);
quickExits = plan.quickExits;
if (plan.delayMs === null) {
term.write(
"\r\n\x1b[33m[Disconnected: the session keeps dropping. It may still be running in " +
"the workspace: Project Home → Sessions can reattach or end it.]\x1b[0m\r\n",
);
return;
}
if (plan.delayMs === 0) void reconnect(null);
else
setTimeout(() => {
if (!aborted) void reconnect(null);
}, plan.delayMs);
return;
}
ended();
}).then((unlisten) => {
if (aborted) unlisten();
return unlisten;
});
// A tab opened for a running session attaches only now, with both
// listeners registered, so neither its history nor tmux's first draw is
// lost.
if (pendingReattachRef.current) {
Promise.all([outputPromise, exitPromise]).then(() => {
if (aborted) return;
try {
fitAddon.fit();
} catch {
// Hidden tab: it is fitted (and tmux resized) when shown.
}
void reconnect(term.rows);
});
}
// Handle resize (throttled via requestAnimationFrame to avoid excessive calls).
// Skip resize work for hidden terminals — containerRef will have 0 dimensions.
let resizeRafId: number | null = null;
+19
View File
@@ -74,4 +74,23 @@ describe("Button", () => {
fireEvent.click(button);
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;
/** Why the button cannot be used. Required for `unavailable` to say anything. */
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`. */
ref?: Ref<HTMLButtonElement>;
}
@@ -48,6 +53,12 @@ const SIZES: Record<ButtonSize, string> = {
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({
variant = "secondary",
size = "sm",
@@ -55,6 +66,7 @@ export default function Button({
type = "button",
unavailable = false,
unavailableReason = "",
wrap = false,
children,
...rest
}: Props) {
@@ -71,7 +83,7 @@ export default function Button({
type={type}
{...rest}
{...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}
</button>
+1 -1
View File
@@ -208,7 +208,7 @@ export default function Modal({
</div>
{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}
</div>
)}
+4 -1
View File
@@ -53,6 +53,8 @@ interface Props {
iconOnly?: boolean;
className?: string;
title?: string;
/** Let a long label (a failure summary) wrap instead of overflowing its container. */
wrap?: boolean;
}
export default function StatusIndicator({
@@ -61,11 +63,12 @@ export default function StatusIndicator({
iconOnly = false,
className = "",
title,
wrap = false,
}: Props) {
const style = TONES[tone];
return (
<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}
>
<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 { useDocker } from "./useDocker";
const checkDocker = vi.fn();
const getDockerStatus = vi.fn();
const checkImageExists = vi.fn();
vi.mock("../lib/tauri-commands", () => ({
checkDocker: () => checkDocker(),
getDockerStatus: () => getDockerStatus(),
checkImageExists: () => checkImageExists(),
buildImage: 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()) }));
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();
vi.mock("../store/appState", () => ({
@@ -22,6 +24,8 @@ vi.mock("../store/appState", () => ({
selector({
dockerAvailable: false,
setDockerAvailable,
dockerStatus: null,
setDockerStatus,
imageExists: false,
setImageExists,
}),
@@ -49,7 +53,7 @@ describe("useDocker.startDockerPolling", () => {
});
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 { result } = renderHook(() => useDocker());
@@ -59,9 +63,11 @@ describe("useDocker.startDockerPolling", () => {
await tick();
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();
expect(setDockerAvailable).toHaveBeenCalledWith(true);
expect(setDockerStatus).toHaveBeenLastCalledWith(status("running"));
expect(setImageExists).toHaveBeenCalledWith(true);
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 () => {
checkDocker.mockResolvedValue(true);
getDockerStatus.mockResolvedValue(status("running"));
const { result } = renderHook(() => useDocker());
let stop: () => void = () => {};
@@ -81,7 +87,7 @@ describe("useDocker.startDockerPolling", () => {
act(() => stop());
await tick();
expect(checkDocker).not.toHaveBeenCalled();
expect(setDockerAvailable).not.toHaveBeenCalled();
expect(getDockerStatus).not.toHaveBeenCalled();
expect(setDockerStatus).not.toHaveBeenCalled();
});
});
+18 -9
View File
@@ -7,12 +7,16 @@ import * as commands from "../lib/tauri-commands";
export function useDocker() {
const {
dockerAvailable,
dockerStatus,
setDockerStatus,
setDockerAvailable,
imageExists,
setImageExists,
} = useAppState(
useShallow(s => ({
dockerAvailable: s.dockerAvailable,
dockerStatus: s.dockerStatus,
setDockerStatus: s.setDockerStatus,
setDockerAvailable: s.setDockerAvailable,
imageExists: s.imageExists,
setImageExists: s.setImageExists,
@@ -21,14 +25,14 @@ export function useDocker() {
const checkDocker = useCallback(async () => {
try {
const available = await commands.checkDocker();
setDockerAvailable(available);
return available;
const status = await commands.getDockerStatus();
setDockerStatus(status);
return status.state === "running";
} catch {
setDockerAvailable(false);
return false;
}
}, [setDockerAvailable]);
}, [setDockerStatus, setDockerAvailable]);
const checkImage = useCallback(async () => {
try {
@@ -62,7 +66,9 @@ export function useDocker() {
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
* image has been re-checked. It exists because a session that started before
@@ -75,11 +81,11 @@ export function useDocker() {
const interval = setInterval(async () => {
try {
const available = await commands.checkDocker();
if (available) {
const status = await commands.getDockerStatus();
if (status.state === "running") {
clearInterval(interval);
pollingRef.current = null;
setDockerAvailable(true);
setDockerStatus(status);
// Also check image once Docker is available
try {
const exists = await commands.checkImageExists();
@@ -92,6 +98,8 @@ export function useDocker() {
} catch (e) {
console.error("Docker-available callback failed:", e);
}
} else {
setDockerStatus(status);
}
} catch {
// Still not available, keep polling
@@ -103,7 +111,7 @@ export function useDocker() {
clearInterval(interval);
pollingRef.current = null;
};
}, [setDockerAvailable, setImageExists]);
}, [setDockerStatus, setImageExists]);
const pullImage = useCallback(
async (imageName: string, onProgress?: (msg: string) => void) => {
@@ -125,6 +133,7 @@ export function useDocker() {
return {
dockerAvailable,
dockerStatus,
imageExists,
checkDocker,
checkImage,
@@ -0,0 +1,91 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const listWorkspaceTerminals = vi.fn();
const openTerminalSession = vi.fn();
vi.mock("../lib/tauri-commands", () => ({
listWorkspaceTerminals: (id: string) => listWorkspaceTerminals(id),
openTerminalSession: (...a: unknown[]) => openTerminalSession(...a),
}));
vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn() }));
import { act, renderHook, waitFor } from "@testing-library/react";
import { useAppState } from "../store/appState";
import { resetPersistentTerminalSync, syncProjectTerminals, usePersistentTerminals } from "./usePersistentTerminals";
import { useTerminal } from "./useTerminal";
import type { Project, WorkspaceTerminal } from "../lib/types";
const aws = (container_id: string | null, status = "running") =>
({ id: "p1", name: "api", host_id: "h1", status, container_id }) as unknown as Project;
const t = (id: string, known: boolean): WorkspaceTerminal => ({
session_id: id,
kind: "claude",
name: null,
created_unix: 1,
attached: false,
known,
});
beforeEach(() => {
resetPersistentTerminalSync();
listWorkspaceTerminals.mockReset();
useAppState.setState({ projects: [], sessions: [], tabOrder: [], activeTabKey: null, toasts: [] } as never);
});
describe("usePersistentTerminals", () => {
it("reopens this app's running terminals once per connection, in the background", async () => {
// Something else is the current tab: the reopened ones must not take focus.
useAppState.getState().addSession({ id: "mine", projectId: "p2", projectName: "x", sessionType: "bash", sessionName: null });
listWorkspaceTerminals.mockResolvedValue([t("a", true), t("elsewhere", false), t("b", true)]);
useAppState.setState({ projects: [aws("http://127.0.0.1:5000/")] } as never);
const { rerender } = renderHook(() => usePersistentTerminals());
await waitFor(() => expect(useAppState.getState().sessions).toHaveLength(3));
const s = useAppState.getState();
expect(s.sessions.slice(1).map((x) => [x.id, x.pendingReattach, x.persistent])).toEqual([
["a", true, true],
["b", true, true],
]);
expect(s.activeSessionId).toBe("mine");
expect(s.toasts.some((x) => x.message.includes("Reopened 2 terminals"))).toBe(true);
// The same connection again: nothing more is asked.
rerender();
act(() => useAppState.setState({ projects: [aws("http://127.0.0.1:5000/")] } as never));
expect(listWorkspaceTerminals).toHaveBeenCalledTimes(1);
// A new connection (re-attach on another port) lists again; open tabs
// are not opened twice.
act(() => useAppState.setState({ projects: [aws("http://127.0.0.1:6000/")] } as never));
await waitFor(() => expect(listWorkspaceTerminals).toHaveBeenCalledTimes(2));
expect(useAppState.getState().sessions).toHaveLength(3);
});
it("leaves Docker and stopped projects alone", async () => {
useAppState.setState({
projects: [
{ id: "d", name: "local", host_id: null, status: "running", container_id: "abc" } as unknown as Project,
aws("http://127.0.0.1:5000/", "stopped"),
],
} as never);
renderHook(() => usePersistentTerminals());
await new Promise((r) => setTimeout(r, 10));
expect(listWorkspaceTerminals).not.toHaveBeenCalled();
});
});
it("does not reopen a tab whose own open is still in flight", async () => {
let finishOpen: (v: unknown) => void = () => {};
openTerminalSession.mockImplementation(() => new Promise((r) => (finishOpen = r)));
const { result } = renderHook(() => useTerminal());
const opening = result.current.open("p1", "api");
const id = openTerminalSession.mock.calls[0][1] as string;
// The workspace already lists (and remembers) it.
listWorkspaceTerminals.mockResolvedValue([t(id, true)]);
expect(await syncProjectTerminals(aws("http://127.0.0.1:5000/"))).toBe(0);
finishOpen({ persistent: true, notice: null });
await act(async () => {
await opening;
});
expect(useAppState.getState().sessions.filter((s) => s.id === id)).toHaveLength(1);
expect(useAppState.getState().sessions[0].pendingReattach).toBeUndefined();
});
+66
View File
@@ -0,0 +1,66 @@
import { useEffect } from "react";
import { useAppState } from "../store/appState";
import { isAwsProject } from "../lib/awsWorkspace";
import { listWorkspaceTerminals } from "../lib/tauri-commands";
import { reattachTab, terminalsToReopen } from "../lib/persistentTerminals";
import type { Project } from "../lib/types";
import { isOpening } from "./useTerminal";
/** Connections already synced this run, `<project id>|<target id>`: an AWS
* project's `container_id` is its tunnel's endpoint, new on every connect. */
const synced = new Set<string>();
/** For tests. */
export function resetPersistentTerminalSync() {
synced.clear();
}
function connectionKey(p: Project): string | null {
if (!isAwsProject(p) || p.status !== "running" || !p.container_id) return null;
return `${p.id}|${p.container_id}`;
}
/**
* Reopen a project's tabs once per connection to its AWS workspace (app
* start with the workspace still running, a Start that attached to a running
* task, a re-attach): the terminals this app opened that still run there
* come back as tabs, in the order they were opened, without stealing focus.
* The backend waits for a re-attach in progress before listing.
*/
export async function syncProjectTerminals(project: Project): Promise<number> {
const running = await listWorkspaceTerminals(project.id);
const state = useAppState.getState();
const open = new Set(state.sessions.map((s) => s.id));
// A tab being opened right now is listed (and remembered) before its
// own addSession lands: never a second copy of it.
const reopen = terminalsToReopen(running, open).filter((t) => !isOpening(t.session_id));
for (const t of reopen) {
state.addSession(reattachTab(project.id, project.name, t), { activate: false });
}
if (reopen.length > 0) {
state.pushToast({
kind: "info",
message: `Reopened ${reopen.length} terminal${reopen.length === 1 ? "" : "s"} still running in “${project.name}”`,
dedupeKey: `terminals-reopened-${project.id}`,
});
}
return reopen.length;
}
/** App-wide: run [`syncProjectTerminals`] for each new AWS connection. */
export function usePersistentTerminals() {
const projects = useAppState((s) => s.projects);
useEffect(() => {
for (const p of projects) {
const key = connectionKey(p);
if (!key || synced.has(key)) continue;
synced.add(key);
syncProjectTerminals(p).catch((e) => {
// Not connected yet, or the workspace did not answer: a later
// connection (new container_id) tries again.
synced.delete(key);
console.warn(`Could not list the terminals of “${p.name}”:`, e);
});
}
}, [projects]);
}
@@ -0,0 +1,56 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const openTerminalSession = vi.fn();
const closeTerminalSession = vi.fn();
vi.mock("../lib/tauri-commands", () => ({
openTerminalSession: (...a: unknown[]) => openTerminalSession(...a),
closeTerminalSession: (id: string) => closeTerminalSession(id),
terminalInput: vi.fn(),
terminalResize: vi.fn(),
pasteImageToTerminal: vi.fn(),
updateProject: vi.fn(),
}));
vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn() }));
import { renderHook } from "@testing-library/react";
import { useTerminal } from "./useTerminal";
import { useAppState } from "../store/appState";
beforeEach(() => {
openTerminalSession.mockReset();
closeTerminalSession.mockReset();
useAppState.setState({ projects: [], sessions: [], tabOrder: [], activeTabKey: null, toasts: [] } as never);
});
describe("useTerminal and persistent AWS terminals", () => {
it("marks a tab persistent when the workspace keeps it", async () => {
openTerminalSession.mockResolvedValue({ persistent: true, notice: null });
const { result } = renderHook(() => useTerminal());
const id = await result.current.open("p1", "api", "bash");
expect(useAppState.getState().sessions.find((s) => s.id === id)?.persistent).toBe(true);
expect(useAppState.getState().toasts).toHaveLength(0);
});
it("says once that the image has no tmux", async () => {
openTerminalSession.mockResolvedValue({ persistent: false, notice: "This workspace image has no tmux, so …" });
const { result } = renderHook(() => useTerminal());
await result.current.open("p1", "api");
await result.current.open("p1", "api");
const toasts = useAppState.getState().toasts.filter((t) => t.message.includes("no tmux"));
expect(toasts).toHaveLength(1);
expect(useAppState.getState().sessions.every((s) => !s.persistent)).toBe(true);
});
it("closing a tab is not mistaken for a lost connection", async () => {
openTerminalSession.mockResolvedValue({ persistent: true, notice: null });
let persistentWhenClosed: boolean | undefined;
closeTerminalSession.mockImplementation(async (id: string) => {
persistentWhenClosed = useAppState.getState().sessions.find((s) => s.id === id)?.persistent;
});
const { result } = renderHook(() => useTerminal());
const id = await result.current.open("p1", "api");
await result.current.close(id);
expect(persistentWhenClosed).toBe(false);
expect(useAppState.getState().sessions).toHaveLength(0);
});
});
+35 -2
View File
@@ -84,6 +84,14 @@ function discardInputQueue(sessionId: string): void {
if (!q.draining) inputQueues.delete(sessionId);
}
/** Session ids whose `open_terminal_session` is in flight: a reconnect sync
* listing the workspace meanwhile must not reopen them as a second tab. */
const opening = new Set<string>();
export function isOpening(sessionId: string): boolean {
return opening.has(sessionId);
}
export function useTerminal() {
const { sessions, activeSessionId, addSession, removeSession, setActiveSession } =
useAppState(
@@ -105,8 +113,30 @@ export function useTerminal() {
resumeSessionId?: string,
) => {
const sessionId = crypto.randomUUID();
await commands.openTerminalSession(projectId, sessionId, sessionType, sessionName, resumeSessionId);
addSession({ id: sessionId, projectId, projectName, sessionType, sessionName: sessionName ?? null });
opening.add(sessionId);
let opened;
try {
opened = await commands.openTerminalSession(projectId, sessionId, sessionType, sessionName, resumeSessionId);
} catch (e) {
opening.delete(sessionId);
throw e;
}
opening.delete(sessionId);
addSession({
id: sessionId,
projectId,
projectName,
sessionType,
sessionName: sessionName ?? null,
persistent: opened?.persistent ?? false,
});
if (opened?.notice) {
useAppState.getState().pushToast({
kind: "info",
message: opened.notice,
dedupeKey: `no-tmux-${projectId}`,
});
}
return sessionId;
},
[addSession],
@@ -120,6 +150,9 @@ export function useTerminal() {
const project = session ? projects.find((p) => p.id === session.projectId) : undefined;
discardInputQueue(sessionId);
// A closed tab ends its session: the exit this causes must not read
// as a dropped connection to reattach.
useAppState.getState().updateSession(sessionId, { persistent: false, pendingReattach: false });
await commands.closeTerminalSession(sessionId);
removeSession(sessionId);
+19 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
import { awsErrorMessage, toAwsError } from "./aws-error";
import { awsErrorMessage, looksDenied, toAwsError } from "./aws-error";
describe("toAwsError", () => {
it("passes a tagged AwsError through", () => {
@@ -21,3 +21,21 @@ describe("toAwsError", () => {
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.";
case "state_bucket_taken":
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:
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);
}
+8
View File
@@ -323,3 +323,11 @@ export const EC2_DOCKER_ACCESS_NOTE =
export const EC2_VPN_HINT =
"Grants NET_ADMIN, the /dev/net/tun device and src_valid_mark so a VPN client (PIA, WireGuard, OpenVPN) can build a tunnel inside the workspace, an ECS task on your own EC2 instance. Anything in the workspace can then reconfigure the task's own network stack; the instance's is untouched. Applies on the project's next start.";
export const EC2_NO_CAPACITY = "Ask an admin to add EC2 capacity to your onboarding";
/** Persistent terminals (`host/persistent.rs`): the cost of the user's goal
* that a Claude session keeps working with the app closed. */
export const PERSISTENT_TERMINALS_NOTE =
"Terminals keep running in the workspace when you close Triple-C. A Claude session left " +
"running keeps the workspace up (and billed) after you close the app — until it ends, you " +
"end it in Project Home → Sessions, you Stop, or the lifetime cap. Shells left open do not " +
"keep it up.";
+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";
}
}
+92
View File
@@ -0,0 +1,92 @@
import { describe, it, expect, vi } from "vitest";
import { nextReconnect, reattachTab, reattachWithRetry, terminalLabel, terminalsToReopen, RECONNECT_DELAY_MS } from "./persistentTerminals";
import type { ReattachOutcome, WorkspaceTerminal } from "./types";
const noSleep = () => Promise.resolve();
const reattached: ReattachOutcome = { outcome: "reattached", kind: "claude", name: null };
const term = (id: string, known: boolean, kind: "claude" | "bash" = "bash", name: string | null = null): WorkspaceTerminal => ({
session_id: id,
kind,
name,
created_unix: 1,
attached: false,
known,
});
describe("reattachWithRetry", () => {
it("reattaches at once when the workspace answers", async () => {
const reattach = vi.fn(async () => reattached);
expect(await reattachWithRetry({ reattach, stillWanted: () => true, sleep: noSleep })).toBe("reattached");
expect(reattach).toHaveBeenCalledTimes(1);
});
it("stops at once when the session is gone, without retrying", async () => {
const reattach = vi.fn(async (): Promise<ReattachOutcome> => ({ outcome: "ended" }));
expect(await reattachWithRetry({ reattach, stillWanted: () => true, sleep: noSleep })).toBe("ended");
expect(reattach).toHaveBeenCalledTimes(1);
});
it("retries while the workspace is unreachable, saying so, then reattaches", async () => {
const reattach = vi
.fn<() => Promise<ReattachOutcome>>()
.mockRejectedValueOnce("not connected")
.mockRejectedValueOnce("not connected")
.mockResolvedValue(reattached);
const onRetrying = vi.fn();
const sleep = vi.fn(noSleep);
const r = await reattachWithRetry({ reattach, stillWanted: () => true, onRetrying, sleep, delayMs: 7 });
expect(r).toBe("reattached");
expect(onRetrying).toHaveBeenCalledTimes(2);
expect(sleep).toHaveBeenCalledWith(7);
});
it("gives up after its attempts, and is cancelled when the tab or project stops wanting it", async () => {
const failing = vi.fn(async (): Promise<ReattachOutcome> => {
throw new Error("down");
});
expect(await reattachWithRetry({ reattach: failing, stillWanted: () => true, sleep: noSleep, attempts: 3 })).toBe("gave_up");
expect(failing).toHaveBeenCalledTimes(3);
let wanted = true;
const stopping = vi.fn(async (): Promise<ReattachOutcome> => {
wanted = false; // the project stopped meanwhile
throw new Error("not running");
});
expect(await reattachWithRetry({ reattach: stopping, stillWanted: () => wanted, sleep: noSleep })).toBe("cancelled");
expect(stopping).toHaveBeenCalledTimes(1);
});
});
describe("which terminals come back as tabs", () => {
it("reopens only this app's terminals that are not open, in order", () => {
const running = [term("a", true), term("b", false), term("c", true), term("d", true)];
expect(terminalsToReopen(running, new Set(["c"])).map((t) => t.session_id)).toEqual(["a", "d"]);
});
it("makes a reattaching persistent tab with the workspace's kind and label", () => {
expect(reattachTab("p1", "api", term("k", true, "claude", "main"))).toEqual({
id: "k",
projectId: "p1",
projectName: "api",
sessionType: "claude",
sessionName: "main",
persistent: true,
pendingReattach: true,
});
expect(terminalLabel(term("k", true, "claude"))).toBe("Claude Code");
expect(terminalLabel(term("k", true, "bash"))).toBe("Shell");
});
});
describe("nextReconnect", () => {
it("reattaches at once after a long-lived attach, backs off on quick drops, then stops", () => {
expect(nextReconnect(0, 10_000, 0)).toEqual({ delayMs: 0, quickExits: 0 });
expect(nextReconnect(1_000, 60_000, 2)).toEqual({ delayMs: 0, quickExits: 0 });
let r = nextReconnect(1_000, 2_000, 0);
expect(r).toEqual({ delayMs: RECONNECT_DELAY_MS, quickExits: 1 });
r = nextReconnect(1_000, 2_000, r.quickExits);
expect(r).toEqual({ delayMs: RECONNECT_DELAY_MS * 2, quickExits: 2 });
expect(nextReconnect(1_000, 2_000, r.quickExits).delayMs).toBeNull();
});
});
+103
View File
@@ -0,0 +1,103 @@
import type { ReattachOutcome, TerminalSession, WorkspaceTerminal } from "./types";
/**
* Persistent AWS terminals (`host/persistent.rs`): every tab on an AWS
* workspace whose image has tmux runs in its own tmux server, so it outlives
* the app and a dropped connection. These are the frontend's rules for
* getting back to one.
*/
/** How long a tab keeps trying after its connection dropped. */
export const RECONNECT_ATTEMPTS = 40;
export const RECONNECT_DELAY_MS = 3000;
export type ReattachResult = "reattached" | "ended" | "gave_up" | "cancelled";
/**
* Attach a tab to its workspace session again, retrying while the workspace
* cannot be reached (the tunnel is being re-opened). Ends as soon as the
* workspace says the session is gone (`ended`), or when the tab or project
* no longer wants it (`cancelled`: closed, stopped).
*/
export async function reattachWithRetry(opts: {
reattach: () => Promise<ReattachOutcome>;
stillWanted: () => boolean;
onRetrying?: (error: unknown) => void;
sleep?: (ms: number) => Promise<void>;
attempts?: number;
delayMs?: number;
}): Promise<ReattachResult> {
const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
const attempts = opts.attempts ?? RECONNECT_ATTEMPTS;
const delay = opts.delayMs ?? RECONNECT_DELAY_MS;
for (let i = 0; i < attempts; i++) {
if (!opts.stillWanted()) return "cancelled";
try {
const out = await opts.reattach();
return out.outcome === "reattached" ? "reattached" : "ended";
} catch (e) {
opts.onRetrying?.(e);
}
if (i + 1 < attempts) await sleep(delay);
}
return opts.stillWanted() ? "gave_up" : "cancelled";
}
/** An exit this soon after a successful reattach counts as a quick one. */
export const QUICK_EXIT_MS = 5000;
/** Quick exits in a row before a tab stops reattaching on its own. */
export const MAX_QUICK_EXITS = 3;
/**
* What a persistent tab does when its exec ends: reattach now (`delayMs` 0),
* after a back-off, or stop (`null`) when attaches keep dropping right after
* they succeed. `quickExits` is the new count to keep.
*/
export function nextReconnect(
lastReattachAt: number,
now: number,
quickExits: number,
): { delayMs: number | null; quickExits: number } {
const quick = lastReattachAt > 0 && now - lastReattachAt < QUICK_EXIT_MS;
const count = quick ? quickExits + 1 : 0;
if (count >= MAX_QUICK_EXITS) return { delayMs: null, quickExits: count };
return { delayMs: count === 0 ? 0 : RECONNECT_DELAY_MS * count, quickExits: count };
}
/** The tab label a workspace terminal gets when nothing else names it. */
export function terminalLabel(t: Pick<WorkspaceTerminal, "kind" | "name">): string {
return t.name ?? (t.kind === "claude" ? "Claude Code" : "Shell");
}
/**
* The tab for a workspace terminal: it attaches (and replays its history)
* once its view is listening.
*/
export function reattachTab(
projectId: string,
projectName: string,
t: WorkspaceTerminal,
): TerminalSession {
return {
id: t.session_id,
projectId,
projectName,
sessionType: t.kind,
sessionName: t.name,
persistent: true,
pendingReattach: true,
};
}
/**
* Which of a workspace's terminals to reopen as tabs after a connect: the
* ones this app opened (`known`) that are not already open. Sessions from
* elsewhere (another machine, the web terminal) are listed in Project Home →
* Sessions instead, never opened unasked.
*/
export function terminalsToReopen(
running: WorkspaceTerminal[],
openIds: ReadonlySet<string>,
): WorkspaceTerminal[] {
return running.filter((t) => t.known && !openIds.has(t.session_id));
}
+14 -2
View File
@@ -1,8 +1,9 @@
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, OpenedTerminal, WorkspaceTerminal, ReattachOutcome } from "./types";
// 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 buildImage = () => invoke<void>("build_image");
export const getContainerInfo = (projectId: string) =>
@@ -234,13 +235,24 @@ export const openTerminalSession = (
sessionName?: string,
resumeSessionId?: string,
) =>
invoke<void>("open_terminal_session", { projectId, sessionId, sessionType, sessionName, resumeSessionId });
invoke<OpenedTerminal>("open_terminal_session", { projectId, sessionId, sessionType, sessionName, resumeSessionId });
export const terminalInput = (sessionId: string, data: number[]) =>
invoke<void>("terminal_input", { sessionId, data });
export const terminalResize = (sessionId: string, cols: number, rows: number) =>
invoke<void>("terminal_resize", { sessionId, cols, rows });
export const closeTerminalSession = (sessionId: string) =>
invoke<void>("close_terminal_session", { sessionId });
/** AWS: the terminals running in the workspace (empty elsewhere). */
export const listWorkspaceTerminals = (projectId: string) =>
invoke<WorkspaceTerminal[]>("list_workspace_terminals", { projectId });
/** Attach a tab to a terminal still running in the workspace. `rows` (a
* fresh xterm) replays its history first. Register the output listener
* before calling. */
export const reattachTerminalSession = (projectId: string, sessionId: string, rows: number | null) =>
invoke<ReattachOutcome>("reattach_terminal_session", { projectId, sessionId, rows });
/** End a workspace terminal that has no tab here. */
export const endWorkspaceTerminal = (projectId: string, sessionId: string) =>
invoke<void>("end_workspace_terminal", { projectId, sessionId });
export const pasteImageToTerminal = (sessionId: string, imageData: number[]) =>
invoke<string>("paste_image_to_terminal", { sessionId, imageData });
export const uploadHostFileToTerminal = (sessionId: string, hostPath: string) =>
+43
View File
@@ -339,8 +339,40 @@ export interface TerminalSession {
projectName: string;
sessionType: "claude" | "bash";
sessionName: string | null;
/** Runs in tmux in an AWS workspace and outlives the app
* (`host/persistent.rs`): a lost connection reattaches instead of ending. */
persistent?: boolean;
/** Opened for a session already running in the workspace: the view
* attaches (and replays its history) once its listeners are up. */
pendingReattach?: boolean;
}
/** `models/terminal.rs` (`host::persistent::TerminalKind`). */
export type TerminalKind = "claude" | "bash";
/** `open_terminal_session`'s answer. */
export interface OpenedTerminal {
persistent: boolean;
/** Say once: the workspace image has no tmux. */
notice: string | null;
}
/** A terminal running in an AWS workspace (`list_workspace_terminals`). */
export interface WorkspaceTerminal {
session_id: string;
kind: TerminalKind;
name: string | null;
created_unix: number;
attached: boolean;
/** This app opened it and reopens it on connect. */
known: boolean;
}
/** `reattach_terminal_session`'s answer. */
export type ReattachOutcome =
| { outcome: "reattached"; kind: TerminalKind; name: string | null }
| { outcome: "ended" };
export type ImageSource = "registry" | "local_build" | "custom";
export interface GlobalAwsSettings {
@@ -702,6 +734,17 @@ export interface FileContents {
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 {
os: "linux" | "macos" | "windows" | "unknown";
product_name: string;
+22 -4
View File
@@ -3,6 +3,7 @@ import type {
Project,
TerminalSession,
AppSettings,
DockerStatus,
UpdateInfo,
ImageUpdateInfo,
Note,
@@ -128,7 +129,10 @@ interface AppState {
// Terminal sessions
sessions: TerminalSession[];
activeSessionId: string | null;
addSession: (session: TerminalSession) => void;
/** Adds the tab and makes it current, unless `activate` is false (tabs
* reopened in the background after a reconnect). */
addSession: (session: TerminalSession, opts?: { activate?: boolean }) => void;
updateSession: (id: string, patch: Partial<Omit<TerminalSession, "id">>) => void;
removeSession: (id: string) => void;
setActiveSession: (id: string | null) => void;
@@ -243,6 +247,10 @@ interface AppState {
setNotesDockWidth: (width: number) => void;
dockerAvailable: boolean | null;
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;
setImageExists: (exists: boolean | null) => void;
// App settings
@@ -324,17 +332,24 @@ export const useAppState = create<AppState>((set) => ({
// Terminal sessions
sessions: [],
activeSessionId: null,
addSession: (session) =>
addSession: (session, opts) =>
set((state) => {
const key = terminalTabKey(session.id);
const activate = opts?.activate ?? true;
return {
sessions: [...state.sessions, session],
sessions: state.sessions.some((s) => s.id === session.id)
? state.sessions.map((s) => (s.id === session.id ? session : s))
: [...state.sessions, session],
tabOrder: state.tabOrder.includes(key)
? state.tabOrder
: [...state.tabOrder, key],
...activation(key),
...(activate || state.activeTabKey === null ? activation(key) : {}),
};
}),
updateSession: (id, patch) =>
set((state) => ({
sessions: state.sessions.map((s) => (s.id === id ? { ...s, ...patch } : s)),
})),
removeSession: (id) =>
set((state) => {
const key = terminalTabKey(id);
@@ -569,6 +584,9 @@ export const useAppState = create<AppState>((set) => ({
},
dockerAvailable: null,
setDockerAvailable: (available) => set({ dockerAvailable: available }),
dockerStatus: null,
setDockerStatus: (status) =>
set({ dockerStatus: status, dockerAvailable: status.state === "running" }),
imageExists: null,
setImageExists: (exists) => set({ imageExists: exists }),
// App settings
+12 -1
View File
@@ -322,7 +322,12 @@ RUN npx --yes playwright@latest --version \
&& npx --yes playwright@latest install-deps --dry-run chromium \
&& rm -rf /var/lib/apt/lists/* /root/.npm
# ── Python 3 + pip + uv + ruff ──────────────────────────────────────────────
# ── Python 3 + pip + uv + ruff (and tmux) ───────────────────────────────────
# `tmux` rides this layer, the last apt layer and the cheapest to change: it
# keeps AWS workspaces' terminals alive while the app is closed (one tmux
# server per tab, app/src-tauri/src/host/persistent.rs, config
# /etc/triple-c/tmux.conf below). Unused on Docker projects. +3 packages
# (tmux, libevent-core, libutempter0), ~1.5 MB installed.
ARG APT_REFRESH=
RUN echo "apt refresh: ${APT_REFRESH:-unset}" \
&& for i in 1 2 3 4 5; do \
@@ -335,6 +340,7 @@ RUN echo "apt refresh: ${APT_REFRESH:-unset}" \
python3 \
python3-pip \
python3-venv \
tmux \
&& rm -rf /var/lib/apt/lists/*
# ── Docker CLI (not daemon) ─────────────────────────────────────────────────
@@ -503,6 +509,11 @@ COPY triple-c-workspace-status /usr/local/bin/triple-c-workspace-status
COPY triple-c-apply-connect /usr/local/bin/triple-c-apply-connect
RUN chmod 755 /usr/local/bin/triple-c-wip-push /usr/local/bin/triple-c-idle-watch \
/usr/local/bin/triple-c-workspace-status /usr/local/bin/triple-c-apply-connect
# The tmux config every persistent AWS terminal runs with (`tmux -f`). Outside
# /home/claude, which is seed-only, so an image update reaches it; the app
# probes for it and runs terminals the old way without it.
COPY triple-c-tmux.conf /etc/triple-c/tmux.conf
RUN chmod 755 /etc/triple-c && chmod 644 /etc/triple-c/tmux.conf
# Root-owned in /usr/local/bin: entrypoint.sh starts it as root (only when a
# token is configured), and it rides the snapshot and migration like the other
# shims here.
+33
View File
@@ -881,6 +881,38 @@ start_agent
# >>> aws_stop
triplec_idle_exit=75
triplec_lifetime_exit=76
# Persistent terminals (one tmux server per app tab, `tmux -L triple-c-<id>`,
# app/src-tauri/src/host/persistent.rs) outlive the app, so a detached shell or
# Claude could still be writing while the push below takes its snapshot: end
# them first (as the user that owns them; bounded wait for the servers to go).
# The app's own Stop does the same before its push.
aws_end_terminals() {
command -v tmux >/dev/null 2>&1 || return 0
local script
# >>> end_terminals (app/src-tauri/src/host/persistent.rs END_ALL_SCRIPT, verbatim)
script=$(cat <<'TRIPLEC_END_TERMINALS'
d="${TMUX_TMPDIR:-/tmp}/tmux-$(id -u)"
command -v tmux >/dev/null 2>&1 || exit 0
pids=""
for s in "$d"/triple-c-*; do
[ -S "$s" ] || continue
pids="$pids $(tmux -L "${s##*/}" list-panes -a -F '#{pane_pid}' 2>/dev/null)"
tmux -L "${s##*/}" kill-server 2>/dev/null
done
i=0
while [ $i -lt 50 ]; do
alive=""
for p in $pids; do kill -0 "$p" 2>/dev/null && alive=1; done
pgrep -u "$(id -u)" -f '^tmux -L triple-c-' >/dev/null 2>&1 && alive=1
[ -n "$alive" ] || break
sleep 0.1; i=$((i + 1))
done
exit 0
TRIPLEC_END_TERMINALS
)
# <<< end_terminals
_triplec_as_user sh -c "$script"
}
aws_before_stop() {
[ "${TRIPLEC_HOST:-}" = aws ] || return 0
[ -z "${triplec_stopping:-}" ] || return 0
@@ -905,6 +937,7 @@ aws_before_stop() {
return 0 ;;
esac
if [ "${TRIPLEC_WIP_PUSH:-0}" = 1 ]; then
aws_end_terminals
echo "entrypoint: stopping ($reason) — pushing work in progress..."
_triplec_as_user timeout -k 5 90 /usr/local/bin/triple-c-wip-push --reason "$reason" \
|| echo "entrypoint: warning — WIP push incomplete (see above)"
+33
View File
@@ -232,6 +232,38 @@ lifetime_reached() {
[ -n "$lifetime" ] && [ $(( $(date +%s) - started_at )) -ge $((lifetime * 60)) ]
}
# Persistent terminals (the app's tmux servers, app/src-tauri/src/host/persistent.rs)
# would keep writing after the push's snapshot: end them, as their user,
# before a lifetime-cap push (the stop is certain then; an idle stop has no
# live terminal output to lose). Same script as entrypoint.sh's.
end_terminals() {
command -v tmux >/dev/null 2>&1 || return 0
local script
# >>> end_terminals (app/src-tauri/src/host/persistent.rs END_ALL_SCRIPT, verbatim)
script=$(cat <<'TRIPLEC_END_TERMINALS'
d="${TMUX_TMPDIR:-/tmp}/tmux-$(id -u)"
command -v tmux >/dev/null 2>&1 || exit 0
pids=""
for s in "$d"/triple-c-*; do
[ -S "$s" ] || continue
pids="$pids $(tmux -L "${s##*/}" list-panes -a -F '#{pane_pid}' 2>/dev/null)"
tmux -L "${s##*/}" kill-server 2>/dev/null
done
i=0
while [ $i -lt 50 ]; do
alive=""
for p in $pids; do kill -0 "$p" 2>/dev/null && alive=1; done
pgrep -u "$(id -u)" -f '^tmux -L triple-c-' >/dev/null 2>&1 && alive=1
[ -n "$alive" ] || break
sleep 0.1; i=$((i + 1))
done
exit 0
TRIPLEC_END_TERMINALS
)
# <<< end_terminals
as_user sh -c "$script"
}
# The cap is reached: push (best effort) unless the app has decided already,
# record "lifetime", signal the entrypoint and end.
lifetime_stop() {
@@ -241,6 +273,7 @@ lifetime_stop() {
pushed|discard)
echo "triple-c-idle-watch: Triple-C is already stopping it — keeping its decision" ;;
*)
end_terminals
if [ "$wip_push" = 1 ]; then
echo "triple-c-idle-watch: pushing work in progress before the stop..."
as_user timeout -k 5 "$wip_timeout" "$wip_bin" --reason lifetime \
+71
View File
@@ -0,0 +1,71 @@
# /etc/triple-c/tmux.conf — the tmux every persistent AWS terminal runs in.
#
# The app (host/persistent.rs) starts one tmux *server* per terminal tab,
# `tmux -L triple-c-<session id> -f /etc/triple-c/tmux.conf new-session -A …`,
# so the tab's Claude Code or shell outlives the app closing or the SSM tunnel
# dropping, and the app re-attaches to it on its next connect. tmux is only the
# keeper of the process here, never a UI: the person in front of xterm.js must
# not be able to tell it is there. Hence every setting below.
#
# Lives outside /home/claude (seed-only, see CLAUDE.md) so an image update
# reaches it. The app probes for this file (and tmux) before using it; an image
# without them runs terminals the old way.
# No prefix key at all: Ctrl+B is readline's backward-char and Claude Code's
# own binding, and nothing here is driven from the keyboard.
set -g prefix None
set -g prefix2 None
unbind-key C-b
# No status line: the app's tab strip is the status line.
set -g status off
# An ESC must reach Claude Code at once (vi mode, Esc to interrupt), and ESC+CR
# (the app's Shift+Enter, CLAUDE_SOFT_NEWLINE) must arrive as one Meta-Enter.
set -s escape-time 0
# Pane history the app replays into a re-opened tab (capture-pane).
set -g history-limit 50000
# Inside: a terminfo every Ubuntu has (ncurses-base). Outside: xterm.js, which
# speaks 24-bit colour, OSC 8 hyperlinks and OSC 52.
set -g default-terminal "tmux-256color"
set -as terminal-features ",xterm*:RGB:hyperlinks:clipboard"
set -s set-clipboard on
# Draw in xterm.js's normal screen, not its alternate screen, so scrolled-off
# output lands in the app's own scrollback and its copy cleanup and link
# detection keep working (smcup@/rmcup@). Two more, both measured by feeding
# tmux's real output into xterm.js:
# * indn@: with it tmux scrolls with CSI S (SU), and xterm.js's SU deletes the
# top line instead of saving it to scrollback (4 of 300 fast lines kept);
# without it tmux scrolls with newlines, which xterm.js keeps (all 300).
# * clear=\E[H: tmux sends `clear` when its client exits, which without an
# alternate screen wiped the session's last screen (Claude's goodbye, the
# shell's last output) from the tab. Its full redraws repaint every row
# anyway (checked: bash `clear`, ED 2, a curses alternate screen, a
# re-attach over an old screen and Claude Code's TUI all match tmux's own
# view of the pane).
set -as terminal-overrides ",xterm*:smcup@:rmcup@:indn@:clear=\\E[H"
# The mouse belongs to xterm.js (selection, links, wheel scrollback).
set -g mouse off
set -g focus-events on
# The process is the session: when it exits, the server goes with it (the tab
# shows "[Session ended]"); nothing is kept after a client detaches.
set -g remain-on-exit off
set -g destroy-unattached off
set -g exit-empty on
set -g exit-unattached off
# Follow the size of whichever client attached last (there is normally one).
set -g window-size latest
setw -g aggressive-resize on
# No window/title games behind the app's back.
set -g set-titles off
setw -g automatic-rename off
setw -g allow-rename off
set -g visual-bell off
set -g bell-action none
+154
View File
@@ -0,0 +1,154 @@
# build-ssm-plugin.ps1 - build AWS's session-manager-plugin FROM SOURCE for
# Windows and put it where Tauri's bundle.externalBin expects it:
#
# app\src-tauri\binaries\session-manager-plugin-x86_64-pc-windows-msvc.exe
#
# The Windows runner's half of scripts/build-ssm-plugin.sh - read that header
# for the why. The same pins and the same build, so it must produce the same
# bytes (Go builds are reproducible across hosts); keep the two in step.
#
# 1. Source: AWS's tag 1.2.896.0 by COMMIT, as GitHub's archive of that
# commit, SHA-256 checked before extraction (and its top directory must
# name the commit).
# 2. Toolchain: Go, pinned, SHA-256 as published by go.dev, checked before use.
# 3. AWS's own build (GOPATH mode over the vendored deps, -ldflags "-s -w"),
# version stamped to the tag, made reproducible (-trimpath, no VCS stamp,
# empty build id, CGO off, GOAMD64=v1, nothing inherited).
# 4. The output must equal the pinned SHA-256.
#
# The result is UNSIGNED: in a release build Tauri presents it to the sign
# command (windows-sign.ps1 signs it with our certificate), and
# windows-verify-signatures.ps1 requires our signature on it in both installers.
#
# Needs tar.exe (bsdtar, in every Windows 10+). Idempotent.
$ErrorActionPreference = 'Stop'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Add-Type -AssemblyName System.IO.Compression.FileSystem
$PluginVersion = '1.2.896.0'
$PluginCommit = '6430675a44032a551be1937fb27a2d3fdfeb27f7'
$SourceUrl = "https://codeload.github.com/aws/session-manager-plugin/tar.gz/$PluginCommit"
$SourceSha = '7C95BE411AD5F43D14D01460500BFD5A5AA0E28BA94815F8B049AF33A2C381B0'
$GoVersion = '1.26.11'
$GoSha = '71AE086F0137E665F855A811CC119152B6A783E0BBC1B906E709F46D80141EB0' # go1.26.11.windows-amd64.zip, go.dev
$BinarySha = '6D428E5FD77E76D9713F0C42B8EC39F2DE1031E5F3C567FEB73C7FE11B14B226'
$Triple = 'x86_64-pc-windows-msvc'
$repoRoot = Split-Path -Parent $PSScriptRoot
$destDir = Join-Path $repoRoot 'app\src-tauri\binaries'
$dest = Join-Path $destDir "session-manager-plugin-$Triple.exe"
$notices = Join-Path $repoRoot 'app\src-tauri\THIRD_PARTY_NOTICES'
function Get-Sha256([string]$Path) { (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToUpperInvariant() }
if (-not ((Select-String -LiteralPath $notices -SimpleMatch "Version: $PluginVersion" -Quiet) -and
(Select-String -LiteralPath $notices -SimpleMatch "Commit: $PluginCommit" -Quiet))) {
throw "$notices does not name plugin $PluginVersion at $PluginCommit - update it with the bump"
}
if ((Test-Path -LiteralPath $dest) -and ((Get-Sha256 $dest) -eq $BinarySha)) {
Write-Host "session-manager-plugin-$Triple.exe: already the pinned $PluginVersion build"
exit 0
}
# A short work root, not %TEMP% (on the runner that is deep under
# systemprofile): the longest extracted path is ~200 characters, and MAX_PATH
# is 260 for Windows PowerShell 5.1, tar.exe and the Go build alike.
$work = Join-Path "$env:SystemDrive\" ('ssm-' + [guid]::NewGuid().ToString('N').Substring(0, 8))
New-Item -ItemType Directory -Path $work | Out-Null
# A directory at the drive root inherits C:\'s ACL, where Authenticated Users
# may create and modify files - another local user could swap the source, the
# toolchain or the output between our checks and their use. So before anything
# lands in it: no inheritance, full control for SYSTEM, Administrators and this
# process's own user only. Mandatory on Windows; skipped only where there is no
# Windows ACL (the Linux pwsh test path).
if ($env:OS -eq 'Windows_NT') {
$me = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
& icacls.exe $work /inheritance:r /grant:r '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F' "*${me}:(OI)(CI)F" | Out-Null
if ($LASTEXITCODE -ne 0) {
Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue
throw "icacls could not restrict $work ($LASTEXITCODE)"
}
}
$ProgressPreference = 'SilentlyContinue'
try {
$goZip = Join-Path $work 'go.zip'
Write-Host "Downloading Go $GoVersion (windows-amd64)"
Invoke-WebRequest -Uri "https://go.dev/dl/go$GoVersion.windows-amd64.zip" -OutFile $goZip -UseBasicParsing
$actual = Get-Sha256 $goZip
if ($actual -ne $GoSha) { throw "SHA-256 mismatch for the Go toolchain: got $actual, pinned $GoSha" }
[IO.Compression.ZipFile]::ExtractToDirectory($goZip, (Join-Path $work 'toolchain'))
$go = Join-Path $work 'toolchain\go\bin\go.exe'
$srcTgz = Join-Path $work 'source.tar.gz'
Write-Host "Downloading session-manager-plugin $PluginVersion source ($PluginCommit)"
Invoke-WebRequest -Uri $SourceUrl -OutFile $srcTgz -UseBasicParsing
$actual = Get-Sha256 $srcTgz
if ($actual -ne $SourceSha) { throw "SHA-256 mismatch for the plugin source: got $actual, pinned $SourceSha" }
$srcDir = Join-Path $work 'src'
New-Item -ItemType Directory -Path $srcDir | Out-Null
# Only what the build reads, as build-ssm-plugin.sh does: the vendored SDK's
# Java codegen/ tree reaches 258 characters inside the archive, past
# MAX_PATH, and its snapshot/ files are test data.
& tar.exe --exclude='*/codegen/*' --exclude='*/snapshot/*' -xzf $srcTgz -C $srcDir
if ($LASTEXITCODE -ne 0) { throw "tar.exe could not extract the source ($LASTEXITCODE)" }
$goSpace = Join-Path $srcDir "session-manager-plugin-$PluginCommit"
if (-not (Test-Path -LiteralPath (Join-Path $goSpace 'src\sessionmanagerplugin-main'))) {
throw "the source archive is not the pinned commit's tree"
}
# A clean, fully specified Go environment for everything below.
foreach ($v in 'GOFLAGS', 'GOROOT', 'GOBIN', 'GOEXPERIMENT', 'GOTMPDIR') { Remove-Item "env:$v" -ErrorAction SilentlyContinue }
$gopath = Join-Path $work 'gopath'
$env:GOENV = 'off'; $env:GOTOOLCHAIN = 'local'; $env:GO111MODULE = 'off'; $env:GOPROXY = 'off'; $env:GOWORK = 'off'
$env:GOPATH = "$gopath;$(Join-Path $goSpace 'vendor')"
$env:GOCACHE = Join-Path $work 'cache'; $env:GOMODCACHE = Join-Path $work 'modcache'
$env:CGO_ENABLED = '0'; $env:GOAMD64 = 'v1'; $env:GOARM64 = 'v8.0'
# makefile pre-build: stamp the version with AWS's own generator.
[IO.File]::WriteAllText((Join-Path $goSpace 'VERSION'), $PluginVersion)
# version-gen runs on this host, so no GOOS/GOARCH yet.
Remove-Item env:GOOS, env:GOARCH -ErrorAction SilentlyContinue
Push-Location $goSpace
try { & $go run ./src/version/versiongenerator/version-gen.go | Out-Null } finally { Pop-Location }
if ($LASTEXITCODE -ne 0) { throw "version-gen failed ($LASTEXITCODE)" }
if (-not (Select-String -LiteralPath (Join-Path $goSpace 'src\version\version.go') -SimpleMatch "const Version = `"$PluginVersion`"" -Quiet)) {
throw 'the version stamp did not take'
}
# makefile copy-src: GOPATH mode, from a copy at the import path.
$pkgRoot = Join-Path $gopath 'src\github.com\aws\session-manager-plugin'
New-Item -ItemType Directory -Force -Path $pkgRoot | Out-Null
Copy-Item -Recurse -LiteralPath (Join-Path $goSpace 'src') -Destination $pkgRoot
$out = Join-Path $work 'session-manager-plugin.exe'
Write-Host "Building session-manager-plugin $PluginVersion for windows/amd64"
$env:GOOS = 'windows'; $env:GOARCH = 'amd64'
Push-Location $pkgRoot
try {
& $go build -trimpath -buildvcs=false -ldflags '-s -w -buildid=' -o $out `
github.com/aws/session-manager-plugin/src/sessionmanagerplugin-main
} finally { Pop-Location }
if ($LASTEXITCODE -ne 0) { throw "go build failed ($LASTEXITCODE)" }
$actual = Get-Sha256 $out
if ($actual -ne $BinarySha) {
throw "the windows/amd64 build is not the pinned binary: got $actual, pinned $BinarySha (source, toolchain or build flags changed)"
}
New-Item -ItemType Directory -Force -Path $destDir | Out-Null
Move-Item -LiteralPath $out -Destination $dest -Force
# And what landed is still what was checked.
$actual = Get-Sha256 $dest
if ($actual -ne $BinarySha) {
Remove-Item -LiteralPath $dest -Force -ErrorAction SilentlyContinue
throw "$dest changed after it was verified: got $actual, pinned $BinarySha"
}
Write-Host "session-manager-plugin-$Triple.exe: session-manager-plugin $PluginVersion (unsigned; signed by the release build)"
} finally {
Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue
# PS 5.1's Remove-Item can give up on read-only files and deep trees;
# rd /s /q is the fallback.
if (Test-Path -LiteralPath $work) { cmd /c rd /s /q "`"$work`"" | Out-Null }
if (Test-Path -LiteralPath $work) { Write-Warning "could not remove $work" }
}
+233
View File
@@ -0,0 +1,233 @@
#!/usr/bin/env bash
#
# build-ssm-plugin.sh [target-triple ...] - build AWS's session-manager-plugin
# FROM SOURCE and put it where Tauri's `bundle.externalBin` expects it:
#
# app/src-tauri/binaries/session-manager-plugin-<target-triple>[.exe]
#
# The app runs the plugin to connect to workspaces on AWS; bundling it means
# users do not have to install it. We build it ourselves from AWS's Apache-2.0
# source (github.com/aws/session-manager-plugin) rather than redistributing
# AWS's prebuilt binaries, which AWS ships as "AWS Content" under the AWS
# Customer Agreement.
#
# With no argument the host's triple is used (`rustc -vV`). Every target is a
# pure-Go cross-compile (CGO_ENABLED=0), so any host can build any of them; CI
# builds each platform's own targets in its own job. scripts/build-ssm-plugin.ps1
# is the same build for the Windows runner, which has no bash.
#
# Supported triples:
# x86_64-unknown-linux-gnu linux/amd64
# aarch64-unknown-linux-gnu linux/arm64
# x86_64-apple-darwin darwin/amd64
# aarch64-apple-darwin darwin/arm64
# universal-apple-darwin both darwin slices plus the two thin files,
# joined with lipo (`tauri build --target
# universal-apple-darwin` compiles each arch and
# tauri-build wants each arch's sidecar; the
# bundler then wants the universal one)
# x86_64-pc-windows-msvc windows/amd64 (for local cross-builds; CI uses
# the .ps1)
#
# Trust and reproducibility - the build fails on any miss:
# 1. The source is AWS's tag 1.2.896.0, pinned by COMMIT, downloaded as
# GitHub's archive of that commit and checked against a pinned SHA-256
# BEFORE extraction (the SHA-256 is the check; the archive's top
# directory, which names the commit, must also be there). Only what the
# build reads is extracted: the vendored SDK's Java `codegen/` tree and its
# test `snapshot/` files are skipped, which also keeps every path under
# Windows' MAX_PATH (the .ps1 extracts the same way, so both build the
# same tree).
# 2. The Go toolchain is a pinned release from go.dev, checked against the
# SHA-256 go.dev publishes (https://go.dev/dl/?mode=json), before use.
# 3. The build is AWS's own (its makefile: GOPATH mode over the vendored
# dependencies, `-ldflags "-s -w"`, package sessionmanagerplugin-main),
# with VERSION set to the tag so `--version` prints 1.2.896.0 (AWS's
# release pipeline stamps it; the repo's VERSION file says 1.3.0.0), plus
# what makes it reproducible: -trimpath, no VCS stamping, an empty build
# id, CGO off, explicit GOAMD64/GOARM64, no inherited GOFLAGS.
# 4. The output must equal a PINNED SHA-256 per target. Go builds are
# bit-for-bit reproducible across hosts, so every CI runner must produce
# exactly the binary recorded here; a mismatch means the source, the
# toolchain or the build changed.
#
# To bump the plugin or Go: change the pins in this script and in
# build-ssm-plugin.ps1, rebuild every target, record the new output hashes
# (both scripts), and update the version/commit lines in
# app/src-tauri/THIRD_PARTY_NOTICES (checked below) and its dependency licences.
#
# Idempotent: a destination that already holds the pinned binary is left alone.
set -euo pipefail
PLUGIN_VERSION="1.2.896.0"
PLUGIN_COMMIT="6430675a44032a551be1937fb27a2d3fdfeb27f7"
SOURCE_URL="https://codeload.github.com/aws/session-manager-plugin/tar.gz/${PLUGIN_COMMIT}"
SOURCE_SHA256="7c95be411ad5f43d14d01460500bfd5a5aa0e28ba94815f8b049af33a2c381b0"
GO_VERSION="1.26.11"
go_pin() { # <goos-goarch of the build host> -> SHA-256 published by go.dev
case "$1" in
linux-amd64) echo 9849f4e04ee35303714e34fbc3ac8ab44ea3e448a95aa182f91e3b9b79c710ec ;;
linux-arm64) echo 6c2f29b458b5add0835f18b776f69c8881a6d88428f1484a6da55755e620757e ;;
darwin-amd64) echo 394baae971332f2bc783d6e2004ae57101479bd3b06ed8209a3fe3570d4ce498 ;;
darwin-arm64) echo e3a42e67a7a8acf450ebada2b074c7ca863000ca514907b7185b45e8f5cdff57 ;;
*) return 1 ;;
esac
}
# target triple -> GOOS GOARCH SHA-256 of the binary we build
target_pin() {
case "$1" in
x86_64-unknown-linux-gnu) echo "linux amd64 414dafe49a90428cb4271a28ea964ad9242a26cb08a38d9679d808470c3b6b62" ;;
aarch64-unknown-linux-gnu) echo "linux arm64 79f00cd41536611e2906a9ea703175ab4f06f9b81107a0357b2304c8bfac61dd" ;;
x86_64-apple-darwin) echo "darwin amd64 fc61cd7e30bef3524a3681dc6b1a0f472506d9c98bccf62a67865067c9f2f059" ;;
aarch64-apple-darwin) echo "darwin arm64 9f3857f85cbcdc88e3ca686f84ac2a794e19e1778ad47ac3294c39e700de08f8" ;;
x86_64-pc-windows-msvc) echo "windows amd64 6d428e5fd77e76d9713f0c42b8ec39f2de1031e5f3c567feb73c7fe11b14b226" ;;
*) return 1 ;;
esac
}
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
dest_dir="$repo_root/app/src-tauri/binaries"
notices="$repo_root/app/src-tauri/THIRD_PARTY_NOTICES"
die() { echo "build-ssm-plugin: $*" >&2; exit 1; }
sha256() {
if command -v sha256sum >/dev/null 2>&1; then
sha256sum "$1" | cut -d' ' -f1
else
shasum -a 256 "$1" | cut -d' ' -f1
fi
}
# The notices name the version and commit they describe; a bump updates both.
grep -qF "Version: ${PLUGIN_VERSION}" "$notices" && grep -qF "Commit: ${PLUGIN_COMMIT}" "$notices" \
|| die "$notices does not name plugin ${PLUGIN_VERSION} at ${PLUGIN_COMMIT} - update it with the bump"
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
prepared=false
download() { # <url> <out>
curl -fsSL --proto '=https' --tlsv1.2 --retry 3 --retry-delay 5 -o "$2" "$1" \
|| die "download failed: $1"
}
# Toolchain and source, once per run, both verified before they are unpacked.
prepare() {
[ "$prepared" = true ] && return 0
local host_os host_arch go_sha go_tgz
case "$(uname -s)" in Linux) host_os=linux ;; Darwin) host_os=darwin ;; *) die "unsupported build host $(uname -s)" ;; esac
case "$(uname -m)" in x86_64|amd64) host_arch=amd64 ;; arm64|aarch64) host_arch=arm64 ;; *) die "unsupported build host arch $(uname -m)" ;; esac
go_sha="$(go_pin "$host_os-$host_arch")" || die "no pinned Go for $host_os-$host_arch"
go_tgz="$work/go.tar.gz"
echo "Downloading Go ${GO_VERSION} (${host_os}-${host_arch})"
download "https://go.dev/dl/go${GO_VERSION}.${host_os}-${host_arch}.tar.gz" "$go_tgz"
[ "$(sha256 "$go_tgz")" = "$go_sha" ] \
|| die "SHA-256 mismatch for the Go toolchain: got $(sha256 "$go_tgz"), pinned $go_sha"
mkdir -p "$work/toolchain"
tar -xzf "$go_tgz" -C "$work/toolchain"
GO="$work/toolchain/go/bin/go"
local src_tgz="$work/source.tar.gz"
echo "Downloading session-manager-plugin ${PLUGIN_VERSION} source (${PLUGIN_COMMIT})"
download "$SOURCE_URL" "$src_tgz"
[ "$(sha256 "$src_tgz")" = "$SOURCE_SHA256" ] \
|| die "SHA-256 mismatch for the plugin source: got $(sha256 "$src_tgz"), pinned $SOURCE_SHA256"
mkdir -p "$work/src"
tar --exclude='*/codegen/*' --exclude='*/snapshot/*' -xzf "$src_tgz" -C "$work/src"
GO_SPACE="$work/src/session-manager-plugin-${PLUGIN_COMMIT}"
[ -d "$GO_SPACE/src/sessionmanagerplugin-main" ] || die "the source archive is not the pinned commit's tree"
# makefile `pre-build`: stamp the version with AWS's own generator.
printf '%s' "$PLUGIN_VERSION" >"$GO_SPACE/VERSION"
( cd "$GO_SPACE" && go_env "$(go_host_os)" "$(go_host_arch)" "$GO" run ./src/version/versiongenerator/version-gen.go >/dev/null )
grep -qF "const Version = \"${PLUGIN_VERSION}\"" "$GO_SPACE/src/version/version.go" \
|| die "the version stamp did not take"
# makefile `copy-src`: the code builds in GOPATH mode, from a copy at its
# import path, with the vendored dependencies as a second GOPATH entry.
GOPATH_DIR="$work/gopath"
mkdir -p "$GOPATH_DIR/src/github.com/aws/session-manager-plugin"
cp -R "$GO_SPACE/src" "$GOPATH_DIR/src/github.com/aws/session-manager-plugin/"
prepared=true
}
go_host_os() { "$GO" env GOHOSTOS; }
go_host_arch() { "$GO" env GOHOSTARCH; }
# Run with a clean, fully specified Go environment (nothing inherited).
go_env() { # <goos> <goarch> <cmd...>
local goos="$1" goarch="$2"; shift 2
env -u GOFLAGS -u GOROOT -u GOBIN -u GOEXPERIMENT \
GOENV=off GOTOOLCHAIN=local GO111MODULE=off GOPROXY=off GOWORK=off \
GOPATH="${GOPATH_DIR:-$work/gopath}:${GO_SPACE}/vendor" \
GOCACHE="$work/cache" GOMODCACHE="$work/modcache" GOTMPDIR= \
CGO_ENABLED=0 GOOS="$goos" GOARCH="$goarch" GOAMD64=v1 GOARM64=v8.0 \
"$@"
}
build_thin() { # <triple> <out>
local triple="$1" out="$2" pin goos goarch want
pin="$(target_pin "$triple")" || die "unsupported target $triple"
read -r goos goarch want <<<"$pin"
if [ -f "$out" ] && [ "$(sha256 "$out")" = "$want" ]; then
echo "$(basename "$out"): already the pinned ${PLUGIN_VERSION} build"
return 0
fi
prepare
echo "Building session-manager-plugin ${PLUGIN_VERSION} for ${goos}/${goarch}"
( cd "$GOPATH_DIR/src/github.com/aws/session-manager-plugin" && \
go_env "$goos" "$goarch" "$GO" build -trimpath -buildvcs=false \
-ldflags "-s -w -buildid=" -o "$work/out-$triple" \
github.com/aws/session-manager-plugin/src/sessionmanagerplugin-main )
local got
got="$(sha256 "$work/out-$triple")"
[ "$got" = "$want" ] || die "the ${goos}/${goarch} build is not the pinned binary: got $got, pinned $want (source, toolchain or build flags changed)"
mkdir -p "$(dirname "$out")"
chmod 0755 "$work/out-$triple"
mv -f "$work/out-$triple" "$out"
echo "$(basename "$out"): session-manager-plugin ${PLUGIN_VERSION}"
}
build_universal() {
local lipo
lipo="$(command -v lipo || command -v llvm-lipo || true)"
[ -n "$lipo" ] || die "universal-apple-darwin needs lipo (Xcode command line tools) or llvm-lipo"
local x86="$dest_dir/session-manager-plugin-x86_64-apple-darwin"
local arm="$dest_dir/session-manager-plugin-aarch64-apple-darwin"
local uni="$dest_dir/session-manager-plugin-universal-apple-darwin"
build_thin x86_64-apple-darwin "$x86"
build_thin aarch64-apple-darwin "$arm"
"$lipo" -create "$x86" "$arm" -output "$work/universal"
# Each slice must come back out byte-identical to its pinned thin binary.
local pair arch triple
for pair in x86_64:x86_64-apple-darwin arm64:aarch64-apple-darwin; do
arch="${pair%%:*}" triple="${pair#*:}"
"$lipo" "$work/universal" -thin "$arch" -output "$work/slice-$arch"
[ "$(sha256 "$work/slice-$arch")" = "$(target_pin "$triple" | cut -d' ' -f3)" ] \
|| die "the $arch slice of the universal binary is not the pinned binary"
done
chmod 0755 "$work/universal"
mv -f "$work/universal" "$uni"
echo "$(basename "$uni"): session-manager-plugin ${PLUGIN_VERSION} (x86_64 + arm64)"
}
targets=("$@")
if [ ${#targets[@]} -eq 0 ]; then
host="$(rustc -vV 2>/dev/null | sed -n 's/^host: //p')"
[ -n "$host" ] || die "no target given and rustc is not available to name the host's"
targets=("$host")
fi
for t in "${targets[@]}"; do
case "$t" in
universal-apple-darwin) build_universal ;;
*-windows-*) build_thin "$t" "$dest_dir/session-manager-plugin-$t.exe" ;;
*) build_thin "$t" "$dest_dir/session-manager-plugin-$t" ;;
esac
done
+16
View File
@@ -317,6 +317,22 @@ if [ "$pw_removed" = true ]; then
fi
[ -x "$out/usr/bin/triple-c" ] || fail "no executable usr/bin/triple-c."
# The bundled AWS Session Manager plugin (bundle.externalBin, built from
# source by build-ssm-plugin.sh) is what AWS workspaces connect through. Tauri copies it
# beside the app binary with the target triple stripped, which is where
# `host::ssm::find_plugin` looks. It must be the real plugin: an ELF, not the
# placeholder a debug build writes (build.rs refuses that for release, and this
# is the check on what actually shipped).
plugin="$out/usr/bin/session-manager-plugin"
[ -x "$plugin" ] || fail "no executable usr/bin/session-manager-plugin (the bundled AWS plugin)."
[ "$(head -c 4 "$plugin" | od -An -c | tr -d ' ')" = "177ELF" ] \
|| fail "usr/bin/session-manager-plugin is not an ELF binary (a placeholder?)."
"$plugin" --version >/dev/null 2>&1 \
|| fail "usr/bin/session-manager-plugin does not run (--version)."
# Its license and notices travel with it (bundle.resources).
notices=("$out"/usr/lib/*/THIRD_PARTY_NOTICES)
[ -f "${notices[0]}" ] || fail "THIRD_PARTY_NOTICES is not in the image."
# Every file readable by all, every program executable by all — what the
# `chmod -R a+rX` before the repack promised (AppRun.wrapped used to ship 0770).
# Files only: the AppImage runtime's --appimage-extract creates every
+10 -4
View File
@@ -10,9 +10,10 @@
# extension DLLs candle/light load, the NSIS plugins makensis embeds - and
# each signature is metered (about 1000 a month), so those are skipped. The
# allowlist below is the whole of what reaches users: the app binary, the MSI,
# the NSIS installer, and the uninstaller makensis writes to the job's temp
# directory. A file that already carries a valid signature is skipped too:
# Tauri presents the app binary once per bundle type.
# the NSIS installer, the uninstaller makensis writes to the job's temp
# directory, and the session-manager-plugin sidecar we build from source. A
# file that already carries a valid signature is skipped too: Tauri presents
# the app binary once per bundle type.
#
# This may run as 32-bit PowerShell: the NSIS uninstaller is signed from inside
# makensis, which is 32-bit and resolves `powershell` to the SysWOW64 copy. So
@@ -46,7 +47,12 @@ try {
$full = (Resolve-Path -LiteralPath $Path).ProviderPath
Write-Log "== $full"
$ships = ($full -match '\\target\\release\\[^\\]+\.exe$') -or
# The bundled session-manager-plugin sidecar (bundle.externalBin), which we
# build from AWS's source (scripts/build-ssm-plugin.ps1) and so ship unsigned
# unless signed here. Tauri presents a sidecar to the sign command, in place
# under app\src-tauri\binaries, only when `signtool verify /pa` rejects it.
$ships = ($full -match '\\src-tauri\\binaries\\session-manager-plugin-x86_64-pc-windows-msvc\.exe$') -or
($full -match '\\target\\release\\[^\\]+\.exe$') -or
($full -match '\\target\\release\\bundle\\(msi|nsis)\\[^\\]+\.(msi|exe)$') -or
$full.StartsWith($env:TRIPLE_C_SIGN_TMP.TrimEnd('\') + '\', [StringComparison]::OrdinalIgnoreCase)
if (-not $ships) {
+50 -1
View File
@@ -14,6 +14,10 @@
# unpacked with an administrative install and its binaries checked directly;
# the NSIS installer cannot be unpacked that way, so for it the signing log
# must show the app binary and the uninstaller were signed.
#
# The bundled session-manager-plugin (built from source, signed by us) is
# checked too: present in the MSI, and in both installers validly signed,
# timestamped, and by the same signing identity as the installer itself.
param([Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)][string[]]$Patterns)
@@ -47,6 +51,24 @@ function Test-Signature([IO.FileInfo]$File, [string]$Label) {
return $false
}
# The session-manager-plugin sidecar is built from AWS's source
# (build-ssm-plugin.ps1), so it is unsigned until windows-sign.ps1 signs it. It
# must carry OUR signature: valid, timestamped, and from the same signing
# identity (subject and issuer) as the installer that ships it.
$sidecarName = 'session-manager-plugin.exe'
$sidecarSource = Join-Path (Split-Path -Parent $PSScriptRoot) 'app\src-tauri\binaries\session-manager-plugin-x86_64-pc-windows-msvc.exe'
function Test-OurSigner([IO.FileInfo]$File, [string]$Label, [IO.FileInfo]$Installer) {
if (-not (Test-Signature $File $Label)) { return $false }
$ours = (Get-AuthenticodeSignature -FilePath $Installer.FullName).SignerCertificate
$theirs = (Get-AuthenticodeSignature -FilePath $File.FullName).SignerCertificate
# Subject + Issuer, not the thumbprint: Azure Artifact Signing issues a
# fresh short-lived certificate (daily), so the plugin and the installer
# can legitimately carry different thumbprints within one build.
if ($ours -and $theirs -and $ours.Subject -eq $theirs.Subject -and $ours.Issuer -eq $theirs.Issuer) { return $true }
Write-Host "FAIL $Label - signed by '$($theirs.Subject)' (issuer '$($theirs.Issuer)'), not the identity that signed $($Installer.Name)"
return $false
}
function Get-SignedLog {
if ($env:TRIPLE_C_SIGN_LOG -and (Test-Path $env:TRIPLE_C_SIGN_LOG)) { return @(Get-Content $env:TRIPLE_C_SIGN_LOG) }
return @()
@@ -56,7 +78,7 @@ $failed = @()
$nsisBuilt = $false
foreach ($file in $files) {
if (-not (Test-Signature $file $file.Name)) { $failed += $file.Name }
if ($file.FullName -match '\\bundle\\nsis\\') { $nsisBuilt = $true }
if ($file.FullName -match '\\bundle\\nsis\\') { $nsisBuilt = $true; $nsisInstaller = $file }
if ($file.Extension -eq '.msi') {
$extract = Join-Path ([IO.Path]::GetTempPath()) ('msi-verify-' + [guid]::NewGuid().ToString('N'))
@@ -74,6 +96,21 @@ foreach ($file in $files) {
foreach ($f in $inner) {
if (-not (Test-Signature $f "$($file.Name) > $($f.Name)")) { $failed += "$($file.Name) > $($f.Name)" }
}
# Its licence notices travel with it (bundle.resources).
if ($proc.ExitCode -eq 0 -and -not @(Get-ChildItem -Path $extract -Recurse -File -Filter 'THIRD_PARTY_NOTICES').Count) {
Write-Host "FAIL $($file.Name) - carries no THIRD_PARTY_NOTICES"
$failed += "$($file.Name) > THIRD_PARTY_NOTICES (missing)"
}
# The bundled plugin must be in there, under our signature.
if ($proc.ExitCode -eq 0) {
$plugin = @($inner | Where-Object { $_.Name -eq $sidecarName })
if ($plugin.Count -ne 1) {
Write-Host "FAIL $($file.Name) - carries $($plugin.Count) $sidecarName, expected 1"
$failed += "$($file.Name) > $sidecarName (missing)"
} elseif (-not (Test-OurSigner $plugin[0] "$($file.Name) > $sidecarName" $file)) {
$failed += "$($file.Name) > $sidecarName (signer)"
}
}
Remove-Item -Recurse -Force $extract -ErrorAction SilentlyContinue
}
}
@@ -92,6 +129,18 @@ if ($nsisBuilt) {
} else {
Write-Host "OK app binary - signed before packaging ($($appSigned.Count)x)"
}
# makensis packs the sidecar straight from app\src-tauri\binaries, where
# Tauri had it signed in place before any bundle: so that file, and a
# logged signature for it, are what NSIS shipped.
if (-not (Test-Path -LiteralPath $sidecarSource)) {
Write-Host "FAIL $sidecarName - $sidecarSource is missing"
$failed += "NSIS > $sidecarName (missing)"
} elseif (-not (Test-OurSigner (Get-Item -LiteralPath $sidecarSource) "NSIS > $sidecarName (as packed)" $nsisInstaller)) {
$failed += "NSIS > $sidecarName (signer)"
} elseif (-not @($log | Where-Object { $_ -match '\\src-tauri\\binaries\\session-manager-plugin-x86_64-pc-windows-msvc\.exe$' }).Count) {
Write-Host "FAIL $sidecarName - no signature was logged for it"
$failed += "NSIS > $sidecarName (not logged)"
}
$tmp = $env:TRIPLE_C_SIGN_TMP
$uninstaller = @()
if ($tmp) { $uninstaller = @($log | Where-Object { $_.StartsWith($tmp, [StringComparison]::OrdinalIgnoreCase) }) }