Skip to main content

vtcode_core/terminal_setup/terminals/
iterm2.rs

1//! iTerm2 configuration instruction generator.
2//!
3//! Most iTerm2 settings live in plist files, which are complex to modify
4//! programmatically, so this module generates manual setup instructions for
5//! them. The tab icon is the exception: iTerm2 loads Dynamic Profiles from
6//! plain JSON files with no restart, so the icon profile below is fully
7//! installable from code.
8
9use std::path::{Path, PathBuf};
10
11use crate::terminal_setup::detector::TerminalType;
12use crate::terminal_setup::features::multiline;
13use anyhow::{Context, Result};
14use vtcode_commons::VtCodePaths;
15use vtcode_commons::terminal_detection::{
16    ITERM2_DYNAMIC_PROFILE_FILENAME, ITERM2_ICON_MODE_CUSTOM, ITERM2_PROFILE_NAME, installed_iterm2_profile_path,
17    iterm2_dynamic_profiles_dir,
18};
19use vtcode_commons::ui_protocol::AppIconPreference;
20
21/// Generate iTerm2 setup instructions (manual configuration required)
22pub fn generate_config(features: &[crate::terminal_setup::detector::TerminalFeature]) -> Result<String> {
23    let mut instructions = vec![
24        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━".to_string(),
25        "  iTerm2 Manual Configuration Instructions".to_string(),
26        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━".to_string(),
27        String::new(),
28        "iTerm2 requires manual configuration via the GUI.".to_string(),
29        "Follow these steps to configure each feature:".to_string(),
30        String::new(),
31    ];
32
33    for (i, feature) in features.iter().enumerate() {
34        match feature {
35            crate::terminal_setup::detector::TerminalFeature::Multiline => {
36                instructions.push(format!("{}. MULTILINE INPUT (Shift+Enter)", i + 1));
37                instructions.push(String::new());
38                let multiline_instructions = multiline::generate_config(TerminalType::ITerm2)?;
39                instructions.push(multiline_instructions);
40                instructions.push(String::new());
41            }
42            crate::terminal_setup::detector::TerminalFeature::CopyPaste => {
43                instructions.push(format!("{}. COPY/PASTE INTEGRATION", i + 1));
44                instructions.push(String::new());
45                instructions.push("1. Open iTerm2 Preferences (Cmd+,)".to_string());
46                instructions.push("2. Go to General → Selection".to_string());
47                instructions.push("3. Enable 'Copy to pasteboard on selection'".to_string());
48                instructions.push("4. Go to Pointer tab".to_string());
49                instructions.push("5. Set middle-click action to 'Paste from Clipboard'".to_string());
50                instructions.push(String::new());
51            }
52            crate::terminal_setup::detector::TerminalFeature::ShellIntegration => {
53                instructions.push(format!("{}. SHELL INTEGRATION", i + 1));
54                instructions.push(String::new());
55                instructions.push("1. Open iTerm2 Preferences (Cmd+,)".to_string());
56                instructions.push("2. Go to Profiles → General".to_string());
57                instructions.push("3. Under 'Command', select your shell".to_string());
58                instructions.push("4. iTerm2's shell integration will auto-install on first launch".to_string());
59                instructions.push("5. Or manually install: curl -L https://iterm2.com/shell_integration/install_shell_integration.sh | bash".to_string());
60                instructions.push(String::new());
61            }
62            crate::terminal_setup::detector::TerminalFeature::ThemeSync => {
63                instructions.push(format!("{}. THEME SYNCHRONIZATION", i + 1));
64                instructions.push(String::new());
65                instructions.push("1. Open iTerm2 Preferences (Cmd+,)".to_string());
66                instructions.push("2. Go to Profiles → Colors".to_string());
67                instructions.push("3. Choose a color preset or customize manually".to_string());
68                instructions.push("4. VT Code theme colors can be manually configured here".to_string());
69                instructions.push(String::new());
70            }
71            crate::terminal_setup::detector::TerminalFeature::Notifications => {
72                instructions.push(format!("{}. SYSTEM NOTIFICATIONS", i + 1));
73                instructions.push(String::new());
74                instructions.push("1. Open iTerm2 Preferences (Cmd+,)".to_string());
75                instructions.push("2. Navigate to Profiles → Terminal".to_string());
76                instructions.push(
77                    "3. Enable 'Silence bell' and Filter Alerts → 'Send escape sequence-generated alerts'".to_string(),
78                );
79                instructions.push("4. Set your preferred notification delay".to_string());
80                instructions.push(
81                    "5. For shell integration notifications, consider using tools like terminal-notifier".to_string(),
82                );
83                instructions.push(String::new());
84            }
85        }
86    }
87
88    instructions.push("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━".to_string());
89    instructions.push("After configuration, restart iTerm2 for changes to take effect.".to_string());
90    instructions.push("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━".to_string());
91
92    Ok(instructions.join("\n"))
93}
94
95/// Stable identity of the shipped iTerm2 profile so reinstalls overwrite
96/// instead of duplicating it.
97pub const PROFILE_GUID: &str = "1FC21C70-F2B1-4F0F-BB03-D1AE12EF900E";
98
99/// Filename of the installed profile artwork under the data root.
100pub const PROFILE_ICON_FILENAME: &str = "vtcode-app-icon.png";
101
102/// Retired artwork filename from earlier installs; removed opportunistically
103/// on install so the data dir does not keep stale bytes forever.
104const LEGACY_PROFILE_ICON_FILENAME: &str = "vtcode-profile-120.png";
105
106/// Embedded 128px profile artwork so installed binaries work without a repo
107/// checkout. Resolved through the `build.rs` embedded-assets pipeline so the
108/// published crate compiles without reaching outside its package root.
109const PROFILE_ICON_LIGHT_BYTES: &[u8] =
110    include_bytes!(concat!(env!("OUT_DIR"), "/embedded_assets/resources/icons/vtcode-app-light-128.png"));
111const PROFILE_ICON_DARK_BYTES: &[u8] =
112    include_bytes!(concat!(env!("OUT_DIR"), "/embedded_assets/resources/icons/vtcode-app-dark-128.png"));
113const PROFILE_ICON_CLEAR_BYTES: &[u8] =
114    include_bytes!(concat!(env!("OUT_DIR"), "/embedded_assets/resources/icons/vtcode-app-clear-128.png"));
115const PROFILE_ICON_TINTED_BYTES: &[u8] =
116    include_bytes!(concat!(env!("OUT_DIR"), "/embedded_assets/resources/icons/vtcode-app-tinted-128.png"));
117
118/// Artwork bytes for a concrete icon variant.
119///
120/// Callers pass [`resolve_artwork`] output: unresolved `Dynamic`/`Unknown`
121/// input falls back to the light tile rather than failing the install.
122pub fn artwork_bytes(preference: AppIconPreference) -> &'static [u8] {
123    match preference {
124        AppIconPreference::Dark => PROFILE_ICON_DARK_BYTES,
125        AppIconPreference::Clear => PROFILE_ICON_CLEAR_BYTES,
126        AppIconPreference::Tinted => PROFILE_ICON_TINTED_BYTES,
127        AppIconPreference::Light | AppIconPreference::Dynamic | AppIconPreference::Unknown => PROFILE_ICON_LIGHT_BYTES,
128    }
129}
130
131/// Reject empty artwork: published-crate, Nix, and docs.rs builds embed an
132/// empty placeholder (see `build.rs`), which must never be installed as the
133/// tab icon.
134fn require_artwork_available(bytes: &'static [u8]) -> Result<&'static [u8]> {
135    if bytes.is_empty() {
136        anyhow::bail!("icon artwork is unavailable in this build; reinstall from a full release")
137    } else {
138        Ok(bytes)
139    }
140}
141
142/// Resolve an icon preference to concrete artwork against a theme id.
143/// `Dynamic` (and `Unknown`) follow the theme's own light/dark mode;
144/// explicit variants pin their art.
145pub fn resolve_artwork_with_theme(preference: AppIconPreference, theme_id: &str) -> AppIconPreference {
146    preference.resolve(!crate::ui::theme::is_light_theme(theme_id))
147}
148
149/// Resolve an icon preference to concrete artwork against the active CLI theme.
150pub fn resolve_artwork(preference: AppIconPreference) -> AppIconPreference {
151    resolve_artwork_with_theme(preference, &crate::ui::theme::active_theme_id())
152}
153
154/// Outcome of [`install_profile_icon`].
155pub struct ProfileIconInstallReport {
156    /// Dynamic-profile JSON that iTerm2 loads live.
157    pub profile_path: PathBuf,
158    /// Installed artwork referenced by the profile.
159    pub icon_path: PathBuf,
160}
161
162/// Render the dynamic-profile JSON pointing at an absolute icon path.
163///
164/// Unspecified attributes inherit live from the default profile, so
165/// switching to this profile changes only the tab icon. There is no
166/// `Automatic Profile Switching` rule: VT Code switches to this profile
167/// explicitly at TUI startup and reverts to the session's original profile
168/// on exit, so automatic reversion (which requires iTerm2 Shell Integration)
169/// is neither needed nor reliable.
170pub fn dynamic_profile_json(icon_path: &Path) -> Result<String> {
171    let document = serde_json::json!({
172        "Profiles": [{
173            "Name": ITERM2_PROFILE_NAME,
174            "Guid": PROFILE_GUID,
175            "Icon": ITERM2_ICON_MODE_CUSTOM,
176            "Custom Icon Path": icon_path.to_string_lossy(),
177        }],
178    });
179    serde_json::to_string_pretty(&document).context("failed to serialize iTerm2 dynamic profile")
180}
181
182/// Absolute destination of the installed icon under a data root.
183pub fn installed_icon_path(data_dir: &Path) -> PathBuf {
184    data_dir.join("icons").join(PROFILE_ICON_FILENAME)
185}
186
187/// Install the VT Code iTerm2 profile icon (macOS only, idempotent).
188///
189/// Pass [`resolve_artwork`] output: unresolved `Dynamic`/`Unknown` input
190/// falls back to the light tile (see [`artwork_bytes`]). Writes only VT
191/// Code-owned files: the artwork under the data root and `vtcode.json`
192/// under iTerm2's DynamicProfiles directory. Existing profiles are never
193/// modified; deleting `vtcode.json` uninstalls.
194pub fn install_profile_icon(
195    home: &Path,
196    data_dir: &Path,
197    preference: AppIconPreference,
198) -> Result<ProfileIconInstallReport> {
199    if !cfg!(target_os = "macos") {
200        anyhow::bail!("iTerm2 profile icons are only available on macOS");
201    }
202    let icon_path = installed_icon_path(data_dir);
203    if let Some(parent) = icon_path.parent() {
204        std::fs::create_dir_all(parent)
205            .with_context(|| format!("failed to create icon directory {}", parent.display()))?;
206    }
207    std::fs::write(&icon_path, require_artwork_available(artwork_bytes(preference))?)
208        .with_context(|| format!("failed to write icon {}", icon_path.display()))?;
209    if let Some(parent) = icon_path.parent() {
210        let _removed = std::fs::remove_file(parent.join(LEGACY_PROFILE_ICON_FILENAME));
211    }
212    let profiles_dir = iterm2_dynamic_profiles_dir(home);
213    std::fs::create_dir_all(&profiles_dir).with_context(|| format!("failed to create {}", profiles_dir.display()))?;
214    let profile_path = profiles_dir.join(ITERM2_DYNAMIC_PROFILE_FILENAME);
215    let json = dynamic_profile_json(&icon_path)?;
216    std::fs::write(&profile_path, json).with_context(|| format!("failed to write {}", profile_path.display()))?;
217    Ok(ProfileIconInstallReport { profile_path, icon_path })
218}
219
220/// Resolve default install locations: home directory and canonical data root.
221pub fn default_install_paths() -> Result<(PathBuf, PathBuf)> {
222    let home = dirs::home_dir().context("failed to determine home directory")?;
223    let data_dir = VtCodePaths::resolve()?.data_dir().to_path_buf();
224    Ok((home, data_dir))
225}
226
227/// Guidance lines pointing at the automatic installer and the manual fallback.
228pub fn profile_icon_instructions() -> Vec<String> {
229    vec![
230        "TAB ICON (profile image):".to_string(),
231        "1. Run `/terminal-setup install-iterm2-icon` to install the VT Code tab icon automatically.".to_string(),
232        "2. If a tab is stuck showing the VT Code icon after exit, run `/terminal-setup reset-iterm2-icon`."
233            .to_string(),
234        "3. Switch artwork with `/terminal-setup icon light|dark|clear|tinted|dynamic` (persist via `ui.app_icon`)."
235            .to_string(),
236        "4. Or set it manually: Settings → Profiles → General → Icon → Custom, then pick a PNG from resources/icons/."
237            .to_string(),
238    ]
239}
240
241/// Fail closed unless the session runs under iTerm2. Returns false after
242/// reporting, so callers just early-return. Reset-only: it emits a
243/// live-session profile switch, which is meaningless outside iTerm2.
244fn check_iterm2_terminal(renderer: &mut crate::utils::ansi::AnsiRenderer) -> Result<bool> {
245    use crate::utils::ansi::MessageStyle;
246
247    let terminal = TerminalType::detect()?;
248    if matches!(terminal, TerminalType::ITerm2) {
249        return Ok(true);
250    }
251    renderer.line(MessageStyle::Error, &format!("Tab icon commands need iTerm2 (detected {}).", terminal.name()))?;
252    Ok(false)
253}
254
255/// Fail closed off macOS. Returns false after reporting, so callers just
256/// early-return.
257///
258/// Install/show/switch only write VT Code-owned files (show only reads
259/// theme state), so they accept any terminal on macOS: a stale iTerm2
260/// profile can be repaired from Rex, Ghostty, or anywhere else without
261/// launching iTerm2 first.
262fn check_macos(renderer: &mut crate::utils::ansi::AnsiRenderer) -> Result<bool> {
263    use crate::utils::ansi::MessageStyle;
264
265    if cfg!(target_os = "macos") {
266        return Ok(true);
267    }
268    renderer.line(MessageStyle::Error, "Tab icon commands need macOS (iTerm2 profiles are macOS-only).")?;
269    Ok(false)
270}
271
272/// Parsed `/terminal-setup icon` subcommand.
273#[derive(Debug, PartialEq, Eq)]
274pub enum TerminalIconCommand {
275    /// Report the Dynamic resolution without writing files.
276    Show,
277    /// Install one variant immediately.
278    Switch(AppIconPreference),
279}
280
281/// Parse `icon [variant]` args (case- and whitespace-tolerant). Returns
282/// `None` for anything that is not an icon command, including unknown
283/// variants, so callers fall through to usage.
284pub fn parse_terminal_icon_command(args: &str) -> Option<TerminalIconCommand> {
285    let lowered = args.trim().to_ascii_lowercase();
286    let parts: Vec<&str> = lowered.split_whitespace().collect();
287    match parts.as_slice() {
288        ["icon"] => Some(TerminalIconCommand::Show),
289        ["icon", "light"] => Some(TerminalIconCommand::Switch(AppIconPreference::Light)),
290        ["icon", "dark"] => Some(TerminalIconCommand::Switch(AppIconPreference::Dark)),
291        ["icon", "clear"] => Some(TerminalIconCommand::Switch(AppIconPreference::Clear)),
292        ["icon", "tinted"] => Some(TerminalIconCommand::Switch(AppIconPreference::Tinted)),
293        ["icon", "dynamic"] => Some(TerminalIconCommand::Switch(AppIconPreference::Dynamic)),
294        _ => None,
295    }
296}
297
298/// Run the non-interactive profile-icon install with progress output.
299///
300/// Installs the `Dynamic` artwork (resolved against the active CLI theme).
301/// Fails closed off macOS; works from any terminal since it only writes
302/// VT Code-owned files, never existing profiles.
303pub fn run_profile_icon_install(renderer: &mut crate::utils::ansi::AnsiRenderer) -> Result<()> {
304    run_terminal_icon_switch(renderer, AppIconPreference::Dynamic)
305}
306
307/// Report the Dynamic artwork resolution without writing files.
308///
309/// Fails closed off macOS like the installer: the advice only applies
310/// to the iTerm2 dynamic profile.
311pub fn run_terminal_icon_show(renderer: &mut crate::utils::ansi::AnsiRenderer) -> Result<()> {
312    use crate::utils::ansi::MessageStyle;
313
314    if !check_macos(renderer)? {
315        return Ok(());
316    }
317    let theme_id = crate::ui::theme::active_theme_id();
318    let resolved = resolve_artwork(AppIconPreference::Dynamic);
319    renderer.line(
320        MessageStyle::Info,
321        &format!(
322            "With `ui.app_icon = \"dynamic\"` (default), the tab icon follows the active theme ('{theme_id}', {} artwork). Switch now with `/terminal-setup icon light|dark|clear|tinted|dynamic`, or pin via `ui.app_icon`.",
323            resolved.id(),
324        ),
325    )?;
326    Ok(())
327}
328
329/// Install one icon variant immediately.
330///
331/// Explicit variants apply for this session (persist via `ui.app_icon`);
332/// `Dynamic` is the default and needs no persistence note. Fails closed
333/// off macOS; works from any terminal since it only writes VT Code-owned
334/// files, never existing profiles.
335pub fn run_terminal_icon_switch(
336    renderer: &mut crate::utils::ansi::AnsiRenderer,
337    preference: AppIconPreference,
338) -> Result<()> {
339    use crate::utils::ansi::MessageStyle;
340
341    if !check_macos(renderer)? {
342        return Ok(());
343    }
344    let (home, data_dir) = default_install_paths()?;
345    let resolved = resolve_artwork(preference);
346    renderer.line(MessageStyle::Info, &format!("Installing VT Code iTerm2 tab icon ({} artwork)...", resolved.id()))?;
347    let report = install_profile_icon(&home, &data_dir, resolved)?;
348    renderer.line(MessageStyle::Status, &format!("✓ Profile written: {}", report.profile_path.display()))?;
349    renderer.line(MessageStyle::Status, &format!("✓ Icon installed: {}", report.icon_path.display()))?;
350    renderer.line(
351        MessageStyle::Info,
352        "Open a new iTerm2 tab so it picks up the profile; the logo replaces the generic tab glyph while VT Code runs.",
353    )?;
354    if !matches!(preference, AppIconPreference::Dynamic | AppIconPreference::Unknown) {
355        renderer.line(
356            MessageStyle::Info,
357            &format!("Applied for this session. Persist with `ui.app_icon = \"{}\"`.", preference.id()),
358        )?;
359    }
360    Ok(())
361}
362
363/// Reset the current session's iTerm2 profile to its original name.
364///
365/// Repair path for tabs left stuck on the `VT Code` icon profile by an older
366/// build that switched profile without reverting. Emits `OSC 1337;SetProfile=`
367/// with the session's original profile (from `ITERM_PROFILE`, falling back to
368/// iTerm2's `Default`). Fails closed outside iTerm2 or off macOS.
369pub fn run_profile_icon_reset(renderer: &mut crate::utils::ansi::AnsiRenderer) -> Result<()> {
370    use crate::utils::ansi::MessageStyle;
371    use std::io::Write as _;
372    use vtcode_commons::ansi_codes::set_iterm2_profile;
373    use vtcode_commons::terminal_detection::{ITERM2_DEFAULT_PROFILE_NAME, original_iterm2_profile_name};
374
375    if !check_iterm2_terminal(renderer)? {
376        return Ok(());
377    }
378    let target = original_iterm2_profile_name().unwrap_or_else(|| ITERM2_DEFAULT_PROFILE_NAME.to_string());
379    let mut stdout = std::io::stdout();
380    stdout
381        .write_all(set_iterm2_profile(&target).as_bytes())
382        .with_context(|| "failed to write iTerm2 profile reset sequence")?;
383    stdout
384        .flush()
385        .with_context(|| "failed to flush iTerm2 profile reset sequence")?;
386    renderer.line(MessageStyle::Status, &format!("✓ Session profile reset to \"{target}\"."))?;
387    Ok(())
388}
389
390/// Ensure the iTerm2 profile icon is installed, returning the install
391/// report when this call wrote files.
392///
393/// Best-effort first-run path: skips silently off macOS, outside iTerm2,
394/// or under tmux, and rewrites the profile when the installed JSON or
395/// artwork drifts from the shipped copy so icon/profile updates propagate.
396/// `Dynamic` resolves against the active CLI theme, so a theme-mode change
397/// across launches refreshes the tab icon on the next startup.
398pub fn ensure_profile_icon(preference: AppIconPreference) -> Result<Option<ProfileIconInstallReport>> {
399    if !cfg!(target_os = "macos") {
400        return Ok(None);
401    }
402    let (home, data_dir) = default_install_paths()?;
403    let iterm_session = std::env::var("ITERM_SESSION_ID").is_ok();
404    let tmux_session = std::env::var("TMUX").is_ok();
405    let resolved = resolve_artwork(preference);
406    ensure_profile_icon_at(&home, &data_dir, iterm_session, tmux_session, resolved)
407}
408
409/// Testable core of [`ensure_profile_icon`] with explicit paths, environment
410/// flags, and resolved artwork preference (no process-environment reads, no
411/// global roots, no theme-global reads).
412pub fn ensure_profile_icon_at(
413    home: &Path,
414    data_dir: &Path,
415    iterm_session: bool,
416    tmux_session: bool,
417    preference: AppIconPreference,
418) -> Result<Option<ProfileIconInstallReport>> {
419    if !cfg!(target_os = "macos") || !iterm_session || tmux_session {
420        return Ok(None);
421    }
422    let profile_path = installed_iterm2_profile_path(home);
423    let icon_path = installed_icon_path(data_dir);
424    let expected_artwork = artwork_bytes(preference);
425    let icon_fresh = std::fs::read(&icon_path)
426        .map(|bytes| bytes == expected_artwork)
427        .unwrap_or(false);
428    let profile_current = std::fs::read_to_string(&profile_path)
429        .ok()
430        .zip(dynamic_profile_json(&icon_path).ok())
431        .is_some_and(|(installed, expected)| installed == expected);
432    if profile_current && icon_fresh {
433        return Ok(None);
434    }
435    install_profile_icon(home, data_dir, preference).map(Some)
436}
437
438#[cfg(test)]
439mod tests {
440    use super::*;
441    use crate::terminal_setup::detector::TerminalFeature;
442
443    #[test]
444    fn test_generate_instructions() {
445        let features = vec![TerminalFeature::Multiline, TerminalFeature::CopyPaste];
446        let instructions = generate_config(&features).unwrap();
447        assert!(instructions.contains("iTerm2"));
448        assert!(instructions.contains("Preferences"));
449        assert!(instructions.contains("MULTILINE"));
450        assert!(instructions.contains("COPY/PASTE"));
451    }
452
453    #[test]
454    fn dynamic_profile_json_points_at_given_icon() {
455        let first = dynamic_profile_json(Path::new("/data/vtcode/icons/vtcode-app-icon.png")).unwrap();
456        let second = dynamic_profile_json(Path::new("/other/icons/vtcode-app-icon.png")).unwrap();
457        assert_ne!(first, second);
458
459        let value: serde_json::Value = serde_json::from_str(&first).unwrap();
460        let profile = &value["Profiles"][0];
461        assert_eq!(profile["Name"], ITERM2_PROFILE_NAME);
462        assert_eq!(profile["Guid"], PROFILE_GUID);
463        assert_eq!(profile["Icon"], ITERM2_ICON_MODE_CUSTOM);
464        assert_eq!(profile["Custom Icon Path"], "/data/vtcode/icons/vtcode-app-icon.png");
465        assert!(
466            profile.get("Automatic Profile Switching").is_none(),
467            "reversion is explicit now; the dynamic profile must not carry an APS rule"
468        );
469    }
470
471    #[test]
472    fn artwork_bytes_differ_per_variant_and_are_non_empty() {
473        let variants = [
474            AppIconPreference::Light,
475            AppIconPreference::Dark,
476            AppIconPreference::Clear,
477            AppIconPreference::Tinted,
478        ];
479        for preference in variants {
480            let bytes = artwork_bytes(preference);
481            assert!(!bytes.is_empty(), "{preference:?} artwork must be embedded");
482            assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n", "{preference:?} artwork must be a PNG");
483            // IHDR is always the first chunk: width/height sit at bytes 16..24.
484            // Fails when a wrong-size master (e.g. a 512px file) is embedded.
485            assert_eq!(&bytes[12..16], b"IHDR", "{preference:?} artwork must start with IHDR");
486            let width = u32::from_be_bytes(bytes[16..20].try_into().unwrap());
487            let height = u32::from_be_bytes(bytes[20..24].try_into().unwrap());
488            assert_eq!((width, height), (128, 128), "{preference:?} artwork must be 128x128");
489        }
490        for (index, first) in variants.iter().enumerate() {
491            for second in &variants[index + 1..] {
492                assert_ne!(artwork_bytes(*first), artwork_bytes(*second), "{first:?} vs {second:?}");
493            }
494        }
495        assert_eq!(artwork_bytes(AppIconPreference::Dynamic), artwork_bytes(AppIconPreference::Light));
496        assert_eq!(artwork_bytes(AppIconPreference::Unknown), artwork_bytes(AppIconPreference::Light));
497    }
498
499    #[test]
500    fn resolve_artwork_pins_explicit_variants_and_follows_theme_for_dynamic() {
501        use vtcode_commons::ui_protocol::AppIconPreference;
502
503        for theme_id in ["mono", "vitesse-light", "unknown-theme"] {
504            for pinned in [
505                AppIconPreference::Light,
506                AppIconPreference::Dark,
507                AppIconPreference::Clear,
508                AppIconPreference::Tinted,
509            ] {
510                assert_eq!(resolve_artwork_with_theme(pinned, theme_id), pinned, "{pinned:?} on {theme_id}");
511            }
512        }
513        assert_eq!(resolve_artwork_with_theme(AppIconPreference::Dynamic, "mono"), AppIconPreference::Dark);
514        assert_eq!(resolve_artwork_with_theme(AppIconPreference::Dynamic, "vitesse-light"), AppIconPreference::Light);
515        assert_eq!(
516            resolve_artwork_with_theme(AppIconPreference::Unknown, "vitesse-light"),
517            resolve_artwork_with_theme(AppIconPreference::Dynamic, "vitesse-light")
518        );
519    }
520
521    #[test]
522    fn parse_terminal_icon_command_accepts_show_and_each_variant() {
523        use vtcode_commons::ui_protocol::AppIconPreference;
524
525        assert_eq!(parse_terminal_icon_command("icon"), Some(TerminalIconCommand::Show));
526        for (raw, expected) in [
527            ("light", AppIconPreference::Light),
528            ("dark", AppIconPreference::Dark),
529            ("clear", AppIconPreference::Clear),
530            ("tinted", AppIconPreference::Tinted),
531            ("dynamic", AppIconPreference::Dynamic),
532        ] {
533            assert_eq!(
534                parse_terminal_icon_command(&format!("icon {raw}")),
535                Some(TerminalIconCommand::Switch(expected)),
536                "{raw}"
537            );
538        }
539    }
540
541    #[test]
542    fn parse_terminal_icon_command_is_case_and_whitespace_tolerant() {
543        use vtcode_commons::ui_protocol::AppIconPreference;
544
545        for raw in ["  ICON  ", "Icon", "iCoN"] {
546            assert_eq!(parse_terminal_icon_command(raw), Some(TerminalIconCommand::Show), "{raw:?}");
547        }
548        for raw in ["icon  light", "ICON\tDARK\n", "  icon dynamic  "] {
549            let parsed = parse_terminal_icon_command(raw).expect("variant parses");
550            assert!(matches!(parsed, TerminalIconCommand::Switch(_)), "{raw:?}");
551        }
552        assert_eq!(
553            parse_terminal_icon_command("icon  light"),
554            Some(TerminalIconCommand::Switch(AppIconPreference::Light))
555        );
556        assert_eq!(
557            parse_terminal_icon_command("ICON\tDARK\n"),
558            Some(TerminalIconCommand::Switch(AppIconPreference::Dark))
559        );
560    }
561
562    #[test]
563    fn parse_terminal_icon_command_rejects_unknown_and_extra_args() {
564        for raw in [
565            "",
566            "icons",
567            "icon holographic",
568            "icon light dark",
569            "icon-light",
570            "install-iterm2-icon",
571        ] {
572            assert_eq!(parse_terminal_icon_command(raw), None, "{raw:?}");
573        }
574    }
575
576    #[test]
577    fn require_artwork_available_rejects_empty_placeholders() {
578        assert!(require_artwork_available(b"").is_err());
579        assert_eq!(require_artwork_available(b"x").unwrap(), b"x");
580    }
581
582    #[cfg(target_os = "macos")]
583    #[test]
584    fn install_profile_icon_writes_artwork_and_profile() {
585        let home = tempfile::tempdir().unwrap();
586        let data = tempfile::tempdir().unwrap();
587
588        let first = install_profile_icon(home.path(), data.path(), AppIconPreference::Dark).unwrap();
589        assert!(first.profile_path.exists());
590        assert!(first.icon_path.exists());
591        assert_eq!(std::fs::read(&first.icon_path).unwrap(), artwork_bytes(AppIconPreference::Dark));
592
593        let stored: serde_json::Value =
594            serde_json::from_str(&std::fs::read_to_string(&first.profile_path).unwrap()).unwrap();
595        assert_eq!(
596            stored["Profiles"][0]["Custom Icon Path"].as_str().unwrap().to_string(),
597            first.icon_path.to_string_lossy().into_owned()
598        );
599
600        let second = install_profile_icon(home.path(), data.path(), AppIconPreference::Dark).unwrap();
601        assert_eq!(second.profile_path, first.profile_path);
602        assert_eq!(second.icon_path, first.icon_path);
603    }
604
605    #[cfg(target_os = "macos")]
606    #[test]
607    fn install_profile_icon_removes_retired_legacy_artwork() {
608        let home = tempfile::tempdir().unwrap();
609        let data = tempfile::tempdir().unwrap();
610
611        let legacy = data.path().join("icons").join(LEGACY_PROFILE_ICON_FILENAME);
612        std::fs::create_dir_all(legacy.parent().unwrap()).unwrap();
613        std::fs::write(&legacy, b"stale-legacy-bytes").unwrap();
614
615        let report = install_profile_icon(home.path(), data.path(), AppIconPreference::Dark).unwrap();
616        assert!(report.icon_path.exists());
617        assert!(!legacy.exists(), "retired artwork must be removed on install");
618    }
619
620    #[cfg(target_os = "macos")]
621    #[test]
622    fn install_profile_icon_switches_artwork_between_variants() {
623        let home = tempfile::tempdir().unwrap();
624        let data = tempfile::tempdir().unwrap();
625
626        // Install every pinned variant in turn: each write must land that
627        // variant's own bytes at the same stable path (fails on crossed
628        // artwork selection, where two variants would install identical art).
629        let mut installed: Vec<Vec<u8>> = Vec::new();
630        for preference in [
631            AppIconPreference::Dark,
632            AppIconPreference::Light,
633            AppIconPreference::Clear,
634            AppIconPreference::Tinted,
635        ] {
636            let report = install_profile_icon(home.path(), data.path(), preference).unwrap();
637            assert_eq!(report.icon_path, installed_icon_path(data.path()));
638            let bytes = std::fs::read(&report.icon_path).unwrap();
639            assert_eq!(bytes, artwork_bytes(preference), "{preference:?} must install its own art");
640            assert!(!installed.contains(&bytes), "{preference:?} art must differ from earlier installs");
641            installed.push(bytes);
642        }
643    }
644
645    #[test]
646    fn profile_icon_instructions_point_at_installer() {
647        let lines = profile_icon_instructions();
648        assert!(lines.iter().any(|line| line.contains("install-iterm2-icon")));
649        // The switch guidance must name every selectable variant, so a future
650        // variant cannot land in the parser without surfacing in setup help.
651        let joined = lines.join("\n");
652        for variant in AppIconPreference::ALL {
653            assert!(joined.contains(variant.id()), "instructions lack {}", variant.id());
654        }
655    }
656
657    #[test]
658    fn ensure_skips_without_iterm_session_and_writes_nothing() {
659        let home = tempfile::tempdir().unwrap();
660        let data = tempfile::tempdir().unwrap();
661
662        let report = ensure_profile_icon_at(home.path(), data.path(), false, false, AppIconPreference::Dark).unwrap();
663        assert!(report.is_none());
664        assert!(!iterm2_dynamic_profiles_dir(home.path()).exists());
665    }
666
667    #[test]
668    fn ensure_skips_under_tmux_and_writes_nothing() {
669        let home = tempfile::tempdir().unwrap();
670        let data = tempfile::tempdir().unwrap();
671
672        let report = ensure_profile_icon_at(home.path(), data.path(), true, true, AppIconPreference::Dark).unwrap();
673        assert!(report.is_none());
674        assert!(!iterm2_dynamic_profiles_dir(home.path()).exists());
675    }
676
677    #[cfg(target_os = "macos")]
678    #[test]
679    fn ensure_installs_once_then_refreshes_stale_artwork() {
680        let home = tempfile::tempdir().unwrap();
681        let data = tempfile::tempdir().unwrap();
682
683        let first = ensure_profile_icon_at(home.path(), data.path(), true, false, AppIconPreference::Dark).unwrap();
684        assert!(first.is_some());
685
686        let second = ensure_profile_icon_at(home.path(), data.path(), true, false, AppIconPreference::Dark).unwrap();
687        assert!(second.is_none());
688
689        let icon_path = installed_icon_path(data.path());
690        std::fs::write(&icon_path, b"stale-bytes").unwrap();
691        let third = ensure_profile_icon_at(home.path(), data.path(), true, false, AppIconPreference::Dark).unwrap();
692        let report = third.expect("stale artwork must trigger a refresh");
693        assert_eq!(std::fs::read(&report.icon_path).unwrap(), artwork_bytes(AppIconPreference::Dark));
694    }
695
696    #[cfg(target_os = "macos")]
697    #[test]
698    fn ensure_refreshes_when_resolved_artwork_changes() {
699        let home = tempfile::tempdir().unwrap();
700        let data = tempfile::tempdir().unwrap();
701
702        let first = ensure_profile_icon_at(home.path(), data.path(), true, false, AppIconPreference::Dark).unwrap();
703        assert!(first.is_some());
704        assert_eq!(std::fs::read(installed_icon_path(data.path())).unwrap(), artwork_bytes(AppIconPreference::Dark));
705
706        let second = ensure_profile_icon_at(home.path(), data.path(), true, false, AppIconPreference::Clear).unwrap();
707        let report = second.expect("artwork change must refresh the installed artwork");
708        assert_eq!(std::fs::read(&report.icon_path).unwrap(), artwork_bytes(AppIconPreference::Clear));
709
710        let third = ensure_profile_icon_at(home.path(), data.path(), true, false, AppIconPreference::Clear).unwrap();
711        assert!(third.is_none());
712    }
713
714    #[cfg(target_os = "macos")]
715    #[test]
716    fn ensure_refreshes_when_installed_profile_content_drifts() {
717        let home = tempfile::tempdir().unwrap();
718        let data = tempfile::tempdir().unwrap();
719
720        let first = ensure_profile_icon_at(home.path(), data.path(), true, false, AppIconPreference::Dark).unwrap();
721        let profile_path = first.expect("first run installs").profile_path;
722
723        // Simulate an older install that still carries the removed APS rule.
724        std::fs::write(&profile_path, r#"{"Profiles":[{"Name":"VT Code"}]}"#).unwrap();
725        let refreshed = ensure_profile_icon_at(home.path(), data.path(), true, false, AppIconPreference::Dark).unwrap();
726        let report = refreshed.expect("drifted profile content must trigger a rewrite");
727        assert_eq!(report.profile_path, profile_path);
728
729        let stored: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&profile_path).unwrap()).unwrap();
730        assert!(stored["Profiles"][0].get("Automatic Profile Switching").is_none());
731    }
732
733    #[cfg(target_os = "macos")]
734    #[test]
735    fn ensure_repairs_profile_pointing_at_retired_legacy_artwork() {
736        let home = tempfile::tempdir().unwrap();
737        let data = tempfile::tempdir().unwrap();
738
739        // Arrange: an older install whose profile still points at the
740        // retired `vtcode-profile-120.png` filename (observed in the wild).
741        let legacy = installed_icon_path(data.path())
742            .parent()
743            .unwrap()
744            .join(LEGACY_PROFILE_ICON_FILENAME);
745        std::fs::create_dir_all(legacy.parent().unwrap()).unwrap();
746        std::fs::write(&legacy, b"stale-legacy-bytes").unwrap();
747        let profiles_dir = iterm2_dynamic_profiles_dir(home.path());
748        std::fs::create_dir_all(&profiles_dir).unwrap();
749        let profile_path = installed_iterm2_profile_path(home.path());
750        let stale = serde_json::json!({
751            "Profiles": [{
752                "Name": ITERM2_PROFILE_NAME,
753                "Guid": PROFILE_GUID,
754                "Icon": ITERM2_ICON_MODE_CUSTOM,
755                "Custom Icon Path": legacy.to_string_lossy(),
756            }],
757        });
758        std::fs::write(&profile_path, serde_json::to_string_pretty(&stale).unwrap()).unwrap();
759
760        // Act.
761        let refreshed = ensure_profile_icon_at(home.path(), data.path(), true, false, AppIconPreference::Dark).unwrap();
762        let report = refreshed.expect("legacy-path profile must trigger a reinstall");
763
764        // Assert: profile repoints at the current artwork and the retired
765        // file is gone, so the tab can no longer load stale bytes.
766        assert_eq!(report.profile_path, profile_path);
767        assert_eq!(report.icon_path, installed_icon_path(data.path()));
768        assert_eq!(std::fs::read(&report.icon_path).unwrap(), artwork_bytes(AppIconPreference::Dark));
769        assert!(!legacy.exists(), "retired artwork must be removed on repair");
770        let stored: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&profile_path).unwrap()).unwrap();
771        assert_eq!(stored["Profiles"][0]["Custom Icon Path"].as_str().unwrap(), report.icon_path.to_string_lossy());
772    }
773}