Compare commits

...
6 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-linux (pull_request) In progress
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
- 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
44 changed files with 2989 additions and 39 deletions

No files matched your search

+69 -1
View File
@@ -320,6 +320,59 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li
(`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
@@ -571,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
@@ -767,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
+3
View File
@@ -96,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
@@ -662,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",
@@ -878,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",
@@ -974,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",
@@ -1658,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",
@@ -1874,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",
@@ -1970,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",
@@ -662,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",
@@ -878,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",
@@ -974,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",
@@ -1658,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",
@@ -1874,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",
@@ -1970,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",
@@ -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,12 +1153,17 @@ 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 {
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 {
@@ -1752,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...");
@@ -1810,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...");
@@ -3231,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());
}
+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!(
+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
@@ -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()]);
}
+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(())
}
+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();
+3
View File
@@ -661,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,
}
+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();
}
}
+2
View File
@@ -25,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";
@@ -80,6 +81,7 @@ export default function App() {
useMarketplaceSyncToasts();
useProjectStatusEvents();
useWorkspaceWarnings();
usePersistentTerminals();
// Initialize on mount
useEffect(() => {
@@ -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">
@@ -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;
@@ -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);
+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.";
+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));
}
+13 -2
View File
@@ -1,5 +1,5 @@
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, DockerStatus, ClaudeSession, ContainerCapabilities, ScheduledTask, ScheduledTaskInput, SchedulerNotification, AuthBridgeStatus, BrowserViewStatus, BrowserViewPopoutState, BrowserPageState, PlaywrightDetection, BrowserSetupOutcome, BrowserInstallTarget, ContainerStaleness, MigrationOptions, MigrationReport, MigrationState, ClearTokenOutcome, CaCertInfo, UploadOutcome, Note, ViewerFile, ViewerPoll, ViewerSaved, ViewerState, FileDiff, InstallScope, ItemUpdate, Marketplace, MarketplaceAccount, MarketplaceItemRef, MarketplaceSnapshot, ProjectSyncResult, SyncReport, HostConnection, CallerIdentity, PermissionReport, PolicyFile, HourlyEstimate, AwsWorkspaceConfig, Tier, EnvironmentScan, NetworkChoice, ModuleKind, Ec2Choice, Ec2Compute, Ec2InstanceTable, Ec2Capacity, SavedBundle } from "./types";
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");
@@ -235,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) =>
+32
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 {
+14 -4
View File
@@ -129,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;
@@ -329,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);
+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