Skip to content

Fix native Windows PTY startup query handling - #9500

Merged
Jinwoo-H merged 6 commits into
mainfrom
Jinwoo-H/bug-windows-only-sometimes-new-codex-session-pri
Jul 20, 2026
Merged

Jinwoo-H merged 6 commits into
mainfrom
Jinwoo-H/bug-windows-only-sometimes-new-codex-session-pri

Conversation

@Jinwoo-H

Copy link
Copy Markdown
Contributor

Fixes #9432

Summary

  • Make the source-owned startup query path authoritative and emit canonical OSC replies.
  • Apply cooked-echo suppression only to native Windows ConPTY startup queries, with raw-span and sequence accounting preserved.
  • Gate the behavior through daemon and relay capabilities while keeping WSL, SSH, remote, and legacy paths passive.

Design: Windows ConPTY startup query and focus authority

Validation

  • Electron passed fresh and repeat Codex sessions, hide/reveal, focus/reconnect, PowerShell, and Ubuntu WSL scenarios. The local ignored validation-screenshots/ manifest records the evidence.
  • SSH manual validation was skipped only because the Docker Linux engine was unavailable: open //./pipe/dockerDesktopLinuxEngine: The system cannot find the file specified. Automated relay and SSH coverage passed.
  • Passed: typecheck; 49-file oxlint; 52-file oxfmt; max-lines ratchet; all 44 reliability gates; git diff --check; focused matrix (1,146 passed, 15 skipped); broader matrix (1,188 passed, 15 skipped); focused relay startup (2 passed, 97 skipped); relay builds for Windows, Linux, macOS, and the WSL hook.
  • Baseline-only: relay current was 77 passed, 15 failed, 7 skipped versus clean base at 75 passed with the identical 15 failures, 7 skips, and timeout; runtime current and base were both 756 passed and 1 failed; full lint reported only untouched skill-freshness-group.tsx:101, reproduced exactly on clean base.

Jinwoo-H added 2 commits July 19, 2026 19:15
…only-sometimes-new-codex-session-pri

# Conflicts:
#	docs/reference/terminal-model-view-contract.md
#	docs/reference/terminal-query-authority.md
#	src/main/daemon/session.test.ts
#	src/main/daemon/terminal-host.ts
#	src/main/providers/types.ts
@coderabbitai

coderabbitai Bot commented Jul 20, 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

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: a66b0457-2ff8-48dc-9e5d-dde153537f68

📥 Commits

Reviewing files that changed from the base of the PR and between 99c79d5 and a5565fd.

📒 Files selected for processing (1)
  • config/scripts/windows-daemon-workspace-close-repro.mjs

📝 Walkthrough

Walkthrough

Adds a source-owned PTY startup ingress pipeline that intercepts startup OSC color queries, emits canonical replies, suppresses matching ConPTY projections, and preserves raw sequence accounting. The change wires ingress through local providers, daemon sessions, SSH relay handling, IPC, runtime batching, renderer delivery, snapshots, and teardown. It adds protocol-version gating, transformed OutputSpan framing, authority-close RPCs, expanded event metadata, validation helpers, and integration tests for startup classification, legacy compatibility, transformed spans, resynchronization, and lifecycle boundaries.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is far short of the required template and omits Screenshots, Testing, AI Review Report, Security Audit, and Notes. Add the missing template sections: Screenshots, Testing, AI Review Report, Security Audit, and Notes, and fill them with PR-specific details.
Docstring Coverage ⚠️ Warning Docstring coverage is 10.34% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately describes the main change: native Windows PTY startup query handling.
Linked Issues check ✅ Passed The changes address #9432 by making startup query handling authoritative and preventing raw OSC replies from leaking into output on Windows.
Out of Scope Changes check ✅ Passed The diff stays focused on startup-ingress, metadata propagation, and related tests/docs, with no clear unrelated feature work.
✨ 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: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/daemon/daemon-stream-data-batcher.ts (1)

247-282: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

sequenceChars/seq drift when a queued entry is split.

  • sliceSequenceChars falls back to slice.length for any non-transformed slice unless the whole entry fits, so a merged entry with real raw/clean divergence is reported as if it matched.
  • On partial drains, entry.sequenceChars is reduced, but entry.seq is reused unchanged for later flushes, so subsequent slices carry the wrong sequence value.

writeStreamDataEvents has the same chunk-length assumption and will need the same treatment once this path preserves divergence.

🧹 Nitpick comments (3)
src/main/daemon/daemon-protocol-version.ts (1)

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

Derive PREVIOUS_DAEMON_PROTOCOL_VERSIONS instead of hand-listing it.

Manually enumerating every prior version risks drifting out of sync the next time PROTOCOL_VERSION is bumped (forgetting to append the new "previous" entry).

