Skip to content

fix(agents): recover Codex startup draft delivery - #8281

Closed
bbingz wants to merge 4 commits into
stablyai:mainfrom
bbingz:bbingz/split-7950-startup-drafts
Closed

bbingz wants to merge 4 commits into
stablyai:mainfrom
bbingz:bbingz/split-7950-startup-drafts

Conversation

@bbingz

@bbingz bbingz commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

Summary

Replacement slice for #7950, limited to Codex startup commands and draft delivery.

  • replace the removed codex --prefill assumption with explicit positional-prompt startup planning
  • fall back from oversized Windows argv to paste-submit delivery
  • require the real Codex composer-ready state before pasting linked drafts
  • preserve launch-bound delivery ownership across PTY dispose/remount and delayed background workspace activation
  • distinguish not-written from delivery-uncertain: retry only when no bytes were accepted, never replay partial writes or a request whose acknowledgement was lost
  • preserve successful follow-up component state so a later draft-only retry cannot submit the follow-up twice
  • discard delayed work when its tab is gone and re-run readiness checks when the PTY is replaced

Why this is separate

#7950 combined unrelated hook, auth/rate-limit, session/native-chat, and startup behavior. This PR contains only the startup/drafts slice so its delivery ownership and side-effect boundary can be reviewed and reverted independently.

Correctness and compatibility

  • explicit readiness timeout or terminal rejection before any write can requeue the remaining payload
  • partial chunk delivery, remote acknowledgement loss, or Promise rejection remains consumed; the client does not automatically replay ambiguous user/task text
  • an uncertain result does not show the “was not sent, paste manually” toast, which could otherwise induce a duplicate
  • the automatic no-write retry is bounded: a second no-write result waits for a later relevant state transition and does not spin
  • a replacement PTY never inherits the old PTY's readiness decision
  • existing boolean paste/follow-up APIs remain compatible; the structured outcome is used only where retry safety needs it
  • Windows command-length fallback uses the existing paste-submit transport; macOS, Linux, local, and SSH launch paths keep their platform gates

Testing

  • original focused startup suite: 12 files / 1,681 tests
  • side-effect-aware delivery suite: 4 files / 76 tests
  • focused PTY retry/ownership cases: 8 tests
  • transient unrelated Droid timer case rerun: passed
  • pnpm typecheck
  • pnpm lint
  • targeted oxfmt --check
  • pnpm check:max-lines-ratchet
  • git diff --check origin/main...HEAD
  • independent spec gate: PASS
  • independent code-quality re-gate: APPROVED
  • Electron/E2E/GUI
  • Windows/SSH live smoke

AI Review Report

The first independent gate approved the original startup split. After submission, CodeRabbit correctly identified that a boolean failure could represent either zero writes or partial delivery. The fix introduces an explicit side-effect-aware outcome through the paste/follow-up and delayed-delivery boundary.

A second independent gate verified that only not-written requeues; partial chunks, lost acknowledgements, and rejected Promises do not replay; successful follow-up state is removed from a draft retry; and dispose/remount cannot release an uncertain claim. Its only follow-up was to avoid the existing manual-paste toast for uncertain delivery; that was fixed and the final re-gate ended APPROVED.

Security Audit

Generated task text is never replayed when delivery may already have occurred. The change adds no credentials, commands, IPC methods, dependencies, or persisted data, and keeps the existing PTY/runtime ownership checks.

Notes

The full 430-test PTY file had one unrelated timer-sensitive Droid assertion fail in the combined run; that exact test passed immediately in isolation. No assertion or production behavior was weakened. Validation used Node 26.5.0 while the repository declares Node 24.

ELI5

Codex startup could fail to deliver the first prompt/draft (especially on Windows or after remounts) after the old --prefill path went away. Startup planning, paste-when-ready, and ownership across dispose/remount are fixed so drafts actually reach the composer.

@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The changes centralize TUI launch command resolution and add shell-specific Windows command-length handling. Shell-ready startup delivery now requires explicit configuration, while Codex draft readiness requires both prompt signals. Startup and PTY draft delivery paths now return delivery outcomes, release failed attempts, and requeue retries when launch state remains valid. Related tests cover positional Codex prompts, readiness scanning, retry behavior, PTY handoffs, and paste timing.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise and accurately summarizes the main change: recovering Codex startup draft delivery.
Description check ✅ Passed The description covers the required summary, testing, AI review, security, and notes sections; only the screenshots section is omitted.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai 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.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 055ebc34-01d0-4a97-a4af-01df44c25192

