Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Make TUI welcome and New Harness start with the task (#688)

Deef70b02788403
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index cf8148aae..4ac43f28d 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -811,7 +811,7 @@ describe('BackendSocket outbound queue', () => {
const asked: Array<[string, number | undefined]> = []
socket.sessionSearchProvider = (query, options) => {
asked.push([query, options.limit])
- return { hits: [], indexed: 3, pending: 0, tookMs: 1 }
+ return { hits: [], indexed: 3, pending: 0, ready: true, tookMs: 1 }
}
socket.connect()
const ws = wsMock.instances[0]
@@ -825,7 +825,7 @@ describe('BackendSocket outbound queue', () => {
unwrap.mockReturnValueOnce({ type: 'session_search', payload: { requestId: 's-1', query: 'dial scroll', limit: 12 } })
ws.message({ t: 'down', connId: 'web-1', frame: { type: 'session_search', payload: envelope } })
await vi.waitFor(() => {
- expect(wrapReply).toHaveBeenCalledWith('web-1', 'session_search_result', 's-1', { hits: [], indexed: 3, pending: 0, tookMs: 1 })
+ expect(wrapReply).toHaveBeenCalledWith('web-1', 'session_search_result', 's-1', { hits: [], indexed: 3, pending: 0, ready: true, tookMs: 1 })
})
expect(asked).toEqual([['dial scroll', 12]])
diff --git a/cli/src/lib/sessionSearch/indexer.spec.ts b/cli/src/lib/sessionSearch/indexer.spec.ts
index 8142c62eb..1195fcb4e 100644
--- a/cli/src/lib/sessionSearch/indexer.spec.ts
+++ b/cli/src/lib/sessionSearch/indexer.spec.ts
@@ -39,6 +39,54 @@ function setup(initial: string, agents?: () => string[]) {
}
describe('SessionSearchIndex', () => {
+ it('discovers on first search and distinguishes an unfinished scan from empty history', async () => {
+ const store = SessionSearchStore.open(':memory:')!
+ let finish!: () => void
+ const discover = vi.fn(() => new Promise<void>((resolve) => { finish = resolve }))
+ const index = new SessionSearchIndex({ store, sources: () => [], discover })
+ cleanups.push(() => { index.stop(); store.close() })
+ index.start(60_000)
+ expect(index.search('')).toMatchObject({ hits: [], ready: false, pending: 0 })
+ await Promise.resolve()
+ expect(discover).toHaveBeenCalledTimes(1)
+ index.search('')
+ index.sweep()
+ expect(discover).toHaveBeenCalledTimes(1)
+ finish()
+ await vi.waitFor(() => expect(index.search('')).toMatchObject({ hits: [], ready: true }))
+ })
+
+ it('keeps readiness false through the final indexing pass, then returns discovered history', async () => {
+ const store = SessionSearchStore.open(':memory:')!
+ let finish!: (events: LiveEvent[]) => void
+ const index = new SessionSearchIndex({ store, sources: () => [{
+ agentId: '', sessionId: 'existing-codex', engine: 'codex', transcriptPath: null,
+ header: '', changedAt: Date.now(), external: { cwd: '/repo', origin: 'terminal', title: 'Existing work' },
+ readHistory: () => new Promise<LiveEvent[]>((resolve) => { finish = resolve }),
+ }] })
+ cleanups.push(() => { index.stop(); store.close() })
+ expect(index.search('')).toMatchObject({ ready: false, pending: 0 })
+ finish([{ type: 'user_message', payload: { content: 'fix welcome' } }])
+ await vi.waitFor(() => {
+ const result = index.search('', { from: 0, to: Date.now() + 1 })
+ expect(result.ready).toBe(true)
+ expect(result.hits[0]).toMatchObject({ sessionId: 'existing-codex', external: { title: 'Existing work' } })
+ })
+ })
+
+ it('reports discovery failure and lets a later search retry without overlapping scans', async () => {
+ const store = SessionSearchStore.open(':memory:')!
+ const discover = vi.fn().mockRejectedValueOnce(new Error('not ready')).mockResolvedValue(undefined)
+ const index = new SessionSearchIndex({ store, sources: () => [], discover })
+ cleanups.push(() => { index.stop(); store.close() })
+ index.search('')
+ await vi.waitFor(() => expect(index.search('')).toMatchObject({ ready: false, discoveryError: true }))
+ expect(discover).toHaveBeenCalledTimes(1)
+ index.sweep()
+ await vi.waitFor(() => expect(index.search('').ready).toBe(true))
+ expect(discover).toHaveBeenCalledTimes(2)
+ })
+
it('does not resurrect deleted conversation history from an in-flight pass or stale source list', async () => {
const { index, found, settle, store } = setup(prompt('purge search history', 0) + answer('sensitive fixture', 1))
await settle()
diff --git a/cli/src/lib/sessionSearch/indexer.ts b/cli/src/lib/sessionSearch/indexer.ts
index 33c984413..e9b39a2fa 100644
--- a/cli/src/lib/sessionSearch/indexer.ts
+++ b/cli/src/lib/sessionSearch/indexer.ts
@@ -84,6 +84,10 @@ export interface SessionSearchResult {
/** Sessions in the index, and sessions still waiting for their first pass. */
indexed: number
pending: number
+ /** False until discovery and its queued first passes have finished. */
+ ready: boolean
+ /** A scan failed; any cached hits are still usable and a later search retries it. */
+ discoveryError?: boolean
tookMs: number
}
@@ -135,6 +139,10 @@ export class SessionSearchIndex {
private stopped = false
private sweepTimer: NodeJS.Timeout | null = null
private sliceStart = 0
+ private initialized = false
+ private discovering = false
+ private discoveryFailed = false
+ private discoveryStartedAt: number | undefined
/** Callers waiting for a session's next pass (`tail`). */
private readonly waiters = new Map<string, Array<() => void>>()
@@ -191,14 +199,28 @@ export class SessionSearchIndex {
/** Queue every known session, newest first; drop sessions whose agent no longer exists. */
sweep(): void {
- if (this.stopped) return
+ if (this.stopped || this.discovering) return
+ this.discovering = true
+ this.discoveryFailed = false
+ this.discoveryStartedAt = Date.now()
+ const finish = (failed = false) => {
+ if (this.stopped) { this.discovering = false; return }
+ this.discoveryFailed = failed
+ try { this.sweepSources() }
+ catch (error) {
+ this.discoveryFailed = true
+ this.opts.log?.(`[search] source discovery failed: ${error instanceof Error ? error.message : String(error)}`)
+ }
+ this.initialized = true
+ this.discovering = false
+ }
if (this.opts.discover) {
// Which of them are open, looked at now: a search reads it without waiting.
void this.opts.openSessions?.fresh().catch(() => undefined)
- void this.opts.discover().catch(() => undefined).then(() => this.sweepSources())
+ void Promise.resolve().then(() => this.opts.discover!()).then(() => finish(), () => finish(true))
return
}
- this.sweepSources()
+ finish()
}
private sweepSources(): void {
@@ -218,6 +240,10 @@ export class SessionSearchIndex {
search(query: string, options: { limit?: number; from?: number; to?: number } = {}): SessionSearchResult {
const started = performance.now()
+ // Opening welcome/search is an explicit demand for history. Start the first scan now,
+ // without blocking this request or waiting for the daemon's deferred boot sweep.
+ if ((!this.initialized || this.discoveryFailed) && !this.discovering &&
+ (this.discoveryStartedAt === undefined || Date.now() - this.discoveryStartedAt >= 1_000)) this.sweep()
const hits = this.opts.store.search(query, options)
// Whether a terminal still has it, as last looked: a search never waits for a process table.
if (hits.some((hit) => hit.external) && this.opts.openSessions) {
@@ -230,7 +256,10 @@ export class SessionSearchIndex {
}
}
const indexed = this.opts.store.counts().sessions
- return { hits, indexed, pending: this.queue.size, tookMs: Math.round((performance.now() - started) * 10) / 10 }
+ return { hits, indexed, pending: this.queue.size,
+ ready: this.initialized && !this.discovering && !this.discoveryFailed && !this.running && this.queue.size === 0,
+ ...(this.discoveryFailed ? { discoveryError: true } : {}),
+ tookMs: Math.round((performance.now() - started) * 10) / 10 }
}
/**
diff --git a/docs/validation-and-release.md b/docs/validation-and-release.md
index 3b0ed67c0..a2f103587 100644
--- a/docs/validation-and-release.md
+++ b/docs/validation-and-release.md
@@ -158,7 +158,7 @@ removes those objects and the consumed candidate. It cannot publish a product.
Native TUI CI tests and builds the shipped musl target in the same Cargo output
directory. Dependency caches are keyed by target, Rust toolchain, and Cargo inputs;
-cache hits still run every test. The ten native TUI fixtures run two at a time,
+cache hits still run every test. The eleven native TUI fixtures run two at a time,
using their own homes, socket names, and mock ports. CI retains each fixture's log
and validation receipt as an artifact. To run the same set locally after building:
diff --git a/scripts/validate-tui-native.py b/scripts/validate-tui-native.py
index 62066aa2f..dcf11e9e0 100644
--- a/scripts/validate-tui-native.py
+++ b/scripts/validate-tui-native.py
@@ -28,13 +28,14 @@ def main():
"timeout_seconds": 120,
}
- # All ten native checks from CI, with the longest first. Each fixture uses
+ # The native checks from CI and the welcome journey, with the longest first. Each fixture uses
# its own HOME, socket prefix, mock port(s), and cleanup. Two workers leave
# capacity for their PTY children; deadlines and assertions are unchanged.
checks = [
fixture("reconnect", "HN_RECONNECT_TEST_BINARY", "HN_RECONNECT_TEST_PORT", 19781),
fixture("layout-sync", "HN_LAYOUT_TEST_BINARY", "HN_LAYOUT_TEST_PORT", 19801),
fixture("new-harness", "HN_NEW_UI_BINARY", "HN_NEW_UI_PORT", 19786),
+ fixture("welcome", "HN_WELCOME_TEST_BINARY", "HN_WELCOME_TEST_PORT", 19787),
fixture("local-shells", "HN_LOCAL_TEST_BINARY", "HN_LOCAL_TEST_PORT", 19441),
fixture("native-terminal", "HN_NATIVE_TEST_BINARY", "HN_NATIVE_TEST_PORT", 19433),
fixture("pane-ui", "HN_PANE_UI_BINARY", "HN_PANE_UI_PORT", 19783),
diff --git a/tui/README.md b/tui/README.md
index 6de04267d..72ef6f578 100644
--- a/tui/README.md
+++ b/tui/README.md
@@ -144,7 +144,7 @@ sends a plain Enter).
| tmux keys | |
|---|---|
| `C-b s` | every harness on every machine — an fzf list with a live preview |
-| `C-b c` | new window, on the home page: your recent harnesses and the Claude Code and Codex conversations Harness did not start (last 30 days, every machine) — `1…9` opens one there (or `↑`/`↓` then `enter`; a conversation resumed as a harness). Anything you type starts a shell there with your keys in it, as after tmux's `C-b c`: `C-b c` then `claude⏎` runs `claude`. `new-window` from a script, or with options (`-c`, a command…), makes the shell at once, as tmux does; `set -g @hn-new-window shell` (or `@hn-look tmux`) makes the key tmux's too |
+| `C-b c` | new window with the task-first creation form. Type a task and Enter to start; Open Terminal opens a shell. Up to three recent sessions and Browse All Sessions appear below. `new-window` from a script, or with options (`-c`, a command…), makes the shell at once, as tmux does; `set -g @hn-new-window shell` (or `@hn-look tmux`) keeps that behavior for the key and startup too |
| `C-b %` `C-b "` (and `C-b \|` for `%`) | split right / below — a shell, at once, in this pane's machine and folder (`C-b -` is tmux's delete-buffer) |
| `C-b o` `C-b ;` `C-b ←↑→↓` `C-b q` | next pane, last pane, pane in a direction, pane numbers |
| `C-b z` `C-b space` `C-b M-1…7` `C-b { }` `C-b C-o` | zoom, next layout, a layout, swap, rotate |
@@ -163,22 +163,23 @@ Harness's own, only on keys tmux leaves unbound (every tmux key does what tmux d
| | |
|---|---|
| `C-b a` / `C-b A` | the next harness that needs you (`next-harness`) / all those waiting on you (`M-1…9` answers from the list; `M-a` types an answer — an option's number, several for a multi-choice question, `1,3`, or your own words) |
-| `C-b N` `C-b T` | New Harness popup / new terminal. Agent, Project and optional Task sit above Branch, Worktree, Model, Approvals and applicable Profile, with searchable choices. |
+| `C-b N` `C-b T` | New Harness popup / new terminal. The optional Task is focused first, above Agent, Project, Branch, Worktree, Model, Approvals and applicable Profile, with searchable choices. |
| `C-b I` `C-b @` `C-b S` | models, machines, the Harness Store |
| `C-b g` `C-b B` | send a task (Harness picks the harness) / broadcast to the window |
| `C-b R` `C-b P` `C-b K` | restart, pause, clone the harness |
-`C-b N` opens a compact, centered New Harness form. Agent, Project and optional Task come first,
-then a blank row separates Branch, Worktree, Model, Approvals and applicable Profile.
+`C-b N` opens a compact, centered New Harness form with the task ready to type at the top.
+Agent and Project follow, then Branch, Worktree, Model, Approvals and applicable Profile.
All settings are visible without expanding Options. Project reads `project @ local`, or
`project @ machine` for a remote destination; focusing it shows the full path below.
The initial destination is the connected local Harness machine, with successful agent
and project choices remembered. Explicit project commands keep their destination. Enter starts
with the displayed choices; the action names the selected agent (for example, Start Codex).
-Up/Down moves between fields and previews their choices on the right. Enter,
-Right or typing enters the chooser. Tab switches between the form and chooser; Enter accepts
-an item and returns to New Harness. A second Enter starts it in the current window, splitting
-beside the focused pane when needed. Lowercase `C-b n` remains next window.
+Tab/Shift-Tab moves between fields. Outside the task editor, Up/Down also moves between fields
+and previews their choices on the right. Enter, Right or typing enters a chooser; Enter accepts
+an item and focuses Start. Enter in the task editor starts immediately. The harness opens in
+the window that requested it, splitting beside the focused pane when needed. Switching windows
+while it starts leaves your new window focused. Lowercase `C-b n` remains next window.
Agent combines coding agents and installed Store harnesses; a Store harness then offers its
compatible coding agents. Project offers Clone Repository, Open Folder, New Folder and recent
@@ -187,8 +188,12 @@ a path. Project search includes the 50 most recently active distinct folders per
duplicate sessions in one folder count once. Combine a machine name and folder, such as
`office harness` or `m2 harness`, in either order. The local machine's actual
name remains searchable when its label says `local`.
-Task opens an editor beside the form: Enter accepts, Alt-Enter inserts a newline,
-and pasted tasks retain line breaks. Escape preserves the task in the draft. Supported agents
+Task is edited directly in the form: Enter starts, Alt-Enter inserts a newline, and pasted tasks
+retain line breaks. Enhanced terminals can use Shift-Enter too. Arrow keys navigate wrapped
+lines; Home/End, Ctrl-A/E, word movement/deletion, Ctrl-U/K and Ctrl-Y work in the editor.
+On the welcome screen, `C-b ]` also pastes into the task, preserving its line breaks.
+The popup keeps text-editor keys directly, as a tmux prompt does; Escape closes it with the draft kept.
+Unicode graphemes stay intact. Escape preserves a dismissed dialog's task. Supported agents
receive it as their first message; an unavailable first task or one exceeding the daemon's
2,000-character limit is explained before launch. A blank task starts an ordinary session.
Git projects default to a new worktree from main, as on desktop; missing main requires a branch
@@ -203,7 +208,19 @@ to its right; in narrow terminals they temporarily occupy the form's place. Esca
nested choosers and preserves a dismissed draft. Confirmed failures keep the draft and reuse
any prepared project folder on retry. A lost reply offers Check status for the original launch;
repeated Enter cannot start another harness while its outcome is unknown. Input in the form
-never reaches a working pane. No reverse-video selection is used.
+never reaches a working pane.
+
+A fresh startup and `C-b c` use the same form, with a separate draft per window. The welcome
+screen explains the first task; later windows inherit the machine and folder they were opened
+from. Up to three recent sessions appear below the creation actions; Browse All Sessions opens
+the full launcher. Existing Claude Code, Codex and other supported histories are discovered on
+connected machines. Loading, empty and unavailable history have distinct states; Ctrl-R retries
+discovery. Digits and plain-key bindings belong to the task while you type. Your modified prefix
+(for example Ctrl-B) still switches windows and opens commands. With a plain prefix such as a
+backtick, Tab to a setting first to use it for navigation. Open Terminal is explicit and
+never sends the task to a shell. With the daemon offline, a task can be prepared while the local
+terminal remains available. Existing workspaces still restore as usual. Harness OS keeps its
+dedicated installation, network and first-launch actions.
In the harness and command lists, fzf's keys: `C-j/C-k` `C-n/C-p` move, `Tab` marks, `C-/` toggles the preview,
diff --git a/tui/docs/new-harness.png b/tui/docs/new-harness.png
index 89556815d..9385b3ba7 100644
Binary files a/tui/docs/new-harness.png and b/tui/docs/new-harness.png differ
diff --git a/tui/src/app.rs b/tui/src/app.rs
index 0d74fffdd..aa6d2bff7 100644
--- a/tui/src/app.rs
+++ b/tui/src/app.rs
@@ -518,19 +518,10 @@ pub struct App {
/// When the prefix was pressed: a pause after it shows the keys (which-key).
pub prefix_at: Option<Instant>,
pub tick: u64,
- pub home_cursor: usize,
- /// The home page's selection moved by you (until then Enter, like any key, starts a shell).
- pub home_moved: bool,
/// More commands of the same line or binding wait behind the one running.
pub chain_follows: bool,
- /// The Claude Code and Codex conversations Harness did not start that the home page offers
- /// (each machine's session index, asked once each time the page shows), and the machines
- /// asked so far.
+ /// Saved conversations discovered on connected machines for the welcome composer.
pub home_external: Vec<External>,
- pub home_asked: HashSet<String>,
- home_shown: bool,
- /// The pane C-b c was pressed from: the machine and folder the home page's shell (t) takes.
- pub home_from: Option<(String, String)>,
/// C-b s's search by what was said (each machine's session_search): the query wanted and when
/// to ask (a moment after the last key), the query the hits answer, and the hits.
pub said_want: String,
@@ -555,6 +546,7 @@ pub struct App {
pub dsh: HashMap<String, Vec<Value>>,
/// A dismissed New Harness draft, including any pending creation receipt.
pub new_harness_draft: Option<Box<crate::new_harness::Form>>,
+ pub welcome: crate::new_harness::Welcome,
/// ── models: the Models view's replies (local models, grids, APIs) and a Use under way ──
pub models_view: crate::models::Models,
/// Each machine's last measured round trip (the live roster request), for `@`.
@@ -987,13 +979,8 @@ impl App {
hup_parent: false,
prefix: false,
tick: 0,
- home_cursor: 0,
- home_moved: false,
chain_follows: false,
home_external: Vec::new(),
- home_asked: HashSet::new(),
- home_shown: false,
- home_from: None,
said_want: String::new(),
said_due: None,
said_pending: 0,
@@ -1014,6 +1001,7 @@ impl App {
daemon_down: false,
dsh: HashMap::new(),
new_harness_draft: None,
+ welcome: Default::default(),
models_view: Default::default(),
rtt: HashMap::new(),
homes: HashMap::new(),
@@ -4784,8 +4772,6 @@ impl App {
let at = self.tabs.iter().position(|t| self.nums.get(&t.id).map(|m| *m > n).unwrap_or(false)).unwrap_or(self.tabs.len());
self.tabs.insert(at, tab);
self.active = at;
- self.home_cursor = 0;
- self.home_moved = false;
self.home_order.borrow_mut().clear();
self.fit_panes();
}
@@ -4812,7 +4798,6 @@ impl App {
let at = self.tabs.iter().position(|t| self.nums.get(&t.id).map(|m| *m > n).unwrap_or(false)).unwrap_or(self.tabs.len());
self.tabs.insert(at, tab);
self.active = at;
- self.home_cursor = 0;
self.home_order.borrow_mut().clear();
self.fit_panes();
}
@@ -5299,8 +5284,16 @@ impl App {
// The desk's first shell: where hn was started (-c: where it was asked to), running what
// `hn new` asked for.
let start = self.start_session.take().unwrap_or_default();
+ let welcome = start.command.is_none() && start.cwd.is_none() && start.window.is_none()
+ && !start.create && self.options.get("@hn-new-window", "", None).as_deref() != Some("shell")
+ && self.options.get("@hn-look", "", None).as_deref() != Some("tmux");
let cwd = start.cwd.or_else(|| std::env::current_dir().ok().map(|d| d.display().to_string()));
- crate::input::new_shell_from(self, None, Placement::Auto(None), cwd, start.command);
+ if welcome {
+ self.tab_mut().home = true;
+ crate::new_harness::ensure_welcome(self, None, cwd.clone());
+ let tab = self.tab().id.clone();
+ crate::input::new_shell_from(self, None, Placement::Fill(tab), cwd, start.command);
+ } else { crate::input::new_shell_from(self, None, Placement::Auto(None), cwd, start.command); }
}
fn fetch_desk(&mut self) {
@@ -5687,31 +5680,6 @@ impl App {
/// The home page is on screen: a window with nothing in it, nothing over it.
pub fn home_visible(&self) -> bool { self.modal.is_none() && self.tabs.get(self.active).map(|t| t.home || t.root.is_none()).unwrap_or(false) }
- /// The home page's conversations Harness did not start: each connected machine asked once
- /// while the page shows (`session_search` with a time and no words: the last 30 days), as the
- /// desktop's welcome page asks; one that connects meanwhile is asked too. Read afresh the next
- /// time the page shows.
- fn ask_home_external(&mut self) {
- let shown = self.home_visible();
- if shown && !self.home_shown { self.home_asked.clear(); self.home_external.clear() }
- self.home_shown = shown;
- if !shown { return }
- let now = fleet::now_ms();
- let machines: Vec<String> = self.fleet.machines.iter().filter(|m| m.usable() && !self.home_asked.contains(&m.id)).map(|m| m.id.clone()).collect();
- for machine in machines {
- let Some(link) = self.link(&machine) else { continue };
- self.home_asked.insert(machine.clone());
- let payload = json!({ "query": "", "from": now.saturating_sub(30 * 86_400_000), "to": now, "limit": 30 });
- self.spawn(async move { link.rpc("session_search", payload, Duration::from_secs(10)).await }, move |app, reply| {
- // (A daemon without session search has none to offer.)
- let Ok(reply) = reply else { return };
- for x in externals(&machine, &reply) {
- if !x.open && !app.home_external.iter().any(|y| y.machine == x.machine && y.session_id == x.session_id) { app.home_external.push(x) }
- }
- });
- }
- }
-
/// C-b s's query, a moment after its last key: every connected machine asked what was said
/// (its hits kept while the query is still the one they answer; the list filled again).
fn ask_said(&mut self) {
@@ -5779,7 +5747,7 @@ impl App {
pub fn on_tick(&mut self) {
self.run_start_then();
- self.ask_home_external();
+ crate::new_harness::welcome_tick(self);
self.ask_said();
self.ask_tails();
self.tick += 1;
diff --git a/tui/src/commands.rs b/tui/src/commands.rs
index fc2e0c998..57ae7374e 100644
--- a/tui/src/commands.rs
+++ b/tui/src/commands.rs
@@ -1869,7 +1869,7 @@ fn run_words_in(app: &mut App, words: &[String]) {
if app.capture.is_some() { app.tab_mut().size = app.cli_size; }
if bare {
app.tab_mut().home = true;
- app.home_from = from.clone();
+ crate::new_harness::ensure_welcome(app, from.clone(), cwd.clone());
let tab = app.tab().id.clone();
input::new_shell_from(app, from, Placement::Fill(tab), cwd, command);
return;
@@ -2213,13 +2213,17 @@ fn run_words_in(app: &mut App, words: &[String]) {
// tmux's paste-buffer [-dpr] [-s separator] [-b buffer-name] [-t target-pane]: the
// buffer (the newest automatic one without -b) into the pane — its newlines as -s, a
// newline with -r, else a carriage return; -p bracketed; -d the buffer then deleted.
- let Some((_, pane)) = target_pane(app, words) else { return };
let name = match opt(words, "-b") {
Some(b) => { if app.paste.get(&b).is_none() { return app.error(format!("no buffer {b}")) } Some(b) }
None => app.paste.top().map(|b| b.name.clone()),
};
let Some(name) = name else { return };
let text = app.paste.get(&name).map(|b| b.data.clone()).unwrap_or_default();
+ if app.capture.is_none() && opt(words, "-t").is_none() && input::paste_form(app, &text) {
+ if flag(words, "-d") { app.paste.free(&name) }
+ return;
+ }
+ let Some((_, pane)) = target_pane(app, words) else { return };
let sep = opt(words, "-s").unwrap_or_else(|| if flag(words, "-r") { "\n".into() } else { "\r".into() });
input::paste_into(app, pane, &text, &sep, flag(words, "-p"));
if flag(words, "-d") { app.paste.free(&name) }
diff --git a/tui/src/input.rs b/tui/src/input.rs
index b5cedb827..5ef9a9855 100644
--- a/tui/src/input.rs
+++ b/tui/src/input.rs
@@ -53,7 +53,7 @@ pub fn handle(app: &mut App, event: CEvent) {
/// Overlays that type text keep every key (tmux's prompt ignores the prefix too).
fn typing(app: &App) -> bool {
- matches!(app.modal, Some(Modal::Prompt(_)) | Some(Modal::Picker { .. }) | Some(Modal::Confirm { .. }) | Some(Modal::Popup { .. }) | Some(Modal::Menu { .. }) | Some(Modal::NewHarness(_)))
+ (app.home_visible() && !os_home(app)) || matches!(app.modal, Some(Modal::Prompt(_)) | Some(Modal::Picker { .. }) | Some(Modal::Confirm { .. }) | Some(Modal::Popup { .. }) | Some(Modal::Menu { .. }) | Some(Modal::NewHarness(_)))
}
fn on_key(app: &mut App, key: KeyEvent) {
@@ -143,7 +143,7 @@ fn on_key(app: &mut App, key: KeyEvent) {
// at the status line keeps it — and a plain-key prefix (`` ` ``, Enter) is the prefix over the
// panes alone: in a list it is typed into the search, or chooses.
let line_edit = matches!(app.modal, Some(Modal::Prompt(_)) | Some(Modal::Confirm { .. }) | Some(Modal::Popup { .. }) | Some(Modal::Menu { .. }) | Some(Modal::NewHarness(_)));
- let listed = chord.plain() && app.modal.is_some();
+ let listed = chord.plain() && (app.modal.is_some() || app.home_visible() && !os_home(app) && crate::new_harness::welcome_editing(app));
if !line_edit && !listed && (chord == app.keymap.prefix || Some(chord) == app.keymap.prefix2) {
app.status_redraws += 1;
app.prefix = true;
@@ -153,7 +153,7 @@ fn on_key(app: &mut App, key: KeyEvent) {
// key-table (a session's default table, root unless set — `off` for a nested tmux): its key
// runs; one it has not goes to the pane, root's bindings not this client's then.
let base = app.options.get("key-table", "", None).unwrap_or_else(|| "root".into());
- if base != "root" && app.modal.is_none() {
+ if base != "root" && app.modal.is_none() && !app.home_visible() {
if let Some(b) = app.keymap.named.get(&base).and_then(|l| l.iter().rev().find(|b| b.chord == chord)).cloned() {
app.status_redraws += 1;
commands::execute_bound(app, &b.command);
@@ -256,7 +256,7 @@ pub fn send_to_pane(app: &mut App, focus: u64, bytes: Vec<u8>) {
}
fn on_paste(app: &mut App, text: String) {
- if let Some(Modal::NewHarness(form)) = &mut app.modal { crate::new_harness::paste(form, &text); return }
+ if paste_form(app, &text) { return }
if let Some(Modal::Picker { picker, .. }) = &mut app.modal { for c in text.chars().filter(|c| !c.is_control()) { picker.type_char(c) } return }
if let Some(Modal::Prompt(prompt)) = &mut app.modal { prompt.value.push_str(&text.replace(['\r', '\n'], " ")); return }
app.tab_mut().home = false;
@@ -267,6 +267,17 @@ fn on_paste(app: &mut App, text: String) {
else { send_to_focused(app, text.into_bytes()) }
}
+/// A foreground creation editor owns paste, including the tmux paste-buffer binding.
+pub(crate) fn paste_form(app: &mut App, text: &str) -> bool {
+ if let Some(Modal::NewHarness(form)) = &mut app.modal {
+ crate::new_harness::paste(form, text);
+ true
+ } else if app.home_visible() {
+ if !os_home(app) { crate::new_harness::welcome_paste(app, text); }
+ true
+ } else { false }
+}
+
fn on_mouse(app: &mut App, mouse: MouseEvent) {
// tmux asks the terminal for bare motion only when a pane here wants it (or a menu opened by
// the mouse): the rest of the motion hn is sent never happened, as far as tmux is concerned.
@@ -276,6 +287,7 @@ fn on_mouse(app: &mut App, mouse: MouseEvent) {
// ── status bar ──
// (The bar down a side and the tabs over the panes: theirs, unless a menu is open.)
if !matches!(app.modal, Some(Modal::Menu(_))) && crate::bar::mouse(app, &mouse) { return }
+ if app.home_visible() { if !os_home(app) { crate::new_harness::welcome_mouse(app, mouse); } return }
crate::mouse::on_event(app, mouse);
}
@@ -468,7 +480,7 @@ pub enum HomeRow { Harness(String, String), External(crate::app::External) }
impl HomeRow {
/// Its key in the home page's order: (machine, agent), or (machine, "x:" session).
- fn key(&self) -> (String, String) {
+ pub(crate) fn key(&self) -> (String, String) {
match self { HomeRow::Harness(m, a) => (m.clone(), a.clone()), HomeRow::External(x) => (x.machine.clone(), format!("x:{}", x.session_id)) }
}
}
@@ -478,16 +490,17 @@ impl HomeRow {
/// the last 30 days that Harness did not start, on every connected machine.
pub fn home_rows(app: &App) -> Vec<HomeRow> {
let mut all: Vec<(u64, HomeRow)> = app.fleet.agents.values()
- .filter(|a| app.fleet.state_of(a) != crate::fleet::State::Offline)
+ .filter(|a| a.engine != "terminal" && app.fleet.state_of(a) != crate::fleet::State::Offline)
.map(|a| (a.recency(), HomeRow::Harness(a.key().0, a.key().1)))
.collect();
- all.extend(app.home_external.iter().map(|x| (x.last_at, HomeRow::External(x.clone()))));
+ all.extend(app.home_external.iter()
+ .filter(|x| app.fleet.machine(&x.machine).is_some_and(|m| m.usable()))
+ .map(|x| (x.last_at, HomeRow::External(x.clone()))));
// (Ties by name, so two alike keep their places between readings.)
let name = |r: &HomeRow| match r { HomeRow::Harness(m, a) => app.fleet.agent(m, a).map(|x| x.name.clone()).unwrap_or_default(), HomeRow::External(x) => x.title.clone() };
all.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| name(&a.1).cmp(&name(&b.1))));
let ranked: Vec<HomeRow> = all.into_iter().map(|(_, r)| r).collect();
- // Numbers are for fingers: a row keeps its number while you look at the list, however the
- // harnesses' activity reorders them (the order is fresh each time the window is entered).
+ // Keep rows stable while activity changes; refresh the order when entering a window.
let mut order = app.home_order.borrow_mut();
let mut out: Vec<HomeRow> = order.iter().filter_map(|k| ranked.iter().find(|r| &r.key() == k).cloned()).collect();
for r in &ranked { if out.len() >= 9 { break } if !out.iter().any(|o| o.key() == r.key()) { out.push(r.clone()) } }
@@ -496,15 +509,7 @@ pub fn home_rows(app: &App) -> Vec<HomeRow> {
out
}
-/// A conversation Harness did not start, opened as a harness that resumes it — in its own folder,
-/// named for its title — in the window here when it is empty (else a new one). Its machine says
-/// why when it will not (open elsewhere, already a harness, its folder gone).
-pub fn resume_external(app: &mut App, x: &crate::app::External) {
- let placement = if app.tab().home { Placement::Replace } else if app.tab().root.is_none() { Placement::Auto(None) } else { Placement::Tab };
- resume_external_as(app, x, placement)
-}
-
-/// resume_external, placed as asked (a new window, beside, below, here).
+/// Resume an external conversation, placed as asked (a new window, beside, below, here).
pub fn resume_external_as(app: &mut App, x: &crate::app::External, placement: Placement) {
let Some(link) = app.link(&x.machine) else { app.say("That machine is not connected", theme::DANGER); return };
let mut payload = json!({ "engine": x.engine, "cwd": x.cwd, "bypassPermission": true, "resumeSessionId": x.session_id, "creationId": uuid::Uuid::new_v4().to_string() });
@@ -543,7 +548,7 @@ fn os_home_command(app: &App, key: KeyEvent) -> Option<Option<&'static str>> {
}
}
-/// A window with no harness in it has no pane to take keys from, so plain letters work here.
+/// The shared welcome composer owns ordinary keys; the OS retains its setup actions.
fn home_key(app: &mut App, key: KeyEvent) {
if os_home(app) {
if let Some(command) = os_home_command(app, key) {
@@ -551,43 +556,10 @@ fn home_key(app: &mut App, key: KeyEvent) {
}
return;
}
- let rows = home_rows(app);
- let open = |app: &mut App, index: usize| {
- match rows.get(index).cloned() {
- Some(HomeRow::Harness(m, a)) => app.open_agent(&m, &a, Placement::Auto(None)),
- Some(HomeRow::External(x)) => resume_external(app, &x),
- None => {}
- }
- };
- let plain = !key.modifiers.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER);
- let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
- let rows_n = rows.len();
- match key.code {
- // A row by its number, or chosen with the arrows (C-p / C-n) and then Enter.
- KeyCode::Char(c @ '1'..='9') if plain && (c as usize - '1' as usize) < rows_n => open(app, c as usize - '1' as usize),
- KeyCode::Up => { app.home_cursor = if app.home_moved { app.home_cursor.saturating_sub(1) } else { 0 }; app.home_moved = true }
- KeyCode::Char('p') if ctrl => { app.home_cursor = if app.home_moved { app.home_cursor.saturating_sub(1) } else { 0 }; app.home_moved = true }
- KeyCode::Down => { app.home_cursor = if app.home_moved { (app.home_cursor + 1).min(rows_n.saturating_sub(1)) } else { 0 }; app.home_moved = true }
- KeyCode::Char('n') if ctrl => { app.home_cursor = if app.home_moved { (app.home_cursor + 1).min(rows_n.saturating_sub(1)) } else { 0 }; app.home_moved = true }
- KeyCode::Enter if app.home_moved && rows_n > 0 => open(app, app.home_cursor),
- KeyCode::Esc => app.home_moved = false,
- // Anything else is typed into a shell made here, as after tmux's C-b c: in the machine and
- // folder of the pane you came from, what you type (`claude⏎`, `git status⏎`) its.
- _ => {
- if app.tab().home && (app.focused().is_some() || app.shell_inputs.contains_key(&app.tab().id)) {
- app.tab_mut().home = false;
- app.home_from = None;
- on_key(app, key);
- return;
- }
- let Some(bytes) = crate::pane::encode_key(&key, alacritty_terminal::term::TermMode::empty()) else { return };
- let from = app.home_from.take();
- new_shell_from(app, from, Placement::Auto(None), None, None);
- if let Some(buffer) = app.shell_inputs.get(&app.tab().id) { buffer.lock().unwrap().push(bytes) }
- }
- }
+ crate::new_harness::welcome_key(app, key);
}
+
// ── commands ──────────────────────────────────────────────────────────────
pub fn picker(app: &mut App, kind: PickerKind, title: &str, placeholder: &str) {
@@ -1103,7 +1075,8 @@ fn harness_preview(picker: &mut Picker) {
/// Rebuild the open overlay's rows (the fleet or a catalog moved under it).
pub fn refill(app: &mut App) {
- if matches!(app.modal, Some(Modal::NewHarness(_))) { return crate::new_harness::refresh(app) }
+ crate::new_harness::refresh(app);
+ if matches!(app.modal, Some(Modal::NewHarness(_))) { return }
// A delayed search/catalog reply may arrive after the picker has closed. It must not
// consume a command prompt, confirmation or copy mode that replaced that picker.
if !matches!(app.modal, Some(Modal::Picker { .. })) { return }
@@ -1340,9 +1313,13 @@ fn create_in(app: &mut App, machine: String, what: What, cwd: Option<String>, me
pub(crate) fn create_opts(app: &mut App, machine: String, what: What, cwd: Option<String>, message: Option<String>, worktree: bool, opts: NewOpts) {
let machine = app.fleet.launch_machine_id(&machine).to_string();
- let Some(link) = app.link(&machine) else { return app.error("That machine is not connected") };
+ let Some(link) = app.link(&machine) else {
+ if let Some(id) = &opts.form_id { crate::new_harness::completed(app, id, Some("That machine is not connected. Your draft is kept here.".into())); }
+ return app.error("That machine is not connected")
+ };
let terminal = what.engine == "terminal";
let mut payload = json!({ "engine": what.engine, "creationId": uuid::Uuid::new_v4().to_string(), "bypassPermission": !terminal });
+ if terminal { configure_local_shell(app, &machine, &mut payload); }
if let Some(dsh) = &what.dsh { payload["dsh"] = json!(dsh) }
match &cwd {
Some(cwd) if worktree => { payload["projectSource"] = json!("worktree"); payload["gitSource"] = json!(cwd) }
@@ -1355,19 +1332,17 @@ pub(crate) fn create_opts(app: &mut App, machine: String, what: What, cwd: Optio
if let Some(name) = opts.name.as_ref().filter(|n| !n.is_empty()) { payload["name"] = json!(name) }
if let Some(extra) = opts.extra.as_ref().and_then(|v| v.as_object()) { for (key, value) in extra { payload[key] = value.clone(); } }
if let Some(form_id) = &opts.form_id {
- let Some(Modal::NewHarness(form)) = &mut app.modal else { return };
- if &form.id != form_id || form.attempt.is_some() { return }
- form.attempt = Some(crate::new_harness::Creation {
- id: payload["creationId"].as_str().unwrap().into(), machine: machine.clone(), session: app.session_id,
- });
- form.starting = true; form.error.clear();
+ if !crate::new_harness::record_attempt(app, form_id, crate::new_harness::Creation {
+ id: payload["creationId"].as_str().unwrap().into(), machine: machine.clone(),
+ session: opts.target.as_ref().map(|t| t.session).unwrap_or(app.session_id), target: opts.target.clone(),
+ }) { return }
}
// (From a shell: nothing said on the way — a message there is the command's error.)
if app.capture.is_none() { app.say(format!("Starting {} on {}…", what.label, app.fleet.machine_name(&machine)), theme::SOFT) }
if opts.form_id.is_none() { app.modal = None; }
// -P: the shell that asked waits for it, and is told where it is (as new-window -P).
if opts.print.is_some() { app.print_new = opts.print.clone() }
- let session = app.session_id;
+ let session = opts.target.as_ref().map(|t| t.session).unwrap_or(app.session_id);
let timeout = Duration::from_secs(if opts.form_id.is_some() { 20 } else { 180 });
app.spawn(async move { link.rpc("agent_create", payload, timeout).await }, move |app, reply| {
creation_finished(app, machine, session, opts, reply, false);
@@ -1375,7 +1350,7 @@ pub(crate) fn create_opts(app: &mut App, machine: String, what: What, cwd: Optio
}
pub(crate) fn check_creation(app: &mut App, form_id: String, attempt: crate::new_harness::Creation) {
- let opts = NewOpts { form_id: Some(form_id), ..Default::default() };
+ let opts = NewOpts { form_id: Some(form_id), target: attempt.target.clone(), ..Default::default() };
let Some(link) = app.link(&attempt.machine) else {
return creation_finished(app, attempt.machine, attempt.session, opts, Err(crate::daemon::RpcError::new("DISCONNECTED", "")), true);
};
@@ -1395,13 +1370,19 @@ fn creation_finished(app: &mut App, machine: String, session: u32, opts: NewOpts
if let Some(id) = reply.pointer("/agent/id").and_then(|v| v.as_str()) {
if let Some(form_id) = &opts.form_id { crate::new_harness::created(app, form_id, &reply["agent"]); }
app.fleet.agents.insert((machine.clone(), id.to_string()), crate::fleet::agent_from(&machine, &reply["agent"], None));
+ if reply["agent"]["engine"] == "terminal" { app.shells.insert((machine.clone(), id.to_string())); }
// Keep new harnesses in the current window, filling it or splitting beside
// the focused pane; -d keeps the previous pane focused.
let back = (app.session_id, app.tab().id.clone());
let swapped = session != app.session_id && app.swap_back.is_none() && app.sessions.iter().any(|s| s.id == session) && { app.swap_back = Some(back.0); app.swap_session(session) };
let before = (app.tab().id.clone(), app.focused(), app.tab().zoomed);
- app.open_agent(&machine, id, Placement::Auto(None));
- if opts.detached {
+ let lastw = app.lastw.clone();
+ let target = opts.target.as_ref().and_then(|t| app.tabs.iter().position(|w| w.id == t.tab));
+ if opts.target.is_none() || target.is_some() {
+ if let Some(i) = target { app.select_tab(i) }
+ app.open_agent(&machine, id, Placement::Auto(None));
+ }
+ if opts.detached || opts.target.as_ref().is_some_and(|t| t.tab != before.0) {
if let Some(i) = app.tabs.iter().position(|t| t.id == before.0) {
app.select_tab(i);
if let Some(pane) = before.1.filter(|p| app.tabs[i].panes().contains(p)) {
@@ -1410,13 +1391,16 @@ fn creation_finished(app: &mut App, machine: String, session: u32, opts: NewOpts
app.fit_panes();
}
}
+ if opts.target.is_some() { app.lastw = lastw; }
}
if let Some(fmt) = opts.print.as_ref().and(app.print_new.take()) {
let line = app.find_pane(&machine, id).map(|(w, p)| crate::format::spans_for_pane(app, &fmt, w, p, ratatui::style::Style::default()).into_iter().map(|s| s.content.into_owned()).collect::<String>()).unwrap_or_default();
if let Some(tx) = app.held_reply.take() { let _ = tx.send((vec![line], Vec::new(), 0)); }
}
if swapped { app.swap_back = None; app.swap_session(back.0); app.fit_panes(); app.save_sessions() }
- app.toast = None;
+ if opts.target.is_some() && target.is_none() {
+ app.say("Harness started. Open it from Sessions.", theme::SOFT);
+ } else { app.toast = None; }
} else {
if let Some(tx) = app.held_reply.take().filter(|_| opts.print.is_some()) { app.print_new = None; let _ = tx.send((Vec::new(), vec!["the machine created no harness".into()], 1)); return }
if let Some(form_id) = &opts.form_id { crate::new_harness::completed(app, form_id, Some("The machine created no harness — try again".into())); }
@@ -3006,6 +2990,7 @@ pub fn is_command(id: &str) -> bool {
/// choose-buffer's pick: that buffer pasted into this pane, as paste-buffer -b does.
pub fn paste_buffer(app: &mut App, name: &str) {
let Some(text) = app.paste.get(name).map(|b| b.data.clone()) else { return app.say(format!("no buffer {name}"), theme::WARN) };
+ if paste_form(app, &text) { return }
let Some(focus) = app.focused() else { return };
paste_into(app, focus, &text, "\r", false);
}
@@ -3035,7 +3020,8 @@ pub fn paste_into(app: &mut App, pane: u64, text: &str, sep: &str, bracket: bool
/// over the pane (what fzf in the pane would get: C-b is backward-char, C-a beginning-of-line), to
/// copy mode through its table (C-b is page-up in copy-mode-vi), else to the pane's program.
pub fn send_prefix_key(app: &mut App, key: KeyEvent) {
- if matches!(app.modal, Some(Modal::Picker { .. }) | Some(Modal::Copy { .. })) { return modal_key(app, key) }
+ if matches!(app.modal, Some(Modal::Picker { .. }) | Some(Modal::Copy { .. }) | Some(Modal::NewHarness(_))) { return modal_key(app, key) }
+ if app.home_visible() { return home_key(app, key) }
// The tree over the pane: it has the key (C-b is page-up there).
if let Some(pane) = app.focused().filter(|f| app.panes.get(f).map(|p| p.tree_top()).unwrap_or(false)) {
return crate::tree::key(app, pane, keys::of(&key), None, true);
@@ -3128,8 +3114,12 @@ pub struct NewOpts {
pub detached: bool, pub name: Option<String>, pub print: Option<String>,
/// Additional project/permission choices from the interactive draft.
pub extra: Option<serde_json::Value>, pub form_id: Option<String>,
+ pub target: Option<LaunchTarget>,
}
+#[derive(Clone, Debug)]
+pub(crate) struct LaunchTarget { pub session: u32, pub tab: String }
+
/// `new-harness [-dP] [-e engine] [-c folder] [-n name] [-F format] [engine] [@machine] [folder]
/// [task …]`: the engine a known one (else -e's, else Claude Code), the folder a path, and the
/// words after them the first message it is given.
@@ -3289,6 +3279,7 @@ mod tests {
}
app.os_session = true;
app.os_live = false;
+ assert!(!typing(&app), "the OS setup page retains root key bindings");
assert_eq!(os_home_command(&app, key(KeyCode::Enter)), Some(Some("/usr/bin/hn-os try")));
assert_eq!(os_home_command(&app, key(KeyCode::Char('T'))), Some(None));
for code in [KeyCode::Char('i'), KeyCode::Char('I')] {
@@ -3352,6 +3343,49 @@ mod tests {
assert_eq!(app.focused(), Some(created));
}
+ #[tokio::test]
+ async fn a_delayed_launch_fills_its_original_window_without_stealing_the_current_one() {
+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();
+ let mut app = App::new(19789, sink, (150, 42));
+ let first = app.tab().id.clone();
+ app.tab_mut().home = true;
+ app.open_agent("fixture", "unused-shell", Placement::Fill(first.clone()));
+ let session = app.session_id;
+ app.new_tab();
+ app.open_agent("fixture", "other-work", Placement::Auto(None));
+ let current = app.tab().id.clone();
+ let focus = app.focused();
+ let lastw = app.lastw.clone();
+ creation_finished(&mut app, "fixture".into(), session,
+ NewOpts { target: Some(LaunchTarget { session, tab: first.clone() }), ..Default::default() },
+ Ok(json!({"agent":{"id":"created", "name":"New harness", "engine":"codex"}})), false);
+ assert_eq!(app.tab().id, current);
+ assert_eq!(app.focused(), focus);
+ assert_eq!(app.lastw, lastw, "a background completion must preserve last-window navigation");
+ assert_eq!(app.tabs.len(), 2);
+ assert!(app.find_pane("fixture", "unused-shell").is_none());
+ let (window, _) = app.find_pane("fixture", "created").unwrap();
+ assert_eq!(app.tabs[window].id, first);
+ assert_eq!(app.tabs[window].panes().len(), 1);
+ assert!(!app.tabs[window].home);
+ }
+
+ #[tokio::test]
+ async fn a_closed_launch_window_does_not_replace_unrelated_work() {
+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();
+ let mut app = App::new(19789, sink, (150, 42));
+ app.open_agent("fixture", "other-work", Placement::Auto(None));
+ let before = (app.tab().id.clone(), app.focused());
+ let session = app.session_id;
+ creation_finished(&mut app, "fixture".into(), session,
+ NewOpts { target: Some(LaunchTarget { session, tab: "closed-window".into() }), ..Default::default() },
+ Ok(json!({"agent":{"id":"created", "name":"New harness", "engine":"codex"}})), false);
+ assert_eq!((app.tab().id.clone(), app.focused()), before);
+ assert_eq!(app.tabs.len(), 1);
+ assert!(app.find_pane("fixture", "created").is_none());
+ assert!(app.fleet.agent("fixture", "created").is_some(), "completed work remains available in Sessions");
+ }
+
#[tokio::test]
async fn delayed_picker_refresh_preserves_the_replacement_modal() {
let (sink, _) = tokio::sync::mpsc::unbounded_channel();
diff --git a/tui/src/main.rs b/tui/src/main.rs
index ba9566e4a..6c36bcdbd 100644
--- a/tui/src/main.rs
+++ b/tui/src/main.rs
@@ -515,7 +515,7 @@ async fn run(config: config::Config) -> io::Result<()> {
if let Some(event) = first { apply(&mut app, event, &mut refill, &mut startup_input); need_draw = true }
// Everything else already waiting goes into the same frame.
while let Ok(event) = rx.try_recv() { apply(&mut app, event, &mut refill, &mut startup_input); need_draw = true }
- if !input_ready && (app.focused().is_some() || app.shell_asked && app.starting_shell.is_none()) {
+ if !input_ready && (app.focused().is_some() || app.tab().home || app.shell_asked && app.starting_shell.is_none()) {
input_ready = true;
while let Some(event) = startup_input.pop_front() { input::handle(&mut app, event); refill = true; }
}
@@ -558,7 +558,9 @@ async fn run(config: config::Config) -> io::Result<()> {
let all = app.mouse && app.wants_motion();
if all != mouse_all { execute!(term.backend_mut(), term_out::Mouse(if all { 2 } else { 1 }))?; mouse_all = all }
app.flush_acks();
- if refill && matches!(app.modal, Some(modal::Modal::Picker { .. } | modal::Modal::NewHarness(_))) { input::refill(&mut app) }
+ // Welcome forms also need connection and catalog updates, including drafts in
+ // background windows. Refill leaves unrelated overlays alone.
+ if refill { input::refill(&mut app) }
// A scroll that has rested: every row of the screen written again, once — row by row over
// what is there, not after erasing it, so it never flashes.
let settle = app::scroll_settle_in(app.scrolled_at, Instant::now()) == Some(Duration::ZERO);
diff --git a/tui/src/new_harness.rs b/tui/src/new_harness.rs
index 44b7a6d3f..ebd2085c7 100644
--- a/tui/src/new_harness.rs
+++ b/tui/src/new_harness.rs
@@ -2,6 +2,10 @@
mod data;
mod receipt;
mod task;
+mod welcome;
+pub(crate) use welcome::{Welcome, draw as draw_welcome, ensure as ensure_welcome, tick as welcome_tick};
+pub(crate) use welcome::{key as welcome_key, mouse as welcome_mouse, paste as welcome_paste};
+pub(crate) use welcome::editing as welcome_editing;
pub(crate) use receipt::Creation;
mod view;
use crate::{
@@ -54,7 +58,13 @@ enum Field {
Branch,
Worktree,
Create,
+ Terminal,
+ Recent(usize),
+ Browse,
}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+enum Surface { Dialog, Dismissed, Window(String) }
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ProjectAction {
Open,
@@ -75,11 +85,10 @@ enum Choice {
Path,
Clone,
NewFolder,
- Task,
}
impl Choice {
fn editing(&self) -> bool {
- matches!(self, Self::Path | Self::Clone | Self::NewFolder | Self::Task)
+ matches!(self, Self::Path | Self::Clone | Self::NewFolder)
}
}
struct Child {
@@ -95,6 +104,15 @@ pub struct Form {
checking: bool,
pub error: String,
pub attempt: Option<Creation>,
+ surface: Surface,
+ recovery_page: Option<String>,
+ recent: Vec<crate::input::HomeRow>,
+ recent_labels: Vec<(String, String)>,
+ recent_status: String,
+ first_run: bool,
+ launch_target: Option<crate::input::LaunchTarget>,
+ remember_choices: bool,
+ local_only: bool,
prepared_folder: Option<String>,
focus: Field,
child: Option<Child>,
@@ -102,6 +120,8 @@ pub struct Form {
trail: Vec<Child>,
area: Rect,
child_area: Rect,
+ task_area: Rect,
+ task_editor: task::Editor,
hits: Vec<(Rect, Field)>,
machine_label: String,
home: String,
@@ -131,7 +151,7 @@ impl Form {
data::project_payload(&self.draft, &self.git)
}
fn fields(&self) -> Vec<Field> {
- let mut fields = vec![Field::Agent, Field::Project, Field::Task, Field::Branch, Field::Worktree];
+ let mut fields = vec![Field::Task, Field::Agent, Field::Project, Field::Branch, Field::Worktree];
if self.draft.what.engine != "terminal" {
fields.push(Field::Model);
}
@@ -142,6 +162,11 @@ impl Form {
fields.push(Field::Profile);
}
fields.push(Field::Create);
+ if matches!(self.surface, Surface::Window(_)) {
+ fields.push(Field::Terminal);
+ fields.extend((0..self.recent.len()).map(Field::Recent));
+ fields.push(Field::Browse);
+ }
fields
}
fn move_by(&mut self, delta: isize) {
@@ -155,11 +180,15 @@ impl Form {
&& self.draft.worktree.unwrap_or(true)
}
fn blocked(&self, field: Field) -> Option<&str> {
- if field == Field::Task && !task::supported(&self.draft.what.engine) && self.draft.task.trim().is_empty() {
+ if self.local_only && matches!(field, Field::Branch | Field::Worktree | Field::Create) && self.draft.what.engine != "terminal" {
+ Some("Start the Harness daemon first")
+ } else if field == Field::Task && !task::supported(&self.draft.what.engine) && self.draft.task.trim().is_empty() {
Some("Not available for this agent")
} else if matches!(field, Field::Branch | Field::Worktree) {
if self.git_loading {
Some("Checking Git…")
+ } else if self.git["error"] == "OFFLINE" {
+ Some("Waiting for machine…")
} else if self.git["error"].is_string() {
Some("Could not read Git · Enter to retry")
} else if !data::git(&self.git) || self.draft.what.engine == "terminal" {
@@ -188,23 +217,22 @@ impl Form {
fn project_label(&self) -> String {
format!("{} @ {}", self.project_name(), self.machine_label)
}
- fn save_task(&mut self) {
- if let Some(c) = &self.child {
- if c.kind == Choice::Task {
- self.draft.task.clone_from(&c.picker.query);
- }
- }
- }
fn hint(&self) -> String {
- if self.starting { return "Esc close · launch continues".into() }
- if self.attempt.is_some() { return "Enter check status · Esc close".into() }
+ let page = matches!(self.surface, Surface::Window(_));
+ if self.starting { return if page { "Launch continues if you change windows" } else { "Esc close · launch continues" }.into() }
+ if self.attempt.is_some() { return if page { "Enter check status" } else { "Enter check status · Esc close" }.into() }
+ if self.focus == Field::Task {
+ return "Enter start · Tab fields · Alt-Enter newline".into();
+ }
if self.focus == Field::Project {
if let Project::Folder(path) = &self.draft.project {
return format!("{} @ {}", short_path(path, &self.home), self.machine_label);
}
}
if self.focus == Field::Create {
- "↑/↓ fields · Enter start · Esc close".into()
+ if page { "Enter start · Tab fields" } else { "↑/↓ fields · Enter start · Esc close" }.into()
+ } else if page && matches!(self.focus, Field::Terminal | Field::Recent(_) | Field::Browse) {
+ "Enter open · Tab fields · Esc task".into()
} else {
"↑/↓ fields · Enter choose · Esc back".into()
}
@@ -288,6 +316,9 @@ impl Form {
},
String::new(),
),
+ Field::Terminal => ("Open Terminal", String::new()),
+ Field::Recent(i) => ("", self.recent_labels.get(i).map(|r| r.0.clone()).unwrap_or_default()),
+ Field::Browse => ("Browse All Sessions…", String::new()),
};
(
if field == Field::Create && !self.starting && self.attempt.is_none() {
@@ -371,6 +402,21 @@ pub fn open(app: &mut App, machine: Option<String>, cwd: Option<String>) {
{
return app.error("That machine is not connected");
}
+ // A closed window can still own a pending receipt. Reopen that receipt as a dialog so
+ // it can be checked, without replacing an unrelated dismissed dialog's draft.
+ if machine.is_none() && cwd.is_none() {
+ let orphan = app.welcome.forms.iter().find(|(tab, form)|
+ (form.starting || form.attempt.is_some())
+ && !app.tabs.iter().chain(app.sessions.iter().flat_map(|s| s.tabs.iter())).any(|t| &t.id == *tab)
+ ).map(|(tab, _)| tab.clone());
+ if let Some(tab) = orphan {
+ let mut form = app.welcome.forms.remove(&tab).unwrap();
+ form.recovery_page = Some(tab);
+ form.surface = Surface::Dialog;
+ store_form(app, form);
+ return;
+ }
+ }
if app
.new_harness_draft
.as_ref()
@@ -378,11 +424,21 @@ pub fn open(app: &mut App, machine: Option<String>, cwd: Option<String>) {
|| (machine.is_none() && cwd.is_none() && app.new_harness_draft.is_some())
{
let mut form = app.new_harness_draft.take().unwrap();
+ form.surface = Surface::Dialog;
resolve_launch_machine(app, &mut form);
refresh_form(app, &mut form);
app.modal = Some(Modal::NewHarness(form));
return;
}
+ let Some(form) = make_form(app, machine, cwd, Surface::Dialog) else {
+ return app.error("No machine is connected yet");
+ };
+ let machine = form.draft.machine.clone();
+ store_form(app, form);
+ crate::input::load_dsh(app, machine);
+}
+
+fn make_form(app: &mut App, machine: Option<String>, cwd: Option<String>, surface: Surface) -> Option<Box<Form>> {
let saved = defaults();
let machine = machine
.filter(|id| app.fleet.machines.iter().any(|m| m.id == *id && m.usable()))
@@ -400,10 +456,11 @@ pub fn open(app: &mut App, machine: Option<String>, cwd: Option<String>) {
.iter()
.find(|m| m.usable())
.map(|m| m.id.clone())
- });
- let Some(machine) = machine else {
- return app.error("No machine is connected yet");
- };
+ })
+ .or_else(|| matches!(surface, Surface::Window(_)).then(|| {
+ if app.fleet.local_id.is_empty() { crate::local::MACHINE.into() } else { app.fleet.local_id.clone() }
+ }));
+ let machine = machine?;
let current = app
.focused()
.and_then(|f| app.panes.get(&f))
@@ -451,13 +508,24 @@ pub fn open(app: &mut App, machine: Option<String>, cwd: Option<String>) {
checking: false,
error: String::new(),
attempt: None,
+ surface,
+ recovery_page: None,
+ recent: vec![],
+ recent_labels: vec![],
+ recent_status: String::new(),
+ first_run: false,
+ launch_target: None,
+ remember_choices: true,
+ local_only: false,
prepared_folder: None,
- focus: Field::Create,
+ focus: if task::supported(&engine) { Field::Task } else { Field::Create },
child: None,
child_active: false,
trail: vec![],
area: Rect::default(),
child_area: Rect::default(),
+ task_area: Rect::default(),
+ task_editor: task::Editor::default(),
hits: vec![],
machine_label: String::new(),
home: String::new(),
@@ -473,11 +541,11 @@ pub fn open(app: &mut App, machine: Option<String>, cwd: Option<String>) {
});
refresh_form(app, &mut form);
sync_git(app, &mut form, false);
- app.modal = Some(Modal::NewHarness(form));
- crate::input::load_dsh(app, machine);
+ Some(form)
}
fn refresh_form(app: &App, form: &mut Form) {
form.machine_label = machine_label(app, &form.draft.machine);
+ form.local_only = crate::local::is_local(&form.draft.machine) && app.daemon_down;
form.home = app
.homes
.get(&form.draft.machine)
@@ -537,16 +605,15 @@ fn refresh_form(app: &App, form: &mut Form) {
}
}
pub fn refresh(app: &mut App) {
- if !matches!(app.modal, Some(Modal::NewHarness(_))) {
- return;
+ let mut ids: Vec<_> = app.welcome.forms.values().map(|f| f.id.clone()).collect();
+ if let Some(Modal::NewHarness(f)) = &app.modal { ids.push(f.id.clone()) }
+ for id in ids {
+ with_form(app, &id, |app, form| {
+ resolve_launch_machine(app, form);
+ refresh_form(app, form);
+ sync_git(app, form, false);
+ });
}
- let Some(Modal::NewHarness(mut form)) = app.modal.take() else {
- return;
- };
- resolve_launch_machine(app, &mut form);
- refresh_form(app, &mut form);
- sync_git(app, &mut form, false);
- app.modal = Some(Modal::NewHarness(form));
}
fn resolve_launch_machine(app: &mut App, form: &mut Form) {
// A pending receipt belongs to its original transport, even if the daemon has returned.
@@ -649,7 +716,7 @@ fn sync_git(app: &mut App, form: &mut Form, force: bool) {
} else {
None
};
- if form.draft.what.engine == "terminal" || path.is_none() {
+ if form.draft.what.engine == "terminal" || form.local_only || path.is_none() {
form.git = Value::Null;
form.git_key = None;
form.git_loading = false;
@@ -686,6 +753,7 @@ fn sync_git(app: &mut App, form: &mut Form, force: bool) {
return;
}
form.git_loading = false;
+ if form.error == "Checking the project…" { form.error.clear(); }
form.git = reply.unwrap_or_else(|_| json!({"error":"UNAVAILABLE"}));
if let Some(main) = form.git["mainFolder"].as_str().map(str::to_string)
.filter(|_| !matches!(&form.draft.project, Project::Folder(p) if form.prepared_folder.as_ref() == Some(p)))
@@ -704,23 +772,57 @@ fn sync_git(app: &mut App, form: &mut Form, force: bool) {
},
);
}
-fn with_form(app: &mut App, id: &str, f: impl FnOnce(&mut App, &mut Form)) {
+fn store_form(app: &mut App, form: Box<Form>) {
+ match &form.surface {
+ Surface::Dialog => app.modal = Some(Modal::NewHarness(form)),
+ Surface::Dismissed => app.new_harness_draft = Some(form),
+ Surface::Window(tab) => { app.welcome.forms.insert(tab.clone(), form); }
+ }
+}
+fn dismiss(app: &mut App, mut form: Box<Form>) {
+ if let Some(tab) = form.recovery_page.take().filter(|_| form.starting || form.attempt.is_some()) {
+ form.surface = Surface::Window(tab);
+ } else if matches!(form.surface, Surface::Window(_)) {
+ form.focus = Field::Task;
+ } else { form.surface = Surface::Dismissed; }
+ store_form(app, form);
+}
+fn take_active(app: &mut App) -> Option<Box<Form>> {
+ if matches!(app.modal, Some(Modal::NewHarness(_))) {
+ let Some(Modal::NewHarness(form)) = app.modal.take() else { unreachable!() };
+ Some(form)
+ } else if app.home_visible() {
+ app.welcome.forms.remove(&app.tab().id.clone())
+ } else { None }
+}
+fn take_id(app: &mut App, id: &str) -> Option<Box<Form>> {
if matches!(&app.modal,Some(Modal::NewHarness(form)) if form.id==id) {
- let Some(Modal::NewHarness(mut form)) = app.modal.take() else {
- return;
- };
- f(app, &mut form);
- app.modal = Some(Modal::NewHarness(form));
- } else if app
- .new_harness_draft
- .as_ref()
- .is_some_and(|form| form.id == id)
- {
- let mut form = app.new_harness_draft.take().unwrap();
+ let Some(Modal::NewHarness(form)) = app.modal.take() else { unreachable!() };
+ Some(form)
+ } else if app.new_harness_draft.as_ref().is_some_and(|form| form.id == id) {
+ app.new_harness_draft.take()
+ } else {
+ let tab = app.welcome.forms.iter().find(|(_, f)| f.id == id).map(|(t, _)| t.clone())?;
+ app.welcome.forms.remove(&tab)
+ }
+}
+fn with_form(app: &mut App, id: &str, f: impl FnOnce(&mut App, &mut Form)) {
+ if let Some(mut form) = take_id(app, id) {
f(app, &mut form);
- app.new_harness_draft = Some(form);
+ store_form(app, form);
}
}
+pub(crate) fn record_attempt(app: &mut App, id: &str, attempt: Creation) -> bool {
+ let mut recorded = false;
+ with_form(app, id, |_, form| {
+ if form.attempt.is_some() { return }
+ form.attempt = Some(attempt);
+ form.starting = true;
+ form.error.clear();
+ recorded = true;
+ });
+ recorded
+}
fn load_resource(app: &mut App, form: &mut Form, models: bool) {
let Some(link) = app.link(&form.draft.machine) else {
return;
@@ -785,7 +887,6 @@ fn child(app: &mut App, form: &mut Form, kind: Choice, initial: &str) {
Choice::Path => "/path/to/project or ~/project",
Choice::Clone => "GitHub URL or owner/repository",
Choice::NewFolder => "Folder name (optional)",
- Choice::Task => "Describe the task…",
};
let mut picker = Picker::new("", hint);
picker.keep_order = kind != Choice::Project;
@@ -896,7 +997,6 @@ fn load_folder(app: &mut App, form: &mut Form, path: String) {
);
}
fn reveal(app: &mut App, form: &mut Form) {
- form.save_task();
form.child = None;
form.child_active = false;
form.trail.clear();
@@ -906,15 +1006,14 @@ fn reveal(app: &mut App, form: &mut Form) {
let kind = match form.focus {
Field::Agent => Choice::Agent,
Field::Project => Choice::Project,
- Field::Task => Choice::Task,
+ Field::Task => return,
Field::Model => Choice::Model,
Field::Approvals => Choice::Approvals,
Field::Profile => Choice::Profile,
Field::Branch => Choice::Branch,
_ => return,
};
- let initial = if kind == Choice::Task { form.draft.task.clone() } else { String::new() };
- child(app, form, kind, &initial);
+ child(app, form, kind, "");
}
fn activate(app: &mut App, form: &mut Form) -> bool {
form.error.clear();
@@ -926,6 +1025,7 @@ fn activate(app: &mut App, form: &mut Form) -> bool {
}
match form.focus {
Field::Create => return true,
+ Field::Task => { form.child_active = false; }
Field::Worktree => {
form.draft.worktree = Some(!form.worktree());
form.draft.branch = None;
@@ -1165,7 +1265,6 @@ fn choose(app: &mut App, form: &mut Form) {
set_project(form, Project::Clone(query));
}
Choice::NewFolder => set_project(form, Project::New(query)),
- Choice::Task => form.draft.task = c.picker.query.clone(),
}
form.child_active = false;
form.trail.clear();
@@ -1175,7 +1274,6 @@ fn choose(app: &mut App, form: &mut Form) {
sync_git(app, form, false);
}
fn back(app: &mut App, form: &mut Form) -> bool {
- form.save_task();
if form.child_active {
if let Some(previous) = form.trail.pop() {
form.child = Some(previous);
@@ -1207,6 +1305,13 @@ fn terminal_selected(form: &Form) -> bool {
}
fn open_terminal(app: &mut App, mut form: Box<Form>) {
+ if matches!(form.surface, Surface::Window(_)) {
+ form.child = None;
+ form.child_active = false;
+ form.trail.clear();
+ form.focus = Field::Terminal;
+ return welcome::activate(app, form);
+ }
let machine = form.draft.machine.clone();
let cwd = match &form.draft.project {
Project::Folder(path) if !path.is_empty() => Some(path.clone()),
@@ -1217,7 +1322,7 @@ fn open_terminal(app: &mut App, mut form: Box<Form>) {
form.child = None;
form.child_active = false;
form.trail.clear();
- app.new_harness_draft = Some(form);
+ dismiss(app, form);
crate::input::new_shell_from(app, Some((machine, String::new())), crate::app::Placement::Auto(None), cwd, None);
}
@@ -1225,19 +1330,19 @@ pub fn key(app: &mut App, mut form: Box<Form>, key: KeyEvent) {
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
if key.code == KeyCode::Esc || (ctrl && matches!(key.code, KeyCode::Char('c' | 'g'))) {
if back(app, &mut form) {
- app.modal = Some(Modal::NewHarness(form));
+ store_form(app, form);
} else {
- app.new_harness_draft = Some(form);
+ dismiss(app, form);
}
return;
}
if form.starting || key.kind == KeyEventKind::Repeat && key.code == KeyCode::Enter {
- app.modal = Some(Modal::NewHarness(form));
+ store_form(app, form);
return;
}
if form.attempt.is_some() {
let check = matches!(key.code, KeyCode::Enter | KeyCode::Char(' '));
- app.modal = Some(Modal::NewHarness(form));
+ store_form(app, form);
if check {
start(app);
}
@@ -1247,15 +1352,27 @@ pub fn key(app: &mut App, mut form: Box<Form>, key: KeyEvent) {
open_terminal(app, form);
return;
}
+ if !form.child_active && matches!(key.code, KeyCode::Enter | KeyCode::Char(' '))
+ && matches!(form.focus, Field::Terminal | Field::Recent(_) | Field::Browse) {
+ return welcome::activate(app, form);
+ }
let mut launch = false;
- let task_width = form.child_area.width.saturating_sub(6).max(1) as usize;
- if form.child_active {
+ if !form.child_active && form.focus == Field::Task {
+ match key.code {
+ KeyCode::Tab | KeyCode::BackTab => {
+ form.move_by(if key.code == KeyCode::BackTab { -1 } else { 1 });
+ reveal(app, &mut form);
+ }
+ KeyCode::Enter if !key.modifiers.intersects(KeyModifiers::ALT | KeyModifiers::SHIFT) => launch = true,
+ _ => {
+ form.task_editor.key(&mut form.draft.task, key, form.task_area.width.max(1) as usize);
+ form.error.clear();
+ }
+ }
+ } else if form.child_active {
if let Some(c) = &mut form.child {
let editing = c.kind.editing();
match key.code {
- KeyCode::Enter if c.kind == Choice::Task && key.modifiers.contains(KeyModifiers::ALT) => {
- c.picker.type_char('\n');
- }
KeyCode::Enter => choose(app, &mut form),
KeyCode::Tab | KeyCode::BackTab => form.child_active = false,
KeyCode::Char('l') if ctrl && matches!(c.kind, Choice::Folder(_)) => {
@@ -1267,8 +1384,6 @@ pub fn key(app: &mut App, mut form: Box<Form>, key: KeyEvent) {
let previous = form.child.take().unwrap();
step_into(app, &mut form, previous, Choice::Path, &path);
}
- KeyCode::Up if c.kind == Choice::Task => task::move_vertical(&mut c.picker, -1, task_width),
- KeyCode::Down if c.kind == Choice::Task => task::move_vertical(&mut c.picker, 1, task_width),
KeyCode::Up if !editing => c.picker.move_by(-1),
KeyCode::Down if !editing => c.picker.move_by(1),
KeyCode::PageUp if !editing => c.picker.move_by(-c.picker.page_rows.get().max(1)),
@@ -1319,12 +1434,8 @@ pub fn key(app: &mut App, mut form: Box<Form>, key: KeyEvent) {
reveal(app, &mut form);
}
KeyCode::Tab | KeyCode::BackTab => {
- if form.child.is_some() {
- form.child_active = true;
- } else {
- form.move_by(if key.code == KeyCode::BackTab { -1 } else { 1 });
- reveal(app, &mut form);
- }
+ form.move_by(if key.code == KeyCode::BackTab { -1 } else { 1 });
+ reveal(app, &mut form);
}
KeyCode::Enter | KeyCode::Char(' ') => launch = activate(app, &mut form),
KeyCode::Right if form.focus != Field::Create => {
@@ -1362,7 +1473,6 @@ pub fn key(app: &mut App, mut form: Box<Form>, key: KeyEvent) {
_ => {}
}
}
- form.save_task();
if form
.child
.as_ref()
@@ -1370,7 +1480,7 @@ pub fn key(app: &mut App, mut form: Box<Form>, key: KeyEvent) {
{
refresh_form(app, &mut form);
}
- app.modal = Some(Modal::NewHarness(form));
+ store_form(app, form);
if launch {
start(app);
}
@@ -1379,18 +1489,13 @@ pub fn paste(form: &mut Form, text: &str) {
if form.starting || form.attempt.is_some() {
return;
}
+ if !form.child_active && form.focus == Field::Task {
+ form.task_editor.insert(&mut form.draft.task, text);
+ form.error.clear();
+ return;
+ }
if let Some(c) = &mut form.child {
form.child_active = true;
- if c.kind == Choice::Task {
- let text: String = text.replace("\r\n", "\n").replace('\r', "\n").chars()
- .filter(|ch| *ch == '\n' || *ch == '\t' || !ch.is_control()).collect();
- let at = c.picker.query.char_indices().nth(c.picker.qcursor)
- .map(|(at, _)| at).unwrap_or(c.picker.query.len());
- c.picker.qcursor = c.picker.query[..at].chars().count() + text.chars().count();
- c.picker.query.insert_str(at, &text);
- form.save_task();
- return;
- }
let mut line_break = false;
for ch in text.chars() {
if matches!(ch, '\r' | '\n') {
@@ -1408,9 +1513,7 @@ pub fn paste(form: &mut Form, text: &str) {
}
}
pub fn mouse(app: &mut App, mouse: MouseEvent) {
- let Some(Modal::NewHarness(mut form)) = app.modal.take() else {
- return;
- };
+ let Some(mut form) = take_active(app) else { return };
let pos = Position::new(mouse.column, mouse.row);
let mut launch = false;
if !form.starting && form.attempt.is_some() {
@@ -1420,12 +1523,15 @@ pub fn mouse(app: &mut App, mouse: MouseEvent) {
.iter()
.any(|(r, field)| *field == Field::Create && r.contains(pos));
if !form.area.contains(pos) {
- app.new_harness_draft = Some(form);
+ dismiss(app, form);
return;
}
}
} else if !form.starting {
- if matches!(
+ if matches!(mouse.kind, MouseEventKind::ScrollUp | MouseEventKind::ScrollDown) && form.task_area.contains(pos) {
+ let delta = if mouse.kind == MouseEventKind::ScrollUp { -3 } else { 3 };
+ form.task_editor.scroll_by(&form.draft.task, form.task_area, delta);
+ } else if matches!(
mouse.kind,
MouseEventKind::ScrollUp | MouseEventKind::ScrollDown
) && form.child_area.contains(pos)
@@ -1437,19 +1543,13 @@ pub fn mouse(app: &mut App, mouse: MouseEvent) {
} else {
1
};
- if c.kind == Choice::Task {
- task::move_vertical(&mut c.picker, delta, form.child_area.width.saturating_sub(6).max(1) as usize);
- } else {
- c.picker.move_by(delta as i64);
- }
+ c.picker.move_by(delta as i64);
}
} else if mouse.kind == MouseEventKind::Down(MouseButton::Left) {
if form.child.is_some() && form.child_area.contains(pos) {
form.child_active = true;
let c = form.child.as_mut().unwrap();
- if c.kind == Choice::Task {
- task::click(&mut c.picker, form.child_area, pos);
- } else if let Some((_, index)) = c.picker.row_at.iter().find(|(y, _)| *y == mouse.row) {
+ if let Some((_, index)) = c.picker.row_at.iter().find(|(y, _)| *y == mouse.row) {
c.picker.cursor = *index;
if terminal_selected(&form) {
open_terminal(app, form);
@@ -1457,19 +1557,26 @@ pub fn mouse(app: &mut App, mouse: MouseEvent) {
}
choose(app, &mut form);
}
+ } else if form.task_area.contains(pos) {
+ form.focus = Field::Task;
+ reveal(app, &mut form);
+ form.task_editor.click(&form.draft.task, form.task_area, pos);
} else if let Some((_, field)) = form.hits.iter().find(|(r, _)| r.contains(pos)) {
form.focus = *field;
+ if matches!(field, Field::Terminal | Field::Recent(_) | Field::Browse) {
+ return welcome::activate(app, form);
+ }
reveal(app, &mut form);
launch = activate(app, &mut form);
} else if !form.area.contains(pos) {
if !back(app, &mut form) {
- app.new_harness_draft = Some(form);
+ dismiss(app, form);
return;
}
}
}
}
- app.modal = Some(Modal::NewHarness(form));
+ store_form(app, form);
if launch {
start(app);
}
@@ -1477,11 +1584,9 @@ pub fn mouse(app: &mut App, mouse: MouseEvent) {
/// Validate launch choices using the selected machine; no side effects occur while browsing.
pub fn start(app: &mut App) {
- let Some(Modal::NewHarness(mut form)) = app.modal.take() else {
- return;
- };
+ let Some(mut form) = take_active(app) else { return };
if form.starting {
- app.modal = Some(Modal::NewHarness(form));
+ store_form(app, form);
return;
}
if let Some(attempt) = form.attempt.clone() {
@@ -1489,13 +1594,16 @@ pub fn start(app: &mut App) {
form.checking = true;
form.error.clear();
let id = form.id.clone();
- app.modal = Some(Modal::NewHarness(form));
+ store_form(app, form);
crate::input::check_creation(app, id, attempt);
return;
}
resolve_launch_machine(app, &mut form);
- form.save_task();
- let fail = if let Some(error) = task::error(&form.draft.what.engine, &form.draft.task) {
+ form.remember_choices = true;
+ form.launch_target = Some(crate::input::LaunchTarget { session: app.session_id, tab: app.tab().id.clone() });
+ let fail = if form.local_only && form.draft.what.engine != "terminal" {
+ Some("Run `harness start` to connect agents, then retry. Your task stays here.".into())
+ } else if let Some(error) = task::error(&form.draft.what.engine, &form.draft.task) {
Some(error)
} else if form.git_loading {
Some("Checking the project…".into())
@@ -1506,12 +1614,12 @@ pub fn start(app: &mut App) {
};
if let Some(error) = fail {
form.error = error;
- app.modal = Some(Modal::NewHarness(form));
+ store_form(app, form);
return;
}
let Some(link) = app.link(&form.draft.machine) else {
form.error = "That machine is not connected".into();
- app.modal = Some(Modal::NewHarness(form));
+ store_form(app, form);
return;
};
let id = form.id.clone();
@@ -1521,19 +1629,18 @@ pub fn start(app: &mut App) {
&& form.draft.profile.is_some();
let package = form.draft.what.dsh.is_some();
if !model && !profile && !package {
- launch(app, form, true);
+ launch(app, form);
return;
}
form.starting = true;
form.error.clear();
- app.modal = Some(Modal::NewHarness(form));
+ store_form(app, form);
app.spawn(async move{
let models=async{if model{link.rpc("grid_models_list",json!({"rowState":true}),Duration::from_secs(30)).await.ok()}else{None}};
let profiles=async{if profile{link.rpc("codex_profiles_list",json!({}),Duration::from_secs(20)).await.ok()}else{None}};
let packages=async{if package{link.rpc("dsh_list",json!({}),Duration::from_secs(20)).await.ok()}else{None}};
tokio::join!(models,profiles,packages)
},move|app,(models,profiles,packages)|{
- let visible=matches!(&app.modal,Some(Modal::NewHarness(f))if f.id==id);
let mut result=None;with_form(app,&id,|_,form|{form.starting=false;
if let Some((grid,id,_))=&form.draft.model{let expected=json!([grid,id]).to_string();if !data::model_rows(&models.unwrap_or(Value::Null),&form.draft.what.engine).iter().any(|r|r.id==expected&&!r.disabled){form.error="Model unavailable here. Choose a model or your subscription.".into();return}}
if profile{let (machine,path,_)=form.draft.profile.as_ref().unwrap();if machine!=&form.draft.machine{form.error="Choose a profile on this machine.".into();return}if !profiles.unwrap_or(Value::Null)["profiles"].as_array().into_iter().flatten().any(|p|p["path"].as_str()==Some(path)){form.error="Profile unavailable here. Choose another profile.".into();return}}
@@ -1544,22 +1651,22 @@ pub fn start(app: &mut App) {
if !compatible{form.error="Choose a compatible coding agent for this harness.".into();return}
}result=Some(());
});
- if result.is_some(){let form=if visible{let Some(Modal::NewHarness(f))=app.modal.take()else{return};f}else{let Some(f)=app.new_harness_draft.take()else{return};f};launch(app,form,visible);}
+ if result.is_some() { if let Some(form) = take_id(app, &id) { launch(app, form); } }
});
}
-fn launch(app: &mut App, mut form: Box<Form>, visible: bool) {
+fn launch(app: &mut App, mut form: Box<Form>) {
let d = form.draft.clone();
let (cwd, mut extra) = match form.project_payload() {
Ok(v) => v,
Err(e) => {
form.error = e;
- app.modal = Some(Modal::NewHarness(form));
+ store_form(app, form);
return;
}
};
if d.what.engine == "terminal" && cwd.is_none() {
form.error = "Choose an existing folder for a terminal".into();
- app.modal = Some(Modal::NewHarness(form));
+ store_form(app, form);
return;
}
extra["permissionMode"] = Value::Null;
@@ -1578,8 +1685,8 @@ fn launch(app: &mut App, mut form: Box<Form>, visible: bool) {
}
}
let id = form.id.clone();
- let previous = app.modal.take();
- app.modal = Some(Modal::NewHarness(form));
+ let target = form.launch_target.clone();
+ store_form(app, form);
crate::input::create_opts(
app,
d.machine,
@@ -1590,15 +1697,11 @@ fn launch(app: &mut App, mut form: Box<Form>, visible: bool) {
crate::input::NewOpts {
extra: Some(extra),
form_id: Some(id),
+ target,
..Default::default()
},
);
- if !visible {
- if let Some(Modal::NewHarness(form)) = app.modal.take() {
- app.new_harness_draft = Some(form);
- }
- app.modal = previous;
- }
+
}
/// Apply the daemon's receipt before deciding whether another launch is allowed.
/// A status check is read-only, even after a reconnect or a daemon upgrade.
@@ -1656,7 +1759,7 @@ pub fn completed(app: &mut App, id: &str, error: Option<String>) {
if let Some(error) = error {
form.error = error;
} else {
- remember(form);
+ if form.remember_choices { remember(form); }
success = true;
}
});
@@ -1667,6 +1770,7 @@ pub fn completed(app: &mut App, id: &str, error: Option<String>) {
if app.new_harness_draft.as_ref().is_some_and(|f| f.id == id) {
app.new_harness_draft = None;
}
+ app.welcome.forms.retain(|_, f| f.id != id);
}
}
@@ -1855,7 +1959,7 @@ mod tests {
open(&mut app, Some(shell.into()), Some("/home/dev/repo".into()));
let Some(Modal::NewHarness(form)) = &mut app.modal else { panic!() };
if pending {
- form.attempt = Some(Creation { id: "original".into(), machine: shell.into(), session: app.session_id });
+ form.attempt = Some(Creation { id: "original".into(), machine: shell.into(), session: app.session_id, target: None });
}
app.fleet.machine_mut("local").unwrap().reach = crate::fleet::Reach::Ready;
app.fleet.machine_mut("local").unwrap().name = "office".into();
@@ -1925,9 +2029,7 @@ mod tests {
key(&mut app, form, KeyEvent::new(KeyCode::Enter, KeyModifiers::ALT));
let Some(Modal::NewHarness(form)) = app.modal.take() else { panic!() };
assert_eq!(form.draft.task, format!("{expected}\n"));
- // Escape leaves the editor with its text, then dismisses the draft.
- key(&mut app, form, KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
- let Some(Modal::NewHarness(form)) = app.modal.take() else { panic!() };
+ // Escape dismisses the form, preserving the inline task.
key(&mut app, form, KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
open(&mut app, None, None);
let Some(Modal::NewHarness(mut form)) = app.modal.take() else { panic!() };
@@ -1937,9 +2039,8 @@ mod tests {
assert!(form.blocked(Field::Task).is_none(), "a retained task can still be cleared");
set_engine(&mut form, "claude");
reveal(&mut app, &mut form);
- assert_eq!(form.child.as_ref().unwrap().picker.query, format!("{expected}\n"));
- choose(&mut app, &mut form);
- assert_eq!(form.focus, Field::Create);
+ assert!(form.child.is_none());
+ assert_eq!(form.focus, Field::Task);
assert_eq!(form.draft.task, format!("{expected}\n"));
}
@@ -1958,10 +2059,10 @@ mod tests {
let mut anchor = None;
for engine in ["claude", "codex", "terminal"] {
set_engine(&mut form, engine);
- for chooser in [None, Some(Choice::Agent), Some(Choice::Clone), Some(Choice::Task), None] {
+ for chooser in [None, Some(Choice::Agent), Some(Choice::Clone), Some(Choice::Path), None] {
if let Some(kind) = chooser {
- let text = if kind == Choice::Task { "A long task with 界 and 🦀.\n".repeat(50) } else { String::new() };
- child(&mut app, &mut form, kind, &text);
+ let text = "/home/dev/项目";
+ child(&mut app, &mut form, kind, text);
} else {
form.child = None;
}
@@ -1969,7 +2070,7 @@ mod tests {
form.child_active = active;
let mut buf = Buffer::empty(area);
if let Some(cursor) = draw(&mut buf, area, &mut form) {
- assert!(active, "a preview must not take keyboard focus");
+ assert!(active || form.focus == Field::Task, "only the task or an active chooser takes the cursor");
assert!(area.contains(cursor), "{area:?} {cursor:?}");
}
for (hit, _) in &form.hits {
@@ -1978,7 +2079,7 @@ mod tests {
if form.area.width > 0 {
// The form's panel: its own height, one size and place whatever is open.
assert_eq!(form.area, crate::settings::area(area, crate::settings::PanelSize::Form, view::HEIGHT));
- assert!(form.area.width <= 60 && form.area.height <= 17);
+ assert!(form.area.width <= 60 && form.area.height <= view::HEIGHT);
let left = form.area.x - area.x;
let right = area.right() - form.area.right();
assert!(left.abs_diff(right) <= 1, "not centered in {area:?}");
@@ -2039,7 +2140,7 @@ mod tests {
#[tokio::test]
async fn terminal_resize_before_its_input_event_keeps_the_form_and_choosers_in_frame() {
- for choice in [None, Some(Choice::Agent), Some(Choice::Task)] {
+ for choice in [None, Some(Choice::Agent), Some(Choice::Path)] {
let mut app = app();
open(&mut app, None, None);
if let Some(kind) = choice {
@@ -2067,6 +2168,7 @@ mod tests {
let mut app = app();
open(&mut app, None, None);
let Some(Modal::NewHarness(mut form)) = app.modal.take() else { panic!() };
+ form.focus = Field::Create;
form.error = "Could not start it: “My-First-Claude-Project” already exists. Select that folder from your projects.".into();
for width in [45, 80, 130] {
let area = Rect::new(0, 0, width, 38);
@@ -2112,6 +2214,7 @@ mod tests {
assert!(!f.fields().contains(&Field::Model));
assert!(!f.fields().contains(&Field::Profile));
child(&mut app, &mut f, Choice::Clone, "");
+ f.child_active = true;
paste(&mut f, "owner/\r\nrepository");
assert_eq!(f.child.as_ref().unwrap().picker.query, "owner/ repository");
}
@@ -2150,6 +2253,7 @@ mod tests {
id: "intent".into(),
machine: "local".into(),
session: 0,
+ target: None,
});
app.modal = Some(Modal::NewHarness(f));
assert!(!creation_reply(
@@ -2207,6 +2311,7 @@ mod tests {
id: "intent".into(),
machine: "local".into(),
session: 0,
+ target: None,
});
app.modal = Some(Modal::NewHarness(f));
assert!(!creation_reply(
diff --git a/tui/src/new_harness/receipt.rs b/tui/src/new_harness/receipt.rs
index 52507237c..ac061cf97 100644
--- a/tui/src/new_harness/receipt.rs
+++ b/tui/src/new_harness/receipt.rs
@@ -8,6 +8,7 @@ pub(crate) struct Creation {
pub id: String,
pub machine: String,
pub session: u32,
+ pub target: Option<crate::input::LaunchTarget>,
}
#[derive(Debug, PartialEq)]
diff --git a/tui/src/new_harness/task.rs b/tui/src/new_harness/task.rs
index b48781f18..2604b2954 100644
--- a/tui/src/new_harness/task.rs
+++ b/tui/src/new_harness/task.rs
@@ -1,8 +1,12 @@
-//! The optional first task, edited beside the form (in its place on narrow terminals).
+//! The first task: inline editing and the launch contract shared with desktop.
use super::*;
+mod editor;
+pub(super) use editor::Editor;
// Keep these aligned with cli/src/lib/engineLaunch.ts and desktop/lib/core/first_task.dart.
-const MAX_LENGTH: usize = 2000;
+pub(super) const MAX_LENGTH: usize = 2000;
+
+pub(super) fn length(text: &str) -> usize { text.trim().encode_utf16().count() }
pub(super) fn supported(engine: &str) -> bool {
matches!(engine, "claude" | "codex" | "opencode" | "hermes")
@@ -23,218 +27,17 @@ pub(super) fn error(engine: &str, text: &str) -> Option<String> {
}
}
-struct Line {
- start: usize,
- text: String,
-}
-
-fn char_width(ch: char) -> usize {
- if ch == '\t' {
- 4
- } else {
- ch.width().unwrap_or(0)
- }
-}
-
-fn lines(text: &str, width: usize) -> Vec<Line> {
- let width = width.max(1);
- let mut lines = vec![Line {
- start: 0,
- text: String::new(),
- }];
- let mut col = 0;
- for (at, ch) in text.chars().enumerate() {
- if ch == '\n' {
- lines.push(Line {
- start: at + 1,
- text: String::new(),
- });
- col = 0;
- continue;
- }
- let w = char_width(ch);
- if col > 0 && col + w > width {
- lines.push(Line {
- start: at,
- text: String::new(),
- });
- col = 0;
- }
- lines.last_mut().unwrap().text.push(ch);
- col += w;
- }
- // Leave a cell for the insertion cursor after a completely full final line.
- if col >= width {
- lines.push(Line {
- start: text.chars().count(),
- text: String::new(),
- });
- }
- lines
-}
-
-fn position(lines: &[Line], cursor: usize) -> (usize, usize) {
- let row = lines
- .iter()
- .rposition(|line| line.start <= cursor)
- .unwrap_or(0);
- let col = lines[row]
- .text
- .chars()
- .take(cursor.saturating_sub(lines[row].start))
- .map(char_width)
- .sum();
- (row, col)
-}
-
-fn at_column(line: &Line, col: usize) -> usize {
- let mut width = 0;
- let mut at = line.start;
- for ch in line.text.chars() {
- let w = char_width(ch);
- if width + w > col {
- break;
- }
- width += w;
- at += 1;
- }
- at
-}
-
-pub(super) fn move_vertical(picker: &mut Picker, delta: isize, width: usize) {
- let lines = lines(&picker.query, width);
- let (row, col) = position(&lines, picker.qcursor);
- let to = (row as isize + delta).clamp(0, lines.len() as isize - 1) as usize;
- if row != to {
- picker.qcursor = at_column(&lines[to], col)
- }
-}
-
-fn text_area(r: Rect) -> Rect {
- let top = if r.height >= 8 { 4 } else { 1 };
- let footer = if r.width < 43 && r.height >= 9 { 3 } else { 2 };
- Rect::new(
- r.x + 3,
- r.y + top,
- r.width.saturating_sub(6).max(1),
- r.height.saturating_sub(top + footer).max(1),
- )
-}
-
-pub(super) fn click(picker: &mut Picker, panel: Rect, pos: Position) {
- let r = text_area(panel);
- if !r.contains(pos) {
- return;
- }
- let lines = lines(&picker.query, r.width as usize);
- let row = (picker.scroll + (pos.y - r.y) as usize).min(lines.len() - 1);
- picker.qcursor = at_column(&lines[row], (pos.x - r.x) as usize);
-}
-
-pub(super) fn draw(
- buf: &mut Buffer,
- panel: Rect,
- picker: &mut Picker,
- error: &str,
- active: bool,
- base: Style,
- muted: Style,
- accent: Style,
-) -> Position {
- let r = text_area(panel);
- if panel.height >= 8 {
- view::put(buf, r.x, panel.y + 2, r.width, "Task (optional)", muted);
- let count = format!(
- "{}/{}",
- picker.query.trim().encode_utf16().count(),
- MAX_LENGTH
- );
- let width = count.width() as u16;
- if r.width >= width + 18 {
- view::put(buf, r.right() - width, panel.y + 2, width, &count, muted);
- }
- }
- let lines = lines(&picker.query, r.width as usize);
- let (row, col) = position(&lines, picker.qcursor);
- picker.scroll = picker
- .scroll
- .min(row)
- .max(row.saturating_sub(r.height as usize - 1));
- if picker.query.is_empty() {
- view::put(buf, r.x, r.y, r.width, &picker.placeholder, muted);
- } else {
- for (dy, line) in lines
- .iter()
- .skip(picker.scroll)
- .take(r.height as usize)
- .enumerate()
- {
- view::put(
- buf,
- r.x,
- r.y + dy as u16,
- r.width,
- &line.text.replace('\t', " "),
- base,
- );
- }
- }
- let y = r.y + (row - picker.scroll) as u16;
- if active {
- view::put(buf, panel.x + 1, y, 1, "›", accent);
- }
- let short_footer = panel.width < 43 && panel.height >= 9;
- if error.is_empty() && short_footer && active {
- view::put(buf, panel.x + 2, panel.bottom() - 3, panel.width - 4, "Alt-Enter newline", muted);
- }
- view::put(
- buf,
- panel.x + 2,
- panel.bottom() - if panel.height >= 5 { 2 } else { 1 },
- panel.width.saturating_sub(4),
- if error.is_empty() {
- if !active {
- "Enter or → to edit"
- } else if short_footer {
- "Enter done · Esc back"
- } else {
- "Enter done · Alt-Enter newline · Esc back"
- }
- } else {
- error
- },
- if error.is_empty() {
- muted
- } else {
- base.patch(theme::fg(theme::DANGER))
- },
- );
- Position::new(r.x + (col as u16).min(r.width - 1), y)
-}
-
#[cfg(test)]
mod tests {
use super::*;
-
#[test]
- fn first_task_validation_preserves_text_and_matches_wire_length() {
- assert!(error("terminal", " ").is_none());
- assert!(error("cursor", "Fix login").is_some());
- assert!(error("codex", &"🦀".repeat(1000)).is_none());
- assert!(error("claude", &"🦀".repeat(1001)).is_some());
- assert!(error("claude", &format!("\n{}\n", "x".repeat(MAX_LENGTH))).is_none());
- }
-
- #[test]
- fn wrapped_task_navigation_tracks_unicode_and_hard_breaks() {
- let mut p = Picker::new("", "");
- p.query = "ab界cd\nnext".into();
- p.qcursor = 3;
- move_vertical(&mut p, 1, 5);
- assert_eq!(p.qcursor, 5);
- move_vertical(&mut p, 1, 5);
- assert_eq!(p.qcursor, 7);
- let lines = lines("界界", 4);
- assert_eq!(position(&lines, 2), (1, 0));
+ fn first_task_matches_the_launch_contract() {
+ assert!(error("terminal", " ").is_none());
+ assert!(error("terminal", "do work").is_some());
+ for engine in ["claude", "codex", "opencode", "hermes"] {
+ assert!(error(engine, &"🦀".repeat(1000)).is_none());
+ assert!(error(engine, &"🦀".repeat(1001)).is_some());
+ assert!(error(engine, &format!(" {} ", "a".repeat(2000))).is_none());
+ }
}
}
diff --git a/tui/src/new_harness/task/editor.rs b/tui/src/new_harness/task/editor.rs
new file mode 100644
index 000000000..77f120386
--- /dev/null
+++ b/tui/src/new_harness/task/editor.rs
@@ -0,0 +1,256 @@
+//! The first task's inline editor. Offsets are UTF-8 grapheme boundaries; wrapping uses cells.
+use super::*;
+use unicode_segmentation::UnicodeSegmentation;
+
+#[derive(Default)]
+pub(crate) struct Editor {
+ pub cursor: usize,
+ scroll: usize,
+ column: Option<usize>,
+ killed: String,
+ free_scroll: bool,
+}
+
+struct Line { start: usize, end: usize, text: String }
+fn width(glyph: &str) -> usize { if glyph == "\t" { 4 } else { glyph.width() } }
+
+fn lines(text: &str, limit: usize) -> Vec<Line> {
+ let limit = limit.max(1);
+ let mut out = vec![Line { start: 0, end: 0, text: String::new() }];
+ let mut col = 0;
+ for (at, glyph) in text.grapheme_indices(true) {
+ if glyph == "\n" {
+ out.last_mut().unwrap().end = at;
+ out.push(Line { start: at + 1, end: at + 1, text: String::new() });
+ col = 0;
+ continue;
+ }
+ let w = width(glyph);
+ if col > 0 && col + w > limit {
+ out.push(Line { start: at, end: at, text: String::new() });
+ col = 0;
+ }
+ let line = out.last_mut().unwrap();
+ line.text.push_str(glyph);
+ line.end = at + glyph.len();
+ col += w;
+ }
+ if col >= limit { out.push(Line { start: text.len(), end: text.len(), text: String::new() }); }
+ out
+}
+fn position(lines: &[Line], cursor: usize) -> (usize, usize) {
+ let row = lines.iter().rposition(|line| line.start <= cursor).unwrap_or(0);
+ let col = lines[row].text.grapheme_indices(true)
+ .take_while(|(at, _)| lines[row].start + at < cursor).map(|(_, g)| width(g)).sum();
+ (row, col)
+}
+fn at_column(line: &Line, col: usize) -> usize {
+ let mut used = 0;
+ for (at, glyph) in line.text.grapheme_indices(true) {
+ let w = width(glyph);
+ if used + w > col { return line.start + at }
+ used += w;
+ }
+ line.end
+}
+
+impl Editor {
+ fn clamp(&mut self, text: &str) {
+ self.cursor = text.grapheme_indices(true).map(|(at, _)| at)
+ .chain(std::iter::once(text.len())).take_while(|at| *at <= self.cursor).last().unwrap_or(0);
+ }
+ fn previous(&self, text: &str) -> usize {
+ text[..self.cursor].grapheme_indices(true).next_back().map(|(at, _)| at).unwrap_or(0)
+ }
+ fn next(&self, text: &str) -> usize {
+ self.cursor + text[self.cursor..].graphemes(true).next().map(str::len).unwrap_or(0)
+ }
+ fn line_start(&self, text: &str) -> usize { text[..self.cursor].rfind('\n').map(|at| at + 1).unwrap_or(0) }
+ fn line_end(&self, text: &str) -> usize { text[self.cursor..].find('\n').map(|at| self.cursor + at).unwrap_or(text.len()) }
+ fn word_left(&self, text: &str) -> usize {
+ let mut at = self.cursor;
+ let mut word = false;
+ for (i, glyph) in text[..self.cursor].grapheme_indices(true).rev() {
+ let space = glyph.chars().all(char::is_whitespace);
+ if word && space { break }
+ word |= !space;
+ at = i;
+ }
+ at
+ }
+ fn word_right(&self, text: &str) -> usize {
+ let mut at = text.len();
+ let mut word = false;
+ for (i, glyph) in text[self.cursor..].grapheme_indices(true) {
+ let space = glyph.chars().all(char::is_whitespace);
+ if word && space { at = self.cursor + i; break }
+ word |= !space;
+ }
+ at
+ }
+ pub fn insert(&mut self, text: &mut String, value: &str) {
+ self.free_scroll = false;
+ self.clamp(text);
+ let clean: String = value.replace("\r\n", "\n").replace('\r', "\n").chars()
+ .filter(|ch| matches!(ch, '\n' | '\t') || !ch.is_control()).collect();
+ text.insert_str(self.cursor, &clean);
+ self.cursor += clean.len();
+ // Inserting before a combining mark can join the next grapheme.
+ self.cursor = text.grapheme_indices(true).map(|(at, _)| at)
+ .chain(std::iter::once(text.len())).find(|at| *at >= self.cursor).unwrap_or(text.len());
+ self.column = None;
+ }
+ fn remove(&mut self, text: &mut String, start: usize, end: usize, kill: bool) {
+ if start < end {
+ if kill { self.killed = text[start..end].to_string(); }
+ text.replace_range(start..end, "");
+ self.cursor = start;
+ }
+ self.column = None;
+ }
+ fn vertical(&mut self, text: &str, delta: isize, limit: usize) {
+ let rows = lines(text, limit);
+ let (row, col) = position(&rows, self.cursor);
+ let col = *self.column.get_or_insert(col);
+ let to = (row as isize + delta).clamp(0, rows.len() as isize - 1) as usize;
+ self.cursor = at_column(&rows[to], col);
+ }
+ pub fn key(&mut self, text: &mut String, key: KeyEvent, limit: usize) -> bool {
+ self.free_scroll = false;
+ self.clamp(text);
+ let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
+ let alt = key.modifiers.contains(KeyModifiers::ALT);
+ let vertical = matches!(key.code, KeyCode::Up | KeyCode::Down) || ctrl && matches!(key.code, KeyCode::Char('p' | 'n'));
+ if !vertical { self.column = None; }
+ match key.code {
+ KeyCode::Enter if alt || key.modifiers.contains(KeyModifiers::SHIFT) => self.insert(text, "\n"),
+ KeyCode::Left => self.cursor = if ctrl || alt { self.word_left(text) } else { self.previous(text) },
+ KeyCode::Right => self.cursor = if ctrl || alt { self.word_right(text) } else { self.next(text) },
+ KeyCode::Char('b') if ctrl || alt => self.cursor = if alt { self.word_left(text) } else { self.previous(text) },
+ KeyCode::Char('f') if ctrl || alt => self.cursor = if alt { self.word_right(text) } else { self.next(text) },
+ KeyCode::Up => self.vertical(text, -1, limit),
+ KeyCode::Down => self.vertical(text, 1, limit),
+ KeyCode::Char('p') if ctrl => self.vertical(text, -1, limit),
+ KeyCode::Char('n') if ctrl => self.vertical(text, 1, limit),
+ KeyCode::Home if ctrl => self.cursor = 0,
+ KeyCode::End if ctrl => self.cursor = text.len(),
+ KeyCode::Home => self.cursor = self.line_start(text),
+ KeyCode::End => self.cursor = self.line_end(text),
+ KeyCode::Char('a') if ctrl => self.cursor = self.line_start(text),
+ KeyCode::Char('e') if ctrl => self.cursor = self.line_end(text),
+ KeyCode::Backspace => self.remove(text, if ctrl || alt { self.word_left(text) } else { self.previous(text) }, self.cursor, ctrl || alt),
+ KeyCode::Delete => self.remove(text, self.cursor, if ctrl || alt { self.word_right(text) } else { self.next(text) }, ctrl || alt),
+ KeyCode::Char('d') if ctrl => self.remove(text, self.cursor, self.next(text), false),
+ KeyCode::Char('w') if ctrl => self.remove(text, self.word_left(text), self.cursor, true),
+ KeyCode::Char('u') if ctrl => self.remove(text, self.line_start(text), self.cursor, true),
+ KeyCode::Char('k') if ctrl => {
+ let end = self.line_end(text);
+ self.remove(text, self.cursor, if end == self.cursor { self.next(text) } else { end }, true);
+ }
+ KeyCode::Char('y') if ctrl => self.insert(text, &self.killed.clone()),
+ KeyCode::Char(ch) if !key.modifiers.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER) => self.insert(text, &ch.to_string()),
+ _ => return false,
+ }
+ true
+ }
+ pub fn click(&mut self, text: &str, area: Rect, pos: Position) {
+ if !area.contains(pos) { return }
+ let rows = lines(text, area.width as usize);
+ let row = (self.scroll + (pos.y - area.y) as usize).min(rows.len() - 1);
+ self.cursor = at_column(&rows[row], (pos.x - area.x) as usize);
+ self.column = None;
+ self.free_scroll = false;
+ }
+ pub fn scroll_by(&mut self, text: &str, area: Rect, delta: isize) {
+ if area.is_empty() { return }
+ let max = lines(text, area.width as usize).len().saturating_sub(area.height as usize);
+ self.scroll = (self.scroll as isize + delta).clamp(0, max as isize) as usize;
+ self.free_scroll = true;
+ }
+ pub fn draw(&mut self, buf: &mut Buffer, area: Rect, text: &str, active: bool, base: Style, muted: Style) -> Option<Position> {
+ if area.is_empty() { return None }
+ self.clamp(text);
+ let rows = lines(text, area.width as usize);
+ let (row, col) = position(&rows, self.cursor);
+ if self.free_scroll { self.scroll = self.scroll.min(rows.len().saturating_sub(area.height as usize)); }
+ else { self.scroll = self.scroll.min(row).max(row.saturating_sub(area.height as usize - 1)); }
+ if text.is_empty() {
+ view::put(buf, area.x, area.y, area.width, "What should this agent work on?", muted);
+ } else {
+ for (dy, line) in rows.iter().skip(self.scroll).take(area.height as usize).enumerate() {
+ view::put(buf, area.x, area.y + dy as u16, area.width, &line.text.replace('\t', " "), base);
+ }
+ }
+ (active && row >= self.scroll && row < self.scroll + area.height as usize)
+ .then(|| Position::new(area.x + (col as u16).min(area.width - 1), area.y + (row - self.scroll) as u16))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ fn key(editor: &mut Editor, text: &mut String, code: KeyCode, modifiers: KeyModifiers) {
+ assert!(editor.key(text, KeyEvent::new(code, modifiers), 8));
+ }
+ #[test]
+ fn editing_never_splits_a_grapheme_and_paste_preserves_newlines() {
+ let mut editor = Editor::default();
+ let mut text = String::new();
+ editor.insert(&mut text, "cafe\u{301}👨‍👩‍👧‍👦\r\n界\r\n");
+ assert_eq!(text, "cafe\u{301}👨‍👩‍👧‍👦\n界\n");
+ key(&mut editor, &mut text, KeyCode::Home, KeyModifiers::CONTROL);
+ for _ in 0..4 { key(&mut editor, &mut text, KeyCode::Right, KeyModifiers::NONE); }
+ key(&mut editor, &mut text, KeyCode::Delete, KeyModifiers::NONE);
+ assert_eq!(text, "cafe\u{301}\n界\n");
+ key(&mut editor, &mut text, KeyCode::Backspace, KeyModifiers::NONE);
+ assert_eq!(text, "caf\n界\n");
+ }
+ #[test]
+ fn line_editing_and_yank_preserve_the_other_task_lines() {
+ let mut editor = Editor::default();
+ let mut text = String::new();
+ editor.insert(&mut text, "one\nsecond task\nthree");
+ key(&mut editor, &mut text, KeyCode::Char('a'), KeyModifiers::CONTROL);
+ key(&mut editor, &mut text, KeyCode::Backspace, KeyModifiers::NONE);
+ assert_eq!(text, "one\nsecond taskthree");
+ key(&mut editor, &mut text, KeyCode::Char('u'), KeyModifiers::CONTROL);
+ assert_eq!(text, "one\nthree");
+ key(&mut editor, &mut text, KeyCode::Char('y'), KeyModifiers::CONTROL);
+ assert_eq!(text, "one\nsecond taskthree");
+ }
+ #[test]
+ fn wrapping_and_mouse_use_cells_not_bytes_or_codepoints() {
+ let rows = lines("e\u{301}界👨‍👩‍👧‍👦x", 5);
+ assert_eq!(rows.len(), 2);
+ assert_eq!(rows[0].text, "e\u{301}界👨‍👩‍👧‍👦");
+ assert_eq!(at_column(&rows[0], 2), "e\u{301}".len());
+ let rows = lines("界界", 4);
+ assert_eq!(position(&rows, "界界".len()), (1, 0));
+ let mut editor = Editor::default();
+ editor.click("ab界cd", Rect::new(10, 4, 6, 2), Position::new(13, 4));
+ assert_eq!(editor.cursor, 2);
+ }
+
+ #[test]
+ fn scrolling_a_long_task_does_not_move_the_edit_point() {
+ let mut editor = Editor::default();
+ let mut text = String::new();
+ editor.insert(&mut text, "one\ntwo\nthree\nfour\nfive");
+ let area = Rect::new(3, 4, 12, 2);
+ let mut buf = Buffer::empty(Rect::new(0, 0, 20, 10));
+ let style = Style::default();
+ assert_eq!(editor.draw(&mut buf, area, &text, true, style, style), Some(Position::new(7, 5)));
+ let end = editor.cursor;
+ editor.scroll_by(&text, area, -20);
+ assert_eq!(editor.draw(&mut buf, area, &text, true, style, style), None);
+ assert_eq!(editor.cursor, end);
+ assert_eq!(buf[(3, 4)].symbol(), "o");
+ editor.insert(&mut text, "!");
+ assert!(text.ends_with("five!"));
+ assert_eq!(editor.draw(&mut buf, area, &text, true, style, style), Some(Position::new(8, 5)));
+ editor.scroll_by(&text, area, -20);
+ editor.click(&text, area, Position::new(4, 4));
+ editor.insert(&mut text, "X");
+ assert!(text.starts_with("oXne\n"));
+ }
+}
diff --git a/tui/src/new_harness/view.rs b/tui/src/new_harness/view.rs
index 8b2bf370b..84291c548 100644
--- a/tui/src/new_harness/view.rs
+++ b/tui/src/new_harness/view.rs
@@ -32,12 +32,12 @@ pub(super) fn put(buf: &mut Buffer, x: u16, y: u16, width: u16, text: &str, styl
let mut used = 0;
let limit = width as usize;
let trunc = text.width() > limit;
- for ch in text.chars().filter(|c| !c.is_control()) {
- let w = ch.width().unwrap_or(0);
+ for ch in text.graphemes(true).filter(|g| !g.chars().any(char::is_control)) {
+ let w = ch.width();
if used + w > limit.saturating_sub(usize::from(trunc)) {
break;
}
- out.push(ch);
+ out.push_str(ch);
used += w;
}
if trunc {
@@ -48,7 +48,7 @@ pub(super) fn put(buf: &mut Buffer, x: u16, y: u16, width: u16, text: &str, styl
/// The form's height: enough rows for every agent's settings, the same whatever is open, so
/// changing agents or opening an editor never moves it.
-pub(super) const HEIGHT: u16 = 17;
+pub(super) const HEIGHT: u16 = 19;
/// The form's surface, as the settings panel draws its own: filled, no border.
fn panel(buf: &mut Buffer, r: Rect, base: Style) {
@@ -59,6 +59,7 @@ pub fn draw(buf: &mut Buffer, body: Rect, form: &mut Form) -> Option<Position> {
form.hits.clear();
form.area = Rect::default();
form.child_area = Rect::default();
+ form.task_area = Rect::default();
if body.width < 22 || body.height < 5 {
put(
buf,
@@ -70,96 +71,78 @@ pub fn draw(buf: &mut Buffer, body: Rect, form: &mut Form) -> Option<Position> {
);
return None;
}
- // The settings panel's colours, and its quiet backdrop over the working panes.
- let crate::settings::Chrome {
- base,
- muted,
- accent,
- backdrop,
- ..
- } = crate::settings::chrome();
- crate::settings::backdrop(buf, body, backdrop);
- // The form is a Form panel (settings::area): centred — the form, not the form and its chooser —
- // and as tall as every agent's settings need, so changing agents or opening an editor never
- // moves it. A chooser opens beside it where there is room, else in its place.
- let r = crate::settings::area(body, crate::settings::PanelSize::Form, HEIGHT);
+ let page = matches!(form.surface, Surface::Window(_));
+ let crate::settings::Chrome { base, muted, accent, backdrop, .. } = crate::settings::chrome();
+ if page {
+ panel(buf, body, Style::default().bg(ratatui::style::Color::Reset).fg(ratatui::style::Color::Reset));
+ } else { crate::settings::backdrop(buf, body, backdrop); }
+ // Only the terminal's size changes this anchor. Task wrapping, history, and choosers do not.
+ let r = crate::settings::area(body, crate::settings::PanelSize::Form, if page { 28 } else { HEIGHT });
let (x, y, form_w, form_h) = (r.x, r.y, r.width, r.height);
let side_w = body.right().saturating_sub(r.right() + 4).min(60);
let side = side_w >= 32;
let child_w = if side { side_w } else { form_w };
- let child_h = if side {
- body.bottom().saturating_sub(y + 1).min(22).max(form_h)
- } else {
- form_h
- };
- let fields = form.fields();
- let fields_y = y + if form_h >= 9 { 3 } else { 1 };
- let errors = error_lines(&form.error, form_w.saturating_sub(4) as usize);
- // Even a long error in a tiny terminal leaves one field (the focused action) visible.
- let error_h = errors.len().min(r.bottom().saturating_sub(fields_y + 2).max(1) as usize) as u16;
+ let child_h = if side { body.bottom().saturating_sub(y + 1).min(22).max(form_h.min(22)) } else { form_h };
+ let spacious = if page { form_h >= 27 } else { form_h >= HEIGHT };
+ let task_h = if spacious { 3 } else if page && form_h >= 21 { 2 } else { 1 };
+ let mut task_cursor = None;
+ let fields_y = y + if spacious { if page { 4 } else { 3 } } else if form_h >= 9 { 2 } else { 1 };
+ let live_error = task::error(&form.draft.what.engine, &form.draft.task);
+ let message = if form.error.is_empty() { live_error.as_deref().unwrap_or("") } else { &form.error };
+ let errors = error_lines(message, form_w.saturating_sub(4) as usize);
+ let footer_h = if message.is_empty() { 2 } else { errors.len().max(2) as u16 }
+ .min(r.bottom().saturating_sub(fields_y + 1 + u16::from(spacious)).max(1));
+ let footer_y = r.bottom().saturating_sub(footer_h + u16::from(spacious));
form.area = r;
if form.child.is_none() || side || !form.child_active {
panel(buf, r, base);
if form_h >= 9 {
- put(buf, x + 3, y + 1, form_w - 6, "New Harness", base.add_modifier(Modifier::BOLD));
+ let title = if page { if form.first_run { "Welcome to Harness" } else { "New Window" } } else { "New Harness" };
+ put(buf, x + 3, y + u16::from(spacious), form_w - 6, title, base.add_modifier(Modifier::BOLD));
+ if page && spacious {
+ put(buf, x + 3, y + 2, form_w - 6, "Start a task. Your agent takes it from here.", muted);
+ }
}
- let error_y = r.bottom() - 1 - error_h;
- let capacity = error_y.saturating_sub(fields_y);
+ let capacity = footer_y.saturating_sub(fields_y);
let mut row: u16 = 0;
- let rows: Vec<_> = fields
- .iter()
- .map(|field| {
- // One blank line between the task and settings, and before the launch action.
- if matches!(field, Field::Branch | Field::Create) {
- row += 1;
- }
- let at = row;
+ let mut recent_header = None;
+ let rows: Vec<_> = form.fields().into_iter().map(|field| {
+ if spacious && matches!(field, Field::Branch | Field::Create) { row += 1; }
+ if page && (field == Field::Recent(0) || field == Field::Browse && form.recent.is_empty()) {
+ if spacious { row += 1; }
+ recent_header = Some(row);
row += 1;
- (at, field)
- })
- .collect();
- let focus = rows
- .iter()
- .find(|(_, field)| **field == form.focus)
- .map(|(row, _)| *row)
- .unwrap_or(0);
+ }
+ let at = row;
+ row += if field == Field::Task { task_h } else { 1 };
+ (at, field)
+ }).collect();
+ let focus = rows.iter().find(|(_, field)| *field == form.focus).map(|(row, _)| *row).unwrap_or(0);
let skip = focus.saturating_sub(capacity.saturating_sub(1));
- for (row, field) in rows
- .into_iter()
- .filter(|(row, _)| *row >= skip && *row < skip + capacity)
- {
+ if let Some(row) = recent_header.filter(|row| *row >= skip && *row < skip + capacity) {
+ put(buf, x + 3, fields_y + row - skip, form_w - 6, &form.recent_status, muted);
+ }
+ for (row, field) in rows.into_iter().filter(|(row, _)| *row >= skip && *row < skip + capacity) {
let fy = fields_y + row - skip;
- let active = *field == form.focus;
- let st = if form.blocked(*field).is_some() {
- muted
- } else if active {
- accent
- } else {
- base
- };
- let (label, value) = form.describe(*field);
- put(buf, r.x + 1, fy, 1, if active { "›" } else { " " }, accent);
- let label_w = if r.width < 45 { 10 } else { 12 };
- put(
- buf,
- r.x + 3,
- fy,
- if *field == Field::Create {
- r.width.saturating_sub(6)
- } else {
- label_w
- },
- &label,
- if *field == Field::Create {
- st.add_modifier(Modifier::BOLD)
- } else {
- muted
- },
- );
- let value_width = r.width.saturating_sub(6 + label_w);
- let value_x = r.x + 3 + label_w;
- if *field == Field::Project {
- // Keep the destination visible even when the project name must be shortened.
+ let active = field == form.focus;
+ let st = if form.blocked(field).is_some() { muted } else if active { accent } else { base };
+ let (label, value) = form.describe(field);
+ put(buf, x + 1, fy, 1, if active { "›" } else { " " }, accent);
+ let label_w = if form_w < 45 { 10 } else { 12 };
+ let action = matches!(field, Field::Create | Field::Terminal | Field::Browse);
+ let recent = matches!(field, Field::Recent(_));
+ let height = if field == Field::Task { task_h.min(footer_y.saturating_sub(fy)) } else { 1 };
+ if !recent {
+ put(buf, x + 3, fy, if action { form_w - 6 } else { label_w }, &label,
+ if field == Field::Create { st.add_modifier(Modifier::BOLD) } else if action { st } else { muted });
+ }
+ let value_width = form_w.saturating_sub(6 + label_w);
+ let value_x = x + 3 + label_w;
+ if field == Field::Task && (task::supported(&form.draft.what.engine) || !form.draft.task.is_empty()) {
+ form.task_area = Rect::new(value_x, fy, value_width, height);
+ task_cursor = form.task_editor.draw(buf, form.task_area, &form.draft.task,
+ active && !form.child_active && !form.starting && form.attempt.is_none(), base, muted);
+ } else if field == Field::Project {
let suffix = format!(" @ {}", form.machine_label);
let suffix_width = suffix.width() as u16;
if value_width > suffix_width + 2 {
@@ -167,70 +150,50 @@ pub fn draw(buf: &mut Buffer, body: Rect, form: &mut Form) -> Option<Position> {
let name_width = (name.width() as u16).min(value_width - suffix_width);
put(buf, value_x, fy, name_width, &name, st);
put(buf, value_x + name_width, fy, suffix_width, &suffix, st);
- } else {
- put(
- buf,
- value_x,
- fy,
- value_width,
- &format!("@ {}", form.machine_label),
- st,
- );
+ } else { put(buf, value_x, fy, value_width, &format!("@ {}", form.machine_label), st); }
+ } else if let Field::Recent(i) = field {
+ let st = if active {
+ if theme::fzf().bw { st.add_modifier(Modifier::REVERSED) }
+ else { st.bg(theme::fzf().bg_plus) }
+ } else { st };
+ if active { panel(buf, Rect::new(x + 3, fy, form_w - 6, 1), st); }
+ if let Some((title, detail)) = form.recent_labels.get(i) {
+ let room = form_w - 6;
+ let detail_w = if room >= 42 { (detail.width() as u16).min(22) } else { 0 };
+ put(buf, x + 3, fy, room.saturating_sub(detail_w + u16::from(detail_w > 0)), title, st);
+ if detail_w > 0 { put(buf, r.right() - 3 - detail_w, fy, detail_w, detail, if active { accent } else { muted }); }
}
+ } else if !action { put(buf, value_x, fy, value_width, &value, st); }
+ form.hits.push((Rect::new(x + 1, fy, form_w - 2, height), field));
+ }
+ if message.is_empty() {
+ if form.local_only && form.draft.what.engine != "terminal" {
+ put(buf, x + 2, footer_y, form_w - 4, "Run `harness start` to connect agents.", muted);
+ if footer_h > 1 { put(buf, x + 2, footer_y + 1, form_w - 4, "You can prepare a task or open a terminal now.", muted); }
} else {
- put(
- buf,
- value_x,
- fy,
- value_width,
- &value,
- if *field == Field::Task && form.draft.task.is_empty() && !active {
- muted
- } else {
- st
- },
- );
+ put(buf, x + 2, footer_y, form_w - 4, &form.hint(), muted);
+ }
+ if footer_h > 1 && form.focus == Field::Task && !form.local_only {
+ let count = task::length(&form.draft.task);
+ let hint = if count >= 1600 { format!("{count}/{} characters", task::MAX_LENGTH) }
+ else { "Task is optional · leave blank to start interactively".into() };
+ put(buf, x + 2, footer_y + 1, form_w - 4, &hint, muted);
}
- form.hits
- .push((Rect::new(r.x + 1, fy, r.width - 2, 1), *field));
- }
- if form.error.is_empty() {
- put(buf, r.x + 2, error_y, r.width - 4, &form.hint(), muted);
} else {
- for (row, line) in errors.iter().take(error_h as usize).enumerate() {
- put(
- buf,
- r.x + 2,
- error_y + row as u16,
- r.width - 4,
- line,
- base.patch(theme::fg(theme::DANGER)),
- );
+ for (row, line) in errors.iter().take(footer_h as usize).enumerate() {
+ put(buf, x + 2, footer_y + row as u16, form_w - 4, line, base.patch(theme::fg(theme::DANGER)));
}
}
}
if !side && !form.child_active {
- return None;
+ return task_cursor;
}
let Some(c) = &mut form.child else {
- return None;
+ return task_cursor;
};
let r = Rect::new(if side { x + form_w + 2 } else { x }, y, child_w, child_h);
form.child_area = r;
panel(buf, r, base);
- if c.kind == Choice::Task {
- let cursor = task::draw(
- buf,
- r,
- &mut c.picker,
- &form.error,
- form.child_active,
- base,
- muted,
- accent,
- );
- return form.child_active.then_some(cursor);
- }
let query_x = r.x + 4;
let query_y = r.y + 2;
let query_w = r.width.saturating_sub(6) as usize;
diff --git a/tui/src/new_harness/welcome.rs b/tui/src/new_harness/welcome.rs
new file mode 100644
index 000000000..3a82aa10a
--- /dev/null
+++ b/tui/src/new_harness/welcome.rs
@@ -0,0 +1,441 @@
+//! The same creation form in an empty window, with a small, secondary session history.
+use super::*;
+use crate::{app::Placement, input::{HomeRow, LaunchTarget, NewOpts}};
+use std::time::Instant;
+
+#[derive(Default)]
+pub(crate) struct Welcome {
+ pub(super) forms: HashMap<String, Box<Form>>,
+ searches: HashMap<String, Search>,
+ shown: bool,
+ generation: u64,
+}
+struct Search {
+ pending: bool,
+ discovering: bool,
+ failed: bool,
+ asked_at: Instant,
+ next: Instant,
+}
+
+/// Context is captured before creating the window; switching windows never replaces its draft.
+pub(crate) fn ensure(app: &mut App, from: Option<(String, String)>, cwd: Option<String>) {
+ if crate::input::os_home(app) { return }
+ let tab = app.tab().id.clone();
+ if app.welcome.forms.contains_key(&tab) { return }
+ let machine = from.as_ref().map(|(m, _)| app.fleet.launch_machine_id(m).to_string());
+ let cwd = cwd.or_else(|| from.as_ref().and_then(|(m, a)| {
+ app.find_pane(m, a).and_then(|(_, p)| app.panes.get(&p))
+ .and_then(|p| p.cwd.clone().or_else(|| p.live_path.clone()))
+ .or_else(|| app.fleet.agent(m, a).map(|a| a.cwd.clone()).filter(|c| !c.is_empty()))
+ })).or_else(|| machine.is_none().then(|| std::env::current_dir().ok().map(|p| p.display().to_string())).flatten());
+ let first = app.welcome.forms.is_empty() && defaults().is_null()
+ && !crate::app::state_dir().join("welcome-seen").exists();
+ if let Some(mut form) = make_form(app, machine, cwd, Surface::Window(tab)) {
+ form.first_run = first;
+ let machine = form.draft.machine.clone();
+ store_form(app, form);
+ crate::input::load_dsh(app, machine);
+ }
+}
+
+fn seen() {
+ if cfg!(test) { return }
+ let path = crate::app::state_dir().join("welcome-seen");
+ if let Some(parent) = path.parent() {
+ let _ = std::fs::create_dir_all(parent);
+ let _ = std::fs::write(path, b"1\n");
+ }
+}
+
+fn prepare(app: &App, form: &mut Form) {
+ let available = crate::input::home_rows(app);
+ let selected = if let Field::Recent(i) = form.focus { form.recent.get(i).map(HomeRow::key) } else { None };
+ // Existing rows stay still while discovery adds results. A disappearing selection never
+ // silently becomes a different conversation under Enter.
+ form.recent.retain(|r| available.iter().any(|a| a.key() == r.key()));
+ for row in available {
+ if form.recent.len() >= 3 { break }
+ if !form.recent.iter().any(|r| r.key() == row.key()) { form.recent.push(row) }
+ }
+ if let Some(key) = selected {
+ form.focus = form.recent.iter().position(|r| r.key() == key).map(Field::Recent).unwrap_or(Field::Browse);
+ }
+ form.recent_labels = form.recent.iter().map(|r| match r {
+ HomeRow::Harness(machine, id) => {
+ let a = app.fleet.agent(machine, id).unwrap();
+ (a.name.clone(), format!("{} · {}", app.fleet.machine_name(machine), if a.project.is_empty() { theme::engine_label(&a.engine) } else { &a.project }))
+ }
+ HomeRow::External(x) => (
+ if x.title.is_empty() { "Untitled session".into() } else { x.title.clone() },
+ format!("{} · {}", app.fleet.machine_name(&x.machine), theme::engine_label(&x.engine)),
+ ),
+ }).collect();
+ let searches: Vec<_> = app.welcome.searches.iter()
+ .filter(|(m, _)| app.fleet.machine(m).is_some_and(|m| m.usable())).map(|(_, s)| s).collect();
+ let loading = searches.iter().any(|s| s.pending || s.discovering);
+ let failed = searches.iter().any(|s| s.failed);
+ form.recent_status = if loading {
+ format!("{} Finding saved sessions…", theme::spinner(app.tick))
+ } else if failed {
+ "Some history is unavailable · Ctrl-R retry".into()
+ } else if form.recent.is_empty() {
+ if searches.is_empty() { "History appears when a machine connects".into() }
+ else { "No recent sessions · start with a task above".into() }
+ } else { "Recent sessions".into() };
+}
+
+pub(crate) fn draw(buf: &mut Buffer, app: &mut App, area: Rect) -> Option<Position> {
+ ensure(app, None, None);
+ let tab = app.tab().id.clone();
+ let mut form = app.welcome.forms.remove(&tab)?;
+ prepare(app, &mut form);
+ let cursor = view::draw(buf, area, &mut form);
+ store_form(app, form);
+ if app.modal.is_none() && !app.prefix { cursor } else { None }
+}
+
+/// A plain prefix belongs to text while typing, and resumes navigation on a setting.
+pub(crate) fn editing(app: &App) -> bool {
+ app.welcome.forms.get(&app.tab().id).is_none_or(|form| form.focus == Field::Task || form.child_active)
+}
+
+pub(crate) fn key(app: &mut App, key: KeyEvent) {
+ ensure(app, None, None);
+ if key.code == KeyCode::Char('r') && key.modifiers.contains(KeyModifiers::CONTROL) {
+ app.welcome.generation += 1;
+ app.welcome.searches.clear();
+ tick(app);
+ return;
+ }
+ if let Some(mut form) = take_active(app) {
+ prepare(app, &mut form);
+ super::key(app, form, key);
+ }
+}
+pub(crate) fn paste(app: &mut App, text: &str) {
+ ensure(app, None, None);
+ if let Some(mut form) = take_active(app) {
+ super::paste(&mut form, text);
+ store_form(app, form);
+ }
+}
+pub(crate) fn mouse(app: &mut App, mouse: MouseEvent) { super::mouse(app, mouse); }
+
+pub(super) fn activate(app: &mut App, mut form: Box<Form>) {
+ let target = Some(LaunchTarget { session: app.session_id, tab: app.tab().id.clone() });
+ match form.focus {
+ Field::Browse => {
+ store_form(app, form);
+ crate::commands::execute(app, "choose-tree -Zs");
+ }
+ Field::Terminal => {
+ // This action opens the selected folder without sending the task to a shell.
+ let Project::Folder(cwd) = &form.draft.project else {
+ form.error = "Choose an existing project folder for a terminal.".into();
+ store_form(app, form);
+ return;
+ };
+ let cwd = cwd.clone();
+ let machine = crate::input::shell_machine(app, Some(&(form.draft.machine.clone(), String::new())));
+ let backing = app.focused().and_then(|p| app.panes.get(&p)).is_some_and(|p| {
+ app.fleet.agent(&p.machine_id, &p.agent_id).is_some_and(|a|
+ a.engine == "terminal" && app.fleet.launch_machine_id(&p.machine_id) == machine
+ && p.cwd.as_ref().or(p.live_path.as_ref()).unwrap_or(&a.cwd) == &cwd)
+ });
+ if backing {
+ store_form(app, form);
+ app.tab_mut().home = false;
+ seen();
+ return;
+ }
+ form.remember_choices = false;
+ let id = form.id.clone();
+ store_form(app, form);
+ crate::input::create_opts(app, machine, What { engine: "terminal".into(), label: "Terminal".into(), dsh: None },
+ Some(cwd), None, false, NewOpts { form_id: Some(id), target, ..Default::default() });
+ seen();
+ }
+ Field::Recent(i) => {
+ let row = form.recent.get(i).cloned();
+ form.remember_choices = false;
+ let id = form.id.clone();
+ store_form(app, form);
+ match row {
+ Some(HomeRow::Harness(m, a)) => { app.open_agent(&m, &a, Placement::Auto(None)); seen(); }
+ Some(HomeRow::External(x)) => {
+ crate::input::create_opts(app, x.machine,
+ What { label: theme::engine_label(&x.engine).into(), engine: x.engine, dsh: None },
+ Some(x.cwd), None, false, NewOpts { form_id: Some(id), target, name: Some(x.title),
+ extra: Some(json!({"resumeSessionId":x.session_id})), ..Default::default() });
+ seen();
+ }
+ None => {}
+ }
+ }
+ _ => store_form(app, form),
+ }
+}
+
+/// Read-only discovery continues while the page is visible. Older daemons have no readiness
+/// flag, so an empty first result is revisited while their initial index warms up.
+pub(crate) fn tick(app: &mut App) {
+ let windows: std::collections::HashSet<_> = app.tabs.iter().chain(app.sessions.iter().flat_map(|s| s.tabs.iter()))
+ .map(|t| t.id.clone()).collect();
+ app.welcome.forms.retain(|tab, form| windows.contains(tab) || form.starting || form.attempt.is_some());
+ let shown = app.home_visible();
+ if shown && !app.welcome.shown {
+ for s in app.welcome.searches.values_mut() { if !s.pending { s.next = Instant::now() } }
+ }
+ app.welcome.shown = shown;
+ if !shown { return }
+ let now = Instant::now();
+ let machines: Vec<_> = app.fleet.visible_machines().filter(|m| m.usable() && !crate::local::is_local(&m.id))
+ .filter(|m| app.welcome.searches.get(&m.id).is_none_or(|s| !s.pending && now >= s.next))
+ .map(|m| m.id.clone()).collect();
+ for machine in machines {
+ let Some(link) = app.link(&machine) else { continue };
+ let generation = app.welcome.generation;
+ let search = app.welcome.searches.entry(machine.clone()).or_insert(Search {
+ pending: false, discovering: true, failed: false, asked_at: now, next: now,
+ });
+ search.pending = true;
+ let end = crate::fleet::now_ms();
+ let payload = json!({"query":"", "from":end.saturating_sub(30 * 86_400_000), "to":end, "limit":30});
+ app.spawn(async move { link.rpc("session_search", payload, Duration::from_secs(10)).await }, move |app, result| {
+ if app.welcome.generation != generation { return }
+ let Some(search) = app.welcome.searches.get_mut(&machine) else { return };
+ search.pending = false;
+ match result {
+ Ok(reply) => {
+ let external = crate::app::externals(&machine, &reply);
+ search.failed = reply["discoveryError"] == true;
+ search.discovering = !search.failed && reply["ready"].as_bool().map(|ready| !ready).unwrap_or_else(||
+ reply["pending"].as_u64().unwrap_or(0) > 0 ||
+ external.is_empty() && reply["indexed"].as_u64().unwrap_or(0) == 0 && search.asked_at.elapsed() < Duration::from_secs(20));
+ search.next = Instant::now() + Duration::from_secs(if search.discovering { 1 } else { 30 });
+ app.home_external.retain(|x| x.machine != machine);
+ app.home_external.extend(external.into_iter().filter(|x| !x.open));
+ }
+ Err(_) => {
+ search.failed = true;
+ search.discovering = false;
+ search.next = Instant::now() + Duration::from_secs(15);
+ }
+ }
+ });
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ fn app() -> App {
+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();
+ let mut app = App::new(19789, sink, (150, 42));
+ app.fleet.local_id = "local".into();
+ app.fleet.machines.push(crate::fleet::Machine {
+ id: "local".into(), name: "office".into(), local: true,
+ status: "online".into(), reach: crate::fleet::Reach::Ready,
+ });
+ app.tab_mut().home = true;
+ app
+ }
+ fn event(app: &mut App, code: KeyCode, modifiers: KeyModifiers) {
+ crate::input::handle(app, crossterm::event::Event::Key(KeyEvent::new(code, modifiers)));
+ }
+
+ #[tokio::test]
+ async fn each_window_keeps_its_task_and_paste_never_reaches_the_backing_shell() {
+ let mut app = app();
+ ensure(&mut app, None, Some("/work/first".into()));
+ let first = app.tab().id.clone();
+ let buffer = std::sync::Arc::new(std::sync::Mutex::new(vec![]));
+ app.shell_inputs.insert(first.clone(), buffer.clone());
+ for ch in "123 fix login".chars() { event(&mut app, KeyCode::Char(ch), KeyModifiers::NONE); }
+ crate::input::handle(&mut app, crossterm::event::Event::Paste("\r\nKeep café and 界.".into()));
+ assert!(buffer.lock().unwrap().is_empty());
+ assert_eq!(app.welcome.forms[&first].draft.task, "123 fix login\nKeep café and 界.");
+ app.new_tab();
+ let second = app.tab().id.clone();
+ ensure(&mut app, None, Some("/work/second".into()));
+ event(&mut app, KeyCode::Char('x'), KeyModifiers::NONE);
+ assert_eq!(app.welcome.forms[&second].draft.task, "x");
+ let index = app.tabs.iter().position(|t| t.id == first).unwrap();
+ app.select_tab(index);
+ assert!(matches!(&app.welcome.forms[&first].draft.project, Project::Folder(p) if p == "/work/first"));
+ assert_eq!(app.welcome.forms[&first].draft.task, "123 fix login\nKeep café and 界.");
+ event(&mut app, KeyCode::Esc, KeyModifiers::NONE);
+ assert!(app.home_visible());
+ assert!(buffer.lock().unwrap().is_empty());
+ }
+
+ #[tokio::test]
+ async fn page_resource_replies_do_not_replace_other_windows_or_a_modal() {
+ let mut app = app();
+ ensure(&mut app, None, None);
+ let first = app.tab().id.clone();
+ let id = app.welcome.forms[&first].id.clone();
+ app.new_tab();
+ ensure(&mut app, None, None);
+ let second = app.tab().id.clone();
+ app.modal = Some(Modal::Confirm { prompt: "keep me".into(), command: "".into(), key: 'y', enter_yes: false });
+ with_form(&mut app, &id, |_, form| { form.error = "Only the first window".into() });
+ assert!(matches!(app.modal, Some(Modal::Confirm { .. })));
+ assert_eq!(app.welcome.forms[&first].error, "Only the first window");
+ assert!(app.welcome.forms[&second].error.is_empty());
+ }
+
+ #[tokio::test]
+ async fn tmux_paste_and_forwarded_prefix_edit_the_task_without_reaching_a_pane() {
+ let mut app = app();
+ ensure(&mut app, None, Some("/work/project".into()));
+ let tab = app.tab().id.clone();
+ app.open_agent("local", "backing-shell", Placement::Fill(tab.clone()));
+ let pane = app.focused().unwrap();
+ app.paste.add("first\r\nsecond".into(), 10);
+ crate::commands::execute(&mut app, "paste-buffer -d");
+ assert!(app.paste.top().is_none());
+ assert_eq!(app.welcome.forms[&tab].draft.task, "first\nsecond");
+ crate::commands::execute(&mut app, "send-prefix");
+ event(&mut app, KeyCode::Char('!'), KeyModifiers::NONE);
+ assert_eq!(app.welcome.forms[&tab].draft.task, "first\nsecon!d");
+ assert!(app.panes[&pane].queued.is_empty());
+ // An explicitly targeted pane remains a scriptable terminal, as in tmux.
+ app.paste.add("explicit shell input".into(), 10);
+ crate::commands::execute(&mut app, &format!("paste-buffer -t {}", crate::pane::tag(pane)));
+ assert_eq!(app.welcome.forms[&tab].draft.task, "first\nsecon!d");
+ assert_eq!(app.panes[&pane].queued, vec![b"explicit shell input".to_vec()]);
+ }
+
+ #[tokio::test]
+ async fn a_plain_prefix_is_text_in_the_task_and_navigation_on_a_setting() {
+ let mut app = app();
+ ensure(&mut app, None, None);
+ app.keymap.prefix = crate::keys::parse("`").unwrap();
+ let tab = app.tab().id.clone();
+ event(&mut app, KeyCode::Char('`'), KeyModifiers::NONE);
+ assert_eq!(app.welcome.forms[&tab].draft.task, "`");
+ assert!(!app.prefix);
+ event(&mut app, KeyCode::Tab, KeyModifiers::NONE);
+ event(&mut app, KeyCode::Char('`'), KeyModifiers::NONE);
+ assert!(app.prefix, "Tab out of text must restore a custom plain prefix");
+ assert_eq!(app.welcome.forms[&tab].draft.task, "`");
+ }
+
+ #[tokio::test]
+ async fn a_draft_typed_before_connection_follows_the_local_daemon_when_it_arrives() {
+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();
+ let mut app = App::new(19789, sink, (150, 42));
+ ensure(&mut app, None, Some("/work/project".into()));
+ let tab = app.tab().id.clone();
+ event(&mut app, KeyCode::Char('1'), KeyModifiers::NONE);
+ assert_eq!(app.welcome.forms[&tab].draft.machine, crate::local::MACHINE);
+ app.fleet.local_id = "registered-local".into();
+ app.fleet.machines.push(crate::fleet::Machine {
+ id: "registered-local".into(), name: "office".into(), local: true,
+ status: "online".into(), reach: crate::fleet::Reach::Ready,
+ });
+ super::super::refresh(&mut app);
+ let form = &app.welcome.forms[&tab];
+ assert_eq!(form.draft.machine, "registered-local");
+ assert_eq!(form.draft.task, "1");
+ assert!(matches!(&form.draft.project, Project::Folder(p) if p == "/work/project"));
+ }
+
+ #[tokio::test]
+ async fn welcome_stays_anchored_and_reachable_with_history_long_tasks_and_small_terminals() {
+ let mut app = app();
+ ensure(&mut app, None, Some("/work/project".into()));
+ let mut form = take_active(&mut app).unwrap();
+ set_engine(&mut form, "codex");
+ for (width, height) in [(150, 41), (80, 23), (45, 14), (22, 5), (1, 1)] {
+ let area = Rect::new(0, 0, width, height);
+ form.recent.clear();
+ form.draft.task.clear();
+ view::draw(&mut Buffer::empty(area), area, &mut form);
+ let anchor = form.area;
+ form.draft.task = "Fix café and 界.\n".repeat(80);
+ form.recent = (0..3).map(|i| HomeRow::Harness("local".into(), format!("{i}"))).collect();
+ form.recent_labels = (0..3).map(|i| (format!("Previous work {i}"), "office · app".into())).collect();
+ for focus in form.fields() {
+ form.focus = focus;
+ let cursor = view::draw(&mut Buffer::empty(area), area, &mut form);
+ assert_eq!(form.area, anchor);
+ assert!(cursor.is_none_or(|p| area.contains(p)));
+ if width >= 22 && height >= 5 { assert!(form.hits.iter().any(|(_, f)| *f == focus), "{width}x{height}: {focus:?}"); }
+ assert!(form.hits.iter().all(|(r, _)| r.intersection(area) == *r));
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn discovery_removal_cannot_move_enter_to_another_conversation() {
+ let mut app = app();
+ for i in 0..3 {
+ let a = crate::fleet::agent_from("local", &json!({"id":format!("{i}"), "name":format!("Work {i}"), "engine":"codex"}), None);
+ app.fleet.agents.insert(a.key(), a);
+ }
+ ensure(&mut app, None, None);
+ let mut form = take_active(&mut app).unwrap();
+ prepare(&app, &mut form);
+ form.focus = Field::Recent(1);
+ let key = form.recent[1].key();
+ app.fleet.agents.remove(&key);
+ prepare(&app, &mut form);
+ assert_eq!(form.focus, Field::Browse);
+ }
+
+ #[tokio::test]
+ async fn closing_a_pending_window_preserves_its_receipt_and_the_other_dialog_draft() {
+ let mut app = app();
+ super::super::open(&mut app, None, Some("/work/dialog".into()));
+ let mut dialog = take_active(&mut app).unwrap();
+ dialog.draft.task = "Keep my separate dialog draft".into();
+ let dialog_id = dialog.id.clone();
+ dismiss(&mut app, dialog);
+ ensure(&mut app, None, Some("/work/page".into()));
+ let mut pending = take_active(&mut app).unwrap();
+ let id = pending.id.clone();
+ pending.surface = Surface::Window("closed-window".into());
+ pending.attempt = Some(Creation { id: "receipt".into(), machine: "local".into(),
+ session: app.session_id, target: Some(LaunchTarget { session: app.session_id, tab: "closed-window".into() }) });
+ store_form(&mut app, pending);
+ tick(&mut app);
+ assert!(app.welcome.forms.contains_key("closed-window"));
+ super::super::open(&mut app, None, None);
+ let pending = take_active(&mut app).unwrap();
+ assert_eq!(pending.id, id);
+ assert_eq!(pending.describe(Field::Create).0, "Check status");
+ dismiss(&mut app, pending);
+ assert!(app.welcome.forms.contains_key("closed-window"));
+ assert_eq!(app.new_harness_draft.as_ref().unwrap().id, dialog_id);
+ assert_eq!(app.new_harness_draft.as_ref().unwrap().draft.task, "Keep my separate dialog draft");
+ assert!(super::super::creation_reply(&mut app, &id,
+ &Ok(json!({"creationId":"receipt", "state":"created", "agent":{"id":"created"}})), true));
+ super::super::created(&mut app, &id, &json!({"id":"created"}));
+ assert!(!app.welcome.forms.contains_key("closed-window"));
+ assert_eq!(app.new_harness_draft.as_ref().unwrap().id, dialog_id);
+ }
+
+ #[tokio::test]
+ async fn disconnected_history_does_not_leave_a_stale_spinner_or_resume_target() {
+ let mut app = app();
+ ensure(&mut app, None, None);
+ app.home_external = crate::app::externals("local", &json!({"hits":[{
+ "sessionId":"previous", "engine":"codex", "lastAt":1,
+ "external":{"title":"Previous task", "cwd":"/work"}
+ }]}));
+ app.welcome.searches.insert("local".into(), Search { pending: true, discovering: true,
+ failed: false, asked_at: Instant::now(), next: Instant::now() });
+ let mut form = take_active(&mut app).unwrap();
+ prepare(&app, &mut form);
+ assert_eq!(form.recent.len(), 1);
+ form.focus = Field::Recent(0);
+ app.fleet.machine_mut("local").unwrap().reach = crate::fleet::Reach::Offline;
+ prepare(&app, &mut form);
+ assert!(form.recent.is_empty());
+ assert_eq!(form.focus, Field::Browse);
+ assert_eq!(form.recent_status, "History appears when a machine connects");
+ }
+}
diff --git a/tui/src/ui.rs b/tui/src/ui.rs
index 041fa1022..85c6b8f5c 100644
--- a/tui/src/ui.rs
+++ b/tui/src/ui.rs
@@ -16,13 +16,11 @@ use unicode_width::UnicodeWidthStr;
use crate::app::App;
use crate::fleet::ago;
-use crate::format::clip_middle;
use crate::keys;
use crate::modal::{Modal, PickerKind, PromptKind};
use crate::pane::{Pane, Phase};
use crate::picker::Picker;
-use crate::theme::{self, bold, fg, engine_mark, state_mark};
-use crate::input::{home_rows, HomeRow};
+use crate::theme::{self, bold, fg};
/// Time-dependent content asks for its next repaint; a static surface asks for
/// none. Hints and messages are deadlines, independent of reduced motion.
@@ -184,7 +182,7 @@ pub fn draw(frame: &mut Frame, app: &mut App) {
// (The settings panel is not one: it floats over the panes, as the New Harness form does.)
let full_screen = matches!(&app.modal, Some(Modal::Picker { kind, .. }) if theme::fzf_opts().height.is_none() && !crate::settings::is_panel(kind));
if !full_screen {
- if app.tab().home || app.tab().root.is_none() { empty_window(buf, app, body) }
+ if app.tab().home || app.tab().root.is_none() { cursor = empty_window(buf, app, body); themed_home(buf, body); }
else { cursor = window(buf, app, body) }
}
// Panes in clock mode: the time over each (its cursor hidden).
@@ -580,110 +578,11 @@ fn box_style(app: &App, id: u64) -> Style {
if app.marked == Some(id) { style.add_modifier(Modifier::BOLD) } else { style }
}
-/// A window with no harness in it: the harnesses you were just with, one key away.
const WORDMARK: [&str; 2] = ["█ █ ▄▀█ █▀█ █▄ █ █▀▀ █▀ █▀", "█▀█ █▀█ █▀▄ █ ▀█ ██▄ ▄█ ▄█"];
-fn empty_window(buf: &mut Buffer, app: &App, area: Rect) {
- if crate::input::os_home(app) { os_welcome(buf, app, area); return }
- let rows = home_rows(app);
- let (_, theme_fg, _) = crate::theme::palette();
- let width = area.width.min(84).saturating_sub(4);
- let left = area.x + (area.width.saturating_sub(width)) / 2;
- let compact = area.height < 22;
- let mut lines: Vec<Line> = Vec::new();
- if !compact { for w in WORDMARK { lines.push(Line::styled(w, fg(theme::accent()))) } lines.push(Line::raw("")) }
- else { lines.push(Line::styled("harness", bold(theme::accent()))) }
- let local = app.fleet.local_machine_name();
- let up = app.fleet.visible_machines().filter(|m| m.usable()).count();
- let total = app.fleet.visible_machines().count();
- let sub = if total > 1 { format!("{local} · {up}/{total} machines connected") } else { local };
- lines.push(Line::styled(sub, fg(theme::MUTED)));
- lines.push(Line::raw(""));
- let centered = lines.len();
- if app.daemon_down {
- lines.push(Line::styled("The Harness daemon is not running here.", bold(theme::DANGER)));
- lines.push(Line::styled("Run `harness start` — this screen connects by itself.", fg(theme::SOFT)));
- } else if app.fleet.agents.is_empty() && app.started.elapsed().as_secs() < 3 {
- lines.push(Line::styled(format!("{} Finding your harnesses…", theme::spinner(app.tick)), fg(theme::SOFT)));
- } else if rows.is_empty() {
- lines.push(Line::styled("Nothing running.", fg(theme::SOFT)));
- let hint = |c: &str| app.keymap.hint(c).unwrap_or_default();
- lines.push(Line::from(vec![Span::styled(hint("new-harness"), bold(theme::accent())), Span::styled(" starts a harness · ", fg(theme::MUTED)), Span::styled(hint("choose-tree -Zs"), bold(theme::accent())), Span::styled(" opens a paused one", fg(theme::MUTED))]));
- } else {
- let many = up > 1;
- for (index, row) in rows.iter().enumerate() {
- // A harness as its state says; a conversation Harness did not start as a paused one
- // would be (nothing running), its folder where the project goes.
- let (m, dot, color, engine, title, recency, detail) = match row {
- HomeRow::Harness(m, a) => {
- let Some(agent) = app.fleet.agent(m, a) else { continue };
- let (dot, _, color) = state_mark(app.fleet.state_of(agent), app.tick);
- let detail = agent.question.as_ref().map(|q| (q.prompt.clone(), theme::ATTENTION)).unwrap_or((if agent.project.is_empty() { agent.cwd.clone() } else { agent.project.clone() }, theme::MUTED));
- (m.clone(), dot, color, agent.engine.clone(), agent.name.clone(), agent.recency(), detail)
- }
- HomeRow::External(x) => {
- let (dot, _, color) = state_mark(crate::fleet::State::Paused, app.tick);
- let folder = x.cwd.trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string();
- (x.machine.clone(), dot, color, x.engine.clone(), if x.title.is_empty() { folder.clone() } else { x.title.clone() }, x.last_at, (folder, theme::MUTED))
- }
- };
- let m = &m;
- let (mark, mark_color) = engine_mark(&engine);
- // Narrow: the machine goes before the title gives way (then the age).
- let right = if width < 56 { String::new() } else { format!("{}{}", if many && width >= 70 { format!("{} ", app.fleet.machine_name(m)) } else { String::new() }, ago(recency)) };
- let name_w = if width < 56 { (width as usize).saturating_sub(10).min(28) } else { 28 };
- // Widths are display widths: a CJK or emoji title keeps the columns straight.
- let name = clip_middle(&title, name_w);
- let name = format!("{name}{}", " ".repeat(name_w.saturating_sub(name.width())));
- let detail_room = (width as usize).saturating_sub(name_w + right.width() + 12);
- let detail_text = clip(&detail.0, detail_room);
- let used = 2 + 2 + 2 + name_w + 2 + detail_text.width();
- let pad = (width as usize).saturating_sub(used + right.width());
- let selected = app.home_moved && index == app.home_cursor;
- // The chosen row as fzf draws its current line (reverse video where there is no colour).
- let bg = match (selected, theme::fzf().bw) { (true, true) => Style::default().add_modifier(Modifier::REVERSED), (true, false) => Style::default().bg(theme::fzf().bg_plus), _ => Style::default() };
- let tint = |c: Color| if c == theme::MUTED || c == theme::SOFT { bg.fg(theme::paint(theme_fg)).add_modifier(Modifier::DIM) } else { bg.fg(theme::paint(c)) };
- lines.push(Line::from(vec![
- Span::styled(format!("{} ", index + 1), tint(theme::accent())),
- Span::styled(format!("{dot} "), tint(color)),
- Span::styled(format!("{mark} "), tint(mark_color)),
- Span::styled(format!("{name} "), bg.fg(theme::paint(theme_fg)).add_modifier(Modifier::BOLD)),
- Span::styled(detail_text, tint(detail.1)),
- Span::styled(" ".repeat(pad), bg),
- Span::styled(right, tint(theme::MUTED)),
- ]));
- }
- }
- lines.push(Line::raw(""));
- // Typing here is a shell's (as after tmux's C-b c); the rows by number, or the arrows and Enter;
- // the rest on the prefix's keys, as everywhere.
- let hint = |c: &str| app.keymap.hint(c).unwrap_or_default();
- let keys: Vec<(String, &str)> = vec![("1-9".into(), "open"), ("↑↓ enter".into(), "choose"), ("type".into(), "a shell here"), (hint("new-terminal"), "new terminal"), (hint("choose-tree -Zs"), "harnesses"), (hint("new-harness"), "new agent"), (hint("choose-tree -a"), "waiting"), (hint("choose-tree -m"), "machines")];
- let keys: Vec<(String, &str)> = keys.into_iter().filter(|(k, _)| !k.is_empty()).collect();
- let mut row: Vec<Span> = Vec::new();
- let mut row_w = 0;
- for (k, w) in keys {
- let piece_w = k.width() + w.width() + 4;
- if row_w + piece_w > width as usize { lines.push(Line::from(std::mem::take(&mut row))); row_w = 0 }
- row.push(Span::styled(k.clone(), bold(theme::accent())));
- row.push(Span::styled(format!(" {w} "), fg(theme::SOFT)));
- row_w += piece_w;
- }
- if !row.is_empty() { lines.push(Line::from(row)) }
- lines.push(Line::raw(""));
- let prefix = crate::keys::name(&app.keymap.prefix);
- let (key, description) = if app.os_session { ("Super+B".into(), " browser · Super+Enter terminal") }
- else { (format!("{prefix} d"), " detach — everything keeps running") };
- lines.push(Line::from(vec![Span::styled(format!("{prefix} ?"), bold(theme::accent())), Span::styled(" every key ", fg(theme::SOFT)), Span::styled(key, bold(theme::accent())), Span::styled(description, fg(theme::SOFT))]));
- let top = area.y + area.height.saturating_sub(lines.len() as u16) / 2;
- for (index, line) in lines.iter().enumerate() {
- let y = top + index as u16;
- if y >= area.y + area.height { break }
- let w = line.width() as u16;
- let x = if index < centered { area.x + area.width.saturating_sub(w) / 2 } else { left };
- buf.set_line(x, y, line, area.width.saturating_sub(x - area.x));
- }
- themed_home(buf, area);
+fn empty_window(buf: &mut Buffer, app: &mut App, area: Rect) -> Option<Position> {
+ if crate::input::os_home(app) { os_welcome(buf, app, area); None }
+ else { crate::new_harness::draw_welcome(buf, app, area) }
}
fn os_welcome(buf: &mut Buffer, app: &App, area: Rect) {
@@ -718,8 +617,8 @@ fn os_welcome(buf: &mut Buffer, app: &App, area: Rect) {
mod os_welcome_tests {
use super::*;
- #[test]
- fn ordinary_hn_installed_os_and_live_usb_have_separate_homes() {
+ #[tokio::test]
+ async fn ordinary_hn_installed_os_and_live_usb_have_separate_homes() {
for (width, height) in [(80, 24), (60, 18), (120, 40)] {
let (sink, _) = tokio::sync::mpsc::unbounded_channel();
let mut app = App::new(19789, sink, (width, height));
@@ -729,13 +628,13 @@ mod os_welcome_tests {
app.os_live = live;
let area = Rect::new(0, 0, width, height);
let mut buf = Buffer::empty(area);
- empty_window(&mut buf, &app, area);
+ empty_window(&mut buf, &mut app, area);
let text = (0..height).map(|y| (0..width).map(|x| buf[(x, y)].symbol()).collect::<String>()).collect::<Vec<_>>().join("\n");
if !os {
- for action in ["Install Harness", "Try without installing", "Start OpenCode", "Wi-Fi", "Super+B"] {
+ for action in ["Install Harness", "Try without installing", "Wi-Fi", "Super+B"] {
assert!(!text.contains(action), "ordinary hn must not offer {action}: {text}");
}
- assert!(text.contains("detach"), "{text}");
+ assert!(text.contains("Task"), "{text}");
} else if live {
assert!(text.contains("Enter Install Harness"), "{text}");
assert!(text.contains("T Try without installing"), "{text}");
@@ -3074,7 +2973,7 @@ mod theme_render_tests {
assert_eq!(buf[(2, 0)].fg, Color::Rgb(1, 2, 3));
}
- /// The home screen follows a chosen theme: the wordmark in its accent, the screen on its
+ /// The home screen follows a chosen theme: the task pointer in its accent, the screen on its
/// background; with no theme, the terminal's own background stays.
#[test]
fn the_home_screen_follows_the_theme() {
@@ -3084,7 +2983,7 @@ mod theme_render_tests {
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(150, 42)).unwrap();
term.draw(|f| draw(f, app)).unwrap();
let buf = term.backend().buffer().clone();
- (buf[(1, 1)].bg, (0..42).flat_map(|y| (0..150).map(move |x| (x, y))).find(|p| buf[*p].symbol() == "█").map(|p| buf[p].fg))
+ (buf[(1, 1)].bg, (0..42).flat_map(|y| (0..150).map(move |x| (x, y))).find(|p| buf[*p].symbol() == "›").map(|p| buf[p].fg))
};
let (plain, _) = bg_at(&mut app);
assert_eq!(plain, Color::Reset, "no theme: the terminal's own background");
@@ -3092,7 +2991,7 @@ mod theme_render_tests {
let t = crate::terminal_themes::TERMINAL_THEMES.iter().find(|t| t.name == "Adwaita Dark").unwrap();
let (themed, logo) = bg_at(&mut app);
assert_eq!(themed, theme::depth_fit(Color::Rgb(t.background[0], t.background[1], t.background[2])));
- assert_eq!(logo, Some(theme::depth_fit(theme::accent())), "the wordmark in the theme's accent");
+ assert_eq!(logo, Some(theme::depth_fit(theme::accent())), "the task pointer in the theme's accent");
let _ = app.set_look("theme", "");
}
@@ -3306,6 +3205,7 @@ mod theme_render_tests {
use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
let mut app = app();
app.keymap.prefix = crate::keys::parse("`").unwrap();
+ app.tab_mut().root = Some(crate::layout::Node::new(0, 150, 41));
let key = |app: &mut App, code: KeyCode, mods: KeyModifiers| crate::input::handle(app, Event::Key(KeyEvent::new(code, mods)));
key(&mut app, KeyCode::Char('`'), KeyModifiers::NONE);
assert!(app.prefix, "over the panes, ` is the prefix");
diff --git a/tui/tests/e2e.sh b/tui/tests/e2e.sh
index 53fb626b8..6c663d1b6 100755
--- a/tui/tests/e2e.sh
+++ b/tui/tests/e2e.sh
@@ -53,8 +53,10 @@ wait_eq() { # wait_eq <what> <expected> <command…>: until the command prints w
echo "✓ $what"
}
-# As tmux starts: window 0 is a shell on this computer.
-expect "starts in a shell, as tmux does" "Mock terminal (mock)" 5000
+# The first window is ready for a task; Open Terminal is an explicit keyboard action.
+expect "starts with the task-first welcome" "Welcome to Harness" 5000
+tmux_ send-keys -t t Tab Tab Tab Tab Tab Tab Tab Tab Enter
+expect "Open Terminal opens a shell here" "Mock terminal (mock)" 5000
status_tabs() { screen | tail -n 1 | grep -q '^ 0:' && echo yes; }
wait_eq "status line starts with window tabs, without a session label" yes status_tabs
expect "status line quotes the local machine's app name" '"mock-local"'
@@ -212,14 +214,13 @@ tmux_ send-keys -t t q
tmux_ send-keys -t t C-b x
expect "C-b x asks first" "(y/n)"
tmux_ send-keys -t t n
-# C-b c: a new window on the home page (its recent harnesses and conversations; typing starts a shell there).
+# C-b c: the same task-first composer, with recent sessions below it.
before=$(dial "(d.deleted || []).length")
tmux_ send-keys -t t C-b c
expect "C-b c: another new window" "2:"
-expect "C-b c: the home page, a conversation Harness did not start in it" "Continue NFC device chat"
-# Its shell (a key typed there makes it, as after tmux's C-b c), killed with its window (C-b &),
-# goes with it, as tmux kills the pane's shell.
-tmux_ send-keys -t t Enter
+expect "C-b c: the creation form and secondary session browser" "Browse All Sessions"
+# Explicitly opening its terminal reuses the backing shell; C-b & kills it with the window.
+tmux_ send-keys -t t Tab Tab Tab Tab Tab Tab Tab Tab Enter
sleep 1
tmux_ send-keys -t t C-b '&'
expect "C-b & asks first" "(y/n)"
@@ -260,7 +261,7 @@ tmux_ has-session -t t 2>/dev/null && screen | grep -q "Mock" && fail "C-b d did
echo "✓ C-b d detaches"
# The last window closed ends hn, as the session's end ends tmux's client.
tmux_ new-session -d -s u -x 120 -y 32 "env -u TMUX -u TMUX_PANE -u HN_SOCKET HN_SOCKET_NAME=$client-2 HOME=$home PORT=$port HARNESS_TUI_DESK=off HARNESS_TUI_NOTIFY=off HN_DESKTOP=off '$bin' -L '$client-2' --port '$port'; sleep 5"
-waited=0; until tmux_ capture-pane -p -t u | grep -qF "Mock terminal (mock)"; do sleep 0.05; waited=$((waited + 50)); [ "$waited" -ge 5000 ] && fail "a second hn started no shell"; done
+waited=0; until tmux_ capture-pane -p -t u | grep -qF "New Window"; do sleep 0.05; waited=$((waited + 50)); [ "$waited" -ge 5000 ] && fail "a second hn showed no new-window form"; done
tmux_ send-keys -t u C-b '&'
sleep 0.3
tmux_ send-keys -t u y
diff --git a/tui/tests/local-first.py b/tui/tests/local-first.py
index b43ebd3f2..bd56f3ede 100644
--- a/tui/tests/local-first.py
+++ b/tui/tests/local-first.py
@@ -108,7 +108,7 @@ try:
assert second['machineId'] == 'b' * 32 and second['signedIn'] is False
assert second['config']['port'] != first['config']['port']
assert status(a)['pid'] == first['pid']
- wait(lambda: 'Nothing running.' in (s := screen()) or 'Terminal on ' in s, 'guest home or local terminal')
+ wait(lambda: 'Welcome to Harness' in (s := screen()) or 'New Window' in s or 'Terminal on ' in s, 'guest home or local terminal')
assert 'OTHER_ACCOUNT_PRIVATE' not in screen()
assert not (b / 'browser-opened').exists()
assert not (b / 'auth/session.json').exists()
diff --git a/tui/tests/mock-daemon.mjs b/tui/tests/mock-daemon.mjs
index a1b91306c..6ead92f7d 100644
--- a/tui/tests/mock-daemon.mjs
+++ b/tui/tests/mock-daemon.mjs
@@ -162,6 +162,10 @@ const desk = DEMO ? { revision: 1, tabs: [
const dial = { said: {}, replies: [], messages: [] }
// How many of each request the windows made (GET /test/counts), for tests of what hn asks.
const counts = {}
+const welcomeTest = process.env.MOCK_WELCOME === '1'
+if (welcomeTest && !(port >= 19780 && port <= 19789)) throw new Error('unsafe welcome test port')
+const welcome = { history: 'loading', delay: 0, searches: [] }
+if (welcomeTest) { agents[LOCAL] = []; agents[REMOTE] = [] }
const windows = new Set()
// Opt-in faults for reconnect.py. No real daemon or agent is involved.
// Controlled desk latency/failures for layout reconciliation tests, on private ports only.
@@ -183,6 +187,13 @@ let demoAsked = false
const json = (res, body) => { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ success: true, data: body })) }
const server = http.createServer((req, res) => {
+ if (welcomeTest && req.url === '/test/welcome') {
+ if (req.method === 'GET') return json(res, welcome)
+ let body = ''
+ req.on('data', (part) => { body += part })
+ req.on('end', () => { const update = JSON.parse(body); Object.assign(welcome, update); json(res, welcome) })
+ return
+ }
if (layoutTest && req.url === '/test/layout') {
if (req.method === 'GET') return json(res, layoutFaults)
let body = ''
@@ -412,7 +423,15 @@ wss.on('connection', (ws) => {
// The e2e reads which harnesses were deleted (a killed pane's shell goes with it).
case 'agent_delete': dial.deleted = [...(dial.deleted || []), payload.agentId]; return reply({ agent: agents[machine][0], deleted: true })
case 'agent_update': case 'agent_resume': case 'agent_restart': return reply({ agent: agents[machine][0], deleted: true })
- case 'session_search': return reply({ hits: searchHits(machine, payload.query, payload.from, payload.to), indexed: 12, pending: 0, tookMs: 3 })
+ case 'session_search': {
+ if (welcomeTest) {
+ welcome.searches.push({ machine, ...payload })
+ if (welcome.history === 'failed') return reply({ error: 'INDEX_UNAVAILABLE' })
+ if (welcome.history === 'loading') return reply({ hits: [], indexed: 0, pending: 0, ready: false, tookMs: 1 })
+ if (welcome.history === 'empty') return reply({ hits: [], indexed: 0, pending: 0, ready: true, tookMs: 1 })
+ }
+ return reply({ hits: searchHits(machine, payload.query, payload.from, payload.to), indexed: 12, pending: 0, ready: true, tookMs: 3 })
+ }
case 'session_tail': {
const x = EXTERNAL.find((e) => e.sessionId === payload.sessionId)
const a = (agents[machine] || []).find((e) => e.sessionId === payload.sessionId)
@@ -464,11 +483,13 @@ wss.on('connection', (ws) => {
return reply({ agent: resumed })
}
const created = agent(randomUUID(), `Mock ${payload.engine}`, payload.engine)
+ if (welcomeTest && payload.cwd) created.project = { name: payload.cwd.split('/').pop(), cwd: payload.cwd, root: payload.cwd, branch: 'main' }
agents[machine].push(created)
if (process.env.MOCK_NEW_UI === '1') {
const outcome = { state: 'created', agent: created }
creationReceipts.set(receiptKey, { fingerprint, outcome, pendingChecks: payload.projectName === 'lose-reply' ? 1 : 0 })
if (payload.projectName === 'lose-reply') return ws.terminate()
+ if (welcomeTest && welcome.delay && payload.engine !== 'terminal') return setTimeout(() => reply({ creationId: payload.creationId, ...outcome }), welcome.delay)
return reply({ creationId: payload.creationId, ...outcome })
}
return reply({ agent: created })
diff --git a/tui/tests/new-harness.py b/tui/tests/new-harness.py
index baa5e94bc..1977eec6a 100644
--- a/tui/tests/new-harness.py
+++ b/tui/tests/new-harness.py
@@ -53,7 +53,7 @@ def state(route='dial'):
def screen(): return tmux('capture-pane', '-p', '-t', 'test')
def form_bounds(lines):
width, height = max(map(len, lines), default=0), len(lines) - 1
- form_w, form_h = min(60, max(0, width - 4)), min(17, max(5, height - 2))
+ form_w, form_h = min(60, max(0, width - 4)), min(19, max(5, height - 2))
return (width - form_w) // 2, max(0, (height - form_h) // 2), form_w, form_h
def form_screen():
lines = screen().splitlines()
@@ -197,10 +197,10 @@ try:
assert create_count() == before, 'searching projects across machines only changes the draft'
print('PASS New Harness: short local machine name and remote folders after a large local history', flush=True)
# Moving over a field previews its choices beside the stationary form.
- keys('Down'); shows('Search agents and harnesses')
+ keys('Down', 'Tab'); shows('Search agents and harnesses')
assert field_position('Task') == anchor, 'a preview must not move or hide the form'
assert any(line.find('Search agents and harnesses') > anchor[0] + 50 for line in screen().splitlines())
- keys('Tab'); shows('Search agents and harnesses')
+ keys('Right'); shows('Search agents and harnesses')
assert field_position('Task') == anchor, 'entering a chooser keeps the form visible'
assert 'Blender' in screen(), 'the agent chooser lists the harnesses'
snapshot('new-harness-agent')
@@ -218,12 +218,12 @@ try:
assert not re.search(field_at('Options|Machine'), form_screen()), 'settings are direct fields; machine belongs in Project'
choose_field('Approvals', 'read only'); shows('Read only')
task_text = 'Fix café login.\n\nKeep 界 and 🦀 intact.\nAdd a regression test.'
- field('Task'); shows('Task (optional)')
+ field('Task'); shows('Enter start')
assert field_position('Task') == anchor, 'the task editor keeps the form visible and fixed'
raw('\x1b[200~Fix café login.\r\n\r\nKeep 界 and 🦀 intact.\x1b[201~')
shows('Keep 界 and 🦀 intact.')
- keys('M-Enter'); type_text('Add a regression test.'); keys('Enter')
- assert create_count() == before, 'accepting a task returns to the form without launching'
+ keys('M-Enter'); type_text('Add a regression test.'); keys('BTab')
+ assert create_count() == before, 'leaving the task editor does not launch'
snapshot('new-harness-settings')
keys('Enter', 'Enter'); shows('Fixture launch failure')
assert create_count() == before + 1, 'busy popup prevents double submission'
@@ -314,10 +314,10 @@ try:
shows('autonomous-harness @ local'); shows('[x]')
tmux('resize-window', '-t', 'test', '-x', '150', '-y', '42'); settle_ui()
snapshot('new-harness-flat')
- field('Task'); shows('Task (optional)')
+ field('Task'); shows('Enter start')
raw('\x1b[200~Improve the New Harness keyboard flow.\nKeep the launch settings visible.\x1b[201~')
shows('Keep the launch settings visible.'); snapshot('new-harness-task')
- keys('Escape', 'Escape'); new_form(); shows('Improve the New Harness keyboard flow.')
+ keys('Escape'); new_form(); shows('Improve the New Harness keyboard flow.')
snapshot('new-harness-flat-task')
tmux('resize-window', '-t', 'test', '-x', '80', '-y', '24'); settle_ui()
snapshot('new-harness-flat-narrow')
@@ -329,10 +329,10 @@ try:
assert request['engine'] == 'terminal' and 'prompt' not in request and 'command' not in request, request
count += 1
new_form(); shows('Improve the New Harness keyboard flow.')
- field('Task'); keys('C-a', 'C-k', 'Enter'); choose_field('Agent|Harness', 'claude')
+ field('Task'); keys('C-Home', 'C-k', 'C-k', 'C-k', 'C-k', 'Tab'); choose_field('Agent|Harness', 'claude')
field('Task'); type_text('x' * 2001); keys('Enter'); field('Start Claude Code'); shows('Task is too long')
assert create_count() == count, 'an overlong task is rejected before creating a harness'
- field('Task'); keys('C-a', 'C-k', 'Enter')
+ field('Task'); keys('C-Home', 'C-k', 'BTab')
tmux('resize-window', '-t', 'test', '-x', '150', '-y', '42'); settle_ui()
# Supply actual terminal palette replies, as a light terminal would.
raw('\x1b]10;rgb:2020/2020/2020\x1b\\\x1b]11;rgb:ffff/ffff/ffff\x1b\\')
diff --git a/tui/tests/reconnect.py b/tui/tests/reconnect.py
index 3c5a60747..c25027661 100644
--- a/tui/tests/reconnect.py
+++ b/tui/tests/reconnect.py
@@ -35,7 +35,7 @@ ENV.update(HOME=str(BASE), HN_TMPDIR=str(BASE), HN_SOCKET_NAME=PREFIX, PORT=str(
TERM='xterm-256color', SHELL='/bin/sh', HARNESS_TUI_DESK='off',
HARNESS_TUI_NOTIFY='off', HN_DESKTOP='off', MOCK_RECONNECT='1')
CONF = BASE / 'tmux.conf'
-CONF.write_text('set -g automatic-rename off\nset -g pane-border-status off\n')
+CONF.write_text('set -g @hn-new-window shell\nset -g automatic-rename off\nset -g pane-border-status off\n')
def hn(*args, ok=True):
diff --git a/tui/tests/repaint.py b/tui/tests/repaint.py
index 0c6f98ec1..4b16c326b 100644
--- a/tui/tests/repaint.py
+++ b/tui/tests/repaint.py
@@ -30,7 +30,7 @@ ENV.update(HOME=str(BASE), HN_TMPDIR=str(BASE), HN_SOCKET_NAME=PREFIX, PORT=str(
HARNESS_TUI_NOTIFY='off', HN_DESKTOP='off', HARNESS_TUI_ASK_TERMINAL='off',
HARNESS_TUI_KITTY_KEYS='off')
CONF = BASE / 'tmux.conf'
-CONF.write_text('set -g automatic-rename off\nset -g status-right "REPAINT_IDLE"\n'
+CONF.write_text('set -g @hn-new-window shell\nset -g automatic-rename off\nset -g status-right "REPAINT_IDLE"\n'
'set -g set-titles-string "REPAINT_TITLE"\n')
COMMAND = [str(HN), '-L', PREFIX, '--port', str(PORT), '-f', str(CONF)]
OUTER = [TMUX, '-L', PREFIX + '-outer', '-f', '/dev/null']
diff --git a/tui/tests/welcome.py b/tui/tests/welcome.py
new file mode 100644
index 000000000..480cf98ef
--- /dev/null
+++ b/tui/tests/welcome.py
@@ -0,0 +1,301 @@
+#!/usr/bin/env python3
+"""Real-terminal welcome/new-window journeys against a private, fresh-user fixture.
+
+No accounts, installed agents, user settings, or live sessions are used.
+"""
+import json
+import os
+from pathlib import Path
+import re
+import shlex
+import shutil
+import socket
+import subprocess
+import tempfile
+import time
+import urllib.request
+
+ROOT = Path(__file__).resolve().parents[1]
+PORT = int(os.environ.get('HN_WELCOME_TEST_PORT', '19787'))
+assert 19780 <= PORT <= 19789
+PREFIX = f'hn-welcome-{os.getpid()}'
+BASE = Path(tempfile.mkdtemp(prefix='hn-welcome-', dir='/tmp')).resolve()
+PROJECT = BASE / 'autonomous-harness'
+PROJECT.mkdir()
+HN = BASE / 'hn'
+shutil.copy2(os.environ.get('HN_WELCOME_TEST_BINARY', ROOT / 'target/release/harness-tui'), HN)
+TMUX = shutil.which('tmux')
+assert TMUX
+ENV = {k: os.environ[k] for k in ('PATH', 'LANG', 'LC_ALL', 'TZ', 'NODE_PATH') if k in os.environ}
+ENV.update(HOME=str(BASE), HN_TMPDIR=str(BASE), HN_SOCKET_NAME=PREFIX, PORT=str(PORT),
+ TERM='xterm-256color', COLORTERM='truecolor', SHELL='/bin/sh', RUST_BACKTRACE='1',
+ HARNESS_TUI_DESK='off', HARNESS_TUI_NOTIFY='off', HN_DESKTOP='off',
+ MOCK_WELCOME='1', MOCK_NEW_UI='1', MOCK_RECONNECT='1')
+OUTPUT = Path(os.environ['HN_WELCOME_OUTPUT']) if os.environ.get('HN_WELCOME_OUTPUT') else None
+if OUTPUT: OUTPUT.mkdir(parents=True, exist_ok=True)
+
+
+def hn(*args, ok=True):
+ result = subprocess.run([str(HN), '-L', PREFIX, '--port', str(PORT), '-f', '/dev/null', *args],
+ env=ENV, cwd=PROJECT, text=True, capture_output=True, timeout=12)
+ if ok: assert result.returncode == 0, (args, result.stdout, result.stderr)
+ return result.stdout.strip()
+
+
+def tmux(*args, ok=True):
+ result = subprocess.run([TMUX, '-L', PREFIX + '-outer', *args], env=ENV, cwd=PROJECT,
+ text=True, capture_output=True, timeout=10)
+ if ok: assert result.returncode == 0, (args, result.stderr)
+ return result.stdout
+
+
+def state(route='dial', update=None):
+ request = urllib.request.Request(f'http://127.0.0.1:{PORT}/test/{route}',
+ data=json.dumps(update).encode() if update is not None else None)
+ with urllib.request.urlopen(request, timeout=2) as response:
+ return json.load(response)['data']
+
+
+def screen(): return tmux('capture-pane', '-p', '-t', 'test')
+
+
+def wait(fn, description, seconds=10):
+ end = time.monotonic() + seconds
+ while time.monotonic() < end:
+ if fn(): return
+ time.sleep(.05)
+ raise AssertionError(description + '\n' + screen())
+
+
+def shows(text): wait(lambda: text in screen(), text)
+
+
+def keys(*args):
+ for key in args:
+ tmux('send-keys', '-t', 'test', key)
+ time.sleep(.06)
+
+
+def type_text(text): tmux('send-keys', '-l', '-t', 'test', text)
+
+
+def raw(text): tmux('send-keys', '-H', '-t', 'test', *[f'{b:02x}' for b in text.encode()])
+
+
+def paste(text): raw('\x1b[200~' + text + '\x1b[201~')
+
+
+def position(label):
+ lines = screen().splitlines()
+ width = int(tmux('display', '-p', '-t', 'test', '#{pane_width}').strip())
+ left = (width - min(60, max(0, width - 4))) // 2
+ for y, line in enumerate(lines[:-1]):
+ text = line[left:left+60]
+ if text[3:].startswith(label): return left + 3, y
+
+
+def click(label):
+ wait(lambda: position(label), label)
+ x, y = position(label)
+ raw(f'\x1b[<0;{x+1};{y+1}M\x1b[<0;{x+1};{y+1}m')
+ time.sleep(.12)
+
+
+def choose(label, query):
+ click(label)
+ type_text(query)
+ keys('Enter')
+
+
+def snapshot(name):
+ time.sleep(.15)
+ if OUTPUT:
+ (OUTPUT / (name + '.ansi')).write_text(tmux('capture-pane', '-p', '-e', '-t', 'test'))
+ (OUTPUT / (name + '.txt')).write_text(screen())
+
+
+def created(): return [p for p in state().get('created', []) if p['engine'] != 'terminal']
+def window(): return hn('display', '-p', '#{window_id}')
+def resize(width, height):
+ tmux('resize-window', '-t', 'test', '-x', str(width), '-y', str(height))
+ time.sleep(.2)
+ assert tmux('display', '-p', '-t', 'test', '#{pane_dead}').strip() == '0', screen()
+
+
+def launch():
+ command = shlex.join(['env', '-u', 'TMUX', '-u', 'TMUX_PANE', '-u', 'HN_SOCKET',
+ *[f'{k}={v}' for k, v in ENV.items()], str(HN), '-L', PREFIX,
+ '--port', str(PORT), '-f', '/dev/null'])
+ tmux('-f', '/dev/null', 'new-session', '-d', '-s', 'test', '-x', '150', '-y', '42', command)
+ tmux('set-window-option', '-t', 'test', 'remain-on-exit', 'on')
+
+
+mock = None
+started = False
+try:
+ with socket.socket() as probe: probe.bind(('127.0.0.1', PORT))
+ mock = subprocess.Popen(['node', str(ROOT / 'tests/mock-daemon.mjs'), str(PORT)], env=ENV,
+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
+ for _ in range(100):
+ assert mock.poll() is None
+ try: state(); break
+ except OSError: time.sleep(.05)
+ else: raise AssertionError('mock startup timeout')
+ launch()
+ started = True
+ shows('Welcome to Harness')
+ shows('Finding saved sessions')
+ snapshot('welcome-discovering')
+ anchor = position('Task')
+ first = window()
+ task = '1 fix café login\nKeep 界 and 🦀 intact.\nFrom a tmux buffer!.'
+ type_text('1 fix café login')
+ paste('\r\nKeep 界 and 🦀 intact.')
+ shows('Keep 界 and 🦀 intact.')
+ hn('set-buffer', '\nFrom a tmux buffer.')
+ keys('C-b', ']'); shows('From a tmux buffer.')
+ keys('C-b', 'C-b'); type_text('!'); shows('From a tmux buffer!.')
+ assert not created(), 'typing a digit or pasting must not launch/resume'
+ assert not state('reconnect')['inputs'], 'the backing shell never receives task text'
+ state('welcome', {'history': 'empty'})
+ keys('C-r'); shows('No recent sessions')
+ assert position('Task') == anchor
+ snapshot('welcome-first-task')
+ state('welcome', {'history': 'ready'})
+ keys('C-r'); shows('Continue NFC device chat')
+ assert position('Task') == anchor, 'late history must not move the form'
+ assert not created()
+ snapshot('welcome-existing-history')
+ print('PASS welcome: fresh history loading/empty/found, immediate typing, paste and no input leak', flush=True)
+
+ # The default agent must work without opening a chooser. In particular, a form
+ # created before the connection arrives must acquire its Git state automatically.
+ shows('Start OpenCode')
+ assert 'Could not read Git' not in screen(), screen()
+ state('welcome', {'delay': 1200})
+ keys('Enter', 'Enter')
+ shows('Starting')
+ snapshot('welcome-starting')
+ keys('C-b', 'c'); shows('New Window')
+ second = window()
+ assert second != first
+ type_text('second window draft')
+ shows('second window draft')
+ wait(lambda: len(created()) == 1, 'one launch')
+ wait(lambda: hn('display', '-p', '-t', first, '#{window_name}') == 'Mock opencode', 'launch delivered to its original window')
+ assert created()[0]['prompt'] == task, created()
+ assert created()[0]['engine'] == 'opencode', created()
+ assert window() == second, 'a late launch must not steal the current window'
+ assert hn('display', '-p', '-t', first, '#{window_panes}') == '1'
+ assert not state('reconnect')['inputs']
+ keys('C-b', 'l'); shows('Mock opencode (mock)')
+ keys('C-b', 'l'); shows('second window draft')
+ snapshot('new-window-draft')
+ print('PASS welcome: immediate first task, duplicate prevention, delayed placement and independent drafts', flush=True)
+
+ keys('C-b', 'N'); shows('New Harness')
+ type_text('a separate modal task')
+ shows('a separate modal task'); snapshot('new-harness-immediate-task')
+ keys('Escape'); shows('second window draft')
+ assert 'a separate modal task' not in screen()
+ # A plain-key prefix and plain root binding both belong to the task editor here.
+ hn('set', '-g', 'prefix', '`')
+ hn('bind', '-n', 'x', 'rename-window', 'wrong-binding')
+ type_text(' ` x'); shows('second window draft ` x')
+ assert hn('display', '-p', '#{window_name}') != 'wrong-binding'
+ keys('Tab', '`', 'c')
+ wait(lambda: window() != second, 'plain prefix navigates after tabbing out of the task')
+ wait(lambda: hn('display', '-p', '#{window_panes}') == '1', 'temporary welcome backing shell')
+ hn('kill-window')
+ shows('second window draft ` x')
+ hn('set', '-g', 'prefix', 'C-b'); hn('unbind', '-n', 'x')
+ choose('Agent', 'codex'); click('Task')
+ resize(80, 24)
+ for text in ('Task', 'Agent', 'Project', 'Branch', 'Worktree', 'Model', 'Approvals', 'Profile', 'Start Codex', 'Open Terminal', 'Browse All Sessions'):
+ shows(text)
+ snapshot('new-window-80x24')
+ click('Project'); shows('Search projects'); snapshot('new-window-picker-narrow')
+ keys('Escape', 'Escape'); shows('second window draft')
+ for width, height in [(45, 14), (22, 5), (1, 1), (150, 42)]: resize(width, height)
+ shows('second window draft')
+ anchor = position('Task')
+ click('Project'); shows('Search projects')
+ assert position('Task') == anchor
+ snapshot('new-window-picker-right')
+ keys('Escape', 'Escape')
+ raw('\x1b]10;rgb:2020/2020/2020\x1b\\\x1b]11;rgb:ffff/ffff/ffff\x1b\\')
+ snapshot('new-window-light')
+ print('PASS welcome: modal separation, keyboard ownership, wide/narrow/light rendering and resize', flush=True)
+
+ state('welcome', {'history': 'failed', 'delay': 0}); keys('C-r')
+ shows('Some history is unavailable')
+ snapshot('welcome-history-unavailable')
+ state('welcome', {'history': 'ready'}); keys('C-r')
+ shows('Recent sessions')
+ click('Browse All Sessions'); shows('Search harnesses')
+ keys('Escape'); shows('second window draft')
+ count = len(created())
+ click('Continue NFC device chat')
+ shows('Continue NFC device chat (mock)')
+ assert len(created()) == count + 1
+ resumed = created()[-1]
+ assert resumed['resumeSessionId'] == 'ext-codex-nfc' and 'prompt' not in resumed
+ assert window() == second
+ keys('C-b', 'c'); shows('New Window')
+ third = window()
+ click('Open Terminal'); shows('Mock terminal (mock)')
+ assert window() == third
+ assert len(created()) == count + 1, 'Open Terminal never launches the selected coding agent'
+ # Replacing the backing shell may delete one already. Closing the opened terminal
+ # must also end its shell, exactly as closing a tmux window does.
+ deleted = len(state().get('deleted', []))
+ hn('kill-window')
+ wait(lambda: len(state().get('deleted', [])) > deleted, 'closing Open Terminal ends its shell')
+ keys('C-b', 'c'); shows('New Window')
+ type_text('Keep this task away from the terminal')
+ choose('Agent', 'Terminal'); shows('Mock terminal (mock)')
+ assert len(created()) == count + 1, 'the Terminal picker action never starts a coding agent'
+ assert not state('reconnect')['inputs'], 'the Terminal picker action never sends the task'
+ keys('C-b', 'N'); shows('a separate modal task')
+ keys('Escape'); hn('kill-window')
+ print('PASS welcome: discovery recovery, browse all, existing-session resume and explicit terminal', flush=True)
+
+ # A new user can arrive without the daemon. Keep the task, explain how to connect,
+ # and let Open Terminal use a real local PTY without executing any draft text.
+ hn('kill-server', ok=False)
+ tmux('kill-server')
+ mock.terminate(); mock.wait(timeout=5); mock = None
+ offline = BASE / 'offline'
+ offline.mkdir()
+ ENV.update(HOME=str(offline), HN_TMPDIR=str(offline))
+ launch()
+ shows('Welcome to Harness')
+ shows('Run `harness start` to connect agents.')
+ type_text('Preserve this offline task')
+ keys('Enter')
+ shows('task stays here.')
+ shows('Preserve this offline task')
+ snapshot('welcome-offline')
+ click('Open Terminal')
+ wait(lambda: 'Welcome to Harness' not in screen(), 'local terminal opened')
+ assert 'Preserve this offline task' not in hn('capture-pane', '-p'), 'draft leaked into the local shell'
+ type_text("printf 'HN_OFFLINE_TERMINAL_%s\\n' OK")
+ keys('Enter'); shows('HN_OFFLINE_TERMINAL_OK')
+ print('PASS welcome: daemon unavailable, preserved task and real local terminal', flush=True)
+finally:
+ try:
+ if started:
+ hn('kill-server', ok=False)
+ tmux('kill-server', ok=False)
+ rows = subprocess.check_output(['ps', '-ax', '-o', 'pid=,command='], text=True).splitlines()
+ owned = [int(parts[0]) for row in rows if len(parts := row.strip().split(None, 1)) == 2
+ and parts[1].startswith(str(HN) + ' ') and f'-L {PREFIX} ' in parts[1]]
+ for pid in owned:
+ try: os.kill(pid, 15)
+ except ProcessLookupError: pass
+ finally:
+ if mock:
+ mock.terminate()
+ try: mock.wait(timeout=5)
+ except subprocess.TimeoutExpired: mock.kill(); mock.wait()
+ shutil.rmtree(BASE, ignore_errors=True)