♻️ Proposed refactor
-export const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = [
-  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23
-] as const
+export const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = Array.from(
+  { length: PROTOCOL_VERSION - 1 },
+  (_, i) => i + 1
+)
src/main/ipc/pty.ts (1)

4142-4150: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add a // Why: comment for this design-driven constraint.

As per coding guidelines, code driven by a design document or non-obvious constraint should have a brief comment explaining why the behavior is necessary. Since this conditionally applies cooked-echo suppression specifically for native Windows ConPTY as dictated by the startup-query design doc, please add a // Why: comment here.

💡 Proposed refactor
       if (startupTerminalColorQueryReplyColors) {
         spawnOptions.startupIngress = {
           colors: startupTerminalColorQueryReplyColors,
           deadlineMs: 5_000,
+          // Why: Native Windows ConPTY echoes the raw query back to us; suppress it so
+          // it doesn't leak into the terminal (terminal-query-authority.md).
           ...(nativeWindowsConptySpawn
             ? { echoProjection: 'windows-conpty-esc-stripped' as const }
             : {})
         }
       }

Source: Coding guidelines

src/main/providers/local-pty-provider.ts (1)

122-128: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider reusing PtyDataEvent instead of a duplicate inline DataCallback shape.

DataCallback's payload is structurally identical to the exported PtyDataEvent type (from ./pty-provider-events), which degraded-daemon-pty-provider.ts already adopted in this same PR. Importing PtyDataEvent here too would keep a single source of truth for this shape.

♻️ Suggested consolidation
-type DataCallback = (payload: {
-  id: string
-  data: string
-  sequenceChars?: number
-  transformed?: boolean
-  seq?: number
-}) => void
+type DataCallback = (payload: PtyDataEvent) => void

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 5c70562a-a217-496f-abe4-8584a953c3ae

📥 Commits

Reviewing files that changed from the base of the PR and between 3a847bf and a4058d7.

📒 Files selected for processing (51)
  • docs/reference/plans/2026-07-19-windows-conpty-startup-query-and-focus-authority.md
  • docs/reference/terminal-model-view-contract.md
  • docs/reference/terminal-query-authority.md
  • src/main/daemon/daemon-protocol-version.ts
  • src/main/daemon/daemon-pty-adapter.test.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/daemon/daemon-pty-router.ts
  • src/main/daemon/daemon-server.ts
  • src/main/daemon/daemon-stream-data-batcher.test.ts
  • src/main/daemon/daemon-stream-data-batcher.ts
  • src/main/daemon/daemon-stream-data-entry.ts
  • src/main/daemon/daemon-stream-data-split.ts
  • src/main/daemon/daemon-stream-events.ts
  • src/main/daemon/daemon-stream-keep-tail-drop.ts
  • src/main/daemon/degraded-daemon-pty-provider.ts
  • src/main/daemon/session.test.ts
  • src/main/daemon/session.ts
  • src/main/daemon/terminal-host-create-contract.ts
  • src/main/daemon/terminal-host-options.ts
  • src/main/daemon/terminal-host.ts
  • src/main/daemon/terminal-modes.ts
  • src/main/daemon/terminal-snapshot.ts
  • src/main/daemon/types.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/ipc/ssh.test.ts
  • src/main/ipc/terminal-startup-color-query-replies.ts
  • src/main/providers/local-pty-provider.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/providers/pty-provider-events.ts
  • src/main/providers/ssh-pty-provider.test.ts
  • src/main/providers/ssh-pty-provider.ts
  • src/main/providers/types.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/ssh/ssh-relay-session-data-delivery.test.ts
  • src/main/ssh/ssh-relay-session-terminal-error.test.ts
  • src/main/ssh/ssh-relay-session.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/relay/pty-handler.test.ts
  • src/relay/pty-handler.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/pty-dispatcher.ts
  • src/renderer/src/runtime/remote-runtime-terminal-frame-drop-resync.test.ts
  • src/renderer/src/runtime/remote-runtime-terminal-multiplexer.ts
  • src/shared/pty-startup-ingress-intent.ts
  • src/shared/pty-startup-ingress.test.ts
  • src/shared/pty-startup-ingress.ts
  • src/shared/terminal-stream-protocol.ts

Comment on lines +26 to +29
const rawLengthBefore = last.sequenceChars ?? last.data.length - data.length
const combinedRawLength = rawLengthBefore + (options.rawLength ?? data.length)
last.sequenceChars = combinedRawLength === last.data.length ? undefined : combinedRawLength
last.seq = options.seq

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

