Add /daemon menu for local background server updates (#45854)

## Why

Local daemon version warnings direct users to a shell command. Provide an update flow from the TUI with an explicit choice of package source and confirmation before exiting.

## What changed

- Add `/daemon` with options to install the latest public stable release or use the current CLI package. Point local server version notices to the menu.
- Default confirmation to Cancel and explain restart, interruption, and relaunch behavior. After confirmation, exit the TUI and run the update through the launching CLI executable, propagating failures.
- Keep maintenance available when disconnected or using the embedded server. Disable updates for remote connections or a missing CLI executable, and disable copying the CLI build when no local package is available.

## Testing

Add menu snapshots and interaction tests covering both update sources, cancellation, and unavailable actions. Add a Unix CLI handoff test verifying the selected executable, command arguments, and failure propagation.

GitOrigin-RevId: 06b485feb5650673ec7dd00adda01fedb8909393
This commit is contained in:
Eric Traut authored and copyberry committed 2026-09-16 03:43:59 +00:00
1 parent 7322c5e790
commit 04581f9604
31 files changed
+544 -18

No files matched your search

+132
View File
@@ -0,0 +1,132 @@
//! Local daemon maintenance only records an update action after explicit confirmation.
//! The CLI executes it in the foreground after the TUI restores the terminal.
use super::*;
use crate::bottom_pane::SelectionItem;
use crate::bottom_pane::SelectionViewParams;
use crate::update_action::DaemonUpdateSource;
use crate::wrapping::word_wrap_lines;
use ratatui::buffer::Buffer;
use ratatui::widgets::Paragraph;
struct DaemonMenuHeader(Vec<Line<'static>>);
impl Renderable for DaemonMenuHeader {
fn render(&self, area: Rect, buf: &mut Buffer) {
Renderable::render(
&Paragraph::new(word_wrap_lines(&self.0, usize::from(area.width))),
area,
buf,
);
}
fn desired_height(&self, width: u16) -> u16 {
word_wrap_lines(&self.0, usize::from(width)).len() as u16
}
}
impl App {
pub(super) fn open_daemon_menu(&mut self) {
let status = self
.chat_widget
.remote_connection
.as_ref()
.filter(|_| matches!(self.app_server_target, AppServerTarget::LocalDaemon { .. }))
.map(|connection| format!("Running daemon: {}", connection.version))
.unwrap_or_else(|| "Not connected to the local background server.".to_string());
let mut header = vec![Line::from("Daemon".bold()), Line::from(status.dim())];
let unavailable = if matches!(self.app_server_target, AppServerTarget::Remote { .. }) {
Some(
"Manage this server on its host. Local daemon updates are unavailable for remote connections.",
)
} else if self.daemon_cli_executable.is_none() {
Some("Run the Codex CLI to manage the daemon from this menu.")
} else {
None
};
if let Some(guidance) = unavailable {
header.push(Line::from(guidance.dim()));
}
let has_package = self.daemon_cli_executable.as_ref().is_some_and(|path| {
codex_install_context::InstallContext::from_exe(
cfg!(target_os = "macos"),
Some(path.as_path()),
/*method_override*/ None,
)
.package_layout
.is_some()
});
let items = [
(
DaemonUpdateSource::PublicStable,
"Install latest public stable",
),
(DaemonUpdateSource::ThisCli, "Use this CLI build"),
]
.into_iter()
.map(|(source, name)| SelectionItem {
name: name.to_string(),
is_disabled: unavailable.is_some(),
disabled_reason: (unavailable.is_none()
&& source == DaemonUpdateSource::ThisCli
&& !has_package)
.then(|| "This CLI has no local package to copy.".to_string()),
actions: vec![Box::new(move |tx| {
tx.send(AppEvent::ConfirmDaemonUpdate(source));
})],
dismiss_on_select: true,
..Default::default()
})
.collect();
self.chat_widget.show_selection_view(SelectionViewParams {
header: Box::new(DaemonMenuHeader(header)),
items,
..Default::default()
});
}
pub(super) fn confirm_daemon_update(&mut self, source: DaemonUpdateSource) {
let Some(executable) = &self.daemon_cli_executable else {
return;
};
if matches!(self.app_server_target, AppServerTarget::Remote { .. }) {
return;
}
let mut explanation = match source {
DaemonUpdateSource::PublicStable => "Install the latest public stable release (version resolved when the command runs). Production update eligibility will be restored; your automatic-update setting is preserved.".to_string(),
DaemonUpdateSource::ThisCli => {
let version = codex_install_context::InstallContext::current()
.package_manifest()
.map_or_else(|| CODEX_CLI_VERSION.to_string(), |manifest| manifest.version.to_string());
format!("Use this CLI package v{version} from {}. The complete local package will be copied and pinned against automatic updates.", executable.display())
}
};
explanation.push_str("\nThe daemon will restart if needed. Active or queued work may be interrupted.\nCodex will exit and run the update in this terminal, then return to the shell. Relaunch Codex afterward.");
let mut header = vec![Line::from("Update daemon and exit Codex?".bold())];
header.extend(explanation.lines().map(|line| Line::from(line.to_owned())));
self.chat_widget.show_selection_view(SelectionViewParams {
header: Box::new(DaemonMenuHeader(header)),
items: vec![
SelectionItem {
name: "Cancel".to_string(),
dismiss_on_select: true,
..Default::default()
},
SelectionItem {
name: "Update and exit".to_string(),
actions: vec![Box::new(move |tx| {
tx.send(AppEvent::RunDaemonUpdate(source))
})],
require_explicit_confirmation: true,
dismiss_on_select: true,
..Default::default()
},
],
..Default::default()
});
}
}
#[cfg(test)]
#[path = "daemon_menu_tests.rs"]
mod tests;
+168
View File
@@ -0,0 +1,168 @@
use super::*;
use crate::app::test_support::make_test_app;
use crate::chatwidget::tests::helpers::render_bottom_popup;
use crate::chatwidget::tests::make_chatwidget_manual_with_sender;
use crate::status::remote_connection::RemoteConnectionStatus;
use crossterm::event::KeyCode;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn daemon_menu_is_read_only_and_confirmation_can_cancel_or_handoff() {
let mut app = make_test_app().await;
let (chat, _, mut rx, _) = make_chatwidget_manual_with_sender().await;
app.chat_widget = chat;
let package = tempfile::tempdir().unwrap();
std::fs::create_dir(package.path().join("bin")).unwrap();
std::fs::write(package.path().join("bin/codex"), "CLI").unwrap();
std::fs::write(package.path().join("codex-package.json"), "{}").unwrap();
app.daemon_cli_executable =
Some(AbsolutePathBuf::from_absolute_path(package.path().join("bin/codex")).unwrap());
app.app_server_target = AppServerTarget::LocalDaemon {
endpoint: crate::RemoteAppServerEndpoint::UnixSocket {
socket_path: AbsolutePathBuf::relative_to_current_dir("codex.sock").unwrap(),
},
};
app.chat_widget.remote_connection = Some(RemoteConnectionStatus {
address: "local".into(),
version: "v0.153.0".into(),
});
app.initialize_server_version_notice("0.154.0", Some("0.153.0"));
let view = app.agents_overview_view(Vec::new(), /*selected_thread_id*/ None);
app.chat_widget.show_bottom_pane_view(Box::new(view));
let overview = render_bottom_popup(&app.chat_widget, /*width*/ 80);
insta::assert_snapshot!(overview.lines().next().unwrap().trim(), @"Service v0.153.0 < Codex CLI v0.154.0 · /daemon");
let executable = app.daemon_cli_executable.clone();
for (width, source, snapshot) in [
(
80,
DaemonUpdateSource::PublicStable,
"daemon_stable_confirmation",
),
(100, DaemonUpdateSource::ThisCli, "daemon_cli_confirmation"),
] {
app.daemon_cli_executable = executable.clone();
app.open_daemon_menu();
if source == DaemonUpdateSource::PublicStable {
insta::assert_snapshot!(
"daemon_menu",
render_bottom_popup(&app.chat_widget, /*width*/ 80)
);
} else {
app.chat_widget.handle_key_event(KeyCode::Down.into());
}
assert!(rx.try_recv().is_err());
app.chat_widget.handle_key_event(KeyCode::Enter.into());
assert!(
matches!(rx.try_recv().unwrap(), AppEvent::ConfirmDaemonUpdate(selected) if selected == source)
);
app.daemon_cli_executable = Some(
AbsolutePathBuf::from_absolute_path(if cfg!(windows) {
r"C:\cli-build\bin\codex"
} else {
"/x/cli-build/bin/codex"
})
.unwrap(),
);
app.confirm_daemon_update(source);
insta::assert_snapshot!(
snapshot,
render_bottom_popup(&app.chat_widget, width)
.replace(r"C:\cli-build\bin\codex", "/x/cli-build/bin/codex")
);
// The default choice cancels without emitting an update or exiting.
app.chat_widget.handle_key_event(KeyCode::Enter.into());
assert!(rx.try_recv().is_err());
assert_eq!(app.pending_update_action, None);
app.confirm_daemon_update(source);
app.chat_widget.handle_key_event(KeyCode::Down.into());
app.chat_widget.handle_key_event(KeyCode::Enter.into());
assert!(
matches!(rx.try_recv().unwrap(), AppEvent::RunDaemonUpdate(selected) if selected == source)
);
}
// Maintenance remains available when startup selects the embedded server.
app.app_server_target = AppServerTarget::Embedded;
app.chat_widget.remote_connection = None;
app.daemon_cli_executable = executable;
for source in [
DaemonUpdateSource::PublicStable,
DaemonUpdateSource::ThisCli,
] {
app.open_daemon_menu();
if source == DaemonUpdateSource::PublicStable {
insta::assert_snapshot!(
"daemon_disconnected",
render_bottom_popup(&app.chat_widget, /*width*/ 80)
);
} else {
app.chat_widget.handle_key_event(KeyCode::Down.into());
}
assert!(rx.try_recv().is_err());
app.chat_widget.handle_key_event(KeyCode::Enter.into());
assert!(
matches!(rx.try_recv().unwrap(), AppEvent::ConfirmDaemonUpdate(selected) if selected == source)
);
app.confirm_daemon_update(source);
app.chat_widget.handle_key_event(KeyCode::Enter.into());
assert!(rx.try_recv().is_err());
assert_eq!(app.pending_update_action, None);
app.confirm_daemon_update(source);
app.chat_widget.handle_key_event(KeyCode::Down.into());
app.chat_widget.handle_key_event(KeyCode::Enter.into());
assert!(
matches!(rx.try_recv().unwrap(), AppEvent::RunDaemonUpdate(selected) if selected == source)
);
}
std::fs::remove_file(package.path().join("codex-package.json")).unwrap();
// The full CLI can have any filename; capability comes from its entry point.
app.daemon_cli_executable =
Some(AbsolutePathBuf::from_absolute_path(package.path().join("bin/codex-tui")).unwrap());
app.open_daemon_menu();
insta::assert_snapshot!(
"daemon_unpackaged_cli",
render_bottom_popup(&app.chat_widget, /*width*/ 80)
);
app.chat_widget.handle_key_event(KeyCode::Enter.into());
assert!(matches!(
rx.try_recv().unwrap(),
AppEvent::ConfirmDaemonUpdate(DaemonUpdateSource::PublicStable)
));
app.daemon_cli_executable = None;
app.open_daemon_menu();
insta::assert_snapshot!(
"daemon_no_cli_handoff",
render_bottom_popup(&app.chat_widget, /*width*/ 80)
);
app.chat_widget.handle_key_event(KeyCode::Enter.into());
assert!(rx.try_recv().is_err());
}
#[tokio::test]
async fn unavailable_daemon_menu_offers_guidance_without_update_actions() {
let mut app = make_test_app().await;
app.daemon_cli_executable =
Some(AbsolutePathBuf::from_absolute_path(std::env::current_exe().unwrap()).unwrap());
let (chat, _, mut rx, _) = make_chatwidget_manual_with_sender().await;
app.chat_widget = chat;
app.app_server_target = AppServerTarget::Remote {
endpoint: crate::RemoteAppServerEndpoint::WebSocket {
websocket_url: "ws://example.test:1234".into(),
auth_token: None,
},
};
app.chat_widget.remote_connection = Some(RemoteConnectionStatus {
address: "ws://example.test:1234".into(),
version: "v0.153.0".into(),
});
app.open_daemon_menu();
insta::assert_snapshot!(
"daemon_remote_guidance",
render_bottom_popup(&app.chat_widget, /*width*/ 80)
);
app.chat_widget.handle_key_event(KeyCode::Enter.into());
assert!(rx.try_recv().is_err());
assert_eq!(app.pending_update_action, None);
}
+10 -1
View File
@@ -34,7 +34,10 @@ impl App {
if self.reconnect.offline
&& !matches!(
&event,
AppEvent::InsertHistoryCell(_)
AppEvent::OpenDaemonMenu
| AppEvent::ConfirmDaemonUpdate(_)
| AppEvent::RunDaemonUpdate(_)
| AppEvent::InsertHistoryCell(_)
| AppEvent::CommitRealtimeTranscriptHistory
| AppEvent::ResetTranscriptForThreadSwitch
| AppEvent::FinishPromptRevert { .. }
@@ -94,6 +97,12 @@ impl App {
}
match event {
AppEvent::OpenDaemonMenu => self.open_daemon_menu(),
AppEvent::ConfirmDaemonUpdate(source) => self.confirm_daemon_update(source),
AppEvent::RunDaemonUpdate(source) => {
self.pending_update_action = Some(UpdateAction::Daemon(source));
return Ok(self.handle_exit_mode(app_server, ExitMode::Immediate).await);
}
AppEvent::UserVerificationApproved { thread_id, server_name, request_id } => {
Box::pin(self.start_user_verification(app_server, thread_id, server_name, request_id)).await?;
}
+10 -3
View File
@@ -1,4 +1,4 @@
//! Keeps the older remote server notice in the overview's shared view state.
//! Keeps the older server notice and local maintenance guidance in the overview.
use super::*;
@@ -47,7 +47,14 @@ impl App {
.view_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.server_version_notice =
older_server.map(|server| format!("Service v{server} < Codex CLI v{client_version}"));
.server_version_notice = older_server.map(|server| {
let guidance = if matches!(self.app_server_target, AppServerTarget::LocalDaemon { .. })
{
" · /daemon"
} else {
""
};
format!("Service v{server} < Codex CLI v{client_version}{guidance}")
});
}
}
@@ -0,0 +1,15 @@
---
source: tui/src/app/daemon_menu_tests.rs
expression: "render_bottom_popup(&app.chat_widget,\nwidth).replace(r\"C:\\cli-build\\bin\\codex\", \"/x/cli-build/bin/codex\")"
---
Update daemon and exit Codex?
Use this CLI package v0.0.0 from /x/cli-build/bin/codex. The complete local package will be
copied and pinned against automatic updates.
The daemon will restart if needed. Active or queued work may be interrupted.
Codex will exit and run the update in this terminal, then return to the shell. Relaunch Codex
afterward.
› 1. Cancel
2. Update and exit
Press enter to confirm or esc to go back
@@ -0,0 +1,11 @@
---
source: tui/src/app/daemon_menu_tests.rs
expression: "render_bottom_popup(&app.chat_widget, 80)"
---
Daemon
Not connected to the local background server.
› 1. Install latest public stable
2. Use this CLI build
Press enter to confirm or esc to go back
@@ -0,0 +1,11 @@
---
source: tui/src/app/daemon_menu_tests.rs
expression: "render_bottom_popup(&app.chat_widget, 80)"
---
Daemon
Running daemon: v0.153.0
› 1. Install latest public stable
2. Use this CLI build
Press enter to confirm or esc to go back
@@ -0,0 +1,12 @@
---
source: tui/src/app/daemon_menu_tests.rs
expression: "render_bottom_popup(&app.chat_widget, 80)"
---
Daemon
Not connected to the local background server.
Run the Codex CLI to manage the daemon from this menu.
› Install latest public stable
Use this CLI build
Press enter to confirm or esc to go back
@@ -0,0 +1,13 @@
---
source: tui/src/app/daemon_menu_tests.rs
expression: "render_bottom_popup(&app.chat_widget, 80)"
---
Daemon
Not connected to the local background server.
Manage this server on its host. Local daemon updates are unavailable for
remote connections.
› Install latest public stable
Use this CLI build
Press enter to confirm or esc to go back
@@ -0,0 +1,16 @@
---
source: tui/src/app/daemon_menu_tests.rs
expression: "render_bottom_popup(&app.chat_widget,\nwidth).replace(r\"C:\\cli-build\\bin\\codex\", \"/x/cli-build/bin/codex\")"
---
Update daemon and exit Codex?
Install the latest public stable release (version resolved when the command
runs). Production update eligibility will be restored; your automatic-update
setting is preserved.
The daemon will restart if needed. Active or queued work may be interrupted.
Codex will exit and run the update in this terminal, then return to the
shell. Relaunch Codex afterward.
› 1. Cancel
2. Update and exit
Press enter to confirm or esc to go back
@@ -0,0 +1,12 @@
---
source: tui/src/app/daemon_menu_tests.rs
expression: "render_bottom_popup(&app.chat_widget, 80)"
---
Daemon
Not connected to the local background server.
› 1. Install latest public stable
Use this CLI build (disabled) disabled: This CLI has no local package to
copy.
Press enter to confirm or esc to go back
+2
View File
@@ -156,6 +156,7 @@ impl App {
startup_hooks_browser: Option<HooksListEntry>,
mut startup_draft: StartupDraftPump,
managed_worktree: Option<crate::ManagedTuiWorktree>,
daemon_cli_executable: Option<AbsolutePathBuf>,
) -> Result<AppExitInfo> {
use tokio_stream::StreamExt;
@@ -756,6 +757,7 @@ See the Codex keymap documentation for supported actions and examples."
.map(|(_, key)| key.clone()),
..Default::default()
},
daemon_cli_executable,
pending_update_action: None,
pending_shutdown_exit_thread_id: None,
windows_sandbox: WindowsSandboxState {
+1
View File
@@ -62,6 +62,7 @@ pub(super) async fn make_test_app() -> App {
environment_manager: Arc::new(EnvironmentManager::default_for_tests()),
app_server_target: crate::AppServerTarget::Embedded,
reconnect: Default::default(),
daemon_cli_executable: None,
pending_update_action: None,
pending_shutdown_exit_thread_id: None,
windows_sandbox: WindowsSandboxState::default(),
+2
View File
@@ -5924,6 +5924,7 @@ async fn make_test_app() -> App {
environment_manager: Arc::new(EnvironmentManager::default_for_tests()),
app_server_target: crate::AppServerTarget::Embedded,
reconnect: Default::default(),
daemon_cli_executable: None,
pending_update_action: None,
pending_shutdown_exit_thread_id: None,
windows_sandbox: WindowsSandboxState::default(),
@@ -6024,6 +6025,7 @@ pub(super) async fn make_test_app_with_channels() -> (
environment_manager: Arc::new(EnvironmentManager::default_for_tests()),
app_server_target: crate::AppServerTarget::Embedded,
reconnect: Default::default(),
daemon_cli_executable: None,
pending_update_action: None,
pending_shutdown_exit_thread_id: None,
windows_sandbox: WindowsSandboxState::default(),
@@ -35,6 +35,7 @@ async fn run_startup_for_test(
/*startup_hooks_browser*/ None,
crate::startup_draft::tests::quiet_startup_test_pump(),
/*managed_worktree*/ None,
/*daemon_cli_executable*/ None,
)
.await
}