📥 Commits

Reviewing files that changed from the base of the PR and between ff8192a and 5b36bc66b822c266221c3ca474559f5a404c3b57.

📒 Files selected for processing (22)
  • src/main/daemon/pty-subprocess.test.ts
  • src/main/ipc/pty.test.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/relay/pty-handler.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/lib/agent-paste-draft.test.ts
  • src/renderer/src/lib/agent-paste-draft.ts
  • src/renderer/src/lib/agent-startup-delayed-delivery-perf.test.ts
  • src/renderer/src/lib/agent-startup-delayed-delivery.ts
  • src/renderer/src/lib/launch-agent-background-session.test.ts
  • src/renderer/src/lib/new-workspace.test.ts
  • src/renderer/src/lib/new-workspace.ts
  • src/shared/agent-draft-platform-limit.ts
  • src/shared/codex-startup-delivery.test.ts
  • src/shared/codex-startup-delivery.ts
  • src/shared/draft-paste-ready-scanner.test.ts
  • src/shared/draft-paste-ready-scanner.ts
  • src/shared/tui-agent-config.ts
  • src/shared/tui-agent-launch-command.ts
  • src/shared/tui-agent-startup.test.ts
  • src/shared/tui-agent-startup.ts

Comment thread src/renderer/src/lib/agent-startup-delayed-delivery.ts Outdated
Comment thread src/renderer/src/lib/new-workspace.ts Outdated
@bbingz

bbingz commented Jul 13, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@bbingz
bbingz force-pushed the bbingz/split-7950-startup-drafts branch 2 times, most recently from e74e1b2 to 606dbc0 Compare July 14, 2026 00:38
@bbingz

bbingz commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto latest origin/main (force-with-lease).

Conflict resolution notes:

  • Kept main's resolveAgentLaunchCommand + session-options structure (PR's older resolveTuiAgentBaseCommand path discarded)
  • Merged side-effect-aware paste outcomes (not-written / delivery-uncertain) into main's normalizeTerminalPasteLineEndings / wrapTerminalBracketedPasteText paste path
  • Preserved PR intent: oversized Windows argv falls back to post-ready paste-submit; Codex positional startup uses shell-ready delivery

@bbingz
bbingz force-pushed the bbingz/split-7950-startup-drafts branch from b4e05d2 to aa212c4 Compare July 22, 2026 01:27
@bbingz

bbingz commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current main. Codex startup draft delivery recovered against main’s resolveAgentLaunchCommand/session-options shape. Ready for re-review.

@nwparker nwparker added the bug Something isn't working label Jul 27, 2026
@bbingz
bbingz force-pushed the bbingz/split-7950-startup-drafts branch 2 times, most recently from ebec2b6 to 7e1c571 Compare July 31, 2026 09:57
@greptile-apps

greptile-apps Bot commented Jul 31, 2026

Copy link
Copy Markdown

Greptile Summary

This PR recovers Codex startup draft delivery after the removal of --prefill, introducing an explicit 'not-written' | 'delivery-uncertain' | 'delivered' outcome type to distinguish safe-to-retry from ambiguous failures, and adding a Windows cmd.exe argv-length fallback that routes oversized prompts through the post-ready stdin path instead of truncating them.

  • Outcome-aware delivery pipeline: sendAgentDraftPasteContentWithOutcome, sendFollowupPromptWhenAgentReadyWithOutcome, and pasteDraftToAgentPtyWhenReadyWithOutcome replace boolean returns; only not-written (zero bytes accepted) requeues — partial writes and lost ACKs consume the launch token permanently to prevent duplicate user/task text.
  • PTY dispose/remount ownership: startupDraftPasteInFlight prevents premature delivery release during in-flight writes; handOffFailedStartupDraftPaste correctly routes same-PTY retries through the existing transport and replacement-PTY retries through the full readiness gate.
  • Readiness scanner hardening: Codex composer readiness now requires both the glyph and the "Ask Codex" placeholder text after DECSET 2004, preventing early delivery triggered by the bare glyph emitted during hooks review before the composer owns input.

Confidence Score: 5/5

Safe to merge. The changes are tightly scoped to startup/draft delivery, introduce no new external dependencies, and the boolean-compat wrappers keep all existing callers working without modification.

