Synced from monorepo
Synced from monorepo Changes: - Workspace server: report `/ready` as failed with dwell on hub connect failure - Refresh OIDC token for the Grok agent in the shell - ACP terminal output recorder - Cross-platform provider auth commands in the shell - Default `/resume` to Grok sessions with a hint for hidden external sessions - Resume sessions by title with `--resume` - Limit app-builder archive size - Data-driven tag labels for slash commands - Doctor fixes for tmux - Custom provider gateways and subprocess environment policy in the shell - `/tutorial` — opt-in onboarding tour of Grok Build - Soft and required CLI version checks in the shell - Privacy banner env overrides survive live settings updates - Add remote flag to override the image-edit model - Return profile fields from auth info even when the access token is expired - Add edit control on queued prompt rows - Keep fail-closed policy when clearing orphans with no team - Setting to disable the Ctrl+Space/F8 voice shortcut - Pass `--raw` to pw-record so Linux dictation works on older PipeWire - Validate git URLs when adding marketplace entries - Stop shipping stale tool-doc parameter and tool names - Re-point dashboard attach after `/fork` only when the parent was attached - Surface Grok Computer media-generation results as file-path chunks - Clear web background-task tray on kill and keep the task description - Show privacy upsell banner in agent view until acted on - Add tools-server client callback surface - Protect persistent global hook sources Source-Revision: 95d84f443eddcbed6cbfd6eed22e2eafe6b3939d
This commit is contained in:
parent
a5727c5960
commit
69f0ba880a
286 changed files with 22939 additions and 9624 deletions
|
|
@ -1,6 +1,14 @@
|
|||
//! Shared tmux command protocol and result parsing.
|
||||
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::Duration;
|
||||
|
||||
const TMUX_QUERY_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
/// After the leader exits, allow this much additional time for process-group
|
||||
/// teardown and concurrent pipe drains so a near-deadline success is not turned
|
||||
/// into a drain timeout. The main process wait still uses only
|
||||
/// [`TMUX_QUERY_TIMEOUT`].
|
||||
const POST_EXIT_CLEANUP_GRACE: Duration = Duration::from_millis(300);
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum TmuxCommand<'a> {
|
||||
|
|
@ -25,17 +33,110 @@ struct LiveTmuxCommandRunner;
|
|||
|
||||
impl TmuxCommandRunner for LiveTmuxCommandRunner {
|
||||
fn run(&self, command: TmuxCommand<'_>) -> Result<TmuxCommandOutput, String> {
|
||||
let output = build_tmux_command(command)
|
||||
.output()
|
||||
.map_err(|error| format!("failed to run tmux: {error}"))?;
|
||||
Ok(TmuxCommandOutput {
|
||||
status_success: output.status.success(),
|
||||
stdout: output.stdout,
|
||||
stderr: output.stderr,
|
||||
})
|
||||
run_tmux_bounded(command, TMUX_QUERY_TIMEOUT)
|
||||
}
|
||||
}
|
||||
|
||||
fn run_tmux_bounded(
|
||||
command: TmuxCommand<'_>,
|
||||
timeout: Duration,
|
||||
) -> Result<TmuxCommandOutput, String> {
|
||||
let mut command = build_tmux_command(command);
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.map_err(|error| format!("failed to run tmux: {error}"))?;
|
||||
let group = xai_tty_utils::ProcessGroup::new()
|
||||
.and_then(|mut group| {
|
||||
group.attach_std(&child)?;
|
||||
Ok(group)
|
||||
})
|
||||
.map_err(|error| {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
format!("failed to own tmux process tree: {error}")
|
||||
})?;
|
||||
let stdout = child
|
||||
.stdout
|
||||
.take()
|
||||
.ok_or_else(|| "tmux stdout pipe was not captured".to_owned())?;
|
||||
let stderr = child
|
||||
.stderr
|
||||
.take()
|
||||
.ok_or_else(|| "tmux stderr pipe was not captured".to_owned())?;
|
||||
let stdout = spawn_pipe_drain(stdout, "stdout");
|
||||
let stderr = spawn_pipe_drain(stderr, "stderr");
|
||||
let deadline = std::time::Instant::now() + timeout;
|
||||
|
||||
let status = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break status,
|
||||
Ok(None) if std::time::Instant::now() < deadline => {
|
||||
std::thread::sleep(Duration::from_millis(15));
|
||||
}
|
||||
Ok(None) => {
|
||||
terminate_tmux_tree(&group, &mut child);
|
||||
return Err(format!("tmux query timed out after {timeout:?}"));
|
||||
}
|
||||
Err(error) => {
|
||||
terminate_tmux_tree(&group, &mut child);
|
||||
return Err(format!("failed to wait for tmux: {error}"));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// The leader may be reaped while descendants still exist or hold pipes.
|
||||
// Use a fresh post-exit bound so near-deadline success still drains; the
|
||||
// main process deadline is not extended for hung leaders.
|
||||
let cleanup_deadline = std::time::Instant::now() + POST_EXIT_CLEANUP_GRACE;
|
||||
terminate_owned_group(&group);
|
||||
let stdout = recv_pipe_drain(stdout, cleanup_deadline, "stdout")?;
|
||||
let stderr = recv_pipe_drain(stderr, cleanup_deadline, "stderr")?;
|
||||
Ok(TmuxCommandOutput {
|
||||
status_success: status.success(),
|
||||
stdout,
|
||||
stderr,
|
||||
})
|
||||
}
|
||||
|
||||
fn spawn_pipe_drain(
|
||||
mut pipe: impl std::io::Read + Send + 'static,
|
||||
label: &'static str,
|
||||
) -> std::sync::mpsc::Receiver<Result<Vec<u8>, String>> {
|
||||
let (sender, receiver) = std::sync::mpsc::sync_channel(1);
|
||||
std::thread::spawn(move || {
|
||||
let mut output = Vec::new();
|
||||
let result = pipe
|
||||
.read_to_end(&mut output)
|
||||
.map(|_| output)
|
||||
.map_err(|error| format!("failed to read tmux {label}: {error}"));
|
||||
let _ = sender.send(result);
|
||||
});
|
||||
receiver
|
||||
}
|
||||
|
||||
fn recv_pipe_drain(
|
||||
receiver: std::sync::mpsc::Receiver<Result<Vec<u8>, String>>,
|
||||
deadline: std::time::Instant,
|
||||
label: &'static str,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
|
||||
receiver
|
||||
.recv_timeout(remaining)
|
||||
.map_err(|_| format!("tmux {label} did not close before the query deadline"))?
|
||||
}
|
||||
|
||||
fn terminate_tmux_tree(group: &xai_tty_utils::ProcessGroup, child: &mut std::process::Child) {
|
||||
terminate_owned_group(group);
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
fn terminate_owned_group(group: &xai_tty_utils::ProcessGroup) {
|
||||
let _ = group.terminate();
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
// KILL is unconditional because leader state says nothing about descendants.
|
||||
let _ = group.kill();
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum TmuxQueryResult<T> {
|
||||
Available(T),
|
||||
|
|
@ -102,22 +203,22 @@ fn build_tmux_command(command: TmuxCommand<'_>) -> Command {
|
|||
let mut cmd = Command::new("tmux");
|
||||
match command {
|
||||
TmuxCommand::Version => {
|
||||
cmd.arg("-V").stdout(Stdio::piped()).stderr(Stdio::null());
|
||||
cmd.arg("-V").stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
}
|
||||
TmuxCommand::OptionValue(option) => {
|
||||
cmd.args(["show-option", "-gqv", option])
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null());
|
||||
.stderr(Stdio::piped());
|
||||
}
|
||||
TmuxCommand::OptionSupport(option) => {
|
||||
cmd.args(["show-option", "-gv", option])
|
||||
.stdout(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
}
|
||||
TmuxCommand::ControlMode => {
|
||||
cmd.args(["display-message", "-p", "#{client_flags}"])
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null());
|
||||
.stderr(Stdio::piped());
|
||||
}
|
||||
}
|
||||
cmd.stdin(Stdio::null()).envs(xai_tty_utils::pager_env());
|
||||
|
|
@ -271,4 +372,67 @@ mod tests {
|
|||
TmuxQueryResult::Unavailable
|
||||
);
|
||||
}
|
||||
|
||||
/// A leader that exits successfully just under the process deadline must
|
||||
/// still return captured output: post-exit TERM grace + pipe drain use a
|
||||
/// separate bound and must not turn success into a drain timeout.
|
||||
///
|
||||
/// A background descendant keeps the captured pipes open until process-group
|
||||
/// teardown so the drain cannot finish during the wait loop. That makes the
|
||||
/// post-exit cleanup window load-bearing once the main deadline is nearly
|
||||
/// exhausted.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
#[serial_test::serial(tmux_probe_path)]
|
||||
fn successful_near_deadline_exit_still_returns_captured_output() {
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let bin = temp.path().join("bin");
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
let tmux = bin.join("tmux");
|
||||
// Burn most of the process budget, then exit successfully while a
|
||||
// descendant still holds the pipes. Remaining main-deadline time is
|
||||
// intentionally below the fixed TERM grace sleep so a shared deadline
|
||||
// would fail the drain; the separate post-exit cleanup grace must keep
|
||||
// this a success. Perl select is used for subsecond precision.
|
||||
let timeout = Duration::from_millis(1500);
|
||||
std::fs::write(
|
||||
&tmux,
|
||||
"#!/bin/sh\n\
|
||||
/usr/bin/perl -e 'select(undef, undef, undef, 1.2)'\n\
|
||||
( exec sleep 30 ) &\n\
|
||||
printf 'tmux 3.4\\n'\n\
|
||||
exit 0\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&tmux, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
let previous_path = std::env::var_os("PATH");
|
||||
let mut path = OsString::from(bin.as_os_str());
|
||||
path.push(":");
|
||||
if let Some(existing) = &previous_path {
|
||||
path.push(existing);
|
||||
}
|
||||
// SAFETY: serialized on `tmux_probe_path`; restored before return.
|
||||
unsafe {
|
||||
std::env::set_var("PATH", &path);
|
||||
}
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
run_tmux_bounded(TmuxCommand::Version, timeout)
|
||||
}));
|
||||
match previous_path {
|
||||
Some(value) => unsafe {
|
||||
std::env::set_var("PATH", value);
|
||||
},
|
||||
None => unsafe {
|
||||
std::env::remove_var("PATH");
|
||||
},
|
||||
}
|
||||
let output = result
|
||||
.expect("near-deadline probe must not panic")
|
||||
.expect("near-deadline success must not become a drain error");
|
||||
assert!(output.status_success, "expected successful status");
|
||||
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "tmux 3.4");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue