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>
This commit is contained in:
1 parent
7951da008e
commit
21bd7f5347
20 files changed
+1580
-23
No files matched your search
@@ -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 @@
|
||||
{"__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 @@
|
||||
{"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()
|
||||
@@ -1752,6 +1753,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 +1814,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 +3237,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());
|
||||
}
|
||||
|
||||
|
||||
@@ -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,194 @@ 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) {
|
||||
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);
|
||||
match target {
|
||||
Some(t) => {
|
||||
if let Err(e) = persistent::end(&t, &session_id).await {
|
||||
log::warn!("Could not end terminal {session_id} in the workspace: {e}");
|
||||
}
|
||||
}
|
||||
None => log::warn!(
|
||||
"Terminal {session_id}: not connected, so it keeps running in the workspace \
|
||||
(Project Home → Sessions lists it)"
|
||||
),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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?;
|
||||
let running = persistent::list(&target).await?;
|
||||
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))?;
|
||||
let target = aws_target(&project).await?;
|
||||
if !persistent::supported(&target).await {
|
||||
terminal_store::remove(&session_id).ok();
|
||||
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 {
|
||||
if let Some(history) = persistent::history(&target, &session_id).await {
|
||||
let bytes = persistent::replay_bytes(&history, rows);
|
||||
if !bytes.is_empty() {
|
||||
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?;
|
||||
|
||||
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 +792,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;
|
||||
|
||||
@@ -1321,6 +1321,53 @@ 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 kill-server\ntmux -L triple-c-bbb kill-server\npush --reason sigterm\n"
|
||||
);
|
||||
drop(keep);
|
||||
// The app's own Stop ends them with the same loop.
|
||||
let app = crate::host::persistent::end_all_cmd().join(" ");
|
||||
assert!(app.contains(r#"tmux -L "${s##*/}" kill-server"#) && app.contains("\"$d\"/triple-c-*"), "{app}");
|
||||
assert!(block(ENTRYPOINT, "aws_stop").contains(r#"tmux -L "${s##*/}" kill-server"#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_idle_exit_status_is_the_one_the_app_reads() {
|
||||
assert!(
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,496 @@
|
||||
//! 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 — until no tmux server of ours is left, so a pane's last writes
|
||||
/// land before the snapshot.
|
||||
pub fn end_all_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" ] && tmux -L "${{s##*/}}" kill-server 2>/dev/null
|
||||
done
|
||||
i=0
|
||||
while pgrep -u "$(id -u)" -f '^tmux -L {SOCKET_PREFIX}' >/dev/null 2>&1 && [ $i -lt 50 ]; do
|
||||
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`].
|
||||
pub fn client_env(mut env: Vec<String>) -> Vec<String> {
|
||||
env.retain(|e| !e.starts_with("TERM="));
|
||||
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`], an unanswered probe counting as no.
|
||||
pub async fn supported(target: &ContainerTarget) -> bool {
|
||||
probe(target).await.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// 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()) };
|
||||
if !ok && notice.is_none() {
|
||||
log::info!("Terminal {key}: not persistent (no tmux in the image, or it could not be asked)");
|
||||
}
|
||||
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).
|
||||
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}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
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\"",
|
||||
"set -as terminal-overrides \",xterm*:smcup@:rmcup@:indn@\"",
|
||||
] {
|
||||
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");
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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::*;
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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::*;
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
//! 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>>,
|
||||
}
|
||||
|
||||
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());
|
||||
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).
|
||||
pub fn clear_in(dir: &Path, project_id: &str) -> Result<(), String> {
|
||||
edit_in(dir, |f| {
|
||||
f.projects.remove(project_id);
|
||||
})
|
||||
}
|
||||
|
||||
// ── 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)
|
||||
}
|
||||
|
||||
/// 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_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);
|
||||
}
|
||||
}
|
||||
@@ -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,26 @@ 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 };
|
||||
if persistent {
|
||||
if let Err(e) = crate::host::persistent::end(&target, session_id).await {
|
||||
log::warn!("Web terminal: could not end terminal {session_id}: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -311,6 +332,29 @@ async fn handle_open(
|
||||
let session_id = uuid::Uuid::new_v4().to_string();
|
||||
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,
|
||||
&session_id,
|
||||
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 +379,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,
|
||||
|
||||
Reference in new issue
Block a user