The outcome-type refactor is internally consistent: not-written is the only outcome that requeues, all partial/uncertain paths consume the launch token, and the deliveryStarted flag in the chunked paste path correctly distinguishes zero-write from mid-stream failure. PTY dispose/in-flight interlock logic is sound — startupDraftPasteInFlight prevents premature release and the async resolution paths all converge correctly. The scanner dual-marker change is conservative and the state variables are monotonic booleans, so cross-chunk detection is reliable.

Files Needing Attention: No files require special attention. The large pty-connection.ts change is well-contained to the startup draft section and the new state variables are clearly named.

Important Files Changed

Filename Overview
src/renderer/src/components/terminal-pane/pty-connection.ts Split startupDraftPasteAttempted into three flags; handOffFailedStartupDraftPaste correctly distinguishes same-PTY retry from replacement-PTY retry; dispose during in-flight correctly defers release until the async settles.
src/renderer/src/lib/new-workspace.ts Refactors deliverAgentStartupToTerminal to return AgentStartupDeliveryOutcome; strips followupPrompt from retry to prevent double-submission; immediate retry then state-change-gated re-queue prevents spin loops.
src/renderer/src/lib/agent-startup-delayed-delivery.ts New requeueFailedAgentStartupDelivery gates the toast on tab/launch-token expiry; uncertain outcomes keep the delivery consumed to prevent duplicate replay.
src/renderer/src/lib/agent-draft-paste-content.ts Chunk-level deliveryStarted flag correctly distinguishes zero-write from partial-write failures; backward-compatible boolean wrapper preserved.
src/shared/draft-paste-ready-scanner.ts Codex readiness now requires both the glyph AND the Ask Codex placeholder after DECSET 2004; redundant first observeCodexMarkers(data) call is harmless.
src/shared/tui-agent-startup.ts Adds Windows oversized-argv fallback routing oversized prompts to followupPrompt instead of truncating.
src/shared/tui-agent-draft-launch-plan.ts Extracted buildAgentDraftLaunchPlan; removed dead codex-specific startupCommandDelivery: 'shell-ready' inside draftPromptFlag block.
src/shared/codex-startup-delivery.ts Removes hasCodexNativeDraftFlag and the --prefill tokenizer; function now checks only the explicit startupCommandDelivery field.
src/shared/agent-draft-platform-limit.ts Adds tighter 7,500-char limit for cmd shell to respect 8,191-char cmd.exe cap.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[ensureAgentStartupInTerminal] --> B{PTY available?}
    B -- No --> C[queuePendingAgentStartupDelivery]
    B -- Yes --> D[beginAgentStartupDeliveryAttempt]
    D --> E[deliverAgentStartupToTerminal]
    E --> F{followupPrompt?}
    F -- Yes --> G[sendFollowupPromptWhenAgentReadyWithOutcome]
    G -- delivered --> H[strip followupPrompt from remainingStartup]
    G -- not-written --> R1[retryable]
    G -- delivery-uncertain --> U[consumed, no toast]
    H --> I{draftPrompt?}
    F -- No --> I
    I -- Yes --> J[pasteDraftToAgentPtyWhenReadyWithOutcome]
    J -- delivered --> OK[kind: delivered]
    J -- not-written --> R2[retryable, followupPrompt cleared]
    J -- delivery-uncertain --> U
    I -- No --> OK
    R1 & R2 --> RQ[release + queuePendingAgentStartupDelivery]
    RQ --> FD[immediate retry via flush]
    FD -- not-written again --> RF[requeueFailedAgentStartupDelivery]
    RF -- tab gone / token stale --> T[showAutomationPromptNotSentToast]
    RF -- guards pass --> WAIT[wait for store state change]
Loading

Reviews (2): Last reviewed commit: "test(agents): hoist startup toast mock" | Re-trigger Greptile

Comment thread src/renderer/src/lib/new-workspace.ts
Comment thread src/shared/tui-agent-draft-launch-plan.ts Outdated
@bbingz
bbingz force-pushed the bbingz/split-7950-startup-drafts branch from 7e1c571 to a22ea63 Compare August 2, 2026 01:59
@bbingz
bbingz force-pushed the bbingz/split-7950-startup-drafts branch from a22ea63 to bffe3f8 Compare August 4, 2026 00:41
@bbingz

bbingz commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

Closing as part of fork PR backlog cleanup.

This branch is long-conflicted (DIRTY) against current main and is not on the active campaign rebase list. Feel free to reopen or cut a fresh PR from an updated branch if the change is still needed.

@bbingz bbingz closed this Aug 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants