Skip to content

Fix Windows ConPTY OSC color reply leaks at the PTY owner - #9651

Merged
OrcaWin merged 2 commits into
mainfrom
OrcaWin/osc-color-reply-leak-windows-runtime
Jul 21, 2026
Merged

OrcaWin merged 2 commits into
mainfrom
OrcaWin/osc-color-reply-leak-windows-runtime

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Jul 21, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Stop OSC 10/11 color-query replies from leaking into Codex input on native Windows ConPTY, including when a macOS/non-Windows client controls a paired Windows runtime.
  • Classify the PTY backend on the process that actually owns and spawned it (windows-conpty, windows-wsl, or posix-pty) instead of inferring ownership from renderer, cwd, or connection heuristics.
  • Consume exact native-ConPTY OSC 10/11 queries before model/history/replay/view delivery. Reply immediately at the owner when validated startup colors are available; otherwise consume without replying.
  • Preserve normal query replies for WSL and POSIX PTYs, and propagate theme colors through paired-runtime terminal creation to retain the light-theme behavior introduced by fix(renderer): answer OSC color queries from active terminal theme #6502.
  • Bump the daemon protocol to 25 and relay startup-ingress protocol to 2.

This supersedes the design direction in #6975. That PR suppresses in downstream renderer handlers and treats remote runtimes as safe; the paired-Windows reproduction shows the PTY owner, not the viewer/connection kind, must decide.

Reproduction

A deterministic Session-level regression models the complete byte flow without sleeps:

  1. A non-Windows remote view attaches to a PTY classified by the legacy flow as POSIX even though it is Windows-owned ConPTY.
  2. Codex emits OSC 10;?.
  3. The recorded remote-visible-renderer producer sees the query and writes a synthetic color reply as PTY input.
  4. The harness applies the observed ESC-stripped ConPTY projection and proves the printable ]10;rgb:...\\ body reaches the client and authoritative snapshot.
  5. With native owner classification, the query is consumed before the producer callback, no reply input is written, and the snapshot remains clean.

The shared byte-level harness also splits OSC queries at every byte and covers authority-close, deadline expiry, snapshot, malformed input, and re-entrant provider callbacks.

On real Windows, native node-pty loaded as WindowsTerminal. Codex CLI 0.144.6 did not naturally emit OSC 10/11 in the available configuration, but complete ESC-framed replies were consumed while injecting the exact ESC-stripped bodies reproduced the literal composer text from the field report.

Screenshots

No intended visual change beyond preventing terminal protocol text from appearing in the composer.

Testing

  • pnpm lint — oxlint passes; the combined command remains blocked by the unrelated pre-existing switch-exhaustiveness error in skill-freshness-group.tsx.
  • pnpm typecheck
  • pnpm test — targeted terminal/PTY suites were run instead; full relay/runtime baselines are noted below.
  • pnpm build
  • Added or updated high-quality tests that would catch regressions

Passed before and after the final review changes:

  • 268 shared/daemon tests in the final broad pass
  • 85/85 local PTY provider tests
  • 299 IPC PTY tests
  • 142 terminal query-authority tests
  • 522 renderer, hidden-pane, replay, reconnect, and restore tests
  • 29 daemon restore tests
  • 819/820 runtime/RPC tests; the sole failure is the existing Windows /tmp normalization baseline
  • focused native Windows, paired-runtime, WSL, POSIX SSH, and Windows SSH relay tests after rebasing onto current main
  • oxlint, oxfmt --check, git diff --check, reliability-gate manifest, and max-lines ratchet

Known unrelated baseline: the full relay file has 80 passing tests and 15 Windows assertions that expect POSIX kill(signal) arguments even though Windows node-pty calls kill() argumentlessly.

AI Review Report

The requested internal-review skill was unavailable, so four manual adversarial review/fix rounds were run against the branch diff. Review rejected both renderer ownership heuristics and a proposed input-reply filter, then checked:

  • actual spawned-shell ownership versus stale WSL/request metadata
  • local, daemon, SSH relay, paired runtime, revive, reattach, hidden, visible, and replay paths
  • duplicate response authorities and authority-close/deadline races
  • split OSC at every byte, malformed/non-query OSC, and unrelated input/escape behavior
  • source sequence accounting and transformed empty spans
  • daemon/relay protocol skew
  • hot-path performance and bounded buffering

