diff --git a/.config/nextest.toml b/.config/nextest.toml index 373f71dc9..725010049 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(completion_capsules_keep_all_chinese_choices_at_large_font_size) 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)' +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(completion_capsules_keep_all_chinese_choices_at_large_font_size) 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 负载测试。 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..70b5307b8 --- /dev/null +++ b/architecture/notes/nebula_settings/agent_resume/2026-10-03-explicit-resume-arguments.md @@ -0,0 +1,73 @@ +# 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 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 +`!`, 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 +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. 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. + +## 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 2f64a9bf3..bb6debff8 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 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 b0d8d8d5f..e014e3599 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..5479b309b --- /dev/null +++ b/nebula_app/src/agent_resume.rs @@ -0,0 +1,68 @@ +//! Literal argument arrays for automatic recovery, quoted for the pane's shell. + +use crate::display::side_panel::PathQuote; + +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); + } + 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) +} + +pub(crate) fn append( + command: String, + value: &str, + shell: PathQuote, + program: Option<&str>, +) -> Option { + let args = parse(value)?; + if args.is_empty() { + return Some(command); + } + let quoted = crate::platform::agent_resume::quote_args(&args, shell, program)?; + 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, None).unwrap(), + "codex resume id --config 'name=a b;$(touch nope)&|' 'it'\\''s'" + ); + assert_eq!( + 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, 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, None).is_none() + ); + } + 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/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/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(); diff --git a/nebula_app/src/gpui_shell/settings_pane.rs b/nebula_app/src/gpui_shell/settings_pane.rs index f795423e3..337c2c2c6 100644 --- a/nebula_app/src/gpui_shell/settings_pane.rs +++ b/nebula_app/src/gpui_shell/settings_pane.rs @@ -36,6 +36,7 @@ use crate::gpui_shell::prelude::*; use crate::gpui_shell::widgets::{NebulaButton, settings_control_height}; mod about; +mod agent_resume; mod agents; mod app_icon; mod appearance; 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..99ea6857c --- /dev/null +++ b/nebula_app/src/gpui_shell/settings_pane/agent_resume.rs @@ -0,0 +1,97 @@ +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..bc2710b4a --- /dev/null +++ b/nebula_app/src/gpui_shell/settings_pane/agent_resume_tests.rs @@ -0,0 +1,68 @@ +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: &'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: &'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); + 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, window, reply, _) = fixture(cx); + drop(reply); + draw(window); + let value = r#"["--yolo", "--config", "model=example"]"#; + edit_input("agent-resume-input-1", value, window); + assert_eq!(RuntimeSettings::load().agent_resume_args.get("codex"), ""); + 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| { + assert_eq!( + cx.global::().agent_resume_args.get("codex"), + persisted + ); + }); + 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(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", window); + click("agent-resume-save-1", window); + assert_eq!(RuntimeSettings::load().agent_resume_args.get("codex"), persisted); + pane.read_with(window, |pane, _| { + assert!(matches!(pane.agents.resume_feedback, Some((1, Err(_))))); + }); + 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(); + 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..127a8feed 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,43 @@ 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 +218,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 d1678e6ee..e1e5c2d71 100644 --- a/nebula_app/src/gpui_shell/settings_pane/initialization.rs +++ b/nebula_app/src/gpui_shell/settings_pane/initialization.rs @@ -620,12 +620,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 517c2278a..3b751532c 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,20 @@ impl TerminalView { } } + fn configured_recovery_command( + &self, + command: String, + source: &str, + cx: &App, + ) -> Option { + // 没有全局设置(启动早期、无设置的测试窗口)等同于未配置,保持默认命令。 + 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) + } + pub(crate) fn restore_agent( &mut self, mut agent: crate::session::AgentSession, @@ -190,7 +208,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 +254,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 338c3bf27..0909356af 100644 --- a/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs +++ b/nebula_app/src/gpui_shell/terminal/view/startup_tests.rs @@ -1249,6 +1249,107 @@ fn a_failed_codex_chooser_does_not_start_an_automatic_retry_loop(cx: &mut TestAp }); } +#[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")), + }; + 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(_)))); + 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()); + 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); + 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| { + 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)); + }); +} + #[gpui::test] fn host_administrator_scope_excludes_remote_and_wsl_shells(cx: &mut TestAppContext) { let (view, window, _) = open(cx); diff --git a/nebula_app/src/main.rs b/nebula_app/src/main.rs index 600f579aa..fd253806b 100644 --- a/nebula_app/src/main.rs +++ b/nebula_app/src/main.rs @@ -36,6 +36,7 @@ use winit::raw_window_handle::{HasDisplayHandle, RawDisplayHandle}; use nebula_terminal::tty; mod agent_env; +mod agent_resume; mod ai_agents; mod ai_assistant; mod ai_hook; diff --git a/nebula_app/src/platform/agent_resume.rs b/nebula_app/src/platform/agent_resume.rs new file mode 100644 index 000000000..cfadef739 --- /dev/null +++ b/nebula_app/src/platform/agent_resume.rs @@ -0,0 +1,128 @@ +//! 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 = 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)); + } + quoted.push_str(&item); + } + quoted + } else { + 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; + } + 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 004f1ef2d..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)] -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 ca9c241e2..412403119 100644 --- a/nebula_app/src/platform/mod.rs +++ b/nebula_app/src/platform/mod.rs @@ -11,6 +11,7 @@ #[cfg(feature = "gpui-shell")] pub(crate) mod acrylic; +pub(crate) mod agent_resume; pub(crate) mod ai_session_identity; #[cfg(all(feature = "gpui-shell", feature = "video-background"))] pub(crate) mod background_media; diff --git a/nebula_settings/src/agent_resume.rs b/nebula_settings/src/agent_resume.rs new file mode 100644 index 000000000..89eb6a67a --- /dev/null +++ b/nebula_settings/src/agent_resume.rs @@ -0,0 +1,60 @@ +//! 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 1253417ed..a3020fe13 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; @@ -1062,6 +1064,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, @@ -1259,6 +1263,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 75b65172c..18adee860 100644 --- a/nebula_settings/src/reset.rs +++ b/nebula_settings/src/reset.rs @@ -108,6 +108,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() @@ -149,6 +152,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"; diff --git a/scripts/tests/test_ci_native_tests.py b/scripts/tests/test_ci_native_tests.py index 176713d37..fabbf7fad 100644 --- a/scripts/tests/test_ci_native_tests.py +++ b/scripts/tests/test_ci_native_tests.py @@ -192,6 +192,7 @@ def test_nextest_reserves_only_shared_settings_and_exact_bounded_git_fixtures(se " 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", }, {