Skip to content

perf(worktree): retain composer drafts and prepare agent shells - #18794

Merged
nwparker merged 33 commits into
nwparker/worktree-create-technicalfrom
nwparker/faster-worktree-create-ASTRA-astronaut
Sep 5, 2026
Merged

nwparker merged 33 commits into
nwparker/worktree-create-technicalfrom
nwparker/faster-worktree-create-ASTRA-astronaut

Conversation

@nwparker

@nwparker nwparker commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Latest follow-up

Current heads: A 80c93771548, B 5da57004e9f. Product source is unchanged from the released 2aa499b9412 build. The test-only follow-ups fix the relay-restart test's stale-binding wait and strengthen its oracle: the expected marker must be generated by the shell, and the sole durable reattachable lease must belong to the active PTY. All five restart cycles passed locally in 39.4 seconds, but worker teardown timed out at 120 seconds; the overall local command did not pass. Scoped review/elegance and lint/format passed. Fresh current-head CI is pending. The preceding B unit shard failed before tests during pnpm installation (ECONNRESET from npm); its workflow was still running when GitHub rejected a job retry.

Codex preflight imports its existing service directly and loads all-agent hook controls only for status/on/off. Isolated CLI comparison: 482 → 351 modules; median about 102 → 85 ms. Bundled output under the same signed Electron runtime: 126 → 110 ms (installation excluded; storage layouts differ). Nine command tests, full CLI + electron-vite build, runtime-import closure verification, lint/format and independent readiness/elegance review passed. Packaging CI found the initially missing direct-import entry; its fix subsequently passed Windows/Linux packaging. No additional user-facing negative trade-off identified.

ELI5

Opening the composer can prepare a real workspace and its shell while the user fills out the form. Create adopts that exact workspace and releases the selected agent command. Canceling keeps the draft available as a normal workspace.

Stacked on #18793. Both branches include main af82126058de and are non-draft. The integrated 14a65301892 passed CI, scoped readiness/elegance review, rendered creation, and forced app-process crash recovery. Later a7d1aef437e also passed CI and Pullfrog review. These historical passes do not replace current-head CI; see the follow-up above.

What Changed

  • Retain one immutable composer request and execution owner. Quick submit joins its creation; edits or cancellation preserve the existing workspace.
  • Keep a bounded, serialized checkout preparation for the active native target, with per-window leases and replacement after successful creation.
  • Prepare native local agent shells with the original environment, while the daemon holds the agent command until Create. Release requires the same workspace, PTY incarnation, and operation; retries never type a fallback command into an uncertain terminal.
  • Manual shell input retires the held command. Agent-start bookkeeping follows accepted release, and reattachment preserves authoritative deferred state.
  • Require daemon v38 for new preparation, while preserving release of commands already held by v37. Unsupported and older owners use ordinary creation or checkout-only preparation.
  • Preserve setup sequencing, default-tab policies, draft/follow-up delivery, terminal replay, and background selection.

Why

Move checkout and shell-profile work ahead of Create without launching the selected agent before submission. Preserve user-created/profile output and terminal ownership through cancellation and reattachment.

Linked Issue

User-requested performance work; no linked issue supplied.

Measured Behavior

Single native macOS development-build trials at 14a65301892 with real Codex:

Composer timing Create to workspace selection Create to prompt and resolved model
Create after 2.39 seconds 155 ms 531 ms
Create after 399 ms 838 ms 1876 ms

MCP servers were still initializing. The two trials above disabled Codex's update check only in isolated test settings; product defaults are unchanged. A further trial on 14a65301892 with normal update-check behavior selected the workspace in 228 ms but displayed Codex's update-choice screen instead of a task prompt throughout the 15-second observation. This existing agent prompt is not introduced by B. These measurements establish neither full tool readiness nor consistently near-instant creation.

