Skip to content

fix(layout-owner): window tabs that launch an agent or carry a draft start through main - #51934

Merged
Jinwoo-H merged 32 commits into
layout-owner-v2from
layout-owner-launch-drafts-through-main
Nov 29, 2026
Merged

Jinwoo-H merged 32 commits into
layout-owner-v2from
layout-owner-launch-drafts-through-main

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

On the layout-owner path, main is supposed to start every terminal. A new tab you open in a window that launches an agent, or that carries a draft prompt for the agent, still started its own terminal from the window. Now main starts those too, the same way it already starts plain new tabs.

Files Added Deleted Net
Test 22 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3957 $\color{#cf222e}{\Huge{\mathbf{−}}}$​24 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3933
Prod 89 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2407 $\color{#cf222e}{\Huge{\mathbf{−}}}$​647 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1760

Before / after (layout-owner path only)

  • Before: a new window tab started in main only for a plain shell or command. If its startup had an agent launch request, a draft prompt, session options, OpenCode model options, an initial agent status or "agent started" telemetry, the window's pane spawned the terminal itself.
  • After: main starts all of these. The only tabs that still start from the window are a sidebar resume of a saved agent session (it needs main to publish the "session restored" outcome first; ledger L251). SSH and WSL tabs are unchanged.

The switch-off path is unchanged.

Mechanism

  • Agent launch: the pane's agent-launch steps (tracking, closed-pane refusal, intent resolution, one verdict to the window) move unchanged out of pty:spawn into src/main/agent-launch/pane-agent-launch-lifecycle.ts. pty:spawn and main's window-tab start (terminal.create with windowTab) both use it, so there is one implementation.
  • Create inputs: terminal.create (window-tab branch only, local desktop caller only) gains optional telemetry, agentLaunch, the OpenCode model start fields and draftPaste (window-tab-start-params.ts). A bad value is dropped, never refused. window-tab-start-inputs.ts turns them into main's create options.
  • Drafts: for an agent that only takes a draft after it is ready, main pastes it with the existing startup-draft paste custody. The window no longer arms its own paste for that pane, and the workspace-create delayed delivery for the same launch token is fenced, so the draft is pasted exactly once. If main's paste never lands, main tells the window (ui:startupDraftNotPasted) and the window shows the existing "wasn't sent" notice.
  • One call for a new tab: a tab main starts is written and started by one terminal.create {windowTab} that carries the window's createTerminalTab. Main writes the tab as the first step of the pane's start, inside the per-pane start gate, so another window or a phone never finds the tab recorded but unstarted (they join the start instead of starting it without its --model or startup). The window keeps its drawn tab held until the reply's frame, as for layout.apply. A refusal ({refused}) closes the tab; a failed start ({startFailure}) shows on the pane; host_not_owned answers as layout.apply would (a twin's start goes to the window, a local refusal closes the tab). The tab's startup and first cwd are published with the tab in createTab, so the one call carries them; nothing is queued after it.
  • Who starts the tab (owner latch): when the window draws a tab main should start, it records the pane as asking before the pane mounts. Main's answer settles it once: main (main took the start, or may have run it) or window (host_not_owned: main ran nothing). The pane's connect waits while asking. The startup stays in the window's store until main takes it, so on window the waiting pane runs its own start with the startup it captured, including its draft paste, with no remount (pane-start-owner.ts).
  • Attach, never start (pty:attachPane): a pane main starts sends one new IPC call built only from {worktreeId, tabId, leafId, cols, rows, initiallyHidden}; main refuses one naming anything else. Main waits for the pane's in-flight start, then attaches the view to its terminal, or answers a typed state: sleeping, held, failed, exited, unstarted, unknown. None of these is an error, so none shows a toast or triggers remount recovery. The window's own start code is never reached for such a pane (fresh-spawn-start.ts refuses it as a backstop).
  • One starter per pane in main: main's window-tab start runs under the same per-pane gate as restore, wake and restart (PaneStarter.startWith), registered before its first await. A window tab's start is spent once the terminal it ran ends on its own (main's existing exit verdict: no close, kill, sleep, Restart or daemon replacement), while no later terminal holds the pane and the pane keeps no resume record; a failed start is spent too. A spent start is never run again by a view, a phone or a wake; Restart (a layout command that ruled on it) or a resume record starts it. Because the fact belongs to the terminal, not the pane, sleeping, restarting or replacing the terminal makes it lapse on its own; no lifecycle path has to clear a flag.
  • Main publishes the start, not window memory: main publishes 'starting' on the pane the moment its starter takes a start (before any await), and clears it when the start ends. It also publishes the launch's initial agent status on the pane, tied to the terminal id like the resume outcome. A reloaded window has no owner latch, so it learns both from main's published layout: it waits on 'starting' instead of starting a shell, and re-seeds the agent status on attach.
  • Restart through main: Restart on a main-started pane (account switch, a died agent's Restart, even after its transport dropped the terminal id) sends restartPane. Main stops the old terminal and starts the pane again through the same per-pane starter as a new start; the pane then attaches. A daemon restart forgets the pane's consumed start too, so main's startPane starts it again.
  • runtime-window-lifecycle.ts was at the 300-line cap, so the agent-launch notifier entries moved next to their relay (agentLaunchWindowNotices).

How it was tested

  • New switch-on e2e tests/layout-owner-e2e/window-tab-agent-starts-in-main.spec.ts (added to the window shard of the lane). After the first terminal is up it records every terminal the window's own pty:spawn starts (calls that only attach to a live terminal don't count), then opens a Codex tab from the tab bar's + menu and a launch-draft tab with the startup a workspace's first agent terminal carries. A fake agent logs each start with its pane and size, every resize and all input. It checks:
    • each tab starts exactly one agent, and the window started none of them;
    • the draft is pasted exactly once;
    • the agent saw no resize (the first size main gave it was the pane's);
    • after a graceful relaunch both panes rebind to the same terminals, with no second start and no second paste.
  • Passes 2/2 locally (--repeat-each=2). Without the fix it fails: the window starts both terminals itself.
  • Second e2e in the same file: an agent launch request, the OpenCode model start (argv carries the model), the initial status seed, an unreadable launch (typed refusal, no raw toast, nothing started), a draft whose agent exits before ready (main sends ui:startupDraftNotPasted), and a host_not_owned give-back (the window starts that tab itself, once). The status assertion fails if the reattach-path seed is removed.
  • Third e2e: a command that exits before its view attaches (its tab stays open, as when the window ran it; nothing starts it again after reveal and a remount), the OpenCode model start and a status tab remounted during main's start, and a slow host_not_owned remounted while the window is still asking (one window start, one paste, no remount of its own).
  • Fourth e2e (round 3): an account-switch restart starts the agent again once, in main; a create main refuses closes the tab with nothing started; a window reload while main is still planning an OpenCode model start gets exactly one start with the model and no window spawn, and the reloaded window shows the status tab's initial status from main; a daemon restart leaves the pane on a working terminal (echo round-trip). With the daemon-restart fix reverted, that last step fails (the pane stays blank). Locally the account-restart step needs ORCA_DAEMON_MAX_HOST_TERMINALS raised when the machine is near the shared 256-terminal cap; CI is not.
  • Round 4: the test writer's test(layout-owner): adversarial unit and e2e tests against PR #51934 #52167 is merged (unit: attach states, the consumed starter, the died-pane Restart, the refused create; e2e: lifecycle, and two windows plus a phone on one workspace, an exited tab opened from the phone, and a phone opening the tab while its create is in flight). All pass with the switch on, along with the default-tabs crash, layout oracle, pane close, cold activation, stream-loss and latency-budget specs.
  • Lane-wide oracle: every switch-on spec now fails if its window starts a terminal (a pty:spawn that is not an attach) in a pane main accepted a window-tab start for, in either order (helpers/main-started-pane-spawn-oracle.ts, checked at app close). With the latch and attach disabled it fails the first spec.
  • Unit: attachPaneView (attach only, exited when the terminal died while the view registered, every miss state, close and owner-change races as states, refusal of a request naming a start input); the per-pane starter ('starting' published before the start settles, startWith joins, settled, consumed, forget clears consumed), the consumed startPane rule (fails if the rule is removed), the one-way latch, the attach allow-list, and startWindowTabWithInputs verdicts (not-started vs unconfirmed around the provider spawn, plan and create failures, exit during start, closed pane).
  • pnpm tc:node, pnpm tc:web, oxlint and oxfmt clean on changed files.
  • Unit suite in both modes: switch-on failures are only the listed known rows (A5 browser team policy, B1 slept-agent wake); the 4 switch-off failures were load flakes and pass when rerun alone.

Census rows

No census row is directly fixed. This is plan item (b) (L299, L252). L308 belongs to #51731, L314 is fixed by #51734, and L312/L313 need the SSH Docker and paired lanes; this PR doesn't claim them.

Visible changes

None intended. On the layout-owner path only:

  • an agent or draft tab's terminal starts at main's size for the pane; the e2e saw no resize;
  • when main's draft paste fails, the "wasn't sent" notice comes from main's paste result instead of the pane's own timer;
  • bug fix: a main-started command that exits before its view attaches now keeps its tab open on macOS, as the window's own start does (round 2 closed it on macOS).

Review fixes

  • Round 2, start seam (replaces round 1's fences): the window's starting mark, the startup hand-off and give-back remount, main-started-pane-view.ts, windowSpawnFencedByMainStart, mainPaneStartHandedBack and the attach-only pty:spawn for these panes are gone; the owner latch, pty:attachPane and the per-pane starter above replace them. This fixes the attach-only connect looping on terminal_pane_not_live, the give-back's spurious connect, and the OpenCode branch being reachable.

  • Round 2, typed outcomes: main's create asks the launch what a failed pane shows before either failure writer publishes, so every failure path publishes exactly one typed outcome (agent_session_exited_during_start included) and a pane the user closed publishes none.

  • Round 2: main-started view facts are dropped when a create fails or the tab closes; main's draft cap counts sanitised UTF-8 bytes.

  • Typed launch refusals: a refused agent launch now leaves the launch's typed refusal on the pane, so the window shows its launch notice, not a raw "could not start" toast. An agent that exits during start keeps its start-failure detail.

  • Dispatch point: the launch counts as dispatched only right before the provider spawn (a new create hook), as pty:spawn does. A failure before that point now reports "not started".

  • Draft paste: main's paste now uses the window's draft-paste framing (ESC neutralised, CR line endings, 16 KiB chunks, 16 MiB cap). The chunker moved unchanged to shared/terminal/input/agent-draft-paste-chunks.ts.

  • terminal-paste: the guard is restored; such startups keep the window's spawn.

  • Round 5b, waking during a sleep (on main too): main finishes a sleep before the window commits it, so opening the workspace or one of its tabs in that gap saw terminals that were still listed and woke nothing. Now:

    • the window remounts the tabs when the sleep ends on a workspace that was already reopened;
    • attach answers sleeping for a pane main keeps a resume record for;
    • a phone open waits for a sleep that is still running, then trusts main's resume record over the window's stale ready.

    The same gap exists on main (the window's late commit and the phone's ready gate are unchanged there). A new e2e covers an Agent Sleep woken by a terminal send to its handle.

  • Round 5: the start's spent fact moved from a pane flag to the terminal it ran (fixes wake, mailbox/CLI wake, phone open of slept tabs and held Reopen); the terminal bridge and the initial-terminal seeding pass their startup and cwd into createTab; host_not_owned answers in one call; a held pane's Reopen asks main to start it; the window lane runs the two new specs.

  • Round 4: the create/start gap is removed at the root (one call, design step 6) instead of patched; ensureStarted refuses a consumed pane; a died pane's Restart reaches restartPane.

  • Round 3: in-place restart and daemon restart go through main's starter (above); 'starting' is published at receipt, so a reload during agent-launch planning no longer spawns a shell; a refused create only closes the tab (it used to start the window's spawn first); an attach whose binding is already present attaches at once; 'held' shows the newer-daemon Reopen card; attachPaneView answers close and owner-change races and an exited registration as states; main notes the spawn commit before the binding save, and the window counts main's first start as its fresh spawn, so the exited tab stays open; the launch status is published per terminal instead of a window-memory map that was never cleared.

Still started by the window

  • A sidebar resume of a saved agent session (resumeSource / showSessionRestoredBanner), until main publishes its restored outcome (L251).
  • SSH and WSL tabs, as before.

launchDraft view field

This PR does not give main a draft record for the native chat composer (nativeChatLaunchDraftByTabId), so the temporary launchDraft view field must stay for now. Main only pastes the terminal startup draft.

Performance

None, because the change only moves where an existing start runs: one terminal.create call (which now also writes the tab, replacing the separate layout.apply) plus one pty:attachPane replace the pane's pty:spawn for these tabs, with the same planning and paste code. No new polling, timers or per-frame work; the owner latch is capped at 256 entries, and main's published launch status is dropped with its terminal.

@greptile-apps

greptile-apps Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Confidence Score: 4/5 · The PR should wait until commands that exit before attachment show their saved output instead of a blank pane.RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The change reaches main’s local terminal starts and the window and phone views that attach to them.

The PR should wait until commands that exit before attachment show their saved output instead of a blank pane.

Findings

  1. P1 Short commands lose their output ▶
  2. P2 Failed draft writes stay silent ▶
  3. P2 Drafts gain broken characters ▶
  4. P2 Background test shows the tab ▶

Summary

Moves eligible window-tab starts into main and gives their views an attach-only path.

  • Main starts eligible new local tabs with their startup inputs.
  • Pane views attach to main’s terminal without starting another one.
  • Main coordinates window-tab starts with pane recovery and status updates.

Reviews (20) · Last reviewed commit: "fix(layout-owner): a frame binds a layou..." · Reviewed by Greptile

Comment on lines +68 to +70
for (const chunk of iterateAgentDraftPasteContentChunks(draft.content)) {
host.readiness.write(target.ptyId, chunk, 'launch')
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Failed draft writes stay silent

The new loop ignores whether each chunk was accepted. writePtyFromRuntimeController returns false when the provider is unavailable or refuses a write, rather than throwing. The loop therefore finishes without calling onNotPasted, so the user can lose their draft without a notice. Preserve the write result, stop on refusal, and notify the window.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

… outcome, none for a closed pane

Main's create asks the launch what a failed pane shows before either failure writer
publishes, so no raw start failure reaches the window first. Exited-during-start
shows the launch refusal, as the pane's own spawn does. Main-started view facts are
dropped on a failed create and when the tab closes. The draft cap counts sanitised
UTF-8 bytes.
Comment on lines +36 to +41
if (chunk && chunkBytes + characterBytes > safeMaxChunkBytes) {
yield chunk
chunk = sanitized
chunkBytes = characterBytes
continue
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Drafts gain broken characters

Main now chunks every startup draft. When an emoji crosses the 16 KiB boundary, this branch adds the whole character, then takes continue before skipping its second string unit. The next pass adds that unit again, corrupting the text sent to the agent. For example, 16,383 ASCII characters followed by an emoji triggers this. These small drafts previously used the window's direct paste without chunking.

Advance past both string units before continuing.

Suggested change
if (chunk && chunkBytes + characterBytes > safeMaxChunkBytes) {
yield chunk
chunk = sanitized
chunkBytes = characterBytes
continue
}
if (chunk && chunkBytes + characterBytes > safeMaxChunkBytes) {
yield chunk
chunk = sanitized
chunkBytes = characterBytes
if (codeUnitLength === 2) {
index += 1
}
continue
}

…r per pane in main

The window asks main once who starts a new tab's first terminal (asking, then main or
window) before the pane connects. A pane main starts sends pty:attachPane, built from
an allow-list, which awaits main's in-flight start and answers a typed state instead of
an error, so it never starts a terminal or feeds remount recovery. Main runs the window
tab's start under the same per-pane gate as every other start and marks it consumed, so
a later startPane never re-runs it from tab facts. Main hands the launch's view facts
back with the attach. The window's starting mark, startup hand-off and give-back
remount, and the main-started view map are gone.
…owner

A lane-wide oracle fails any switch-on spec whose window starts a terminal in a pane
main started. The window-tab spec adds a command that exits before its view, remounts
during main's start, and a slow decline remounted while the window is still asking.
Unit tests pin the per-pane starter, the consumed startPane rule, the one-way owner
latch and the attach request's allow-list.
return page.evaluate(
({ id, opts, show }) => {
const state = window.__store!.getState()
const tab = state.createTab(id, undefined, undefined, opts)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Background test shows the tab

openTab(..., { background: true }) still activates the tab because createTab activates it by default. Skipping the later setActiveTab call does not keep the pane hidden. The exit-before-view test can therefore attach before the agent exits and pass without covering the race it claims to test. Pass activate: false to createTab for background tabs.

…er-launch-drafts-through-main

# Conflicts:
#	.github/workflows/layout-owner-switch-on.yml
…tabs crash spec

Main now starts default tabs that carry startup fields, through the window's
terminal.create, so stalling only pty:spawn no longer keeps every terminal from
starting before the crash. The exited-before-view case no longer assumes the tab
closes: it stayed open on Linux and closed on macOS.
…emon restart and reload

- Restart (account switch, died-pane Restart) of a main-started pane goes through main's
  restartPane: main stops the terminal and starts the pane again through the same starter.
- A daemon restart forgets the consumed start, so main's startPane runs again.
- Main publishes 'starting' when it takes a start, and the launch status per terminal, so a
  reloaded window waits on main and re-seeds the agent status instead of starting a shell.
- A refused create only closes the tab.
- Attach replies: closed/owner-changed races map to states, an exited registration is 'exited',
  'held' shows the newer-daemon card; an already-present binding is attached at once.
- An exited-before-view tab stays open: main notes the spawn commit before the binding save,
  and the window treats main's first start as its fresh spawn.
…umed start stays consumed

- One-call tab create (design step 6): the window's terminal.create carries its createTerminalTab;
  main writes the tab as the first step of the pane's start, under the start gate. No window or
  phone finds the tab recorded but unstarted, so none starts it without its --model or startup.
  A refusal or failed start answers with the call's frame; host_not_owned still records the tab
  alone and the window starts it, as before.
- PaneStarter.ensureStarted refuses a consumed pane instead of clearing it: a phone opening an
  exited main-started tab no longer runs its command again. A stop (forget) or a layout command's
  start (byLayoutCommand: startPane with a resume record, wake, restartPane) still starts it.
- A died pane's Restart reaches main's restartPane: the connect is marked as a restart, since the
  exited transport no longer names its terminal.
- Tests from #52167 merged; refusal stubs follow the one call, my spec imports the shared harness.
…al ends on its own

- Replace the pane-level 'consumed' flag with a fact about the start's terminal: a window-tab
  start is spent once the terminal it ran ends on its own (main's existing ended-on-its-own exit
  verdict), no later terminal holds the pane, and the pane keeps no resume record. Sleep, Restart,
  a daemon replacing the terminal and a held pane are not that, so wake, mailbox/CLI wake, a phone
  opening a slept tab and held Reopen start again with no forget call; the daemon-restart forget
  is gone. A failed start stays spent; a refused tab records nothing.
- createTab publishes the first terminal's cwd with the tab, and the terminal bridge passes its
  startup command into createTab, so the one-call create carries both (nothing is queued after).
- host_not_owned from the one call answers as layout.apply would (a twin's start goes to the
  window, a local refusal closes the tab), with no second layout.apply.
- A held pane's Reopen asks main to start it, then attaches.
- The switch-on window lane runs the two new window-tab specs.
…ep, reopen held, survive restarts and keep their inputs

- Slept window agent and draft tabs wake once, through main, from the sidebar and from a phone.
- A held window tab's Reopen after a newer terminal service gets a live terminal from main.
- A daemon restart after the tab was viewed, opened on a phone and reloaded gives it a live terminal.
- A repeated one-call create runs nothing new and leaves the pane startable.
- ui:createTerminal's startup command and a subfolder project's first terminal run in the right cwd.
- The spawn oracle no longer counts a refused or reattached one-call create as a main start.
…ll settling wakes its slept tabs

Main finishes a sleep before the window commits it. Opening the workspace or one of its tabs in that gap saw
terminals that were still listed, so nothing woke the slept tabs:
- the window remounts the tabs when the sleep ends on a workspace that was already reopened
- attach answers `sleeping` for a pane main keeps a resume record for, so the view asks main to wake it
- a phone open waits for a sleep that is still running, then trusts main's resume record over the window's stale `ready`

Also adds an e2e for an Agent Sleep woken by a terminal send to its handle.
…er-launch-drafts-through-main

# Conflicts:
#	src/renderer/src/runtime/workspace-layout/commands/layout-apply-send.ts
Comment on lines +43 to +45
case 'exited':
// Main's start ran and its terminal is gone; nothing runs it again but a user act.
break

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Short commands lose their output

When a command exits before its pane connects, main answers exited, and this branch does nothing. connectMainStartedPane returns before handleReattachResult, so the pane never receives the command's saved output. No later attach is scheduled. A short command can therefore leave an empty tab instead of showing its result or error.

Restore the ended terminal's output without running its startup again.

…er-launch-drafts-through-main

# Conflicts:
#	.github/workflows/layout-owner-switch-on.yml
…er-launch-drafts-through-main

# Conflicts:
#	src/renderer/src/runtime/workspace-layout/commands/layout-apply-send.ts
#	src/renderer/src/store/terminals/tabs/creation/terminal-tab-create-through-layout-owner.ts
…er-launch-drafts-through-main

# Conflicts:
#	tests/layout-owner-e2e/helpers/orca-restart.ts
@Jinwoo-H
Jinwoo-H merged commit 98eb61e into layout-owner-v2 Nov 29, 2026
81 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant