Repository navigation
fix(terminal): keep keys typed while an agent tab connects, in order - #43787
brennanb2025 wants to merge 5 commits into
Conversation
…later typing When Orca's zsh wrapper runs the launch, the daemon reports it in the spawn result and the renderer writes a short pre-connect draft to the PTY at bind, so typing that spans the connect reaches the agent in order. Longer drafts, launch-time prompts and typed launches keep the existing paste-when-ready path, and the daemon's typed fallback clears the line before the launch.
Perf scan: #43787 (head
|
…aunch itself When the shell wrapper never claims the launch, the daemon types it with an erase prefix that also wipes keys the renderer sent at bind. The daemon now reports that typed launch per incarnation; main tracks and forwards it, and the pane re-runs its paste-or-notice path with the keys it sent. The prefix becomes Ctrl-E then Ctrl-U so it clears the whole line in more shells.
Perf scan — #43787 @
|
| # | Work | Trigger / rate | Owner · thread | Work per event | Bound / cleanup |
|---|---|---|---|---|---|
| 1 | Daemon types the fallback launch with a \x05\x15 prefix, then calls fallback.onTyped() → markSessionStartupLaunchTyped (session-shell-ready-barrier.ts:214-219, session-input-path.ts:48) |
Only on the onShellReadyTimeout path, after the claim proves the wrapper never ran. startupCommandFallback is nulled before the claim, so it runs at most once per session incarnation |
daemon · per Session | 1 WeakMap-keyed lookup, 1 bool write, 1 viewer callback | Once per incarnation. The path is keyed by Session, so it goes away with the session |
| 2 | startupLaunchTyped stream event (daemon-terminal-admission.ts:200-213) |
Same as #1. Sent only when a viewer is attached | daemon → main socket | 1 control event plus 1 flush(clientId). This is the same shape as the existing inputClosed |
≤1 per incarnation per attached client |
| 3 | isSessionStartupLaunchTyped on reattach/create results (terminal-host-session-create.ts:84, -publish.ts:265 shellWrapperLaunch) |
Per createOrAttach | daemon | 1 map lookup. 1 optional field on the reply | Constant |
| 4 | DaemonPtyIncarnationFlags (daemon-pty-incarnation-flags.ts): a second per-session Map<sessionId, Set<incarnationId>> that sits next to inputClosed |
record per event (#2). sync per spawn reply, now 2 flags × O(1) |
Electron main · adapter singleton | O(1) Map/Set ops | sync collapses each set to ≤1 live incarnation. delete(sessionId) runs in the same teardown as activeSessionIds.delete (daemon-pty-runtime-state.ts:185). record() returns false on a duplicate, so main never re-emits the same fact |
| 5 | Main forwards the fact → pty:startupLaunchTyped (daemon-pty-event-subscriptions.ts:52-66, bind-listeners.ts:75-81) |
Only when #4 record() is new |
Electron main | 1 emit over the existing backgroundStreamListeners, then 1 webContents.send with {id, incarnationId} |
≤1 per incarnation |
| 6 | Hot write path write/writeWithSettlement/prepareWrite (daemon-pty-session-input.ts) |
Per keystroke / PTY write | Electron main | Unchanged: the isClosed → inputClosed.has rename adds one property hop. startupLaunchTyped is not consulted on the write path |
Constant |
| 7 | Renderer pre-handler buffer preHandlerLaunchTyped (pty-pre-handler-buffer.ts:189-205) |
A fact that arrives with no watcher. This is the common case for timed-out launches with no typed-ahead keys | renderer · module singleton | 1 Map set + sequence increment | Capped at PRE_HANDLER_PTY_EXIT_MAX_PTYS = 64 by evictOldestPtyIfAtCap. Cleared by take on watch, the prior-incarnation fence in ipc-pty-connect.ts:123, clearPreHandlerPtyState on exit/shutdown, and the discarded-state gate. Worst case is 64 tiny {incarnationId, sequence} entries, which stays the same at 10× fleet |
| 8 | Watcher registry launchTypedWatchers (pty-startup-launch-typed.ts) |
One registration per bind that sent held keys (fresh spawn + wrapper launch + non-empty draft ≤512 B) | renderer · module singleton, ≤1 entry per PTY | Map get/set. The closure keeps text (≤512 B) and the pane session |
Removed when the fact fires, by forgetPtyLaunchTyped on every exit (pty-dispatcher.ts:192), by discardAgentPreReadyDraft on pane dispose() (pane-pty-binding.ts:180), and on rebind to a different PTY (forgetSentAtBind). When the wrapper claims the launch (the success path), the entry stays until exit or dispose. That is ≤1 entry per live PTY, with no growth over time or history |
| 9 | encoder.encode(draft).byteLength budget check (agent-pre-ready-typed-draft.ts:152) |
Once per bind while capturing | renderer | O(draft bytes) once | One-time per bind. It does not run per keystroke |
| 10 | onPtySpawn / cold-restore bind carry shellWrapperLaunch + incarnationId (ipc-pty-connect.ts, fresh-spawn-start.ts, active-pane-pty-binding.ts) |
Per spawn / bind | renderer | 2 field writes | Constant |
Subscription / publication census
- New IPC channel
pty:startupLaunchTyped. It has 1ipcRenderer.onlistener per renderer window, installed once inattachPtySecondaryPushListenersnext toonWriteUnavailable, with its unsubscribe pushed onto the same list. Dispatch is oneMap.get(id)over a registry with ≤1 entry per PTY. It does not fan out per pane. - Main: no new listener. The event rides the existing single
onBackgroundStreamsubscriber inbindProviderListenersas a newkindbranch.liveRendererContents()is a pure extraction of the existing destroyed-window guard. - Daemon: no new subscription. It adds the optional
onStartupLaunchTypedcallback to the existing per-viewer stream client. - Send rates. Idle: 0/s, because no timer, poll or cadence was added. Under load: ≤1 event per new PTY incarnation whose shell-ready barrier timed out and whose fallback claim won. That is bounded by the terminal spawn rate, not by fleet size. At the reference fleet (a few hundred terminals, 100+ agents), a mass restore of N agents sends at most N events in total, each O(1) on main and renderer. Hook-status, PTY-chunk and keystroke rates have no effect on it.
Regression classes touched
| Class | Disposition |
|---|---|
| Per-entity state outlives the entity | Matched, disproved. The main flag map is deleted in the same teardown as activeSessionIds. The renderer pre-handler map is capped at 64 and cleared on exit, shutdown and the fence. The watcher map is cleared on fire, exit, dispose and rebind (#4, #7, #8) |
| Update published when nothing changed | Matched, disproved. record() dedups by incarnation before main emits. The daemon source fires at most once because startupCommandFallback is nulled before the claim |
| Hot-path rescans | Matched, disproved. The only scan is the one-time TextEncoder pass over a draft of ≤ budget size per bind. Nothing was added per chunk or per keystroke |
| Sync fs/SQLite on Electron main | No matching code. The claim file read stays in the daemon, as before |
| Fixed-cadence poll / subprocess per item / unbounded fan-out / eager imports | No matching code. There is no new timer, no spawn and no Promise.all. The only new import is a local module |
Six questions
- Unused work before the skip gate. Reviewed. Main emits only after
record()returns new. The renderer buffers a 2-field record only when no watcher exists. Nothing is serialized or parsed beyond{id, incarnationId}. - Ownership multiplication. Reviewed. There is one IPC listener per window and one main subscriber. Per-PTY state is ≤1 entry and does not multiply per pane or per mount.
- Thread / storage. Reviewed. All new work on main and the renderer is O(1) Map work with no sync I/O. The daemon writes one launch line, which it already wrote before this change; the change only adds 2 bytes.
- Growth / progress. Reviewed. Nothing scales with worktrees, history or uptime. The buffer is capped, and each watcher is one-shot.
- Execution host. Reviewed by code only. The event is produced by the local daemon terminal host. SSH and relay providers do not emit it, so they add no cost; whether they need the event is a correctness question, not a perf one. Windows, WSL and Linux follow the same barrier path with no host-specific probes. I did not verify this on those hosts.
- Obsolete work stops. Reviewed. Pane dispose and rebind drop the watcher. A late fact for a disposed or rebound pane is rejected by
session.disposed || getPtyId() !== ptyIdbeforedeliverAfterAgentReady. Exit drops the watcher (incarnation-fenced) and pre-handler state. A late fact for a discarded PTY is not buffered (discardedPreHandlerPtyStatesgate).
Paths examined: daemon barrier/session-input-path/terminal-admission/host create+publish; main adapter incarnation flags, spawn-result sync, event subscriptions, bind-listeners; preload bridge; renderer dispatcher, pre-handler buffer, launch-typed registry, typed-draft bind, connect/fresh-spawn/active-pane binding. Host: macOS code reading only.
Residual gaps: no runtime evidence (no builds/benchmarks per reviewer constraint); Windows/WSL/Linux and SSH-relay behaviour not exercised.
…don't resend keys after an early typed launch The daemon's create-or-attach reply dropped shellWrapperLaunch, so the renderer never took the bind-time path. A launch the host typed before the pane bound now keeps the held keys on the paste-when-ready path instead of writing them raw and pasting them again, and a typed-launch fact first learned from an attach reply is forwarded like the stream event.
Perf scan — #43787 @ 4aa8805 (stacked on #43698)Range: Findings: none. Every piece of new work runs at most once per spawn or attach, on paths that already do far more. Nothing runs per keystroke, per PTY chunk or per status update, and nothing scales with the fleet. Work added (trigger → owner/thread → work × consumers → bound)
Subscription / publication census
Retention / teardown (Q6)
Regression classes touched
Six questions
Paths examined: daemon Residual gaps: no runtime evidence (no builds or benchmarks, per reviewer constraint). Windows/WSL/Linux and SSH-relay behaviour were not exercised. |
Stacked on #43698 (merge that first; this PR's base is its branch).
Problem
When you open an agent tab and start typing right away, the keys you type before the terminal has connected are held and pasted into the agent once it is ready. If you keep typing after the terminal connects, that held part is dropped (with a notice) and only the later keys reach the agent: typing
ademarkqzacross the connect delivered onlyqz.Change
With #43698, Orca's zsh wrapper runs the agent launch itself, so anything written to the terminal while the tab starts waits in the terminal's input queue and the agent reads it in order. The daemon now reports that in the spawn result, and when it holds:
--resume) tab, which also starts a new process through the wrapper;Everything else keeps the current behavior (held and pasted when the agent is ready): longer drafts, launches that also paste a launch-time prompt, shells other than zsh, Windows/WSL, remote terminals, and reattaching to a running session.
If the shell never runs Orca's wrapper (no line editor, a profile that replaces the shell, or startup past the 15 s timeout), the daemon types the launch itself, clearing the line first with Ctrl-E then Ctrl-U so earlier keys can't turn it into
command not found. It then reports that it typed the launch. The pane takes back the keys it sent at connect and runs the existing path: paste them once the agent is ready, or show the recoverable notice if more was typed after connect. Nothing typed before connect is lost silently.Tests
agent-pre-ready-typed-draft.test.ts: a wrapper launch sends the held keys at bind, ahead of later typing.agent-pre-ready-typed-draft.test.ts: when the host reports it typed the launch, keys sent at bind are pasted again, or offered in the notice if typing followed.terminal-host-startup-type-ahead.node-pty.test.ts: with a real zsh that has no line editor, the host types the launch once and reports it once for that process.Known limits
command not found; the typed text is offered back in the notice. No line-clear prefix fixes vi-insert safely.command not found).readin a startup file can consume the keys sent at connect, and the agent also gets them through the paste.