seq is dropped on merge instead of being carried forward, in both the daemon and relay batching paths. Both implementations correctly accumulate rawLength/sequenceChars across merged writes (old value + new contribution), but neither does the equivalent for seq — it's only set when the current call explicitly provides one, otherwise it's discarded (daemon: reset to undefined; relay: left undefined on a fresh pending object). This can silently erase a previously-tracked absolute raw-stream position the moment an untracked write gets folded into a tracked entry, degrading the client's resync-detection fidelity for the merged output.

  • src/main/daemon/daemon-stream-data-entry.ts#L26-L29: change last.seq = options.seq to fall back to an extended prior value, e.g. last.seq = options.seq ?? (last.seq === undefined ? undefined : last.seq + data.length).
  • src/relay/pty-handler.ts#L697-L719: in the meta.seq === undefined branch, fall back similarly: pending.seq = existing?.seq === undefined ? undefined : existing.seq + data.length instead of leaving pending.seq unset.
📍 Affects 2 files
  • src/main/daemon/daemon-stream-data-entry.ts#L26-L29 (this comment)
  • src/relay/pty-handler.ts#L697-L719

Comment thread src/main/ipc/pty.ts
Comment on lines +2379 to 2381
...(rawLength !== data.length ? { rawLength } : {}),
...(transformed ? { transformed: true } : {}),
...(nextContainsBackgroundOutput ? { containsBackgroundOutput: true } : {})

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 | 🔴 Critical | ⚡ Quick win

Mark non-linear chunks as transformed to prevent slicing corruption.

When a new chunk is created with a non-linear byte-to-sequence mapping (rawLength !== data.length) but transformed is falsy, it is saved without transformed: true.
During flushPendingData, this chunk is not considered indivisible (since pending.transformed is not true) and gets sliced. The first slice incorrectly inherits the full original rawLength, while the remaining slice loses its raw length tracking entirely, permanently corrupting the sequence space.

Mirror the merge path (line 2387) by explicitly marking chunks as transformed: true whenever sequence preservation is broken.

🐛 Proposed fix
-        ...(rawLength !== data.length ? { rawLength } : {}),
-        ...(transformed ? { transformed: true } : {}),
+        ...(!preservesSeq || transformed ? { rawLength, transformed: true as const } : {}),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
...(rawLength !== data.length ? { rawLength } : {}),
...(transformed ? { transformed: true } : {}),
...(nextContainsBackgroundOutput ? { containsBackgroundOutput: true } : {})
...(!preservesSeq || transformed ? { rawLength, transformed: true as const } : {}),
...(nextContainsBackgroundOutput ? { containsBackgroundOutput: true } : {})

Comment thread src/main/ipc/pty.ts
Comment on lines +2765 to +2770
? {
seq: pending.startSeq + (pending.rawLength ?? nextData.length),
rawLength: pending.rawLength ?? nextData.length
}
: {}),
...(pending.transformed ? { transformed: true } : {}),

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 | 🔴 Critical | ⚡ Quick win

Use makePtyDataPayload to preserve rawLength when startSeq is undefined.

This inline object construction incorrectly omits rawLength if typeof pending.startSeq !== 'number'. If a chunk has a broken sequence tracking (startSeq is undefined) but contains a valid rawLength !== data.length (e.g., from a transformed gap), the renderer will fall back to using data.length for its internal calculation.

This discrepancy forces the renderer to send incorrect processedChars in its ACKs back to main, leading to an accounting wedge in rendererInFlightTotalChars. Using makePtyDataPayload guarantees rawLength is included even when startSeq is missing.

🐛 Proposed fix
-        sendPtyDataToRenderer(payload.id, {
-          id: payload.id,
-          data: nextData,
-          ...(typeof pending.startSeq === 'number'
-            ? {
-                seq: pending.startSeq + (pending.rawLength ?? nextData.length),
-                rawLength: pending.rawLength ?? nextData.length
-              }
-            : {}),
-          ...(pending.transformed ? { transformed: true } : {}),
-          ...(pending.containsBackgroundOutput === true ? { background: true } : {}),
-          ...(pending.droppedOutput === true ? { droppedOutput: true } : {})
-        })
+        const payloadToSend = makePtyDataPayload(
+          payload.id,
+          nextData,
+          pending.startSeq,
+          pending.containsBackgroundOutput,
+          pending.rawLength,
+          pending.transformed
+        )
+        if (pending.droppedOutput === true) {
+          payloadToSend.droppedOutput = true
+        }
+        sendPtyDataToRenderer(payload.id, payloadToSend)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
? {
seq: pending.startSeq + (pending.rawLength ?? nextData.length),
rawLength: pending.rawLength ?? nextData.length
}
: {}),
...(pending.transformed ? { transformed: true } : {}),
const payloadToSend = makePtyDataPayload(
payload.id,
nextData,
pending.startSeq,
pending.containsBackgroundOutput,
pending.rawLength,
pending.transformed
)
if (pending.droppedOutput === true) {
payloadToSend.droppedOutput = true
}
sendPtyDataToRenderer(payload.id, payloadToSend)