Additional optimized-renderer comparison on the same commit and isolated profile (local Electron, production-bundled renderer with store instrumentation; not an installed-release benchmark):

  • Two prepared trials: workspace visible at 82 ms and 76 ms; Codex prompt/model at 510 ms and 364 ms.
  • In the second trial, keyboard-entered text rendered at 400 ms after Create; no task was submitted. MCP readiness remains excluded.
  • Immediate-click trial: workspace visible at 940 ms, prompt/model at 2066 ms. Git checkout alone took 769 ms, with negligible admission wait.
  • No renderer long tasks over 50 ms occurred in these optimized samples. Earlier development samples included 97–103 ms renderer tasks; no speculative renderer rewrite was made.

Validation scope: early optimized local trials had a missing out/cli/index.js. A later instrumented launch did not call that launcher, and an existing retained test shell reported no CODEX_HOME or ORCA_CODEX_LAUNCH_PREFLIGHT; therefore the missing file alone does not establish that those UI trials skipped preflight work they would otherwise perform. The separate preflight benchmarks measure the managed-home launch command, not a demonstrated cost in this fixture.

With the CLI built, two later prepared trials on the same running 14a65301892 app selected the workspace in 100/88 ms, rendered the Codex prompt/model in 597/530 ms, and displayed real keyboard input in 649/566 ms. Each included one 56–57 ms renderer long task. Screenshots inspected; no task submitted. MCP readiness remains excluded; update checks were disabled only for each trial and restored afterwards. These are local optimized-build measurements, not installed-release benchmarks. The instrumented launcher was restored after the final trial.

An additional instrumented warm trial isolated the prepared-command release: 28.7 ms after Create to enter the release IPC, 2.2 ms for that call to settle, workspace visible at 91 ms, Codex banner at 180 ms, prompt at 531 ms, and real typed input at 582 ms. CDP logpoints were removed afterwards. The running app remains the optimized 14a65301892 build (release-path source unchanged); update checks were disabled for this trial and restored, and MCP readiness is excluded. This rules out substantial release-IPC overhead in this sample, not across every topology.

Visual Proof

The earlier normal-restart images below are supplemented by 14a65301892 creation screenshots and a forced app-process crash check. The daemon remained running in both restart scenarios.

Composer open, with the real workspace prepared without changing the active workspace:
Prepared composer

The canceled draft reopened after a normal app-process restart on its original terminal. A shell command rendered successfully, and releasing the original agent operation returned retired after manual use:
Retained draft after restart

Draft at 14a65301892 after SIGKILL of the isolated app process and relaunch: original terminal restored, manual command rendered, original held-agent release returned retired:
Draft restored after forced app-process crash

Testing

  • Current-main integrated tree: 115 creation/deferral tests across nine suites and 73 process-inspection/router tests across four suites passed; full pnpm tc passed.
  • v38 boundary: 51 protocol, preserved-owner routing, and older-adapter compatibility tests passed before the main merge.
  • Native rendered trials verify exact workspace adoption, selected Codex startup, cancellation, manual retirement, and normal app-process restart with the original terminal identity.
  • All integrated-head (14a65301892) CI checks passed, including all eight test shards, packaging, typecheck, wire compatibility, and native smoke checks.
  • Final independent review: 64 focused tests across six suites passed; zero proven defects and no elegance changes requested.
  • Rendered native creation and SIGKILL/relaunch at 14a65301892 preserved the original draft terminal with no premature agent execution.
  • Additional isolated macOS daemon-process SIGKILL proof used real Bash PTYs: a held command executed zero times; an accepted command plus retry executed once; replacement daemons had empty inventories and rejected old-incarnation retries as unavailable. All owned processes exited. The daemon bundle was built at the earlier tested 14a65301892 baseline; daemon sources are unchanged through current head. This does not prove UI restoration or the unacknowledged release/crash window.
  • A further current-build macOS protocol probe used a socket proxy to withhold accepted release replies: actual DaemonClient rejected with connection loss. Reconnect/retry on the surviving daemon remained one execution; lost acknowledgement followed by daemon replacement returned unavailable and remained one execution. All owned processes exited. Execution completed before intentional SIGKILL, so arbitrary internal crash windows and UI/SSH recovery remain unproven.
  • Remaining evidence gaps: arbitrary internal daemon crash windows, host crash and adverse network transitions, broader live agent/default-tab/setup flows, and rendered deferral across all supported platforms. Native smoke CI is not full feature coverage.