Review found and fixed a split-query race across close/expiry/snapshot barriers, removed a redundant renderer-selected echo-projection wire field, and added the missing daemon server route for startup authority closure.

Cross-platform audit: native Windows ConPTY alone gets the suppression contract. Windows WSL, Windows-hosted POSIX/WSL shells, Linux/macOS PTYs, POSIX SSH, and paired non-Windows runtimes retain existing behavior. No keyboard shortcut, label, path, or UI-platform logic changed.

Security Audit

  • No command construction, shell execution, auth, secret, dependency, or filesystem behavior was added.
  • Runtime RPC accepts only bounded optional foreground/background strings; existing color normalization validates them before replies are enabled.
  • Daemon and relay inputs remain version-gated and parsed through existing allowlisted contracts.
  • The ingress parser recognizes only exact OSC 10/11 query grammar and never filters the PTY input/write path, so typed Escape keys and pasted reply-looking text are unaffected.

Notes

Tradeoffs:

  • Native ConPTY applications no longer receive downstream OSC 10/11 replies after the bounded owner-side startup opportunity. This is deliberate because a late reply can become user input. Other terminal capabilities are unaffected.
  • Owner-side scanning adds one linear scan to native-ConPTY output with a maximum 64-character pending candidate; POSIX/no-intent traffic keeps its direct pass-through path.
  • Existing sessions owned by an old daemon/relay binary need that owner upgraded/restarted before source-side suppression is available.
  • Real Windows validated the ConPTY/composer sink, but the installed Codex build did not naturally issue the startup query, so the exact live timing remains represented by the deterministic transport regression.

@coderabbitai

coderabbitai Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: ba37b70c-bbb9-4a87-b445-3f783f007b1c

📥 Commits

Reviewing files that changed from the base of the PR and between 0659cb4 and 072e03b.

📒 Files selected for processing (1)
  • src/relay/pty-handler.test.ts

📝 Walkthrough

Walkthrough

The change classifies PTY ownership as native ConPTY, Windows WSL, or POSIX and passes that classification through local, daemon, and relay startup-ingress paths. Startup-ingress contracts and span handling are centralized, while native ConPTY queries receive backend-specific suppression and lifecycle behavior. Terminal view colors can now be forwarded through runtime and remote terminal creation. Daemon and startup-ingress protocol versions are updated, with routing support for closing startup query authority.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.38% 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
Title check ✅ Passed The title clearly matches the main change: fixing native Windows ConPTY OSC color reply leaks at the PTY owner.
Description check ✅ Passed The description includes all required template sections and covers summary, testing, AI review, security, and notes.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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: 1

🧹 Nitpick comments (4)
src/relay/pty-handler.ts (1)

1333-1336: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Preserve WSL backend classification during relay revival.

reviveEntry resolves the PTY backend using the default shell and omits wslDistro. Because SerializedPtyEntry does not currently capture the original shellPath or wslDistro, revived WSL sessions over the relay on Windows will lose their WSL context and misclassify as windows-conpty.

If preserving the correct backend classification across relay restarts is intended, consider updating serialize to capture wslDistro and shellPath so they can be restored here.

src/shared/pty-startup-ingress-contract.ts (1)

31-41: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Safeguard sequence numbers against negative or out-of-bounds slice indices.

If this generic utility is ever called with negative or out-of-bounds start or end arguments (which are perfectly valid for String.prototype.slice), the raw sequence boundary calculations will be corrupted because they blindly add the index arguments rather than compute the actual slice distance.

Compute the normalized start index and use the resulting sliced data length to calculate rawEndSeq so the interval always equals the payload length.

♻️ Proposed refactor
 export function slicePtyIngressSourceSpan(
   span: PtyIngressSourceSpan,
   start: number,
-  end = span.data.length
+  end?: number
 ): PtyIngressSourceSpan {
+  const normalizedStart = start < 0 ? Math.max(0, span.data.length + start) : Math.min(span.data.length, start)
+  const slicedData = span.data.slice(start, end)
   return {
-    data: span.data.slice(start, end),
-    rawStartSeq: span.rawStartSeq + start,
-    rawEndSeq: span.rawStartSeq + end
+    data: slicedData,
+    rawStartSeq: span.rawStartSeq + normalizedStart,
+    rawEndSeq: span.rawStartSeq + normalizedStart + slicedData.length
   }
 }
src/main/runtime/orca-runtime.ts (1)

