Skip to main content

rpi_cli/
app.rs

1//! CLI entry orchestrator. The `main(args)` function that:
2//!
3//! 1. Parses argv ([`crate::args::parse_args`]).
4//! 2. Handles `--help`/`--version` + parse errors + startup warnings.
5//! 3. Reads piped stdin (non-TTY ⇒ treat as the initial prompt text).
6//! 4. Expands `@file` attachments into an initial-message text block
7//!    ([`build_initial_message`]).
8//! 5. Resolves the provider + model + thinking level ([`crate::provider::resolve`]).
9//! 6. Builds the harness ([`crate::session::build`]).
10//! 7. Resolves the effective run mode ([`crate::args::resolve_mode`]) and
11//!    dispatches to [`crate::modes`] (`print`/`json`/`interactive`), mapping the
12//!    outcome to an exit code.
13//!
14//! `@file` expansion covers text files; images are detected but not attached to
15//! the prompt — the harness `prompt_text` accepts images, but this path does not
16//! yet wire an image processor. Binary/non-UTF-8 files error.
17//!
18use std::io::{IsTerminal, Read};
19use std::path::Path;
20
21use rpi_ai::types::{ImageContent, ImageContentType};
22
23use crate::args::{parse_args, print_help, print_version, resolve_mode, Args, RunMode};
24use crate::provider::{resolve_with_extensions, ResolveError};
25use crate::session::{build_prepared, prepare_extensions, BuildError};
26use crate::startup_diagnostics::{Phase, StartupSpan};
27
28/// The exit code for a usage/parse error. (TS `main.ts` uses `process.exit(1)`
29/// for most error paths; v1 distinguishes usage errors with the conventional
30/// `2` so scripts can tell "bad invocation" from "run failed".)
31pub const EXIT_USAGE: i32 = 2;
32/// The exit code for a runtime failure (model-resolution, harness-build, or
33/// run failure). Mirrors TS `process.exitCode` set from `runPrintMode`.
34pub const EXIT_RUNTIME: i32 = 1;
35/// The exit code when an extension **vetoes** startup at a lifecycle event
36/// (e.g. a `BeforeTuiStart` handler returns [`rpi_plugin_sdk::EVENT_HANDLER_ABORT`]).
37/// Distinct from [`EXIT_RUNTIME`] so scripts can tell "an extension refused to
38/// start" from "the run itself failed".
39pub const EXIT_VETOED: i32 = 3;
40
41/// Read a long-flag value from argv, supporting both `--flag <value>` and
42/// `--flag=value`, without disturbing the normal parser. Used for the early
43/// `--connect` interception.
44fn take_flag_value(argv: &[String], flag: &str) -> Option<String> {
45    let prefix = format!("{flag}=");
46    let mut iter = argv.iter();
47    while let Some(arg) = iter.next() {
48        if let Some(value) = arg.strip_prefix(&prefix) {
49            return Some(value.to_string());
50        }
51        if arg == flag {
52            return iter.next().cloned();
53        }
54    }
55    None
56}
57
58/// Resolve the `--connect` auth token: the `--token` flag wins, then the
59/// `RPI_SERVER_TOKEN` environment variable (ignoring empty/whitespace values).
60fn resolve_connect_token(argv: &[String]) -> Option<String> {
61    take_flag_value(argv, "--token").or_else(|| {
62        std::env::var("RPI_SERVER_TOKEN")
63            .ok()
64            .map(|value| value.trim().to_string())
65            .filter(|value| !value.is_empty())
66    })
67}
68
69/// The v1 CLI entry point. Mirrors TS `export async function main(args)`.
70///
71/// Returns the process exit code (0 = success). The binary wrapper
72/// ([`crate::bin`] / `src/bin/rpi.rs`) calls this under a tokio runtime and
73/// `std::process::exit`s with the returned code.
74pub async fn run() -> i32 {
75    // Startup profiling wrapper: RPI_TIMING=1 records namespace timings and
76    // flushes them to stderr once the run completes, regardless of exit path.
77    crate::timings::reset(crate::timings::TimingNamespace::Main);
78    let code = run_inner().await;
79    crate::timings::print_timings();
80    code
81}
82
83async fn run_inner() -> i32 {
84    let startup = StartupSpan::start(Phase::StartupToHarness);
85    // argv[0] is the program name; skip it (TS `main(args)` receives the same,
86    // already sliced by the Node CLI entry).
87    let mut argv: Vec<String> = std::env::args().skip(1).collect();
88    // Shared Host control is an explicit independent entry point: never hydrate
89    // ambient durable/session/provider/extension state or interpret it as a prompt.
90    if argv.first().map(String::as_str) == Some("host") {
91        return crate::host::cli::run(&argv[1..]).await;
92    }
93    if let Some(first) = argv.first_mut() {
94        if first == "--native-host" || first.starts_with("--native-host=") {
95            *first = first.replacen("--native-host", "--host", 1);
96            return crate::host::area_entry::run(&argv).await;
97        }
98    }
99    if matches!(argv.as_slice(), [host, restore] if host == "--host" && restore == "--restore-areas")
100    {
101        return crate::host::area_entry::run(&argv).await;
102    }
103    if argv
104        .iter()
105        .take_while(|arg| *arg != "--")
106        .any(|arg| arg == "--session-preview" || arg.starts_with("--session-preview="))
107    {
108        return crate::session_preview::run(&argv);
109    }
110    if let Err(error) = crate::native_durable::experimental_epoch::early_check(&argv) {
111        eprintln!("error: {error}");
112        return EXIT_USAGE;
113    }
114    // Safe old-host negotiation: callers discover this flag through --help
115    // first. Never fall through to prompts, remote clients, resource commands,
116    // trust, migration, leases, credentials, providers or DLL startup.
117    if argv
118        .iter()
119        .any(|a| a == "--resource-capabilities" || a.starts_with("--resource-capabilities="))
120    {
121        if argv.len() != 1 || argv[0] != "--resource-capabilities" {
122            println!(
123                "{}",
124                serde_json::json!({"version":1,"success":false,"error":"--resource-capabilities must be used alone"})
125            );
126            return EXIT_USAGE;
127        }
128        match serde_json::to_string(&crate::resource_selection::capabilities()) {
129            Ok(profile) if profile.len() < crate::resource_selection::MAX_CAPABILITIES_BYTES => {
130                println!("{profile}");
131                return 0;
132            }
133            _ => {
134                println!(
135                    "{}",
136                    serde_json::json!({"version":1,"success":false,"error":"capability profile exceeds bound"})
137                );
138                return EXIT_RUNTIME;
139            }
140        }
141    }
142
143    if argv
144        .iter()
145        .any(|arg| arg == "--resource-session-read" || arg.starts_with("--resource-session-read="))
146    {
147        return crate::saved_session_read::run(&argv).await;
148    }
149
150    if argv.first().map(String::as_str) == Some("__rpi_dev_cleanup") {
151        return crate::dev_extension::run_cleanup_helper(&argv[1..]);
152    }
153
154    #[cfg(unix)]
155    if argv
156        .first()
157        .is_some_and(|arg| arg == crate::local_host::DAEMON_COMMAND)
158    {
159        return crate::local_host::run_daemon_command(&argv[1..]).await;
160    }
161
162    // ---- `rpi --connect <addr>` — pure remote client ----
163    // Intercepted before any provider / harness / session / extension work so
164    // the client holds no local agent resources at all: it only connects to a
165    // running `rpi --server` and renders the remote transcript.
166    if let Some(addr) = take_flag_value(&argv, "--connect") {
167        if argv
168            .iter()
169            .any(|arg| arg == "--host" || arg.starts_with("--host="))
170        {
171            eprintln!("error: --host cannot be combined with --connect");
172            return EXIT_USAGE;
173        }
174        if argv
175            .iter()
176            .any(|arg| arg == "--mini" || arg.starts_with("--mini="))
177        {
178            eprintln!("error: --mini cannot be combined with --connect");
179            return EXIT_USAGE;
180        }
181        let token = resolve_connect_token(&argv);
182        return crate::remote::tui::run(&addr, token.as_deref()).await;
183    }
184
185    // Normalize the CLI flag into RPI_OFFLINE so early-dispatch subcommands and
186    // the regular parsed path all observe the same process-wide gate.
187    crate::args::normalize_offline_mode(&argv);
188
189    #[cfg(target_os = "macos")]
190    if argv.is_empty() && std::io::stdin().is_terminal() && std::io::stdout().is_terminal() {
191        if let Some(code) = crate::host::area_entry::run_default_terminal().await {
192            return code;
193        }
194    }
195
196    // `rpi dev` wraps the normal CLI: consume only development-specific
197    // options, then pass every remaining argument through the regular parser.
198    let dev_command = argv.first().map(String::as_str);
199    let dev_options = if matches!(dev_command, Some("dev" | "dev-local")) {
200        match crate::dev_extension::parse_args(&argv[1..]) {
201            Ok(options) if options.help => {
202                crate::dev_extension::print_help();
203                return 0;
204            }
205            Ok(mut options) => {
206                if dev_command == Some("dev-local") {
207                    options.local_only = true;
208                }
209                argv = options.passthrough.clone();
210                Some(options)
211            }
212            Err(error) => {
213                eprintln!("error: {error}");
214                crate::dev_extension::print_help();
215                return EXIT_USAGE;
216            }
217        }
218    } else {
219        None
220    };
221
222    // ---- Top-level subcommand dispatch (before flag parsing) ----
223    // These are top-level subcommands (mirrors TS `runAuthCommand` / the
224    // `handlePackageCommand` / `handleConfigCommand` routing in `main.ts`);
225    // dispatching them here avoids them being misparsed as prompts. The set is
226    // fixed and each handler has a different shape (sync vs async, extra argv
227    // inspection), so a `match` on the first argument — not a trait registry —
228    // is the right level of abstraction (and matches the `match mode { .. }`
229    // dispatch at the end of this function).
230    match argv.first().map(String::as_str) {
231        Some("auth") => {
232            let cwd = std::env::current_dir().unwrap_or_else(|_| Path::new(".").to_path_buf());
233            let args = crate::args::parse_args(&argv[1..]);
234            if !args.errors.is_empty() {
235                for error in &args.errors {
236                    eprintln!("error: {error}");
237                }
238                return EXIT_USAGE;
239            }
240            let trusted = crate::session::resolve_project_trust(&args, &cwd);
241            let _resource_leases = match crate::resource_management::host_leases(&cwd) {
242                Ok(leases) => leases,
243                Err(error) => {
244                    eprintln!("error: {error}");
245                    return EXIT_RUNTIME;
246                }
247            };
248            let extension_session = crate::session::load_extensions(
249                &crate::config::AgentHome::process(),
250                &args,
251                &cwd,
252                trusted,
253                None,
254            );
255            return crate::auth::run_with_extensions(&argv[1..], extension_session.snapshot_arc())
256                .await;
257        }
258        Some("events") => return crate::events::run(&argv[1..]).await,
259        Some("session") => return crate::session_gc::run(&argv[1..]).await,
260        Some("update") => return crate::updates::run_self_update(&argv[1..]),
261        Some("install") => return crate::install::run_async(&argv[1..]).await,
262        Some("uninstall") => return crate::install::uninstall(&argv[1..]),
263        Some("extension") => return crate::packages::run_extension(&argv[1..]),
264        Some("resource") => return crate::resource_management::run(&argv[1..]),
265        Some("package") => return crate::packages::run(&argv[1..]),
266        // These historical aliases are intentionally rejected instead of
267        // falling through to the prompt path.
268        Some(removed @ ("pi-package" | "pi-update" | "install-pi" | "uninstall-pi")) => {
269            eprintln!(
270                "error: `rpi {removed}` is not available; use `rpi package`, `rpi install`, or `rpi update`."
271            );
272            return EXIT_USAGE;
273        }
274        // // Never a working invocation; the same fall-through applies.
275        // Some("self-update") => {
276        //     eprintln!("error: unknown command `self-update`; use `rpi update`");
277        //     return EXIT_USAGE;
278        // }
279        _ => {}
280    }
281
282    let mut parsed = parse_args(&argv);
283    crate::timings::time("args parsed", crate::timings::TimingNamespace::Main);
284
285    // ---- Parsed startup stages ----
286    if let Some(code) = handle_parse_short_circuits(&parsed) {
287        return code;
288    }
289
290    if parsed.host.is_some() {
291        if dev_options.is_some() {
292            eprintln!("error: --host cannot be combined with dev/dev-local");
293            return EXIT_USAGE;
294        }
295        #[cfg(unix)]
296        {
297            return crate::local_host::run(parsed).await;
298        }
299        #[cfg(not(unix))]
300        {
301            eprintln!("error: --host requires Unix-domain sockets");
302            return EXIT_USAGE;
303        }
304    }
305
306    if dev_options.is_some()
307        && (parsed.resource_config.is_some() || parsed.resource_transition.is_some())
308    {
309        eprintln!(
310            "error: --resource-config is restart-only and cannot be combined with dev/dev-local"
311        );
312        return EXIT_USAGE;
313    }
314    let cwd = match resolve_cwd() {
315        Ok(cwd) => cwd,
316        Err(code) => return code,
317    };
318    // ---- Legacy-layout migration (flat ~/.rpi → ~/.rpi/agent/) ----
319    // Best-effort; never blocks startup. Skipped when RPI_CODING_AGENT_DIR is
320    // set (an explicit override is its own layout).
321    let _ = crate::config::migrate_legacy_layout();
322    crate::timings::time("config migrated", crate::timings::TimingNamespace::Main);
323
324    if let Some(code) = export_if_requested(&parsed) {
325        return code;
326    }
327
328    // `--list-models` is intentionally handled before credentials, session
329    // restoration, and harness construction. It is a catalog inspection
330    // command, so it must work for a newly installed user who has not
331    // authenticated yet.
332    if let Some(search) = parsed.list_models.as_deref() {
333        return list_models(search, &parsed, &cwd).await;
334    }
335
336    // Dev compilation is deferred until after native session resource preflight.
337
338    // `-r/--resume` is an interactive picker, unlike `-c/--continue` which
339    // immediately opens the latest session. Resolve the picker result before
340    // building the harness so cancelling does not create or modify a session.
341    if let Some(code) = resolve_resume(&mut parsed, &cwd).await {
342        return code;
343    }
344
345    emit_startup_warnings(&parsed);
346
347    // ---- stdin ownership ----
348    // Do NOT drain stdin when the run is an RPC/server session: stdin is the
349    // JSONL command channel there (a spawned `rpi --mode rpc` child reads its
350    // commands from stdin), so consuming it up-front would leave the protocol
351    // loop nothing to read. `--mode rpc` and `--server` both select RunMode::Rpc.
352    //
353    // NOTE: the actual `read_piped_stdin()` call is deferred until *after*
354    // extension load (below), because a plugin may `declare
355    // {"ownsStdio":true}` — an ACP/MCP-style stdio server that owns this
356    // process's stdin/stdout. Draining stdin before that plugin's `register`
357    // runs would deadlock it (and the host would swallow the client handshake).
358    // `--mode rpc`/`--server` are a static pre-computation (no plugin needed);
359    // the plugin claim is only known once `build()` has loaded extensions.
360    let wants_rpc_channel =
361        parsed.mode == crate::args::Mode::Rpc || parsed.unknown_flags.contains_key("server");
362
363    // ---- @file attachments → text (TS processFileArguments, text branch only) ----
364    // Deliberately runs BEFORE the cwd adoption below: `@file` paths come from
365    // the shell that launched `rpi`, so they resolve against the launch cwd no
366    // matter which directory the restored session points at.
367    let (file_text, file_images) = match process_file_args(&parsed.file_args, &cwd) {
368        Ok(t) => t,
369        Err(msg) => {
370            eprintln!("error: {msg}");
371            return EXIT_USAGE;
372        }
373    };
374
375    // ---- restored-session working directory (adopted before any resource load) ----
376    // A session records the cwd it was created in; restoring one must return
377    // the agent to that directory, because every tool resolves relative paths
378    // against the run's cwd. Adopting it here — before trust resolution,
379    // extension preparation, and the harness build — makes the whole run (tool
380    // env, system prompt, context files, extensions, footer) agree on one
381    // working directory. `@file` args above intentionally stay launch-cwd.
382    //
383    // The session ROOT is frozen first, for the same reason: settings and
384    // `RPI_CODING_AGENT_SESSION_DIR` may change while extensions load, and the
385    // adopted cwd belongs to another project's tree. Pinning the resolved root
386    // into `args` makes `prepare_extensions` and the build below read one root.
387    let session_root = crate::session::configured_session_dir(&parsed, &cwd);
388    parsed.session_dir = Some(session_root.clone());
389    let mut startup_notices: Vec<String> = Vec::new();
390    // The peek and the build both derive their selection from this frozen root,
391    // so they can never inspect one session and open another.
392    let selection = crate::session::select_session_in_dir(&parsed, session_root);
393    let cwd_lookup = StartupSpan::start(Phase::CwdLookup);
394    let restored_cwd = crate::session::peek_restored_session_cwd(&selection, &cwd).await;
395    cwd_lookup.finish();
396    // Pin the session the peek resolved: `-c` re-lists the directory when the
397    // build runs, and another `rpi` may have written a newer session in
398    // between. Adopting one session's directory while opening another would
399    // put the tools in a directory the opened conversation never used, which is
400    // the failure this adoption exists to prevent.
401    if let Some(restored) = &restored_cwd {
402        crate::session::pin_restored_selection(&mut parsed, restored);
403    }
404    let launch_cwd = cwd;
405    let cwd = match &restored_cwd {
406        Some(restored) => match &restored.adopted {
407            Some(adopted) => {
408                // Adopting a directory is a behaviour change the user must see:
409                // tools, context files, and extensions all switch projects.
410                // `-c` in the project the session was created in adopts nothing
411                // (`adopted` IS `launch_cwd`), so the note is only produced for
412                // a real move.
413                startup_notices.extend(crate::session_cwd::moved_session_cwd_note(
414                    &launch_cwd,
415                    adopted,
416                ));
417                adopted.clone()
418            }
419            None => {
420                startup_notices.push(crate::session_cwd::missing_session_cwd_note(
421                    &restored.recorded,
422                    &launch_cwd,
423                ));
424                launch_cwd.clone()
425            }
426        },
427        None => launch_cwd.clone(),
428    };
429
430    // ---- provider + model resolution ----
431    // Trust is resolved against the (possibly adopted) cwd: a session recorded
432    // in another project must not inherit the launch directory's trust decision.
433    let project_trusted = crate::session::resolve_project_trust(&parsed, &cwd);
434    if !project_trusted && !crate::session_cwd::is_same_directory(&cwd, &launch_cwd) {
435        startup_notices.push(crate::session_cwd::untrusted_session_cwd_note(&cwd));
436    }
437    // Development preflight precedes prepare_extensions: protect its registry
438    // reads at orchestration too; the fact reader itself stays non-mutating.
439    let _dev_resource_leases = if dev_options.is_some() {
440        match crate::resource_management::host_leases(&cwd) {
441            Ok(leases) => Some(leases),
442            Err(error) => {
443                eprintln!("error: {error}");
444                return EXIT_RUNTIME;
445            }
446        }
447    } else {
448        None
449    };
450    // Reject a bound exact session before dev can build or stage any code.
451    if dev_options.is_some() {
452        if let Err(error) =
453            crate::session::preflight_extension_startup(&parsed, &cwd, project_trusted)
454        {
455            print_build_error(&error);
456            return EXIT_RUNTIME;
457        }
458    }
459    let dev_extension = match prepare_dev_extension(dev_options.as_ref(), &launch_cwd, &mut parsed)
460    {
461        Ok(extension) => extension,
462        Err(code) => return code,
463    };
464    let extension_prepare = StartupSpan::start(Phase::ExtensionPrepare);
465    let prepared = match prepare_extensions(
466        &crate::config::AgentHome::process(),
467        &parsed,
468        &cwd,
469        project_trusted,
470    ) {
471        Ok(prepared) => prepared,
472        Err(error) => {
473            print_build_error(&error);
474            return EXIT_RUNTIME;
475        }
476    };
477    extension_prepare.finish();
478    let model_resolve = StartupSpan::start(Phase::ModelResolve);
479    let resolved = match resolve_with_extensions(
480        &crate::config::AgentHome::process(),
481        &parsed,
482        &cwd,
483        project_trusted,
484        &prepared.extension_session,
485    ) {
486        Ok(r) => r,
487        Err(e) => {
488            print_resolve_error(&e);
489            return match e {
490                ResolveError::NoApiKey { .. } | ResolveError::Config(_) => EXIT_USAGE,
491                _ => EXIT_RUNTIME,
492            };
493        }
494    };
495
496    model_resolve.finish();
497    for warning in &resolved.compat_warnings {
498        eprintln!("warning: models.json: {warning}");
499    }
500
501    // `--models <patterns>`: persist the Ctrl+P cycle scope to settings.json
502    // (the same set `/scoped-models` edits). Each pattern matches catalog ids
503    // case-insensitively; unmatched patterns are reported so a typo doesn't
504    // silently empty the cycle.
505    if let Some(patterns) = &parsed.models {
506        let model_catalog = crate::provider::authenticated_catalog(&resolved);
507        let mut matched: Vec<String> = Vec::new();
508        for p in patterns {
509            let hits: Vec<String> = model_catalog
510                .iter()
511                .filter(|m| m.id.eq_ignore_ascii_case(p))
512                .map(|m| m.id.clone())
513                .collect();
514            if hits.is_empty() {
515                eprintln!("warning: --models pattern \"{p}\" matched no model");
516            }
517            matched.extend(hits);
518        }
519        let mut settings = crate::settings::load_settings().unwrap_or_default();
520        settings.scoped_models = if matched.is_empty() {
521            None
522        } else {
523            Some(matched)
524        };
525        if let Err(e) = crate::settings::save_settings(&settings) {
526            eprintln!("warning: could not save --models scope: {e}");
527        }
528    }
529
530    // ---- harness build ----
531    let harness_build = StartupSpan::start(Phase::HarnessBuild);
532    let (harness, event_rx, mut reload_context) = match build_prepared(
533        &crate::config::AgentHome::process(),
534        &resolved,
535        &parsed,
536        &cwd,
537        project_trusted,
538        prepared,
539    )
540    .await
541    {
542        Ok(triple) => triple,
543        Err(e) => {
544            print_build_error(&e);
545            return EXIT_RUNTIME;
546        }
547    };
548    harness_build.finish();
549    startup.finish();
550    reload_context.dev_extension = dev_extension;
551    // ---- post-load stdin claim + initial message ----
552    // Extensions are loaded by `build()` (above). A plugin may have declared
553    // `{"ownsStdio":true}`: this process's stdio belongs to it (an ACP/MCP stdio
554    // server), so the host must neither drain stdin nor run a prompt/TUI mode
555    // that writes to stdout. Only now — after load — do we know. `--mode
556    // rpc`/`--server` already skipped the drain via `wants_rpc_channel`.
557    let stdio_claimed = reload_context
558        .extension_session
559        .lock()
560        .map(|session| session.owns_stdio())
561        .unwrap_or(false);
562    let web_requested = match parsed.unknown_flags.get("web") {
563        Some(serde_json::Value::Bool(value)) => *value,
564        Some(serde_json::Value::String(value)) => {
565            !value.is_empty() && !value.eq_ignore_ascii_case("false")
566        }
567        _ => false,
568    };
569    let web_registered = reload_context
570        .extension_session
571        .lock()
572        .ok()
573        .and_then(|session| {
574            session
575                .snapshot()
576                .map(|snapshot| snapshot.flags().iter().any(|flag| flag.name == "web"))
577        })
578        .unwrap_or(false);
579    if web_requested && (!web_registered || !stdio_claimed) {
580        eprintln!("error: --web requires the rpi-web server extension; it is missing, disabled, or failed to load.\nInstall it with: rpi install rpi-web --github pi-rust/rpi-extension\nThen restart with: rpi --web");
581        return EXIT_USAGE;
582    }
583    let stdio_lifecycle = reload_context
584        .extension_session
585        .lock()
586        .ok()
587        .and_then(|session| session.action_bridge())
588        .map(|bridge| bridge.stdio_lifecycle());
589    if let Some(lifecycle) = &stdio_lifecycle {
590        if let Err(error) = lifecycle.validate() {
591            eprintln!("error: {error}");
592            return EXIT_RUNTIME;
593        }
594    }
595    let stdin_text = if wants_rpc_channel || stdio_claimed {
596        None
597    } else {
598        read_piped_stdin()
599    };
600
601    // ---- initial message + extra messages (TS buildInitialMessage) ----
602    let file_text_opt = if file_text.is_empty() {
603        None
604    } else {
605        Some(file_text.as_str())
606    };
607    let (initial, extra) = build_initial_message(&parsed, stdin_text.as_deref(), file_text_opt);
608    let initial = initial.or_else(|| (!file_images.is_empty()).then(String::new));
609
610    // ---- mode dispatch (TS resolveAppMode → runPrintMode / InteractiveMode / runRpcMode) ----
611    let stdin_is_tty = std::io::stdin().is_terminal();
612    let stdout_is_tty = std::io::stdout().is_terminal();
613    let mode = resolve_mode(&parsed, stdin_is_tty, stdout_is_tty);
614
615    // TS downgrades interactive → print when piped stdin is present.
616    let mode = if matches!(mode, RunMode::Interactive) && stdin_text.is_some() {
617        RunMode::Print
618    } else {
619        mode
620    };
621
622    // Debug/testing escape hatch: RPI_FORCE_TUI=1 forces interactive mode
623    // (for testing the TUI in non-TTY environments).
624    let mode = if std::env::var("RPI_FORCE_TUI")
625        .map(|v| v == "1")
626        .unwrap_or(false)
627    {
628        RunMode::Interactive
629    } else {
630        mode
631    };
632
633    // A plugin that claimed stdio owns this process's stdin/stdout: force the
634    // headless Rpc lifecycle (dispatch startup events, then wait for completion)
635    // and let the plugin's own protocol server read/write stdio. This is
636    // authoritative — it must win over TTY detection and RPI_FORCE_TUI,
637    // otherwise the host would start a TUI/print run that writes to a stream the
638    // plugin owns.
639    let mode = if stdio_claimed { RunMode::Rpc } else { mode };
640    // ---- startup notices (restored-session cwd) ----
641    // The interactive TUI renders them as transcript notes (they must survive
642    // into the alternate screen); headless modes print them to stderr like the
643    // other startup warnings.
644    if matches!(mode, RunMode::Interactive) {
645        reload_context.startup_notices = startup_notices;
646    } else {
647        for notice in &startup_notices {
648            eprintln!("warning: {notice}");
649        }
650    }
651
652    let dev_cleanup = reload_context.dev_extension.clone();
653    let dev_watcher = if matches!(mode, RunMode::Interactive) {
654        reload_context
655            .dev_extension
656            .as_ref()
657            .and_then(|extension| extension.start_watcher(reload_context.mailbox.clone()))
658    } else {
659        None
660    };
661
662    let model_catalog = || {
663        reload_context
664            .catalog
665            .read()
666            .unwrap_or_else(|error| error.into_inner())
667            .clone()
668    };
669    let exit_code = match mode {
670        RunMode::Print => {
671            // Print mode only consumes the completed reply. Keeping the receiver
672            // alive buffers unread snapshots of the growing streamed message.
673            drop(event_rx);
674            crate::modes::print(&harness, &parsed, initial, &extra, file_images).await
675        }
676        RunMode::Json => {
677            crate::modes::json(
678                &harness,
679                &parsed,
680                initial.clone(),
681                &extra,
682                file_images.clone(),
683                Some(event_rx),
684            )
685            .await
686        }
687        RunMode::Interactive => {
688            crate::modes::interactive(
689                &harness,
690                Some(event_rx),
691                &parsed,
692                model_catalog(),
693                crate::modes::InteractiveStartup {
694                    initial: initial.clone(),
695                    extra_messages: &extra,
696                    initial_images: file_images.clone(),
697                    theme: if parsed.no_themes {
698                        None
699                    } else {
700                        parsed.theme.as_deref().or(resolved.theme.as_deref())
701                    },
702                    no_themes: parsed.no_themes,
703                },
704                &reload_context,
705            )
706            .await
707        }
708        RunMode::Rpc => {
709            // Headless lifecycle (P0): no TUI, but a session still starts/ends —
710            // extensions (e.g. rpi-server) auto-start on SessionStart and clean
711            // up on SessionShutdown, exactly as in interactive mode. This is why
712            // `rpi --server` works headless: the SessionStart hook fires and the
713            // extension brings up the TCP server.
714            let before_start = StartupSpan::start(Phase::BeforeStartHooks);
715            let veto = crate::session::dispatch_session_event_async(
716                &reload_context,
717                rpi_plugin_sdk::EventTag::BeforeTuiStart,
718            )
719            .await;
720            before_start.finish();
721            if let Some(reason) = veto {
722                eprintln!("[rpi] startup vetoed by extension: {reason}");
723                EXIT_VETOED
724            } else {
725                let session_start = StartupSpan::start(Phase::SessionStartHooks);
726                if let Some(reason) = crate::session::dispatch_session_event_async(
727                    &reload_context,
728                    rpi_plugin_sdk::EventTag::SessionStart,
729                )
730                .await
731                {
732                    tracing::warn!(
733                        "[rpi] extension vetoed SessionStart (headless, advisory): {reason}"
734                    );
735                }
736                session_start.finish();
737
738                let code = if parsed.unknown_flags.contains_key("server") || stdio_claimed {
739                    // Server mode OR a plugin-claimed stdio server: the extension
740                    // owns the process's I/O. Wait for its completion or Ctrl+C,
741                    // then dispatch SessionShutdown before unloading plugins.
742                    eprintln!(
743                        "[rpi] running in headless mode (no TUI); extension owns stdio; Ctrl+C to stop"
744                    );
745                    if stdio_claimed {
746                        let lifecycle = stdio_lifecycle
747                            .as_ref()
748                            .expect("stdio owner requires an action bridge");
749                        tokio::select! {
750                            code = lifecycle.wait() => code,
751                            _ = tokio::signal::ctrl_c() => 0,
752                        }
753                    } else {
754                        let _ = tokio::signal::ctrl_c().await;
755                        0
756                    }
757                } else {
758                    // `--mode rpc`: JSONL command loop over stdio — the
759                    // server-side agent that rpi-server spawns and that
760                    // `rpi --connect` talks to. The extension `UiDialog`
761                    // mailbox is bridged over the same channel so a permission
762                    // gate can ask the client mid-run.
763                    // Release the extension session lock before the RPC loop awaits.
764                    // ToolCall hooks need the same lock to dispatch approvals.
765                    let oauth_snapshot = {
766                        let session = reload_context.extension_session.lock().unwrap();
767                        session.snapshot_arc()
768                    };
769                    crate::modes::rpc_with_durable_home(
770                        &harness,
771                        Some(event_rx),
772                        model_catalog(),
773                        crate::modes::RpcOptions {
774                            ui_dialog: reload_context.ui_dialog.clone(),
775                            oauth_snapshot,
776                            extension_session: Some(reload_context.extension_session.clone()),
777                            message_updates: parsed.rpc_message_updates,
778                            native_durable: parsed.native_durable,
779                            home: reload_context.home.clone(),
780                        },
781                    )
782                    .await
783                };
784
785                if let Some(reason) = crate::session::dispatch_session_event_async(
786                    &reload_context,
787                    rpi_plugin_sdk::EventTag::SessionShutdown,
788                )
789                .await
790                {
791                    tracing::warn!(
792                        "[rpi] extension vetoed SessionShutdown (ignored, closing): {reason}"
793                    );
794                }
795                code
796            }
797        }
798    };
799
800    if let Some(dev) = &dev_cleanup {
801        dev.stop_watcher();
802    }
803    if let Some(watcher) = dev_watcher {
804        let _ = watcher.join();
805    }
806    drop(reload_context);
807    drop(harness);
808    if let Some(dev) = dev_cleanup {
809        dev.cleanup();
810    }
811    exit_code
812}
813
814fn handle_parse_short_circuits(parsed: &Args) -> Option<i32> {
815    // ---- --help / --version short-circuit (before any heavy work) ----
816    if parsed.help {
817        print_help();
818        return Some(0);
819    }
820    if parsed.version {
821        print_version();
822        return Some(0);
823    }
824
825    // ---- Parse errors → help + usage exit ----
826    if !parsed.errors.is_empty() {
827        for err in &parsed.errors {
828            eprintln!("error: {err}");
829        }
830        eprintln!();
831        print_help();
832        return Some(EXIT_USAGE);
833    }
834
835    None
836}
837
838fn resolve_cwd() -> Result<std::path::PathBuf, i32> {
839    std::env::current_dir().map_err(|error| {
840        eprintln!("error: could not determine the current directory: {error}");
841        EXIT_USAGE
842    })
843}
844
845fn export_if_requested(parsed: &Args) -> Option<i32> {
846    let input = parsed.export.as_deref()?;
847    let output = parsed
848        .messages
849        .first()
850        .map(Path::new)
851        .map(Path::to_path_buf)
852        .unwrap_or_else(|| {
853            let stem = input
854                .file_stem()
855                .and_then(|value| value.to_str())
856                .unwrap_or("session");
857            Path::new(&format!("rpi-session-{stem}.html")).to_path_buf()
858        });
859
860    match crate::export::export_file(input, &output) {
861        Ok(()) => {
862            println!("Exported to: {}", output.display());
863            Some(0)
864        }
865        Err(error) => {
866            eprintln!("error: {error}");
867            Some(EXIT_RUNTIME)
868        }
869    }
870}
871
872fn prepare_dev_extension(
873    options: Option<&crate::dev_extension::DevOptions>,
874    cwd: &Path,
875    parsed: &mut Args,
876) -> Result<Option<std::sync::Arc<crate::dev_extension::DevExtension>>, i32> {
877    let Some(options) = options else {
878        return Ok(None);
879    };
880
881    match crate::dev_extension::DevExtension::detect(cwd, options) {
882        Ok(extension) => match extension.prepare_initial(parsed) {
883            Ok(extension) => Ok(Some(extension)),
884            Err(error) => {
885                eprintln!("error: initial extension preparation failed: {error}");
886                Err(EXIT_RUNTIME)
887            }
888        },
889        Err(error) => {
890            // No Cargo cdylib found: degrade to skills-only mode.
891            eprintln!("dev: {error}");
892            eprintln!("dev: no Cargo cdylib found; running in skills-only mode");
893            parsed.no_extensions = true;
894            parsed.extensions_dir.clear();
895            parsed.extension.clear();
896            if options.local_only {
897                parsed.dev_local_only = true;
898            }
899            Ok(None)
900        }
901    }
902}
903
904async fn resolve_resume(parsed: &mut Args, cwd: &Path) -> Option<i32> {
905    if !parsed.resume {
906        return None;
907    }
908    if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() {
909        eprintln!("error: --resume requires an interactive terminal");
910        return Some(EXIT_USAGE);
911    }
912
913    let session_dir = crate::session::configured_session_dir(parsed, cwd);
914    match crate::resume_picker::select_in_dir(cwd, &session_dir).await {
915        Ok(Some(id)) => {
916            parsed.resume = false;
917            parsed.session = Some(id);
918            parsed.session_dir = Some(session_dir);
919            None
920        }
921        Ok(None) => Some(0),
922        Err(error) => {
923            eprintln!("error: {error}");
924            Some(EXIT_RUNTIME)
925        }
926    }
927}
928
929pub(crate) fn emit_startup_warnings(parsed: &Args) {
930    // ---- Startup warnings (ignored-but-recognized flags) ----
931    if parsed.verbose {
932        for warn in &parsed.ignored {
933            eprintln!("warning: {warn}");
934        }
935    }
936    if parsed.no_themes && parsed.theme.is_some() {
937        eprintln!("warning: --no-themes overrides --theme; using the built-in default theme");
938    }
939}
940
941/// Print the merged model catalog, optionally filtered by a case-insensitive
942/// fuzzy-ish substring over provider, id, and display name.
943async fn list_models(search: &str, args: &Args, cwd: &Path) -> i32 {
944    let trusted = crate::session::resolve_project_trust(args, cwd);
945    let prepared =
946        match prepare_extensions(&crate::config::AgentHome::process(), args, cwd, trusted) {
947            Ok(prepared) => prepared,
948            Err(error) => {
949                print_build_error(&error);
950                return EXIT_RUNTIME;
951            }
952        };
953    let manifests = crate::provider::manifests_from_session(&prepared.extension_session);
954    let home = crate::config::AgentHome::process();
955    let catalog = match crate::provider::catalog_with_diagnostics(&home, &manifests) {
956        Ok((models, warnings)) => {
957            for warning in warnings {
958                eprintln!("warning: models.json: {warning}");
959            }
960            models
961        }
962        Err(error) => {
963            eprintln!("warning: could not load models.json: {error}");
964            Vec::new()
965        }
966    };
967    let needle = search.trim().to_ascii_lowercase();
968    let mut models: Vec<_> = catalog
969        .into_iter()
970        .filter(|model| {
971            needle.is_empty()
972                || format!("{} {} {}", model.provider, model.id, model.name)
973                    .to_ascii_lowercase()
974                    .contains(&needle)
975        })
976        .collect();
977    if models.is_empty() {
978        if needle.is_empty() {
979            println!("{}", crate::auth_guidance::no_models_available_message());
980        } else {
981            println!("No models matching \"{search}\"");
982        }
983        return 0;
984    }
985
986    fn format_tokens(value: u64) -> String {
987        if value >= 1_000_000 {
988            let whole = value.is_multiple_of(1_000_000);
989            if whole {
990                format!("{}M", value / 1_000_000)
991            } else {
992                format!("{:.1}M", value as f64 / 1_000_000.0)
993            }
994        } else if value >= 1_000 {
995            let whole = value.is_multiple_of(1_000);
996            if whole {
997                format!("{}K", value / 1_000)
998            } else {
999                format!("{:.1}K", value as f64 / 1_000.0)
1000            }
1001        } else {
1002            value.to_string()
1003        }
1004    }
1005
1006    let rows: Vec<_> = models
1007        .drain(..)
1008        .map(|model| {
1009            let images = model
1010                .input
1011                .iter()
1012                .any(|input| matches!(input, rpi_ai::InputModality::Image));
1013            (
1014                model.provider,
1015                model.id,
1016                format_tokens(model.context_window),
1017                format_tokens(model.max_tokens),
1018                if model.reasoning { "yes" } else { "no" }.to_string(),
1019                if images { "yes" } else { "no" }.to_string(),
1020            )
1021        })
1022        .collect();
1023    let widths = (
1024        rows.iter().map(|r| r.0.len()).max().unwrap_or(8).max(8),
1025        rows.iter().map(|r| r.1.len()).max().unwrap_or(5).max(5),
1026        rows.iter().map(|r| r.2.len()).max().unwrap_or(7).max(7),
1027        rows.iter().map(|r| r.3.len()).max().unwrap_or(7).max(7),
1028        rows.iter().map(|r| r.4.len()).max().unwrap_or(8).max(8),
1029        rows.iter().map(|r| r.5.len()).max().unwrap_or(6).max(6),
1030    );
1031    println!(
1032        "{:provider$}  {:model$}  {:context$}  {:max_out$}  {:thinking$}  {:images$}",
1033        "provider",
1034        "model",
1035        "context",
1036        "max-out",
1037        "thinking",
1038        "images",
1039        provider = widths.0,
1040        model = widths.1,
1041        context = widths.2,
1042        max_out = widths.3,
1043        thinking = widths.4,
1044        images = widths.5,
1045    );
1046    for row in rows {
1047        println!(
1048            "{:provider$}  {:model$}  {:context$}  {:max_out$}  {:thinking$}  {:images$}",
1049            row.0,
1050            row.1,
1051            row.2,
1052            row.3,
1053            row.4,
1054            row.5,
1055            provider = widths.0,
1056            model = widths.1,
1057            context = widths.2,
1058            max_out = widths.3,
1059            thinking = widths.4,
1060            images = widths.5,
1061        );
1062    }
1063    0
1064}
1065
1066/// Read piped stdin into a string. Mirrors TS `readPipedStdin`: returns `None`
1067/// when stdin is a TTY (interactive), else the trimmed stdin text (empty ⇒
1068/// `None`).
1069///
1070/// NOTE: if stdin is *not* a TTY but no bytes arrive (e.g. `pi < /dev/null`),
1071/// this returns `None` (empty), which is what TS does too (`data.trim() || undefined`).
1072fn read_piped_stdin() -> Option<String> {
1073    // Debug/testing escape hatch: RPI_SKIP_STDIN=1 skips reading piped stdin
1074    // (avoids blocking on non-TTY stdin in automated environments).
1075    if std::env::var("RPI_SKIP_STDIN")
1076        .map(|v| v == "1")
1077        .unwrap_or(false)
1078    {
1079        return None;
1080    }
1081    if std::io::stdin().is_terminal() {
1082        return None;
1083    }
1084    let mut buf = String::new();
1085    match std::io::stdin().read_to_string(&mut buf) {
1086        Ok(_) => {
1087            let trimmed = buf.trim();
1088            if trimmed.is_empty() {
1089                None
1090            } else {
1091                Some(trimmed.to_string())
1092            }
1093        }
1094        Err(_) => None,
1095    }
1096}
1097
1098/// Expand `@file` attachments into prompt text. Mirrors the *text* branch of
1099/// TS `processFileArguments`: each readable text file is wrapped in
1100/// `<file name="...">\n<contents>\n</file>\n` and concatenated.
1101///
1102/// Paths are resolved relative to `cwd` (the TS uses `resolve(readPath, cwd)`).
1103pub(crate) fn process_file_args(
1104    file_args: &[std::path::PathBuf],
1105    cwd: &Path,
1106) -> Result<(String, Vec<ImageContent>), String> {
1107    let mut text = String::new();
1108    let mut images = Vec::new();
1109    for rel in file_args {
1110        let abs = if rel.is_absolute() {
1111            rel.clone()
1112        } else {
1113            cwd.join(rel)
1114        };
1115        if !abs.exists() {
1116            return Err(format!("file not found: {}", abs.display()));
1117        }
1118        let bytes = std::fs::read(&abs)
1119            .map_err(|e| format!("could not read file {}: {e}", abs.display()))?;
1120        if let Some(image) = image_content_from_bytes(&bytes) {
1121            images.push(image);
1122        } else {
1123            let content = String::from_utf8(bytes).map_err(|_| {
1124                format!(
1125                    "file is not valid UTF-8 text or a supported image: {}",
1126                    abs.display()
1127                )
1128            })?;
1129            text.push_str(&format!(
1130                "<file name=\"{}\">\n{}\n</file>\n",
1131                abs.display(),
1132                content
1133            ));
1134        }
1135    }
1136    Ok((text, images))
1137}
1138
1139pub(crate) fn image_content_from_path(path: &Path) -> Result<Option<ImageContent>, String> {
1140    let bytes =
1141        std::fs::read(path).map_err(|e| format!("could not read file {}: {e}", path.display()))?;
1142    Ok(image_content_from_bytes(&bytes))
1143}
1144
1145fn image_content_from_bytes(bytes: &[u8]) -> Option<ImageContent> {
1146    let mime_type = rpi_tools::detect_supported_image_mime_type(bytes)?;
1147    Some(ImageContent {
1148        kind: ImageContentType,
1149        data: rpi_tools::encode_base64(bytes).into(),
1150        mime_type: mime_type.to_string(),
1151    })
1152}
1153
1154/// Build the initial prompt + the remaining extra messages. Mirrors TS
1155/// `buildInitialMessage`: `[stdinContent, fileText, messages[0]].join("")` is
1156/// the initial message; `messages[1..]` are the follow-up prompts.
1157///
1158/// Returns `(initial: Option<String>, extra: Vec<String>)`.
1159fn build_initial_message(
1160    parsed: &Args,
1161    stdin: Option<&str>,
1162    file_text: Option<&str>,
1163) -> (Option<String>, Vec<String>) {
1164    let mut extra = parsed.messages.clone();
1165    let mut parts: Vec<String> = Vec::new();
1166    if let Some(s) = stdin {
1167        parts.push(s.to_string());
1168    }
1169    if let Some(t) = file_text {
1170        parts.push(t.to_string());
1171    }
1172    // Pull the first positional message into the initial prompt (TS `.shift()`).
1173    if !extra.is_empty() {
1174        parts.push(extra.remove(0));
1175    }
1176    let initial = if parts.is_empty() {
1177        None
1178    } else {
1179        Some(parts.join(""))
1180    };
1181    (initial, extra)
1182}
1183
1184#[cfg(unix)]
1185pub(crate) fn mini_input(
1186    args: &mut Args,
1187    file_text: String,
1188    images: Vec<ImageContent>,
1189) -> crate::mini::Input {
1190    let mut messages = std::mem::take(&mut args.messages).into_iter();
1191    let mut parts = read_piped_stdin()
1192        .into_iter()
1193        .chain((!file_text.is_empty()).then_some(file_text))
1194        .chain(messages.next());
1195    let initial = parts.next().map(|mut text| {
1196        for part in parts {
1197            text.push_str(&part);
1198        }
1199        text
1200    });
1201    let prompts = initial
1202        .or_else(|| (!images.is_empty()).then(String::new))
1203        .into_iter()
1204        .chain(messages)
1205        .collect();
1206    crate::mini::Input { prompts, images }
1207}
1208
1209/// Format a model-resolution error with env-specific guidance.
1210pub(crate) fn resolve_error_message(e: &ResolveError) -> String {
1211    match e {
1212        ResolveError::NoApiKey { hint } => {
1213            format!("error: {e}\n\nProvide credentials via one of: {hint}.")
1214        }
1215        ResolveError::Config(_) => format!(
1216            "error: {e}\n\nCheck ~/.rpi/auth.json / ~/.rpi/models.json (set RPI_CODING_AGENT_DIR to relocate)."
1217        ),
1218        _ => format!("error: {e}"),
1219    }
1220}
1221
1222fn print_resolve_error(e: &ResolveError) {
1223    eprintln!("{}", resolve_error_message(e));
1224}
1225
1226/// Print a harness-build error with flag-specific guidance for restore requests.
1227fn print_build_error(e: &BuildError) {
1228    match e {
1229        BuildError::SessionNotFound { .. } => {
1230            eprintln!("error: {e}");
1231            eprintln!();
1232            eprintln!("List saved sessions with the /session command in interactive mode.");
1233        }
1234        _ => eprintln!("error: {e}"),
1235    }
1236}
1237
1238#[cfg(test)]
1239mod tests {
1240    use super::*;
1241    use crate::args::Args;
1242
1243    #[test]
1244    fn take_flag_value_supports_both_spellings() {
1245        let argv = vec![
1246            "--connect".to_string(),
1247            "127.0.0.1:9899".to_string(),
1248            "--token".to_string(),
1249            "abc".to_string(),
1250        ];
1251        assert_eq!(
1252            take_flag_value(&argv, "--connect").as_deref(),
1253            Some("127.0.0.1:9899")
1254        );
1255        assert_eq!(take_flag_value(&argv, "--token").as_deref(), Some("abc"));
1256        assert_eq!(take_flag_value(&argv, "--missing"), None);
1257
1258        let inline = vec!["--connect=1.2.3.4:1".to_string()];
1259        assert_eq!(
1260            take_flag_value(&inline, "--connect").as_deref(),
1261            Some("1.2.3.4:1")
1262        );
1263    }
1264
1265    #[test]
1266    fn connect_token_prefers_the_flag_over_the_env_var() {
1267        // The flag wins regardless of any RPI_SERVER_TOKEN in the environment.
1268        let argv = vec!["--token".to_string(), "flag-token".to_string()];
1269        assert_eq!(resolve_connect_token(&argv).as_deref(), Some("flag-token"));
1270    }
1271
1272    #[test]
1273    fn build_initial_combines_stdin_file_and_first_message() {
1274        let mut args = Args::default();
1275        args.messages = vec!["first".into(), "second".into(), "third".into()];
1276        let (initial, extra) =
1277            build_initial_message(&args, Some("stdin-text"), Some("<file>...</file>"));
1278        assert_eq!(initial.as_deref(), Some("stdin-text<file>...</file>first"));
1279        assert_eq!(extra, vec!["second".to_string(), "third".to_string()]);
1280    }
1281
1282    #[test]
1283    fn build_initial_with_no_messages_uses_stdin_and_file_only() {
1284        let args = Args::default();
1285        let (initial, extra) =
1286            build_initial_message(&args, Some("only-stdin"), Some("<file>x</file>"));
1287        assert_eq!(initial.as_deref(), Some("only-stdin<file>x</file>"));
1288        assert!(extra.is_empty());
1289    }
1290
1291    #[test]
1292    fn build_initial_none_when_all_empty() {
1293        let args = Args::default();
1294        let (initial, extra) = build_initial_message(&args, None, None);
1295        assert!(initial.is_none());
1296        assert!(extra.is_empty());
1297    }
1298
1299    #[test]
1300    fn build_initial_shifts_only_first_message() {
1301        let mut args = Args::default();
1302        args.messages = vec!["a".into(), "b".into()];
1303        let (initial, extra) = build_initial_message(&args, None, None);
1304        assert_eq!(initial.as_deref(), Some("a"));
1305        assert_eq!(extra, vec!["b".to_string()]);
1306    }
1307
1308    #[test]
1309    fn process_file_args_attaches_supported_images() {
1310        let dir = tempfile::tempdir().unwrap();
1311        let path = dir.path().join("image.bin");
1312        let mut png = vec![137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13];
1313        png.extend_from_slice(b"IHDR");
1314        png.extend_from_slice(&[0; 13]);
1315        std::fs::write(&path, png).unwrap();
1316        let (text, images) = process_file_args(&[path], dir.path()).unwrap();
1317        assert!(text.is_empty());
1318        assert_eq!(images.len(), 1);
1319        assert_eq!(images[0].mime_type, "image/png");
1320        assert!(!images[0].data.is_empty());
1321    }
1322
1323    #[test]
1324    fn image_content_from_path_reports_supported_mime() {
1325        let dir = tempfile::tempdir().unwrap();
1326        let path = dir.path().join("drop.png");
1327        let mut png = vec![137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13];
1328        png.extend_from_slice(b"IHDR");
1329        png.extend_from_slice(&[0; 13]);
1330        std::fs::write(&path, png).unwrap();
1331        let image = image_content_from_path(&path).unwrap().unwrap();
1332        assert_eq!(image.mime_type, "image/png");
1333    }
1334}