Review and Merge Risk

Earlier reductions completed Fable review/fix and elegance passes. Native reviews covered the subsequent runtime and composer integration; the review-found restart metadata gap was fixed and tested. Final independent review and CI passed for 14a65301892; the two-file follow-up passed independent review and current-head Pullfrog re-review. CI passed at those earlier revisions, including the additional end-to-end jobs; latest-head CI remains pending. Current A re-review used Pullfrog, not Fable; later integration reviews used native subagents as requested.

Merge risk: moderate. This changes workspace lifecycle, background resource use, and daemon startup ownership. No known release-blocking defect remains; the breadth of the lifecycle change and the live topology gaps keep this above low risk.

User-facing Negative Trade-offs

  • Opening the composer can run checkout hooks and shell profiles before Create, including their side effects.
  • Canceled or edited drafts retain workspaces and shells, consuming disk/memory and adding cleanup.
  • Standby preparation and earlier terminal-code loading consume resources even when no workspace is ultimately submitted.

Remaining limitations:

  • Quick Create can still visibly wait for checkout, shell profiles, and agent startup.
  • SSH, folder, paired/runtime, VM, and structured-chat paths do not all receive the same acceleration.
  • Telemetry acknowledgement bookkeeping is not durable across a main-process crash; daemon command deduplication is independent.

Release

Refreshed release from exact commit 2aa499b9412fa37d8fcb9f644b513f3e0a8207e2, containing A+B product changes atop main af82126058de. Build run. Signed/notarized Apple Silicon and Intel macOS installers are published; downloaded Apple Silicon ZIP matches the updater SHA-512 and passes archive integrity verification. Windows packaging and publication also succeeded; the downloaded 181,968,744-byte installer matches its updater SHA-512. This build predates only the E2E test follow-ups at current head; product source is identical. Fresh CI remains pending, so this is a trial build rather than a claim of final readiness.

Agent skill upstream boundary: not applicable.

@nwparker
nwparker force-pushed the nwparker/faster-worktree-create-ASTRA-astronaut branch from b09175b to 8c0e7ec Compare September 5, 2026 05:35
# Conflicts:
#	src/shared/child-process/process-tree-termination.test.ts
@nwparker nwparker changed the title perf(worktree): overlap preparation and prestart blank terminals perf(worktree): retain composer drafts and prepare agent shells Sep 5, 2026
@nwparker
nwparker marked this pull request as ready for review September 5, 2026 12:37
@greptile-apps

greptile-apps Bot commented Sep 5, 2026

Copy link
Copy Markdown

Too many files changed for review (169 files, 100 file limit).

Bypass the limit by tagging @greptile-apps to review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

Reviewed the full head (14a6530) against base nwparker/worktree-create-technical — 169 files across the daemon control protocol, the PTY runtime/ipc spawn paths, the local/remote worktree-create flows, and the renderer composer. Substantive changes:

  • Daemon deferred-startup hold/release — a new deferredStartupOperationId flows through createOrAttach; SessionDeferredStartup holds the agent submission and only releases it on a releaseStartupCommand matching the exact session, PTY incarnation, and operation. deferStartupCommand suppresses argv delivery in shell-launch-plan.ts.
  • Protocol versioning — PROTOCOL_VERSION 36→38, split into DEFERRED_STARTUP_DAEMON_PROTOCOL_VERSION=37 (release) and DEFERRED_STARTUP_STATE_DAEMON_PROTOCOL_VERSION=38 (reattach state), keeping v37 release compatible so an upgrade never strands a held command.
  • Owner-fenced release — the runtime controller and the renderer worktrees:releaseStartup handler both re-derive the exact pty/incarnation/operation (and Claude account-switch) before releasing; unknown local ids return unavailable rather than falling through, and retries never type a fallback into an uncertain terminal.
  • Retained composer drafts — useRetainedComposerCreation reserves one frozen, execution-identity-keyed workspace+terminal per composer revision; Create joins the pending creation and releases the held command, while cancel/edit leaves it as a normal workspace.
  • Standby checkout preparation — a per-window WorktreeCreateStandbyOwner with a serialized queue plus holdPreparation/completePreparationClaim in the preparation pool, replenished only after successful finalization.
  • Startup-effect deferral — agent_started telemetry, markClaudePtySpawned, and Command-Code detection are withheld until accepted release in both the ipc and runtime spawn paths, with trust preflight (markCodexProjectTrusted awaited, non-interactive inspectHooksTrust) ordered before release.
  • Child-process hardening — resolveSpawn extracted to a pure module; hasExitedPosixProcessGroup shortens the POSIX termination barrier only when the whole group is provably gone (ESRCH).

