From 1460915530aeb69ba4452d508dc90b4acf10cf5a Mon Sep 17 00:00:00 2001 From: GeekMr <140129782+WilliamWang1721@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:31:16 +0800 Subject: [PATCH 01/15] feat(agents): configure explicit automatic resume arguments --- .config/nextest.toml | 2 +- .../2026-10-03-explicit-resume-arguments.md | 64 +++++++++++++++ nebula_app/i18n/en-US.json | 4 + nebula_app/i18n/zh-CN.json | 4 + nebula_app/src/agent_resume.rs | 71 ++++++++++++++++ nebula_app/src/gpui_shell/config.rs | 2 + nebula_app/src/gpui_shell/settings_pane.rs | 1 + .../gpui_shell/settings_pane/agent_resume.rs | 72 +++++++++++++++++ .../settings_pane/agent_resume_tests.rs | 66 +++++++++++++++ .../src/gpui_shell/settings_pane/agents.rs | 36 ++++++++- .../gpui_shell/settings_pane/agents/tests.rs | 3 + .../settings_pane/initialization.rs | 3 +- .../terminal/view/startup_command.rs | 24 +++++- .../gpui_shell/terminal/view/startup_tests.rs | 80 +++++++++++++++++++ nebula_app/src/main.rs | 1 + nebula_settings/src/agent_resume.rs | 57 +++++++++++++ nebula_settings/src/lib.rs | 5 ++ nebula_settings/src/reset.rs | 12 +++ 18 files changed, 502 insertions(+), 5 deletions(-) create mode 100644 architecture/notes/nebula_settings/agent_resume/2026-10-03-explicit-resume-arguments.md create mode 100644 nebula_app/src/agent_resume.rs create mode 100644 nebula_app/src/gpui_shell/settings_pane/agent_resume.rs create mode 100644 nebula_app/src/gpui_shell/settings_pane/agent_resume_tests.rs create mode 100644 nebula_settings/src/agent_resume.rs diff --git a/.config/nextest.toml b/.config/nextest.toml index c0a001ca0..e46d2b800 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -6,7 +6,7 @@ theme-studio = { max-threads = 1 } [[profile.default.overrides]] -filter = 'test(gpui_shell::settings_pane::theme_studio_tests::) or test(ctrl_wheel_font_zoom_toggle_gates_zoom_and_terminal_scroll) or test(ctrl_wheel_font_zoom_setting_is_searchable_and_has_a_visible_switch) or test(environment_refresh_switch_is_searchable_and_persists) or test(pasted_proxy_scheme_updates_the_visible_protocol_and_saved_url) or test(capsule_uses_inset_thumb_full_hit_targets_and_keyboard_selection) or test(long_segments_use_a_real_dropdown_without_losing_preference_updates) or test(font_size_click_input_commits_cancels_and_bounds_values) or test(cjk_dropdown_selection_preserves_the_english_font_chain) or test(review_regression_font_fields_align_and_dropdown_toggles_with_search)' +filter = 'test(gpui_shell::settings_pane::theme_studio_tests::) or test(ctrl_wheel_font_zoom_toggle_gates_zoom_and_terminal_scroll) or test(ctrl_wheel_font_zoom_setting_is_searchable_and_has_a_visible_switch) or test(environment_refresh_switch_is_searchable_and_persists) or test(pasted_proxy_scheme_updates_the_visible_protocol_and_saved_url) or test(capsule_uses_inset_thumb_full_hit_targets_and_keyboard_selection) or test(long_segments_use_a_real_dropdown_without_losing_preference_updates) or test(font_size_click_input_commits_cancels_and_bounds_values) or test(cjk_dropdown_selection_preserves_the_english_font_chain) or test(review_regression_font_fields_align_and_dropdown_toggles_with_search) or test(resume_arguments_save_reopen_reject_invalid_and_clear_through_real_controls)' test-group = 'theme-studio' # 三模式夹具包含九个真实 Git/窗口场景;原生进程的墙钟期限不能用并发 UI 负载测试。 diff --git a/architecture/notes/nebula_settings/agent_resume/2026-10-03-explicit-resume-arguments.md b/architecture/notes/nebula_settings/agent_resume/2026-10-03-explicit-resume-arguments.md new file mode 100644 index 000000000..c5b6a9678 --- /dev/null +++ b/architecture/notes/nebula_settings/agent_resume/2026-10-03-explicit-resume-arguments.md @@ -0,0 +1,64 @@ +# Explicit automatic Agent resume arguments + +## Status +Proposed for review, 2026-10-03. + +## Context +[Issue #323](https://github.com/Kuddev/pebrel/issues/323) requests explicit per-Agent +arguments when restarting Pebrel, while preserving the default resume command for +users who have not configured them. The request does not establish a permission +regression in any provider. + +## Evidence +`AgentSession::resume_command` already owns saved identity validation, including +Codex rollout normalization. GPUI workspace recovery calls +`TerminalView::restore_agent`, which waits for a new shell prompt before submission. +Pi resolves a native session file asynchronously before constructing its command. +`RuntimeSettings` and `SettingsPane::try_persist` already own preference loading, +persistence and the cached GPUI snapshot. + +## Decision +Add eleven stable `agent_resume_args_` preferences for providers with an +existing resume command. Each value is a JSON array of literal, nonempty arguments; +missing/empty values and `[]` append nothing. The zero-dependency settings crate +preserves the serialized value; the application uses its existing JSON dependency +and target-shell quoting helper. Arrays are limited to 32 arguments and 64 KiB +quoted text; control characters are rejected. CMD rejects double quotes, `%` and +`!`, and quoted trailing backslashes are doubled for the native argv parser. + +The GPUI Agent page edits drafts and validates them on Save, reports persistence +success/failure in place, and resets them with other preferences. Saving updates the +cached settings immediately for the next cold resume or retry. A command already +queued for submission retains its original snapshot. Automatic cold recovery, +including resolved Pi targets, appends arguments after the existing identity. +Invalid serialized arguments or unsupported shell quoting fail the recovery without +silently retrying a different command. The existing recovery UI retains the target. + +## Rejected alternatives +Full command templates need a new substitution language and executable policy. +Replaying launch history may reproduce permissions the user never opted to resume. +Interpreting a raw shell suffix would execute expansions rather than literal args. +New parsing dependencies in the settings core violate its existing boundary. + +## Consequences +No arguments or permission flags are enabled by default. Session identity and cwd +remain owned by existing recovery; session snapshots do not acquire launch history. +The setting applies to GPUI automatic recovery and retry, independent of hook +installation. Manual palette resume, forks and runtime Agent start retain their +existing commands. Legacy shell UI does not expose or apply this additive setting. +The new keys remain outside the existing WebDAV sync allowlist because arguments +can contain machine-specific values; this change does not broaden sync policy. + +## Validation +Authored settings round-trip/reset tests, literal shell-quoting tests, rendered +Save/reopen/invalid/clear coverage and real cold recovery/PTY submission/retry tests. +All formatting, architecture, compile and native tests must run in GitHub Actions; +local inspection is not execution evidence. Native screenshot and real CLI +acceptance are separate from these regression tests. + +## Supersedes +None. + +## Revisit when +A concrete wrapper executable/template or manual-resume configuration requirement +is accepted, or a supported shell's literal argument contract changes. diff --git a/nebula_app/i18n/en-US.json b/nebula_app/i18n/en-US.json index 52874d55b..8f9e87a01 100644 --- a/nebula_app/i18n/en-US.json +++ b/nebula_app/i18n/en-US.json @@ -194,6 +194,10 @@ "save_failed": "Could not change startup settings: {error}" }, "agents": { + "resume_title": "Automatic resume arguments", + "resume_description": "Enter a JSON array of literal arguments for each agent, such as [\"--flag\", \"value\"]. Empty keeps the default command. Saved values apply to the next automatic resume or retry; they never replay command history. CMD cannot accept arguments containing double quotes, % or !.", + "resume_invalid": "Use a JSON array of up to 32 nonempty strings, without control characters (at most 64 KiB after quoting).", + "resume_failed": "Could not save resume arguments: {error}", "title": "Coding agents", "description": "Show agent activity, completion and approval requests in Pebrel. Claude Code and Codex are enabled by default.", "refresh": "Refresh", diff --git a/nebula_app/i18n/zh-CN.json b/nebula_app/i18n/zh-CN.json index a61a8c5b9..3820577c8 100644 --- a/nebula_app/i18n/zh-CN.json +++ b/nebula_app/i18n/zh-CN.json @@ -194,6 +194,10 @@ "save_failed": "无法更改启动设置:{error}" }, "agents": { + "resume_title": "自动接续附加参数", + "resume_description": "按 Agent 输入由字面参数组成的 JSON 数组,例如 [\"--flag\", \"value\"]。留空保持默认命令。保存后用于下次自动接续或重试,不重放命令历史。CMD 不支持包含双引号、% 或 ! 的参数。", + "resume_invalid": "请输入最多 32 个非空字符串组成的 JSON 数组,不包含控制字符(引用后最多 64 KiB)。", + "resume_failed": "无法保存接续参数:{error}", "title": "编程智能体", "description": "在 Pebrel 中显示运行状态、完成通知和授权请求。Claude Code 与 Codex 默认开启。", "refresh": "刷新", diff --git a/nebula_app/src/agent_resume.rs b/nebula_app/src/agent_resume.rs new file mode 100644 index 000000000..09483e8c1 --- /dev/null +++ b/nebula_app/src/agent_resume.rs @@ -0,0 +1,71 @@ +//! Literal argument arrays for automatic recovery, quoted for the pane's shell. + +use crate::display::side_panel::{PathQuote, drop_text_for_paths}; + +pub(crate) fn parse(value: &str) -> Option> { + if value.trim().is_empty() { + return Some(Vec::new()); + } + let args: Vec = serde_json::from_str(value).ok()?; + if args.is_empty() { + return Some(args); + } + drop_text_for_paths(&args, PathQuote::Posix)?; + Some(args) +} + +pub(crate) fn append(command: String, value: &str, shell: PathQuote) -> Option { + let args = parse(value)?; + if args.is_empty() { + return Some(command); + } + let quoted = if matches!(shell, PathQuote::CommandPrompt) { + let mut quoted = String::new(); + // CMD passes quotes to the CLI's argv parser. A quoted argument ending in + // a backslash needs doubled trailing slashes before its closing quote. + for arg in &args { + let mut item = drop_text_for_paths(std::slice::from_ref(arg), shell)?; + if item.starts_with('"') { + let trailing = arg.chars().rev().take_while(|ch| *ch == '\\').count(); + item.insert_str(item.len() - 2, &"\\".repeat(trailing)); + } + quoted.push_str(&item); + } + quoted + } else { + drop_text_for_paths(&args, shell)? + }; + if quoted.len() > 64 * 1024 { + return None; + } + Some(format!("{command} {}", quoted.trim_end())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn literal_arguments_cannot_become_shell_expressions() { + let value = r#"["--config", "name=a b;$(touch nope)&|", "it's"]"#; + assert_eq!( + append("codex resume id".into(), value, PathQuote::Posix).unwrap(), + "codex resume id --config 'name=a b;$(touch nope)&|' 'it'\\''s'" + ); + assert_eq!( + append("codex resume id".into(), value, PathQuote::PowerShell).unwrap(), + "codex resume id --config 'name=a b;$(touch nope)&|' 'it''s'" + ); + assert_eq!( + append("codex resume id".into(), r#"["a b\\"]"#, PathQuote::CommandPrompt) + .unwrap(), + "codex resume id \"a b\\\\\"" + ); + for value in [r#"["%PATH%"]"#, r#"["!VAR!"]"#, r#"["a\"b"]"#] { + assert!(append("codex resume id".into(), value, PathQuote::CommandPrompt).is_none()); + } + for value in ["--yolo", r#"[1]"#, r#"[""]"#, r#"["\n"]"#] { + assert!(parse(value).is_none()); + } + } +} diff --git a/nebula_app/src/gpui_shell/config.rs b/nebula_app/src/gpui_shell/config.rs index 7d9fa9888..2c2c691b3 100644 --- a/nebula_app/src/gpui_shell/config.rs +++ b/nebula_app/src/gpui_shell/config.rs @@ -86,6 +86,7 @@ pub struct Settings { pub dim_inactive_panes: bool, /// Cached in-app toast preference, independent of native system notifications. pub ai_toasts: bool, + pub(crate) agent_resume_args: nebula_settings::AgentResumeArgs, /// Cached display lifetime; toast delivery and native notifications are independent. pub notification_duration: nebula_settings::NotificationDuration, /// 标签关闭按钮与标签插入动画都在渲染热路径读取,必须随全局设置驻留内存。 @@ -301,6 +302,7 @@ impl Settings { .unwrap_or(raw.mouse.focus_follows_mouse), dim_inactive_panes: runtime.dim_inactive_panes, ai_toasts: runtime.ai_toasts, + agent_resume_args: runtime.agent_resume_args, notification_duration: runtime.notification_duration, tab_close_visible: runtime.tab_close_visible, tab_reveal: runtime.tab_reveal, diff --git a/nebula_app/src/gpui_shell/settings_pane.rs b/nebula_app/src/gpui_shell/settings_pane.rs index fbb910dab..ea1379f91 100644 --- a/nebula_app/src/gpui_shell/settings_pane.rs +++ b/nebula_app/src/gpui_shell/settings_pane.rs @@ -37,6 +37,7 @@ use crate::gpui_shell::widgets::{NebulaButton, settings_control_height}; mod about; mod agents; +mod agent_resume; mod app_icon; mod appearance; mod appearance_advanced; diff --git a/nebula_app/src/gpui_shell/settings_pane/agent_resume.rs b/nebula_app/src/gpui_shell/settings_pane/agent_resume.rs new file mode 100644 index 000000000..dbe2f472a --- /dev/null +++ b/nebula_app/src/gpui_shell/settings_pane/agent_resume.rs @@ -0,0 +1,72 @@ +use super::*; +use crate::i18n::Message; +use nebula_settings::AGENT_RESUME_SETTINGS; + +impl SettingsPane { + pub(super) fn save_agent_resume_args(&mut self, index: usize, cx: &mut Context) { + let value = self.agents.resume_inputs[index].read(cx).value().to_string(); + let language = crate::gpui_shell::config::ui_language(cx); + let result = match crate::agent_resume::parse(&value) { + Some(args) => { + let value = if args.is_empty() { + String::new() + } else { + serde_json::to_string(&args).expect("string arguments serialize") + }; + self.try_persist(&[(AGENT_RESUME_SETTINGS[index].1, value)], cx) + .map_err(|error| { + language.format( + Message::SettingsAgentsResumeFailed, + &[("error", &error.to_string())], + ) + }) + }, + None => Err(language.text(Message::SettingsAgentsResumeInvalid).to_owned()), + }; + self.agents.resume_feedback = Some((index, result)); + cx.notify(); + } + + pub(super) fn agent_resume_settings(&self, cx: &mut Context) -> gpui::Div { + let language = crate::gpui_shell::config::ui_language(cx); + let muted = cx.theme().muted_foreground; + let mut content = v_flex() + .w_full() + .gap_3() + .child(div().text_sm().font_weight(gpui::FontWeight::MEDIUM) + .child(language.text(Message::SettingsAgentsResumeTitle))) + .child(div().text_sm().text_color(muted) + .child(language.text(Message::SettingsAgentsResumeDescription))); + for (index, (source, _)) in AGENT_RESUME_SETTINGS.iter().enumerate() { + let agent = crate::ai_agents::AgentKind::parse(source).expect("registered resume source"); + let feedback = self.agents.resume_feedback.as_ref() + .filter(|(row, _)| *row == index) + .map(|(_, result)| match result { + Ok(()) => language.text(Message::CommonSaved).to_owned(), + Err(error) => error.clone(), + }); + content = content.child( + v_flex() + .w_full() + .gap_1() + .child(div().text_sm().child(agent.display_name())) + .child(h_flex().w_full().gap_2() + .child(div().debug_selector(move || format!("agent-resume-input-{index}")) + .flex_1().min_w_0() + .child(Input::new(&self.agents.resume_inputs[index]) + .aria_label(format!("{} {}", agent.display_name(), + language.text(Message::SettingsAgentsResumeTitle))))) + .child(Button::new(("agent-resume-save", index)) + .debug_selector(move || format!("agent-resume-save-{index}")) + .label(language.text(Message::CommonSave)) + .on_click(cx.listener(move |this, _, _, cx| { + this.save_agent_resume_args(index, cx); + })))) + .when_some(feedback, |view, text| { + view.child(div().text_xs().text_color(muted).child(text)) + }), + ); + } + content + } +} diff --git a/nebula_app/src/gpui_shell/settings_pane/agent_resume_tests.rs b/nebula_app/src/gpui_shell/settings_pane/agent_resume_tests.rs new file mode 100644 index 000000000..e16c10ff4 --- /dev/null +++ b/nebula_app/src/gpui_shell/settings_pane/agent_resume_tests.rs @@ -0,0 +1,66 @@ +use super::*; +use crate::gpui_shell::settings_fixture::{SettingsBytesGuard, lock_theme_studio}; + +fn draw(cx: &mut VisualTestContext) { + cx.run_until_parked(); + cx.update(|window, cx| { + window.draw(cx).clear(cx); + }); +} + +fn click(selector: &str, cx: &mut VisualTestContext) { + let bounds = cx.debug_bounds(selector).expect("visible control"); + cx.simulate_click(bounds.center(), Modifiers::default()); + draw(cx); +} + +fn edit_input(selector: &str, value: &str, cx: &mut VisualTestContext) { + click(selector, cx); + cx.simulate_keystrokes(if cfg!(target_os = "macos") { "cmd-a" } else { "ctrl-a" }); + cx.simulate_input(value); + draw(cx); +} + +#[gpui::test] +fn resume_arguments_save_reopen_reject_invalid_and_clear_through_real_controls( + cx: &mut TestAppContext, +) { + let _fixture_guard = lock_theme_studio(); + let _settings_guard = SettingsBytesGuard::capture(); + std::fs::create_dir_all(nebula_settings::settings_dir()).unwrap(); + std::fs::write(nebula_settings::settings_path(), "theme=Nord\nlanguage=en-US\n").unwrap(); + let (pane, mut window, reply, _) = fixture(cx); + drop(reply); + draw(&mut window); + let value = r#"["--yolo", "--config", "model=example"]"#; + edit_input("agent-resume-input-1", value, &mut window); + assert_eq!(RuntimeSettings::load().agent_resume_args.get("codex"), ""); + click("agent-resume-save-1", &mut window); + let persisted = r#"["--yolo","--config","model=example"]"#; + assert_eq!(RuntimeSettings::load().agent_resume_args.get("codex"), persisted); + window.read(|cx| { + assert_eq!(cx.global::() + .agent_resume_args.get("codex"), persisted); + }); + pane.read_with(&mut window, |pane, _| { + assert!(matches!(pane.agents.resume_feedback, Some((1, Ok(()))))); + }); + let reopened = window.update(|window, cx| cx.new(|cx| SettingsPane::new(window, cx))); + reopened.read_with(&mut window, |pane, cx| { + assert_eq!(pane.agents.resume_inputs[1].read(cx).value().as_ref(), persisted); + assert_eq!(pane.runtime.agent_resume_args.get("claude"), ""); + }); + edit_input("agent-resume-input-1", "--yolo; echo invalid", &mut window); + click("agent-resume-save-1", &mut window); + assert_eq!(RuntimeSettings::load().agent_resume_args.get("codex"), persisted); + pane.read_with(&mut window, |pane, _| { + assert!(matches!(pane.agents.resume_feedback, Some((1, Err(_))))); + }); + edit_input("agent-resume-input-1", "[]", &mut window); + click("agent-resume-save-1", &mut window); + assert_eq!(RuntimeSettings::load().agent_resume_args.get("codex"), ""); + let input = window.debug_bounds("agent-resume-input-1").unwrap(); + let save = window.debug_bounds("agent-resume-save-1").unwrap(); + assert!(input.right() <= save.left()); + assert!(save.size.height >= px(24.0)); +} diff --git a/nebula_app/src/gpui_shell/settings_pane/agents.rs b/nebula_app/src/gpui_shell/settings_pane/agents.rs index 8f573a794..67a38f23c 100644 --- a/nebula_app/src/gpui_shell/settings_pane/agents.rs +++ b/nebula_app/src/gpui_shell/settings_pane/agents.rs @@ -19,6 +19,8 @@ type TestOperation = std::sync::Arc< pub(super) struct AgentSettingsState { rows: Option>, + pub(super) resume_inputs: Vec>, + pub(super) resume_feedback: Option<(usize, Result<(), String>)>, loading: bool, busy: Option, sequence: u64, @@ -29,8 +31,39 @@ pub(super) struct AgentSettingsState { } impl AgentSettingsState { - pub(super) fn new(cx: &mut Context) -> Self { + pub(super) fn new( + runtime: &RuntimeSettings, + window: &mut Window, + subscriptions: &mut Vec, + cx: &mut Context, + ) -> Self { + let resume_inputs = nebula_settings::AGENT_RESUME_SETTINGS + .iter() + .enumerate() + .map(|(index, (source, _))| { + let input = cx.new(|cx| { + InputState::new(window, cx) + .placeholder(r#"["--flag", "value"]"#) + .default_value(runtime.agent_resume_args.get(source)) + }); + subscriptions.push(cx.subscribe_in( + &input, + window, + move |pane, _, event, _, cx| { + if matches!(event, InputEvent::Change) + && pane.agents.resume_feedback.as_ref().is_some_and(|(row, _)| *row == index) + { + pane.agents.resume_feedback = None; + cx.notify(); + } + }, + )); + input + }) + .collect(); Self { + resume_inputs, + resume_feedback: None, rows: None, loading: false, busy: None, @@ -181,6 +214,7 @@ impl SettingsPane { .text_color(muted) .child(language.text(Message::SettingsAgentsRestart)), ) + .child(self.agent_resume_settings(cx)) } fn agent_hook_row( diff --git a/nebula_app/src/gpui_shell/settings_pane/agents/tests.rs b/nebula_app/src/gpui_shell/settings_pane/agents/tests.rs index 051facc45..a9efd2238 100644 --- a/nebula_app/src/gpui_shell/settings_pane/agents/tests.rs +++ b/nebula_app/src/gpui_shell/settings_pane/agents/tests.rs @@ -225,3 +225,6 @@ fn closing_settings_does_not_cancel_a_submitted_hook_write_or_reopen_the_view( window.run_until_parked(); assert!(weak.upgrade().is_none()); } + +#[path = "../agent_resume_tests.rs"] +mod resume_tests; diff --git a/nebula_app/src/gpui_shell/settings_pane/initialization.rs b/nebula_app/src/gpui_shell/settings_pane/initialization.rs index 2c14c6d18..43393340f 100644 --- a/nebula_app/src/gpui_shell/settings_pane/initialization.rs +++ b/nebula_app/src/gpui_shell/settings_pane/initialization.rs @@ -586,12 +586,13 @@ impl SettingsPane { }); subscriptions.push(cx.intercept_keystrokes(font_size_interceptor)); + let agents = agents::AgentSettingsState::new(&runtime, window, &mut subscriptions, cx); Self { focus_handle: cx.focus_handle(), runtime, launch_at_login: crate::platform::startup::launch_at_login(), active_section: 1, - agents: agents::AgentSettingsState::new(cx), + agents, mobile: mobile::MobileState::new(window, cx), appearance_picker: None, appearance_picker_seq: 0, diff --git a/nebula_app/src/gpui_shell/terminal/view/startup_command.rs b/nebula_app/src/gpui_shell/terminal/view/startup_command.rs index 834dbc3d9..276d169f9 100644 --- a/nebula_app/src/gpui_shell/terminal/view/startup_command.rs +++ b/nebula_app/src/gpui_shell/terminal/view/startup_command.rs @@ -95,13 +95,17 @@ impl TerminalView { } pub(super) fn choose_codex_recovery_session(&mut self, cx: &mut Context) { + let Some(command) = self.configured_recovery_command("codex resume".into(), "codex", cx) + else { + return; + }; // Keep the old target until the user's choice receives a native // acknowledgement. Directory similarity cannot recover a missing ID. self.recovery.choosing_session = true; self.recovery.submitted = false; self.recovery.failed = false; self.last_command_failed = false; - self.run_command("codex resume".into(), cx); + self.run_command(command, cx); cx.emit(TerminalViewEvent::Notification(crate::notify::Notification::Text { body: ui_language().text(crate::i18n::Message::SessionRestoreChooseCodex).to_owned(), program: Some("codex".into()), @@ -178,6 +182,16 @@ impl TerminalView { } } + fn configured_recovery_command( + &self, + command: String, + source: &str, + cx: &App, + ) -> Option { + let value = cx.global::().agent_resume_args.get(source); + crate::agent_resume::append(command, value, self.path_quote()) + } + pub(crate) fn restore_agent( &mut self, mut agent: crate::session::AgentSession, @@ -190,7 +204,10 @@ impl TerminalView { ..SessionRecovery::default() }; if agent.source != "pi" || self.ssh_destination.is_some() { - if let Some(command) = agent.resume_command() { + if let Some(command) = agent + .resume_command() + .and_then(|command| self.configured_recovery_command(command, &agent.source, cx)) + { self.run_command(command, cx); } else { self.recovery.failed = true; @@ -233,6 +250,9 @@ impl TerminalView { ) .map(|quoted| format!("pi --session {}", quoted.trim_end())) }); + let command = command.and_then(|command| { + view.configured_recovery_command(command, &target.source, cx) + }); view.recovery.target = Some(target); if let Some(command) = command { view.run_command(command, cx); diff --git a/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs b/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs index 05a157893..6807ebffb 100644 --- a/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs +++ b/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs @@ -1231,3 +1231,83 @@ fn a_failed_codex_chooser_does_not_start_an_automatic_retry_loop(cx: &mut TestAp assert!(receiver.try_iter().all(|message| !matches!(message, Msg::Input(_)))); }); } + +#[gpui::test] +fn configured_cold_resume_preserves_saved_identity_cwd_and_retries(cx: &mut TestAppContext) { + let cwd = tempfile::tempdir().unwrap(); + let (view, window, receiver) = open_at(cx, Some(cwd.path().to_owned())); + let text = nebula_settings::apply_updates( + "resume_ai=1\n", + &[("agent_resume_args_codex", r#"["--yolo", "--config", "model=a b;$(echo nope)"]"#.into())], + ); + window.update(|_, cx| { + let runtime = nebula_settings::RuntimeSettings::from_raw( + &nebula_settings::RawSettings::from_text(&text), + ); + cx.set_global(Settings::load_with_runtime(nebula_settings::ThemeName::Nord, runtime)); + }); + view.update(window, |view, cx| { + let thread = "0199a213-c2a4-7cf5-8f6b-d746fbb6e86c"; + let saved = crate::session::AgentSession { + source: "codex".into(), + session_id: Some("obsolete-hook-group".into()), + session_file: Some(format!("/sessions/rollout-date-{thread}.jsonl")), + }; + let before_cwd = view.cwd.clone(); + view.restore_agent(saved, cx); + assert!(view.pending_shell_command.is_some()); + assert!(!receiver.try_iter().any(|message| matches!(message, Msg::Input(_)))); + let target = view.session_agent().unwrap(); + assert_eq!(target.session_id.as_deref(), Some(thread)); + let expected = format!("codex resume {thread} --yolo --config 'model=a b;$(echo nope)'"); + assert_eq!(view.cwd, before_cwd); + feed(view, b"\x1b]133;A\x07user@host:~$ "); + view.flush_pending_shell_command(cx); + assert!(receiver.try_iter().any(|message| { + matches!(message, Msg::Input(bytes) if bytes.as_ref() == expected.as_bytes()) + })); + assert!(view.recovery_pending()); + view.running_program = None; + view.recovery.command_ended(); + view.retry_recovery(cx); + assert!(receiver.try_iter().any(|message| { + matches!(message, Msg::Input(bytes) if bytes.as_ref() == expected.as_bytes()) + })); + assert_eq!(view.session_agent(), Some(target)); + assert_eq!(view.cwd, before_cwd); + view.running_program = None; + view.recovery.command_ended(); + view.choose_recovery_session(cx); + let chooser = "codex resume --yolo --config 'model=a b;$(echo nope)'"; + assert!(receiver.try_iter().any(|message| { + matches!(message, Msg::Input(bytes) if bytes.as_ref() == chooser.as_bytes()) + })); + }); +} + +#[gpui::test] +fn invalid_resume_arguments_fail_without_submitting_a_default_or_shell_expression( + cx: &mut TestAppContext, +) { + let (view, window, receiver) = open(cx); + window.update(|_, cx| { + let raw = nebula_settings::RawSettings::from_text("agent_resume_args_codex=--yolo; echo bad\n"); + cx.set_global(Settings::load_with_runtime( + nebula_settings::ThemeName::Nord, + nebula_settings::RuntimeSettings::from_raw(&raw), + )); + }); + view.update(window, |view, cx| { + let saved = crate::session::AgentSession { + source: "codex".into(), + session_id: Some("saved-conversation".into()), + session_file: None, + }; + feed(view, b"\x1b]133;A\x07user@host:~$ "); + view.restore_agent(saved.clone(), cx); + assert!(view.can_retry_recovery()); + assert!(view.pending_shell_command.is_none()); + assert!(!receiver.try_iter().any(|message| matches!(message, Msg::Input(_)))); + assert_eq!(view.session_agent(), Some(saved)); + }); +} diff --git a/nebula_app/src/main.rs b/nebula_app/src/main.rs index c5da100f4..400ed8121 100644 --- a/nebula_app/src/main.rs +++ b/nebula_app/src/main.rs @@ -37,6 +37,7 @@ use nebula_terminal::tty; mod agent_env; mod ai_agents; +mod agent_resume; mod ai_assistant; mod ai_hook; mod ai_providers; diff --git a/nebula_settings/src/agent_resume.rs b/nebula_settings/src/agent_resume.rs new file mode 100644 index 000000000..3dacd7208 --- /dev/null +++ b/nebula_settings/src/agent_resume.rs @@ -0,0 +1,57 @@ +//! Explicit cold-resume arguments; never inferred from command history. + +use crate::RawSettings; + +pub const AGENT_RESUME_SETTINGS: [(&str, &str); 11] = [ + ("claude", "agent_resume_args_claude"), + ("codex", "agent_resume_args_codex"), + ("gemini", "agent_resume_args_gemini"), + ("opencode", "agent_resume_args_opencode"), + ("amp", "agent_resume_args_amp"), + ("cursor", "agent_resume_args_cursor"), + ("copilot", "agent_resume_args_copilot"), + ("grok", "agent_resume_args_grok"), + ("pi", "agent_resume_args_pi"), + ("omp", "agent_resume_args_omp"), + ("kimi", "agent_resume_args_kimi"), +]; + +#[derive(Clone, Debug, Default)] +pub struct AgentResumeArgs(std::collections::HashMap); + +impl AgentResumeArgs { + pub(crate) fn from_raw(raw: &RawSettings) -> Self { + Self( + AGENT_RESUME_SETTINGS + .iter() + .filter_map(|(source, key)| { + raw.value(key).map(|value| ((*source).to_owned(), value.to_owned())) + }) + .collect(), + ) + } + + pub fn get(&self, source: &str) -> &str { + self.0.get(source).map(String::as_str).unwrap_or("") + } +} + +#[cfg(test)] +mod tests { + use crate::{RawSettings, RuntimeSettings, apply_updates}; + + #[test] + fn explicit_resume_arguments_round_trip_without_affecting_other_agents() { + let original = "resume_ai=1\ncustom=keep\n"; + let value = r#"["--yolo", "--config", "model=example"]"#; + let text = apply_updates(original, &[("agent_resume_args_codex", value.into())]); + let runtime = RuntimeSettings::from_raw(&RawSettings::from_text(&text)); + assert_eq!(runtime.agent_resume_args.get("codex"), value); + assert_eq!(runtime.agent_resume_args.get("claude"), ""); + assert!(text.starts_with(original)); + let cleared = apply_updates(&text, &[("agent_resume_args_codex", String::new())]); + let defaults = RuntimeSettings::from_raw(&RawSettings::from_text(&cleared)); + assert_eq!(defaults.agent_resume_args.get("codex"), ""); + assert_eq!(RuntimeSettings::from_raw(&RawSettings::default()).agent_resume_args.get("codex"), ""); + } +} diff --git a/nebula_settings/src/lib.rs b/nebula_settings/src/lib.rs index 96a940976..005f65070 100644 --- a/nebula_settings/src/lib.rs +++ b/nebula_settings/src/lib.rs @@ -15,6 +15,8 @@ use std::collections::HashMap; +mod agent_resume; +pub use agent_resume::{AGENT_RESUME_SETTINGS, AgentResumeArgs}; mod agent_hooks; pub use agent_hooks::AgentHook; mod app_icon; @@ -1056,6 +1058,8 @@ pub struct RuntimeSettings { pub silent_start: bool, pub restore_session: bool, pub resume_ai: bool, + /// JSON argument arrays interpreted only by the application shell adapter. + pub agent_resume_args: AgentResumeArgs, /// 常驻系统托盘图标。 pub tray: bool, pub blur: BlurModeName, @@ -1239,6 +1243,7 @@ impl RuntimeSettings { silent_start: raw.bool_on("silent_start").unwrap_or(false), restore_session: raw.bool_on("restore_session").unwrap_or(true), resume_ai: raw.bool_on("resume_ai").unwrap_or(true), + agent_resume_args: AgentResumeArgs::from_raw(raw), tray: raw.bool_on("tray").unwrap_or(true), blur, opacity, diff --git a/nebula_settings/src/reset.rs b/nebula_settings/src/reset.rs index cdf499e56..75c029e15 100644 --- a/nebula_settings/src/reset.rs +++ b/nebula_settings/src/reset.rs @@ -91,6 +91,9 @@ fn default_settings_text(text: &str) -> String { .filter(|line| { !line.split_once('=').is_some_and(|(key, _)| { RESET_KEYS.iter().any(|known| key.trim().eq_ignore_ascii_case(known)) + || crate::AGENT_RESUME_SETTINGS + .iter() + .any(|(_, known)| key.trim().eq_ignore_ascii_case(known)) }) }) .collect() @@ -132,6 +135,15 @@ mod tests { use super::*; use crate::{RawSettings, RuntimeSettings}; + #[test] + fn reset_removes_resume_arguments_for_every_supported_agent() { + let text: String = crate::AGENT_RESUME_SETTINGS + .iter() + .map(|(_, key)| format!("{key}=[\"--custom\"]\n")) + .collect(); + assert_eq!(default_settings_text(&text), ""); + } + #[test] fn reset_preserves_explicit_hook_authorization_and_opt_out() { let text = "ai_hooks=0\nai_hooks_claude=0\nai_hooks_codex=1\nai_hooks_grok=1\n"; From 95df940fcb3b67299eda7a379aec48376ce692b3 Mon Sep 17 00:00:00 2001 From: GeekMr <140129782+WilliamWang1721@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:33:56 +0800 Subject: [PATCH 02/15] style: apply GitHub Actions rustfmt output --- nebula_app/src/agent_resume.rs | 7 +- nebula_app/src/gpui_shell/settings_pane.rs | 2 +- .../gpui_shell/settings_pane/agent_resume.rs | 85 ++++++++++++------- .../settings_pane/agent_resume_tests.rs | 6 +- .../src/gpui_shell/settings_pane/agents.rs | 6 +- .../gpui_shell/terminal/view/startup_tests.rs | 8 +- nebula_app/src/main.rs | 2 +- nebula_settings/src/agent_resume.rs | 5 +- 8 files changed, 79 insertions(+), 42 deletions(-) diff --git a/nebula_app/src/agent_resume.rs b/nebula_app/src/agent_resume.rs index 09483e8c1..7c5613d44 100644 --- a/nebula_app/src/agent_resume.rs +++ b/nebula_app/src/agent_resume.rs @@ -21,8 +21,8 @@ pub(crate) fn append(command: String, value: &str, shell: PathQuote) -> Option Err(language.text(Message::SettingsAgentsResumeInvalid).to_owned()), }; @@ -33,35 +32,61 @@ impl SettingsPane { let mut content = v_flex() .w_full() .gap_3() - .child(div().text_sm().font_weight(gpui::FontWeight::MEDIUM) - .child(language.text(Message::SettingsAgentsResumeTitle))) - .child(div().text_sm().text_color(muted) - .child(language.text(Message::SettingsAgentsResumeDescription))); + .child( + div() + .text_sm() + .font_weight(gpui::FontWeight::MEDIUM) + .child(language.text(Message::SettingsAgentsResumeTitle)), + ) + .child( + div() + .text_sm() + .text_color(muted) + .child(language.text(Message::SettingsAgentsResumeDescription)), + ); for (index, (source, _)) in AGENT_RESUME_SETTINGS.iter().enumerate() { - let agent = crate::ai_agents::AgentKind::parse(source).expect("registered resume source"); - let feedback = self.agents.resume_feedback.as_ref() - .filter(|(row, _)| *row == index) - .map(|(_, result)| match result { - Ok(()) => language.text(Message::CommonSaved).to_owned(), - Err(error) => error.clone(), - }); + let agent = + crate::ai_agents::AgentKind::parse(source).expect("registered resume source"); + let feedback = + self.agents.resume_feedback.as_ref().filter(|(row, _)| *row == index).map( + |(_, result)| match result { + Ok(()) => language.text(Message::CommonSaved).to_owned(), + Err(error) => error.clone(), + }, + ); content = content.child( v_flex() .w_full() .gap_1() .child(div().text_sm().child(agent.display_name())) - .child(h_flex().w_full().gap_2() - .child(div().debug_selector(move || format!("agent-resume-input-{index}")) - .flex_1().min_w_0() - .child(Input::new(&self.agents.resume_inputs[index]) - .aria_label(format!("{} {}", agent.display_name(), - language.text(Message::SettingsAgentsResumeTitle))))) - .child(Button::new(("agent-resume-save", index)) - .debug_selector(move || format!("agent-resume-save-{index}")) - .label(language.text(Message::CommonSave)) - .on_click(cx.listener(move |this, _, _, cx| { - this.save_agent_resume_args(index, cx); - })))) + .child( + h_flex() + .w_full() + .gap_2() + .child( + div() + .debug_selector(move || format!("agent-resume-input-{index}")) + .flex_1() + .min_w_0() + .child( + Input::new(&self.agents.resume_inputs[index]).aria_label( + format!( + "{} {}", + agent.display_name(), + language.text(Message::SettingsAgentsResumeTitle) + ), + ), + ), + ) + .child( + Button::new(("agent-resume-save", index)) + .debug_selector(move || format!("agent-resume-save-{index}")) + .label(language.text(Message::CommonSave)) + .on_click(cx.listener(move |this, _, _, cx| { + this.save_agent_resume_args(index, cx); + })), + ), + ) .when_some(feedback, |view, text| { view.child(div().text_xs().text_color(muted).child(text)) }), diff --git a/nebula_app/src/gpui_shell/settings_pane/agent_resume_tests.rs b/nebula_app/src/gpui_shell/settings_pane/agent_resume_tests.rs index e16c10ff4..df6d6b810 100644 --- a/nebula_app/src/gpui_shell/settings_pane/agent_resume_tests.rs +++ b/nebula_app/src/gpui_shell/settings_pane/agent_resume_tests.rs @@ -39,8 +39,10 @@ fn resume_arguments_save_reopen_reject_invalid_and_clear_through_real_controls( let persisted = r#"["--yolo","--config","model=example"]"#; assert_eq!(RuntimeSettings::load().agent_resume_args.get("codex"), persisted); window.read(|cx| { - assert_eq!(cx.global::() - .agent_resume_args.get("codex"), persisted); + assert_eq!( + cx.global::().agent_resume_args.get("codex"), + persisted + ); }); pane.read_with(&mut window, |pane, _| { assert!(matches!(pane.agents.resume_feedback, Some((1, Ok(()))))); diff --git a/nebula_app/src/gpui_shell/settings_pane/agents.rs b/nebula_app/src/gpui_shell/settings_pane/agents.rs index 67a38f23c..127a8feed 100644 --- a/nebula_app/src/gpui_shell/settings_pane/agents.rs +++ b/nebula_app/src/gpui_shell/settings_pane/agents.rs @@ -51,7 +51,11 @@ impl AgentSettingsState { window, move |pane, _, event, _, cx| { if matches!(event, InputEvent::Change) - && pane.agents.resume_feedback.as_ref().is_some_and(|(row, _)| *row == index) + && pane + .agents + .resume_feedback + .as_ref() + .is_some_and(|(row, _)| *row == index) { pane.agents.resume_feedback = None; cx.notify(); diff --git a/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs b/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs index 6807ebffb..c66659047 100644 --- a/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs +++ b/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs @@ -1238,7 +1238,10 @@ fn configured_cold_resume_preserves_saved_identity_cwd_and_retries(cx: &mut Test let (view, window, receiver) = open_at(cx, Some(cwd.path().to_owned())); let text = nebula_settings::apply_updates( "resume_ai=1\n", - &[("agent_resume_args_codex", r#"["--yolo", "--config", "model=a b;$(echo nope)"]"#.into())], + &[( + "agent_resume_args_codex", + r#"["--yolo", "--config", "model=a b;$(echo nope)"]"#.into(), + )], ); window.update(|_, cx| { let runtime = nebula_settings::RuntimeSettings::from_raw( @@ -1291,7 +1294,8 @@ fn invalid_resume_arguments_fail_without_submitting_a_default_or_shell_expressio ) { let (view, window, receiver) = open(cx); window.update(|_, cx| { - let raw = nebula_settings::RawSettings::from_text("agent_resume_args_codex=--yolo; echo bad\n"); + let raw = + nebula_settings::RawSettings::from_text("agent_resume_args_codex=--yolo; echo bad\n"); cx.set_global(Settings::load_with_runtime( nebula_settings::ThemeName::Nord, nebula_settings::RuntimeSettings::from_raw(&raw), diff --git a/nebula_app/src/main.rs b/nebula_app/src/main.rs index 400ed8121..c4e819b24 100644 --- a/nebula_app/src/main.rs +++ b/nebula_app/src/main.rs @@ -36,8 +36,8 @@ use winit::raw_window_handle::{HasDisplayHandle, RawDisplayHandle}; use nebula_terminal::tty; mod agent_env; -mod ai_agents; mod agent_resume; +mod ai_agents; mod ai_assistant; mod ai_hook; mod ai_providers; diff --git a/nebula_settings/src/agent_resume.rs b/nebula_settings/src/agent_resume.rs index 3dacd7208..89eb6a67a 100644 --- a/nebula_settings/src/agent_resume.rs +++ b/nebula_settings/src/agent_resume.rs @@ -52,6 +52,9 @@ mod tests { let cleared = apply_updates(&text, &[("agent_resume_args_codex", String::new())]); let defaults = RuntimeSettings::from_raw(&RawSettings::from_text(&cleared)); assert_eq!(defaults.agent_resume_args.get("codex"), ""); - assert_eq!(RuntimeSettings::from_raw(&RawSettings::default()).agent_resume_args.get("codex"), ""); + assert_eq!( + RuntimeSettings::from_raw(&RawSettings::default()).agent_resume_args.get("codex"), + "" + ); } } From d06417806a794681a0b8e6f48e0564a67a11d1e7 Mon Sep 17 00:00:00 2001 From: GeekMr <140129782+WilliamWang1721@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:38:52 +0800 Subject: [PATCH 03/15] test(ci): register resume settings fixture isolation --- scripts/tests/test_ci_native_tests.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/tests/test_ci_native_tests.py b/scripts/tests/test_ci_native_tests.py index 2c9573014..3c3cb30f1 100644 --- a/scripts/tests/test_ci_native_tests.py +++ b/scripts/tests/test_ci_native_tests.py @@ -191,7 +191,8 @@ def test_nextest_reserves_only_shared_settings_and_the_heavy_git_fixture(self): " or test(long_segments_use_a_real_dropdown_without_losing_preference_updates)" " or test(font_size_click_input_commits_cancels_and_bounds_values)" " or test(cjk_dropdown_selection_preserves_the_english_font_chain)" - " or test(review_regression_font_fields_align_and_dropdown_toggles_with_search)", + " or test(review_regression_font_fields_align_and_dropdown_toggles_with_search)" + " or test(resume_arguments_save_reopen_reject_invalid_and_clear_through_real_controls)", "test-group": "theme-studio", }, { "filter": "test(=gpui_shell::terminal::view::startup_tests::" From 825f980c234e3ab54774c9eab5dc5892023fc575 Mon Sep 17 00:00:00 2001 From: GeekMr <140129782+WilliamWang1721@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:43:45 +0800 Subject: [PATCH 04/15] fix(test): use static selectors for rendered resume controls --- nebula_app/src/gpui_shell/settings_pane/agent_resume_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nebula_app/src/gpui_shell/settings_pane/agent_resume_tests.rs b/nebula_app/src/gpui_shell/settings_pane/agent_resume_tests.rs index df6d6b810..ce77971c6 100644 --- a/nebula_app/src/gpui_shell/settings_pane/agent_resume_tests.rs +++ b/nebula_app/src/gpui_shell/settings_pane/agent_resume_tests.rs @@ -8,13 +8,13 @@ fn draw(cx: &mut VisualTestContext) { }); } -fn click(selector: &str, cx: &mut VisualTestContext) { +fn click(selector: &'static str, cx: &mut VisualTestContext) { let bounds = cx.debug_bounds(selector).expect("visible control"); cx.simulate_click(bounds.center(), Modifiers::default()); draw(cx); } -fn edit_input(selector: &str, value: &str, cx: &mut VisualTestContext) { +fn edit_input(selector: &'static str, value: &str, cx: &mut VisualTestContext) { click(selector, cx); cx.simulate_keystrokes(if cfg!(target_os = "macos") { "cmd-a" } else { "ctrl-a" }); cx.simulate_input(value); From eed61f0f6d5a0b4cb10fa3254c7d53e2c7d83b10 Mon Sep 17 00:00:00 2001 From: GeekMr <140129782+WilliamWang1721@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:57:19 +0800 Subject: [PATCH 05/15] fix(agents): preserve legacy PowerShell native resume arguments --- .../2026-10-03-explicit-resume-arguments.md | 13 +++- nebula_app/src/agent_resume.rs | 73 +++++++++++++++++-- .../terminal/view/startup_command.rs | 10 ++- .../gpui_shell/terminal/view/startup_tests.rs | 7 ++ nebula_app/src/platform/elevation.rs | 2 +- 5 files changed, 96 insertions(+), 9 deletions(-) diff --git a/architecture/notes/nebula_settings/agent_resume/2026-10-03-explicit-resume-arguments.md b/architecture/notes/nebula_settings/agent_resume/2026-10-03-explicit-resume-arguments.md index c5b6a9678..77726da68 100644 --- a/architecture/notes/nebula_settings/agent_resume/2026-10-03-explicit-resume-arguments.md +++ b/architecture/notes/nebula_settings/agent_resume/2026-10-03-explicit-resume-arguments.md @@ -25,6 +25,10 @@ preserves the serialized value; the application uses its existing JSON dependenc and target-shell quoting helper. Arrays are limited to 32 arguments and 64 KiB quoted text; control characters are rejected. CMD rejects double quotes, `%` and `!`, and quoted trailing backslashes are doubled for the native argv parser. +Windows PowerShell 5's legacy native argv binder additionally receives arguments +encoded through the existing Windows native argument encoder in `platform/elevation`. +PowerShell 7 uses the ordinary literal adapter. The pane's frozen native shell +program selects this distinction; guest/SSH arguments retain the guest adapter. The GPUI Agent page edits drafts and validates them on Save, reports persistence success/failure in place, and resets them with other preferences. Saving updates the @@ -53,8 +57,13 @@ can contain machine-specific values; this change does not broaden sync policy. Authored settings round-trip/reset tests, literal shell-quoting tests, rendered Save/reopen/invalid/clear coverage and real cold recovery/PTY submission/retry tests. All formatting, architecture, compile and native tests must run in GitHub Actions; -local inspection is not execution evidence. Native screenshot and real CLI -acceptance are separate from these regression tests. +local inspection is not execution evidence. A native Windows test compiles a +small stdlib argv receiver, then runs the production adapter's generated command +through Windows PowerShell and PowerShell 7 and compares the complete argv array. +The [fork native argv experiment](https://github.com/WilliamWang1721/pebrel/actions/runs/37110686203) +confirmed that ordinary single quotes alone lose embedded quotes and argument +boundaries in Windows PowerShell 5. Native screenshot and real provider CLI +acceptance remain separate from the regression tests. ## Supersedes None. diff --git a/nebula_app/src/agent_resume.rs b/nebula_app/src/agent_resume.rs index 7c5613d44..e8f386f8d 100644 --- a/nebula_app/src/agent_resume.rs +++ b/nebula_app/src/agent_resume.rs @@ -14,11 +14,30 @@ pub(crate) fn parse(value: &str) -> Option> { Some(args) } -pub(crate) fn append(command: String, value: &str, shell: PathQuote) -> Option { +pub(crate) fn append( + command: String, + value: &str, + shell: PathQuote, + legacy_powershell: bool, +) -> Option { let args = parse(value)?; if args.is_empty() { return Some(command); } + #[cfg(windows)] + let args = if legacy_powershell { + args.iter() + .map(|arg| { + let quoted = crate::platform::elevation::quoted_argument(std::ffi::OsStr::new(arg)) + .ok()?; + String::from_utf16("ed).ok() + }) + .collect::>>()? + } else { + args + }; + #[cfg(not(windows))] + let _ = legacy_powershell; let quoted = if matches!(shell, PathQuote::CommandPrompt) { let mut quoted = String::new(); // CMD passes quotes to the CLI's argv parser. A quoted argument ending in @@ -49,22 +68,66 @@ mod tests { fn literal_arguments_cannot_become_shell_expressions() { let value = r#"["--config", "name=a b;$(touch nope)&|", "it's"]"#; assert_eq!( - append("codex resume id".into(), value, PathQuote::Posix).unwrap(), + append("codex resume id".into(), value, PathQuote::Posix, false).unwrap(), "codex resume id --config 'name=a b;$(touch nope)&|' 'it'\\''s'" ); assert_eq!( - append("codex resume id".into(), value, PathQuote::PowerShell).unwrap(), + append("codex resume id".into(), value, PathQuote::PowerShell, false).unwrap(), "codex resume id --config 'name=a b;$(touch nope)&|' 'it''s'" ); assert_eq!( - append("codex resume id".into(), r#"["a b\\"]"#, PathQuote::CommandPrompt).unwrap(), + append("codex resume id".into(), r#"["a b\\"]"#, PathQuote::CommandPrompt, false).unwrap(), "codex resume id \"a b\\\\\"" ); for value in [r#"["%PATH%"]"#, r#"["!VAR!"]"#, r#"["a\"b"]"#] { - assert!(append("codex resume id".into(), value, PathQuote::CommandPrompt).is_none()); + assert!(append("codex resume id".into(), value, PathQuote::CommandPrompt, false).is_none()); } for value in ["--yolo", r#"[1]"#, r#"[""]"#, r#"["\n"]"#] { assert!(parse(value).is_none()); } } } + +#[cfg(all(test, windows))] +mod native_tests { + use super::*; + + #[test] + fn windows_powershell_and_pwsh_deliver_the_exact_native_argument_array() { + let root = tempfile::tempdir().unwrap(); + let source = root.path().join("argv.rs"); + let executable = root.path().join("argv probe.exe"); + std::fs::write( + &source, + r#"fn main() { print!("{:?}", std::env::args().skip(1).collect::>()); }"#, + ) + .unwrap(); + assert!(std::process::Command::new("rustc") + .arg(&source).arg("-o").arg(&executable).status().unwrap().success()); + let args = [ + "--config", + "model_provider=\"custom\"", + "a\"b", + "a b\\", + "x\\\"y", + "it's & $(Write-Output nope)", + ]; + let value = serde_json::to_string(&args).unwrap(); + let quoted_exe = drop_text_for_paths( + &[executable.to_string_lossy().into_owned()], PathQuote::PowerShell, + ).unwrap(); + for (shell, legacy) in [("powershell.exe", true), ("pwsh.exe", false)] { + let line = append(format!("& {}", quoted_exe.trim_end()), &value, + PathQuote::PowerShell, legacy).unwrap(); + let mut command = std::process::Command::new(shell); + command.args(["-NoProfile", "-NonInteractive", "-Command", &line]); + let output = crate::platform::process_output::read_cancellable( + command, + std::time::Duration::from_secs(15), + 8192, + &|| false, + ).unwrap(); + assert_eq!(String::from_utf8(output).unwrap(), format!("{args:?}"), "{shell}: {line}"); + } + } +} diff --git a/nebula_app/src/gpui_shell/terminal/view/startup_command.rs b/nebula_app/src/gpui_shell/terminal/view/startup_command.rs index 276d169f9..f3698ae70 100644 --- a/nebula_app/src/gpui_shell/terminal/view/startup_command.rs +++ b/nebula_app/src/gpui_shell/terminal/view/startup_command.rs @@ -189,7 +189,15 @@ impl TerminalView { cx: &App, ) -> Option { let value = cx.global::().agent_resume_args.get(source); - crate::agent_resume::append(command, value, self.path_quote()) + let legacy_powershell = cfg!(windows) + && self.exec_context.as_ref().and_then(|context| context.shell_program()).is_some_and( + |program| { + let name = program.rsplit(['/', '\\']).next().unwrap_or(program); + name.eq_ignore_ascii_case("powershell") + || name.eq_ignore_ascii_case("powershell.exe") + }, + ); + crate::agent_resume::append(command, value, self.path_quote(), legacy_powershell) } pub(crate) fn restore_agent( diff --git a/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs b/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs index c66659047..2c85f2eba 100644 --- a/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs +++ b/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs @@ -1256,7 +1256,14 @@ fn configured_cold_resume_preserves_saved_identity_cwd_and_retries(cx: &mut Test session_id: Some("obsolete-hook-group".into()), session_file: Some(format!("/sessions/rollout-date-{thread}.jsonl")), }; + view.exec_context = Some(crate::runtime_exec::PaneExecContext::from_pty_options( + &nebula_terminal::tty::Options { + shell: Some(nebula_terminal::tty::Shell::new("wsl.exe".into(), vec![])), + ..Default::default() + }, + )); let before_cwd = view.cwd.clone(); + assert_eq!(before_cwd, cwd.path().to_string_lossy().into_owned()); view.restore_agent(saved, cx); assert!(view.pending_shell_command.is_some()); assert!(!receiver.try_iter().any(|message| matches!(message, Msg::Input(_)))); diff --git a/nebula_app/src/platform/elevation.rs b/nebula_app/src/platform/elevation.rs index 004f1ef2d..b46e8aa52 100644 --- a/nebula_app/src/platform/elevation.rs +++ b/nebula_app/src/platform/elevation.rs @@ -72,7 +72,7 @@ pub(crate) fn is_elevated() -> io::Result { } #[cfg(windows)] -fn quoted_argument(argument: &OsStr) -> io::Result> { +pub(crate) fn quoted_argument(argument: &OsStr) -> io::Result> { use std::os::windows::ffi::OsStrExt; let mut result = vec![b'"' as u16]; let mut backslashes = 0; From c0cbdf63761828bf5069830513d4603c1ac0c22b Mon Sep 17 00:00:00 2001 From: GeekMr <140129782+WilliamWang1721@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:58:43 +0800 Subject: [PATCH 06/15] style(agents): apply remote formatter to native argv regression --- nebula_app/src/agent_resume.rs | 40 ++++++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/nebula_app/src/agent_resume.rs b/nebula_app/src/agent_resume.rs index e8f386f8d..3617a024c 100644 --- a/nebula_app/src/agent_resume.rs +++ b/nebula_app/src/agent_resume.rs @@ -28,8 +28,8 @@ pub(crate) fn append( let args = if legacy_powershell { args.iter() .map(|arg| { - let quoted = crate::platform::elevation::quoted_argument(std::ffi::OsStr::new(arg)) - .ok()?; + let quoted = + crate::platform::elevation::quoted_argument(std::ffi::OsStr::new(arg)).ok()?; String::from_utf16("ed).ok() }) .collect::>>()? @@ -76,11 +76,14 @@ mod tests { "codex resume id --config 'name=a b;$(touch nope)&|' 'it''s'" ); assert_eq!( - append("codex resume id".into(), r#"["a b\\"]"#, PathQuote::CommandPrompt, false).unwrap(), + append("codex resume id".into(), r#"["a b\\"]"#, PathQuote::CommandPrompt, false) + .unwrap(), "codex resume id \"a b\\\\\"" ); for value in [r#"["%PATH%"]"#, r#"["!VAR!"]"#, r#"["a\"b"]"#] { - assert!(append("codex resume id".into(), value, PathQuote::CommandPrompt, false).is_none()); + assert!( + append("codex resume id".into(), value, PathQuote::CommandPrompt, false).is_none() + ); } for value in ["--yolo", r#"[1]"#, r#"[""]"#, r#"["\n"]"#] { assert!(parse(value).is_none()); @@ -102,8 +105,15 @@ mod native_tests { r#"fn main() { print!("{:?}", std::env::args().skip(1).collect::>()); }"#, ) .unwrap(); - assert!(std::process::Command::new("rustc") - .arg(&source).arg("-o").arg(&executable).status().unwrap().success()); + assert!( + std::process::Command::new("rustc") + .arg(&source) + .arg("-o") + .arg(&executable) + .status() + .unwrap() + .success() + ); let args = [ "--config", "model_provider=\"custom\"", @@ -114,11 +124,18 @@ mod native_tests { ]; let value = serde_json::to_string(&args).unwrap(); let quoted_exe = drop_text_for_paths( - &[executable.to_string_lossy().into_owned()], PathQuote::PowerShell, - ).unwrap(); + &[executable.to_string_lossy().into_owned()], + PathQuote::PowerShell, + ) + .unwrap(); for (shell, legacy) in [("powershell.exe", true), ("pwsh.exe", false)] { - let line = append(format!("& {}", quoted_exe.trim_end()), &value, - PathQuote::PowerShell, legacy).unwrap(); + let line = append( + format!("& {}", quoted_exe.trim_end()), + &value, + PathQuote::PowerShell, + legacy, + ) + .unwrap(); let mut command = std::process::Command::new(shell); command.args(["-NoProfile", "-NonInteractive", "-Command", &line]); let output = crate::platform::process_output::read_cancellable( @@ -126,7 +143,8 @@ mod native_tests { std::time::Duration::from_secs(15), 8192, &|| false, - ).unwrap(); + ) + .unwrap(); assert_eq!(String::from_utf8(output).unwrap(), format!("{args:?}"), "{shell}: {line}"); } } From 92bd3a9c122a7a673d8d246a7b889615af0af36f Mon Sep 17 00:00:00 2001 From: GeekMr <140129782+WilliamWang1721@users.noreply.github.com> Date: Sat, 3 Oct 2026 17:02:53 +0800 Subject: [PATCH 07/15] fix(agents): keep native quoting in its platform adapter --- .../2026-10-03-explicit-resume-arguments.md | 2 +- nebula_app/src/agent_resume.rs | 102 +---------------- .../settings_pane/agent_resume_tests.rs | 22 ++-- .../terminal/view/startup_command.rs | 11 +- nebula_app/src/platform/agent_resume.rs | 108 ++++++++++++++++++ nebula_app/src/platform/elevation.rs | 2 +- nebula_app/src/platform/mod.rs | 1 + 7 files changed, 130 insertions(+), 118 deletions(-) create mode 100644 nebula_app/src/platform/agent_resume.rs diff --git a/architecture/notes/nebula_settings/agent_resume/2026-10-03-explicit-resume-arguments.md b/architecture/notes/nebula_settings/agent_resume/2026-10-03-explicit-resume-arguments.md index 77726da68..8d7d039f5 100644 --- a/architecture/notes/nebula_settings/agent_resume/2026-10-03-explicit-resume-arguments.md +++ b/architecture/notes/nebula_settings/agent_resume/2026-10-03-explicit-resume-arguments.md @@ -22,7 +22,7 @@ Add eleven stable `agent_resume_args_` preferences for providers with an existing resume command. Each value is a JSON array of literal, nonempty arguments; missing/empty values and `[]` append nothing. The zero-dependency settings crate preserves the serialized value; the application uses its existing JSON dependency -and target-shell quoting helper. Arrays are limited to 32 arguments and 64 KiB +and the native quoting adapter in `platform/agent_resume`. Arrays are limited to 32 arguments and 64 KiB quoted text; control characters are rejected. CMD rejects double quotes, `%` and `!`, and quoted trailing backslashes are doubled for the native argv parser. Windows PowerShell 5's legacy native argv binder additionally receives arguments diff --git a/nebula_app/src/agent_resume.rs b/nebula_app/src/agent_resume.rs index 3617a024c..238e712ff 100644 --- a/nebula_app/src/agent_resume.rs +++ b/nebula_app/src/agent_resume.rs @@ -18,45 +18,13 @@ pub(crate) fn append( command: String, value: &str, shell: PathQuote, - legacy_powershell: bool, + program: Option<&str>, ) -> Option { let args = parse(value)?; if args.is_empty() { return Some(command); } - #[cfg(windows)] - let args = if legacy_powershell { - args.iter() - .map(|arg| { - let quoted = - crate::platform::elevation::quoted_argument(std::ffi::OsStr::new(arg)).ok()?; - String::from_utf16("ed).ok() - }) - .collect::>>()? - } else { - args - }; - #[cfg(not(windows))] - let _ = legacy_powershell; - let quoted = if matches!(shell, PathQuote::CommandPrompt) { - let mut quoted = String::new(); - // CMD passes quotes to the CLI's argv parser. A quoted argument ending in - // a backslash needs doubled trailing slashes before its closing quote. - for arg in &args { - let mut item = drop_text_for_paths(std::slice::from_ref(arg), shell)?; - if item.starts_with('"') { - let trailing = arg.chars().rev().take_while(|ch| *ch == '\\').count(); - item.insert_str(item.len() - 2, &"\\".repeat(trailing)); - } - quoted.push_str(&item); - } - quoted - } else { - drop_text_for_paths(&args, shell)? - }; - if quoted.len() > 64 * 1024 { - return None; - } + let quoted = crate::platform::agent_resume::quote_args(&args, shell, program)?; Some(format!("{command} {}", quoted.trim_end())) } @@ -68,21 +36,21 @@ mod tests { fn literal_arguments_cannot_become_shell_expressions() { let value = r#"["--config", "name=a b;$(touch nope)&|", "it's"]"#; assert_eq!( - append("codex resume id".into(), value, PathQuote::Posix, false).unwrap(), + append("codex resume id".into(), value, PathQuote::Posix, None).unwrap(), "codex resume id --config 'name=a b;$(touch nope)&|' 'it'\\''s'" ); assert_eq!( - append("codex resume id".into(), value, PathQuote::PowerShell, false).unwrap(), + append("codex resume id".into(), value, PathQuote::PowerShell, None).unwrap(), "codex resume id --config 'name=a b;$(touch nope)&|' 'it''s'" ); assert_eq!( - append("codex resume id".into(), r#"["a b\\"]"#, PathQuote::CommandPrompt, false) + append("codex resume id".into(), r#"["a b\\"]"#, PathQuote::CommandPrompt, None) .unwrap(), "codex resume id \"a b\\\\\"" ); for value in [r#"["%PATH%"]"#, r#"["!VAR!"]"#, r#"["a\"b"]"#] { assert!( - append("codex resume id".into(), value, PathQuote::CommandPrompt, false).is_none() + append("codex resume id".into(), value, PathQuote::CommandPrompt, None).is_none() ); } for value in ["--yolo", r#"[1]"#, r#"[""]"#, r#"["\n"]"#] { @@ -91,61 +59,3 @@ mod tests { } } -#[cfg(all(test, windows))] -mod native_tests { - use super::*; - - #[test] - fn windows_powershell_and_pwsh_deliver_the_exact_native_argument_array() { - let root = tempfile::tempdir().unwrap(); - let source = root.path().join("argv.rs"); - let executable = root.path().join("argv probe.exe"); - std::fs::write( - &source, - r#"fn main() { print!("{:?}", std::env::args().skip(1).collect::>()); }"#, - ) - .unwrap(); - assert!( - std::process::Command::new("rustc") - .arg(&source) - .arg("-o") - .arg(&executable) - .status() - .unwrap() - .success() - ); - let args = [ - "--config", - "model_provider=\"custom\"", - "a\"b", - "a b\\", - "x\\\"y", - "it's & $(Write-Output nope)", - ]; - let value = serde_json::to_string(&args).unwrap(); - let quoted_exe = drop_text_for_paths( - &[executable.to_string_lossy().into_owned()], - PathQuote::PowerShell, - ) - .unwrap(); - for (shell, legacy) in [("powershell.exe", true), ("pwsh.exe", false)] { - let line = append( - format!("& {}", quoted_exe.trim_end()), - &value, - PathQuote::PowerShell, - legacy, - ) - .unwrap(); - let mut command = std::process::Command::new(shell); - command.args(["-NoProfile", "-NonInteractive", "-Command", &line]); - let output = crate::platform::process_output::read_cancellable( - command, - std::time::Duration::from_secs(15), - 8192, - &|| false, - ) - .unwrap(); - assert_eq!(String::from_utf8(output).unwrap(), format!("{args:?}"), "{shell}: {line}"); - } - } -} diff --git a/nebula_app/src/gpui_shell/settings_pane/agent_resume_tests.rs b/nebula_app/src/gpui_shell/settings_pane/agent_resume_tests.rs index ce77971c6..bc2710b4a 100644 --- a/nebula_app/src/gpui_shell/settings_pane/agent_resume_tests.rs +++ b/nebula_app/src/gpui_shell/settings_pane/agent_resume_tests.rs @@ -29,13 +29,13 @@ fn resume_arguments_save_reopen_reject_invalid_and_clear_through_real_controls( let _settings_guard = SettingsBytesGuard::capture(); std::fs::create_dir_all(nebula_settings::settings_dir()).unwrap(); std::fs::write(nebula_settings::settings_path(), "theme=Nord\nlanguage=en-US\n").unwrap(); - let (pane, mut window, reply, _) = fixture(cx); + let (pane, window, reply, _) = fixture(cx); drop(reply); - draw(&mut window); + draw(window); let value = r#"["--yolo", "--config", "model=example"]"#; - edit_input("agent-resume-input-1", value, &mut window); + edit_input("agent-resume-input-1", value, window); assert_eq!(RuntimeSettings::load().agent_resume_args.get("codex"), ""); - click("agent-resume-save-1", &mut window); + click("agent-resume-save-1", window); let persisted = r#"["--yolo","--config","model=example"]"#; assert_eq!(RuntimeSettings::load().agent_resume_args.get("codex"), persisted); window.read(|cx| { @@ -44,22 +44,22 @@ fn resume_arguments_save_reopen_reject_invalid_and_clear_through_real_controls( persisted ); }); - pane.read_with(&mut window, |pane, _| { + pane.read_with(window, |pane, _| { assert!(matches!(pane.agents.resume_feedback, Some((1, Ok(()))))); }); let reopened = window.update(|window, cx| cx.new(|cx| SettingsPane::new(window, cx))); - reopened.read_with(&mut window, |pane, cx| { + reopened.read_with(window, |pane, cx| { assert_eq!(pane.agents.resume_inputs[1].read(cx).value().as_ref(), persisted); assert_eq!(pane.runtime.agent_resume_args.get("claude"), ""); }); - edit_input("agent-resume-input-1", "--yolo; echo invalid", &mut window); - click("agent-resume-save-1", &mut window); + edit_input("agent-resume-input-1", "--yolo; echo invalid", window); + click("agent-resume-save-1", window); assert_eq!(RuntimeSettings::load().agent_resume_args.get("codex"), persisted); - pane.read_with(&mut window, |pane, _| { + pane.read_with(window, |pane, _| { assert!(matches!(pane.agents.resume_feedback, Some((1, Err(_))))); }); - edit_input("agent-resume-input-1", "[]", &mut window); - click("agent-resume-save-1", &mut window); + edit_input("agent-resume-input-1", "[]", window); + click("agent-resume-save-1", window); assert_eq!(RuntimeSettings::load().agent_resume_args.get("codex"), ""); let input = window.debug_bounds("agent-resume-input-1").unwrap(); let save = window.debug_bounds("agent-resume-save-1").unwrap(); diff --git a/nebula_app/src/gpui_shell/terminal/view/startup_command.rs b/nebula_app/src/gpui_shell/terminal/view/startup_command.rs index f3698ae70..a20950022 100644 --- a/nebula_app/src/gpui_shell/terminal/view/startup_command.rs +++ b/nebula_app/src/gpui_shell/terminal/view/startup_command.rs @@ -189,15 +189,8 @@ impl TerminalView { cx: &App, ) -> Option { let value = cx.global::().agent_resume_args.get(source); - let legacy_powershell = cfg!(windows) - && self.exec_context.as_ref().and_then(|context| context.shell_program()).is_some_and( - |program| { - let name = program.rsplit(['/', '\\']).next().unwrap_or(program); - name.eq_ignore_ascii_case("powershell") - || name.eq_ignore_ascii_case("powershell.exe") - }, - ); - crate::agent_resume::append(command, value, self.path_quote(), legacy_powershell) + let program = self.exec_context.as_ref().and_then(|context| context.shell_program()); + crate::agent_resume::append(command, value, self.path_quote(), program) } pub(crate) fn restore_agent( diff --git a/nebula_app/src/platform/agent_resume.rs b/nebula_app/src/platform/agent_resume.rs new file mode 100644 index 000000000..424eefcff --- /dev/null +++ b/nebula_app/src/platform/agent_resume.rs @@ -0,0 +1,108 @@ +//! Native argv quoting for automatic Agent recovery. + +use crate::display::side_panel::{PathQuote, drop_text_for_paths}; + +pub(crate) fn quote_args(args: &[String], shell: PathQuote, program: Option<&str>) -> Option { + #[cfg(windows)] + let legacy_args = if matches!(shell, PathQuote::PowerShell) + && program.is_some_and(|program| { + let name = program.rsplit(['/', '\\']).next().unwrap_or(program); + name.eq_ignore_ascii_case("powershell") || name.eq_ignore_ascii_case("powershell.exe") + }) + { + Some(args.iter() + .map(|arg| { + let quoted = + crate::platform::elevation::quoted_argument(std::ffi::OsStr::new(arg)).ok()?; + String::from_utf16("ed).ok() + }) + .collect::>>()?) + } else { + None + }; + #[cfg(windows)] + let args = legacy_args.as_deref().unwrap_or(args); + #[cfg(not(windows))] + let _ = program; + let quoted = if matches!(shell, PathQuote::CommandPrompt) { + let mut quoted = String::new(); + // CMD passes quotes to the CLI's argv parser. A quoted argument ending in + // a backslash needs doubled trailing slashes before its closing quote. + for arg in args { + let mut item = drop_text_for_paths(std::slice::from_ref(arg), shell)?; + if item.starts_with('"') { + let trailing = arg.chars().rev().take_while(|ch| *ch == '\\').count(); + item.insert_str(item.len() - 2, &"\\".repeat(trailing)); + } + quoted.push_str(&item); + } + quoted + } else { + drop_text_for_paths(&args, shell)? + }; + if quoted.len() > 64 * 1024 { + return None; + } + Some(quoted) +} + +#[cfg(all(test, windows))] +mod native_tests { + use super::*; + use crate::agent_resume::append; + + #[test] + fn windows_powershell_and_pwsh_deliver_the_exact_native_argument_array() { + let root = tempfile::tempdir().unwrap(); + let source = root.path().join("argv.rs"); + let executable = root.path().join("argv probe.exe"); + std::fs::write( + &source, + r#"fn main() { print!("{:?}", std::env::args().skip(1).collect::>()); }"#, + ) + .unwrap(); + assert!( + std::process::Command::new("rustc") + .arg(&source) + .arg("-o") + .arg(&executable) + .status() + .unwrap() + .success() + ); + let args = [ + "--config", + "model_provider=\"custom\"", + "a\"b", + "a b\\", + "x\\\"y", + "it's & $(Write-Output nope)", + ]; + let value = serde_json::to_string(&args).unwrap(); + let quoted_exe = drop_text_for_paths( + &[executable.to_string_lossy().into_owned()], + PathQuote::PowerShell, + ) + .unwrap(); + for shell in ["powershell.exe", "pwsh.exe"] { + let line = append( + format!("& {}", quoted_exe.trim_end()), + &value, + PathQuote::PowerShell, + Some(shell), + ) + .unwrap(); + let mut command = std::process::Command::new(shell); + command.args(["-NoProfile", "-NonInteractive", "-Command", &line]); + let output = crate::platform::process_output::read_cancellable( + command, + std::time::Duration::from_secs(15), + 8192, + &|| false, + ) + .unwrap(); + let actual = String::from_utf8(output).unwrap(); + assert_eq!(actual.trim(), format!("{args:?}"), "{shell}: {line}"); + } + } +} diff --git a/nebula_app/src/platform/elevation.rs b/nebula_app/src/platform/elevation.rs index b46e8aa52..e59e7ccb9 100644 --- a/nebula_app/src/platform/elevation.rs +++ b/nebula_app/src/platform/elevation.rs @@ -72,7 +72,7 @@ pub(crate) fn is_elevated() -> io::Result { } #[cfg(windows)] -pub(crate) fn quoted_argument(argument: &OsStr) -> io::Result> { +pub(super) fn quoted_argument(argument: &OsStr) -> io::Result> { use std::os::windows::ffi::OsStrExt; let mut result = vec![b'"' as u16]; let mut backslashes = 0; diff --git a/nebula_app/src/platform/mod.rs b/nebula_app/src/platform/mod.rs index 30361287a..dba47a996 100644 --- a/nebula_app/src/platform/mod.rs +++ b/nebula_app/src/platform/mod.rs @@ -10,6 +10,7 @@ //! 能力探测(让 UI 隐藏入口,而不是让功能在别的平台报错)。 #[cfg(feature = "gpui-shell")] +pub(crate) mod agent_resume; pub(crate) mod acrylic; pub(crate) mod ai_session_identity; pub mod capabilities; From 4305dc4e6b88a324234505fa358010b14db50c5d Mon Sep 17 00:00:00 2001 From: GeekMr <140129782+WilliamWang1721@users.noreply.github.com> Date: Sat, 3 Oct 2026 17:03:31 +0800 Subject: [PATCH 08/15] fix(platform): preserve acrylic feature gate --- nebula_app/src/platform/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nebula_app/src/platform/mod.rs b/nebula_app/src/platform/mod.rs index dba47a996..d1c96329c 100644 --- a/nebula_app/src/platform/mod.rs +++ b/nebula_app/src/platform/mod.rs @@ -10,8 +10,8 @@ //! 能力探测(让 UI 隐藏入口,而不是让功能在别的平台报错)。 #[cfg(feature = "gpui-shell")] -pub(crate) mod agent_resume; pub(crate) mod acrylic; +pub(crate) mod agent_resume; pub(crate) mod ai_session_identity; pub mod capabilities; pub mod credentials; From 57b171c3196e2f106e9aff211b30797d3775e620 Mon Sep 17 00:00:00 2001 From: GeekMr <140129782+WilliamWang1721@users.noreply.github.com> Date: Sat, 3 Oct 2026 17:05:10 +0800 Subject: [PATCH 09/15] style(platform): apply remote native-adapter formatting --- nebula_app/src/agent_resume.rs | 1 - nebula_app/src/platform/agent_resume.rs | 26 +++++++++++++++---------- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/nebula_app/src/agent_resume.rs b/nebula_app/src/agent_resume.rs index 238e712ff..29c860923 100644 --- a/nebula_app/src/agent_resume.rs +++ b/nebula_app/src/agent_resume.rs @@ -58,4 +58,3 @@ mod tests { } } } - diff --git a/nebula_app/src/platform/agent_resume.rs b/nebula_app/src/platform/agent_resume.rs index 424eefcff..9bd6a3b2f 100644 --- a/nebula_app/src/platform/agent_resume.rs +++ b/nebula_app/src/platform/agent_resume.rs @@ -2,21 +2,27 @@ use crate::display::side_panel::{PathQuote, drop_text_for_paths}; -pub(crate) fn quote_args(args: &[String], shell: PathQuote, program: Option<&str>) -> Option { +pub(crate) fn quote_args( + args: &[String], + shell: PathQuote, + program: Option<&str>, +) -> Option { #[cfg(windows)] let legacy_args = if matches!(shell, PathQuote::PowerShell) && program.is_some_and(|program| { let name = program.rsplit(['/', '\\']).next().unwrap_or(program); name.eq_ignore_ascii_case("powershell") || name.eq_ignore_ascii_case("powershell.exe") - }) - { - Some(args.iter() - .map(|arg| { - let quoted = - crate::platform::elevation::quoted_argument(std::ffi::OsStr::new(arg)).ok()?; - String::from_utf16("ed).ok() - }) - .collect::>>()?) + }) { + Some( + args.iter() + .map(|arg| { + let quoted = + crate::platform::elevation::quoted_argument(std::ffi::OsStr::new(arg)) + .ok()?; + String::from_utf16("ed).ok() + }) + .collect::>>()?, + ) } else { None }; From ad1f4de270cf0369cdf316c95f0f67bf24b4c266 Mon Sep 17 00:00:00 2001 From: GeekMr <140129782+WilliamWang1721@users.noreply.github.com> Date: Sat, 3 Oct 2026 17:15:13 +0800 Subject: [PATCH 10/15] fix(agents): preserve explicit empty resume arguments --- .../2026-10-03-explicit-resume-arguments.md | 4 ++-- nebula_app/i18n/en-US.json | 2 +- nebula_app/i18n/zh-CN.json | 2 +- nebula_app/src/agent_resume.rs | 14 +++++++++++--- .../gpui_shell/terminal/view/startup_tests.rs | 6 +++--- nebula_app/src/platform/agent_resume.rs | 18 ++++++++++++++++-- 6 files changed, 34 insertions(+), 12 deletions(-) diff --git a/architecture/notes/nebula_settings/agent_resume/2026-10-03-explicit-resume-arguments.md b/architecture/notes/nebula_settings/agent_resume/2026-10-03-explicit-resume-arguments.md index 8d7d039f5..70b5307b8 100644 --- a/architecture/notes/nebula_settings/agent_resume/2026-10-03-explicit-resume-arguments.md +++ b/architecture/notes/nebula_settings/agent_resume/2026-10-03-explicit-resume-arguments.md @@ -19,8 +19,8 @@ persistence and the cached GPUI snapshot. ## Decision Add eleven stable `agent_resume_args_` preferences for providers with an -existing resume command. Each value is a JSON array of literal, nonempty arguments; -missing/empty values and `[]` append nothing. The zero-dependency settings crate +existing resume command. Each value is a JSON array of literal arguments; +missing/empty values and `[]` append nothing. `[""]` passes one explicit empty argument. The zero-dependency settings crate preserves the serialized value; the application uses its existing JSON dependency and the native quoting adapter in `platform/agent_resume`. Arrays are limited to 32 arguments and 64 KiB quoted text; control characters are rejected. CMD rejects double quotes, `%` and diff --git a/nebula_app/i18n/en-US.json b/nebula_app/i18n/en-US.json index 8f9e87a01..67913054c 100644 --- a/nebula_app/i18n/en-US.json +++ b/nebula_app/i18n/en-US.json @@ -196,7 +196,7 @@ "agents": { "resume_title": "Automatic resume arguments", "resume_description": "Enter a JSON array of literal arguments for each agent, such as [\"--flag\", \"value\"]. Empty keeps the default command. Saved values apply to the next automatic resume or retry; they never replay command history. CMD cannot accept arguments containing double quotes, % or !.", - "resume_invalid": "Use a JSON array of up to 32 nonempty strings, without control characters (at most 64 KiB after quoting).", + "resume_invalid": "Use a JSON array of up to 32 strings, without control characters (at most 64 KiB after quoting).", "resume_failed": "Could not save resume arguments: {error}", "title": "Coding agents", "description": "Show agent activity, completion and approval requests in Pebrel. Claude Code and Codex are enabled by default.", diff --git a/nebula_app/i18n/zh-CN.json b/nebula_app/i18n/zh-CN.json index 3820577c8..61b636a92 100644 --- a/nebula_app/i18n/zh-CN.json +++ b/nebula_app/i18n/zh-CN.json @@ -196,7 +196,7 @@ "agents": { "resume_title": "自动接续附加参数", "resume_description": "按 Agent 输入由字面参数组成的 JSON 数组,例如 [\"--flag\", \"value\"]。留空保持默认命令。保存后用于下次自动接续或重试,不重放命令历史。CMD 不支持包含双引号、% 或 ! 的参数。", - "resume_invalid": "请输入最多 32 个非空字符串组成的 JSON 数组,不包含控制字符(引用后最多 64 KiB)。", + "resume_invalid": "请输入最多 32 个字符串组成的 JSON 数组,不包含控制字符(引用后最多 64 KiB)。", "resume_failed": "无法保存接续参数:{error}", "title": "编程智能体", "description": "在 Pebrel 中显示运行状态、完成通知和授权请求。Claude Code 与 Codex 默认开启。", diff --git a/nebula_app/src/agent_resume.rs b/nebula_app/src/agent_resume.rs index 29c860923..5479b309b 100644 --- a/nebula_app/src/agent_resume.rs +++ b/nebula_app/src/agent_resume.rs @@ -1,6 +1,6 @@ //! Literal argument arrays for automatic recovery, quoted for the pane's shell. -use crate::display::side_panel::{PathQuote, drop_text_for_paths}; +use crate::display::side_panel::PathQuote; pub(crate) fn parse(value: &str) -> Option> { if value.trim().is_empty() { @@ -10,7 +10,10 @@ pub(crate) fn parse(value: &str) -> Option> { if args.is_empty() { return Some(args); } - drop_text_for_paths(&args, PathQuote::Posix)?; + if args.len() > 32 || args.iter().any(|arg| arg.chars().any(char::is_control)) { + return None; + } + crate::platform::agent_resume::quote_args(&args, PathQuote::Posix, None)?; Some(args) } @@ -53,7 +56,12 @@ mod tests { append("codex resume id".into(), value, PathQuote::CommandPrompt, None).is_none() ); } - for value in ["--yolo", r#"[1]"#, r#"[""]"#, r#"["\n"]"#] { + assert_eq!(parse(r#"[""]"#), Some(vec![String::new()])); + assert_eq!( + append("codex resume id".into(), r#"[""]"#, PathQuote::Posix, None), + Some("codex resume id ''".into()) + ); + for value in ["--yolo", r#"[1]"#, r#"[null]"#, r#"["\n"]"#] { assert!(parse(value).is_none()); } } diff --git a/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs b/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs index 2c85f2eba..c16e213af 100644 --- a/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs +++ b/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs @@ -1240,7 +1240,7 @@ fn configured_cold_resume_preserves_saved_identity_cwd_and_retries(cx: &mut Test "resume_ai=1\n", &[( "agent_resume_args_codex", - r#"["--yolo", "--config", "model=a b;$(echo nope)"]"#.into(), + r#"["--yolo", "--config", "model=a b;$(echo nope)", ""]"#.into(), )], ); window.update(|_, cx| { @@ -1269,7 +1269,7 @@ fn configured_cold_resume_preserves_saved_identity_cwd_and_retries(cx: &mut Test assert!(!receiver.try_iter().any(|message| matches!(message, Msg::Input(_)))); let target = view.session_agent().unwrap(); assert_eq!(target.session_id.as_deref(), Some(thread)); - let expected = format!("codex resume {thread} --yolo --config 'model=a b;$(echo nope)'"); + let expected = format!("codex resume {thread} --yolo --config 'model=a b;$(echo nope)' ''"); assert_eq!(view.cwd, before_cwd); feed(view, b"\x1b]133;A\x07user@host:~$ "); view.flush_pending_shell_command(cx); @@ -1288,7 +1288,7 @@ fn configured_cold_resume_preserves_saved_identity_cwd_and_retries(cx: &mut Test view.running_program = None; view.recovery.command_ended(); view.choose_recovery_session(cx); - let chooser = "codex resume --yolo --config 'model=a b;$(echo nope)'"; + let chooser = "codex resume --yolo --config 'model=a b;$(echo nope)' ''"; assert!(receiver.try_iter().any(|message| { matches!(message, Msg::Input(bytes) if bytes.as_ref() == chooser.as_bytes()) })); diff --git a/nebula_app/src/platform/agent_resume.rs b/nebula_app/src/platform/agent_resume.rs index 9bd6a3b2f..cfadef739 100644 --- a/nebula_app/src/platform/agent_resume.rs +++ b/nebula_app/src/platform/agent_resume.rs @@ -35,7 +35,11 @@ pub(crate) fn quote_args( // CMD passes quotes to the CLI's argv parser. A quoted argument ending in // a backslash needs doubled trailing slashes before its closing quote. for arg in args { - let mut item = drop_text_for_paths(std::slice::from_ref(arg), shell)?; + let mut item = if arg.is_empty() { + "\"\" ".to_owned() + } else { + drop_text_for_paths(std::slice::from_ref(arg), shell)? + }; if item.starts_with('"') { let trailing = arg.chars().rev().take_while(|ch| *ch == '\\').count(); item.insert_str(item.len() - 2, &"\\".repeat(trailing)); @@ -44,7 +48,15 @@ pub(crate) fn quote_args( } quoted } else { - drop_text_for_paths(&args, shell)? + let mut quoted = String::new(); + for arg in args { + if arg.is_empty() { + quoted.push_str("'' "); + } else { + quoted.push_str(&drop_text_for_paths(std::slice::from_ref(arg), shell)?); + } + } + quoted }; if quoted.len() > 64 * 1024 { return None; @@ -77,12 +89,14 @@ mod native_tests { .success() ); let args = [ + "", "--config", "model_provider=\"custom\"", "a\"b", "a b\\", "x\\\"y", "it's & $(Write-Output nope)", + "", ]; let value = serde_json::to_string(&args).unwrap(); let quoted_exe = drop_text_for_paths( From 7b4004409c2835a238f1c2c4a925ac0509f12146 Mon Sep 17 00:00:00 2001 From: GeekMr <140129782+WilliamWang1721@users.noreply.github.com> Date: Sat, 3 Oct 2026 17:17:39 +0800 Subject: [PATCH 11/15] test(agents): exercise retry through authoritative shell events --- .../gpui_shell/terminal/view/startup_tests.rs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs b/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs index c16e213af..d30be15a1 100644 --- a/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs +++ b/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs @@ -1277,16 +1277,26 @@ fn configured_cold_resume_preserves_saved_identity_cwd_and_retries(cx: &mut Test matches!(message, Msg::Input(bytes) if bytes.as_ref() == expected.as_bytes()) })); assert!(view.recovery_pending()); - view.running_program = None; - view.recovery.command_ended(); + feed(view, expected.as_bytes()); + view.flush_pending_runtime_submit(cx); + view.process_event(Event::CommandStart, cx); + feed(view, b"\r\nresume failed\r\n"); + view.process_event(Event::CommandDone { exit_code: Some(1) }, cx); + feed(view, b"\x1b]133;A\x07user@host:~$ "); + assert!(view.can_retry_recovery()); view.retry_recovery(cx); assert!(receiver.try_iter().any(|message| { matches!(message, Msg::Input(bytes) if bytes.as_ref() == expected.as_bytes()) })); assert_eq!(view.session_agent(), Some(target)); assert_eq!(view.cwd, before_cwd); - view.running_program = None; - view.recovery.command_ended(); + feed(view, expected.as_bytes()); + view.flush_pending_runtime_submit(cx); + view.process_event(Event::CommandStart, cx); + feed(view, b"\r\nresume failed\r\n"); + view.process_event(Event::CommandDone { exit_code: Some(1) }, cx); + feed(view, b"\x1b]133;A\x07user@host:~$ "); + assert!(view.can_choose_recovery_session()); view.choose_recovery_session(cx); let chooser = "codex resume --yolo --config 'model=a b;$(echo nope)' ''"; assert!(receiver.try_iter().any(|message| { From 53e9cdc8b03512a4c0e5ac7cb87e4880a11b5198 Mon Sep 17 00:00:00 2001 From: GeekMr <140129782+WilliamWang1721@users.noreply.github.com> Date: Tue, 6 Oct 2026 20:20:16 +0800 Subject: [PATCH 12/15] fix(ci): keep both native test filters after merging main --- .config/nextest.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.config/nextest.toml b/.config/nextest.toml index 68f4fa55e..0bcd0f099 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -6,7 +6,7 @@ theme-studio = { max-threads = 1 } [[profile.default.overrides]] -filter = 'test(gpui_shell::settings_pane::theme_studio_tests::) or test(ctrl_wheel_font_zoom_toggle_gates_zoom_and_terminal_scroll) or test(ctrl_wheel_font_zoom_setting_is_searchable_and_has_a_visible_switch) or test(environment_refresh_switch_is_searchable_and_persists) or test(pasted_proxy_scheme_updates_the_visible_protocol_and_saved_url) or test(capsule_uses_inset_thumb_full_hit_targets_and_keyboard_selection) or test(long_segments_use_a_real_dropdown_without_losing_preference_updates) or test(font_size_click_input_commits_cancels_and_bounds_values) or test(cjk_dropdown_selection_preserves_the_english_font_chain) or test(review_regression_font_fields_align_and_dropdown_toggles_with_search) or test(=gpui_shell::workspace::keyboard_bindings::tests::dispatch::hybrid_completion_uses_window_tab_dispatch_in_both_workspace_layouts) or test(resume_arguments_save_reopen_reject_invalid_and_clear_through_real_controls)' +filter = 'test(gpui_shell::settings_pane::theme_studio_tests::) or test(ctrl_wheel_font_zoom_toggle_gates_zoom_and_terminal_scroll) or test(ctrl_wheel_font_zoom_setting_is_searchable_and_has_a_visible_switch) or test(environment_refresh_switch_is_searchable_and_persists) or test(pasted_proxy_scheme_updates_the_visible_protocol_and_saved_url) or test(capsule_uses_inset_thumb_full_hit_targets_and_keyboard_selection) or test(long_segments_use_a_real_dropdown_without_losing_preference_updates) or test(font_size_click_input_commits_cancels_and_bounds_values) or test(cjk_dropdown_selection_preserves_the_english_font_chain) or test(review_regression_font_fields_align_and_dropdown_toggles_with_search) or test(resume_arguments_save_reopen_reject_invalid_and_clear_through_real_controls) or test(=gpui_shell::workspace::keyboard_bindings::tests::dispatch::hybrid_completion_uses_window_tab_dispatch_in_both_workspace_layouts)' test-group = 'theme-studio' # 三模式夹具包含九个真实 Git/窗口场景;原生进程的墙钟期限不能用并发 UI 负载测试。 From 6bf90853605d0eb8eb88c2215a78db737526ece9 Mon Sep 17 00:00:00 2001 From: GeekMr <140129782+WilliamWang1721@users.noreply.github.com> Date: Tue, 6 Oct 2026 21:19:57 +0800 Subject: [PATCH 13/15] fix(agents): treat missing global settings as unconfigured resume arguments --- nebula_app/src/gpui_shell/terminal/view/startup_command.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/nebula_app/src/gpui_shell/terminal/view/startup_command.rs b/nebula_app/src/gpui_shell/terminal/view/startup_command.rs index a20950022..888d130a5 100644 --- a/nebula_app/src/gpui_shell/terminal/view/startup_command.rs +++ b/nebula_app/src/gpui_shell/terminal/view/startup_command.rs @@ -188,7 +188,10 @@ impl TerminalView { source: &str, cx: &App, ) -> Option { - let value = cx.global::().agent_resume_args.get(source); + // 没有全局设置(启动早期、无设置的测试窗口)等同于未配置,保持默认命令。 + let value = cx + .try_global::() + .map_or("", |settings| settings.agent_resume_args.get(source)); let program = self.exec_context.as_ref().and_then(|context| context.shell_program()); crate::agent_resume::append(command, value, self.path_quote(), program) } From 9880d4e1a60852a6d1954ba6036fcb767a7f4117 Mon Sep 17 00:00:00 2001 From: GeekMr <140129782+WilliamWang1721@users.noreply.github.com> Date: Tue, 6 Oct 2026 23:20:01 +0800 Subject: [PATCH 14/15] ci: rerun native tests after unrelated flaky failure From 61b2d1f5b185f008e02646ff4f965a95f8b90151 Mon Sep 17 00:00:00 2001 From: Cecic <1518585189@qq.com> Date: Fri, 9 Oct 2026 10:29:37 +0800 Subject: [PATCH 15/15] test(editor): make reader undo fixture independent of typing speed --- nebula_app/src/gpui_shell/file_editor/tests.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/nebula_app/src/gpui_shell/file_editor/tests.rs b/nebula_app/src/gpui_shell/file_editor/tests.rs index 9058ac7da..fce2508f9 100644 --- a/nebula_app/src/gpui_shell/file_editor/tests.rs +++ b/nebula_app/src/gpui_shell/file_editor/tests.rs @@ -108,7 +108,11 @@ fn returning_to_reader_keeps_source_edits_and_blocks_undo_until_source_is_open( _ => "ctrl", }; cx.simulate_keystrokes(&format!("{modifier}-/ {modifier}-a")); - cx.simulate_input("Updated"); + // Keep this one edit: slow simulated typing can cross the undo grouping timeout. + cx.update(|_, cx| { + cx.write_to_clipboard(gpui::ClipboardItem::new_string("Updated".to_owned())); + }); + cx.simulate_keystrokes(&format!("{modifier}-v")); cx.run_until_parked(); cx.simulate_keystrokes(&format!("{modifier}-/ {modifier}-z")); cx.run_until_parked();