Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions .roadmap/features/f-builtin-terminal.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,20 @@ port checks it against the filesystem — the check, not the regex, is what keep
prose like `and/or` from lighting up half the screen. Resolution tries the live
`cwd` from [F-terminal-cwd](#f-terminal-cwd), then the repository holding it,
then the launch directory, because `cargo`, `git` and `pytest` each print
relative to a different root. It opens through the OS handler, which leaves two
debts closing together in #257: the `:line` it parses is carried to the effect
but cannot be honoured, and opening by association means a path that *is* a
program must be refused rather than run — a refusal that is airtight on
macOS/Linux and mostly nominal on Windows, where the association table maps
every installed interpreter. Two contract bugs sit on the same surface: mouse reporting
relative to a different root. It opened through the OS handler, which left two
debts that closed together in #257 — an `open.command` in `settings.json`, with
`{path}` / `{line}` / `{col}` templates. Configured, it replaces the handoff:
the `:line` the terminal printed is finally honoured, and since an explicit
command consults no file association, the refusal that kept a path which *is* a
program from being opened has nothing left to protect and is lifted with it.
That refusal was airtight on macOS/Linux and mostly nominal on Windows, where
the association table maps every installed interpreter — so the command does not
narrow that gap, it removes it. The command is argv and never a shell line: the
configured string is split on whitespace *before* `{path}` is substituted, so a
filename cannot become a second argument, and a placeholder in the program name
is refused outright — what the terminal printed picks the file, never the
executable. Unconfigured, the OS handoff and its refusal both stand.
Two contract bugs sit on the same surface: mouse reporting
isn't forwarded to the child (#155, vim) and the `emitted_lines_never_drift`
property has a known failing scroll sequence whose seed was never committed
(#102)
20 changes: 14 additions & 6 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,12 +212,20 @@ port checks it against the filesystem — the check, not the regex, is what keep
prose like `and/or` from lighting up half the screen. Resolution tries the live
`cwd` from [F-terminal-cwd](#f-terminal-cwd), then the repository holding it,
then the launch directory, because `cargo`, `git` and `pytest` each print
relative to a different root. It opens through the OS handler, which leaves two
debts closing together in #257: the `:line` it parses is carried to the effect
but cannot be honoured, and opening by association means a path that *is* a
program must be refused rather than run — a refusal that is airtight on
macOS/Linux and mostly nominal on Windows, where the association table maps
every installed interpreter. Two contract bugs sit on the same surface: mouse reporting
relative to a different root. It opened through the OS handler, which left two
debts that closed together in #257 — an `open.command` in `settings.json`, with
`{path}` / `{line}` / `{col}` templates. Configured, it replaces the handoff:
the `:line` the terminal printed is finally honoured, and since an explicit
command consults no file association, the refusal that kept a path which *is* a
program from being opened has nothing left to protect and is lifted with it.
That refusal was airtight on macOS/Linux and mostly nominal on Windows, where
the association table maps every installed interpreter — so the command does not
narrow that gap, it removes it. The command is argv and never a shell line: the
configured string is split on whitespace *before* `{path}` is substituted, so a
filename cannot become a second argument, and a placeholder in the program name
is refused outright — what the terminal printed picks the file, never the
executable. Unconfigured, the OS handoff and its refusal both stand.
Two contract bugs sit on the same surface: mouse reporting
isn't forwarded to the child (#155, vim) and the `emitted_lines_never_drift`
property has a known failing scroll sequence whose seed was never committed
(#102)
Expand Down
99 changes: 99 additions & 0 deletions crates/app/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,29 @@ pub struct Settings {
/// prompts first. Absent → both confirm only while a session runs a
/// foreground process, and close/quit an all-idle target silently.
pub close: CloseSettings,
/// How a clicked file leaves termherd. Absent → the OS default handler.
pub open: OpenSettings,
}

/// The on-disk editor command. Absent (or unparsable) → the OS default
/// handler, which is what shipped before the setting existed.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct OpenSettings {
/// The command run for every file termherd opens, with the `{path}`,
/// `{line}` and `{col}` templates. Sanitised by
/// [`Settings::open_command`].
pub command: Option<CommandSpec>,
}

/// A command as the file spells it — one line to split on whitespace, or an
/// explicit argv. Both reach the same [`OpenCommand`]; the array form exists
/// for a program path carrying spaces, which the split form cannot express.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CommandSpec {
Line(String),
Argv(Vec<String>),
}

/// One or several chords bound to an action — a bare string for the common
Expand Down Expand Up @@ -420,6 +443,23 @@ impl Settings {
keymap
}

/// The configured editor command, or `None` for the OS default handler.
/// A command that does not parse warns and degrades to that handoff — like
/// every other bad value here, it costs its own setting and nothing else.
#[must_use]
pub fn open_command(&self) -> Option<termherd_core::OpenCommand> {
let spec = self.open.command.as_ref()?;
let parsed = match spec {
CommandSpec::Line(line) => termherd_core::OpenCommand::parse(line),
CommandSpec::Argv(argv) => termherd_core::OpenCommand::from_words(argv.iter().cloned()),
};
parsed
.inspect_err(|error| {
warn!(%error, "invalid open command in settings; using the OS default handler");
})
.ok()
}

/// Load persisted settings; any problem (no file, bad JSON) falls back to
/// defaults — a corrupt config must never prevent startup.
#[must_use]
Expand Down Expand Up @@ -695,6 +735,65 @@ mod tests {
assert_eq!(back, ConfirmClose::ConfirmWhenActive);
}

/// The `(program, args)` a configured command renders, or a failed test.
fn opens(json: &str, path: &str, line: Option<u32>) -> (String, Vec<String>) {
let s: Settings = serde_json::from_str(json).expect("valid json");
let command = s.open_command().expect("a command");
match command.resolve(std::path::Path::new(path), line, None) {
termherd_core::OpenTarget::Editor { program, args } => (program, args),
other => panic!("expected an editor target, got {other:?}"),
}
}

#[test]
fn no_open_block_keeps_the_os_handoff() {
assert!(Settings::default().open_command().is_none());
let s: Settings = serde_json::from_str(r#"{ "theme": "light" }"#).expect("valid json");
assert!(s.open_command().is_none());
}

#[test]
fn an_open_command_deserialises_as_a_line_or_as_an_argv() {
let (program, args) = opens(
r#"{ "open": { "command": "code -g {path}:{line}:{col}" } }"#,
"/repo/f.rs",
Some(42),
);
assert_eq!(program, "code");
assert_eq!(args, vec!["-g", "/repo/f.rs:42:1"]);

// The array form is what expresses a program path containing spaces.
let (program, args) = opens(
r#"{ "open": { "command": ["/Applications/My Editor", "{path}"] } }"#,
"/repo/f.rs",
None,
);
assert_eq!(program, "/Applications/My Editor");
assert_eq!(args, vec!["/repo/f.rs"]);
}

#[test]
fn a_bad_open_command_degrades_alone() {
// Same contract as a bad colour: the setting falls back to the OS
// handoff, and the rest of the file survives — a typo in the editor
// command must not silently reset the keymap and theme.
for bad in [
r#""""#,
r#""code {file}""#,
r#""code -g""#,
r#""{path} -g {path}""#,
"[]",
// Only the argv form can name a blank program.
r#"["", "{path}"]"#,
] {
let json = format!(r#"{{ "theme": "light", "open": {{ "command": {bad} }} }}"#);
let s: Settings =
serde_json::from_str(&json).expect("a bad command must not fail the whole parse");
assert!(s.open_command().is_none(), "{bad} must not configure");
assert_eq!(s.theme, ThemeChoice::Light, "the rest of the file survives");
}
}

#[test]
fn theme_round_trips_through_json_lowercased() {
let json = serde_json::to_string(&ThemeChoice::Light).expect("serialise");
Expand Down
55 changes: 55 additions & 0 deletions crates/app/src/shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@ pub struct Startup {
pub font_size: f32,
/// Close-confirmation policy for tab close and app quit.
pub close: CloseSettings,
/// The editor command from settings, or `None` for the OS default handler.
pub open: Option<termherd_core::OpenCommand>,
/// Adapter-owned config bits for the MCP `snapshot` tool's config section
/// (the live font size is stamped by `core`, not carried here).
pub config: ConfigInput,
Expand All @@ -129,6 +131,7 @@ impl Startup {
session_limit: settings.session_limit(),
font_size: settings.font_size(),
close: settings.close,
open: settings.open_command(),
config: ConfigInput {
terminal_scheme: settings.terminal.colors.scheme.clone(),
record_fps: record.fps,
Expand Down Expand Up @@ -180,6 +183,7 @@ pub fn run(
session_limit: startup.session_limit,
font_size: startup.font_size,
close: startup.close,
open: startup.open.clone(),
config: startup.config.clone(),
},
);
Expand Down Expand Up @@ -656,6 +660,7 @@ impl Shell {
startup.session_limit,
));
core.apply(termherd_core::Event::FontSizeLoaded(startup.font_size));
core.apply(termherd_core::Event::OpenCommandLoaded(startup.open));
Self {
core,
bounds,
Expand Down Expand Up @@ -1416,6 +1421,7 @@ mod key_routing {
session_limit: 0,
font_size: 14.0,
close: CloseSettings::default(),
open: None,
config: test_config_input(),
}
}
Expand Down Expand Up @@ -1469,6 +1475,54 @@ mod key_routing {
)
}

#[test]
fn a_configured_open_command_reaches_core_from_settings_json() {
// The one seam neither crate's own tests cover: `settings.json` →
// `Startup` → `Event::OpenCommandLoaded`. A command that parses in
// isolation but never reaches `core` would leave the click opening
// through the OS, and every unit test would still pass.
let settings: crate::settings::Settings =
serde_json::from_str(r#"{ "open": { "command": "code -g {path}:{line}:{col}" } }"#)
.expect("valid json");
let (_tx, rx) = iced::futures::channel::mpsc::unbounded::<PtyEvent>();
let mut shell = Shell::new(
WindowConfig::default(),
test_ports(Arc::new(RecordingPty::default()), rx),
test_live_bridge(),
Startup::from_settings(&settings, Overlay::default(), HashSet::new()),
);

let request = termherd_core::PathRequest {
session: termherd_core::SessionId(std::num::NonZeroU64::MIN),
purpose: termherd_core::PathPurpose::Open,
row: 3,
start: 0,
end: 11,
candidate: "src/main.rs".to_owned(),
line: Some(42),
col: None,
};
let effects = shell.core.apply(termherd_core::Event::PathResolved {
request,
resolved: Some(termherd_core::ResolvedPath {
path: "/repo/src/main.rs".into(),
real: "/repo/src/main.rs".into(),
}),
});
match effects.as_slice() {
[
termherd_core::Effect::OpenPath(termherd_core::OpenTarget::Editor {
program,
args,
}),
] => {
assert_eq!(program, "code");
assert_eq!(args, &["-g", "/repo/src/main.rs:42:1"]);
}
other => panic!("expected the configured editor, got {other:?}"),
}
}

/// A `Shell` with one terminal open and focused, plus its recording PTY.
fn shell_with_terminal() -> (Shell, Arc<RecordingPty>) {
let pty = Arc::new(RecordingPty::default());
Expand Down Expand Up @@ -3570,6 +3624,7 @@ mod key_routing {
session_limit: 0,
font_size: 14.0,
close: CloseSettings::default(),
open: None,
config: test_config_input(),
},
);
Expand Down
27 changes: 23 additions & 4 deletions crates/app/src/shell/effects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,32 @@ use std::time::SystemTime;

use iced::{Task, window};
use termherd_core::{
Effect, Launch, McpConfig, Section, SessionId, SnapshotFilter, SnapshotInputs, SpawnSpec,
TerminalScope, WorkspaceSnapshot,
Effect, Launch, McpConfig, OpenTarget, Section, SessionId, SnapshotFilter, SnapshotInputs,
SpawnSpec, TerminalScope, WorkspaceSnapshot, ports::PtyError,
};

use super::bridge::Request;
use super::{Message, Shell};
use os::{notify, open_path, open_url};
use os::{notify, open_path, open_url, spawn_editor};

/// Open a resolved file. The configured command fails *visibly* — a click
/// that opens nothing is indistinguishable from a click that missed, and
/// the user is the only one who can fix a typo in `settings.json`. Falling
/// back to the OS handler here would be worse than silence: it would reopen
/// the association hole on precisely the path where nothing else worked.
fn open_target(target: OpenTarget) -> Result<(), PtyError> {
match target {
OpenTarget::SystemHandler { path } => open_path(&path),
OpenTarget::Editor { program, args } => {
spawn_editor(&program, &args).inspect_err(|error| {
let _ = notify(
"TermHerd",
&format!("The configured open command failed: {program} ({error})"),
);
})
}
}
}

impl Shell {
/// Carry out every effect `core` asked for, returning any async follow-up
Expand Down Expand Up @@ -68,7 +87,7 @@ impl Shell {
}
// Opening a link and a desktop notification are OS handoffs.
Effect::OpenUrl(url) => open_url(&url),
Effect::OpenPath { path, .. } => open_path(&path),
Effect::OpenPath(target) => open_target(target),
// Resolving walks and stats directories, so it runs on the task
// executor rather than the UI thread, and its answer comes back as
// an event like any other. The blocking call sits directly in the
Expand Down
Loading
Loading