The owner-fencing invariant is genuinely load-bearing and I traced it end-to-end: release claims 'accepted' before writing, a reentrant release is a no-op, a throwing write yields 'unverifiable' and is never replayed, and exit/dispose/termination retire the command and block queued delivery. Protocol v37/v38 boundaries, the OptionalPlainString change to preserve empty-string startupCommand, and the schema/wire additions are all consistently gated and tested. The only remaining limitations (non-durable telemetry acknowledgement across main-process crash, no SSH/folder/VM release parity, unverified cross-platform rendered deferral) are disclosed in the PR body and gated experimental — none are defects in this change.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

Reviewed the delta since the prior Pullfrog review (14a6530): the technical base advanced one commit and was merged into this branch, so the net change is a single commit.

  • Malformed remote-base short-circuit — resolveRemoteTrackingBase now returns null for bases whose remote/branch separator is missing, leading, or trailing (e.g. main, /main, origin/, refs/remotes//main), skipping the git remote probe entirely instead of spawning a subprocess that then fails to match.

The change is behavior-preserving for every valid remote-tracking base, and every newly-rejected form already resolved to null under the old code — but only after a wasted git remote spawn. The expanded it.each cases plus the not.toHaveBeenCalled() assertion make the no-launch guarantee fail if Git is ever invoked for these inputs, so the coverage is real rather than cosmetic.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

Reviewed the delta since the prior Pullfrog review (a7d1aef437), which nets to a single performance commit plus the technical-base merge.

  • Codex preflight module decoupling — agent-hooks.ts now imports prepareManagedCodexHomeBeforeShellLaunch directly from codex/managed-home-shell-preflight (its existing service home) instead of routing it through the all-agent managed-agent-hook-controls registry, so a managed-home Codex shell launch no longer drags the full managed-agent-hook registry into its module graph.
  • Lazy-loaded all-agent hook controls — applyAgentStatusHooksEnabled and getManagedAgentHookStatuses are now await imported only inside the status/on/off command paths, keeping them off the preflight's load path.

The split is behavior-preserving: managed-agent-hook-controls.ts still re-exports the preflight function so existing consumers are unchanged, and the new dynamic imports use the same .js-suffixed await import convention already used across the CLI. The test mocks were updated to match the two import sites, and the nine existing command tests continue to exercise the functional paths. No correctness, coverage, or elegance concerns.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

Reviewed the delta since the prior Pullfrog review (net of 2aa499b9412..27e4727d00, the changed-spec E2E race fix pulled in from the stacked technical base).

  • Wait for pane re-binding before lease-recovery input — the keeps one reattachable lease per pane spec now captures the pre-kill PTY id at the top of each generation loop and, after the relay is killed and the transport reports connected, actively polls until the active pane reports a different PTY id before typing the generation marker. This replaces a comment that only stated the intent and closes the race where the marker was sent before the replacement relay was ready.

The fix mirrors the identical .poll(...).catch(() => previousPtyId).not.toBe(...) pattern already used by the preceding verdict spec, so the timing and the swallow-into-retry semantics are consistent with the surrounding suite. It adds a real assertion (the pane must actually re-bind under a new lease) rather than weakening an existing one, so the test is more strict, not less.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker merged commit 27e4727 into nwparker/worktree-create-technical Sep 5, 2026
35 of 37 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