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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:09:09 -08:00

439 lines
15 KiB
Rust

use std::sync::Arc;
use axum::extract::ws::{Message, WebSocket};
use base64::engine::general_purpose::STANDARD as BASE64;
use base64::Engine;
use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;
use crate::commands::aws_commands;
use crate::models::{Backend, BedrockAuthMethod, Project, ProjectStatus};
use super::server::WebTerminalState;
// ── Wire protocol types ──────────────────────────────────────────────
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum ClientMessage {
ListProjects,
Open {
project_id: String,
session_type: Option<String>,
},
Input {
session_id: String,
data: String, // base64
},
Resize {
session_id: String,
cols: u16,
rows: u16,
},
Close {
session_id: String,
},
Ping,
}
#[derive(Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum ServerMessage {
Projects {
projects: Vec<ProjectEntry>,
},
Opened {
session_id: String,
project_name: String,
/// Echoed back so the client can label the session from the reply
/// rather than from a global set at request time.
///
/// Without it the client correlates through a single
/// `pendingSessionType`, so opening two sessions before the first
/// reply lands swaps their labels. That used to be cosmetic; it stopped
/// being cosmetic when Shift+Enter became type-dependent, because a
/// Claude session mislabelled as a shell now submits a half-written
/// prompt instead of inserting a newline.
session_type: String,
},
Output {
session_id: String,
data: String, // base64
},
Exit {
session_id: String,
},
Error {
message: String,
},
Pong,
}
#[derive(Serialize)]
struct ProjectEntry {
id: String,
name: String,
status: String,
}
// ── Connection handler ───────────────────────────────────────────────
pub async fn handle_connection(socket: WebSocket, state: Arc<WebTerminalState>) {
let (mut ws_tx, mut ws_rx) = socket.split();
// Channel for sending messages from session output tasks → WS writer
let (out_tx, mut out_rx) = mpsc::unbounded_channel::<ServerMessage>();
// 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
let writer_handle = tokio::spawn(async move {
while let Some(msg) = out_rx.recv().await {
if let Ok(json) = serde_json::to_string(&msg) {
if ws_tx.send(Message::Text(json.into())).await.is_err() {
break;
}
}
}
});
// Reader loop: parse incoming messages and dispatch
while let Some(Ok(msg)) = ws_rx.next().await {
let text = match &msg {
Message::Text(t) => t.to_string(),
Message::Close(_) => break,
_ => continue,
};
let client_msg: ClientMessage = match serde_json::from_str(&text) {
Ok(m) => m,
Err(e) => {
let _ = out_tx.send(ServerMessage::Error {
message: format!("Invalid message: {}", e),
});
continue;
}
};
match client_msg {
ClientMessage::Ping => {
let _ = out_tx.send(ServerMessage::Pong);
}
ClientMessage::ListProjects => {
let projects = state.projects_store.list();
let entries: Vec<ProjectEntry> = projects
.into_iter()
.map(|p| ProjectEntry {
id: p.id,
name: p.name,
status: serde_json::to_value(&p.status)
.ok()
.and_then(|v| v.as_str().map(|s| s.to_string()))
.unwrap_or_else(|| "unknown".to_string()),
})
.collect();
let _ = out_tx.send(ServerMessage::Projects { projects: entries });
}
ClientMessage::Open {
project_id,
session_type,
} => {
let result = handle_open(
&state,
&project_id,
session_type.as_deref(),
&out_tx,
&owned_sessions,
)
.await;
if let Err(e) = result {
let _ = out_tx.send(ServerMessage::Error { message: e });
}
}
ClientMessage::Input { session_id, data } => {
match BASE64.decode(&data) {
Ok(bytes) => {
if let Err(e) = state.exec_manager.send_input(&session_id, bytes).await {
let _ = out_tx.send(ServerMessage::Error {
message: format!("Input error: {}", e),
});
}
}
Err(e) => {
let _ = out_tx.send(ServerMessage::Error {
message: format!("Base64 decode error: {}", e),
});
}
}
}
ClientMessage::Resize {
session_id,
cols,
rows,
} => {
if let Err(e) = state.exec_manager.resize(&session_id, cols, rows).await {
let _ = out_tx.send(ServerMessage::Error {
message: format!("Resize error: {}", e),
});
}
}
ClientMessage::Close { 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. 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 {
state.exec_manager.close_session(&session_id).await;
}
writer_handle.abort();
}
/// The desktop terminal's update prelude, reused verbatim. Shared rather than
/// copied so the web terminal cannot drift from it — a duplicated `const` with
/// a "keep these identical" comment is only as good as the next reader.
use crate::commands::terminal_commands::UPDATE_PRELUDE;
/// Build the command for a terminal session, mirroring terminal_commands.rs logic.
fn build_terminal_cmd(project: &Project, settings_store: &crate::storage::settings_store::SettingsStore) -> Vec<String> {
let is_bedrock_profile = project.backend == Backend::Bedrock
&& project
.bedrock_config
.as_ref()
.map(|b| b.auth_method == BedrockAuthMethod::Profile)
.unwrap_or(false);
let permission_args = project.effective_permission_mode().cli_args();
// The args are interpolated into a shell script string below, so
// single-quote each one.
let permission_flags: String = permission_args
.iter()
.map(|a| format!(" '{}'", a.replace('\'', "'\\''")))
.collect();
let claude_cmd = format!("exec claude{}", permission_flags);
if !is_bedrock_profile {
return vec![
"bash".to_string(),
"-c".to_string(),
format!("{}\n{}\n", UPDATE_PRELUDE, claude_cmd),
];
}
let profile = aws_commands::resolve_profile_for_project(
project,
settings_store.get().global_aws.aws_profile.as_deref(),
);
let script = format!(
r#"
echo "Validating AWS session for profile '{profile}'..."
if aws sts get-caller-identity --profile '{profile}' >/dev/null 2>&1; then
echo "AWS session valid."
else
echo "AWS session expired or invalid."
if aws configure get sso_start_url --profile '{profile}' >/dev/null 2>&1 || \
aws configure get sso_session --profile '{profile}' >/dev/null 2>&1; then
echo "Starting SSO login..."
echo ""
triple-c-sso-refresh
if [ $? -ne 0 ]; then
echo ""
echo "SSO login failed or was cancelled. Starting Claude anyway..."
echo "You may see authentication errors."
echo ""
fi
else
echo "Profile '{profile}' does not use SSO. Check your AWS credentials."
echo "Starting Claude anyway..."
echo ""
fi
fi
{update_prelude}
{claude_cmd}
"#,
profile = profile,
update_prelude = UPDATE_PRELUDE,
claude_cmd = claude_cmd
);
vec!["bash".to_string(), "-c".to_string(), script]
}
/// A Close from the client: detach, and end a persistent terminal's tmux
/// server (closing a tab is what ends one, as in the desktop app).
async fn close_owned(state: &WebTerminalState, session_id: &str, persistent: bool) {
let target = state.exec_manager.get_target(session_id).await.ok();
state.exec_manager.close_session(session_id).await;
let Some(target) = target else { return };
let Some(key) = tmux_key_of(session_id) else { return };
if persistent {
if let Err(e) = crate::host::persistent::end(&target, key).await {
log::warn!("Web terminal: could not end terminal {session_id}: {e}");
}
}
}
/// The web terminal's exec ids are `web-<tmux key>`, never the bare key: the
/// desktop app attaches to a workspace terminal under the bare key in the
/// same `ExecSessionManager`, and sharing the id would make either front
/// end's attach take over (or its close/disconnect end) the other's exec.
const WEB_EXEC_PREFIX: &str = "web-";
fn web_exec_id(key: &str) -> String {
format!("{WEB_EXEC_PREFIX}{key}")
}
fn tmux_key_of(exec_id: &str) -> Option<&str> {
exec_id.strip_prefix(WEB_EXEC_PREFIX)
}
/// Open a new terminal session for a project.
async fn handle_open(
state: &WebTerminalState,
project_id: &str,
session_type: Option<&str>,
out_tx: &mpsc::UnboundedSender<ServerMessage>,
owned_sessions: &Arc<tokio::sync::Mutex<Vec<(String, bool)>>>,
) -> Result<(), String> {
let project = state
.projects_store
.get(project_id)
.ok_or_else(|| format!("Project {} not found", project_id))?;
if project.status != ProjectStatus::Running {
return Err(format!("Project '{}' is not running", project.name));
}
let container = crate::host::ContainerTarget::for_project_waiting(&project)
.await
.ok_or_else(|| "Container not running".to_string())?;
let cmd = match session_type {
Some("bash") => vec!["bash".to_string(), "-l".to_string()],
_ => build_terminal_cmd(&project, &state.settings_store),
};
// AWS copy-at-connect: the credentials go into this terminal's own
// environment (never the agent's). Empty for everything else.
let env = crate::host::aws_host::terminal_env(&project, &state.settings_store.get()).await;
let key = uuid::Uuid::new_v4().to_string();
let session_id = web_exec_id(&key);
let project_name = project.name.clone();
// AWS: in its own tmux server, like the desktop app's tabs
// (`host::persistent`), so a dropped connection only detaches it. Not
// remembered for the desktop app to reopen: it shows in Project Home →
// Sessions as a session running in the workspace.
let kind = if session_type == Some("bash") {
crate::host::persistent::TerminalKind::Bash
} else {
crate::host::persistent::TerminalKind::Claude
};
let plan = crate::host::persistent::plan(
project.is_aws(),
&container,
&key,
kind,
Some("web terminal"),
cmd,
env,
)
.await?;
if let Some(notice) = plan.notice.clone() {
let _ = out_tx.send(ServerMessage::Error { message: notice });
}
// Set up output routing through the WS channel
let out_tx_output = out_tx.clone();
let session_id_output = session_id.clone();
let on_output = move |data: Vec<u8>| {
let encoded = BASE64.encode(&data);
let _ = out_tx_output.send(ServerMessage::Output {
session_id: session_id_output.clone(),
data: encoded,
});
};
let out_tx_exit = out_tx.clone();
let session_id_exit = session_id.clone();
let on_exit = Box::new(move || {
let _ = out_tx_exit.send(ServerMessage::Exit {
session_id: session_id_exit,
});
});
state
.exec_manager
.create_session(
&container,
&session_id,
plan.cmd,
plan.env,
on_output,
on_exit,
)
.await?;
// Track this session for cleanup on disconnect
owned_sessions.lock().await.push((session_id.clone(), plan.persistent));
let _ = out_tx.send(ServerMessage::Opened {
session_id,
project_name,
// Derived from the same match that chose `cmd` above, not echoed from
// the request: anything that is not exactly "bash" runs Claude, so
// echoing the raw value would label an unrecognised string as its own
// type and put the client back where it started.
session_type: if session_type == Some("bash") { "bash" } else { "claude" }.to_string(),
});
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
/// A desktop reattach (exec id = the bare key) and the web terminal's own
/// exec of the same tmux session never share an `ExecSessionManager` id,
/// in either direction, and the web side maps back to the right key.
#[test]
fn web_and_desktop_execs_of_one_terminal_never_share_an_id() {
let key = "0b9c6f7e-1d2a-4c3b-9e8f-7a6b5c4d3e2f";
let web = web_exec_id(key);
assert_ne!(web, key, "a desktop reattach must not supersede the web exec");
assert_eq!(tmux_key_of(&web), Some(key));
// A desktop exec id is not one the web side would end or detach.
assert_eq!(tmux_key_of(key), None);
crate::host::persistent::validate_key(&web).unwrap();
}
}