Comment on lines +100 to +110
onData({ id: 'ssh-pty-1', data: '', sequenceChars: 9, transformed: true })

expect(runtime.onPtyData).toHaveBeenCalledWith('ssh-pty-1', '', expect.any(Number), 9, true)
expect(mockWindow.webContents.send).toHaveBeenCalledWith('pty:data', {
id: 'ssh-pty-1',
data: '',
sequenceChars: 9,
transformed: true,
seq: 17,
rawLength: 9
})

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect the ssh-relay-session.ts onData handler to see how the outgoing
# 'pty:data' payload is constructed relative to sequenceChars/rawLength.
fd -e ts ssh-relay-session.ts --exclude '*.test.ts' | xargs -I{} ast-grep run --pattern 'onData($_, $BODY)' --lang typescript {}
rg -n -B3 -A15 "webContents\.send\('pty:data'" src/main/ssh/ssh-relay-session.ts

Repository: stablyai/orca

Length of output: 851


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== relevant source =="
sed -n '1128,1160p' src/main/ssh/ssh-relay-session.ts

echo
echo "== payload shape / type references =="
rg -n "sequenceChars|rawLength|pty:data|onData\\(" src/main src/renderer -g '!**/*.map'

echo
echo "== ssh relay tests =="
rg -n "sequenceChars|rawLength|pty:data" src/main/ssh -g '*.test.ts'

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== ssh-relay-session.ts snippet =="
sed -n '1138,1154p' src/main/ssh/ssh-relay-session.ts

echo
echo "== all sequenceChars/rawLength references =="
rg -n "sequenceChars|rawLength" src/main -g '!**/*.map'

Repository: stablyai/orca

Length of output: 21605


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== pty event types =="
sed -n '1,120p' src/main/providers/pty-provider-events.ts

echo
echo "== SSH relay tests that define expected payload shape =="
sed -n '130,220p' src/main/ssh/ssh-relay-session.test.ts

echo
echo "== SSH relay data delivery test =="
sed -n '80,120p' src/main/ssh/ssh-relay-session-data-delivery.test.ts

echo
echo "== renderer pty dispatcher event shape =="
sed -n '150,220p' src/renderer/src/components/terminal-pane/pty-dispatcher.ts

Repository: stablyai/orca

Length of output: 7770


Drop sequenceChars from the pty:data payload expectation. The SSH relay should match the renderer-facing contract used elsewhere: seq + rawLength, without forwarding the internal sequenceChars field.

…only-sometimes-new-codex-session-pri

# Conflicts:
#	src/main/daemon/daemon-server.ts
#	src/main/daemon/types.ts

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

🧹 Nitpick comments (1)
src/main/daemon/daemon-server.ts (1)

712-718: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add a brief comment explaining the connectionId: null constraint.

As per coding guidelines, when code is driven by a design document or non-obvious constraint, add a brief one- or two-line comment explaining why the behavior is necessary. Since the daemon strictly handles local PTYs, explicitly passing connectionId: null guarantees the validation treats the spawn as local, but this contextual assumption isn't immediately obvious.

Consider adding a standard // Why: comment here.

♻️ Proposed refactor
             startupIngress: parsePtyStartupIngressIntent(p.startupIngress, {
               allowWindowsEchoProjection: isNativeWindowsLocalPtySpawn({
+                // Why: Daemon PTYs are exclusively local; remote connections are managed by the main process or relay.
                 connectionId: null,
                 cwd: p.cwd,
                 shellOverride: p.shellOverride

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 0b0258c3-b97a-4c54-8954-83bf3c1278b8

📥 Commits

Reviewing files that changed from the base of the PR and between b1e0c30 and d2b7079.

📒 Files selected for processing (4)
  • src/main/daemon/daemon-protocol-version.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/daemon/daemon-server.ts
  • src/main/daemon/types.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/main/daemon/daemon-protocol-version.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/daemon/types.ts

@Jinwoo-H
Jinwoo-H merged commit c0f0810 into main Jul 20, 2026
9 checks passed
saeedrahimi pushed a commit to saeedrahimi/orca that referenced this pull request Jul 20, 2026
Upstream (stablyai#9500) appends the agent launch command after the OSC-133 bootstrap
inside PowerShell -EncodedCommand. Under ConstrainedLanguage (WDAC/AppLocker on
managed Windows) the bootstrap's top-level return guards abort the whole script
and swallow the launch, so a new Claude session opened pwsh but never ran claude.
Scope the bootstrap in & { } so its returns stay local and the command runs.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* Fix native Windows PTY startup query handling

* Fix daemon boot smoke protocol lookup

* Fix Windows daemon repro protocol lookup
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.

[Bug][windows-only]: Sometimes new Codex session prints raw OSC color escape sequences (]10;rgb / ]11;rgb) as text

1 participant