Files
tty7/src/main.rs
T
l0ng-aiandClaude 24cf458e3b feat(mobile): a phone app to watch and drive tty7 panes (#983)
* feat(mobile): a gateway that lets a paired phone reach this machine over iroh

The first half of the mobile app: everything on the desktop side, plus the
client library the app will link.

- tty7-mobile-proto: the phone<->gateway wire protocol. One stream per purpose
  (pair, control, pane), framed like the daemon's frames, with raw terminal
  bytes kept out of JSON. No tty7-core, so it cross-compiles for iOS/Android.
- tty7-gateway: dials nothing, accepts phones over iroh (hole punching, relay
  fallback, end-to-end encrypted), checks the peer's key against the paired
  device list, and bridges to the daemon. Panes are observed, not attached,
  and keystrokes go in through SendInput, so a phone never resizes a pane or
  takes it away from the desktop window. `pair` prints a one-time QR code.
- tty7-mobile-client: the phone side (pair, tree, pane streams, direct/relay
  and RTT for the link), plus a `probe` example that stands in for a phone.

Verified against a real, isolated daemon: pair, tree, and typing into a pane
over a direct path, ~0.8 ms median echo on loopback.

* feat(mobile): the Tauri app — pair, browse the machine, drive a pane

The phone half, as a Tauri 2 app in mobile/ (its own cargo workspace, so the
desktop build and CI never compile a WebView stack).

- Rust side: the phone's iroh endpoint and key, paired machines, and every
  live stream, behind eight commands. Terminal output crosses to the WebView
  as raw ArrayBuffers on a Tauri channel, batched per frame, in order with the
  pane's JSON events.
- Frontend: vanilla TS + xterm.js. Paired machines and pairing; one machine's
  workspaces, tabs and panes with agents that need you pinned on top and the
  link's direct/relay path and RTT in the header; a terminal that fits the
  desktop pane's width, with an esc/tab/ctrl/arrows key bar. Coming back from
  the background re-watches and re-opens, relying on the daemon's replay.

Verified as a macOS build against a live gateway and an isolated daemon:
paired from the app, tree rendered on a direct path, keystrokes and key-bar
arrows reached the pane. iOS/Android builds need Xcode / the Android NDK,
neither of which is on this machine; mobile/README.md has the steps.

* fix(gateway): one serve per machine, and say how to start a missing server

- `serve` takes an exclusive lock on <config dir>/mobile/serve.lock. A second
  gateway on the same key is a second endpoint answering to one address, so a
  phone reached whichever the network picked. It is now refused, naming the
  pid that holds the lock.
- With no tty7 server running, phones and the terminal both hear "tty7 isn't
  running on <host> — open tty7 there, or run `tty7 server start`" instead of
  "lost the tty7 server: No such file or directory". `serve` checks once at
  startup, and still starts, since tty7 may be opened after it.

* feat(mobile): redesign the app as a native-feeling, minimal UI

The first cut read as a web page of bordered boxes. This rebuilds it the way a
phone app moves and reads, in the desktop tty7's own look:

- Screens push and pop with View Transitions; large titles fold into the bar.
- Grouped inset lists on a tinted canvas, following the system Light/Dark with
  the desktop presets, accent and ANSI palettes. Hack for code and terminal.
- Panes are listed by tab, one card per workspace, with the desktop's agent
  avatars and status badges (Waiting hollow, Working blinking) and its words.
- Pairing is its own screen, with steps, a Paste button and inline errors.
- A machine that stays silent for 10 s says so and offers to pair again; an
  offline notice says what to check.
- The terminal header shows live/offline in words. A pane too wide to read is
  shown at a readable size and pans to follow the cursor, with a toggle to fit
  the whole width. The key bar has drawn icons, puts left/right first, and
  has a keyboard toggle.

PRODUCT.md and DESIGN.md record the product facts and the design system.

* feat(mobile): open a new tab from the phone

Each workspace on a machine's screen gets a "New tab" action. It starts a
shell at the end of that workspace, in the directory its last tab is in, and
opens it straight away.

- Protocol: a one-shot `Open::NewTab { workspace_id, cwd, size }` stream,
  answered with `Ok` and a `TabCreated { tab_id, pane_id }`, or `Denied`.
  It is additive, so the protocol version stays. A gateway from before this
  drops the stream unanswered, and the app says to update it.
- Gateway: takes the same two steps as `tty7 tab new`, spawning a shell owned
  by the workspace and then TabCreate. The shell starts at the grid the phone
  asked for, because no desktop window is showing it yet. Sizes are clamped.
- App: a `tab_new` command, with the size worked out from the screen at the
  readable font size.
- probe: `newtab <workspace-id> [cwd]`.

* feat(mobile): reach the machines the desktop is linked to over SSH

A machine's screen now lists, under its own workspaces, every machine its
tty7 holds an SSH link to, with that machine's workspaces. Panes there open,
take input and get new tabs like local ones. "Needs you" gathers panes from
all of them.

- The gateway routes through the local server over links it already holds,
  the same way `tty7 -m <machine>` does. It never dials a down link, because
  that would guess at credentials the phone does not have. A down link
  shows as "Link down", with a note to reconnect it on the desktop.
- Protocol, additive: `Tree.remotes`, and an optional `machine` (the link
  key) on `Open::Pane` and `Open::NewTab`. A local pane is asked for exactly
  as before, so older gateways still understand it.
- Rebuilding a route target from a link key moves from the CLI into
  tty7-core as `RouteInfo::target` / `RouteInfo::host`, so the CLI and the
  gateway share one rule. The CLI now calls it.

* perf(gateway): read linked machines in parallel, never waiting on a slow one

Linked machines were read one after another on every tree poll. One slow
SSH link, whose requests can take 10 s, stalled the whole tree for every
phone, local workspaces included. It also held a lock that queued pane
opens, input and new tabs on every other link.

- Each linked machine is read on its own thread (`poller::Poller`). A poll
  waits at most 250 ms. A machine that has not answered is reported as it
  last was, and its read lands for the next poll. Only one read is in flight
  per machine, however many phones are watching. A machine that drops off and
  comes back cannot receive a stale read, because each slot has a generation.
- Routed control connections are locked per machine, not all together.
- A link that is up but has not answered its first read is sent as
  `RemoteView.pending` (additive). The app shows "Reading…" with skeleton
  rows instead of claiming the machine has no workspaces.

* fix(mobile): keep reaching the computer after the gateway restarts

Every `serve` bound a random port, so a restart left each phone holding
addresses that no longer answered. Where the n0 relays are unreachable, which
is common behind the Great Firewall, the phone had no other way to find the
gateway until it was paired again.

- `serve` listens on the same UDP port every time. It picks one on first run,
  keeps it in `<config dir>/mobile/port`, and moves only if the port is taken.
  IPv6 binding may fail, as in iroh's own defaults.
- Both ends add mDNS lookup (`iroh-mdns-address-lookup`, service `_tty7._udp`).
  On the same network a phone finds the gateway by key when its addresses are
  stale, such as after a new DHCP lease or a new IPv6 prefix. The gateway
  advertises and the phone only listens. If multicast is refused, each side
  starts without it and says so, rather than failing.
- iOS: `Info.ios.plist` declares the local-network use and the Bonjour
  service, without which iOS blocks multicast.
- An ignored test (`--test mdns`) connects by key alone over mDNS, for a
  machine that allows multicast.

* feat(mobile): run the gateway in the desktop daemon, paired from Settings

Phone access no longer needs `tty7-gateway serve` in a terminal.
Settings → Mobile switches it on, and the local daemon runs the gateway from
then on, with every window closed as well. That is where the panes a phone
reaches live anyway.

- Settings → Mobile, in all three locales:
  - an "Allow phone access" switch;
  - a status line (running, starting, off, or why it failed);
  - "Show code", which draws the QR code and the tty7pair: code with a
    Copy button, and closes on its own once a phone uses it;
  - the paired phones, each with Unpair.
  The section is in search, including by its config key `mobile_access`.
- The daemon (`tty7-app --daemon`) runs a supervisor (`core::mobile`). It
  watches `mobile_access` in config.json, re-reading only when the file
  changes, and starts or stops the gateway. A failed start is retried every
  30 s and logged once.
- tty7-gateway grows a `service` module: `start()` returns a stoppable
  handle, and `pair_code()` makes a code. The CLI's `serve` and `pair` are
  thin wrappers over them now. The gateway logs through `log`, so the
  daemon's output lands in its log file, and it reports itself in
  `mobile/status.json`. `State::serving()` checks the lock, which a crash
  cannot leave stale. A gateway that cannot take the lock leaves the
  status alone, because it belongs to the one holding the lock.
- iroh is linked into the GUI binary only. tty7-server stays the lean static
  binary pushed to remote machines.

* feat(mobile): serve phones whichever daemon is running

A daemon started by `tty7 server start` is the lean tty7-server, which
carries no gateway. With phone access on, the Settings status stayed on
"Starting…" and no phone could connect.

The GUI now checks, 5 s after it starts and whenever phone access is
switched on. If nothing is serving, it starts `tty7-app --mobile-gateway`,
detached the same way as the daemon (`spawn::detach_helper`). The helper
serves until the switch goes off, and exits at once if another process
already holds the gateway lock. When the daemon's own gateway is up, no
helper is started. The helper logs under its own role, "mobile".

* refactor(mobile): the daemon owns the gateway, as a child, whoever started it

There were two ways of running the gateway: a thread inside `tty7-app
--daemon`, and a detached helper the GUI started when the daemon could not.
That is now one way.

Every daemon, whether `tty7-app --daemon` or `tty7-server`, runs
`tty7_core::daemon::mobile::supervise` from `run_with`. While
`mobile_access` is on it keeps the gateway running as a child process, and
stops it when the switch goes off.

- Which program: `tty7-app` runs itself as `--mobile-gateway`. `tty7-server`
  runs a `tty7-gateway serve --exit-with-stdin` from beside it or on PATH,
  and links nothing new. Without one, it writes the reason into
  `mobile/status.json` for Settings to show, instead of "Starting…" forever.
- Lifetime: the child's stdin is a pipe from the daemon, and the gateway
  exits when it closes. A stopped, crashed or handed-off daemon (the pipe
  is close-on-exec) takes its gateway with it, and the next daemon starts
  one from its own binary. No gateway from an older build survives an
  update.
- Isolation: iroh no longer runs inside the process that holds every pane.
- `Status` moves to tty7-core, the one definition that the daemon, the
  gateway and the GUI all share.
- Gone: the GUI's helper check (`core::mobile` in the app) and the in-daemon
  gateway thread.

* fix(mobile): stop and reap the gateway before a daemon handoff

Found by running a real `tty7 server restart`. The old gateway did exit,
because the new image's supervisor started its own gateway and the old one
lost the lock. But it was left as a zombie: the image after the exec never
reaps a child it did not start, so each handoff leaked a process entry.

`hand_over` now calls `daemon::mobile::stop_for_handoff` before the exec,
which closes the gateway's stdin and waits for it. A flag keeps the
supervisor from starting another in the moments before the exec, and
`handoff_failed` clears the flag if the exec never happens, so the daemon
goes on serving.

Checked with two handoffs in a row (tty7-app → tty7-server → tty7-server):
- each old gateway was reaped, with no zombies system-wide;
- exactly one fresh gateway was running after each handoff;
- the pane's shell and its environment survived;
- the probe phone kept working.

* feat(mobile): the switch shows whether phones can reach you, not a status row

Settings → Mobile had an "Allow phone access" switch that showed intent and a
separate Status row that showed reality. That is one thing shown twice, and
the switch could sit on while nothing was running.

- The switch is the state. Switching on holds it at "Starting…", disabled,
  until a gateway is actually serving. If the daemon reports a failure, or
  nothing comes up within 15 s, the switch goes back off, `mobile_access`
  is reverted, and a notification says why.
- If the page opens on a failure the daemon is still retrying, the switch
  shows off with the reason in its description, and switching it on
  retries.
- The Status row is removed, with its four strings. There are two new
  strings for the failure, in en, zh and ja.

Also fixes the Settings window never showing notifications. It is a `Root`
like the workspace window but did not draw the notification layer, so any
toast pushed from Settings was queued and never shown. That included the
existing "Set as Default Terminal" result.

Checked in a dev instance. On a tty7-server daemon with no tty7-gateway:
Starting… first, then off, with "Phone access could not start: … no
tty7-gateway beside it or on PATH". On a tty7-app daemon: on, with Show
code enabled and no toast.

* feat(mobile): drop the "Needs you" section

The machine screen gathered every pane whose agent was waiting or done into
a "Needs you" section above the workspaces. Done lasts until the next prompt,
so the section grew with every finished agent and mostly held panes that
needed nothing.

Panes now appear once, in their own workspace. Each keeps its status badge
and words ("Needs input", "Working", "Done") and the agent's message.
PRODUCT.md and the design sidecar are updated to match.

* fix(mobile): say when typing doesn't reach the pane

The gateway's input thread gave up silently on a failed send_input, and
the app's input task did the same on a failed write, so the phone kept
showing a live pane while keystrokes went nowhere. Both now report the
failure as a pane error. Keys after it are dropped rather than ending
the stream, which the phone would read as the pane closing.

* feat(mobile): a compose box, paste and Shift+Tab on the terminal

Replying to an agent meant typing into xterm a character at a time,
without autocorrect, dictation or a usable IME. The compose box is a
real text field: Send types the text and then Enter, as its own write,
and several lines go in as one bracketed paste when the program asked
for it. Drafts survive leaving the pane and a send that failed. An
agent's pane opens on the box with the keyboard down.

The key bar gains Shift+Tab (Claude Code's mode switch) and a paste key.
A failed keystroke now takes the pane offline with a Reconnect banner
instead of being swallowed.

* feat(mobile): reconnect on its own, and select text to copy

A dropped pane or machine stream is retried with backoff (1s, 2s, 4s …
15s) and at once when the network comes back, rather than waiting for a
tap on Reconnect. The pane keeps its last screen up until the new
replay starts, and output or errors from a replaced stream are ignored.

Touch selection does not work in xterm, so a copy key lays the whole
buffer out as plain text over the pane, wrapped to the phone and joined
where the terminal wrapped, for the phone's own selection and Copy.

* feat(daemon): size leases, and Take Back on the desktop

An observer can now run a pane at its own size (ClientMsg::Lease, feature
size-lease). The pty and every observer go to that size. The controller
keeps its grid, its resizes are remembered rather than applied, and the
pane goes back to the last of them when the lease ends: the observer lets
go, its connection closes, or the controller takes it back.

A controller hears about leases only after asking (Watch), since an older
client cannot decode DaemonMsg::Lease. The desktop asks on every attach,
spawn and relink where the daemon advertises the feature, locally or
through the host hello for remote workspaces, and shows the pane as in
use on the phone with a Take Back button.

* feat(mobile): take a pane over at the phone's size

The terminal's phone button asks the gateway to run the pane at the
phone's grid (PaneRequest::TakeOver), which it turns into a size lease on
the observer connection, named after the paired device. The grid follows
the keyboard and rotation; leaving the pane, or the connection dropping,
gives it back. When the desktop takes it back the app says so and offers
to take it over again, never doing it on its own. A daemon too old for
leases is reported, and the pane keeps working.

* fix(mobile): link SystemConfiguration and install a rustls provider on iOS

The first iOS build failed to link: netdev and system-configuration, pulled
in by iroh, need SystemConfiguration.framework, which the generated Xcode
project does not list. bundle.iOS.frameworks adds it on `tauri ios init`.

Once linked, the app panicked at launch: iroh builds its reqwest client with
`rustls-no-provider`, so a process-wide crypto provider must be installed
before any client is built. Install ring's, which is already in the tree.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(mobile): keep the terminal's scrollbar on screen while panning

Panning a pane wider than the phone scrolled xterm's own box sideways with
the text. The box was only the view's width, so its vertical scrollbar
panned off with the columns and its scrollback stopped taking touches past
the first screen. The box now spans every column, and the bar is shifted
to the visible right edge as the view pans.

The bar is also drawn like the indicator WebKit shows for the pan, thin,
rounded and translucent, instead of VS Code's 14px square slider, so the
two axes match.

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(mobile): pair by scanning the QR code, and Enter and quick-answer keys

Pairing took a pasted `tty7pair:` code, which on a real phone means getting
text off the desktop somehow. A Scan button next to Paste now reads the QR
code tty7 shows, through tauri-plugin-barcode-scanner, and pairs straight
away. The camera runs behind the WebView with our own viewfinder and Cancel,
since the plugin's full-screen view has no way out. The plugin is registered
on phones only, so the desktop dev build is unchanged.

The key bar gains Enter, so an agent's highlighted choice can be confirmed
without raising the keyboard, and 1 2 3 y n for numbered choices and y/n
prompts.

Co-Authored-By: Claude <noreply@anthropic.com>

* chore(mobile): sign for the App Store and declare exempt encryption

Sets the development team so `tauri ios init` writes it into the Xcode
project, and marks the app's encryption (standard TLS/QUIC only) as exempt
so TestFlight uploads skip the export-compliance question.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(mobile): count the iOS safe areas once

The WKWebView's scroll view inset its content by the safe areas, and the
page, laid out with viewport-fit=cover, padded by env(safe-area-inset-*)
as well. The viewport came out 778pt tall on an 874pt screen: everything
sat a status bar's height too low, with a blank band under it. The scroll
view's automatic inset adjustment is now off, so the page runs edge to
edge and its CSS alone keeps clear of the status bar and home indicator.

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(mobile): the Terminal Mobile redesign

The app takes the desktop's neutral greys, light and dark, with ink rather
than a system blue for what is pressed or chosen.

- Machines: pairing's "+" moves to a floating bar at the bottom beside a
  search field. Each machine shows its link, round trip and tab count as
  last seen.
- A machine: tabs grouped by workspace with a count; round agent glyphs;
  a dot on the right for running or waiting on you. The per-group New tab
  buttons give way to one "+" in the same floating bar, beside tab search.
- New tab: a sheet to pick Claude Code, Codex or a shell, and the
  workspace. An agent's command is typed into the new tab once it is live.
- A pane: the bar keeps only back, the title with its state, and a menu
  for selecting text, the fit and the phone's size. Under it, one row of
  equal keys, a page at a time, and a message box that is always there;
  its round button sends, or when empty hands the keyboard to the
  terminal.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(mobile): the tty7 mark as the iOS app icon

The phone showed Tauri's default icon: `tauri ios init` filled the Xcode
project with it. The committed icons/ios set was drawn on the macOS grid,
a rounded tile inset on transparency, which iOS would shrink inside its own
mask with a pale border. icons/app-icon-ios.svg is the same Duo mark full
bleed, rendered without alpha as the App Store requires.

Claude-Session: https://claude.ai/code/session_01HVosmYyVSH3BrsLYx3tcSS

* fix(mobile): typing, scrolling and pairing on a real phone

- Typing into a pane: an input method's text never reached it, since iOS
  never commits a candidate into xterm's hidden textarea. Tapping the
  terminal now focuses a plain field of our own, whose committed text goes
  to the pane as it is committed. Backspace on the empty field, Enter, Tab
  and the arrows go as the terminal's keys.
- xterm sends nothing itself any more (disableStdin). That also stops the
  phone answering a program's colour and device queries: the desktop
  answers those, and the phone's late second answer landed in the shell as
  typed text.
- Scrolling the scrollback: xterm 6 has no working touch scrolling. A
  mostly vertical swipe now scrolls the buffer a row at a time and coasts;
  a sideways one is left to the native pan.
- Pairing: the steps name the desktop's Settings -> Mobile, Allow phone
  access and Show code, not a command-line gateway, and so do the notices
  when a machine cannot be reached.

Claude-Session: https://claude.ai/code/session_01HVosmYyVSH3BrsLYx3tcSS

* fix(mobile): room for the keyboard, and smoother vertical scrolling

- The keyboard: the WebView runs edge to edge and is not resized for it,
  so it covered the dock and the pane's last lines. The app now takes the
  size of the visual viewport, drops the home indicator's gap while the
  keyboard is up, and keeps the cursor's line in sight.
- Scrolling: the terminal draws with xterm's WebGL renderer, which a
  scroll does not make lay every row out again. A swipe is applied once a
  frame, and moves the view by pixels: xterm scrolls whole rows, and the
  rest of a row is a GPU shift of the drawn screen, put on together with
  the rows it goes with.

Claude-Session: https://claude.ai/code/session_01HVosmYyVSH3BrsLYx3tcSS

* feat(mobile): settings, message history, and a tighter home screen

- Settings, from beside the Machines title: appearance (automatic, light,
  dark; the status bar and keyboard follow through the window's interface
  style), terminal text size, how a pane wider than the phone first shows,
  clearing the message history, and the version.
- The message box keeps what it sends on the phone. As a message is
  written, past ones that match take the key row's place; with the box
  empty, a History button opens them all, searchable. A line that asks for
  a password is sent but not kept.
- ^R on the third key page, for the shell's own history search.
- A top-level screen's bar floats over the list, clear until the title
  scrolls under it, so the large title sits just under the status bar.

Claude-Session: https://claude.ai/code/session_01HVosmYyVSH3BrsLYx3tcSS

* fix(mobile): a fitted pane fills the view, and its scrollbar drags

- A pane shorter than the view (a wide one, fitted) no longer leaves the
  bottom of the screen blank: the terminal here runs as many rows as fill
  the view, the extra ones holding the pane's earlier lines, and what is
  left over goes above so the prompt stays next to the keys. The pane on
  the desktop keeps its size.
- A drag that starts on the scrollbar is left to xterm. The swipe handler
  took it too, the other way round, and the two cancelled out.

Claude-Session: https://claude.ai/code/session_01HVosmYyVSH3BrsLYx3tcSS

* fix(mobile): errors say what to do in the app, not on the command line

The messages a phone shows, and the two Settings → Mobile can, named the
gateway process, the CLI's `tty7 server start`, the transport and a lock
file's path. They now speak of tty7 on the computer and of pairing: open
it there, update it, pair again, quit the other copy.

Claude-Session: https://claude.ai/code/session_01HVosmYyVSH3BrsLYx3tcSS

* style: rustfmt the gateway and mobile client

Claude-Session: https://claude.ai/code/session_01HVosmYyVSH3BrsLYx3tcSS

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-29 19:09:32 +08:00

1254 lines
48 KiB
Rust

#![cfg_attr(
all(target_os = "windows", not(debug_assertions)),
windows_subsystem = "windows"
)]
mod core;
mod daemon;
mod terminal;
mod ui;
use crate::core::config::Config;
use crate::ui::assets::Assets;
use crate::ui::keymap;
use gpui::*;
fn register_bundled_fonts(cx: &mut App) {
use std::borrow::Cow;
let fonts = vec![
Cow::Borrowed(include_bytes!("../assets/fonts/hack/Hack-Regular.ttf").as_slice()),
Cow::Borrowed(include_bytes!("../assets/fonts/hack/Hack-Bold.ttf").as_slice()),
Cow::Borrowed(include_bytes!("../assets/fonts/hack/Hack-Italic.ttf").as_slice()),
Cow::Borrowed(include_bytes!("../assets/fonts/hack/Hack-BoldItalic.ttf").as_slice()),
];
if let Err(e) = cx.text_system().add_fonts(fonts) {
log::warn!("failed to register bundled Hack fonts: {e}");
}
}
fn spawn_config_watcher(cx: &mut App) {
use notify::{RecursiveMode, Watcher};
let Some(config_file) = crate::core::config::config_path("config.json") else {
return;
};
let Some(dir) = crate::core::config::config_dir_path() else {
return;
};
let _ = std::fs::create_dir_all(&dir);
const DEBOUNCE: std::time::Duration = std::time::Duration::from_millis(200);
let (tx, rx) = smol::channel::unbounded::<()>();
let watched_file = config_file.clone();
let handler = move |res: notify::Result<notify::Event>| {
let Ok(event) = res else { return };
// A reload re-reads the file, and on Linux reading it is itself an
// event — see `tty7_core::host::is_content_change`.
if !tty7_core::host::is_content_change(&event.kind) {
return;
}
// The saved SSH hosts live beside config.json in a file of their own
// (#911), and a hand edit there has to land the same way.
let hit = event.paths.iter().any(|p| {
p.file_name() == watched_file.file_name()
|| p.file_name() == Some(std::ffi::OsStr::new(crate::core::config::SERVERS_FILE))
|| is_theme_file(p)
});
if hit {
let _ = tx.try_send(());
}
};
let mut watcher = match notify::recommended_watcher(handler) {
Ok(w) => w,
Err(e) => {
log::warn!("config hot-reload disabled: failed to create watcher: {e}");
return;
}
};
if let Err(e) = watcher.watch(&dir, RecursiveMode::Recursive) {
log::warn!(
"config hot-reload disabled: failed to watch {}: {e}",
dir.display()
);
return;
}
Box::leak(Box::new(watcher));
cx.spawn(async move |cx| {
// One toast per breakage rather than one per write: this watcher also
// fires for every theme file, so a config.json left broken would
// otherwise re-announce itself on each of them. Cleared by the load
// that parses, so a second breakage speaks up again.
let mut announced = false;
while rx.recv().await.is_ok() {
cx.background_executor().timer(DEBOUNCE).await;
while rx.try_recv().is_ok() {}
cx.update(|cx| {
apply_reloaded_config(cx, Config::load_with_outcome(), &mut announced);
});
}
})
.detach();
}
/// One watcher tick, once the debounce is out: what a reload does to the
/// running app.
///
/// `announced` is the one-toast-per-breakage latch, which lives across ticks
/// in the watcher. Returns whether the keymap was rebuilt — the watcher has no
/// use for that; it is how a test asks which branch ran.
fn apply_reloaded_config(
cx: &mut App,
load: (Config, crate::core::config::LoadOutcome),
announced: &mut bool,
) -> bool {
let (config, outcome) = load;
if outcome.failed() {
// Keep the settings the app is running on: swapping the stand-in
// defaults in would flash the whole UI onto defaults, and the load
// already parked the broken file beside the original. It reloads
// itself the moment the file parses again.
if !*announced {
*announced = true;
notify_config_load_failed(cx, outcome, false);
}
// The theme files this same watcher covers must keep hot-reloading: a
// typo in config.json is no reason for theme editing to go dead until
// the app restarts. They read the global config, which is deliberately
// still the one the app is running on.
reload_themes(cx);
cx.refresh_windows();
return false;
}
*announced = false;
// The keymap is rebuilt only when a binding actually moved. This watcher
// fires for every write under the config dir — including the app's own
// `save()`, which a sidebar drag or a palette open triggers — so reloading
// bindings on each tick would rebuild the whole keymap for nothing, and
// (before `rebind` cleared first) leak a full table per tick (#548).
// Read past the early return above: a load that failed leaves the global
// alone, so there is nothing to compare and the user's keys stay in the
// keymap the app is dispatching on.
let keymap_before = crate::ui::keymap::keybinding_config(cx);
// Explorer's verbs live in the registry rather than in this process, so a
// hand-edited `gui_language` leaves them behind unless something restates
// them. Gated on the language actually moving, for the same reason the
// keymap below is: this watcher fires on every config write, and a sidebar
// drag has no business touching the registry.
let language_changed = cx.global::<Config>().gui_language != config.gui_language;
crate::ui::i18n::set_locale(&config.gui_language);
cx.set_global(config);
reload_themes(cx);
crate::ui::theme::apply_cursor_hide_mode(cx);
// The menu bar is built once from the current locale, so editing
// gui_language by hand has to rebuild it the same way the in-app language
// picker does.
crate::ui::theme::set_menus(cx);
if language_changed {
crate::core::explorer_context_menu::refresh_labels();
}
crate::ui::windows::WindowRegistry::refresh_locale(cx, None);
// `custom_shells` is only ever hand-edited, so this file is the one place
// it can change from — and the inventory that carries it to the new-tab
// menu is cached per window.
crate::ui::windows::WindowRegistry::refresh_shells(cx);
// A hand-edited keybinding shows up in the settings list off the live
// global immediately; without this it never reaches the keymap gpui
// actually dispatches against, so the key looks bound and does nothing
// until restart. Gated on the triple so an unrelated save does not churn
// it.
let rebound = crate::ui::keymap::keybinding_config(cx) != keymap_before;
if rebound {
crate::ui::keymap::rebind(cx);
}
cx.refresh_windows();
rebound
}
fn is_theme_file(p: &std::path::Path) -> bool {
p.parent().and_then(|d| d.file_name()) == Some(std::ffi::OsStr::new("themes"))
&& p.extension().and_then(|e| e.to_str()).is_some_and(|e| {
e.eq_ignore_ascii_case("yaml")
|| e.eq_ignore_ascii_case("yml")
|| e.eq_ignore_ascii_case("itermcolors")
})
}
/// Re-reads what the theme files on disk say. The config watcher covers the
/// themes directory too, so this has to run even when config.json itself did
/// not load — editing a theme cannot go dead because of a typo elsewhere.
fn reload_themes(cx: &mut App) {
crate::ui::presets::load_registry(cx);
crate::ui::theme::apply_theme(None, cx);
}
/// Says out loud that config.json did not load and, when there is one, where
/// its contents were parked. Without this the symptom is "my settings are
/// gone" (startup) or "my edit did nothing" (reload) — both read as data loss,
/// and neither points at the file that needs fixing.
fn notify_config_load_failed(
cx: &mut App,
outcome: crate::core::config::LoadOutcome,
startup: bool,
) {
use crate::core::config::LoadOutcome;
use crate::ui::i18n::L10nKey;
use gpui_component::WindowExt as _;
// Only an unparseable file leaves a copy behind; an unreadable one had
// nothing to copy, so it must not send the user after a `.corrupt` file
// that was never written.
let key = match (outcome, startup) {
(LoadOutcome::Unreadable, true) => L10nKey::ConfigUnreadableStartup,
(LoadOutcome::Unreadable, false) => L10nKey::ConfigUnreadableReload,
(_, true) => L10nKey::ConfigQuarantinedStartup,
(_, false) => L10nKey::ConfigQuarantinedReload,
};
let Some(workspace) = crate::ui::windows::WindowRegistry::most_recent(cx) else {
return;
};
let Some(handle) = crate::ui::windows::WindowRegistry::window_for(cx, workspace) else {
return;
};
let _ = handle.update(cx, |_, window, cx| {
window.push_notification(crate::ui::i18n::t(key), cx);
});
}
fn strip_os_arg_prefix(arg: &std::ffi::OsStr, prefix: &str) -> Option<std::ffi::OsString> {
let suffix = arg.as_encoded_bytes().strip_prefix(prefix.as_bytes())?;
// SAFETY: `prefix` is ASCII and is removed only from the beginning of an
// existing platform-encoded OsStr. ASCII bytes are self-synchronizing in
// Windows WTF-8 and Unix byte strings, so the suffix keeps valid encoding.
Some(unsafe { std::ffi::OsString::from_encoded_bytes_unchecked(suffix.to_vec()) })
}
fn config_dir_from(
mut args: impl Iterator<Item = std::ffi::OsString>,
) -> Option<std::path::PathBuf> {
while let Some(arg) = args.next() {
if let Some(path) = strip_os_arg_prefix(&arg, "--config-dir=") {
return Some(path.into());
}
if arg == std::ffi::OsStr::new("--config-dir") {
return args.next().map(Into::into);
}
}
None
}
fn apply_config_dir_arg(args: &[std::ffi::OsString]) {
if let Some(path) = config_dir_from(args.iter().cloned()) {
crate::core::config::set_config_dir(path);
}
}
fn open_path_from(
mut args: impl Iterator<Item = std::ffi::OsString>,
) -> Option<std::path::PathBuf> {
while let Some(arg) = args.next() {
if let Some(path) = strip_os_arg_prefix(&arg, "--open-path=") {
return Some(path.into());
}
if arg == std::ffi::OsStr::new("--open-path") {
return args.next().map(Into::into);
}
}
None
}
/// The directory an installer is about to replace, from
/// `--stop-daemon --update-install-dir <dir>`. Meaningful only next to
/// `--stop-daemon`; the caller checks that flag first.
#[cfg(windows)]
fn update_install_dir_from(
mut args: impl Iterator<Item = std::ffi::OsString>,
) -> Option<std::path::PathBuf> {
while let Some(arg) = args.next() {
if arg == std::ffi::OsStr::new("--update-install-dir") {
return args.next().map(Into::into);
}
}
None
}
/// `Some(true)` to register the Explorer verbs, `Some(false)` to remove them.
fn explorer_menu_action_from(args: &[std::ffi::OsString]) -> Option<bool> {
args.iter().find_map(|arg| match arg.as_os_str() {
a if a == std::ffi::OsStr::new("--register-explorer-menu") => Some(true),
a if a == std::ffi::OsStr::new("--unregister-explorer-menu") => Some(false),
_ => None,
})
}
/// Offers an explicit launch request to an already running local GUI.
///
/// The dispatcher is injected so the startup decision can be tested without
/// opening a real daemon connection. Only an explicit `Bool(true)` means the
/// request reached a GUI; every other response keeps the current app alive so
/// it can perform the normal first-window startup. A pathless request asks the
/// GUI to surface itself — restore its most recent workspace, or activate the
/// window it already has — which is what lets a second launch hand the tray
/// its window back instead of opening a second process.
///
/// `daemon_gone` reports whether the recorded daemon process is known dead.
/// The probe connects to that daemon's control listener, so a dead daemon
/// guarantees the request cannot reach a GUI — and the connect would only pay
/// the OS's refusal delay on the stale `control.port` that `ensure_running`
/// clears later. The probe is skipped instead of run.
fn forward_open_path_with(
open_path: Option<&std::path::Path>,
daemon_gone: impl FnOnce() -> bool,
dispatch: impl FnOnce(Option<String>) -> std::io::Result<tty7_core::daemon::control::ReplyOk>,
) -> bool {
use tty7_core::daemon::control::ReplyOk;
if daemon_gone() {
return false;
}
let wire_path = match open_path {
None => None,
Some(path) => {
let path = if path.is_absolute() {
path.to_path_buf()
} else {
match std::env::current_dir() {
Ok(current_dir) => current_dir.join(path),
Err(error) => {
log::debug!("could not resolve the relative GUI open path: {error}");
return false;
}
}
};
// Keep the native PathBuf in this process. Returning false
// continues normal startup, which opens the path without crossing
// the protocol.
let Some(wire_path) = path.to_str().map(str::to_owned) else {
log::debug!("the explicit GUI open path is not valid UTF-8; opening it locally");
return false;
};
Some(wire_path)
}
};
match dispatch(wire_path) {
Ok(ReplyOk::Bool(true)) => true,
Ok(ReplyOk::Bool(false)) => false,
Ok(other) => {
log::debug!("the daemon answered the early GuiOpen request with {other:?}");
false
}
Err(error) => {
log::debug!("the early GuiOpen request was not delivered: {error}");
false
}
}
}
/// Uses a transient host-RPC connection instead of a GUI connection.
///
/// A GUI connection is long-lived and registers itself as the daemon's event
/// target. This short probe must never replace the actual running GUI while it
/// asks that GUI to open the requested folder.
fn forward_open_path(open_path: Option<&std::path::Path>) -> bool {
use tty7_core::client::ControlClient;
use tty7_core::daemon::control::{ControlHello, ControlRequest};
forward_open_path_with(
open_path,
crate::daemon::spawn::recorded_daemon_is_dead,
|path| {
let hello = ControlHello::host_rpc(
format!("tty7-app-open-{}", std::process::id()),
"this computer",
);
let client = ControlClient::connect(&hello)?;
let reply = client.request(ControlRequest::GuiOpen {
path,
workspace: None,
});
client.close();
reply
},
)
}
#[cfg(unix)]
fn merge_paths(primary: &str, secondary: &str) -> String {
let mut seen = std::collections::HashSet::new();
primary
.split(':')
.chain(secondary.split(':'))
.filter(|p| !p.is_empty() && seen.insert(*p))
.collect::<Vec<_>>()
.join(":")
}
/// Brackets the PATH in the probe's output. An interactive rc prints what it
/// likes — a greeting above, an exit hook below — so neither the whole output
/// nor any one line of it can be trusted to be the PATH.
#[cfg(unix)]
const PATH_MARKER: &str = "__TTY7_PATH__";
/// How long startup waits on the user's rc files before giving up on them.
#[cfg(unix)]
const PATH_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
/// The PATH between the first pair of markers, or `None` until both are in.
#[cfg(unix)]
fn path_from_shell_output(out: &[u8]) -> Option<String> {
let out = String::from_utf8_lossy(out);
let (_, rest) = out.split_once(PATH_MARKER)?;
let (path, _) = rest.split_once(PATH_MARKER)?;
Some(path.trim().to_string())
}
/// Runs the probe and returns the PATH as soon as the closing marker arrives,
/// without waiting for EOF: an rc that backgrounds a daemon hands it our
/// stdout, and the pipe then never closes. Past the timeout the shell is
/// killed and startup goes on with the PATH it has.
#[cfg(unix)]
fn read_path_from_shell(shell: &str, args: &[&str]) -> Option<String> {
use std::io::Read;
use std::process::{Command, Stdio};
let mut child = match Command::new(shell)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
{
Ok(child) => child,
Err(e) => {
log::warn!("failed to spawn login shell {shell} for PATH: {e}");
return None;
}
};
let mut stdout = child.stdout.take()?;
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let mut out = Vec::new();
let mut buf = [0u8; 4096];
loop {
match stdout.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => out.extend_from_slice(&buf[..n]),
}
if let Some(path) = path_from_shell_output(&out) {
let _ = tx.send(Some(path));
return;
}
}
let _ = tx.send(None);
});
let path = match rx.recv_timeout(PATH_PROBE_TIMEOUT) {
Ok(path) => path,
Err(_) => {
log::warn!(
"login shell {shell} did not report PATH within {PATH_PROBE_TIMEOUT:?}; \
continuing without it"
);
let _ = child.kill();
None
}
};
if path.is_none() {
let _ = child.kill();
}
// Reap off the startup path: after the marker the shell may still be
// running exit hooks, and none of them is worth a delay here.
std::thread::spawn(move || {
let _ = child.wait();
});
path
}
#[cfg(unix)]
fn enrich_path_from_login_shell() {
let shell = crate::core::shells::login_shell();
let fish = std::path::Path::new(&shell).file_name() == Some("fish".as_ref());
let cmd = if fish {
format!("printf '{PATH_MARKER}%s{PATH_MARKER}' (string join ':' $PATH)")
} else {
format!("printf '{PATH_MARKER}%s{PATH_MARKER}' \"$PATH\"")
};
// A pane gets an interactive shell, and for zsh/bash that is the only one
// that reads `.zshrc` / `.bashrc` — where most people put their PATH. A
// login shell alone reads `.zprofile` / `.bash_profile` and quietly hands
// back the GUI's own bare PATH, so half the tools on `PATH` in a terminal
// do not exist as far as this app is concerned. fish reads its config in
// every mode; `-i` without a tty only makes it complain on stderr.
let args: Vec<&str> = if fish {
vec!["-l", "-c", &cmd]
} else {
vec!["-i", "-l", "-c", &cmd]
};
let Some(login_path) = read_path_from_shell(&shell, &args) else {
return;
};
if login_path.is_empty() {
return;
}
let merged = merge_paths(&login_path, &std::env::var("PATH").unwrap_or_default());
unsafe { std::env::set_var("PATH", merged) };
}
#[cfg(target_os = "macos")]
fn set_dock_icon_for_bare_binary() {
use objc2::{AnyThread, MainThreadMarker};
use objc2_app_kit::{NSApplication, NSImage};
use objc2_foundation::NSData;
let bundled = std::env::current_exe().is_ok_and(|p| {
p.components()
.any(|c| c.as_os_str().to_string_lossy().ends_with(".app"))
});
if bundled {
return;
}
let Some(mtm) = MainThreadMarker::new() else {
return;
};
static ICON_PNG: &[u8] = include_bytes!("../assets/app-icon.png");
let data = NSData::with_bytes(ICON_PNG);
if let Some(image) = NSImage::initWithData(NSImage::alloc(), &data) {
unsafe {
NSApplication::sharedApplication(mtm).setApplicationIconImage(Some(&image));
}
}
}
/// Turns CoreGraphics' stroke thickening off for this process when
/// `font_thicken` is off; with it on there is nothing to do, and whatever the
/// system (or a hand-written `defaults write`) says stands.
///
/// gpui decides whether to dilate a glyph from `AppleFontSmoothing`, read with
/// `CFPreferencesCopyAppValue` the first time it rasterizes text and cached for
/// the life of the process. So this has to land before the application exists,
/// and a change waits for the next launch.
///
/// The value goes into the argument domain — the volatile one that
/// `-AppleFontSmoothing 0` on the command line would fill. It outranks both this
/// app's persisted defaults and the global domain, and it lives only in this
/// process's memory: nothing reaches disk, so no other app sees it and a later
/// launch with the key back on does not inherit it.
#[cfg(target_os = "macos")]
fn apply_font_thicken(thicken: bool) {
use objc2_foundation::{
NSArgumentDomain, NSMutableCopying, NSNumber, NSUserDefaults, ns_string,
};
if thicken {
return;
}
let defaults = NSUserDefaults::standardUserDefaults();
// SAFETY: a Foundation constant, initialized before `main` runs.
let domain = unsafe { NSArgumentDomain };
// Merged into, not replaced: the domain already holds any `-Key value`
// pairs the process was launched with.
let arguments = defaults.volatileDomainForName(domain).mutableCopy();
arguments.insert(ns_string!("AppleFontSmoothing"), &*NSNumber::new_i32(0));
// SAFETY: keys are `NSString` and values property-list objects, which is
// the shape a defaults domain requires.
unsafe { defaults.setVolatileDomain_forName(&arguments, domain) };
}
/// Delivers Finder document opens and LaunchServices URL opens after gpui has
/// created the application. The native callback queues requests; UI state is
/// then changed on gpui's application loop.
fn handle_external_opens(urls: Vec<String>, cx: &mut App) {
use crate::core::default_terminal::{ExternalOpen, parse_open_url};
for raw in urls {
let request = match parse_open_url(&raw) {
Ok(request) => request,
Err(error) => {
log::warn!("ignored external open request {raw:?}: {error}");
continue;
}
};
match request {
ExternalOpen::Folder(path) => crate::ui::windows::open_from_cli(cx, Some(path)),
ExternalOpen::Runnable(path) => {
let Some(parent) = path.parent().map(std::path::Path::to_path_buf) else {
log::warn!(
"ignored runnable without a parent directory: {}",
path.display()
);
continue;
};
let command =
crate::core::shell_quote::quote_for_shell(&path.to_string_lossy(), None);
crate::ui::windows::run_local_command(cx, parent, command);
}
ExternalOpen::Ssh(ssh) => crate::ui::windows::quick_connect_from_url(cx, ssh),
ExternalOpen::ManPage { section, page } => {
let mut command = String::from("man");
for argument in section.iter().chain(std::iter::once(&page)) {
command.push(' ');
command.push_str(&crate::core::shell_quote::quote_for_shell(argument, None));
}
crate::ui::windows::run_local_command(cx, std::env::temp_dir(), command);
}
}
}
}
fn main() {
let args: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
{
if args.first().map(std::ffi::OsString::as_os_str)
== Some(std::ffi::OsStr::new("agent-hook"))
{
if let (Some(agent), Some(event)) = (
args.get(1).and_then(|arg| arg.to_str()),
args.get(2).and_then(|arg| arg.to_str()),
) {
crate::core::agent_hooks::run_agent_hook(agent, event);
}
return;
}
}
apply_config_dir_arg(&args);
let daemon = args
.iter()
.any(|arg| arg == std::ffi::OsStr::new("--daemon"));
let mobile_helper = args
.iter()
.any(|arg| arg == std::ffi::OsStr::new(tty7_core::daemon::mobile::GATEWAY_FLAG));
let role = match (daemon, mobile_helper) {
(true, _) => "daemon",
(false, true) => "mobile",
(false, false) => "gui",
};
crate::core::crash::install(role);
crate::core::logfile::install(role);
// The Windows installer owns the Explorer context menu: a task checkbox
// runs these, and the uninstaller always runs the unregister half. Keeping
// the registry shape in `explorer_context_menu` rather than in the .iss
// means the installer and the running app can never disagree about it.
// Handled after the log file is open, because a GUI-subsystem process has
// no console to report a failure on and Inno does not surface exit codes:
// the log is the only place the reason can survive.
if let Some(register) = explorer_menu_action_from(&args) {
let result = if register {
// The verb labels are localized, and this process stops at the
// `return` below — it never reaches the `set_locale` on the GUI
// path. Without this read every install would write English
// entries, whatever language the user runs tty7 in.
crate::ui::i18n::set_locale(&Config::load().gui_language);
crate::core::explorer_context_menu::register()
} else {
crate::core::explorer_context_menu::unregister()
};
if let Err(error) = result {
log::error!("the Explorer context-menu update failed: {error}");
std::process::exit(1);
}
return;
}
// The daemon's mobile gateway, run by the daemon as its child: see
// `tty7_core::daemon::mobile`.
if mobile_helper {
let served = tty7_gateway::state::State::open_default()
.and_then(tty7_gateway::service::serve_until_stdin_closes);
if let Err(e) = served {
log::warn!("mobile gateway: {e:#}");
}
return;
}
if daemon {
if let Err(e) = crate::daemon::server::run_daemon() {
log::error!("daemon exited with error: {e}");
}
return;
}
if args
.iter()
.any(|arg| arg == std::ffi::OsStr::new("--stop-daemon"))
{
// An installer about to replace `dir` says so, and gets more than a
// stop: orphaned ConPTY hosts and anything else still running from
// that directory are terminated, and the call does not return until
// the images there are actually replaceable (or says why they are
// not). Invoked by the Inno PrepareToInstall step and the updater.
#[cfg(windows)]
if let Some(dir) = update_install_dir_from(args.iter().cloned()) {
// Held in the *parent's* name: this helper returns in seconds,
// but the Setup (or uninstaller) that invoked it keeps replacing
// files in `dir` until it exits — and a daemon spawned in that
// window would relock them. The guard needs no clearing; it goes
// stale the moment that parent is gone.
tty7_core::daemon::update_guard::hold_for_parent();
if let Err(error) = crate::daemon::spawn::stop_for_update(&dir) {
log::error!(
"preparing {} for replacement failed: {error}",
dir.display()
);
std::process::exit(1);
}
return;
}
crate::daemon::spawn::stop();
return;
}
let open_path = open_path_from(args.into_iter());
if forward_open_path(open_path.as_deref()) {
return;
}
// After the forward: a launch that only hands a path to the running
// window has no use for the PATH, and running the user's rc costs time.
#[cfg(unix)]
enrich_path_from_login_shell();
// A package the user asked to have applied at the next launch. Deliberately
// here: after the forward above, so a second launch that is really a
// request to an existing window never replaces the bundle out from under
// it, and before everything below, so there is no daemon to strand and no
// window to flash. On success the updater takes over and this process is
// done; on failure it has already discarded the plan and we start normally.
if crate::core::update::apply_pending_at_launch() {
return;
}
// If this launch *is* the relaunch an updater just performed, its outcome
// file is waiting; fold it into the update state before the first window
// reads it. Also covers the recovery relaunch after a failed install.
crate::core::update::absorb_update_outcome_at_launch();
let (config, config_outcome) = crate::core::config::Config::load_with_outcome();
let gui_language = config.gui_language.clone();
#[cfg(target_os = "macos")]
apply_font_thicken(config.font_thicken);
// After the PATH enrichment above, which is what makes the candidate scan
// see the user's real PATH rather than the stub a Finder launch inherits —
// and before the daemon below, which forks every pane and so must already
// carry the CLI's directory in its environment.
crate::core::cli_install::install(config.install_cli_on_path);
// Give desktop toasts the tty7 icon and name instead of notify-rust's
// PowerShell fallback. Best-effort; no-op off Windows.
#[cfg(target_os = "windows")]
crate::core::aumid::init();
let restore_session = config.restore_session;
let daemon_result = if restore_session {
crate::daemon::spawn::ensure_running()
} else {
crate::daemon::spawn::restart()
};
// A pathless launch that found a GUI already registered hands the request
// to it — the GUI may be sitting in the tray with no window — and exits.
// The forward above cannot do this: it runs before the daemon exists, and
// routing through a daemon that is not up yet would fail on every cold
// start. Here the daemon is known to be running, so the probe is cheap and
// a `Bool(true)` means a GUI actually received the request.
if open_path.is_none() && daemon_result.is_ok() && forward_open_path(None) {
return;
}
if let Err(e) = daemon_result {
log::error!("failed to ensure daemon is running: {e}");
}
// `Application`, not the in-loop `App`, owns the native delegate. Register
// before `run` so macOS can deliver Finder and URL events from launch.
let (external_open_tx, external_open_rx) = smol::channel::unbounded();
let application = gpui_platform::application()
.with_assets(Assets)
// The window-close path decides whether this process survives: with
// the tray icon on, closing the last window retires to the tray, and
// without it the close handler quits explicitly. The platform default
// would quit on the last window unconditionally, which is exactly the
// orphaned-daemon trap the tray is meant to prevent.
.with_quit_mode(QuitMode::Explicit);
application.on_open_urls(move |urls| {
let _ = external_open_tx.try_send(urls);
});
// macOS relaunching an app that is already running — the Dock icon, a
// double-click on the bundle, `open -a tty7` — only reaches this process
// as `applicationShouldHandleReopen:`, and gpui's delegate does nothing
// with it unless a handler is registered. That is the one entrance a
// tray-resident tty7 has: with `show_tray_icon` on, closing the last
// window keeps the process and its Dock icon alive with nothing on
// screen, and without this the icon's click was a no-op (the only ways
// back in were ⌘N, the tray's "Show tty7", or quitting and relaunching).
// Like `on_open_urls`, the hook lives on `Application`, so it cannot go
// beside the other app-level handlers in `keymap::init`; and like that
// path it defers to the loop rather than opening windows on AppKit's
// delegate stack, which is also how Zed's own reopen handler runs.
application.on_reopen(|cx| {
cx.spawn(async move |cx| {
let _ = cx.update(crate::ui::windows::reopen);
})
.detach();
});
application.run(move |cx| {
// gpui invokes this callback without an `App` context. Bridge it
// back onto the application loop instead of touching UI state on
// AppKit's delegate call stack.
cx.spawn(async move |cx| {
while let Ok(urls) = external_open_rx.recv().await {
let _ = cx.update(|cx| handle_external_opens(urls, cx));
}
})
.detach();
gpui_component::init(cx);
register_bundled_fonts(cx);
crate::ui::prompt::install(cx);
cx.activate(true);
#[cfg(target_os = "macos")]
set_dock_icon_for_bare_binary();
crate::ui::i18n::set_locale(&gui_language);
// The load above is reused rather than re-read: reading the same
// file twice at launch would report the same failure twice.
cx.set_global(config);
crate::ui::theme::refresh_system_appearance(cx);
crate::core::session::WorkspaceStore::init(cx);
crate::ui::windows::WindowRegistry::init(cx);
crate::ui::presets::load_registry(cx);
crate::ui::theme::apply_cursor_hide_mode(cx);
spawn_config_watcher(cx);
crate::core::update::spawn_check(cx);
crate::core::update::install_image_client(cx);
cx.background_executor()
.spawn(async {
crate::core::agent_hooks::refresh_hooks_at_launch();
})
.detach();
keymap::init(cx);
crate::ui::local_link::LocalLink::install(cx);
let reopen = crate::ui::windows::restore_target(cx, open_path.as_deref());
crate::ui::windows::open_at(cx, reopen.map(|(id, _)| id), open_path);
crate::ui::windows::announce_detached_at_launch(cx, reopen);
if config_outcome.failed() {
notify_config_load_failed(cx, config_outcome, true);
}
});
}
/// The watcher tick, from a reloaded file to the keys the app dispatches on.
///
/// The one thing #548 is for — hand-editing config.json and having the new
/// chord fire without a restart — crosses a file watcher, a debounce and a
/// keymap rebuild, and used to be covered nowhere. These drive
/// `apply_reloaded_config` directly, which is the whole body of the watcher's
/// tick, so the reload path is exercised without waiting on the filesystem.
#[cfg(test)]
mod config_reload_tests {
use super::{apply_reloaded_config, is_theme_file};
use crate::core::actions::SplitRight;
use crate::core::config::{Config, LoadOutcome};
use gpui::{Action as _, App, KeyContext, Keystroke, TestAppContext};
/// What the live keymap — the one gpui dispatches against — does with
/// `keys` typed in a terminal.
fn dispatched(cx: &App, keys: &str) -> Vec<&'static str> {
let typed = [Keystroke::parse(keys).expect("the typed keystroke parses")];
let context = [KeyContext::parse("Terminal").expect("the context parses")];
cx.key_bindings()
.borrow()
.bindings_for_input(&typed, &context)
.0
.iter()
.map(|b| b.action().name())
.collect()
}
/// An app running on `config`, as far as the config watcher can tell:
/// the globals its tick reads, and a keymap built from that config.
fn running_on(cx: &mut App, config: Config) {
let dir = std::env::temp_dir().join(format!("tty7-reload-{}", std::process::id()));
std::fs::create_dir_all(&dir).ok();
crate::core::config::set_config_dir(dir);
gpui_component::init(cx);
cx.set_global(config);
crate::ui::windows::WindowRegistry::init(cx);
crate::ui::presets::load_registry(cx);
crate::ui::keymap::init(cx);
}
fn bound_to_split_right(config: &mut Config, key: &str) {
config.keybindings.insert(
"SplitRight".to_string(),
crate::core::config::KeybindingOverride::Add(key.to_string()),
);
}
#[gpui::test]
fn a_hand_edited_binding_fires_without_a_restart(cx: &mut TestAppContext) {
cx.update(|cx| {
running_on(cx, Config::default());
assert!(
dispatched(cx, "ctrl-alt-9").is_empty(),
"nothing is on the chord before the edit"
);
let mut edited = Config::default();
bound_to_split_right(&mut edited, "ctrl-alt-9");
let mut announced = false;
assert!(
apply_reloaded_config(cx, (edited, LoadOutcome::Parsed), &mut announced),
"a moved binding rebuilds the keymap"
);
assert_eq!(
dispatched(cx, "ctrl-alt-9"),
vec![SplitRight::name_for_type()],
"the hand-edited chord reaches the keymap gpui dispatches on"
);
});
}
#[gpui::test]
fn a_save_that_moves_no_binding_leaves_the_keymap_alone(cx: &mut TestAppContext) {
cx.update(|cx| {
running_on(cx, Config::default());
// The app's own `save()` fires this watcher on every sidebar drag.
let mut unrelated = Config::default();
unrelated.dim_inactive_panes = !unrelated.dim_inactive_panes;
let mut announced = false;
assert!(
!apply_reloaded_config(
cx,
(unrelated.clone(), LoadOutcome::Parsed),
&mut announced
),
"an unrelated save must not rebuild the keymap"
);
assert_eq!(
cx.global::<Config>().dim_inactive_panes,
unrelated.dim_inactive_panes,
"the reload still took effect; only the rebind was skipped"
);
});
}
#[gpui::test]
fn a_broken_config_does_not_take_the_users_keys_away(cx: &mut TestAppContext) {
cx.update(|cx| {
let mut user = Config::default();
bound_to_split_right(&mut user, "ctrl-alt-9");
running_on(cx, user);
assert_eq!(
dispatched(cx, "ctrl-alt-9"),
vec![SplitRight::name_for_type()]
);
// A quarantined load hands back stand-in defaults, and the global
// is deliberately left alone — so nothing may rebind off them.
let mut announced = false;
assert!(
!apply_reloaded_config(
cx,
(Config::default(), LoadOutcome::Quarantined),
&mut announced
),
"a load that failed has nothing to compare and must not rebind"
);
assert!(announced, "the breakage is announced");
assert_eq!(
cx.global::<Config>().keybindings.get("SplitRight"),
Some(&crate::core::config::KeybindingOverride::Add(
"ctrl-alt-9".to_string()
)),
"the running config survives the broken file"
);
assert_eq!(
dispatched(cx, "ctrl-alt-9"),
vec![SplitRight::name_for_type()],
"and so do the keys the app is dispatching on"
);
// The file parses again: the latch clears, so a second breakage
// can speak up.
let mut fixed = Config::default();
bound_to_split_right(&mut fixed, "ctrl-alt-8");
assert!(apply_reloaded_config(
cx,
(fixed, LoadOutcome::Parsed),
&mut announced
));
assert!(!announced);
assert_eq!(
dispatched(cx, "ctrl-alt-8"),
vec![SplitRight::name_for_type()]
);
assert!(
dispatched(cx, "ctrl-alt-9").is_empty(),
"the chord the fixed file dropped is retired"
);
});
}
/// The watcher covers the whole config directory, and the themes half of
/// it has to keep reloading even when config.json does not parse.
#[test]
fn only_theme_files_beside_the_config_count_as_themes() {
use std::path::Path;
assert!(is_theme_file(Path::new("/cfg/themes/solar.yaml")));
assert!(is_theme_file(Path::new("/cfg/themes/solar.YML")));
assert!(is_theme_file(Path::new("/cfg/themes/solar.itermcolors")));
assert!(!is_theme_file(Path::new("/cfg/themes/notes.txt")));
assert!(!is_theme_file(Path::new("/cfg/config.json")));
assert!(!is_theme_file(Path::new("/cfg/solar.yaml")));
}
}
#[cfg(all(test, unix))]
mod tests {
use super::{merge_paths, path_from_shell_output};
#[test]
fn path_from_shell_output_reads_between_the_markers() {
// The shape `zsh -i` actually prints: an rc that greets the user, the
// `can't change option: zle` chatter `-i` earns without a tty, and an
// exit hook that prints after the PATH.
assert_eq!(
path_from_shell_output(
b"hello\n(eval):1: can't change option: zle\n\
__TTY7_PATH__/opt/bin:/usr/bin__TTY7_PATH__bye\n"
)
.as_deref(),
Some("/opt/bin:/usr/bin")
);
assert_eq!(
path_from_shell_output(b"hello\n__TTY7_PATH__/opt/bin"),
None
);
assert_eq!(path_from_shell_output(b"/opt/bin:/usr/bin\n"), None);
}
#[test]
fn merge_paths_prefers_primary_dedupes_and_drops_empties() {
assert_eq!(
merge_paths("/opt/homebrew/bin:/usr/bin", "/usr/bin:/bin:"),
"/opt/homebrew/bin:/usr/bin:/bin"
);
assert_eq!(
merge_paths(
"/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin",
"/usr/bin:/bin"
),
"/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin"
);
assert_eq!(merge_paths("", "/usr/bin"), "/usr/bin");
}
}
#[cfg(test)]
mod argument_tests {
use super::{
config_dir_from, explorer_menu_action_from, forward_open_path_with, open_path_from,
};
use std::ffi::OsString;
use std::path::PathBuf;
use tty7_core::daemon::control::ReplyOk;
/// The installer passes exactly one of these; every other launch — above
/// all a plain `--open-path` from the very menu they register — must fall
/// through to normal startup instead of rewriting the registry and exiting.
#[test]
fn explorer_menu_flags_are_distinguished_and_otherwise_absent() {
assert_eq!(
explorer_menu_action_from(&[OsString::from("--register-explorer-menu")]),
Some(true)
);
assert_eq!(
explorer_menu_action_from(&[OsString::from("--unregister-explorer-menu")]),
Some(false)
);
assert_eq!(
explorer_menu_action_from(&[OsString::from("--open-path"), OsString::from("/work")]),
None
);
assert_eq!(explorer_menu_action_from(&[]), None);
}
#[test]
fn open_path_accepts_separate_and_equals_forms() {
let separate = open_path_from(
["--config-dir", "/cfg", "--open-path", "/work"]
.into_iter()
.map(OsString::from),
);
assert_eq!(separate, Some(PathBuf::from("/work")));
let equals = open_path_from([OsString::from("--open-path=C:\\work")].into_iter());
assert_eq!(equals, Some(PathBuf::from("C:\\work")));
}
#[test]
fn config_dir_accepts_native_separate_and_equals_forms() {
let separate = config_dir_from(
[OsString::from("--config-dir"), OsString::from("C:\\cfg")].into_iter(),
);
assert_eq!(separate, Some(PathBuf::from("C:\\cfg")));
let equals = config_dir_from([OsString::from("--config-dir=C:\\cfg")].into_iter());
assert_eq!(equals, Some(PathBuf::from("C:\\cfg")));
}
#[cfg(windows)]
#[test]
fn open_path_preserves_unpaired_utf16_from_windows_arguments() {
use std::os::windows::ffi::OsStringExt as _;
let native_path =
OsString::from_wide(&[b'C' as u16, b':' as u16, b'\\' as u16, 0xD800, b'x' as u16]);
let parsed =
open_path_from([OsString::from("--open-path"), native_path.clone()].into_iter());
assert_eq!(parsed, Some(PathBuf::from(native_path.clone())));
let mut equals_arg = OsString::from("--open-path=");
equals_arg.push(&native_path);
assert_eq!(
open_path_from([equals_arg].into_iter()),
Some(PathBuf::from(native_path))
);
}
#[test]
fn a_pathless_forward_asks_the_gui_to_surface_and_exits_only_on_bool_true() {
let delivered = forward_open_path_with(
None,
|| false,
|actual| {
assert_eq!(actual, None, "a pathless request carries no wire path");
Ok(ReplyOk::Bool(true))
},
);
assert!(delivered, "a GUI accepted the surface request");
assert!(!forward_open_path_with(
None,
|| false,
|_| Ok(ReplyOk::Bool(false))
));
assert!(!forward_open_path_with(
None,
|| false,
|_| Ok(ReplyOk::Unit)
));
assert!(!forward_open_path_with(
None,
|| false,
|_| {
Err(std::io::Error::new(
std::io::ErrorKind::ConnectionRefused,
"daemon is not running",
))
}
));
}
#[test]
fn early_dispatch_is_skipped_when_the_recorded_daemon_is_dead() {
// A dead recorded daemon cannot be routing for a registered GUI, so the
// probe must not run — the connect would only wait out the OS's refusal
// delay on the stale control port before `ensure_running` clears it.
assert!(!forward_open_path_with(
None,
|| true,
|_| -> std::io::Result<ReplyOk> {
panic!("the probe must not dispatch when the daemon is dead")
},
));
assert!(!forward_open_path_with(
Some(std::path::Path::new("/work")),
|| true,
|_| -> std::io::Result<ReplyOk> {
panic!("the probe must not dispatch when the daemon is dead")
},
));
}
#[test]
fn early_dispatch_exits_only_after_a_gui_accepts_the_path() {
let path = std::env::current_dir().unwrap().join("folder with spaces");
let expected = path.to_str().unwrap().to_owned();
let delivered = forward_open_path_with(
Some(&path),
|| false,
|actual| {
assert_eq!(actual, Some(expected));
Ok(ReplyOk::Bool(true))
},
);
assert!(delivered);
assert!(!forward_open_path_with(
Some(&path),
|| false,
|_| Ok(ReplyOk::Bool(false))
));
assert!(!forward_open_path_with(
Some(&path),
|| false,
|_| Ok(ReplyOk::Unit)
));
assert!(!forward_open_path_with(
Some(&path),
|| false,
|_| {
Err(std::io::Error::new(
std::io::ErrorKind::ConnectionRefused,
"daemon is not running",
))
}
));
}
#[test]
fn early_dispatch_resolves_relative_paths_before_cross_process_delivery() {
let relative = std::path::Path::new("workspace");
let expected = std::env::current_dir()
.unwrap()
.join(relative)
.to_str()
.unwrap()
.to_owned();
assert!(forward_open_path_with(
Some(relative),
|| false,
|actual| {
assert_eq!(actual, Some(expected));
Ok(ReplyOk::Bool(true))
}
));
}
#[cfg(unix)]
#[test]
fn early_dispatch_keeps_non_utf8_paths_in_the_current_process() {
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt as _;
let path = std::env::temp_dir().join(OsString::from_vec(b"tty7-\xff".to_vec()));
let delivered = forward_open_path_with(
Some(&path),
|| false,
|_| panic!("a non-UTF-8 path must never be changed and sent over the string protocol"),
);
assert!(!delivered);
}
}