1282-1282: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reuse TerminalOscColorQueryReplyColors for the spawn contract.

This redeclares the shared reply-color shape inline even though the same public type is already imported and used at Line 1082. Use the shared type here to prevent the launch and spawn contracts from drifting independently.

Proposed change
-    terminalColorQueryReplies?: { foreground?: string; background?: string }
+    terminalColorQueryReplies?: TerminalOscColorQueryReplyColors
src/main/runtime/rpc/methods/terminal.ts (1)

918-923: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider using z.strictObject() for explicit object parsing.

If you want to reject unknown keys in the color query replies, z.strictObject() provides stricter validation. Based on learnings, Zod 4 introduces z.strictObject() and z.looseObject() for clearer object parsing modes.

♻️ Proposed refactor
-  terminalColorQueryReplies: z
-    .object({
-      foreground: z.string().max(128).optional(),
-      background: z.string().max(128).optional()
-    })
-    .optional(),
+  terminalColorQueryReplies: z
+    .strictObject({
+      foreground: z.string().max(128).optional(),
+      background: z.string().max(128).optional()
+    })
+    .optional(),

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: b53448b1-d7c5-4d8f-9211-2cebb3aa3fef

📥 Commits

Reviewing files that changed from the base of the PR and between 8182141 and 0659cb4.

📒 Files selected for processing (29)
  • docs/reference/plans/2026-07-19-windows-conpty-startup-query-and-focus-authority.md
  • src/main/daemon/daemon-foreground-confirmation-protocol.test.ts
  • src/main/daemon/daemon-protocol-version.ts
  • src/main/daemon/daemon-pty-adapter.test.ts
  • src/main/daemon/daemon-server.test.ts
  • src/main/daemon/daemon-server.ts
  • src/main/daemon/session.test.ts
  • src/main/daemon/session.ts
  • src/main/daemon/terminal-host-pty-owner-backend.test.ts
  • src/main/daemon/terminal-host.ts
  • src/main/ipc/pty.ts
  • src/main/providers/local-pty-provider.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/providers/ssh-pty-provider.test.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/runtime/runtime-rpc.test.ts
  • src/main/runtime/terminal-view-attribute-store.ts
  • src/relay/pty-handler.test.ts
  • src/relay/pty-handler.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
  • src/shared/pty-owner-backend.test.ts
  • src/shared/pty-owner-backend.ts
  • src/shared/pty-startup-ingress-contract.ts
  • src/shared/pty-startup-ingress-intent.ts
  • src/shared/pty-startup-ingress.test.ts
  • src/shared/pty-startup-ingress.ts

Comment on lines 280 to +283
private releaseAllPending(): void {
const pending = this.echoPending ?? this.queryPending
this.echoPending = null
this.queryPending = null
if (pending) {
this.emit(pending, false)
this.releaseEchoPending()
this.releaseQueryPending()
}

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect release/teardown paths and any test coverage for partial-query-at-teardown on ConPTY.
fd -t f 'pty-startup-ingress' src/shared
rg -nP -C4 'releaseAllPending|releaseQueryPending|case .teardown' src/shared/pty-startup-ingress.ts
rg -nP -C3 'drainAndClose' src/shared/pty-startup-ingress.test.ts

Repository: stablyai/orca

Length of output: 4148


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n== relevant source ==\n'
sed -n '1,240p' src/shared/pty-startup-ingress.ts
printf '\n== teardown/release area ==\n'
sed -n '240,340p' src/shared/pty-startup-ingress.ts

printf '\n== tests around ConPTY/query teardown ==\n'
sed -n '1,360p' src/shared/pty-startup-ingress.test.ts | sed -n '1,360p' | rg -n -C4 'windows-conpty|closeQueryAuthority|drainAndClose|queryPending|teardown|expire|snapshot|close-query|partial|split'

Repository: stablyai/orca

Length of output: 18245


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n== teardown-related tests ==\n'
sed -n '170,280p' src/shared/pty-startup-ingress.test.ts

printf '\n== relevant helper semantics ==\n'
sed -n '1,220p' src/shared/terminal-osc-color-reply.ts

Repository: stablyai/orca

Length of output: 10373


Keep ConPTY queryPending private on teardown. releaseAllPending() still flushes a buffered split OSC query raw on drainAndClose(), unlike the other ConPTY barriers; gate releaseQueryPending() here too unless that flush-at-close behavior is intentional.

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