diff --git a/.github/workflows/homebrew-bump.yml b/.github/workflows/homebrew-bump.yml
new file mode 100644
index 000000000..9f1f37341
--- /dev/null
+++ b/.github/workflows/homebrew-bump.yml
@@ -0,0 +1,163 @@
+name: Homebrew Cask Bump
+
+# Why: keep the stablyai/homebrew-orca tap in sync with GitHub Releases.
+# Triggers:
+# - release.published with !prerelease → release workflow just finalized a
+# stable tag (see publish-release step in release.yml)
+# - workflow_call → release.yml finished publishing a stable tag
+# - workflow_dispatch → manual backfill for a specific tag
+#
+# The job computes the sha256 of orca-macos-arm64.dmg + orca-macos-x64.dmg
+# from the release, templates Casks/orca.rb in this repo with the new
+# version and hashes, then PRs the result into stablyai/homebrew-orca. It
+# does NOT run for -rc.* tags: the stable cask should only track GA.
+
+on:
+ workflow_call:
+ inputs:
+ tag:
+ description: Release tag to sync (e.g. v1.3.25)
+ required: true
+ type: string
+ release:
+ types: [published]
+ workflow_dispatch:
+ inputs:
+ tag:
+ description: Release tag to sync (e.g. v1.3.25)
+ required: true
+ type: string
+
+jobs:
+ bump-cask:
+ runs-on: ubuntu-latest
+ # Why: skip prereleases and RC tags. The stable cask tracks GA only; a
+ # beta channel would be a separate cask in a separate job.
+ if: >
+ inputs.tag != '' ||
+ (github.event.release.prerelease == false &&
+ !contains(github.event.release.tag_name, '-rc.'))
+ permissions:
+ contents: read
+ steps:
+ - name: Checkout orca
+ uses: actions/checkout@v4
+
+ - name: Resolve tag and version
+ id: tag
+ env:
+ RELEASE_TAG: ${{ github.event.release.tag_name }}
+ INPUT_TAG: ${{ inputs.tag }}
+ run: |
+ set -euo pipefail
+ if [[ -n "$INPUT_TAG" ]]; then
+ tag="$INPUT_TAG"
+ else
+ tag="$RELEASE_TAG"
+ fi
+ version="${tag#v}"
+ echo "tag=$tag" >>"$GITHUB_OUTPUT"
+ echo "version=$version" >>"$GITHUB_OUTPUT"
+
+ - name: Download DMGs and compute sha256
+ id: hash
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ TAG: ${{ steps.tag.outputs.tag }}
+ run: |
+ set -euo pipefail
+ mkdir -p dmgs
+ gh release download "$TAG" \
+ --repo "${{ github.repository }}" \
+ --pattern 'orca-macos-arm64.dmg' \
+ --pattern 'orca-macos-x64.dmg' \
+ --dir dmgs
+ arm=$(sha256sum dmgs/orca-macos-arm64.dmg | awk '{print $1}')
+ intel=$(sha256sum dmgs/orca-macos-x64.dmg | awk '{print $1}')
+ echo "arm=$arm" >>"$GITHUB_OUTPUT"
+ echo "intel=$intel" >>"$GITHUB_OUTPUT"
+
+ - name: Render updated cask file
+ env:
+ VERSION: ${{ steps.tag.outputs.version }}
+ ARM_SHA: ${{ steps.hash.outputs.arm }}
+ INTEL_SHA: ${{ steps.hash.outputs.intel }}
+ run: |
+ set -euo pipefail
+ python3 - <<'PY'
+ import os, re, pathlib
+ p = pathlib.Path("Casks/orca.rb")
+ src = p.read_text()
+ src = re.sub(r'version "[^"]+"',
+ f'version "{os.environ["VERSION"]}"', src, count=1)
+ src = re.sub(r'sha256 arm:\s*"[0-9a-f]+",\s*\n\s*intel:\s*"[0-9a-f]+"',
+ 'sha256 arm: "{arm}",\n intel: "{intel}"'.format(
+ arm=os.environ["ARM_SHA"],
+ intel=os.environ["INTEL_SHA"]),
+ src, count=1)
+ p.write_text(src)
+ print(src)
+ PY
+
+ # Why: reuse the existing buf0-bot GitHub App (also used by
+ # track-community-prs.yaml) instead of minting a new PAT. The app is
+ # installed org-wide, so it has access to stablyai/homebrew-orca
+ # automatically. GITHUB_TOKEN cannot push cross-repo; a short-lived
+ # installation token can.
+ - name: Generate buf0-bot token
+ id: app-token
+ uses: actions/create-github-app-token@v2
+ with:
+ app-id: 2590194
+ private-key: ${{ secrets.BUFO_BOT_PRIVATE_KEY }}
+ owner: stablyai
+ repositories: homebrew-orca
+
+ - name: Checkout tap
+ uses: actions/checkout@v4
+ with:
+ repository: stablyai/homebrew-orca
+ path: tap
+ token: ${{ steps.app-token.outputs.token }}
+
+ - name: Copy cask into tap and open PR
+ env:
+ GH_TOKEN: ${{ steps.app-token.outputs.token }}
+ VERSION: ${{ steps.tag.outputs.version }}
+ TAG: ${{ steps.tag.outputs.tag }}
+ run: |
+ set -euo pipefail
+ mkdir -p tap/Casks
+ cp Casks/orca.rb tap/Casks/orca.rb
+
+ cd tap
+ # Why: commit author must match the buf0-bot app so commits are
+ # attributed to the bot in the tap's history / PR UI.
+ git config user.name "buf0-bot[bot]"
+ git config user.email "252831055+buf0-bot[bot]@users.noreply.github.com"
+
+ if git diff --quiet; then
+ echo "Cask already up-to-date for $TAG; nothing to do."
+ exit 0
+ fi
+
+ branch="bump/orca-$VERSION"
+ git checkout -b "$branch"
+ git add Casks/orca.rb
+ git commit -m "orca $VERSION"
+ git push -u origin "$branch" --force
+
+ # Why: prefer --fill so the PR body matches the commit; fall back
+ # to a brief body if the PR already exists for this branch.
+ gh pr create \
+ --title "orca $VERSION" \
+ --body "Automated bump from stablyai/orca release $TAG." \
+ --base main \
+ --head "$branch" \
+ || gh pr edit "$branch" --title "orca $VERSION"
+
+ # Why: squash-merge immediately rather than --auto. The tap has no
+ # required checks or branch protection, and `gh pr merge --auto`
+ # only activates when there's something to wait on — on a repo
+ # with no gates it silently no-ops, leaving the PR open forever.
+ gh pr merge "$branch" --squash --delete-branch
diff --git a/.github/workflows/release-cut.yml b/.github/workflows/release-cut.yml
index 2a8159c92..a477e80e8 100644
--- a/.github/workflows/release-cut.yml
+++ b/.github/workflows/release-cut.yml
@@ -1,9 +1,9 @@
name: Cut Release
-# Why: single entry point for manually cutting a release from any ref.
-# Replaces the old local `pnpm release:*` scripts so releases are always
-# reproducible from CI and can never be accidentally tagged against an
-# uncommitted or non-main working tree.
+# Why: single entry point for manually and scheduled cutting releases.
+# Replaces the old local `pnpm release:*` scripts and the standalone scheduled
+# RC workflow so releases are always reproducible from CI and can never be
+# accidentally tagged against an uncommitted or non-main working tree.
#
# Flow:
# 1. Resolve `ref` to a SHA.
@@ -36,6 +36,17 @@ on:
required: false
type: string
default: main
+ dry_run:
+ description: Validate a scheduled-RC run without creating a tag
+ required: false
+ default: false
+ type: boolean
+ schedule:
+ # Why: GitHub scheduled workflows are not guaranteed to start exactly on
+ # time and can be delayed or dropped around high-load periods. We retry
+ # across the full target hour and dedupe per PT slot. Cron is UTC, so run
+ # during both PST and PDT equivalents and let the PT-hour gate decide.
+ - cron: '*/5 10,11,22,23 * * *'
permissions:
contents: write
@@ -49,12 +60,13 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 15
outputs:
- tag: ${{ steps.tag.outputs.tag }}
+ tag: ${{ steps.tag.outputs.tag || steps.version.outputs.recovered_tag }}
+ should_release: ${{ steps.window.outputs.allowed == 'true' && steps.existing.outputs.already_ran != 'true' && !(github.event_name == 'workflow_dispatch' && inputs.dry_run) }}
steps:
- name: Checkout ref
uses: actions/checkout@v4
with:
- ref: ${{ inputs.ref }}
+ ref: ${{ github.event_name == 'schedule' && 'main' || inputs.ref }}
fetch-depth: 0
- name: Setup Node.js
@@ -84,11 +96,90 @@ jobs:
echo "push_main=false" >>"$GITHUB_OUTPUT"
fi
+ - name: Compute RC slot
+ id: slot
+ run: |
+ slot=$(TZ=America/Los_Angeles date '+%Y-%m-%d-%H')
+ echo "value=$slot" >>"$GITHUB_OUTPUT"
+
+ - name: Validate PT release window
+ id: window
+ env:
+ EVENT_NAME: ${{ github.event_name }}
+ run: |
+ if [[ "$EVENT_NAME" != "schedule" ]]; then
+ echo "allowed=true" >>"$GITHUB_OUTPUT"
+ echo "reason=manual" >>"$GITHUB_OUTPUT"
+ exit 0
+ fi
+
+ pt_hour=$(TZ=America/Los_Angeles date '+%H')
+ pt_minute=$(TZ=America/Los_Angeles date '+%M')
+
+ # Why: GitHub may deliver a scheduled event long after the intended
+ # time, so delayed 4:16 AM runs must not cut the 3:00 AM release.
+ if [[ "$pt_hour" == "03" || "$pt_hour" == "15" ]]; then
+ echo "allowed=true" >>"$GITHUB_OUTPUT"
+ echo "reason=target_hour:${pt_hour}:${pt_minute}" >>"$GITHUB_OUTPUT"
+ exit 0
+ fi
+
+ echo "allowed=false" >>"$GITHUB_OUTPUT"
+ echo "reason=outside_target_hour:${pt_hour}:${pt_minute}" >>"$GITHUB_OUTPUT"
+
+ - name: Skip if this PT release window already ran
+ id: existing
+ if: github.event_name == 'schedule' && steps.window.outputs.allowed == 'true'
+ run: |
+ # Why: scheduled runs retry inside each target hour, so make the
+ # schedule idempotent by embedding a slot marker in the release commit.
+ if git log origin/main --grep="\\[rc-slot:${{ steps.slot.outputs.value }}\\]" -n 1 --format=%H | grep -q .; then
+ echo "already_ran=true" >>"$GITHUB_OUTPUT"
+ exit 0
+ fi
+
+ # Why: this preserves dedupe across the older scheduled workflow's
+ # first runs, before all RC cuts shared release-cut's slot marker.
+ latest_rc_tag="$(git for-each-ref --sort=-creatordate --format='%(refname:short) %(creatordate:iso-strict)' 'refs/tags/v*-rc.*' | head -n 1)"
+ if [[ -n "$latest_rc_tag" ]]; then
+ latest_rc_tag_name="${latest_rc_tag%% *}"
+ latest_rc_tag_date="${latest_rc_tag#* }"
+ latest_rc_slot="$(TZ=America/Los_Angeles date -d "$latest_rc_tag_date" '+%Y-%m-%d-%H')"
+
+ if [[ "$latest_rc_slot" == "${{ steps.slot.outputs.value }}" ]]; then
+ echo "already_ran=true" >>"$GITHUB_OUTPUT"
+ echo "reason=latest_rc_tag:$latest_rc_tag_name" >>"$GITHUB_OUTPUT"
+ exit 0
+ fi
+ fi
+
+ echo "already_ran=false" >>"$GITHUB_OUTPUT"
+
+ - name: Dry run summary
+ if: github.event_name == 'workflow_dispatch' && inputs.dry_run
+ run: |
+ echo "Dry run only."
+ echo "Current PT slot: ${{ steps.slot.outputs.value }}"
+ echo "Window allowed: ${{ steps.window.outputs.allowed }}"
+ echo "Window reason: ${{ steps.window.outputs.reason }}"
+ echo "Already ran this slot: ${{ steps.existing.outputs.already_ran }}"
+ echo "Reason: ${{ steps.existing.outputs.reason }}"
+
+ - name: Skip summary
+ if: steps.window.outputs.allowed != 'true' || steps.existing.outputs.already_ran == 'true'
+ run: |
+ echo "Skipping release cut."
+ echo "Current PT slot: ${{ steps.slot.outputs.value }}"
+ echo "Window reason: ${{ steps.window.outputs.reason }}"
+ echo "Already ran this slot: ${{ steps.existing.outputs.already_ran }}"
+ echo "Reason: ${{ steps.existing.outputs.reason }}"
+
- name: Compute next version
id: version
+ if: steps.window.outputs.allowed == 'true' && steps.existing.outputs.already_ran != 'true' && !(github.event_name == 'workflow_dispatch' && inputs.dry_run)
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- KIND: ${{ inputs.kind }}
+ KIND: ${{ github.event_name == 'schedule' && 'rc' || inputs.kind }}
run: |
set -euo pipefail
@@ -187,10 +278,53 @@ jobs:
;;
esac
- # Refuse tag collisions (possible if someone already tagged manually).
+ # Orphan-tag recovery.
+ #
+ # Why: if a previous cut pushed the tag but was cancelled (or the
+ # dependent release.yml job otherwise failed to start) before the
+ # GitHub Release was published, the tag now exists on the remote
+ # but "latest stable" still points at the prior version. Every
+ # subsequent patch cut then recomputes the same version and dies
+ # on "Tag already exists." This exact sequence wedged the cut
+ # pipeline on 2026-05-01 when v1.3.26 was pushed by a cancelled
+ # run (25237882049) — every patch cut after that rehit the same
+ # tag for hours until the orphan release was dispatched by hand.
+ #
+ # Recovery policy: if the tag exists AND no GitHub release has
+ # been published for it (draft-or-absent both count as "not
+ # shipped"), treat this as a resumable state: emit the existing
+ # tag as the job output so the downstream release.yml job runs
+ # against it and finishes what the earlier attempt started. The
+ # bump/commit/push steps are skipped in that case — there is
+ # nothing to bump; the tag is already on the remote.
+ #
+ # Refuse collisions only when the tag *and* a published release
+ # already exist — that's a real conflict (someone tagged manually
+ # over a shipped version) and needs human attention.
if git rev-parse "v$new" >/dev/null 2>&1; then
- echo "::error::Tag v$new already exists." >&2
- exit 1
+ # Use the REST API, not `gh release view`: the latter returns
+ # "release not found" for drafts *and* for absent releases,
+ # which would cause us to "recover" over a draft that a human
+ # is preparing. The API distinguishes them.
+ release_state="$(gh api \
+ "repos/$GITHUB_REPOSITORY/releases/tags/v$new" \
+ --jq '.draft' 2>/dev/null || echo "missing")"
+ case "$release_state" in
+ missing|true)
+ echo "::warning::Tag v$new already exists but no published release is attached — recovering by re-dispatching release.yml against the existing tag."
+ echo "recovered_tag=v$new" >>"$GITHUB_OUTPUT"
+ echo "recovered=true" >>"$GITHUB_OUTPUT"
+ exit 0
+ ;;
+ false)
+ echo "::error::Tag v$new already exists and has a published release. Refusing to re-cut over a shipped version." >&2
+ exit 1
+ ;;
+ *)
+ echo "::error::Unexpected release state for v$new: $release_state" >&2
+ exit 1
+ ;;
+ esac
fi
echo "version=$new" >>"$GITHUB_OUTPUT"
@@ -198,7 +332,10 @@ jobs:
- name: Bump package.json and tag
id: tag
+ if: steps.version.outputs.version != '' && steps.version.outputs.recovered != 'true'
env:
+ EVENT_NAME: ${{ github.event_name }}
+ SLOT: ${{ steps.slot.outputs.value }}
VERSION: ${{ steps.version.outputs.version }}
run: |
set -euo pipefail
@@ -207,12 +344,17 @@ jobs:
# assumptions and any lifecycle scripts that would run on bump).
npm version "$VERSION" --no-git-tag-version --allow-same-version
git add package.json
- git commit -m "release: v$VERSION"
+ commit_message="release: v$VERSION"
+ if [[ "$EVENT_NAME" == "schedule" ]]; then
+ commit_message="$commit_message [rc-slot:$SLOT]"
+ fi
+ git commit -m "$commit_message"
git tag -a "v$VERSION" -m "v$VERSION"
echo "tag=v$VERSION" >>"$GITHUB_OUTPUT"
echo "sha=$(git rev-parse HEAD)" >>"$GITHUB_OUTPUT"
- name: Push tag
+ if: steps.tag.outputs.tag != ''
env:
PUSH_MAIN: ${{ steps.resolve.outputs.push_main }}
TAG: ${{ steps.tag.outputs.tag }}
@@ -229,6 +371,7 @@ jobs:
release:
needs: cut
+ if: needs.cut.outputs.should_release == 'true'
uses: ./.github/workflows/release.yml
with:
tag: ${{ needs.cut.outputs.tag }}
diff --git a/.github/workflows/release-rc.yml b/.github/workflows/release-rc.yml
deleted file mode 100644
index 3ebdc8c2b..000000000
--- a/.github/workflows/release-rc.yml
+++ /dev/null
@@ -1,157 +0,0 @@
-name: Schedule RC Release
-
-on:
- workflow_dispatch:
- inputs:
- dry_run:
- description: Validate the workflow without creating an RC version or tag
- required: false
- default: false
- type: boolean
- schedule:
- # Why: GitHub scheduled workflows are not guaranteed to start exactly on
- # time and can be delayed or dropped around high-load periods. We retry
- # across the full target hour and dedupe per PT slot.
- - cron: '*/5 3,15 * * *'
- timezone: 'America/Los_Angeles'
-
-permissions:
- contents: write
-
-concurrency:
- group: release-rc
- cancel-in-progress: false
-
-jobs:
- create-rc-tag:
- runs-on: ubuntu-latest
- timeout-minutes: 15
- outputs:
- tag: ${{ steps.version.outputs.tag }}
- should_release: ${{ steps.window.outputs.allowed == 'true' && steps.existing.outputs.already_ran != 'true' && !(github.event_name == 'workflow_dispatch' && inputs.dry_run) }}
-
- steps:
- - name: Checkout
- uses: actions/checkout@v4
- with:
- ref: main
- fetch-depth: 0
-
- - name: Setup Node.js
- uses: actions/setup-node@v4
- with:
- node-version-file: package.json
-
- - name: Configure git author
- run: |
- git config user.name "github-actions[bot]"
- git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
-
- - name: Sync with latest main
- run: |
- git fetch origin main --tags
- git checkout main
- git reset --hard origin/main
-
- - name: Compute RC slot
- id: slot
- run: |
- slot=$(TZ=America/Los_Angeles date '+%Y-%m-%d-%H')
- echo "value=$slot" >>"$GITHUB_OUTPUT"
-
- - name: Validate PT release window
- id: window
- env:
- EVENT_NAME: ${{ github.event_name }}
- run: |
- if [[ "$EVENT_NAME" == "workflow_dispatch" ]]; then
- echo "allowed=true" >>"$GITHUB_OUTPUT"
- echo "reason=manual" >>"$GITHUB_OUTPUT"
- exit 0
- fi
-
- pt_hour=$(TZ=America/Los_Angeles date '+%H')
- pt_minute=$(TZ=America/Los_Angeles date '+%M')
-
- # Why: GitHub may deliver a scheduled event long after the intended
- # time. We only allow scheduled RC releases during the exact target
- # PT hours so a delayed run at 4:16 AM never creates a release that
- # was intended for 3:00 AM.
- if [[ "$pt_hour" == "03" || "$pt_hour" == "15" ]]; then
- echo "allowed=true" >>"$GITHUB_OUTPUT"
- echo "reason=target_hour:${pt_hour}:${pt_minute}" >>"$GITHUB_OUTPUT"
- exit 0
- fi
-
- echo "allowed=false" >>"$GITHUB_OUTPUT"
- echo "reason=outside_target_hour:${pt_hour}:${pt_minute}" >>"$GITHUB_OUTPUT"
-
- - name: Skip if this PT release window already ran
- id: existing
- if: steps.window.outputs.allowed == 'true'
- run: |
- # Why: GitHub can delay or drop schedule events, especially near the
- # start of the hour. We schedule multiple attempts inside each target
- # PT hour and make the release idempotent per hour by embedding a
- # slot marker in the release commit message.
- if git log origin/main --grep="\\[rc-slot:${{ steps.slot.outputs.value }}\\]" -n 1 --format=%H | grep -q .; then
- echo "already_ran=true" >>"$GITHUB_OUTPUT"
- exit 0
- fi
-
- # Why: the first scheduled run today used the earlier workflow before
- # slot markers existed. Keep a tag-time fallback so retries in the
- # same PT hour still skip if an RC tag was already created.
- latest_rc_tag="$(git for-each-ref --sort=-creatordate --format='%(refname:short) %(creatordate:iso-strict)' 'refs/tags/v*-rc.*' | head -n 1)"
- if [[ -n "$latest_rc_tag" ]]; then
- latest_rc_tag_name="${latest_rc_tag%% *}"
- latest_rc_tag_date="${latest_rc_tag#* }"
- latest_rc_slot="$(TZ=America/Los_Angeles date -d "$latest_rc_tag_date" '+%Y-%m-%d-%H')"
-
- if [[ "$latest_rc_slot" == "${{ steps.slot.outputs.value }}" ]]; then
- echo "already_ran=true" >>"$GITHUB_OUTPUT"
- echo "reason=latest_rc_tag:$latest_rc_tag_name" >>"$GITHUB_OUTPUT"
- exit 0
- fi
- fi
-
- echo "already_ran=false" >>"$GITHUB_OUTPUT"
-
- - name: Dry run summary
- if: github.event_name == 'workflow_dispatch' && inputs.dry_run
- run: |
- echo "Dry run only."
- echo "Current PT slot: ${{ steps.slot.outputs.value }}"
- echo "Window allowed: ${{ steps.window.outputs.allowed }}"
- echo "Window reason: ${{ steps.window.outputs.reason }}"
- echo "Already ran this slot: ${{ steps.existing.outputs.already_ran }}"
- echo "Reason: ${{ steps.existing.outputs.reason }}"
-
- - name: Skip summary
- if: steps.window.outputs.allowed != 'true'
- run: |
- echo "Skipping scheduled RC release."
- echo "Current PT slot: ${{ steps.slot.outputs.value }}"
- echo "Reason: ${{ steps.window.outputs.reason }}"
-
- - name: Create and push RC tag
- id: version
- if: steps.window.outputs.allowed == 'true' && steps.existing.outputs.already_ran != 'true' && !(github.event_name == 'workflow_dispatch' && inputs.dry_run)
- env:
- GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- run: |
- # Why: pushes made with GITHUB_TOKEN do not reliably trigger other
- # workflows via push events. The RC workflow invokes release.yml
- # directly after creating the tag, so the actual Electron release
- # runs inside this scheduled flow instead of depending on push.
- new_tag="$(npm version prerelease --preid=rc -m "release: %s [rc-slot:${{ steps.slot.outputs.value }}]")"
- git push origin main --follow-tags
- echo "tag=$new_tag" >>"$GITHUB_OUTPUT"
-
- release-rc:
- needs: create-rc-tag
- if: needs.create-rc-tag.outputs.should_release == 'true'
- uses: ./.github/workflows/release.yml
- with:
- tag: ${{ needs.create-rc-tag.outputs.tag }}
- secrets: inherit
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index bda260be9..1706afbc9 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -245,3 +245,13 @@ jobs:
--draft=false \
--prerelease="$prerelease" \
--repo "$GITHUB_REPOSITORY"
+
+ homebrew-bump:
+ needs:
+ - resolve-release
+ - publish-release
+ if: ${{ !contains(needs.resolve-release.outputs.tag, '-rc.') }}
+ uses: ./.github/workflows/homebrew-bump.yml
+ with:
+ tag: ${{ needs.resolve-release.outputs.tag }}
+ secrets: inherit
diff --git a/AGENTS.md b/AGENTS.md
index 44863f549..683b216a3 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -22,6 +22,10 @@ Orca targets macOS, Linux, and Windows. Keep all platform-dependent behavior beh
- **Shortcut labels in UI**: Display `⌘` / `⇧` on Mac and `Ctrl+` / `Shift+` on other platforms.
- **File paths**: Use `path.join` or Electron/Node path utilities — never assume `/` or `\`.
+## SSH Use Case
+
+All changes must consider the SSH use case. Don't assume local-only execution.
+
## GitHub CLI Usage
Be mindful of the user's `gh` CLI API rate limit — batch requests where possible and avoid unnecessary calls. All code, commands, and scripts must be compatible with macOS, Linux, and Windows.
diff --git a/Casks/orca.rb b/Casks/orca.rb
new file mode 100644
index 000000000..43a93af5d
--- /dev/null
+++ b/Casks/orca.rb
@@ -0,0 +1,41 @@
+cask "orca" do
+ arch arm: "arm64", intel: "x64"
+
+ version "1.3.24"
+ sha256 arm: "fc707f290ff3b631b7b7947bf339885b61a43d2e89475997c125b61268ed4966",
+ intel: "5f677c13a08f7a5740442e29d388285a86488c8c1f7aa5f10a8721a2c6ede8e4"
+
+ url "https://github.com/stablyai/orca/releases/download/v#{version}/orca-macos-#{arch}.dmg",
+ verified: "github.com/stablyai/orca/"
+ name "Orca"
+ desc "IDE for orchestrating AI coding agents across terminals and worktrees"
+ homepage "https://onorca.dev/"
+
+ livecheck do
+ url :url
+ strategy :github_latest
+ end
+
+ # Why: electron-updater (src/main/updater.ts) handles in-place updates by
+ # writing a new Orca.app into /Applications. Marking the cask auto_updates
+ # tells Homebrew not to compete with the in-app updater — `brew upgrade`
+ # becomes a no-op unless the user passes --greedy, and brew's version
+ # metadata stays aligned with whatever the app has swapped itself to.
+ auto_updates true
+ depends_on macos: ">= :big_sur"
+
+ app "Orca.app"
+
+ # Why: Orca writes user data under ~/.orca (worktrees, agent state) and
+ # Electron's standard userData directories. Zap removes everything the app
+ # creates during normal use so `brew uninstall --zap` is a clean slate.
+ zap trash: [
+ "~/.orca",
+ "~/Library/Application Support/Orca",
+ "~/Library/Caches/com.stablyai.orca",
+ "~/Library/Caches/com.stablyai.orca.ShipIt",
+ "~/Library/HTTPStorages/com.stablyai.orca",
+ "~/Library/Preferences/com.stablyai.orca.plist",
+ "~/Library/Saved Application State/com.stablyai.orca.savedState",
+ ]
+end
diff --git a/README.md b/README.md
index 5c78431ac..e5624925d 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,6 @@
-
-
-
-
-Orca
+
+ Orca
+
@@ -21,7 +19,7 @@
- Download at onOrca.dev
+ Download 🐋
@@ -30,7 +28,7 @@
## Supported Agents
-Orca supports any CLI agent (_not just this list_).
+Orca supports any CLI agent (*not just this list*).
Claude Code
@@ -49,7 +47,7 @@ Orca supports any CLI agent (_not just this list_).
Cursor
Droid
GitHub Copilot
- Kilocode
+ Kilocode
Kimi
Kiro
Mistral Vibe
@@ -73,8 +71,28 @@ Orca supports any CLI agent (_not just this list_).
## Install
+### Mac, Linux, Windows
+
- **[Download from onOrca.dev](https://onOrca.dev)**
-- Or download the latest binaries via the **[GitHub Releases page](https://github.com/stablyai/orca/releases)**.
+- Or via **[GitHub Releases page](https://github.com/stablyai/orca/releases/latest)**
+
+*Alternatively, install from a package manager:*
+
+### macOS (Homebrew)
+
+```bash
+brew install --cask stablyai/orca/orca
+```
+
+### Arch Linux (AUR)
+
+```bash
+# Precompiled binary
+yay -S stably-orca-bin
+
+# Build from GitHub source
+yay -S stably-orca-git
+```
---
@@ -137,4 +155,4 @@ npx skills add https://github.com/stablyai/orca --skill orca-cli
## Developing
-Want to contribute or run locally? See our [CONTRIBUTING.md](CONTRIBUTING.md) guide.
+Want to contribute or run locally? See our [CONTRIBUTING.md](.github/CONTRIBUTING.md) guide.
diff --git a/agent-nesting-options.html b/agent-nesting-options.html
new file mode 100644
index 000000000..5045e30db
--- /dev/null
+++ b/agent-nesting-options.html
@@ -0,0 +1,314 @@
+
+
+
+
+ Agent nesting — design options
+
+
+
+
+
+
+
+
+
+
+ A. Vertical rail
+ Single left rail anchors agents to the parent. No inner card, no divider. Icons 12px.
+
+
+
+
+
+ fix-notification-suites
+
+
+
+ stably
+
+ fix-notification-suites
+
+
drafted agent-row redesign mockup at agent-row-design.html
+
+
+
+
+ Agents · 2
+
+
+
+
+
+
+
+
+ how likely it is to aff…
+ 8m
+
+
Who runs into the behavior change
+
+
+
+
+
+
fix low-severity spam
+
just now
+
+
+
+
+
+
+
+
+
+ B. Flush rows, dot-only status
+ Drop the agent avatar entirely. Status dot (6px) + title is enough. Indented 12px.
+
+
+
+
+ fix-notification-suites
+
+
+
+ stably
+
+ fix-notification-suites
+
+
drafted agent-row redesign mockup at agent-row-design.html
+
+
+
+ Agents
+ 2
+
+
+
+
+ Implement docs/peek
+ 8m
+
+
+
+
+ fix low-severity spam
+ now
+
+
+
+
+
+
+
+
+
+ C. Inset panel
+ Agents live in a slightly darker recessed block — feels like a drawer, not a card-in-card.
+
+
+
+
+ fix-notification-suites
+
+
+
+ stably
+
+ fix-notification-suites
+
+
drafted agent-row redesign mockup at agent-row-design.html
+
+
+
+
+
+
+ how likely it is to aff…
+ 8m
+
+
+
+
+
+
+
fix low-severity spam
+
now
+
+
+
+
+
+
+
+
+
+ D. Inline summary row
+ Default state is a compact one-line summary. Click to expand. Reduces visual noise when scrolling.
+
+
+
+
+ fix-notification-suites
+
+
+
+ stably
+
+ fix-notification-suites
+
+
drafted agent-row redesign mockup at agent-row-design.html
+
+
+
+
+
+
+
+ 2 agents · 1 running
+
+
+
+
+
+
Expanded state
+
+
+
+ how likely it is to aff…
+ 8m
+
+
+
+
+
+
fix low-severity spam
+
now
+
+
+
+
+
+
+
+
+
+
+ E. Tree branch
+ Explicit hierarchy via L-connectors. Works well when nesting could grow deeper.
+
+
+
+
+ fix-notification-suites
+
+
+
+ stably
+
+ fix-notification-suites
+
+
drafted agent-row redesign mockup at agent-row-design.html
+
+
+
+
+ Agents · 2
+
+
+
+
+
+
+
+
how likely it is to aff…
+
8m
+
+
+
+
+
+
+
+
fix low-severity spam
+
now
+
+
+
+
+
+
+
+
+
+
+ F. Stacked pills
+ Agents feel like chips anchored to the task. Good for 1–3 agents. Compact vertical footprint.
+
+
+
+
+ fix-notification-suites
+
+
+
+ stably
+
+ fix-notification-suites
+
+
drafted agent-row redesign mockup at agent-row-design.html
+
+
+
+
+ how likely it is to aff…
+ 8m
+
+
+
+
+
+
fix low-severity spam
+
now
+
+
+
+
+
+
+
+
+
+
What changed across every option
+
+ Agent avatar shrunk: 14px sparkle → 11–12px status glyph. In most options the vendor sparkle is removed entirely; the state glyph carries the signal.
+ No card-in-card. The inner "AGENTS" box with its own border is replaced by a rail, divider, inset panel, tree, or bare list.
+ Indent aligned under the task title, not offset between icons.
+ Row height: 22–24px instead of 30+.
+
+
+
My pick
+
A (rail) or B (flush + dot-only) . A still communicates "these belong to the parent" visually. B is the leanest — best if users rarely need to distinguish agent vendor at the child level.
+
+
+
diff --git a/agent-nesting-stacked.html b/agent-nesting-stacked.html
new file mode 100644
index 000000000..e0380d1ad
--- /dev/null
+++ b/agent-nesting-stacked.html
@@ -0,0 +1,499 @@
+
+
+
+
+ Worktree cards — stacked list
+
+
+
+
+
+
+
+
+
+
+
+ A. Vertical rail
+ Card breaks appear where agents exist.
+
+
+
+
+
+
+
+ master
+ primary
+
+
+ orca-internal
+ master
+
+
+
+
+
+
+
+ orca-internal
+ master
+
+
switched x-automation home-timeline fetch to @JinjingLiang…
+
+
+
+ Agents · 1
+
+
+
+
+
+
+
+
rebase remote and…
+
3m
+
+
Rebased onto origin/master (resolved…
+
+
+
+
+
+
+
+ main
+ primary
+
+
+ jinjing-work
+ main
+
+
finished email triage (processed 35 new emails)…
+
+
+
+
+
+
+ fix-notification-suites
+
+
+ stably
+ fix-notification-suites
+
+
+
+
+ Agents · 2
+
+
+
+
+
+ how likely it is to aff…
+ 8m
+
+
+
+
+
+
fix low-severity spam
+
now
+
+
+
+
+
+
+
+
+ improve-agent-status-style
+
+
+ orca
+ improve-agent-status-style
+
+
drafted agent-row redesign mockup at agent-row-design.html…
+
+
+
+
+
+
+ feat/full-suite-name-…
+ primary
+
+
+ stably
+ feat/full-suite-name-and-o…
+
+
+
+ PR #153 feat(reporter): remove run…
+
+
+
+
+
+
+
+
+
+
+ B. Flush + dot-only
+ No sparkle icons; status dot is enough.
+
+
+
+
+
+
+ master
+ primary
+
+
+ orca-internal
+ master
+
+
+
+
+
+
+ orca-internal
+ master
+
+
switched x-automation home-timeline fetch to @JinjingLiang…
+
+
+ Agents
+ 1
+
+
+
+ rebase remote and…
+ 3m
+
+
+
+
+
+
+
+ main
+ primary
+
+
+ jinjing-work
+ main
+
+
finished email triage (processed 35 new emails)…
+
+
+
+
+
+ fix-notification-suites
+
+
+ stably
+ fix-notification-suites
+
+
+
+ Agents
+ 2
+
+
+
+ how likely it is to aff…
+ 8m
+
+
+
+ fix low-severity spam
+ now
+
+
+
+
+
+
+
+ improve-agent-status-style
+
+
+ orca
+ improve-agent-status-style
+
+
drafted agent-row redesign mockup at agent-row-design.html…
+
+
+
+
+
+ feat/full-suite-name-…
+ primary
+
+
+ stably
+ feat/full-suite-name-and-o…
+
+
PR #153 feat(reporter): remove run…
+
+
+
+
+
+
+
+
+ D. Inline summary
+ Agents collapse to one line; click to expand.
+
+
+
+
+
+
+ master
+ primary
+
+
+ orca-internal
+ master
+
+
+
+
+
+
+ orca-internal
+ master
+
+
switched x-automation home-timeline fetch to @JinjingLiang…
+
+
+
+
+ 1 agent · done
+
+
+
+
+
+
+
+ main
+ primary
+
+
+ jinjing-work
+ main
+
+
finished email triage (processed 35 new emails)…
+
+
+
+
+
+
+ fix-notification-suites
+
+
+ stably
+ fix-notification-suites
+
+
+
+
+
+
+ 2 agents · 1 running
+
+
+
+
+
+ how likely it is to aff…
+ 8m
+
+
+
+
+
+
fix low-severity spam
+
now
+
+
+
+
+
+
+
+ improve-agent-status-style
+
+
+ orca
+ improve-agent-status-style
+
+
drafted agent-row redesign mockup at agent-row-design.html…
+
+
+
+
+
+ feat/full-suite-name-…
+ primary
+
+
+ stably
+ feat/full-suite-name-and-o…
+
+
PR #153 feat(reporter): remove run…
+
+
+
+
+
+
+
+
+ G. Merged card
+ Agent rows become peer children of the card. No label, no divider.
+
+
+
+
+
+
+ master
+ primary
+
+
+ orca-internal
+ master
+
+
+
+
+
+
+ orca-internal
+ master
+
+
switched x-automation home-timeline fetch to @JinjingLiang…
+
+
+
+
+
+
rebase remote and…
+
3m
+
+
+
+
+
+
+
+ main
+ primary
+
+
+ jinjing-work
+ main
+
+
finished email triage (processed 35 new emails)…
+
+
+
+
+
+ fix-notification-suites
+
+
+ stably
+ fix-notification-suites
+
+
+
+
+ how likely it is to aff…
+ 8m
+
+
+
+
+
+
fix low-severity spam
+
now
+
+
+
+
+
+
+
+ improve-agent-status-style
+
+
+ orca
+ improve-agent-status-style
+
+
drafted agent-row redesign mockup at agent-row-design.html…
+
+
+
+
+
+ feat/full-suite-name-…
+ primary
+
+
+ stably
+ feat/full-suite-name-and-o…
+
+
PR #153 feat(reporter): remove run…
+
+
+
+
+
+
+
+
Scan test
+
With a stack of 6 cards: B and G scan fastest — uniform card height, agents feel like part of the task. A adds one extra visual feature (rail) that reads as deliberate hierarchy. D wins when lists get long (20+ worktrees) — agents stay one line until you care.
+
+
+
+
diff --git a/agent-row-design.html b/agent-row-design.html
new file mode 100644
index 000000000..207f08d23
--- /dev/null
+++ b/agent-row-design.html
@@ -0,0 +1,224 @@
+
+
+
+
+ Agent row — spacing polish only
+
+
+
+
+
+
+
+
+ Before
+
+
+
+
+
+
Revert pushed as 610ffbadb2. Gate the migration behind flag.
+
+
+
+
+
+
+
+ After — spacing only
+
+
+
+
+
+
+
+ Agents (5)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
implement retry logic for websocket disconnects
+
+ 12s
+
+
+
+
+
+
+
+
+
+
+
Bash
+
pnpm test src/ws/*.test.ts --watch
+
+
+
+
+
+
+
+
+
+
+
+
+
Revert pushed as 610ffbadb2. Gate the migration.
+
2m
+
+
Post-deploy health check passed; ready for review.
+
+
+
+
+
+
+
+
+
+
+
+
Approve running rm -rf dist/?
+
just now
+
+
Waiting for your input
+
+
+
+
+
+
+
+
+
+
+
+
local.env points to staging
+
interrupted
+
8m
+
+
Post-deploy health check (last 45 minutes)
+
+
+
+
+
+
+
+
+
+
+
+
Idle
+
1h
+
+
+
+
+
+
+
+ Dark
+
+
+
+
+
+
+
+
+
implement retry logic for websocket disconnects
+
12s
+
+
+
+
Bash
+
pnpm test src/ws/*.test.ts --watch
+
+
+
+
+
+
+
+
+
+
Revert pushed as 610ffbadb2. Gate the migration.
+
2m
+
+
Post-deploy health check passed; ready for review.
+
+
+
+
+
+
+
Approve running rm -rf dist/?
+
just now
+
+
Waiting for your input
+
+
+
+
+
+
+
+ Spacing diff
+
+ Row padding py-0.5 px-1 → py-1.5 px-2. Rows breathe.
+ Inner gap gap-1.5 → gap-2. State dot and agent icon no longer collide.
+ State slot normalized to h-3 w-3; agent icon stays 14px — consistent left edge.
+ Subtitle indent pl-5 → pl-[26px] to line up under the agent icon, not between the two glyphs.
+ Title leading-[18px], subtitle leading-[16px]. Fixes cramped leading-snug on 10–11px text.
+ Dividers removed; hover background separates rows.
+ Always-on dismiss/expand glyphs → hover-only, with 2px chip padding for a real 24×24 hit target.
+ Title weight: font-semibold text-foreground when unvisited or needs-attention, text-muted-foreground normal when read — stops read rows from shouting.
+
+
+
+
+
diff --git a/config/patches/node-pty@1.1.0.patch b/config/patches/node-pty@1.1.0.patch
index d3b5ebbd5..4ff713f6c 100644
--- a/config/patches/node-pty@1.1.0.patch
+++ b/config/patches/node-pty@1.1.0.patch
@@ -73,3 +73,18 @@ index 1ec12f796a822c78fba9ad7f6448c3987e325c23..cec8b67aef02f8199e5606a0d257088b
var DEFAULT_FILE = 'sh';
var DEFAULT_NAME = 'xterm';
var DESTROY_SOCKET_TIMEOUT_MS = 200;
+diff --git a/src/unix/pty.cc b/src/unix/pty.cc
+index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..c17decbb7bc06f10d7b5d26317bd68fdc8c4e339 100644
+--- a/src/unix/pty.cc
++++ b/src/unix/pty.cc
+@@ -778,8 +778,8 @@ done:
+ posix_spawn_file_actions_destroy(&acts);
+ posix_spawnattr_destroy(&attrs);
+
+- for (; count > 0; count--) {
+- close(low_fds[count]);
++ for (size_t i = 0; i <= count && i < 3; i++) {
++ close(low_fds[i]);
+ }
+ }
+ #endif
diff --git a/docs/README.es.md b/docs/README.es.md
index a539a2f81..ed58550d2 100644
--- a/docs/README.es.md
+++ b/docs/README.es.md
@@ -1,13 +1,11 @@
-
-
-
-
-Orca
+
+ Orca
+
-
+
-
+
@@ -16,21 +14,21 @@
El orquestador de IA para desarrolladores 100x.
- Corre Claude Code, Codex u OpenCode en paralelo a lo largo de varios repos — cada uno en su propio worktree, todos administrados desde un solo lugar.
+ Ejecuta Claude Code, Codex u OpenCode en paralelo entre repositorios — cada uno en su propio worktree, todo administrado desde un solo lugar.
Disponible para macOS, Windows y Linux .
- Descarga en onOrca.dev
+ Descargar 🐋
-
+
## Agentes compatibles
-Orca es compatible con cualquier agente CLI (_no solo los de esta lista_).
+Orca es compatible con cualquier agente CLI (*no solo los de esta lista*).
Claude Code
@@ -49,7 +47,7 @@ Orca es compatible con cualquier agente CLI (_no solo los de esta lista_).
Cursor
Droid
GitHub Copilot
- Kilocode
+ Kilocode
Kimi
Kiro
Mistral Vibe
@@ -63,18 +61,38 @@ Orca es compatible con cualquier agente CLI (_no solo los de esta lista_).
- **Sin login** — Usa tu propia suscripción de Claude Code o Codex.
- **Nativo con worktrees** — Cada feature vive en su propio worktree. Nada de stash ni malabares entre ramas. Crea y cambia al instante.
-- **Terminales multi-agente** — Corre varios agentes de IA en paralelo en pestañas y paneles. Mira de un vistazo cuáles están activos.
+- **Terminales multi-agente** — Ejecuta varios agentes de IA en paralelo en pestañas y paneles. Mira de un vistazo cuáles están activos.
- **Control de versiones integrado** — Revisa los diffs generados por IA, haz ediciones rápidas y haz commit sin salir de Orca.
- **Integración con GitHub** — PRs, issues y checks de Actions vinculados automáticamente a cada worktree.
+- **Soporte SSH** — Conéctate a máquinas remotas y ejecuta agentes en ellas directamente desde Orca.
- **Notificaciones** — Entérate cuando un agente termine o necesite tu atención. Marca hilos como no leídos para retomarlos después.
-- **Soporte SSH** — Conéctate a máquinas remotas y corre agentes en ellas directamente desde Orca.
---
## Instalación
+### Mac, Linux, Windows
+
- **[Descarga desde onOrca.dev](https://onOrca.dev)**
-- O descarga los binarios más recientes desde la **[página de GitHub Releases](https://github.com/stablyai/orca/releases)**.
+- O desde la **[página de GitHub Releases](https://github.com/stablyai/orca/releases/latest)**
+
+*También puedes instalar desde un gestor de paquetes:*
+
+### macOS (Homebrew)
+
+```bash
+brew install --cask stablyai/orca/orca
+```
+
+### Arch Linux (AUR)
+
+```bash
+# Binario precompilado
+yay -S stably-orca-bin
+
+# Compilar desde el código de GitHub
+yay -S stably-orca-git
+```
---
@@ -85,7 +103,7 @@ Orca es compatible con cualquier agente CLI (_no solo los de esta lista_).
Anota cualquier línea de un diff generado por IA con tus comentarios y mándalo de vuelta al agente para que lo corrija. Mantén el ciclo de revisión bien ajustado — sin copiar números de línea, sin cambiar de contexto.
-
+
---
@@ -97,19 +115,19 @@ Anota cualquier línea de un diff generado por IA con tus comentarios y mándalo
Si usas varias cuentas de Codex para aprovechar el mejor precio en tokens, Orca te permite cambiar entre ellas al instante — sin volver a hacer login, sin tocar archivos de configuración. Elige una cuenta y sigue construyendo.
-
+
---
-## [Nuevo] Navegador y modo diseño por worktree
+## [Nuevo] Navegador por worktree y modo diseño
-**Mira tu app. Haz clic en cualquier elemento. Arrástralo al chat.**
+**Mira tu app. Haz clic en cualquier elemento. Suéltalo en el chat.**
Orca trae un navegador integrado dentro de tu worktree. Previsualiza tu app mientras la construyes, y cuando quieras cambia al modo diseño — haz clic en cualquier elemento de UI y cae directo en tu chat con la IA como contexto. Sin capturas, sin copiar selectores. Solo apunta a lo que quieres cambiar y dile al agente qué hacer.
-
+
---
@@ -137,4 +155,4 @@ npx skills add https://github.com/stablyai/orca --skill orca-cli
## Desarrollo
-¿Quieres contribuir o ejecutar Orca localmente? Consulta nuestra guía [CONTRIBUTING.md](CONTRIBUTING.md).
+¿Quieres contribuir o ejecutar Orca localmente? Consulta nuestra guía [CONTRIBUTING.md](../.github/CONTRIBUTING.md).
diff --git a/docs/README.ja.md b/docs/README.ja.md
index 859442237..d92b0c2f3 100644
--- a/docs/README.ja.md
+++ b/docs/README.ja.md
@@ -1,14 +1,11 @@
-
-
-
-
-Orca
+
+ Orca
+
-
-
-
-
+
+
+
@@ -16,22 +13,22 @@
- 100x 開発者のための AI IDE。
- Claude Code、Codex、または OpenCode をリポジトリをまたいで並行して実行 — 各エージェントは独立したワークツリーで実行され、1 つの場所で集中管理されます。
- macOS、Windows、Linux で利用可能です。
+ 100x ビルダーのための AI オーケストレーター。
+ Claude Code、Codex、OpenCode をリポジトリをまたいで並行実行 — それぞれを専用のワークツリーで動かし、1 か所で追跡できます。
+ macOS、Windows、Linux で利用できます。
- onOrca.dev でダウンロード
+ ダウンロード 🐋
-
+
-## 対応する AI Agent
+## 対応するエージェント
-Orca は任意の CLI Agent に対応しています(_このリストに限定されません_)。
+Orca は任意の CLI エージェントに対応しています(*このリストに限定されません*)。
Claude Code
@@ -50,7 +47,7 @@ Orca は任意の CLI Agent に対応しています(_このリストに限定
Cursor
Droid
GitHub Copilot
- Kilocode
+ Kilocode
Kimi
Kiro
Mistral Vibe
@@ -63,53 +60,74 @@ Orca は任意の CLI Agent に対応しています(_このリストに限定
## 機能
- **ログイン不要** — お持ちの Claude Code や Codex サブスクリプションをそのまま利用できます。
-- **ワークツリーネイティブ** — 各機能は独立したワークツリーで開発。スタッシュやブランチの切り替えに悩む必要はありません。瞬時に立ち上げ、切り替えることができます。
-- **マルチAgentターミナル** — 複数の AI Agent をタブやペインで並行して実行。どのアカウントがアクティブかを一目で確認できます。
-- **内蔵バージョン管理** — AI が生成したコードDiffを確認し、素早く編集を行い、Orca から離れることなく直接コミットできます。
-- **GitHub 連携** — PR、Issue、Actions のチェックは、各ワークツリーに自動的にリンクされます。
-- **通知** — エージェントが作業を完了した際や注意が必要な際にお知らせします。スレッドを未読にして後で確認することも可能です。
+- **ワークツリーネイティブ** — 各機能は専用のワークツリーで開発できます。スタッシュやブランチ切り替えに悩まず、すぐに作成して切り替えられます。
+- **マルチエージェントターミナル** — 複数の AI エージェントをタブやペインで並行実行できます。どれがアクティブかを一目で確認できます。
+- **組み込みソース管理** — AI が生成した Diff を確認し、すばやく編集して、Orca から離れずにコミットできます。
+- **GitHub 連携** — PR、Issue、Actions チェックが各ワークツリーに自動で紐づきます。
- **SSH サポート** — リモートマシンに接続し、Orca から直接エージェントを実行できます。
+- **通知** — エージェントが完了したときや注意が必要なときに通知します。スレッドを未読にして後で戻ることもできます。
---
## インストール
+### Mac, Linux, Windows
+
- **[onOrca.dev からダウンロード](https://onOrca.dev)**
-- または、**[GitHub Releases ページ](https://github.com/stablyai/orca/releases)**から最新のインストーラーをダウンロードしてください。
+- または **[GitHub Releases ページ](https://github.com/stablyai/orca/releases/latest)** から入手
+
+*パッケージマネージャーからもインストールできます:*
+
+### macOS (Homebrew)
+
+```bash
+brew install --cask stablyai/orca/orca
+```
+
+### Arch Linux (AUR)
+
+```bash
+# ビルド済みバイナリ
+yay -S stably-orca-bin
+
+# GitHub ソースからビルド
+yay -S stably-orca-git
+```
---
-## [新機能] AI Diff へのコメント
+## [新機能] AI Diff への注釈
-**AI が生成した Diff に直接コメントを追加。**
+**AI が生成した Diff に直接コメントできます。**
-AI が生成した Diff の任意の行にフィードバックを付け、そのままエージェントに返して修正させましょう。レビューのループを素早く回せます — 行番号をコピーする必要も、コンテキストを切り替える必要もありません。
+AI が生成した Diff の任意の行にフィードバックを付け、そのままエージェントに返して修正させましょう。レビューのループを素早く保てます — 行番号をコピーする必要も、コンテキストを切り替える必要もありません。
-
+
---
## [新機能] Codex アカウントのホットスワップ
-**複数の Codex アカウントをお持ちですか?ワンクリックで切り替え可能です。**
+**複数の Codex アカウントをお持ちですか?ワンクリックで切り替えできます。**
-最適な API クォータを得るために複数の Codex アカウントを使用している場合、Orca では再ログインや設定ファイルなしで、即座にアカウントをホットスワップできます。ワンクリックでアカウントを切り替え可能です。
+最適なトークン条件を得るために複数の Codex アカウントを使っている場合、Orca なら再ログインも設定ファイルの編集も不要で、すぐにアカウントをホットスワップできます。アカウントを選んで、そのまま開発を続けられます。
-
+
---
-## [新機能] ワークツリーごとのブラウザ & デザインモード
+## [新機能] ワークツリーごとのブラウザとデザインモード
-**アプリをプレビュー。要素をクリックして。そのままチャットにドロップ。**
+**アプリを表示。任意の要素をクリック。チャットにそのまま投入。**
+
+Orca には、ワークツリー内で使える組み込みブラウザがあります。アプリを作りながらプレビューし、デザインモードに切り替えると、任意の UI 要素をクリックするだけで AI チャットにコンテキストとして直接入ります。スクリーンショットもセレクターのコピーも不要です。変更したい箇所を指して、エージェントに指示するだけです。
-Orca には、ワークツリー内にブラウザが組み込まれています。いつでもアプリをプレビューし、デザインモードに切り替えます — 任意の UI 要素をクリックすると、コンテキストとしてそのまま AI チャットに取り込まれます。
-
+
---
@@ -118,7 +136,7 @@ Orca には、ワークツリー内にブラウザが組み込まれています
**ターミナルからのエージェントオーケストレーション。**
-AI Agent に Orca IDE を制御させましょう。AI を使って IDE にプロジェクトを追加したり、ワークツリーを立ち上げたり、ターミナルから AI Agent に現在のワークツリーのコメントを直接更新させることができます。Orca IDE に同梱されています(設定からインストール)。
+AI エージェントに IDE を制御させましょう。AI を使って IDE にプロジェクトを追加し、ワークツリーを立ち上げ、現在のワークツリーのコメントを進捗チェックポイントとしてターミナルから直接更新できます。Orca IDE に同梱されています(設定からインストール)。
```bash
npx skills add https://github.com/stablyai/orca --skill orca-cli
@@ -126,15 +144,15 @@ npx skills add https://github.com/stablyai/orca --skill orca-cli
---
-## コミュニティ & サポート
+## コミュニティとサポート
-- **Discord:** **[Discord](https://discord.gg/fzjDKHxv8Q)** のコミュニティに参加する。
-- **Twitter / X:** アップデートやアナウンスについては **[@orca_build](https://x.com/orca_build)** をフォローしてください。
-- **フィードバック & アイデア:** 私たちは迅速に新機能をリリースします。不足している機能はありますか?[機能リクエストを送信](https://github.com/stablyai/orca/issues) してください。
-- **サポートを示す:** 毎日のリリースを追うために、このリポジトリにスターをつけてください。
+- **Discord:** **[Discord](https://discord.gg/fzjDKHxv8Q)** のコミュニティに参加してください。
+- **Twitter / X:** アップデートやお知らせは **[@orca_build](https://x.com/orca_build)** をフォローしてください。
+- **フィードバックとアイデア:** 私たちは高速にリリースしています。足りない機能がありますか?[機能リクエストを送信](https://github.com/stablyai/orca/issues) してください。
+- **応援する:** 毎日のリリースを追うために、このリポジトリにスターを付けてください。
---
## 開発について
-貢献したい、またはローカルで実行したいですか? [CONTRIBUTING.md](CONTRIBUTING.md) ガイドをご覧ください。
+貢献したい、またはローカルで実行したいですか? [CONTRIBUTING.md](../.github/CONTRIBUTING.md) ガイドをご覧ください。
diff --git a/docs/README.zh-CN.md b/docs/README.zh-CN.md
index bac00fad5..163b1bfb6 100644
--- a/docs/README.zh-CN.md
+++ b/docs/README.zh-CN.md
@@ -1,14 +1,11 @@
-
-
-
-
-Orca
+
+ Orca
+
-
-
-
-
+
+
+
@@ -16,22 +13,22 @@
- 专为 100x 开发者打造的 AI IDE。
- 跨代码库并排运行 Claude Code、Codex 或 OpenCode — 每个都在自己独立的工作区中运行,并在一个地方集中管理。
+ 面向 100x 构建者的 AI 编排器。
+ 跨仓库并排运行 Claude Code、Codex 或 OpenCode — 每个都在自己的 worktree 中运行,并在一个地方统一跟踪。
支持 macOS、Windows 和 Linux 。
- 在 onOrca.dev 下载
+ 下载 🐋
-
+
-## 支持的 AI Agents
+## 支持的智能体
-Orca 支持任何 CLI Agent (_不仅限于以下列表_)。
+Orca 支持任何 CLI 智能体(*不仅限于以下列表*)。
Claude Code
@@ -50,7 +47,7 @@ Orca 支持任何 CLI Agent (_不仅限于以下列表_)。
Cursor
Droid
GitHub Copilot
- Kilocode
+ Kilocode
Kimi
Kiro
Mistral Vibe
@@ -62,31 +59,51 @@ Orca 支持任何 CLI Agent (_不仅限于以下列表_)。
## 特性
-- **免登录** — 直接用你的 Claude Code 或 Codex 订阅。
-- **原生支持 Worktree** — 每个功能都在自己的工作树中开发。告别频繁的 stashing 或切换分支。瞬间启动并无缝切换。
-- **多Agent终端** — 在不同标签和面板中并排运行多个 AI Agent。一目了然地查看哪些代理处于活跃状态。
-- **内置版本控制** — 查看 AI 生成的代码Diff,进行快速修改并直接提交,无需离开 Orca。
-- **集成 GitHub** — PR、Issues 和 Actions 检查会自动链接到对应的工作区。
-- **通知系统** — 当代理完成任务或需要关注时及时通知你。支持标记为未读稍后处理。
-- **SSH 支持** — 连接远程机器,直接在 Orca 中运行远程 Agent。
+- **无需登录** — 直接使用你自己的 Claude Code 或 Codex 订阅。
+- **原生 worktree 工作流** — 每个功能都有自己的 worktree。无需 stash,也不用来回切分支。立即创建,快速切换。
+- **多智能体终端** — 在标签页和面板中并排运行多个 AI 智能体。一眼就能看到哪些正在活跃。
+- **内置源码管理** — 查看 AI 生成的 diff,快速编辑,并且无需离开 Orca 就能提交。
+- **GitHub 集成** — PR、issue 和 Actions 检查会自动链接到对应的 worktree。
+- **SSH 支持** — 连接远程机器,并直接从 Orca 在远程机器上运行智能体。
+- **通知** — 智能体完成任务或需要关注时及时通知你。可将会话标记为未读,方便稍后返回处理。
---
## 安装
+### Mac, Linux, Windows
+
- **[从 onOrca.dev 下载](https://onOrca.dev)**
-- 或者通过 **[GitHub Releases 页面](https://github.com/stablyai/orca/releases)** 下载最新的安装包。
+- 或通过 **[GitHub Releases 页面](https://github.com/stablyai/orca/releases/latest)** 获取
+
+*也可以通过包管理器安装:*
+
+### macOS (Homebrew)
+
+```bash
+brew install --cask stablyai/orca/orca
+```
+
+### Arch Linux (AUR)
+
+```bash
+# 预编译二进制
+yay -S stably-orca-bin
+
+# 从 GitHub 源码构建
+yay -S stably-orca-git
+```
---
-## [全新] AI Diff 标注
+## [全新] 标注 AI Diff
-**直接在 AI 生成的 Diff 上添加批注。**
+**直接在 AI 生成的 diff 上评论。**
-在 AI 生成的 Diff 的任意一行添加你的反馈,然后发回给 Agent 进行修订。保持评审循环高效顺畅 — 无需复制行号,也无需切换上下文。
+在 AI 生成的 diff 的任意一行添加你的反馈,然后发回给智能体进行修改。让评审循环保持紧凑 — 无需复制行号,也无需切换上下文。
-
+
---
@@ -95,30 +112,31 @@ Orca 支持任何 CLI Agent (_不仅限于以下列表_)。
**有多个 Codex 账号?一键切换。**
-如果你使用多个 Codex 账号以获得最佳 API 额度,Orca 让你能在它们之间即时热切换 — 无需重新登录,也无需修改配置文件。只需一键点击切换账号。
+如果你使用多个 Codex 账号来获得更合适的 token 配额,Orca 可让你在它们之间即时热切换 — 无需重新登录,也无需修改配置文件。选中账号,然后继续构建。
-
+
---
-## [全新] 每工作树内置浏览器与设计模式
+## [全新] 每个 worktree 的浏览器和设计模式
-**预览应用。点击任意元素。直接拖入聊天框。**
+**查看你的应用。点击任意元素。直接放入聊天。**
+
+Orca 在你的 worktree 中内置了浏览器。边构建边预览应用,然后切换到设计模式 — 点击任意 UI 元素,它会作为上下文直接进入你的 AI 聊天。无需截图,无需复制选择器。只需指向想修改的地方,然后告诉智能体要做什么。
-Orca 在你的工作树中内置了浏览器。随时预览你的应用,然后切换到设计模式 — 点击任何 UI 元素,它就会直接落入你的 AI 聊天框作为上下文。
-
+
---
-## [全新] 隆重推出 Orca CLI
+## [全新] Orca CLI 介绍
-**在终端中进行代理编排。**
+**从终端编排智能体。**
-让 AI Agent控制你的Orca IDE。使用 AI 将项目添加到 IDE、启动工作树,并在终端让AI Agent直接更新当前工作树的备注。随 Orca IDE 附带 (在设置中安装)。
+让你的 AI 智能体控制 IDE。使用 AI 将项目添加到 IDE、创建 worktree,并直接从终端更新当前 worktree 的评论,留下有意义的进度检查点。Orca IDE 随附此功能(在设置中安装)。
```bash
npx skills add https://github.com/stablyai/orca --skill orca-cli
@@ -130,11 +148,11 @@ npx skills add https://github.com/stablyai/orca --skill orca-cli
- **Discord:** 加入我们的 **[Discord](https://discord.gg/fzjDKHxv8Q)** 社区。
- **Twitter / X:** 关注 **[@orca_build](https://x.com/orca_build)** 获取更新和公告。
-- **反馈与想法:** 我们发布新功能非常快。需要新功能?[提交功能请求](https://github.com/stablyai/orca/issues)。
-- **支持我们:** 给本仓库点亮 Star,关注我们的日常更新。
+- **反馈与想法:** 我们发布很快。缺少什么功能?[提交功能请求](https://github.com/stablyai/orca/issues)。
+- **支持我们:** 给这个仓库点 Star,关注我们的日常发布。
---
## 开发
-想要贡献代码或在本地运行?请参阅我们的 [CONTRIBUTING.md](CONTRIBUTING.md) 指南。
+想要贡献代码或在本地运行?请参阅我们的 [CONTRIBUTING.md](../.github/CONTRIBUTING.md) 指南。
diff --git a/docs/fix-codex-token-refresh-loss.md b/docs/fix-codex-token-refresh-loss.md
new file mode 100644
index 000000000..d5822cc3a
--- /dev/null
+++ b/docs/fix-codex-token-refresh-loss.md
@@ -0,0 +1,478 @@
+# Fix: Claude & Codex accounts intermittently return 401 Unauthorized
+
+**Issue:** [#1284](https://github.com/stablyai/orca/issues/1284)
+**Status:** Proposed fix
+**Approach:** Add `readBackRefreshedTokens()` to both `CodexRuntimeHomeService` and `ClaudeRuntimeAuthService`
+
+## Problem
+
+Codex (and Claude) managed accounts intermittently return `401 Unauthorized` / `token_expired` errors after working normally for some time.
+
+### Root Cause
+
+Both `CodexRuntimeHomeService` and `ClaudeRuntimeAuthService` perform a **one-directional** auth sync: they always copy the managed account's credentials into the shared runtime path, but never read back refreshed tokens.
+
+**The problematic flow (identical for both providers):**
+
+1. User authenticates → credentials saved to managed storage
+2. `syncForCurrentSelection()` copies managed credentials → runtime path
+3. CLI runs using the runtime credentials
+4. OAuth access token expires over time. **CLI refreshes it and writes updated tokens back to the runtime path**
+5. Next PTY launch or rate-limit fetch triggers `syncForCurrentSelection()` again
+6. **The sync overwrites the runtime credentials with the stale managed copy** — the refreshed token is lost
+7. Next request uses the expired token → `401 Unauthorized`
+
+**Codex specifics:**
+- Runtime path: `~/.codex/auth.json`
+- Managed path: `/codex-accounts//home/auth.json`
+- Affected: `CodexRuntimeHomeService.syncForCurrentSelection()` line 84
+
+**Claude specifics:**
+- Runtime path: `~/.claude/.credentials.json` (+ Keychain on macOS)
+- Managed path: `/claude-accounts//auth/.credentials.json` (+ Keychain)
+- Affected: `ClaudeRuntimeAuthService.doSyncForCurrentSelection()` line 125
+- Note: Claude already has `lastWrittenCredentialsJson` and `detectExternalLoginAndUpdateSnapshot()` for the managed→system-default transition, but it **does not** read back refreshed tokens during steady-state sync — the same one-directional overwrite happens
+
+### Why it's intermittent
+
+- Tokens have a multi-hour lifetime, so the bug only surfaces after enough time passes for the original token to expire
+- The overwrite only happens on PTY launch or rate-limit fetch, not continuously
+- If the user re-authenticates, the cycle resets with a fresh token
+
+### Affected code
+
+**Codex:**
+- `src/main/codex-accounts/runtime-home-service.ts` — `syncForCurrentSelection()` (line 49-85)
+- Called from `prepareForCodexLaunch()` (line 39) and `prepareForRateLimitFetch()` (line 44)
+
+**Claude:**
+- `src/main/claude-accounts/runtime-auth-service.ts` — `doSyncForCurrentSelection()` (line 96-131)
+- Called from `prepareForClaudeLaunch()` (line 47) and `prepareForRateLimitFetch()` (line 52)
+
+## System Context
+
+```
+┌──────────────────────────────────────────────────────────────┐
+│ Orca (main process) │
+│ │
+│ ┌──────────────────────────────────────────────────┐ │
+│ │ CodexRuntimeHomeService │ │
+│ │ │ │
+│ │ lastSyncedAccountId: string | null │ │
+│ │ lastWrittenAuthJson: string | null ← NEW │ │
+│ │ │ │
+│ │ syncForCurrentSelection() │ │
+│ │ ├─ captureSystemDefaultSnapshotIfNeeded() │ │
+│ │ ├─ readBackRefreshedTokens() ← NEW │ │
+│ │ └─ writeRuntimeAuth() │ │
+│ │ │ │
+│ │ restoreSystemDefaultSnapshot() │ │
+│ │ └─ detectExternalLoginAndUpdateSnapshot() ← NEW│ │
+│ └──────────┬──────────────────────────┬─────────────┘ │
+│ │ │ │
+│ ┌───────▼───────┐ ┌────────▼──────────┐ │
+│ │ Managed Home │ │ Runtime Home │ │
+│ │ / │ │ ~/.codex/ │ │
+│ │ codex-accounts│ │ auth.json │ │
+│ │ //home/ │ │ │ │
+│ │ auth.json │ │ │ │
+│ └───────────────┘ └────────┬──────────┘ │
+└──────────────────────────────────────────┼────────────────────┘
+ │
+ ┌───────▼───────┐
+ │ Codex CLI │
+ │ │
+ │ reads auth.json
+ │ refreshes token
+ │ writes back │
+ └───────────────┘
+```
+
+## Data Flow: Token Refresh Preservation
+
+```
+ PTY launch / rate-limit fetch
+ │
+ ▼
+ syncForCurrentSelection()
+ │
+ ├─ captureSystemDefaultSnapshotIfNeeded()
+ │
+ ├─ Is lastSyncedAccountId === activeAccount.id?
+ │ │
+ │ YES → readBackRefreshedTokens()
+ │ │ │
+ │ │ ├─ Read ~/.codex/auth.json (current runtime)
+ │ │ ├─ Compare to lastWrittenAuthJson
+ │ │ │ │
+ │ │ │ DIFFER → Codex CLI refreshed the token
+ │ │ │ │ Write runtime auth.json back
+ │ │ │ │ to managed home auth.json
+ │ │ │ │
+ │ │ │ MATCH → No external changes, continue
+ │ │ │
+ │ │ └─ (try/catch: failures log + continue)
+ │ │
+ │ NO → Skip read-back (account switch in progress)
+ │
+ ├─ Read managed auth.json
+ ├─ writeRuntimeAuth(contents)
+ │ ├─ Write to ~/.codex/auth.json
+ │ └─ Record lastWrittenAuthJson = contents
+ │
+ └─ lastSyncedAccountId = activeAccount.id
+```
+
+## Data Flow: External Login Detection (managed → system-default)
+
+```
+ User deselects managed account (activeAccount = null)
+ │
+ ▼
+ syncForCurrentSelection()
+ │
+ ├─ lastSyncedAccountId !== null? (was managed)
+ │ │
+ │ YES → restoreSystemDefaultSnapshot()
+ │ │ │
+ │ │ ├─ detectExternalLoginAndUpdateSnapshot()
+ │ │ │ │
+ │ │ │ ├─ lastWrittenAuthJson !== null?
+ │ │ │ ├─ Read current ~/.codex/auth.json
+ │ │ │ ├─ Compare to lastWrittenAuthJson
+ │ │ │ │ │
+ │ │ │ │ DIFFER → External login detected
+ │ │ │ │ │ (e.g. `codex auth login`)
+ │ │ │ │ │ Delete stale snapshot
+ │ │ │ │ │ Clear lastWrittenAuthJson
+ │ │ │ │ │ Return true (skip restore)
+ │ │ │ │ │
+ │ │ │ │ MATCH → No external login
+ │ │ │ │ Return false (do restore)
+ │ │ │ │
+ │ │ │ └─ (try/catch: failures → return false)
+ │ │ │
+ │ │ └─ If not external: restore snapshot as before
+ │ │
+ │ NO → Skip (was never managed)
+ │
+ └─ lastSyncedAccountId = null
+```
+
+## Fix: Add `readBackRefreshedTokens()` to Both Services
+
+The fix adds the same read-back mechanism to both `CodexRuntimeHomeService` and `ClaudeRuntimeAuthService`. The core logic is identical: before overwriting runtime credentials, compare the file to what Orca last wrote. If they differ, the CLI refreshed the token — write it back to managed storage.
+
+### What each service needs
+
+| Change | Codex (`runtime-home-service.ts`) | Claude (`runtime-auth-service.ts`) |
+|--------|-----------------------------------|-------------------------------------|
+| Add `lastWrittenAuthJson` field | **NEW** | Already exists as `lastWrittenCredentialsJson` |
+| Track writes in `writeRuntime*()` | **NEW** | Already done (line 271) |
+| `readBackRefreshedTokens()` | **NEW** | **NEW** (missing despite having the tracking field) |
+| `detectExternalLoginAndUpdateSnapshot()` | **NEW** | Already exists (line 224) |
+| `clearLastWritten*()` for re-auth | **NEW** | **NEW** (same re-auth clobbering risk) |
+
+### Key differences between services
+
+| Aspect | Claude | Codex |
+|--------|--------|-------|
+| Auth storage | Keychain (macOS) + `.credentials.json` | `auth.json` only |
+| Sync model | Async (serialized via `mutationQueue`) | Synchronous |
+| Managed path | `managedAuthPath/.credentials.json` | `managedHomePath/auth.json` |
+| Tracking field | `lastWrittenCredentialsJson` | `lastWrittenAuthJson` |
+
+### Codex implementation
+
+Add a `lastWrittenAuthJson` field and three new behaviors:
+
+1. **`writeRuntimeAuth()`** — record what was written
+2. **`readBackRefreshedTokens()`** — before overwriting, check if Codex CLI refreshed the token
+3. **`detectExternalLoginAndUpdateSnapshot()`** — on managed→system-default transition, detect external logins
+
+### Pseudocode
+
+```typescript
+export class CodexRuntimeHomeService {
+ private lastSyncedAccountId: string | null = null
+
+ // Why: tracks the auth.json content Orca last wrote to ~/.codex/auth.json.
+ // On managed→system-default transition, if the file differs from this value,
+ // an external login (e.g. `codex auth login`) overwrote it — so Orca adopts
+ // the file as the new system default instead of restoring a stale snapshot.
+ // Between syncs, if the file differs, Codex CLI refreshed the token — so
+ // Orca writes back the refreshed token to managed storage.
+ private lastWrittenAuthJson: string | null = null
+
+ // ... constructor, prepare methods unchanged ...
+
+ syncForCurrentSelection(): void {
+ this.captureSystemDefaultSnapshotIfNeeded()
+
+ const settings = this.store.getSettings()
+ const activeAccount = this.getActiveAccount(
+ settings.codexManagedAccounts,
+ settings.activeCodexManagedAccountId
+ )
+ if (!activeAccount) {
+ if (this.lastSyncedAccountId !== null) {
+ this.restoreSystemDefaultSnapshot()
+ this.lastSyncedAccountId = null
+ }
+ return
+ }
+
+ const activeAuthPath = join(activeAccount.managedHomePath, 'auth.json')
+ if (!existsSync(activeAuthPath)) {
+ console.warn(
+ '[codex-runtime-home] Active managed account is missing auth.json, restoring system default'
+ )
+ this.store.updateSettings({ activeCodexManagedAccountId: null })
+ if (this.lastSyncedAccountId !== null) {
+ this.restoreSystemDefaultSnapshot()
+ this.lastSyncedAccountId = null
+ }
+ return
+ }
+
+ // NEW: Before overwriting runtime auth, check if Codex CLI refreshed
+ // the token since our last write. If so, preserve those refreshed tokens
+ // back to managed storage so they aren't lost.
+ if (this.lastSyncedAccountId === activeAccount.id) {
+ this.readBackRefreshedTokens(activeAuthPath)
+ }
+
+ this.lastSyncedAccountId = activeAccount.id
+ this.writeRuntimeAuth(readFileSync(activeAuthPath, 'utf-8'))
+ }
+
+ // Why: Codex CLI refreshes expired OAuth tokens and writes them back to
+ // ~/.codex/auth.json. If we detect the runtime file differs from what Orca
+ // last wrote, the CLI must have refreshed — so we write the updated tokens
+ // back to managed storage before overwriting runtime with managed state.
+ // This is the Codex analog of the read-back logic implied by
+ // lastWrittenCredentialsJson in ClaudeRuntimeAuthService.
+ private readBackRefreshedTokens(managedAuthPath: string): void {
+ try {
+ const runtimeAuthPath = this.getRuntimeAuthPath()
+ if (!existsSync(runtimeAuthPath)) {
+ return
+ }
+
+ // Nothing to compare against — first sync or after restart.
+ // Skip read-back to avoid capturing stale/unknown state.
+ if (this.lastWrittenAuthJson === null) {
+ return
+ }
+
+ const runtimeContents = readFileSync(runtimeAuthPath, 'utf-8')
+ if (runtimeContents === this.lastWrittenAuthJson) {
+ return
+ }
+
+ // Codex CLI refreshed tokens at runtime — preserve them in managed storage.
+ writeFileAtomically(managedAuthPath, runtimeContents, { mode: 0o600 })
+ } catch (error) {
+ // Why: read-back is best-effort. A transient fs error (permissions,
+ // file locked by another process) must not block the forward sync
+ // path — the worst case is one more stale-token cycle, which is
+ // strictly better than failing the entire sync.
+ console.warn('[codex-runtime-home] Failed to read back refreshed tokens:', error)
+ }
+ }
+
+ private restoreSystemDefaultSnapshot(): void {
+ // Why: detect whether an external tool (e.g. `codex auth login`) overwrote
+ // auth.json while a managed account was active. If so, that external login
+ // becomes the new system default — skip the stale snapshot restore.
+ if (this.detectExternalLoginAndUpdateSnapshot()) {
+ return
+ }
+
+ const snapshotPath = this.getSystemDefaultSnapshotPath()
+ if (!existsSync(snapshotPath)) {
+ return
+ }
+
+ this.writeRuntimeAuth(readFileSync(snapshotPath, 'utf-8'))
+ }
+
+ // Why: mirrors ClaudeRuntimeAuthService.detectExternalLoginAndUpdateSnapshot().
+ // If the runtime auth.json differs from what Orca last wrote, something
+ // external changed it. That external state should become the new system
+ // default rather than being overwritten by a potentially stale snapshot.
+ private detectExternalLoginAndUpdateSnapshot(): boolean {
+ if (this.lastWrittenAuthJson === null) {
+ return false
+ }
+
+ const runtimeAuthPath = this.getRuntimeAuthPath()
+ if (!existsSync(runtimeAuthPath)) {
+ return false
+ }
+
+ try {
+ const currentAuth = readFileSync(runtimeAuthPath, 'utf-8')
+ if (currentAuth === this.lastWrittenAuthJson) {
+ return false
+ }
+ } catch {
+ return false
+ }
+
+ // External login detected — adopt current state as the new system default.
+ const snapshotPath = this.getSystemDefaultSnapshotPath()
+ rmSync(snapshotPath, { force: true })
+ this.lastWrittenAuthJson = null
+ return true
+ }
+
+ private writeRuntimeAuth(contents: string): void {
+ writeFileAtomically(this.getRuntimeAuthPath(), contents, { mode: 0o600 })
+ // Why: record what we wrote so readBackRefreshedTokens() and
+ // detectExternalLoginAndUpdateSnapshot() can detect external changes.
+ this.lastWrittenAuthJson = contents
+ }
+}
+```
+
+### Re-auth safety: clearing `lastWrittenAuthJson`
+
+When `CodexAccountService.doReauthenticateAccount()` runs, it writes fresh tokens to managed storage via `codex login`, then calls `syncForCurrentSelection()`. Without intervention, the read-back logic would see that runtime differs from `lastWrittenAuthJson` (because Codex CLI may have refreshed the runtime token between syncs) and write the stale runtime content back to managed — overwriting the fresh re-auth tokens.
+
+**Fix:** `CodexRuntimeHomeService` must expose a method to clear `lastWrittenAuthJson` so that the re-auth caller can signal "managed storage was externally updated, skip read-back on next sync."
+
+```typescript
+// Called by CodexAccountService before syncForCurrentSelection() after re-auth or add-account.
+clearLastWrittenAuthJson(): void {
+ this.lastWrittenAuthJson = null
+}
+```
+
+The same applies to `doAddAccount()`, which also writes managed auth then syncs. Both callers must call `clearLastWrittenAuthJson()` before `syncForCurrentSelection()`.
+
+### Changes to `CodexAccountService`
+
+Both `doAddAccount()` and `doReauthenticateAccount()` write fresh tokens to managed storage (via `codex login`) then call `syncForCurrentSelection()`. They must clear the tracking field first to prevent read-back from overwriting the fresh tokens:
+
+```typescript
+// In doAddAccount(), after runCodexLogin succeeds:
+this.runtimeHome.clearLastWrittenAuthJson()
+this.runtimeHome.syncForCurrentSelection()
+
+// In doReauthenticateAccount(), after runCodexLogin succeeds:
+this.runtimeHome.clearLastWrittenAuthJson()
+this.runtimeHome.syncForCurrentSelection()
+```
+
+### Safety considerations
+
+- **Only reads back when Orca owns the runtime auth** (`lastSyncedAccountId === activeAccount.id`), so external `codex login` changes are not accidentally captured into the wrong managed account
+- **Skips read-back when `lastWrittenAuthJson` is null** (first sync, after restart, or after re-auth/add) — avoids capturing stale or unknown state that Orca didn't write
+- **try/catch around read-back** — a transient fs error (permissions, locked file) logs a warning but does not block the forward sync. Worst case: one more stale-token cycle, strictly better than a sync failure
+- **try/catch around external login detection** — same rationale; detection failure falls through to normal snapshot restore, which is the safe default
+- **Atomic write** to managed auth prevents partial-write corruption
+- **No behavior change for account switches** — when switching accounts, `lastSyncedAccountId` differs from the new account ID, so no read-back occurs
+- **No behavior change for system-default flow** — read-back only runs when a managed account is active and was previously synced
+- **External login detection on managed→system-default transition** — if `codex auth login` ran while a managed account was active, the snapshot is stale. Deleting it and clearing `lastWrittenAuthJson` lets the external login persist as the new system default
+- **In-memory tracking only** — `lastWrittenAuthJson` is not persisted to disk. After an Orca restart, the field is null, and the first sync performs a clean write without read-back. This is intentionally conservative: we'd rather do one redundant overwrite than risk reading back unknown state
+
+### Claude implementation
+
+Claude already has `lastWrittenCredentialsJson` tracking and `detectExternalLoginAndUpdateSnapshot()`. It only needs two additions:
+
+1. **`readBackRefreshedTokens()`** — same logic as Codex, adapted for Claude's async model and Keychain
+2. **`clearLastWrittenCredentialsJson()`** — for re-auth safety (same pattern as Codex)
+
+```typescript
+// In ClaudeRuntimeAuthService:
+
+// Add to doSyncForCurrentSelection(), before writeRuntimeCredentials():
+if (this.lastSyncedAccountId === activeAccount.id) {
+ await this.readBackRefreshedTokens(activeAccount)
+}
+
+// Why: Claude CLI refreshes expired OAuth tokens and writes them back to
+// .credentials.json (and Keychain on macOS). If we detect the runtime file
+// differs from what Orca last wrote, the CLI must have refreshed.
+private async readBackRefreshedTokens(account: ClaudeManagedAccount): Promise {
+ try {
+ if (this.lastWrittenCredentialsJson === null) {
+ return
+ }
+
+ const paths = this.pathResolver.getRuntimePaths()
+ if (!existsSync(paths.credentialsPath)) {
+ return
+ }
+
+ const runtimeContents = readFileSync(paths.credentialsPath, 'utf-8')
+ if (runtimeContents === this.lastWrittenCredentialsJson) {
+ return
+ }
+
+ // CLI refreshed tokens — write back to managed storage.
+ if (process.platform === 'darwin') {
+ await writeManagedClaudeKeychainCredentials(account.id, runtimeContents)
+ } else {
+ const credentialsPath = join(account.managedAuthPath, '.credentials.json')
+ writeFileAtomically(credentialsPath, runtimeContents, { mode: 0o600 })
+ }
+ } catch (error) {
+ console.warn('[claude-runtime-auth] Failed to read back refreshed tokens:', error)
+ }
+}
+
+// Exposed for ClaudeAccountService to call before sync after re-auth/add.
+clearLastWrittenCredentialsJson(): void {
+ this.lastWrittenCredentialsJson = null
+}
+```
+
+### Changes to `ClaudeAccountService`
+
+Same pattern as Codex — both `doAddAccount()` and `doReauthenticateAccount()` must clear the tracking field before syncing:
+
+```typescript
+// In doAddAccount(), after login succeeds:
+this.runtimeAuth.clearLastWrittenCredentialsJson()
+await this.runtimeAuth.syncForCurrentSelection()
+
+// In doReauthenticateAccount(), after login succeeds:
+this.runtimeAuth.clearLastWrittenCredentialsJson()
+await this.runtimeAuth.syncForCurrentSelection()
+```
+
+### Structural alignment
+
+The two services should stay structurally aligned. Both now have the same three mechanisms:
+
+| Mechanism | Codex | Claude |
+|-----------|-------|--------|
+| Track what we wrote | `lastWrittenAuthJson` | `lastWrittenCredentialsJson` |
+| Read back refreshed tokens | `readBackRefreshedTokens()` | `readBackRefreshedTokens()` |
+| Detect external logins | `detectExternalLoginAndUpdateSnapshot()` | `detectExternalLoginAndUpdateSnapshot()` |
+| Clear tracking on re-auth | `clearLastWrittenAuthJson()` | `clearLastWrittenCredentialsJson()` |
+
+Future changes to either service should be cross-checked against the other.
+
+### Files to modify
+
+**Codex:**
+- `src/main/codex-accounts/runtime-home-service.ts` — add `lastWrittenAuthJson` field, `readBackRefreshedTokens()`, `detectExternalLoginAndUpdateSnapshot()`, `clearLastWrittenAuthJson()`, update `writeRuntimeAuth()` and `restoreSystemDefaultSnapshot()`
+- `src/main/codex-accounts/service.ts` — add `clearLastWrittenAuthJson()` calls in `doAddAccount()` and `doReauthenticateAccount()`
+- `src/main/codex-accounts/runtime-home-service.test.ts` — add test cases
+
+**Claude:**
+- `src/main/claude-accounts/runtime-auth-service.ts` — add `readBackRefreshedTokens()`, `clearLastWrittenCredentialsJson()`, call read-back in `doSyncForCurrentSelection()`
+- `src/main/claude-accounts/service.ts` — add `clearLastWrittenCredentialsJson()` calls in `doAddAccount()` and `doReauthenticateAccount()`
+- `src/main/claude-accounts/runtime-auth-service.test.ts` — add test cases
+
+**Test cases (both services):**
+- Token read-back when CLI refreshes tokens between syncs
+- No read-back on first sync (tracking field is null)
+- No read-back on account switch (`lastSyncedAccountId` differs)
+- External login detection on managed→system-default transition
+- Graceful degradation when read-back throws (fs error)
+- Re-auth does not lose fresh tokens: after clearing tracking field + sync, managed storage retains the re-auth tokens
+- Add-account does not lose fresh tokens: same pattern as re-auth
diff --git a/docs/fix-missing-single-instance-lock.md b/docs/fix-missing-single-instance-lock.md
new file mode 100644
index 000000000..3d8bdf74f
--- /dev/null
+++ b/docs/fix-missing-single-instance-lock.md
@@ -0,0 +1,443 @@
+# Fix: Missing single-instance lock corrupts `orca-runtime.json` + `endpoint.env` on every relaunch
+
+**Issue:** [#1312](https://github.com/stablyai/orca/issues/1312)
+**Status:** Proposed fix
+**Approach:** Add `app.requestSingleInstanceLock()`, clear owned metadata on clean exit, and sweep orphaned sockets on startup.
+
+## Problem
+
+Orca v1.3.24 does not call `app.requestSingleInstanceLock()`. Every launch of the AppImage / `.app` bundle starts a new Electron main process that unconditionally:
+
+1. Opens a fresh Unix socket `o--.sock`.
+2. Atomically rewrites `/orca-runtime.json` with the new pid / socket / runtimeId / authToken, clobbering the previously-running instance's metadata.
+3. Picks a new random port and rewrites `/agent-hooks/endpoint.env` with the new port + token.
+
+The earlier Orca keeps its socket + hook-port alive, but the canonical metadata files no longer point at it. When the most-recent instance quits, the socket is `rmSync`'d in `OrcaRuntimeRpcServer.stop()` but the metadata file is left pointing at the dead pid. `orca status` then returns `runtime.state = 'stale_bootstrap'` even though earlier Orca instances are still running healthily.
+
+### Root cause
+
+Three distinct gaps in the main-process lifecycle:
+
+1. **No single-instance lock.** `grep -rn requestSingleInstanceLock src/` returns zero matches. Every launch boots a full second Electron process instead of focusing the existing window.
+2. **No metadata clear on clean exit.** `src/main/runtime/runtime-metadata.ts:29` exports `clearRuntimeMetadata()` but it is never called. The `will-quit` handler in `src/main/index.ts:516` stops the RPC server (removes the socket) but leaves `orca-runtime.json` on disk pointing at a dead pid + missing socket. The safety comment in `src/main/runtime/runtime-rpc.ts:132-136` explicitly declines to clear metadata, citing the risk of erasing another live runtime's bootstrap during restarts / updates / dev overlap — that concern is real but is the *symptom* of missing single-instance, not a principled design.
+3. **No startup sweep of orphaned sockets.** A process killed by SIGKILL / OOM-kill skips `OrcaRuntimeRpcServer.stop()` entirely, leaving `o--*.sock` files in `/` with no cleanup path. The reporter observed three such orphans on a single live system.
+
+### Symptom (from the issue)
+
+Healthy state with one orca running (pid 50926):
+
+```json
+{
+ "app": { "running": true, "pid": 50926 },
+ "runtime": { "state": "ready", "reachable": true, "runtimeId": "2ad0..." },
+ "graph": { "state": "ready" }
+}
+```
+
+After launching a second instance and quitting it while the first stays open:
+
+```json
+{
+ "app": { "running": false, "pid": null },
+ "runtime": { "state": "stale_bootstrap", "reachable": false, "runtimeId": null },
+ "graph": { "state": "not_running" }
+}
+```
+
+The `stale_bootstrap` branch is distinguished at `src/cli/runtime/status.ts:17-20` — "metadata file exists but pid not running" vs. "no metadata at all".
+
+### Affected code
+
+- `src/main/index.ts` — app lifecycle entry; `app.whenReady` at line 315, `will-quit` at line 516.
+- `src/main/runtime/runtime-rpc.ts` — `OrcaRuntimeRpcServer.start()` line 51, `stop()` line 112 (with the deferred-cleanup comment at lines 132-136).
+- `src/main/runtime/runtime-metadata.ts` — `writeRuntimeMetadata` / `readRuntimeMetadata` / `clearRuntimeMetadata`.
+- `src/main/agent-hooks/server.ts` — `writeEndpointFile` line 1299, `stop()` line 1223 (with a parallel deferred-cleanup comment at lines 1230-1237).
+- `src/shared/runtime-bootstrap.ts` — `RuntimeMetadata` shape and `getRuntimeMetadataPath()`.
+- `src/main/startup/configure-process.ts` — `configureDevUserDataPath(isDev)` redirects dev runs to `orca-dev` userData.
+- `src/cli/runtime/status.ts` — CLI reader, never writes metadata.
+
+## Architecture
+
+### Current (buggy) state
+
+Every launch boots a new Electron main. All live instances race on the same `orca-runtime.json` / `endpoint.env`, and SIGKILL'd predecessors leave orphaned sockets behind.
+
+```
+ / (e.g. ~/.config/orca)
+ ┌────────────────────────────────────────────┐
+ │ orca-runtime.json ← clobbered on every │
+ │ launch (last writer │
+ │ wins, pid may be │
+ │ dead) │
+ │ agent-hooks/endpoint.env ← same race │
+ │ o--*.sock (live, owned by A) │
+ │ o--*.sock (orphan — B SIGKILL'd) │
+ │ o--*.sock (orphan — C OOM-killed)│
+ └────────────────────────────────────────────┘
+ ▲ ▲ ▲
+ │ writes │ writes │ writes
+ │ │ │
+ ┌───────┴──┐ ┌──────┴───┐ ┌─────┴────┐
+ │ Electron │ │ Electron │ │ Electron │
+ │ #1 │ │ #2 │ │ #3 │
+ │ (live, │ │ (live, │ │ (quit; │
+ │ hook │ │ hook │ │ left │
+ │ HTTP) │ │ HTTP) │ │ stale │
+ └──────────┘ └──────────┘ │ meta) │
+ └──────────┘
+ ▲
+ │ reads orca-runtime.json
+ │ → sees wrong/dead pid
+ ┌───────┴───────┐
+ │ CLI (status) │ reports 'stale_bootstrap'
+ └───────────────┘
+```
+
+### Post-fix state
+
+A single Electron owns the userData. Second launches fire `second-instance` and exit. The ownership guard at `clearRuntimeMetadataIfOwned()` protects the auto-updater handoff. Sweep runs at startup.
+
+```
+ /
+ ┌────────────────────────────────────────────┐
+ │ orca-runtime.json ← one writer (pid A) │
+ │ agent-hooks/endpoint.env │
+ │ o--*.sock (live, owned by A) │
+ │ (orphans swept on next start) │
+ └────────────────────────────────────────────┘
+ ▲
+ │ writes
+ ┌───────┴──────────────┐
+ │ Electron #1 (holds │──── hook HTTP ──►
+ │ single-instance lock)│
+ └──────────▲───────────┘
+ │ 'second-instance' event
+ ┌──────────┴───────────┐
+ │ Electron #2 (boots, │
+ │ lock fails, focuses │
+ │ #1's window, quits) │── transient, no writes
+ └──────────────────────┘
+ ▲
+ │ reads orca-runtime.json
+ ┌───────┴───────┐
+ │ CLI (status) │ reports 'ready'
+ └───────────────┘
+
+Ownership guard site: src/main/runtime/runtime-metadata.ts
+ → clearRuntimeMetadataIfOwned(userData, ownedPid, ownedRuntimeId)
+```
+
+### Data flow
+
+**Happy path — single instance steady state**
+
+```
+[user action] → Electron #1 main loop
+ → Electron #1 RPC server (Unix socket) handles IPC
+ → hook HTTP server answers localhost requests
+ → orca-runtime.json unchanged (only written at start)
+ → CLI reads orca-runtime.json → 'ready'
+```
+
+**First-launch cold start**
+
+```
+[launch] → configureDevUserDataPath(is.dev) (startup/configure-process.ts)
+ → app.requestSingleInstanceLock() → true (main/index.ts)
+ → sweepOrphanedRuntimeSockets(userData) (runtime-rpc.ts start())
+ → OrcaRuntimeRpcServer.start() binds o--*.sock
+ → writeRuntimeMetadata({pid, runtimeId, ...}) (runtime-metadata.ts)
+ → agent-hooks server writes endpoint.env
+ → openMainWindow()
+```
+
+**Second-launch rejected**
+
+```
+[launch] → configureDevUserDataPath(is.dev)
+ → app.requestSingleInstanceLock() → false (lock held by #1)
+ → app.quit() (transient process exits)
+ → Electron #1 receives 'second-instance' event
+ → Electron #1 restores + focuses mainWindow
+ → no writes to orca-runtime.json or endpoint.env
+```
+
+**Auto-updater handoff (two orderings, both safe)**
+
+```
+Ordering X: old clears first
+ old.runtimeRpc.stop() rmSync's o--*.sock
+ old.clearRuntimeMetadataIfOwned() — current.pid == oldPid → clear
+ new.writeRuntimeMetadata() — fresh file, no conflict
+
+Ordering Y: new writes first
+ new.writeRuntimeMetadata() — file now points at newPid/newRuntimeId
+ old.clearRuntimeMetadataIfOwned() — current.pid != oldPid → SUPPRESSED
+ new continues undisturbed
+
+Invariant: the ownership guard (pid + runtimeId match) is what makes
+both orderings safe. Without it, Ordering Y would erase the new
+process's just-written metadata.
+```
+
+## Proposed fix
+
+Three surgical changes, in decreasing order of importance:
+
+### 1. Single-instance lock (primary — kills ~90% of the bug surface)
+
+In `src/main/index.ts`, immediately **after** `configureDevUserDataPath(is.dev)` (line 89) and **before** any handler registration or `app.whenReady(...)`, gate the rest of the module on a new helper `acquireSingleInstanceLock()` (see "Helper extraction" in the testing section):
+
+```ts
+function focusExistingWindow(): void {
+ // Why: focus the existing window instead of spawning a parallel Electron
+ // process that would clobber orca-runtime.json and endpoint.env.
+ if (mainWindow) {
+ if (mainWindow.isMinimized()) mainWindow.restore()
+ mainWindow.focus()
+ }
+ // Pre-window case: the active instance is still booting and will call
+ // openMainWindow() from whenReady(). No action needed here.
+}
+
+if (!acquireSingleInstanceLock(app, focusExistingWindow)) {
+ if (is.dev) {
+ console.log(
+ 'Another Orca instance is already running against this userData path — focusing existing window.'
+ )
+ }
+ app.quit()
+ // Why: early-return is what prevents the service constructors and handler
+ // registrations below (whenReady, before-quit, will-quit, etc.) from
+ // running in a process that is already losing the lock race.
+ return
+}
+// All existing app lifecycle setup below.
+```
+
+**Placement rationale (from codex review):** the lock must come *after* `configureDevUserDataPath(is.dev)` so dev (`orca-dev` userData) and packaged (`orca` userData) instances lock in separate namespaces — Electron derives the lock identity from the `userData` path. Placing it before would force dev and packaged builds to serialize against each other, which is the opposite of the current dev/prod isolation contract.
+
+**Dev-mode behavior:** kept unconditional. `configureDevUserDataPath` already isolates `pnpm dev` from packaged runs, so devs who want two instances already get the answer by running both a packaged build and a dev build. Allowing multi-instance against the same userData reopens the exact corruption this fix targets.
+
+**Dev-mode ergonomics:** when the lock fails in dev mode, write a single `console.log('Another Orca instance is already running against this userData path — focusing existing window.')` immediately before `app.quit()`. This makes the behavior discoverable in the `pnpm dev` console so internal devs don't mistake a silent exit for a broken launcher. Packaged runs skip the log — there's no attached console.
+
+### 2. Clear owned metadata on clean exit (secondary — hardens `stale_bootstrap` reporting)
+
+Add a guarded clear in `src/main/runtime/runtime-metadata.ts`:
+
+```ts
+/**
+ * Why: clearing metadata unconditionally would race with a sibling Orca
+ * process during auto-updater handoff or dev/prod overlap — see the comment
+ * in runtime-rpc.ts:132-136. The ownership guard preserves the original
+ * safety invariant while still letting us report 'not_running' (not
+ * 'stale_bootstrap') after a clean exit.
+ */
+export function clearRuntimeMetadataIfOwned(
+ userDataPath: string,
+ ownedPid: number,
+ ownedRuntimeId: string
+): void {
+ const current = readRuntimeMetadata(userDataPath)
+ if (!current) return
+ if (current.pid !== ownedPid) return
+ if (current.runtimeId !== ownedRuntimeId) return
+ clearRuntimeMetadata(userDataPath)
+}
+```
+
+In `src/main/index.ts` `will-quit` handler (line 516-548), the clear must be **awaited before Electron exits**, not fire-and-forget. The existing handler uses a two-pass `preventDefault()` pattern with `disconnectDaemon().finally(app.quit())`. The existing `void runtimeRpc.stop().catch(...)` at line 530-534 currently fires independently of that chain; Electron may exit before `runtimeRpc.stop()` resolves, and a `.then(clear)` appended to it would race the second-pass `app.quit()`. Fold both into the awaited chain instead — and do the work **inside** the `!daemonDisconnectDone` guard so `runtimeRpc.stop()` fires exactly once, on the first pass:
+
+```ts
+if (!daemonDisconnectDone) {
+ e.preventDefault()
+ // Why: capture ownership synchronously (before any await) so the guard
+ // still has the right pid/runtimeId to compare against if shutdown
+ // partially clears global state. Evaluating these inside .then() would
+ // let a later teardown path null them out mid-chain.
+ const ownedPid = process.pid
+ const ownedRuntimeId = runtime?.getRuntimeId()
+ // Why: the construction AND the allSettled() must both live inside the
+ // `!daemonDisconnectDone` guard. The will-quit handler re-fires after
+ // app.quit() below; without this guard, the second pass would re-invoke
+ // runtimeRpc.stop() (redundant rmSync on an already-removed socket) and
+ // re-run the ownership-guarded clear against a metadata file that may
+ // now belong to the auto-updater's replacement process.
+ const rpcStopAndClear = runtimeRpc
+ ? runtimeRpc
+ .stop()
+ .then(() => {
+ if (ownedRuntimeId) {
+ clearRuntimeMetadataIfOwned(app.getPath('userData'), ownedPid, ownedRuntimeId)
+ }
+ })
+ .catch((error) => {
+ console.error('[runtime] Failed to stop local RPC transport:', error)
+ })
+ : Promise.resolve()
+ // Why: Promise.allSettled — we need BOTH the daemon disconnect and the RPC
+ // stop + owned-metadata clear to complete before Electron exits. Using
+ // allSettled (not all) preserves the existing fail-open posture: if
+ // disconnectDaemon rejects, we still quit instead of hanging the app.
+ Promise.allSettled([disconnectDaemon(), rpcStopAndClear]).then(() => {
+ daemonDisconnectDone = true
+ app.quit()
+ })
+}
+```
+
+Remove the standalone `void runtimeRpc.stop().catch(...)` at line 530-534 — it is folded into `rpcStopAndClear` above.
+
+**Why compare-before-clear is not over-engineering:** `autoUpdater.quitAndInstall()` quits the old process immediately and relaunches. The new process may already be starting (writing its own metadata) while the old `will-quit` is running. An unconditional clear would delete the new process's fresh metadata. Codex confirmed this is the correct posture.
+
+### 3. Orphaned-socket sweep on startup (tertiary — hygiene)
+
+In `OrcaRuntimeRpcServer.start()` (`src/main/runtime/runtime-rpc.ts:51`), before creating the new listener, enumerate `/o-*.sock` and remove any whose pid component is dead:
+
+```ts
+// Why: processes killed by SIGKILL / OOM-kill skip stop() and leave behind
+// o--*.sock files. Sweep dead-pid sockets on startup so the userData
+// directory does not accumulate orphans over the app's lifetime.
+function sweepOrphanedRuntimeSockets(userDataPath: string, ownPid: number): void {
+ let entries: string[]
+ try {
+ entries = readdirSync(userDataPath)
+ } catch {
+ return
+ }
+ for (const entry of entries) {
+ const match = /^o-(\d+)-[A-Za-z0-9_-]+\.sock$/.exec(entry)
+ if (!match) continue
+ const pid = Number(match[1])
+ if (!Number.isFinite(pid) || pid === ownPid) continue
+ try {
+ process.kill(pid, 0)
+ // Pid is alive — leave its socket alone. Another Orca instance owns it.
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ESRCH') {
+ try {
+ rmSync(join(userDataPath, entry), { force: true })
+ } catch {
+ // Best-effort sweep; a permission error is fine to ignore.
+ }
+ }
+ }
+ }
+}
+```
+
+**Constraints:** only sweep sockets with the exact `o--.sock` shape; skip anything else. Never touch the current process's own pid even though the stricter `start()` flow already rmSync's it.
+
+**Windows note:** this sweep is POSIX-only by construction — on Windows the transport is a named pipe (`\\.\pipe\orca--`) and named pipes don't leave filesystem entries in `userData`. No sweep needed.
+
+**Socket-name invariant:** the sweep regex `^o-(\d+)-[A-Za-z0-9_-]+\.sock$` must stay in lockstep with `createRuntimeTransportMetadata()` in `runtime-rpc.ts`, which emits `o-${pid}-${endpointSuffix}.sock`. The cheap guard — and what this doc recommends — is a unit test that constructs a transport name via `createRuntimeTransportMetadata()` and asserts the sweep regex matches it; any future change to the socket-name shape trips the test. Longer-term, if the transport name grows more fields, the preferred answer is to export a shared constant or factory from `runtime-rpc.ts` that both the creator and the sweep regex consume, so the two can never drift by construction. Deferred here to keep the diff surgical.
+
+## Deliberately not in scope
+
+- **No CLI-side reader fallback.** Scanning for any live `o-*.sock` in `getCliStatus()` would require a per-socket sidecar metadata file (authToken, runtimeId) since today only one shared `orca-runtime.json` exists. That is a multi-instance-by-design change, not a bug fix. The fix above assumes the intended model is one Orca per userData.
+- **No per-instance userData.** The env-var override `ORCA_USER_DATA_PATH` at `src/cli/runtime/metadata.js` already exists for power users who genuinely want parallel runtimes. No change.
+- **No unlink of `endpoint.env` on stop.** The deferred-cleanup rationale at `src/main/agent-hooks/server.ts:1230-1237` (TOCTOU with a concurrent writer) is still correct under the single-instance lock: auto-update handoff still briefly has two processes sharing the file. Leaving the file unchanged on quit matches the existing fail-open policy and no user symptom motivates changing it.
+
+## Testing strategy
+
+### Unit tests (`src/main/runtime/runtime-metadata.test.ts`, extend)
+
+- `clearRuntimeMetadataIfOwned` with matching `{pid, runtimeId}` → file removed.
+- `clearRuntimeMetadataIfOwned` with mismatched pid → file retained.
+- `clearRuntimeMetadataIfOwned` with mismatched runtimeId → file retained (simulates another instance having overwritten while we were still alive).
+- `clearRuntimeMetadataIfOwned` with no file → no-op, no throw.
+
+### Unit tests (new `src/main/runtime/runtime-socket-sweep.test.ts`)
+
+Seed a temp userData directory with four entries so the three retention branches are distinct:
+
+- `o-1-aaaa.sock` → own-pid-skipped branch (test passes `ownPid: 1`, so this is skipped via the `pid === ownPid` early-exit).
+- `o--bbbb.sock` → alive-but-not-own branch (`process.kill(pid, 0)` succeeds without `ESRCH` → retained).
+- `o-99999999-cccc.sock` → dead-pid branch (`process.kill(pid, 0)` throws `ESRCH` → swept).
+- `foo.sock` → non-matching-shape branch (regex miss → retained untouched).
+
+Run sweep with `ownPid = 1` and assert: the `o-99999999-*.sock` file is gone; the other three remain. Using a synthetic `ownPid` (init pid `1`, effectively always alive on POSIX and never the test runner's own pid) means each of the three retained-entries covers a *distinct* code path, instead of collapsing "own-pid-skipped" and "alive-non-own-pid-retained" into the same observation.
+
+### Helper extraction for the single-instance lock
+
+Extract the lock acquisition into `src/main/startup/single-instance-lock.ts`:
+
+```ts
+export function acquireSingleInstanceLock(
+ app: Electron.App,
+ onSecondInstance: () => void
+): boolean {
+ if (!app.requestSingleInstanceLock()) {
+ return false
+ }
+ app.on('second-instance', onSecondInstance)
+ return true
+}
+```
+
+`src/main/index.ts` wires it up inline after `configureDevUserDataPath(is.dev)`. Because the module's top-level cannot `return`, gate the file-writing init (`initDataPath` / `initStatsPath` / `initClaudeUsagePath` / `initCodexUsagePath` / `enableMainProcessGpuFeatures` / `installDevParentWatchdog` / `installDevParentDisconnectQuit`) behind an `if (hasSingleInstanceLock)` block and let the lifecycle handler registrations fire unconditionally — `app.quit()` prevents `whenReady` from ever dispatching, so `runtime` / `runtimeRpc` / `store` / `stats` stay `null` and every shutdown handler short-circuits via optional chaining:
+
+```ts
+const hasSingleInstanceLock = acquireSingleInstanceLock(app, focusExistingWindow)
+if (!hasSingleInstanceLock) {
+ if (is.dev) {
+ console.log(
+ '[single-instance] Another Orca instance is already running against this userData path — focusing existing window.'
+ )
+ }
+ app.quit()
+}
+
+if (hasSingleInstanceLock) {
+ installDevParentDisconnectQuit(is.dev)
+ installDevParentWatchdog(is.dev)
+ initDataPath()
+ initStatsPath()
+ initClaudeUsagePath()
+ initCodexUsagePath()
+ enableMainProcessGpuFeatures()
+}
+```
+
+### Unit test of the helper (`src/main/startup/single-instance-lock.test.ts`)
+
+With a fake `app` (stub `requestSingleInstanceLock()` + `on()`):
+
+- When `requestSingleInstanceLock()` returns `false` → helper returns `false` and does NOT register `'second-instance'`.
+- When it returns `true` → helper returns `true` and registers exactly one `'second-instance'` listener that invokes the callback.
+
+### Integration assertion (narrow)
+
+Do NOT try to assert "downstream service constructors were not invoked" by re-importing `src/main/index.ts`. Module-level side effects at lines 67-101 (dev watchdog, shell path hydration, userData path configuration) run before the lock check and would fire regardless, either failing the test or requiring heavy mocking.
+
+Instead, the integration surface the fix cares about is already covered by: (a) the helper unit test above, and (b) the manual repro below. If deeper coverage is wanted later, the right move is to refactor `src/main/index.ts` so the `whenReady`-guarded setup is exported as a testable function — that is a separate refactor and deliberately out of scope for this fix.
+
+### Manual repro (matches the issue's steps)
+
+1. Launch packaged Orca. `cp ~/.config/orca/orca-runtime.json /tmp/before.json`.
+2. Launch the AppImage / `.app` a second time. Verify the existing window receives focus (no new window appears) and `stat` shows `orca-runtime.json` mtime is unchanged.
+3. Quit Orca. Verify `~/.config/orca/orca-runtime.json` is gone and `orca status --json` reports `runtime.state = 'not_running'` (not `'stale_bootstrap'`).
+4. Kill a running Orca with `SIGKILL`. Verify that the next Orca launch removes the orphaned `o--*.sock` during `OrcaRuntimeRpcServer.start()`.
+
+### Regression watch — auto-updater
+
+`autoUpdater.quitAndInstall()` in `src/main/updater.ts:194` triggers the relaunch flow. The handoff is short (~1s) but non-atomic, so the design relies on the ownership guard to keep both interleavings safe:
+
+- **Socket is removed before the new process binds.** The old process's `runtimeRpc.stop()` `rmSync`'s `o--*.sock` as part of teardown. The new process then binds its own `o--*.sock`. The brief window of inconsistency is "metadata absent" + "no socket", never "metadata points at a live-but-wrong pid with a still-mounted old socket."
+- **New writes before old clears (Ordering Y).** If the new process calls `writeRuntimeMetadata()` before the old process's `clearRuntimeMetadataIfOwned()` runs, the guard sees `current.pid !== ownedPid` (and `current.runtimeId !== ownedRuntimeId`) and suppresses the clear. The new metadata survives.
+- **Old clears before new writes (Ordering X).** The old process finds its own pid + runtimeId in the file, clears it, and exits. The new process then writes its fresh metadata onto an empty slot. Same end state.
+- **CLI behavior during the ~1s window.** `orca status` transitions `ready` → `not_running` (clean, not `stale_bootstrap`) → `starting` → `ready`. It never reports a wrong-pid reading, because the only two observable file states are "file for old pid" (pre-teardown) and "file for new pid" (post-write); the guard prevents a mixed state.
+
+A future regression report that catches the transient `not_running` during an auto-update should be recognized as intended behavior.
+
+### Cross-platform coverage
+
+- **macOS / Linux / Windows:** single-instance lock path is identical (Electron handles the OS-level plumbing).
+- **Windows:** named-pipe transport means no socket-sweep work; assert the sweep early-returns on `platform === 'win32'` (or simply does nothing because no matching entries exist).
+- **Dev mode:** lock acquired against `orca-dev` userData; asserted by running `pnpm dev` twice and seeing the second exit immediately.
+
+## Confidence
+
+High. The diagnosis matches the reported symptom and filesystem evidence one-for-one; the fix adds only calls that Electron and the existing metadata module already expose. Second opinion from codex flagged the `configureDevUserDataPath` ordering constraint and the `clearRuntimeMetadataIfOwned` ownership guard, both incorporated above.
+
+Concretely, the fix closes the reported data-integrity scenarios: double-click relaunch, `gtk-launch` relaunch, clean-quit of a second instance while the first stays open, and orphaned `o--*.sock` files left by SIGKILL / OOM-kill. It deliberately leaves two narrow scenarios open: (1) the auto-updater handoff, where `orca status` may transiently report `not_running` for ~1s between the old process's clear and the new process's write — covered in the regression-watch section above; and (2) deliberate multi-instance launches via `ORCA_USER_DATA_PATH` / `ORCA_DEV_USER_DATA_PATH`, which remain an explicit power-user escape hatch with isolated userData per instance and are not in scope for this fix.
diff --git a/docs/fix-pty-fd-leak.md b/docs/fix-pty-fd-leak.md
new file mode 100644
index 000000000..120540787
--- /dev/null
+++ b/docs/fix-pty-fd-leak.md
@@ -0,0 +1,628 @@
+# Fix per-session PTY fd leak in the current daemon
+
+## Status: resolved (2026-05-01)
+
+**Native-side root cause confirmed and patched.** E2E validation under both Node and Electron ABIs: 50 spawn/kill cycles, ptmx count stays at baseline (0). Before the patch, the same harness reproduced a 1-fd-per-spawn linear leak (5 → 55 ptmx fds over 50 cycles).
+
+## Root cause (actual)
+
+The leak is a native-side off-by-one in `node-pty@1.1.0`'s `pty_posix_spawn` cleanup loop on macOS. In `src/unix/pty.cc`:
+
+- **Allocation** (lines 697-701) walks `low_fds[0..2]`, allocating via `posix_openpt(O_RDWR)`. The loop `break`s at the first `low_fds[count] >= STDERR_FILENO`, so `count` holds the index of the last allocated slot (0, 1, or 2). These are decoy `/dev/ptmx` handles used as a workaround for a macOS pty race condition that ensures the real master fd lands above `STDERR_FILENO`.
+- **Cleanup** (lines 781-783, buggy):
+ ```c
+ for (; count > 0; count--) {
+ close(low_fds[count]);
+ }
+ ```
+ When the typical case triggers (`break` at `count=0`, i.e. the very first `posix_openpt` returned an fd ≥ 2), the loop body never executes — `low_fds[0]` is never closed. Every spawn leaks one ptmx handle.
+
+Upstream fixed this in commit [`af053f2`](https://github.com/microsoft/node-pty/commit/af053f2) (PR #882, 2026-01-28), but version 1.1.0 (pinned here) predates that fix.
+
+**Applied fix:** minimal 3-line backport in `config/patches/node-pty@1.1.0.patch`:
+
+```c
+- for (; count > 0; count--) {
+- close(low_fds[count]);
++ for (size_t i = 0; i <= count && i < 3; i++) {
++ close(low_fds[i]);
+ }
+```
+
+The `i < 3` bound is an over-cautious defense against the pathological case where all three `posix_openpt` calls returned fds < `STDERR_FILENO` (loop exhausts to `count=3`, which would otherwise read `low_fds[3]` — UB in upstream's fix too, though unreachable in practice).
+
+## Why the JS-side `destroy()` discipline (below) is still correct
+
+The native patch alone closes the leak. But the JS-side changes landed in `pty-subprocess.ts`, `session.ts`, `terminal-host.ts`, `local-pty-provider.ts`, and `relay/pty-handler.ts` remain load-bearing for separate reasons:
+
+1. **SIGHUP-to-recycled-pid hazard.** `UnixTerminal.destroy()` registers `_socket.once('close', () => this.kill('SIGHUP'))`. After the child is reaped, its pid can be recycled to an unrelated user process (Chrome tab, editor, etc.) before the socket close event fires. Neutralizing `proc.kill` on POSIX before `destroy()` prevents delivering SIGHUP to a stranger.
+2. **`forceKill`/`signal` guard against recycled pid.** `process.kill(proc.pid, …)` after `onExit` targets a potentially-recycled pid. The internal `dead` guard converts these into no-ops.
+3. **Daemon shutdown determinism.** `TerminalHost.dispose()` → `Session.forceKillAndDisposeSubprocess()` reaps stubborn children via SIGKILL and releases the master fd synchronously, bypassing the 5s `KILL_TIMEOUT_MS` fallback.
+4. **Belt-and-suspenders fd release.** Calling `destroy()` on every teardown path remains the contract that will keep holding if the pinned node-pty is ever replaced or upgraded to a build without the bug.
+
+## Original problem statement (for historical context)
+
+## Problem
+
+The current `daemon-v4` is leaking PTY master file descriptors (`ptmx`) at a rate roughly 20× the live session count. In a real reported case, the live v4 daemon was holding **269 `ptmx` fds for only 13 active terminals** — every closed terminal should have returned its `ptmx` to the OS, but the daemon keeps accumulating them until it hits macOS's `kern.tty.ptmx_max=511` cap and every new terminal (Orca or otherwise) fails with "cannot allocate any more pty devices."
+
+This is a distinct bug from the orphaned-daemon issue handled in [auto-kill-old-daemons.md](./auto-kill-old-daemons.md):
+
+| Bug | Fd leak unit | Lifetime | Fix surface |
+|---|---|---|---|
+| Orphaned daemons | Whole daemon process | Across app upgrades | `daemon-init.ts`, `daemon-pty-router.ts` |
+| **This doc** | Per-PTY `ptmx` | Within any node-pty-hosting process | `pty-subprocess.ts` (daemon), `local-pty-provider.ts` (legacy), `relay/pty-handler.ts` (SSH) + wiring |
+
+Both bugs compound each other (stale daemons × leaky sessions), but either one is sufficient to exhaust the cap in a few days of normal use. Fixing orphan daemons alone would only slow down the bleed — the PTY wrappers themselves must stop leaking.
+
+The same missing `destroy()` call exists in all three node-pty-hosting code paths (daemon, legacy local provider, SSH relay), so the fix is scoped to all three.
+
+### Root cause
+
+The master ptmx fd is owned by a `tty.ReadStream` that node-pty stores on the `UnixTerminal` instance as `_socket` (see `node_modules/node-pty/lib/unixTerminal.js`). That socket wraps the fd via libuv. The fd only gets closed when the socket is destroyed, and the socket is only destroyed by one of:
+
+1. `UnixTerminal.destroy()` — calls `_close()`, then `_socket.destroy()`, then `_writeStream.dispose()`.
+2. The socket's own `'close'` / `'error'` event firing, which hits the `self._socket.on('close', ...)` wiring inside node-pty's constructor.
+
+None of our current teardown paths reliably trigger either. Specifically:
+
+1. **`forceKill` via raw `process.kill(pid, 'SIGKILL')`** (`pty-subprocess.ts:159-168`) kills the child but does nothing to the libuv socket on the parent side. The slave fd closing in the kernel does not, by itself, cause the parent's read-side socket to emit `'close'` on all platforms / node versions — and even when it does, it races GC.
+2. **`dead = true` after a thrown native error** (`pty-subprocess.ts:127-157`) leaves the `_socket` fully alive. We just stop touching `proc`; the read stream keeps the fd.
+3. **Session `dispose()` / `handleSubprocessExit`** (`session.ts:189-228`, `session.ts:250-271`) never call anything that reaches `_socket.destroy()`. They kill the child and move on.
+
+So the fd leaks until the JS wrapper is GC'd and libuv finalizes the stream — which may be much later, or never, within the daemon's lifetime. Evidence from the reported case is consistent with this: 269 ptmx − 13 live ≈ 256 orphaned fds from terminals that were opened and closed during the daemon's lifetime, which matches a few days of create/kill churn at ~50-100 terminal ops/day.
+
+node-pty already exposes the fix: `UnixTerminal.prototype.destroy` (unixTerminal.js:219) and `WindowsTerminal.prototype.destroy` (windowsTerminal.js:141). We just never call it.
+
+## Goals
+
+- After a PTY terminates (by any path — natural exit, kill, force-kill, native throw, disposal), the master fd is released to the OS on the same tick as teardown.
+- The fix covers every code path in the repo that spawns `node-pty`: the daemon, the legacy local provider, and the SSH relay.
+- Zero regressions to the `dead` flag pattern (`pty-subprocess.ts:119-122`) that prevents `Napi::Error` from killing the daemon.
+- No renderer-visible change. Public IPC / RPC contracts are untouched.
+- Measurable: a repeatable test harness spawns N PTYs, terminates them via each exit path, and asserts the fd count returns to baseline.
+
+## Non-goals
+
+- Fixing the orphaned-daemon issue. Handled in [auto-kill-old-daemons.md](./auto-kill-old-daemons.md).
+- Killing daemon-side sessions when a worktree is deleted. Separate follow-up.
+- Upgrading or replacing `node-pty`. We are calling node-pty's existing `destroy()` — no library change needed.
+- Adding a generic "fd leak monitor" watchdog. Observability belongs in a separate effort (see Related work).
+
+## Design decisions
+
+### Call `node-pty`'s `destroy()` on every teardown path
+
+The fix is exactly that. Each provider already wraps the raw `IPty` in its own small handle/struct. Add a single `dispose()` entry point on those wrappers whose body does:
+
+```ts
+try {
+ ;(proc as unknown as { destroy?: () => void }).destroy?.()
+} catch {
+ /* swallow — already torn down, or native-side error we can't recover from */
+}
+```
+
+That is the primary mechanism. `destroy()` is what drives `_close()` → `_socket.destroy()` → `_writeStream.dispose()` inside node-pty, which is what releases the master fd. Everything else the wrapper needs (idempotency, callback nulling, SIGKILL fallback for unresponsive children) is a local concern layered around that single call.
+
+### Why not reinvent `destroy()`
+
+An earlier draft of this design proposed a hand-rolled body: null callbacks + raw SIGKILL + `proc.kill()` in try/catch. That was wrong. None of those steps touch `_socket`, which is the thing holding the fd. The only reliable trigger is the close path node-pty already ships — `UnixTerminal.prototype.destroy` on POSIX, `WindowsTerminal.prototype.destroy` on ConPTY. Duplicating that logic in our wrappers would (a) not work on POSIX anyway because `_socket` is private and (b) drift from upstream on any future node-pty update. Forward to `destroy()`, layer idempotency and error-swallowing on top, stop.
+
+### Shared handle contract
+
+Each provider exposes a dispose entry point with the same semantics: idempotent, synchronous, throws never. The daemon already has a `SubprocessHandle` type that is the right place to hang it; the local provider and relay each have equivalent internal records (`ptyProcesses` / `ManagedPty`) and get a small helper function that wraps the same `destroy()` call plus their provider-specific bookkeeping (listener disposal, map cleanup).
+
+```ts
+// src/main/daemon/session.ts
+export type SubprocessHandle = {
+ pid: number
+ write(data: string): void
+ resize(cols: number, rows: number): void
+ kill(): void
+ forceKill(): void
+ signal(sig: string): void
+ onData(cb: (data: string) => void): void
+ onExit(cb: (code: number) => void): void
+ /** Release the native PTY handle via node-pty's own destroy() path.
+ * Idempotent. Safe to call after exit. Called by Session on every teardown
+ * path (natural exit, kill, force-kill, native throw, session dispose). */
+ dispose(): void
+}
+```
+
+### Daemon: `pty-subprocess.ts`
+
+Track a `disposed` flag. `dispose()`:
+
+1. If already disposed, return.
+2. Mark `disposed = true` and `dead = true`.
+3. Null the JS-side `onDataCb` / `onExitCb` references so the wrapper stops fanning out anything after destroy.
+4. **On POSIX only, neutralize `proc.kill` on this instance.** Replace it with a no-op before step 5. This closes the pid-recycle SIGHUP hazard described below. Windows is exempt because `WindowsTerminal.destroy` *is* a call to `kill()` — neutralizing it turns destroy() into a no-op and leaks the ConPTY agent.
+5. Call `proc.destroy()` inside try/catch. On Unix this runs `_close()` → `_socket.destroy()` → `_writeStream.dispose()`; on Windows it defers to the ConPTY agent's close via `_deferNoArgs(_this.kill())` (`windowsTerminal.js:141-146`).
+
+```ts
+dispose(): void {
+ if (disposed) return
+ disposed = true
+ dead = true
+ onDataCb = null
+ onExitCb = null
+ // Why: node-pty's UnixTerminal.destroy() registers `_socket.once('close', () => this.kill('SIGHUP'))`
+ // (unixTerminal.js:219-229). On the dispose-while-alive path (e.g. daemon shutdown
+ // of an active session), SIGTERM has already been sent. The socket close fires
+ // asynchronously; by then the child may have exited and its pid been recycled
+ // to an unrelated process. Without this neutralization, SIGHUP can be delivered
+ // to a Chrome tab, editor, or other user process — silent cross-app corruption.
+ // `_socket.destroy()` still releases the fd; only the dangerous SIGHUP is removed.
+ //
+ // Platform guard: WindowsTerminal.destroy() implements the ConPTY close by
+ // CALLING `this.kill()` via `_deferNoArgs` (windowsTerminal.js:141-146). If we
+ // neutralize `kill` on Windows, destroy() becomes a no-op and the ConPTY
+ // agent leaks. The SIGHUP hazard is POSIX-only, so the neutralization is too.
+ if (process.platform !== 'win32') {
+ ;(proc as unknown as { kill?: (sig?: string) => void }).kill = () => {}
+ }
+ try {
+ ;(proc as unknown as { destroy?: () => void }).destroy?.()
+ } catch {
+ /* swallow — already torn down, or native-side error we can't recover from */
+ }
+}
+```
+
+`kill` neutralization lives on this `proc` instance only — the wrapper's exposed `kill()` / `forceKill()` entry points call `process.kill(proc.pid, sig)` directly (`pty-subprocess.ts:149-175`), which is unaffected. Callers that want to send SIGTERM/SIGKILL still can; what they can't do after dispose is have node-pty's internal close listener deliver an unexpected SIGHUP against a stale pid.
+
+No extra SIGKILL is needed from `dispose()`: `forceKill` remains available as a separate entry point for the "we need the child gone now" case. Callers that want both (Session on timeout) call `forceKill()` then `dispose()`.
+
+### Daemon: Session / TerminalHost wiring
+
+`Session.dispose()` (`session.ts:189-228`) and `Session.handleSubprocessExit()` (`session.ts:250-271`) each call `this.subprocess.dispose()`:
+
+- `handleSubprocessExit`: call it immediately after updating `_state = 'exited'` and before fan-out to `attachedClients`. try/catch around the call — a throwing dispose must not prevent exit-code delivery.
+- `dispose()`: call it at the end, after `emulator.dispose()` and after the attached-client fanout.
+- `forceDispose()` (`session.ts:319-347`): same as `dispose()`.
+
+`subprocess.dispose()` is idempotent because `handleSubprocessExit` and the outer `dispose()` can both fire for the same session (manual kill → child exits → handleSubprocessExit runs → later Session.dispose runs).
+
+`TerminalHost.dispose()` (`terminal-host.ts:215-240`) already kills every session. Replace the `session.kill()` call in the shutdown loop with a new `session.forceKillAndDisposeSubprocess()` method, so daemon shutdown reaps stubborn children (SIGKILL) AND releases the PTY master fd synchronously — without depending on the 5s `KILL_TIMEOUT_MS` eventually calling `forceDispose`:
+
+```ts
+for (const [, session] of this.sessions) {
+ session.detachAllClients()
+ session.forceKillAndDisposeSubprocess() // synchronous; bypasses the 5s timer
+}
+// Preserve existing post-loop cleanup: sessions.clear(), killedTombstones.clear(),
+// and any cleanup callbacks fire unchanged after the loop. Only the per-session
+// kill() → forceKillAndDisposeSubprocess() substitution is new.
+```
+
+**Why `forceKillAndDisposeSubprocess` instead of `kill() + disposeSubprocess()`.** Today's shutdown path is `session.kill()` (SIGTERM, start 5s timer) → if the child ignores SIGTERM, `forceDispose()` eventually fires and sends SIGKILL. That 5s fallback is load-bearing: shells with traps, hung compilers, and long-running processes with signal handlers routinely ignore SIGTERM. The earlier draft dropped `killTimer` during disposeSubprocess, which would close the fd but leave the child orphaned at the OS level — worse than today's behavior. `forceKillAndDisposeSubprocess` explicitly sends SIGKILL (via `subprocess.forceKill()`) before releasing the fd, so stubborn children are still reaped synchronously:
+
+```ts
+// Public: orderly-shutdown path. Force-kills the child (SIGKILL is not
+// ignorable), then releases the PTY master fd synchronously. Used only by
+// TerminalHost.dispose() — renderer reconnects cold after daemon exit.
+forceKillAndDisposeSubprocess(): void {
+ // Why: forceKill before the subprocess dispose. disposeSubprocess below
+ // neutralizes node-pty's kill() on POSIX, which is what the internal SIGHUP
+ // close listener would call. forceKill uses process.kill(pid, 'SIGKILL')
+ // directly (pty-subprocess.ts:159-168) — unaffected by the neutralization,
+ // because it does not go through proc.kill. SIGKILL is not ignorable; any
+ // child that would have survived the 5s timer is reaped immediately.
+ try {
+ this.subprocess.forceKill()
+ } catch {
+ /* swallow — child may already be gone */
+ }
+ this.#teardownSubprocess()
+}
+```
+
+`disposeSubprocess()` is a tight helper — it flips the session to the terminal state, cancels any pending timers, and forwards to the subprocess dispose. It deliberately does not fan out `onExit` to attached clients, because `TerminalHost.dispose()` is the orderly-shutdown path and the renderer will reconnect cold.
+
+**Shared `#teardown` helper.** Both `Session.dispose()` and `Session.disposeSubprocess()` mutate the same state (`_disposed`, `_state`, `killTimer`, `shellReadyTimer`) and forward to `this.subprocess.dispose()`. Route them through a single private helper `#teardownSubprocess()` so the state transition is defined exactly once — two dispose paths that drift on which flag gets flipped would be a merge hazard (a future change to one that forgets the other silently drops exit events):
+
+```ts
+// Session — shared private helper, called by both public paths.
+#teardownSubprocess(): void {
+ if (this._disposed) return
+ this._disposed = true
+ // Note: `_state = 'exited'` is NOT set here — the outer caller (Session.dispose,
+ // Session.forceDispose) is responsible for the state transition AFTER capturing
+ // any invariants that depend on the pre-flip value. See the `wasTerminating`
+ // capture in Session.dispose for the load-bearing example.
+ if (this.killTimer) { clearTimeout(this.killTimer); this.killTimer = null }
+ if (this.shellReadyTimer) { clearTimeout(this.shellReadyTimer); this.shellReadyTimer = null }
+ try {
+ this.subprocess.dispose()
+ } catch (err) {
+ // Why: dispose() is documented never to throw, but if it does we must not
+ // prevent callers from completing their own cleanup (fanout, map removal).
+ console.warn('[Session] subprocess.dispose() threw:', err)
+ }
+}
+
+// Public: orderly-shutdown path. Does NOT broadcast onExit to clients; the
+// renderer reconnects cold after TerminalHost.dispose(). Sets _state = 'exited'
+// after teardown because this path has no pre-flip invariants to preserve.
+disposeSubprocess(): void {
+ this.#teardownSubprocess()
+ this._state = 'exited'
+}
+
+// Public: existing Session.dispose() — MUST capture `wasTerminating` BEFORE
+// calling #teardownSubprocess, because the check depends on `_state !== 'exited'`
+// being the PRE-flip value. Forgetting this check would orphan processes that
+// ignored SIGTERM (the `_isTerminating && _state !== 'exited'` guard at
+// session.ts:200 is the only path that calls `subprocess.forceKill()` in the
+// dispose-while-terminating case).
+dispose(): void {
+ // Why: captured BEFORE the `_state = 'exited'` flip at line 230. This check
+ // guards the "dispose while kill() was already in flight" case — if true,
+ // the child hasn't reaped yet and we need to forceKill it here (the 5s
+ // killTimer is also about to be cleared by #teardownSubprocess). Matches
+ // the existing invariant at session.ts:200. Do not move this line below
+ // #teardownSubprocess or the `_state = 'exited'` assignment.
+ const wasTerminating = this._isTerminating && this._state !== 'exited'
+ const clientsToNotify = wasTerminating ? this.attachedClients.slice() : []
+
+ if (wasTerminating) {
+ // Existing forceDispose semantics — child hasn't reaped yet, force it now.
+ try { this.subprocess.forceKill() } catch { /* already dead */ }
+ this._exitCode = -1
+ this._isTerminating = false
+ }
+
+ this.#teardownSubprocess()
+ this._state = 'exited'
+
+ this.attachedClients = []
+ this.preReadyStdinQueue = []
+ this.postReadyFlushGate.clear()
+ this.emulator.dispose()
+
+ for (const client of clientsToNotify) {
+ client.onExit(-1)
+ }
+}
+```
+
+Single source of truth for the state transition. If we ever need to add a new piece of tear-down state, one edit keeps both paths in sync. The asymmetry (`_state = 'exited'` lives in the public methods, not the helper) is deliberate: `dispose()` has a pre-flip invariant (`wasTerminating`) to preserve, `disposeSubprocess()` doesn't. Forcing both through a single helper that flipped `_state` would reintroduce the ordering bug.
+
+**`forceDispose()` must also route through the helper.** `forceDispose` fires from the 5s `killTimer` when a SIGTERM'd child refused to exit (`session.ts:319-347`). This is the exact kill-timeout path this fd-leak fix targets — if `forceDispose` doesn't call `subprocess.dispose()`, the ptmx fd leaks on every force-kill. The current body flips `_disposed = true` directly at `session.ts:324`, which would short-circuit a later `Session.dispose()` call from `TerminalHost` tombstone cleanup at `#teardownSubprocess`'s `if (this._disposed) return` guard, silently skipping `subprocess.dispose()`.
+
+```ts
+// Private: fires from the 5s killTimer when SIGTERM was ignored.
+// `_state === 'exited'` already short-circuits above; below that guard the
+// session is still running, so the fd is still open. MUST release it.
+private forceDispose(): void {
+ if (this._state === 'exited') {
+ return
+ }
+ // Why: unlike dispose(), forceDispose has no pre-flip invariants to capture.
+ // The caller (killTimer) has no attached-client fanout obligation beyond
+ // what the helper + the existing client loop below cover. Route the
+ // subprocess tear-down through the shared helper so `proc.destroy()` runs
+ // exactly once and `_disposed` is flipped in the same transition.
+ try { this.subprocess.forceKill() } catch { /* already dead */ }
+ this._exitCode = -1
+ this._isTerminating = false
+
+ this.#teardownSubprocess() // ← sets _disposed = true, calls subprocess.dispose()
+ this._state = 'exited'
+
+ const clients = this.attachedClients
+ this.attachedClients = []
+ this.preReadyStdinQueue = []
+ this.postReadyFlushGate.clear()
+ this.emulator.dispose()
+
+ for (const client of clients) {
+ client.onExit(-1)
+ }
+}
+```
+
+Order matters. `forceKill()` must run BEFORE `#teardownSubprocess()` — the helper's `subprocess.dispose()` neutralizes `proc.kill` on POSIX, but `subprocess.forceKill()` uses `process.kill(proc.pid, 'SIGKILL')` directly and is unaffected by that neutralization. If we reorder, nothing changes functionally, but the explicit order documents the invariant.
+
+After `session.forceKillAndDisposeSubprocess()`, the 5s `killTimer` started by any prior `kill()` is cleared, so `forceDispose` cannot fire against an already-disposed subprocess. Even if the timer somehow survived the clear, `_state` is now `'exited'` and `forceDispose`'s early-return guard (`session.ts:320`) would short-circuit it.
+
+### LocalPtyProvider
+
+`local-pty-provider.ts` stores each spawned `IPty` in a module-level `ptyProcesses` map and has two teardown sites: `shutdown(id)` (single PTY) and `killAll()` / `safeKillAndClean()` (bulk). Both currently call `proc.kill()` and delete the map entry.
+
+Change: add a `destroyPtyProcess(proc)` helper. Same shape as `disposeManagedPty` in the relay: on POSIX, neutralize `proc.kill` before calling `destroy()` to close the same SIGHUP-to-recycled-pid hazard; on Windows, skip the neutralization because `WindowsTerminal.destroy` calls `kill()` internally. Invoke the helper at the end of `safeKillAndClean` (after listener disposal, after `proc.kill()`), at the end of `shutdown` (same spot), and in the natural-exit `onExit` path after `clearPtyState(id)`.
+
+```ts
+function destroyPtyProcess(proc: IPty): void {
+ // Why: same SIGHUP-to-recycled-pid hazard as the daemon and relay paths.
+ // UnixTerminal.destroy() registers `_socket.once('close', () => this.kill('SIGHUP'))`.
+ // LocalPtyProvider's own kill() has already fired; if the close listener
+ // delivers a trailing SIGHUP after pid recycling, it lands on a random user
+ // process. Local machines recycle pids fast — regression risk is highest here.
+ // Windows exempt: WindowsTerminal.destroy IS a kill() call via _deferNoArgs.
+ if (process.platform !== 'win32') {
+ ;(proc as unknown as { kill?: (sig?: string) => void }).kill = () => {}
+ }
+ try {
+ ;(proc as unknown as { destroy?: () => void }).destroy?.()
+ } catch {
+ /* swallow — already torn down */
+ }
+}
+```
+
+The natural-exit `onExit` invocation is load-bearing: without it, a shell that exits cleanly (the common case) never releases its ptmx fd until the next GC. `onExit` is also the only path that runs without an external kill having been issued, so the neutralization is defensive against future reorderings — today `proc.kill` is a no-op after the child is reaped, but the kernel may still emit the close event.
+
+### Relay: `relay/pty-handler.ts`
+
+`PtyHandler` stores each `IPty` on a `ManagedPty` record. Teardown happens in five places:
+
+- `shutdown(params)` — SIGTERM + 5s SIGKILL fallback, or SIGKILL immediately when `immediate === true`.
+- The `onExit` wiring inside `wireAndStore` — deletes the map entry.
+- `spawn()`'s stale-context path (`pty-handler.ts:144-154`) — client reconnected before the PTY response was delivered, so the PTY is orphaned and gets SIGTERM + 5s SIGKILL fallback.
+- `dispose()` — loops every managed pty and shuts it down.
+- `sendSignal()` — public entry point that forwards arbitrary signals; must keep working after dispose is queued.
+
+Change (ordering matters):
+
+1. **`onExit` wiring**: after the map-delete, call `disposeManagedPty(managed)`. This is the natural-exit path — the child has already exited and been reaped. Neutralizing `pty.kill` here is defensive: any trailing invocation from the socket close listener is no-op'd regardless of pid-recycle timing. The fd is released synchronously.
+2. **`shutdown(params)` with `immediate === true`**: after `managed.pty.kill('SIGKILL')`, call `disposeManagedPty(managed)`. SIGKILL has already reaped the child.
+3. **`shutdown(params)` graceful path (SIGTERM)**: do **not** call `destroy()` immediately after the SIGTERM send. The 5s `killTimer` and the natural `onExit` already cover fd release via step 1. Calling `destroy()` right after SIGTERM collapses the graceful-shutdown window and risks interrupting shell `EXIT` traps or cleanup hooks that run between SIGTERM and shell exit. If the `killTimer` fires (SIGKILL fallback), the SIGKILL reaps the child and `onExit` (step 1) calls `disposeManagedPty` on its own — **do not add a redundant call inside the killTimer closure**. The `disposed` guard makes a redundant call harmless but wiring it in both places is a merge hazard.
+4. **`spawn()` stale-context killTimer**: this path (`pty-handler.ts:149-153`) already sends SIGTERM then SIGKILL at 5s if the PTY wasn't acked. The relevant teardown path is `onExit` (step 1), which now calls `disposeManagedPty`. No code change needed in the stale-context branch itself — the onExit wiring in `wireAndStore` runs for this PTY the same as for any other. Confirmed covered.
+5. **`dispose()` loop**: call `disposeManagedPty` for each active managed pty AFTER `managed.pty.kill('SIGTERM')`. This is the relay-shutdown path — we accept that any in-flight shell cleanup is cut short because the relay process itself is exiting.
+
+The common shape, extracted into a helper:
+
+```ts
+function disposeManagedPty(managed: ManagedPty): void {
+ if (managed.disposed) return
+ managed.disposed = true
+ // Why: clear any pending 5s SIGKILL fallback timer. If graceful-shutdown
+ // armed a killTimer and the child then exited cleanly (firing onExit →
+ // disposeManagedPty), the timer would otherwise fire later and attempt
+ // pty.kill('SIGKILL') on an already-disposed instance. The ptys.has(id)
+ // guard inside the timer short-circuits today, but symmetry is clearer.
+ if (managed.killTimer) {
+ clearTimeout(managed.killTimer)
+ managed.killTimer = undefined
+ }
+ // Why: same SIGHUP-to-recycled-pid hazard as the daemon fix — neutralize
+ // node-pty's kill on the instance before calling destroy(). The relay
+ // typically runs on Linux remote hosts where pid recycling is fast.
+ // Windows exempt: WindowsTerminal.destroy calls kill() internally, so
+ // neutralizing it turns destroy() into a no-op.
+ if (process.platform !== 'win32') {
+ ;(managed.pty as unknown as { kill?: (sig?: string) => void }).kill = () => {}
+ }
+ try {
+ ;(managed.pty as unknown as { destroy?: () => void }).destroy?.()
+ } catch {
+ /* swallow */
+ }
+}
+```
+
+**`disposed` flag on `ManagedPty`.** The flag is new — add it to the `ManagedPty` type. Purpose: prevent `disposeManagedPty` from running twice (both `onExit` and `shutdown` can fire for the same PTY), and — more importantly — let `sendSignal`, `writeData`, and other pre-existing entry points short-circuit if the caller tries to use a disposed PTY:
+
+```ts
+private async sendSignal(params: Record): Promise {
+ // ... existing signal validation ...
+ const managed = this.ptys.get(id)
+ if (!managed || managed.disposed) {
+ throw new Error(`PTY "${id}" not found`)
+ }
+ managed.pty.kill(signal) // ← on POSIX this is neutralized-to-no-op only
+ // AFTER disposeManagedPty runs. The early return
+ // above means we never reach this line post-dispose.
+}
+```
+
+Without the `disposed` guard, a `sendSignal('SIGTERM')` call landing after `onExit` → `disposeManagedPty` has neutralized `managed.pty.kill` would silently succeed (return success, do nothing). The `disposed` check converts the silent failure into the existing "not found" error, which is what callers already handle.
+
+The graceful-SIGTERM path of `shutdown` remains unchanged (SIGTERM + 5s killTimer that sends SIGKILL). Fd release on that path happens either via the `onExit` hook (step 1) when the shell exits cleanly, or via the killTimer → SIGKILL → `onExit` chain if SIGTERM was ignored. Under no circumstance does `shutdown`'s graceful branch synchronously call `destroy()`.
+
+### Why not just replace `node-pty`
+
+Tempting, and probably correct long-term. Out of scope here: node-pty's API surface is deeply woven into the daemon, LocalPtyProvider, and the relay. Swapping it is a multi-week effort with its own regression surface. This bug is a one-line miss against an API the library already ships — fix that first.
+
+### Why not a daemon-level fd watchdog
+
+A periodic "count my open fds, restart if over threshold" watchdog would mask the bug, not fix it. It also introduces the exact timer-based lifecycle the orphan-daemon design [explicitly rejected](./auto-kill-old-daemons.md) for the same reasons (cold-restore instead of warm-reattach, false positives against live work). Observability yes, auto-restart no.
+
+## Interaction states
+
+Because this fix sits below the IPC layer, the renderer sees no state changes. All user-visible interaction states are identical to today:
+
+| Trigger | User-visible state | Behind the scenes (new) |
+|---|---|---|
+| Click "Close terminal" | Tab closes immediately | `terminal:kill` IPC → `Session.kill()` → `handleSubprocessExit` → `subprocess.dispose()` → `proc.destroy()` → fd released |
+| Shell exits naturally (`exit` / Ctrl-D) | Tab shows exit code | `handleSubprocessExit` → `subprocess.dispose()` → `proc.destroy()` → fd released |
+| Daemon is killed mid-session | Renderer reconnects cold on next app launch | On orderly shutdown: `TerminalHost.dispose()` loop → per-session `forceKillAndDisposeSubprocess()` — SIGKILL first (stubborn children reaped), then `proc.destroy()` releases the fd synchronously. Does not depend on the 5s `KILL_TIMEOUT_MS`. |
+| Child hits `Napi::Error` race | Silent (today) | Silent (same) — next teardown trigger reaches `subprocess.dispose()`, which forwards to `proc.destroy()` regardless of `dead` |
+| Session.kill hits `KILL_TIMEOUT_MS` | User sees "force-closed" log entry (unchanged) | `forceDispose` → `forceKill` + `subprocess.dispose()` → fd released |
+| SSH worktree session closed | Tab closes immediately | Relay `PtyHandler.shutdown` → SIGTERM + `managed.pty.destroy()` on exit → fd released on remote host |
+
+## Data flow
+
+```
+Renderer Main (IPC) Daemon (TerminalHost) node-pty
+ │ │ │ │
+ │ terminal:kill │ │ │
+ ├────────────────────────▶│ RPC: kill(sessionId) │ │
+ │ ├───────────────────────────▶│ Session.kill() │
+ │ │ ├─ subprocess.kill() ─────▶│ (SIGTERM)
+ │ │ │ │
+ │ │ │◀── onExit(code) ─────────│
+ │ │ │ handleSubprocessExit │
+ │ │ │ ├─ state='exited' │
+ │ │ │ ├─ subprocess.dispose()─┼─▶ destroy() →
+ │ │ │ │ │ _close() +
+ │ │ │ │ │ _socket.destroy() +
+ │ │ │ │ │ _writeStream.dispose()
+ │ │ │ │ │ → ptmx fd released ✔
+ │ │ │ └─ fanout onExit │
+ │ │◀─── event: 'exit' ─────────│ │
+ │◀── terminal:exit ───────│ │ │
+```
+
+### Failure paths
+
+**Natural exit.** Child dies, `proc` emits `onExit` → `handleSubprocessExit` → `subprocess.dispose()` → `proc.destroy()` → `_socket.destroy()` → fd released, same tick.
+
+**Explicit kill (`Session.kill`).** SIGTERM → child exits → same path as above.
+
+**Kill timeout.** Child ignores SIGTERM → `KILL_TIMEOUT_MS` elapses → `forceDispose` → `subprocess.forceKill()` (SIGKILL) + `subprocess.dispose()` (`proc.destroy()`). Fd released within 5s worst case.
+
+**Native throw.** `proc.write/resize/kill` throws `Napi::Error` → `dead = true`. Session is wedged but still reachable. The next teardown trigger (user close, daemon shutdown, worktree close) reaches `subprocess.dispose()`, which forwards to `proc.destroy()`. The destroy() body itself is try/catch-wrapped — if the native side is already half-torn-down and throws, we swallow; the socket side still gets destroyed by any prior event.
+
+**Daemon shutdown.** `TerminalHost.dispose()` iterates sessions and calls `session.forceKillAndDisposeSubprocess()` synchronously. The ordering is: SIGKILL (`subprocess.forceKill()` → `process.kill(pid, 'SIGKILL')`) → `subprocess.dispose()` → `proc.destroy()`. SIGKILL is not ignorable, so any child that would have survived the normal 5s `KILL_TIMEOUT_MS` SIGTERM window is reaped before the fd release. On POSIX, every `ptmx` fd is released before the daemon process exits. On Windows, `WindowsTerminal.destroy` defers via `_deferNoArgs` — dispose is enqueued but may not run synchronously; this is acceptable because ConPTY is not subject to the POSIX `ptmx` cap (see Risks).
+
+**Local provider (non-daemon).** `LocalPtyProvider.shutdown(id)` / `killAll()` / natural `onExit` all route through the new `destroyPtyProcess(proc)` helper, same `proc.destroy()` call. Fd released symmetrically with the daemon path.
+
+**Relay (SSH).** `PtyHandler.shutdown` and `PtyHandler.dispose` both call `managed.pty.destroy()` after the existing kill. On relay shutdown the loop is synchronous, so ptmx fds in the remote host's relay process are released before the relay exits.
+
+## Architectural fit
+
+```
+┌─ Daemon (forked) ───────────────┐ ┌─ Main process ─────────────┐ ┌─ Relay (remote host) ────┐
+│ TerminalHost │ │ LocalPtyProvider │ │ PtyHandler │
+│ └─ Session │ │ └─ ptyProcesses map │ │ └─ ManagedPty map │
+│ └─ SubprocessHandle │ │ (proc.destroy ←NEW)│ │ (pty.destroy ←NEW)│
+│ └─ dispose() ←NEW │ │ │ │ │
+│ └─ proc.destroy()│ └────────────────────────────┘ └──────────────────────────┘
+└─────────────────────────────────┘ │ │
+ │ └───────────┬─────────────────────┘
+ └───────────────┐ │
+ ▼ ▼
+ ┌──────────────────────────────────────────────┐
+ │ node-pty destroy() │
+ │ → _close() → _socket.destroy() → fd freed │
+ └──────────────────────────────────────────────┘
+```
+
+Three providers, one shared fix: forward the local dispose call to `node-pty.destroy()`. No new layer, no new dependency direction. Each provider already owns its handle lifecycle — we are filling a gap in three existing chains, not creating them.
+
+## Implementation plan
+
+### Files to change
+
+| File | Change |
+|---|---|
+| `src/main/daemon/session.ts` | Add `dispose(): void` to `SubprocessHandle` type. Add `forceKillAndDisposeSubprocess()` + `disposeSubprocess()` public methods. Add private `#teardownSubprocess()` helper that does NOT flip `_state` (see `dispose` section). Call `subprocess.dispose()` from `handleSubprocessExit`, `dispose`, `forceDispose`. Preserve the `wasTerminating = this._isTerminating && this._state !== 'exited'` invariant by capturing it BEFORE any state flip in the refactored `dispose`. |
+| `src/main/daemon/pty-subprocess.ts` | Implement `dispose()` on the returned handle. Idempotent. Nulls callbacks, sets `dead = true`, gates the `proc.kill = noop` neutralization on `process.platform !== 'win32'`, forwards to `(proc as unknown as { destroy?: () => void }).destroy?.()` in try/catch. |
+| `src/main/daemon/terminal-host.ts` | In `dispose()`, call `session.forceKillAndDisposeSubprocess()` instead of `session.kill()`. Preserves the SIGKILL-fallback behavior without depending on the 5s timer. |
+| `src/main/providers/local-pty-provider.ts` | Add `destroyPtyProcess(proc)` helper: gates `proc.kill = noop` neutralization on POSIX, then calls `proc.destroy()` in try/catch. Invoke from `safeKillAndClean`, `shutdown`, and the `onExit` path (after `clearPtyState`). |
+| `src/relay/pty-handler.ts` | Add `disposed: boolean` field to `ManagedPty`. In `wireAndStore`'s `onExit` (after map delete) and in `dispose()` loop, call `disposeManagedPty(managed)`. In `shutdown` immediate-path (after SIGKILL), call `disposeManagedPty`. In the 5s killTimer SIGKILL fallback (graceful path and spawn stale-context path), also call `disposeManagedPty`. Do **not** call it in the graceful SIGTERM branch. Guard `sendSignal`, `writeData`, `resize`, `getCwd`, `getInitialCwd`, `clearBuffer`, `hasChildProcesses`, `getForegroundProcess`, `attach` with `managed.disposed` checks (treat disposed as "not found"). |
+| `src/main/daemon/session.test.ts` | Add `dispose: vi.fn()` to `createMockSubprocess`. |
+| `src/main/daemon/terminal-host.test.ts` | Add `dispose: vi.fn()` to `createMockSubprocess`. |
+| `src/main/daemon/terminal-host-startup.test.ts` | Add `dispose: vi.fn()` to `mockSubprocess`. |
+| `src/main/daemon/production-launcher.test.ts` | Add `dispose: vi.fn()` to `createMockSubprocess`. |
+| `src/main/daemon/daemon-pty-provider.test.ts` | Add `dispose: vi.fn()` to `createMockSubprocess`. |
+| `src/main/daemon/reattach-snapshot.test.ts` | Add `dispose: vi.fn()` to `createMockSubprocess`. |
+| `src/main/daemon/__tests__/pty-fd-leak.test.ts` (new) | Integration test for the daemon path: spawn N sessions, tear them down via each path, assert fd count returns to baseline. |
+| `src/main/providers/__tests__/local-pty-fd-leak.test.ts` (new) | Same test, targeting `LocalPtyProvider` directly. |
+| `src/relay/__tests__/pty-fd-leak.test.ts` (new) | Same test, targeting `PtyHandler` directly. |
+
+### Testing plan
+
+The hard part of this fix is not the code — it's proving the leak is closed in all three providers. Two layers:
+
+#### 1. Unit-level handle behaviour
+
+Per provider, for each exit path (`kill`, `forceKill`, native throw simulated by calling `dispose` after an artificial dead state, natural exit), assert:
+
+- `proc.destroy()` is called exactly once per PTY (spy on the mock `IPty`).
+- Calling the provider's dispose a second time is a no-op (idempotency).
+- After dispose, subsequent `write/resize/kill` are no-ops and do not throw.
+- No `Napi::Error` surfaces from any follow-on method call.
+
+#### 2. Integration-level fd count
+
+One test file per provider (`src/main/daemon/__tests__/pty-fd-leak.test.ts`, `src/main/providers/__tests__/local-pty-fd-leak.test.ts`, `src/relay/__tests__/pty-fd-leak.test.ts`), same shape:
+
+```
+baseline = countPtmxFds(process.pid)
+for i in 1..50:
+ pty = provider.spawn(...)
+ provider.shutdown(pty.id) // or forceKill / dispose / let it exit naturally
+ await exit event
+after = countPtmxFds(process.pid)
+assert after === baseline
+```
+
+Loop once per exit path per provider.
+
+**Platform-specific `countPtmxFds` implementation:**
+
+- **macOS:** `lsof -p -Ffn` → parse as (fd, name) pairs → count pairs whose fd is numeric (not `cwd`/`txt`/`rtd`) AND whose name is exactly `/dev/ptmx`. The `-Ffn` machine-readable mode emits one field per line prefixed with `f` (fd) or `n` (name); a naive `startsWith('n')` filter that doesn't cross-check the preceding `f` row false-matches on non-fd rows whose NAME happens to be `/dev/ptmx`. Never use `grep ptmx` unqualified — it false-matches on env vars and any path containing the substring.
+- **Linux:** iterate `/proc//fd/*`, `readlink` each entry, match against the regex `/^(\/dev\/ptmx$|\/dev\/pts\/ptmx$|anon_inode:\[?ptmx\]?$)/`. The master pty fd does not show as `/dev/ptmx` on modern Linux kernels — depending on the pty backend and kernel version, `readlink` returns `anon_inode:[ptmx]` (devpts backend on many distros) or `/dev/pts/ptmx`. A naive `grep /dev/ptmx` yields zero matches and the test passes vacuously — **zero regression coverage** instead of real coverage. CI runs on `ubuntu-latest`; this matters.
+- **Windows:** skip entirely (ConPTY doesn't expose ptmx; rely on the unit-level `destroy()` spy).
+
+**Mandatory `beforeAll` counter smoke.** Before the first assertion, spawn one real PTY, measure `countPtmxFds`, kill it, measure again, and assert `beforeSpawn < afterSpawn` and `afterKill <= beforeSpawn`. If either check fails, the counter itself is broken on this platform — skip the whole suite with a clear message (`skip('ptmx counter not functional on this platform')`). Otherwise, the fd-count assertions could go green on a broken counter and we'd think the fix landed when it didn't.
+
+```ts
+beforeAll(async () => {
+ const baseline = countPtmxFds(process.pid)
+ const probe = pty.spawn('/bin/sh', ['-c', 'sleep 30'], { /* ... */ })
+ await new Promise((r) => setTimeout(r, 100))
+ const withProbe = countPtmxFds(process.pid)
+ probe.kill('SIGKILL')
+ await new Promise((r) => setTimeout(r, 200))
+ const afterKill = countPtmxFds(process.pid)
+ if (!(withProbe > baseline) || !(afterKill <= baseline)) {
+ // Why: if the counter can't even observe spawn/kill deltas on a known-good
+ // PTY, it can't observe the leak we're trying to prove closed. Vacuously
+ // passing assertions would give false confidence. Skip instead.
+ return describe.skip('ptmx counter smoke failed; skipping fd-leak suite')
+ }
+})
+```
+
+These tests spawn 50 real subprocesses each and must be gated behind an env-var skip (not a vitest tag — vitest 4 doesn't ship built-in tag filtering in this repo's config). Use `describe.skipIf(!process.env.RUN_SLOW_TESTS)`. Every spawn inside the loop must be wrapped in try/finally that force-kills the child regardless of assertion outcome — otherwise a mid-loop failure leaks the remaining subprocesses into the test runner, corrupting the next suite's baseline.
+
+#### 3. Manual verification
+
+Reproduce the reported 269/13 case locally:
+1. Start a fresh daemon.
+2. Baseline: `lsof -p $(pgrep -f daemon-entry) | grep -c ptmx` → small (one per live session).
+3. Churn: open and close 50 terminals via the UI.
+4. Verify the count returns to baseline within seconds. Before the fix, it stays at ~50.
+5. Repeat against a non-daemon worktree (LocalPtyProvider path) and against an SSH worktree (relay path).
+
+### Rollout
+
+No flag needed. The change is pure bug-fix with strictly smaller resource footprint. Ship with the orphan-daemon fix in the same release — they are complementary and together close the full leak story.
+
+### Regression surface
+
+| Regression | Mitigation |
+|---|---|
+| `dispose()` throws, breaking exit-code fanout to clients | Wrap every dispose call site in try/catch. `destroy()` call itself is also in try/catch inside the wrapper. |
+| `proc.destroy()` is not present on an older/forked node-pty build | Optional chain: `(proc as unknown as { destroy?: () => void }).destroy?.()`. Current pinned version has it on both UnixTerminal and WindowsTerminal; tests assert it's called. |
+| Double-dispose double-frees the native handle | Idempotency guard (`if (disposed) return`) at the top of dispose. node-pty's own `destroy()` is also safe to call twice — `_close()` is idempotent (it replaces `write`/`end` with no-ops and flips `_writable`/`_readable` to false the first time; the second call overwrites no-ops with no-ops). `_socket.destroy()` and `_writeStream.dispose()` are both idempotent per Node stream semantics. |
+| `dead` flag pattern regresses, `Napi::Error` kills daemon | All existing `dead`-guarded methods stay exactly as-is. `dispose()` sets `dead = true` and then calls `destroy()`; it adds to the pattern, does not replace it. |
+| Newly-nulled onData callback drops final data burst | Session already fans out synchronously in `handleSubprocessData` before exit. Nulling after exit is safe. |
+| Neutralizing `proc.kill` on Windows turns `destroy()` into a no-op (ConPTY leak) | `WindowsTerminal.destroy` calls `kill()` via `_deferNoArgs` — we gate neutralization on `process.platform !== 'win32'`. Verified in `pty-subprocess.ts` and `local-pty-provider.ts` and `relay/pty-handler.ts` helpers. Test: mock `process.platform = 'win32'`; assert `proc.kill` is NOT replaced with noop; assert `destroy()` is still called. |
+| Shared `#teardownSubprocess` helper flips `_state` before callers capture `wasTerminating`, orphaning stubborn children | Helper explicitly does NOT flip `_state`. Each public method (`dispose`, `disposeSubprocess`, `forceKillAndDisposeSubprocess`) owns its own `_state = 'exited'` line and captures any pre-flip invariants before calling the helper. Test: session with `_isTerminating=true`, `_state='running'` calls `dispose()`; assert `subprocess.forceKill()` is called before `subprocess.dispose()`. |
+| `sendSignal` / `writeData` / `resize` silently no-op after relay `onExit` neutralized `managed.pty.kill` | Every public entry point on `PtyHandler` that touches a `ManagedPty` checks `managed.disposed` first and treats disposed as "not found" (existing error path). Converts silent failure to an explicit error callers already handle. |
+| `TerminalHost.dispose()` drops 5s SIGKILL fallback for stubborn children | New `forceKillAndDisposeSubprocess` method explicitly sends SIGKILL via `subprocess.forceKill()` before releasing the fd. SIGKILL is not ignorable. Test: session whose child ignores SIGTERM; call `forceKillAndDisposeSubprocess`; assert child is reaped AND fd is released, both synchronously. |
+| LocalPtyProvider delivers trailing SIGHUP to recycled pid | `destroyPtyProcess(proc)` mirrors the daemon and relay helpers: POSIX-guarded `proc.kill = noop` neutralization before `destroy()`. Covers natural-exit, `safeKillAndClean`, and `shutdown` paths. |
+
+## Risks
+
+| Risk | Severity | Why acceptable |
+|---|---|---|
+| `destroy()` doesn't actually release the fd | Low | We are literally calling node-pty's canonical close path (`_close()` → `_socket.destroy()` → `_writeStream.dispose()`). Only way this is ineffective is a node-pty bug or a version regression — and the integration fd-count tests catch both before merge. |
+| Idempotent dispose hides a real double-free bug | Low | Idempotency only skips work; it does not suppress errors. |
+| `TerminalHost.dispose()` synchronous loop blocks daemon shutdown | Low | `destroy()` on each PTY is a handful of syscalls; 50 sessions ≈ single-digit ms. |
+| `destroy()` on Windows defers via `_deferNoArgs` | Low | ConPTY never hit the ptmx cap (it's a POSIX resource). Windows dispose is correctness-for-symmetry, not a load-bearing leak fix. |
+| The real leak is elsewhere (e.g., an fd leak outside the PTY code path) | Low | Integration tests directly measure fd reclamation across a full spawn/kill lifecycle. If the fix works there, it addresses the observed symptom. |
+
+## Related work (out of scope)
+
+- **Orphaned legacy daemons**: [auto-kill-old-daemons.md](./auto-kill-old-daemons.md) — complementary fix targeting daemon-level lifecycle.
+- **Worktree-delete does not kill sessions**: separate follow-up. Today, deleting a worktree from the sidebar leaves its PTY sessions live in the daemon, which is a different leak vector.
+- **Daemon fd observability**: expose an IPC `daemon:stats` handler so Orca can surface fd count in a debug view. Would let us detect regressions in production rather than waiting for user reports.
+- **Replace `node-pty`**: out of scope; see "Why not just replace node-pty" above.
diff --git a/docs/homebrew-cask.md b/docs/homebrew-cask.md
new file mode 100644
index 000000000..3292115c2
--- /dev/null
+++ b/docs/homebrew-cask.md
@@ -0,0 +1,90 @@
+# Homebrew Cask
+
+Orca is distributed on macOS as a Homebrew Cask. This doc covers how the cask
+is wired up, how it interacts with Orca's in-app updater, and what to do when
+something drifts.
+
+## For users
+
+```bash
+brew tap stablyai/orca
+brew install --cask orca
+```
+
+Or in one command: `brew install --cask stablyai/orca/orca`. Both forms install
+`Orca.app` into `/Applications`. Subsequent updates are handled by Orca's
+in-app updater (electron-updater) — `brew upgrade` is a no-op because the
+cask is marked `auto_updates true`. Users who want brew to force-reinstall
+from the cask version can pass `--greedy`.
+
+## How the pieces fit together
+
+There are three moving parts:
+
+1. **`Casks/orca.rb`** in this repo — source of truth for the cask file.
+ Edited by automation on every stable release; can be edited manually if
+ metadata (zap list, macOS floor, desc) needs to change.
+2. **`stablyai/homebrew-orca`** — the public tap users consume. Mirrors
+ `Casks/orca.rb` from this repo via the bump workflow. Nothing else lives
+ there; do not hand-edit.
+3. **`.github/workflows/homebrew-bump.yml`** — runs on `release.published`
+ for stable tags (skips `-rc.*` and GitHub pre-releases). Downloads the
+ two DMGs, rewrites `version`/`sha256` in `Casks/orca.rb`, pushes a PR to
+ the tap, and auto-merges it.
+
+### Why the cask uses `auto_updates true`
+
+`electron-updater` (`src/main/updater.ts`) downloads each new release and
+swaps `Orca.app` in place. Homebrew-Cask's tracking of installed versions is
+based on the cask's `version:` field plus an install receipt — so when the
+app mutates itself, brew's metadata drifts. `auto_updates true` tells
+Homebrew this is expected: `brew outdated` and `brew upgrade` ignore the
+cask unless `--greedy` is passed. Uninstall still works normally.
+
+The hidden requirement: Squirrel.Mac (what electron-updater uses) needs
+write access to `/Applications/Orca.app`. Cask installs into `/Applications`
+with user ownership by default, so this works out of the box. If a user ever
+`sudo`-installs or the bundle becomes root-owned, the in-app updater will
+fail silently; they'd need `brew reinstall --cask orca` or `brew upgrade
+--cask orca --greedy` to recover.
+
+## One-time setup (already done, documented here for reference)
+
+1. **Tap repo**: `stablyai/homebrew-orca` on GitHub. Must be named
+ `homebrew-` so `brew tap stablyai/orca` resolves. Public.
+2. **Auto-merge** enabled in tap repo settings.
+3. **Seeded** with a copy of `Casks/orca.rb` for the initial version.
+
+The workflow authenticates as the existing `buf0-bot` GitHub App
+(installed org-wide on stablyai), reusing the `BUFO_BOT_PRIVATE_KEY`
+secret that's already on `stablyai/orca` for `track-community-prs.yaml`.
+No PAT rotation, no new secret.
+
+## Submitting to homebrew-cask (the main tap)
+
+The `stablyai/homebrew-orca` tap ships first. Once Orca has stable user
+demand and has been on a release cadence for ~30+ days without the version
+string breaking conventions (no `-rc`, no date suffixes), we can submit to
+`Homebrew/homebrew-cask` so users can `brew install --cask orca` without a
+tap prefix. That submission is a one-time PR against
+https://github.com/Homebrew/homebrew-cask; subsequent bumps to the main tap
+are handled by their own [autobump infrastructure](https://docs.brew.sh/Autobump)
+as long as the release cadence matches their expectations. T3 Code's
+[cask](https://github.com/Homebrew/homebrew-cask/blob/main/Casks/t/t3-code.rb)
+is a close structural analogue.
+
+## Troubleshooting
+
+- **"electron-updater says no update available, but brew says I'm out of
+ date"** — expected if the user ran `brew upgrade --greedy` or installed
+ the cask before the in-app updater picked up a newer release. The
+ `auto_updates true` flag usually prevents this; if a user reports it,
+ check that their cask file still has the marker.
+- **Bump workflow failed to PR the tap** — verify the `buf0-bot` app is
+ still installed on `stablyai/homebrew-orca` (org-wide install, should
+ auto-cover any new org repo). Re-run via `workflow_dispatch` with the
+ tag name.
+- **Squirrel-mac fails during update** — almost always bundle permissions
+ or a signing-identity mismatch. See the `Why: signing identity stability`
+ comment in `config/electron-builder.config.cjs` and the updater logs in
+ `~/Library/Application Support/Orca/logs/`.
diff --git a/docs/terminal-drop-ssh.md b/docs/terminal-drop-ssh.md
new file mode 100644
index 000000000..09f44a638
--- /dev/null
+++ b/docs/terminal-drop-ssh.md
@@ -0,0 +1,452 @@
+# Terminal drag-and-drop over SSH
+
+## Problem
+
+Dragging a local file onto a terminal pane inserts the file's absolute path
+into the PTY, so the user can reference it in a CLI or TUI-agent prompt. On
+SSH worktrees the terminal runs remotely, so injecting a **local** path
+(`/Users/alice/Desktop/log.txt`) is useless — the remote agent has no access
+to it.
+
+The file-explorer drop path was fixed in PR #1279 by routing through SFTP
+upload (`importExternalPathsSsh`). The terminal drop path was not touched
+and still breaks for SSH worktrees.
+
+Reported: https://stablygroup.slack.com/archives/C0ASMDT6LQZ/p1777530155421009
+
+## Goals
+
+- Dropping a local file onto a terminal connected to an SSH worktree makes
+ that file available to the remote shell/agent, and injects a path the
+ remote process can read.
+- Local terminal drops keep their current behavior: reference-in-place, no
+ copy, no authorization, no repo pollution.
+- Local and SSH paths share one main-side resolver. The renderer may pass
+ connection context and show progress UI, but copy/upload/deconfliction
+ policy stays out of the renderer so the two modes do not drift over time.
+
+## Non-goals
+
+- Unifying terminal drop with file-explorer drop. They have different
+ semantics (explorer always copies into a user-picked `destDir`; terminal
+ references a path). They share the SSH upload primitive internally but
+ remain separate IPCs.
+- Cleanup / garbage collection of staged remote files. Tracked as follow-up
+ (see "Follow-ups" below — file **before merging** and replace this
+ parenthetical with the issue number so the reference is locatable). Until
+ GC lands, files uploaded by a drop whose pane is unmounted before the
+ upload resolves are orphaned in `.orca/drops/` with no injected path.
+ Users should know uploads are not cancellable.
+- Abortable uploads. SFTP transfers run to completion even if the terminal
+ pane is unmounted mid-flight.
+
+## Considered: Option A (full unification)
+
+Terminal drop calls `fs:importExternalPaths` with
+`destDir = worktreePath`, then injects `result.destPath` into the PTY.
+Shares exactly the file-explorer code path.
+
+Rejected because it changes **local** terminal-drop UX: today dropping
+`~/Desktop/log.txt` into the terminal pastes `/Users/…/Desktop/log.txt`
+so the agent reads the file in place; under Option A the file would be
+copied into the repo. Users rely on the reference-in-place behavior to
+point agents at files without polluting the worktree.
+
+## Design (Option B)
+
+### New IPC
+
+```
+fs:resolveDroppedPathsForAgent({
+ paths: string[],
+ worktreePath: string,
+ connectionId?: string,
+}) → {
+ resolvedPaths: string[],
+ skipped: { sourcePath: string; reason: 'missing' | 'symlink' | 'permission-denied' | 'unsupported' }[],
+ failed: { sourcePath: string; reason: string }[],
+}
+```
+
+Contract:
+
+- **Local (`connectionId == null`):** returns
+ `{ resolvedPaths: paths, skipped: [], failed: [] }` unchanged. No copy. No
+ authorization (matches today's behavior — the agent's own read is what gets
+ authorized, not the drop). Use `args.connectionId == null` (not `!args.connectionId`)
+ so an empty string cannot silently pick the local branch.
+- **SSH (`connectionId` is a non-empty string):** uploads each path via SFTP
+ into a staging dir under the worktree. Returns remote absolute paths for
+ items that uploaded successfully, items rejected by policy (symlinks,
+ missing sources, permission-denied, unsupported file types) in `skipped`,
+ and hard upload errors in `failed`. The split mirrors `ImportItemResult`'s
+ existing `'imported' | 'skipped' | 'failed'` and lets the renderer toast
+ "Skipped N symlinks" distinctly from "Failed to upload N files." Collapsing
+ skipped into failed would mislabel routine policy rejections as errors.
+
+### SSH staging dir
+
+`${worktreePath}/.orca/drops/` on the remote. `.orca/` is reserved as an
+Orca-owned directory for future remote state (GC metadata, cached remote
+capability probes, etc.); this is its first use. Future features adding
+subpaths under `.orca/` should namespace themselves (`.orca/drops/`,
+`.orca//`) rather than placing files at the root.
+
+Rationale:
+
+- No need to resolve remote `$HOME` (which would require a round-trip and
+ caching layer).
+- Lives inside the worktree, so cleaned up naturally when the worktree is
+ deleted.
+- The agent has read access by construction (it runs with the worktree's
+ cwd).
+
+The main process must bootstrap `.orca/.gitignore` with `*\n!.gitignore\n`
+before the first successful upload. Otherwise every SSH terminal drop dirties
+source control with an untracked `.orca/` directory, which recreates the
+repo-pollution problem that ruled out Option A for local terminal drops. The
+`!.gitignore` negation keeps the marker file itself trackable if we ever want
+to (and costs nothing today — `git status` stays clean either way because
+nothing tries to add it).
+
+The staging directory must be created recursively over SFTP before upload:
+
+- create `${worktreePath}/.orca` (ignore "already exists")
+- write `${worktreePath}/.orca/.gitignore` as `*\n!.gitignore\n` **only if it
+ does not already exist** — never overwrite. A user may have added patterns
+ there, and silently clobbering user-authored content violates least
+ surprise even inside an Orca-owned directory. Use `sftpPathExists` before
+ writing. (Two concurrent first-drops racing through the `sftpPathExists`
+ check will both write the same bytes — last writer wins, idempotent, so
+ the race is benign and not worth locking.)
+- create `${worktreePath}/.orca/drops` (ignore "already exists")
+
+Do not rely on `uploadFile`, `uploadDirectory`, or the existing
+`mkdirSftp(destPath)` calls to create missing parents. `uploadFile` writes
+directly to the final remote file path, and `mkdirSftp` is not recursive, so
+the first terminal drop into a fresh SSH worktree would fail if the parents do
+not already exist.
+
+### Main-side implementation
+
+`src/main/ipc/filesystem-mutations.ts`:
+
+```ts
+ipcMain.handle('fs:resolveDroppedPathsForAgent', async (_e, args) => {
+ // Why: `== null` (not `!args.connectionId`) so an empty string is treated
+ // as an error from the renderer, not silently routed to the local branch.
+ if (args.connectionId == null) {
+ return { resolvedPaths: args.paths, skipped: [], failed: [] }
+ }
+ const worktreePath = args.worktreePath.replace(/\/+$/, '')
+ const destDir = `${worktreePath}/.orca/drops`
+ const { results } = await importExternalPathsSsh(
+ args.paths,
+ destDir,
+ args.connectionId,
+ { ensureDir: true },
+ )
+ const resolvedPaths: string[] = []
+ const skipped: { sourcePath: string; reason: ImportSkipReason }[] = []
+ const failed: { sourcePath: string; reason: string }[] = []
+ // Iterate in input order so injected paths align with the user's drop order.
+ for (const r of results) {
+ if (r.status === 'imported') {
+ resolvedPaths.push(r.destPath)
+ } else if (r.status === 'skipped') {
+ skipped.push({ sourcePath: r.sourcePath, reason: r.reason })
+ } else {
+ failed.push({ sourcePath: r.sourcePath, reason: r.reason })
+ }
+ }
+ return { resolvedPaths, skipped, failed }
+})
+```
+
+Reuses `importExternalPathsSsh` — SFTP upload, symlink pre-scan, name
+deconfliction, per-item error reporting are all already there.
+
+**Staging bootstrap lives inside `importExternalPathsSsh`** behind a new
+optional `{ ensureDir?: boolean }` parameter. When set, before the first
+upload the function creates `${destDir}`'s parent chain (`.orca`, then
+`drops`) and writes `.orca/.gitignore` (`*\n`) only if missing, all on the
+**same SFTP session** already opened for the upload. Do not add a separate
+`ensureSshDropStagingDir` helper that opens its own channel — that would
+double the SFTP handshake cost on every drop.
+
+### Renderer-side implementation
+
+**API change to `shellEscapePath`.** Today the second arg is a *userAgent
+string* (substring-matched for `"Windows"`), which couples escape rules to
+the client OS. For SSH drops we need to escape for the *target shell*,
+which is always POSIX on the remote regardless of client OS. Change the
+signature to take an explicit target:
+
+```ts
+shellEscapePath(path: string, targetShell: 'posix' | 'windows')
+```
+
+Callers derive `targetShell` from context: local drops pass
+`isWindowsUserAgent() ? 'windows' : 'posix'`; SSH drops always pass
+`'posix'`. This makes test #11 (Windows client → Linux SSH worktree)
+correct by construction instead of by coincidence.
+
+**Migration — all three call sites + tests must change together:**
+
+- `src/renderer/src/components/terminal-pane/pane-helpers.ts:53` — update
+ signature; drop the `userAgent` default.
+- `src/renderer/src/components/terminal-pane/TerminalPane.tsx:937`
+ (file-explorer → terminal drop). This is a **local-only** code path
+ (explorer drag uses a DOM MIME type that the preload SSH bridge does not
+ forward), so pass `isWindowsUserAgent() ? 'windows' : 'posix'` to preserve
+ today's behavior exactly.
+- `src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects.ts:344`
+ — replaced by the new SSH-aware handler below; the `shellEscapePath` call
+ moves inside it with an explicit `targetShell`.
+- `src/renderer/src/components/terminal-pane/pane-helpers.test.ts` — the
+ existing cases pass `'Macintosh'`, `'Linux'`, `'Windows'` as the userAgent
+ arg. Rewrite to pass `'posix'` (for Mac/Linux) and `'windows'`, so tests
+ exercise the new contract rather than the legacy substring match.
+
+No local behavior changes if this migration is done in one commit: Mac/Linux
+already took the POSIX branch via the userAgent string match; Windows
+already took the Windows branch. The new signature just names that
+explicitly.
+
+`src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects.ts`:
+
+```ts
+return window.api.ui.onFileDrop(async (data) => {
+ if (data.target !== 'terminal') return
+ if (data.paths.length === 0) return
+ const manager = managerRef.current
+ if (!manager) return
+ const pane = manager.getActivePane() ?? manager.getPanes()[0]
+ if (!pane) return
+ const paneId = pane.id
+ const transport = paneTransportsRef.current.get(paneId)
+ if (!transport) return
+
+ const wtId = worktreeIdRef.current
+ const worktreePath = worktreePathRef.current
+ if (!wtId || !worktreePath) return
+
+ // Why: getConnectionId (selector on the terminals/repos slice:
+ // `state.repos.find(r => r.id === )?.connectionId`,
+ // exposed via the store) returns `string` (SSH), `null` (local repo
+ // found), or `undefined` (store not hydrated / worktree not found).
+ // Treat `undefined` as an error, not as "local" — otherwise a drop
+ // during hydration would silently paste local paths into a remote
+ // shell.
+ const connectionId = getConnectionId(wtId)
+ if (connectionId === undefined) {
+ toast.error('Worktree not ready — try again in a moment.')
+ return
+ }
+ const isRemote = connectionId !== null
+ const targetShell: 'posix' | 'windows' = isRemote
+ ? 'posix'
+ : isWindowsUserAgent()
+ ? 'windows'
+ : 'posix'
+
+ // Local fast path: no IPC round-trip, no toast. Preserves today's
+ // zero-latency behavior exactly — same code shape as before, only the
+ // shellEscapePath signature is new (and resolves to the same branch).
+ if (!isRemote) {
+ for (const p of data.paths) {
+ transport.sendInput(`${shellEscapePath(p, targetShell)} `)
+ }
+ pane.terminal.focus()
+ return
+ }
+
+ const pending = toast.loading(
+ `Uploading ${data.paths.length} file(s) to remote…`,
+ )
+ try {
+ const { resolvedPaths, skipped, failed } =
+ await window.api.fs.resolveDroppedPathsForAgent({
+ paths: data.paths,
+ worktreePath,
+ connectionId,
+ })
+ // Why: pane may have unmounted during the SFTP upload (tab closed,
+ // worktree switched). Re-check the transport map before writing so
+ // we don't call sendInput on a torn-down PTY. Orphaned uploads are
+ // acknowledged in Non-goals.
+ const liveTransport = paneTransportsRef.current.get(paneId)
+ if (liveTransport) {
+ // resolvedPaths preserves input order (main-side iterates results in
+ // order); injected paths line up with the user's drop gesture.
+ for (const p of resolvedPaths) {
+ liveTransport.sendInput(`${shellEscapePath(p, targetShell)} `)
+ }
+ pane.terminal.focus()
+ }
+ if (skipped.length > 0) {
+ const symlinkCount = skipped.filter((s) => s.reason === 'symlink').length
+ const noun = skipped.length === 1 ? 'item' : 'items'
+ toast.message(
+ symlinkCount === skipped.length
+ ? `Skipped ${skipped.length} symlink${skipped.length === 1 ? '' : 's'}.`
+ : `Skipped ${skipped.length} ${noun}.`,
+ )
+ }
+ if (failed.length > 0) {
+ const noun = failed.length === 1 ? 'file' : 'files'
+ toast.error(`Failed to upload ${failed.length} ${noun}.`)
+ }
+ } catch (err) {
+ toast.error(extractIpcErrorMessage(err, 'Failed to upload files.'))
+ } finally {
+ toast.dismiss(pending)
+ }
+})
+```
+
+`extractIpcErrorMessage` is the existing helper at
+`src/renderer/src/lib/ipc-error.ts:6` (already used by
+`useFileExplorerImport.ts`, `Terminal.tsx`, etc.). Reuse it — do not copy
+the body locally.
+
+New dependencies on the hook: `worktreeId` and `worktreePath` refs. Use the
+`TerminalPane`'s own `worktreeId` prop, not global `activeWorktreeId`. The
+drop listener is already gated by `isActive`, and the pane's own
+`worktreeId` is the authoritative identity of the terminal being written
+to; reading from global state would race during worktree switches. Promote
+this reasoning into a `// Why:` comment at the call site per CLAUDE.md.
+
+Derive `worktreePath` the same way `use-terminal-pane-lifecycle.ts` does
+today: find the worktree by `worktreeId` in the store, then fall back to
+`cwd`.
+
+### Why not branch in the renderer
+
+- Keeps upload semantics in one place. Adding a second terminal consumer
+ (e.g. a standalone TUI pane) should call the same resolver instead of
+ deciding where to copy, how to deconflict names, or how to report per-item
+ failures.
+- The renderer can know that the worktree is SSH for progress UI and shell
+ escaping, but it should not know SFTP details or construct uploaded
+ destination filenames itself.
+
+### UX details
+
+- **SSH "Uploading…" toast:** SFTP of a few MB can take seconds. Without
+ feedback the user thinks the drop failed. Dismiss on success, replace
+ with an error toast on failure.
+- **Don't inject until upload resolves.** Injecting the remote path before
+ the file lands means the agent may try to read a file that doesn't yet
+ exist and error. Worth the extra perceived latency.
+- **Failure policy:** partial failures still inject the succeeded paths
+ and toast the count of failures (same pattern as the explorer).
+- **Escape for the terminal that receives the path.** Local drops keep the
+ existing platform-specific quoting. SSH drops must use POSIX shell quoting
+ for the returned remote paths; do not let a Windows client choose Windows
+ quoting for a Linux/macOS SSH shell.
+
+## System fit
+
+```
+[Electron preload native drop]
+ |
+ v
+[terminal:file-drop IPC relay]
+ |
+ v
+[active TerminalPane drop handler]
+ |
+ v
+[fs:resolveDroppedPathsForAgent]
+ | local | SSH
+ v v
+[return original paths] [SFTP stage into ${worktreePath}/.orca/drops]
+ | |
+ | v
+ | [return remote readable paths]
+ | |
+ +---------------+-----------------+
+ |
+ v
+ [PTY sendInput escaped paths]
+```
+
+## Testing
+
+1. Local worktree, drop a single file onto the terminal → original
+ absolute path pasted. No copy. No change from today.
+2. Local worktree, drop multiple files → each path pasted separated by a
+ space. No change from today.
+3. SSH worktree, drop a single file → file uploads to
+ `${worktreePath}/.orca/drops/` on remote; remote path pasted
+ into PTY; agent can read it.
+4. SSH worktree, drop a folder → folder uploads recursively; remote dir
+ path pasted.
+5. SSH worktree, drop a symlink → no injection; toast reads
+ "Skipped 1 symlink." (not "Failed to upload") because symlink rejection
+ is policy, not error.
+6. SSH worktree, drop 5 files where items 2 and 4 are permission-denied at
+ the local source → paths 1, 3, 5 are injected **in that order**
+ (matching input order), toast says "Skipped 2 items." (permission-denied
+ is classified `skipped`, not `failed`, by `importExternalPathsSsh`).
+ Additionally, simulate an SFTP write error mid-upload to cover the
+ `failed` branch → "Failed to upload N files" toast.
+7. SSH worktree disconnected mid-drag → user-visible error toast, no
+ partial injection.
+8. Name collision: drop the same file twice in quick succession → second
+ upload lands as ` copy.` (deconfliction inherited from
+ `importExternalPathsSsh`).
+9. Fresh SSH worktree with no `.orca` directory → first drop creates
+ `.orca/`, `.orca/.gitignore`, and `.orca/drops/`; upload succeeds.
+10. After an SSH drop, `git status --short` in the remote worktree does not
+ show `.orca/`.
+11. Windows client dropping `my file's $draft.txt` into a Linux SSH worktree
+ pastes a POSIX-escaped remote path, not Windows double-quoted syntax.
+ Expected output for remote path `/home/u/wt/.orca/drops/my file's $draft.txt`:
+ `'/home/u/wt/.orca/drops/my file'\''s $draft.txt'` (literal `$draft`
+ inside single quotes — no expansion, no backslash-escaping).
+16. Local terminal drop on macOS / Linux / Windows clients behaves
+ byte-identically to pre-change: same injected string, no toast, no IPC
+ call. Run the existing `pane-helpers.test.ts` expectations through the
+ new `'posix' | 'windows'` API and confirm outputs match the legacy
+ userAgent-based outputs.
+17. File-explorer → terminal drop (`TerminalPane.tsx` onDrop) continues to
+ work on local and SSH worktrees exactly as today — this path is not
+ touched by the new IPC and must still use the explorer's own handling.
+12. Empty drop (`data.paths.length === 0`) → no IPC call, no toast, no
+ injection. (Possible on some OSes when a drag contains only non-file
+ items.)
+13. Store unhydrated (`getConnectionId` returns `undefined`) → user-visible
+ "Worktree not ready" toast, no injection, no IPC call. Not a silent
+ local fallback.
+14. Existing user-authored `.orca/.gitignore` with extra patterns → after
+ first SSH drop the file is unchanged (bootstrap writes only when
+ missing).
+15. Unit coverage:
+ - preload/API types expose `resolveDroppedPathsForAgent` and the
+ channel is registered in the preload `contextBridge` / IPC
+ allowlist (regression guard — easy to forget).
+ - main IPC covers: local passthrough, SSH success, partial failure
+ (order preserved), fresh-worktree staging bootstrap, bootstrap
+ preserves existing `.gitignore`, and disconnected SSH.
+ - terminal-pane coverage verifies the resolver is called once per
+ gesture, no path is injected until the promise resolves, and
+ `shellEscapePath` is called with `'posix'` for SSH drops regardless
+ of client userAgent.
+
+## Follow-ups
+
+File each of these as a GitHub issue before merging the implementation PR
+so "tracked as follow-up" is actually locatable. Inline the issue number
+next to each item once filed (e.g. `- GC drops dir (#1301)`), and update
+the GC paragraph in Non-goals to point to that issue directly.
+
+- GC `${worktreePath}/.orca/drops/` on worktree delete / disconnect.
+- `AbortController` plumbing so unmounting the terminal pane cancels the
+ in-flight SFTP upload (related to the pane-unmount guard added in the
+ renderer handler: today we no-op the injection, but the bytes still
+ transfer).
+- Drag-over affordance on the terminal pane (it has the
+ `data-native-file-drop-target="terminal"` marker but no hover style),
+ so users get feedback that dropping into the terminal is supported.
diff --git a/package.json b/package.json
index 4ffdf41c2..119f47b42 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "orca",
- "version": "1.3.25-rc.12",
- "description": "An Electron application with React and TypeScript",
+ "version": "1.3.33-rc.0",
+ "description": "Next-gen IDE for parallel agentic development",
"homepage": "https://github.com/stablyai/orca",
"author": "stablyai",
"bin": {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 8d46f4347..d5e449179 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -9,7 +9,7 @@ patchedDependencies:
hash: df21db050a4d85552cafbe583ece863d7fa19ed634a1219210a0455b986b6634
path: config/patches/@xterm__addon-ligatures@0.11.0-beta.198.patch
node-pty@1.1.0:
- hash: 02e16954edbb8e511963557e3b2c80f8a6fb230cd0c6a75ade936022f3347322
+ hash: d39825bae630ddf0fc73e83e6001057c70957161772ba078988767d8569cee63
path: config/patches/node-pty@1.1.0.patch
importers:
@@ -159,7 +159,7 @@ importers:
version: 0.55.1
node-pty:
specifier: ^1.1.0
- version: 1.1.0(patch_hash=02e16954edbb8e511963557e3b2c80f8a6fb230cd0c6a75ade936022f3347322)
+ version: 1.1.0(patch_hash=d39825bae630ddf0fc73e83e6001057c70957161772ba078988767d8569cee63)
pdfjs-dist:
specifier: ^5.6.205
version: 5.6.205
@@ -11533,7 +11533,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
- node-pty@1.1.0(patch_hash=02e16954edbb8e511963557e3b2c80f8a6fb230cd0c6a75ade936022f3347322):
+ node-pty@1.1.0(patch_hash=d39825bae630ddf0fc73e83e6001057c70957161772ba078988767d8569cee63):
dependencies:
node-addon-api: 7.1.1
diff --git a/resources/claude.webp b/resources/claude.webp
new file mode 100644
index 000000000..328fc8547
Binary files /dev/null and b/resources/claude.webp differ
diff --git a/resources/gremlin.webp b/resources/gremlin.webp
new file mode 100644
index 000000000..9e831557a
Binary files /dev/null and b/resources/gremlin.webp differ
diff --git a/resources/opencode.webp b/resources/opencode.webp
new file mode 100644
index 000000000..fa2ac4244
Binary files /dev/null and b/resources/opencode.webp differ
diff --git a/src/main/browser/agent-browser-bridge.test.ts b/src/main/browser/agent-browser-bridge.test.ts
index 6e6fd480c..17394f02f 100644
--- a/src/main/browser/agent-browser-bridge.test.ts
+++ b/src/main/browser/agent-browser-bridge.test.ts
@@ -748,6 +748,21 @@ describe('AgentBrowserBridge', () => {
expect(bridge.getActiveWebContentsId()).toBeNull()
})
+ it('closes the named agent-browser session when a tab closes', async () => {
+ succeedWith({ snapshot: 'tree' })
+ await bridge.snapshot()
+
+ execFileMock.mockClear()
+ succeedWith(null)
+ await bridge.onTabClosed(100)
+
+ const closeCall = execFileMock.mock.calls.find((call: unknown[]) =>
+ (call[1] as string[]).includes('close')
+ )
+ expect(closeCall).toBeTruthy()
+ expect(closeCall![1]).toEqual(['--session', 'orca-tab-tab-1', 'close'])
+ })
+
it('repairs per-worktree active routing when the active tab closes', async () => {
const tabs = new Map([
['tab-a', 1],
diff --git a/src/main/browser/agent-browser-bridge.ts b/src/main/browser/agent-browser-bridge.ts
index 734c0acbc..bdd57ded0 100644
--- a/src/main/browser/agent-browser-bridge.ts
+++ b/src/main/browser/agent-browser-bridge.ts
@@ -1682,7 +1682,10 @@ export class AgentBrowserBridge {
const destroy = (async (): Promise => {
try {
- await this.runAgentBrowserRaw(sessionName, ['close'])
+ // Why: each browser tab uses its own named agent-browser session. Closing
+ // without --session only tears down the default session and leaves the tab
+ // session's daemon process running.
+ await this.runAgentBrowserRaw(sessionName, ['--session', sessionName, 'close'])
} catch {
// Session may already be dead
}
diff --git a/src/main/browser/browser-manager.test.ts b/src/main/browser/browser-manager.test.ts
index 951aefc1e..308a48347 100644
--- a/src/main/browser/browser-manager.test.ts
+++ b/src/main/browser/browser-manager.test.ts
@@ -1117,4 +1117,167 @@ describe('browserManager', () => {
guestOffMock.mock.calls.filter(([eventName]) => eventName === 'before-input-event')
).toHaveLength(2)
})
+
+ describe('setViewportOverride', () => {
+ function makeGuest(id: number): {
+ guest: Record
+ debuggerSendCommand: ReturnType
+ debuggerIsAttached: ReturnType
+ debuggerAttach: ReturnType
+ } {
+ const debuggerSendCommand = vi.fn().mockResolvedValue(undefined)
+ const debuggerIsAttached = vi.fn(() => true)
+ const debuggerAttach = vi.fn()
+ const guest = {
+ id,
+ isDestroyed: vi.fn(() => false),
+ getType: vi.fn(() => 'webview'),
+ getUserAgent: vi.fn(
+ () =>
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) orca/1.0.0 Chrome/134.0.0.0 Electron/30.0.0 Safari/537.36'
+ ),
+ setBackgroundThrottling: guestSetBackgroundThrottlingMock,
+ setWindowOpenHandler: guestSetWindowOpenHandlerMock,
+ on: guestOnMock,
+ off: guestOffMock,
+ openDevTools: guestOpenDevToolsMock,
+ debugger: {
+ isAttached: debuggerIsAttached,
+ attach: debuggerAttach,
+ sendCommand: debuggerSendCommand
+ }
+ }
+ return { guest, debuggerSendCommand, debuggerIsAttached, debuggerAttach }
+ }
+
+ it('returns false when the tab is not registered', async () => {
+ const result = await browserManager.setViewportOverride('missing', {
+ width: 375,
+ height: 667,
+ deviceScaleFactor: 2,
+ mobile: true
+ })
+ expect(result).toBe(false)
+ })
+
+ it('applies device metrics, touch emulation, and a mobile UA for mobile presets', async () => {
+ const { guest, debuggerSendCommand } = makeGuest(4242)
+ webContentsFromIdMock.mockReturnValue(guest)
+ browserManager.attachGuestPolicies(guest as never)
+ browserManager.registerGuest({
+ browserPageId: 'tab-mobile',
+ webContentsId: guest.id as number,
+ rendererWebContentsId
+ })
+ webContentsFromIdMock.mockReset()
+ webContentsFromIdMock.mockReturnValue(guest)
+
+ const ok = await browserManager.setViewportOverride('tab-mobile', {
+ width: 375,
+ height: 667,
+ deviceScaleFactor: 2,
+ mobile: true
+ })
+ expect(ok).toBe(true)
+
+ expect(debuggerSendCommand).toHaveBeenCalledWith('Emulation.setDeviceMetricsOverride', {
+ width: 375,
+ height: 667,
+ deviceScaleFactor: 2,
+ mobile: true
+ })
+ expect(debuggerSendCommand).toHaveBeenCalledWith('Emulation.setTouchEmulationEnabled', {
+ enabled: true,
+ maxTouchPoints: 5
+ })
+ const uaCall = debuggerSendCommand.mock.calls.find(
+ (call) => call[0] === 'Emulation.setUserAgentOverride'
+ )
+ expect(uaCall).toBeDefined()
+ expect(uaCall?.[1]).toMatchObject({
+ userAgent: expect.stringContaining('iPhone')
+ })
+ // Chrome major from the guest UA should be spliced into the mobile UA.
+ expect(uaCall?.[1]).toMatchObject({
+ userAgent: expect.stringContaining('CriOS/134')
+ })
+ })
+
+ it('clears device metrics and disables touch for override=null', async () => {
+ const { guest, debuggerSendCommand } = makeGuest(4343)
+ webContentsFromIdMock.mockReturnValue(guest)
+ browserManager.attachGuestPolicies(guest as never)
+ browserManager.registerGuest({
+ browserPageId: 'tab-clear',
+ webContentsId: guest.id as number,
+ rendererWebContentsId
+ })
+
+ const ok = await browserManager.setViewportOverride('tab-clear', null)
+ expect(ok).toBe(true)
+
+ expect(debuggerSendCommand).toHaveBeenCalledWith('Emulation.clearDeviceMetricsOverride', {})
+ expect(debuggerSendCommand).toHaveBeenCalledWith('Emulation.setTouchEmulationEnabled', {
+ enabled: false,
+ maxTouchPoints: 0
+ })
+ expect(debuggerSendCommand).toHaveBeenCalledWith('Emulation.setUserAgentOverride', {
+ userAgent: ''
+ })
+ })
+
+ it('attaches the debugger if not already attached and does not detach after', async () => {
+ const { guest, debuggerSendCommand, debuggerAttach } = makeGuest(4444)
+ ;(guest.debugger as { isAttached: ReturnType }).isAttached = vi.fn(() => false)
+ webContentsFromIdMock.mockReturnValue(guest)
+ browserManager.attachGuestPolicies(guest as never)
+ browserManager.registerGuest({
+ browserPageId: 'tab-attach',
+ webContentsId: guest.id as number,
+ rendererWebContentsId
+ })
+
+ await browserManager.setViewportOverride('tab-attach', {
+ width: 1024,
+ height: 768,
+ deviceScaleFactor: 1,
+ mobile: false
+ })
+
+ expect(debuggerAttach).toHaveBeenCalledWith('1.3')
+ expect(debuggerSendCommand).toHaveBeenCalled()
+ // Why: detaching would clear Page.addScriptToEvaluateOnNewDocument
+ // (anti-detection). Guard regression.
+ expect((guest.debugger as { detach?: unknown }).detach ?? undefined).toBeUndefined()
+ })
+
+ it('returns false when debugger.attach throws (e.g. DevTools already open)', async () => {
+ const { guest, debuggerSendCommand, debuggerAttach } = makeGuest(4545)
+ ;(guest.debugger as { isAttached: ReturnType }).isAttached = vi.fn(() => false)
+ // Why: Electron throws from debugger.attach if another client (e.g. the
+ // user's open DevTools window) is already attached. setViewportOverride
+ // must surface this as a clean `false` rather than an unhandled rejection.
+ debuggerAttach.mockImplementation(() => {
+ throw new Error('Another debugger is already attached')
+ })
+ webContentsFromIdMock.mockReturnValue(guest)
+ browserManager.attachGuestPolicies(guest as never)
+ browserManager.registerGuest({
+ browserPageId: 'tab-attach-throws',
+ webContentsId: guest.id as number,
+ rendererWebContentsId
+ })
+
+ const ok = await browserManager.setViewportOverride('tab-attach-throws', {
+ width: 1024,
+ height: 768,
+ deviceScaleFactor: 1,
+ mobile: false
+ })
+
+ expect(ok).toBe(false)
+ expect(debuggerAttach).toHaveBeenCalledWith('1.3')
+ expect(debuggerSendCommand).not.toHaveBeenCalled()
+ })
+ })
})
diff --git a/src/main/browser/browser-manager.ts b/src/main/browser/browser-manager.ts
index 4e71156f8..1a5996d1e 100644
--- a/src/main/browser/browser-manager.ts
+++ b/src/main/browser/browser-manager.ts
@@ -34,6 +34,21 @@ import {
setupGuestShortcutForwarding
} from './browser-guest-ui'
import { ANTI_DETECTION_SCRIPT } from './anti-detection'
+import { cleanElectronUserAgent } from './browser-session-ua'
+import type { BrowserViewportOverride } from '../../shared/types'
+
+// Why: mobile presets need a touch-capable UA or responsive sites serve the
+// desktop variant based on UA sniffing. This is the Chrome DevTools default
+// iPhone UA template; we splice in the guest session's real Chrome major so
+// sec-ch-ua headers (see setupClientHintsOverride) stay consistent.
+function buildMobileUserAgent(chromeMajor: string): string {
+ return `Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/${chromeMajor}.0.0.0 Mobile/15E148 Safari/604.1`
+}
+
+function extractChromeMajor(ua: string): string {
+ const match = ua.match(/Chrome\/(\d+)/)
+ return match ? match[1] : '134'
+}
export type BrowserGuestRegistration = {
browserPageId?: string
@@ -83,6 +98,11 @@ export class BrowserManager {
// has to bridge that mismatch to activate the right tab before capture.
private readonly workspaceIdByPageId = new Map()
private readonly rendererWebContentsIdByTabId = new Map()
+ // Why: chain setViewportOverride calls per tab so rapid toggles don't
+ // interleave CDP commands. Without serialization, two concurrent calls can
+ // race (e.g. clearDeviceMetricsOverride landing after a later mobile
+ // setDeviceMetricsOverride), leaving emulation in an unexpected state.
+ private readonly viewportOpsByTabId = new Map>()
private readonly contextMenuCleanupByTabId = new Map void>()
private readonly grabShortcutCleanupByTabId = new Map void>()
private readonly shortcutForwardingCleanupByTabId = new Map void>()
@@ -636,6 +656,9 @@ export class BrowserManager {
this.rendererWebContentsIdByTabId.delete(browserTabId)
this.workspaceIdByPageId.delete(browserTabId)
this.worktreeIdByTabId.delete(browserTabId)
+ // Why: drop any pending viewport-op chain for this tab so the Map doesn't
+ // retain a resolved promise keyed to a destroyed guest.
+ this.viewportOpsByTabId.delete(browserTabId)
}
unregisterAll(): void {
@@ -875,6 +898,132 @@ export class BrowserManager {
return true
}
+ // Why: Electron guests do not expose Chrome DevTools' device
+ // toolbar (Cmd+Shift+M) to the embedding app, so viewport emulation must be
+ // driven through CDP directly. We reuse the debugger attachment that
+ // injectAntiDetection already established and never detach it here — doing
+ // so would clear Page.addScriptToEvaluateOnNewDocument and other per-guest
+ // overrides. Passing override=null clears emulation.
+ async setViewportOverride(
+ browserTabId: string,
+ override: BrowserViewportOverride | null
+ ): Promise {
+ // Why: chain per-tab so rapid toggles (e.g. user clicking presets quickly)
+ // don't interleave CDP commands. Each call waits for the previous one to
+ // settle, guaranteeing the last-requested override wins rather than whichever
+ // sendCommand sequence happens to finish last.
+ const prev = this.viewportOpsByTabId.get(browserTabId) ?? Promise.resolve()
+ const next = prev
+ .catch(() => {})
+ .then(() => this.doSetViewportOverrideImpl(browserTabId, override))
+ this.viewportOpsByTabId.set(browserTabId, next)
+ try {
+ return await next
+ } finally {
+ // Why: only clear if this call's promise is still the tail. A concurrent
+ // later call may have already replaced the entry; deleting would drop the
+ // chain and break serialization for the next invocation.
+ if (this.viewportOpsByTabId.get(browserTabId) === next) {
+ this.viewportOpsByTabId.delete(browserTabId)
+ }
+ }
+ }
+
+ private async doSetViewportOverrideImpl(
+ browserTabId: string,
+ override: BrowserViewportOverride | null
+ ): Promise {
+ const webContentsId = this.webContentsIdByTabId.get(browserTabId)
+ if (!webContentsId) {
+ return false
+ }
+ const guest = webContents.fromId(webContentsId)
+ if (!guest || guest.isDestroyed()) {
+ this.webContentsIdByTabId.delete(browserTabId)
+ this.tabIdByWebContentsId.delete(webContentsId)
+ return false
+ }
+
+ try {
+ if (!guest.debugger.isAttached()) {
+ guest.debugger.attach('1.3')
+ }
+ } catch (err) {
+ // Why: DevTools being open on the guest causes attach to throw with
+ // "Another debugger is already attached". Silently returning false made
+ // this failure mode undiagnosable — surface it via the logger with enough
+ // context (tab + webContents ids) to correlate with user reports.
+ console.warn('[browser-manager] setViewportOverride: failed to attach debugger', {
+ browserTabId,
+ webContentsId,
+ error: err instanceof Error ? err.message : String(err)
+ })
+ return false
+ }
+
+ const dbg = guest.debugger
+ try {
+ if (override) {
+ await dbg.sendCommand('Emulation.setDeviceMetricsOverride', {
+ width: override.width,
+ height: override.height,
+ deviceScaleFactor: override.deviceScaleFactor,
+ mobile: override.mobile
+ })
+ await dbg.sendCommand('Emulation.setTouchEmulationEnabled', {
+ enabled: override.mobile,
+ maxTouchPoints: override.mobile ? 5 : 0
+ })
+ if (override.mobile) {
+ const chromeMajor = extractChromeMajor(cleanElectronUserAgent(guest.getUserAgent()))
+ // Why: pass userAgentMetadata alongside the mobile UA string so
+ // sec-ch-ua-mobile / sec-ch-ua-platform client hints match. Without
+ // it, session-level desktop client-hints leak through and create a
+ // UA/CH mismatch that bot-detection (Cloudflare, Turnstile) flags.
+ await dbg.sendCommand('Emulation.setUserAgentOverride', {
+ userAgent: buildMobileUserAgent(chromeMajor),
+ userAgentMetadata: {
+ brands: [
+ { brand: 'Google Chrome', version: chromeMajor },
+ { brand: 'Chromium', version: chromeMajor },
+ { brand: 'Not/A)Brand', version: '24' }
+ ],
+ fullVersionList: [
+ { brand: 'Google Chrome', version: `${chromeMajor}.0.0.0` },
+ { brand: 'Chromium', version: `${chromeMajor}.0.0.0` },
+ { brand: 'Not/A)Brand', version: '24.0.0.0' }
+ ],
+ fullVersion: `${chromeMajor}.0.0.0`,
+ platform: 'iOS',
+ platformVersion: '17.0',
+ architecture: '',
+ model: 'iPhone',
+ mobile: true
+ }
+ })
+ } else {
+ // Why: desktop presets still need the clean (non-Electron) UA so
+ // Cloudflare/Turnstile don't flag the session. Passing the cleaned
+ // real UA keeps sec-ch-ua consistent with the override.
+ await dbg.sendCommand('Emulation.setUserAgentOverride', {
+ userAgent: cleanElectronUserAgent(guest.getUserAgent())
+ })
+ }
+ } else {
+ await dbg.sendCommand('Emulation.clearDeviceMetricsOverride', {})
+ await dbg.sendCommand('Emulation.setTouchEmulationEnabled', {
+ enabled: false,
+ maxTouchPoints: 0
+ })
+ // Why: passing an empty string restores the session default UA.
+ await dbg.sendCommand('Emulation.setUserAgentOverride', { userAgent: '' })
+ }
+ return true
+ } catch {
+ return false
+ }
+ }
+
// ---------------------------------------------------------------------------
// Browser Context Grab — main-owned operations
// ---------------------------------------------------------------------------
diff --git a/src/main/browser/browser-media-access.ts b/src/main/browser/browser-media-access.ts
new file mode 100644
index 000000000..c1138d6ac
--- /dev/null
+++ b/src/main/browser/browser-media-access.ts
@@ -0,0 +1,63 @@
+import { systemPreferences } from 'electron'
+import type { MediaAccessPermissionRequest } from 'electron'
+
+// Why: macOS gates all camera/microphone access at the app-process level via
+// TCC. Electron's per-session permission handlers run inside that envelope:
+// if we call callback(true) but macOS has not granted the parent app, the
+// stream is still empty. Conversely, if we deny at the session handler, pages
+// never see the stream even when macOS has granted — which is the bug the user
+// hit inside the in-app browser (#1273 only fixed Settings → Permissions, not
+// the actual runtime getUserMedia() path).
+//
+// These helpers let both the main window session and the browser-tab sessions
+// consult the same macOS-aware logic, so once a user has granted Camera or
+// Microphone to Orca (via Settings → Permissions or directly in System
+// Settings), a page inside an in-app browser tab actually receives the stream.
+
+export function requestedMediaTypes(
+ details: MediaAccessPermissionRequest | undefined
+): Set<'audio' | 'video'> {
+ return new Set(details?.mediaTypes ?? [])
+}
+
+export function hasSystemMediaAccess(mediaType: string | undefined): boolean {
+ if (process.platform !== 'darwin') {
+ return true
+ }
+ if (mediaType === 'audio') {
+ return systemPreferences.getMediaAccessStatus('microphone') === 'granted'
+ }
+ if (mediaType === 'video') {
+ return systemPreferences.getMediaAccessStatus('camera') === 'granted'
+ }
+ return false
+}
+
+export async function requestSystemMediaAccess(
+ details: MediaAccessPermissionRequest | undefined
+): Promise {
+ if (process.platform !== 'darwin') {
+ return true
+ }
+
+ const mediaTypes = requestedMediaTypes(details)
+ if (mediaTypes.size === 0) {
+ return false
+ }
+
+ if (mediaTypes.has('audio')) {
+ // Why: macOS only shows the TCC prompt from the app process, so Chromium's
+ // media grant is paired with the OS-level request at the actual media ask.
+ const granted = await systemPreferences.askForMediaAccess('microphone')
+ if (!granted) {
+ return false
+ }
+ }
+ if (mediaTypes.has('video')) {
+ const granted = await systemPreferences.askForMediaAccess('camera')
+ if (!granted) {
+ return false
+ }
+ }
+ return true
+}
diff --git a/src/main/browser/browser-session-registry.test.ts b/src/main/browser/browser-session-registry.test.ts
index 822ecd884..6a51a95c1 100644
--- a/src/main/browser/browser-session-registry.test.ts
+++ b/src/main/browser/browser-session-registry.test.ts
@@ -1,12 +1,20 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
-const { sessionFromPartitionMock } = vi.hoisted(() => ({
- sessionFromPartitionMock: vi.fn()
-}))
+const { sessionFromPartitionMock, askForMediaAccessMock, getMediaAccessStatusMock } = vi.hoisted(
+ () => ({
+ sessionFromPartitionMock: vi.fn(),
+ askForMediaAccessMock: vi.fn(),
+ getMediaAccessStatusMock: vi.fn()
+ })
+)
vi.mock('electron', () => ({
session: {
fromPartition: sessionFromPartitionMock
+ },
+ systemPreferences: {
+ askForMediaAccess: askForMediaAccessMock,
+ getMediaAccessStatus: getMediaAccessStatusMock
}
}))
@@ -24,6 +32,10 @@ import { ORCA_BROWSER_PARTITION } from '../../shared/constants'
describe('BrowserSessionRegistry', () => {
beforeEach(() => {
sessionFromPartitionMock.mockReset()
+ askForMediaAccessMock.mockReset()
+ getMediaAccessStatusMock.mockReset()
+ askForMediaAccessMock.mockResolvedValue(true)
+ getMediaAccessStatusMock.mockReturnValue('granted')
sessionFromPartitionMock.mockReturnValue({
setPermissionRequestHandler: vi.fn(),
setPermissionCheckHandler: vi.fn(),
@@ -147,6 +159,25 @@ describe('BrowserSessionRegistry', () => {
expect(mockSession?.setPermissionCheckHandler).toHaveBeenCalled()
})
+ it('routes media permission requests through macOS TCC for isolated partitions', async () => {
+ // Why: verify the parallel fix to the default partition — isolated/imported
+ // profiles must also defer media permission checks to macOS instead of
+ // denying outright, otherwise pages inside them still hit NotAllowedError
+ // after the user grants Camera/Microphone to Orca.
+ browserSessionRegistry.createProfile('isolated', 'Media Test')
+ const mockSession = sessionFromPartitionMock.mock.results[0]?.value
+ const requestHandler = mockSession.setPermissionRequestHandler.mock.calls[0][0]
+ const checkHandler = mockSession.setPermissionCheckHandler.mock.calls[0][0]
+
+ const cb = vi.fn()
+ const guestWc = { id: 7, getURL: vi.fn(() => 'https://example.com/') }
+ requestHandler(guestWc, 'media', cb, { mediaTypes: ['video'] })
+ await vi.waitFor(() => expect(cb).toHaveBeenCalledWith(true))
+
+ expect(checkHandler(null, 'media', '', { mediaType: 'video' })).toBe(true)
+ expect(checkHandler(null, 'notifications', '', {})).toBe(false)
+ })
+
describe('setupClientHintsOverride', () => {
it('overrides sec-ch-ua headers for Edge UA', () => {
const onBeforeSendHeaders = vi.fn()
diff --git a/src/main/browser/browser-session-registry.ts b/src/main/browser/browser-session-registry.ts
index 10272c1cb..cf6d3fffa 100644
--- a/src/main/browser/browser-session-registry.ts
+++ b/src/main/browser/browser-session-registry.ts
@@ -16,6 +16,7 @@ import { join } from 'node:path'
import { ORCA_BROWSER_PARTITION } from '../../shared/constants'
import type { BrowserSessionProfile, BrowserSessionProfileScope } from '../../shared/types'
import { browserManager } from './browser-manager'
+import { hasSystemMediaAccess, requestSystemMediaAccess } from './browser-media-access'
import { cleanElectronUserAgent, setupClientHintsOverride } from './browser-session-ua'
type BrowserSessionMeta = {
@@ -358,7 +359,39 @@ class BrowserSessionRegistry {
// clipboard commands to work. Without these, navigator.clipboard.writeText/readText
// throws NotAllowedError even when invoked via CDP with userGesture:true.
const autoGranted = new Set(['fullscreen', 'clipboard-read', 'clipboard-sanitized-write'])
- sess.setPermissionRequestHandler((webContents, permission, callback) => {
+ sess.setPermissionRequestHandler((webContents, permission, callback, details) => {
+ // Why: `media` (camera/mic) must defer to macOS TCC instead of being
+ // denied outright. Denying at the session layer would make pages inside
+ // isolated browser profiles throw NotAllowedError even after the user
+ // granted Camera/Microphone to Orca — the same bug we fixed for the
+ // default partition. macOS TCC still gates the actual stream, so
+ // granting here only forwards what the OS has already authorized.
+ if (permission === 'media') {
+ void requestSystemMediaAccess(
+ details as Electron.MediaAccessPermissionRequest | undefined
+ ).then(
+ (granted) => {
+ if (!granted) {
+ browserManager.notifyPermissionDenied({
+ guestWebContentsId: webContents.id,
+ permission,
+ rawUrl: webContents.getURL()
+ })
+ }
+ callback(granted)
+ },
+ (error: unknown) => {
+ console.error('[permissions] Browser media access failed:', error)
+ browserManager.notifyPermissionDenied({
+ guestWebContentsId: webContents.id,
+ permission,
+ rawUrl: webContents.getURL()
+ })
+ callback(false)
+ }
+ )
+ return
+ }
const allowed = autoGranted.has(permission)
if (!allowed) {
browserManager.notifyPermissionDenied({
@@ -369,7 +402,10 @@ class BrowserSessionRegistry {
}
callback(allowed)
})
- sess.setPermissionCheckHandler((_webContents, permission) => {
+ sess.setPermissionCheckHandler((_webContents, permission, _origin, details) => {
+ if (permission === 'media') {
+ return hasSystemMediaAccess(details?.mediaType)
+ }
return autoGranted.has(permission)
})
sess.setDisplayMediaRequestHandler((_request, callback) => {
diff --git a/src/main/claude-accounts/runtime-auth-service.ts b/src/main/claude-accounts/runtime-auth-service.ts
index 64768f2ee..3c9f32c36 100644
--- a/src/main/claude-accounts/runtime-auth-service.ts
+++ b/src/main/claude-accounts/runtime-auth-service.ts
@@ -13,7 +13,8 @@ import {
deleteActiveClaudeKeychainCredentials,
readActiveClaudeKeychainCredentials,
readManagedClaudeKeychainCredentials,
- writeActiveClaudeKeychainCredentials
+ writeActiveClaudeKeychainCredentials,
+ writeManagedClaudeKeychainCredentials
} from './keychain'
export type ClaudeRuntimeAuthPreparation = {
@@ -122,6 +123,14 @@ export class ClaudeRuntimeAuthService {
return
}
+ // Why: Claude CLI refreshes expired OAuth tokens and writes them back to
+ // .credentials.json. If we detect the runtime file differs from what Orca
+ // last wrote, the CLI must have refreshed — so we preserve those tokens
+ // back to managed storage before overwriting runtime with managed state.
+ if (this.lastSyncedAccountId === activeAccount.id) {
+ await this.readBackRefreshedTokens(activeAccount)
+ }
+
this.writeRuntimeCredentials(credentialsJson)
if (process.platform === 'darwin') {
await writeActiveClaudeKeychainCredentials(credentialsJson)
@@ -130,6 +139,44 @@ export class ClaudeRuntimeAuthService {
this.lastSyncedAccountId = activeAccount.id
}
+ // Why: called by ClaudeAccountService before syncForCurrentSelection() after
+ // re-auth or add-account. Those flows write fresh tokens to managed storage,
+ // so the read-back must be skipped to avoid overwriting them with stale
+ // runtime tokens.
+ clearLastWrittenCredentialsJson(): void {
+ this.lastWrittenCredentialsJson = null
+ }
+
+ private async readBackRefreshedTokens(account: ClaudeManagedAccount): Promise {
+ try {
+ if (this.lastWrittenCredentialsJson === null) {
+ return
+ }
+
+ const paths = this.pathResolver.getRuntimePaths()
+ if (!existsSync(paths.credentialsPath)) {
+ return
+ }
+
+ const runtimeContents = readFileSync(paths.credentialsPath, 'utf-8')
+ if (runtimeContents === this.lastWrittenCredentialsJson) {
+ return
+ }
+
+ if (process.platform === 'darwin') {
+ await writeManagedClaudeKeychainCredentials(account.id, runtimeContents)
+ } else {
+ const credentialsPath = join(account.managedAuthPath, '.credentials.json')
+ writeFileAtomically(credentialsPath, runtimeContents, { mode: 0o600 })
+ }
+ } catch (error) {
+ // Why: read-back is best-effort. A transient fs error must not block the
+ // forward sync path — the worst case is one more stale-token cycle, which
+ // is strictly better than failing the entire sync.
+ console.warn('[claude-runtime-auth] Failed to read back refreshed tokens:', error)
+ }
+ }
+
private getPreparation(): ClaudeRuntimeAuthPreparation {
const settings = this.store.getSettings()
const paths = this.pathResolver.getRuntimePaths()
diff --git a/src/main/claude-accounts/service.ts b/src/main/claude-accounts/service.ts
index b1245c234..78324c2ca 100644
--- a/src/main/claude-accounts/service.ts
+++ b/src/main/claude-accounts/service.ts
@@ -115,6 +115,7 @@ export class ClaudeAccountService {
claudeManagedAccounts: [...previousSettings.claudeManagedAccounts, account],
activeClaudeManagedAccountId: account.id
})
+ this.runtimeAuth.clearLastWrittenCredentialsJson()
await this.syncRuntimeAuthWithLivePtyGate()
await this.rateLimits.refreshForClaudeAccountChange(outgoingAccountId)
return this.getSnapshot()
@@ -153,6 +154,7 @@ export class ClaudeAccountService {
)
})
try {
+ this.runtimeAuth.clearLastWrittenCredentialsJson()
await this.syncRuntimeAuthWithLivePtyGate()
await this.rateLimits.refreshForClaudeAccountChange()
return this.getSnapshot()
diff --git a/src/main/claude/hook-service.ts b/src/main/claude/hook-service.ts
index 587967ec6..a78445ec1 100644
--- a/src/main/claude/hook-service.ts
+++ b/src/main/claude/hook-service.ts
@@ -48,7 +48,13 @@ function getManagedScriptPath(): string {
}
function getManagedCommand(scriptPath: string): string {
- return process.platform === 'win32' ? scriptPath : `/bin/sh "${scriptPath}"`
+ // Why: on Windows, Claude Code runs hooks through Git Bash (`/usr/bin/bash`).
+ // A path with single backslashes (e.g. `C:\Users\…\claude-hook.cmd`) is
+ // interpreted by bash as a string with escape sequences, so `\U`, `\A`, etc.
+ // collapse and the launcher fails with `command not found`. Emit forward
+ // slashes — Windows accepts them in path arguments and bash leaves them
+ // intact, so the same JSON value works through every shell layer.
+ return process.platform === 'win32' ? scriptPath.replaceAll('\\', '/') : `/bin/sh "${scriptPath}"`
}
function getManagedScript(): string {
diff --git a/src/main/codex-accounts/runtime-home-service.test.ts b/src/main/codex-accounts/runtime-home-service.test.ts
index d2eee76fd..65d304f71 100644
--- a/src/main/codex-accounts/runtime-home-service.test.ts
+++ b/src/main/codex-accounts/runtime-home-service.test.ts
@@ -39,10 +39,12 @@ function createSettings(overrides: Partial = {}): GlobalSettings
theme: 'system',
editorAutoSave: false,
editorAutoSaveDelayMs: 1000,
+ editorMinimapEnabled: false,
terminalFontSize: 14,
terminalFontFamily: 'JetBrains Mono',
terminalFontWeight: 500,
terminalLineHeight: 1,
+ terminalGpuAcceleration: 'auto',
terminalLigatures: 'auto',
terminalCursorStyle: 'block',
terminalCursorBlink: false,
@@ -93,7 +95,9 @@ function createSettings(overrides: Partial = {}): GlobalSettings
terminalMacOptionAsAltMigrated: true,
experimentalAgentDashboard: false,
experimentalMobile: false,
+ experimentalSidekick: false,
terminalWindowsShell: 'powershell.exe',
+ terminalWindowsPowerShellImplementation: 'powershell.exe',
enableGitHubAttribution: true,
...overrides
}
@@ -499,6 +503,225 @@ describe('CodexRuntimeHomeService', () => {
expect(existsSync(snapshotPath)).toBe(false)
})
+ it('reads back CLI-refreshed tokens into managed storage on subsequent sync', async () => {
+ const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json')
+ writeFileSync(runtimeAuthPath, '{"account":"system"}\n', 'utf-8')
+ const managedHomePath = createManagedAuth(
+ testState.userDataDir,
+ 'account-1',
+ '{"tokens":"original"}\n'
+ )
+ const managedAuthPath = join(managedHomePath, 'auth.json')
+ const settings = createSettings({
+ codexManagedAccounts: [
+ {
+ id: 'account-1',
+ email: 'user@example.com',
+ managedHomePath,
+ providerAccountId: null,
+ workspaceLabel: null,
+ workspaceAccountId: null,
+ createdAt: 1,
+ updatedAt: 1,
+ lastAuthenticatedAt: 1
+ }
+ ],
+ activeCodexManagedAccountId: 'account-1'
+ })
+ const store = createStore(settings)
+
+ const { CodexRuntimeHomeService } = await import('./runtime-home-service')
+ const service = new CodexRuntimeHomeService(store as never)
+
+ // Simulate CLI refreshing the token in ~/.codex/auth.json
+ writeFileSync(runtimeAuthPath, '{"tokens":"refreshed"}\n', 'utf-8')
+
+ // Next sync should read back the refreshed token to managed storage
+ service.syncForCurrentSelection()
+
+ expect(readFileSync(managedAuthPath, 'utf-8')).toBe('{"tokens":"refreshed"}\n')
+ expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe('{"tokens":"refreshed"}\n')
+ })
+
+ it('skips read-back on first sync after restart (lastWrittenAuthJson is null)', async () => {
+ const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json')
+ // Pre-populate runtime with different content to simulate a CLI refresh while Orca was down
+ writeFileSync(runtimeAuthPath, '{"tokens":"refreshed-while-down"}\n', 'utf-8')
+ const managedHomePath = createManagedAuth(
+ testState.userDataDir,
+ 'account-1',
+ '{"tokens":"original"}\n'
+ )
+ const managedAuthPath = join(managedHomePath, 'auth.json')
+ const store = createStore(
+ createSettings({
+ codexManagedAccounts: [
+ {
+ id: 'account-1',
+ email: 'user@example.com',
+ managedHomePath,
+ providerAccountId: null,
+ workspaceLabel: null,
+ workspaceAccountId: null,
+ createdAt: 1,
+ updatedAt: 1,
+ lastAuthenticatedAt: 1
+ }
+ ],
+ activeCodexManagedAccountId: 'account-1'
+ })
+ )
+
+ const { CodexRuntimeHomeService } = await import('./runtime-home-service')
+ new CodexRuntimeHomeService(store as never)
+
+ // After restart, managed storage should NOT be overwritten by unknown runtime state
+ expect(readFileSync(managedAuthPath, 'utf-8')).toBe('{"tokens":"original"}\n')
+ // Runtime should be overwritten with managed (conservative behavior)
+ expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe('{"tokens":"original"}\n')
+ })
+
+ it('skips read-back during account switch', async () => {
+ const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json')
+ writeFileSync(runtimeAuthPath, '{"account":"system"}\n', 'utf-8')
+ const managedHomePath1 = createManagedAuth(
+ testState.userDataDir,
+ 'account-1',
+ '{"tokens":"account1"}\n'
+ )
+ const managedHomePath2 = createManagedAuth(
+ testState.userDataDir,
+ 'account-2',
+ '{"tokens":"account2"}\n'
+ )
+ const managedAuthPath2 = join(managedHomePath2, 'auth.json')
+ const settings = createSettings({
+ codexManagedAccounts: [
+ {
+ id: 'account-1',
+ email: 'user1@example.com',
+ managedHomePath: managedHomePath1,
+ providerAccountId: null,
+ workspaceLabel: null,
+ workspaceAccountId: null,
+ createdAt: 1,
+ updatedAt: 1,
+ lastAuthenticatedAt: 1
+ },
+ {
+ id: 'account-2',
+ email: 'user2@example.com',
+ managedHomePath: managedHomePath2,
+ providerAccountId: null,
+ workspaceLabel: null,
+ workspaceAccountId: null,
+ createdAt: 1,
+ updatedAt: 1,
+ lastAuthenticatedAt: 1
+ }
+ ],
+ activeCodexManagedAccountId: 'account-1'
+ })
+ const store = createStore(settings)
+
+ const { CodexRuntimeHomeService } = await import('./runtime-home-service')
+ const service = new CodexRuntimeHomeService(store as never)
+
+ // Switch to account-2 — runtime still has account-1 tokens
+ settings.activeCodexManagedAccountId = 'account-2'
+ service.syncForCurrentSelection()
+
+ // Account-2's managed auth should NOT be contaminated with account-1's runtime tokens
+ expect(readFileSync(managedAuthPath2, 'utf-8')).toBe('{"tokens":"account2"}\n')
+ expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe('{"tokens":"account2"}\n')
+ })
+
+ it('detects external login on managed→system-default transition', async () => {
+ const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json')
+ writeFileSync(runtimeAuthPath, '{"account":"system"}\n', 'utf-8')
+ const managedHomePath = createManagedAuth(
+ testState.userDataDir,
+ 'account-1',
+ '{"account":"managed"}\n'
+ )
+ const settings = createSettings({
+ codexManagedAccounts: [
+ {
+ id: 'account-1',
+ email: 'user@example.com',
+ managedHomePath,
+ providerAccountId: null,
+ workspaceLabel: null,
+ workspaceAccountId: null,
+ createdAt: 1,
+ updatedAt: 1,
+ lastAuthenticatedAt: 1
+ }
+ ],
+ activeCodexManagedAccountId: 'account-1'
+ })
+ const store = createStore(settings)
+
+ const { CodexRuntimeHomeService } = await import('./runtime-home-service')
+ const service = new CodexRuntimeHomeService(store as never)
+
+ // External `codex auth login` overwrites runtime auth
+ writeFileSync(runtimeAuthPath, '{"account":"external-login"}\n', 'utf-8')
+
+ // Deselect managed account
+ settings.activeCodexManagedAccountId = null
+ service.syncForCurrentSelection()
+
+ // Should keep the external login, not restore stale system snapshot
+ expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe('{"account":"external-login"}\n')
+ // Snapshot should be deleted so next capture picks up the external login
+ expect(
+ existsSync(join(testState.userDataDir, 'codex-runtime-home', 'system-default-auth.json'))
+ ).toBe(false)
+ })
+
+ it('does not clobber fresh tokens after clearLastWrittenAuthJson', async () => {
+ const runtimeAuthPath = join(testState.fakeHomeDir, '.codex', 'auth.json')
+ writeFileSync(runtimeAuthPath, '{"account":"system"}\n', 'utf-8')
+ const managedHomePath = createManagedAuth(
+ testState.userDataDir,
+ 'account-1',
+ '{"tokens":"original"}\n'
+ )
+ const managedAuthPath = join(managedHomePath, 'auth.json')
+ const settings = createSettings({
+ codexManagedAccounts: [
+ {
+ id: 'account-1',
+ email: 'user@example.com',
+ managedHomePath,
+ providerAccountId: null,
+ workspaceLabel: null,
+ workspaceAccountId: null,
+ createdAt: 1,
+ updatedAt: 1,
+ lastAuthenticatedAt: 1
+ }
+ ],
+ activeCodexManagedAccountId: 'account-1'
+ })
+ const store = createStore(settings)
+
+ const { CodexRuntimeHomeService } = await import('./runtime-home-service')
+ const service = new CodexRuntimeHomeService(store as never)
+
+ // Simulate re-auth: managed storage gets fresh tokens
+ writeFileSync(managedAuthPath, '{"tokens":"reauthed"}\n', 'utf-8')
+
+ // Clear tracking before sync (as CodexAccountService would)
+ service.clearLastWrittenAuthJson()
+ service.syncForCurrentSelection()
+
+ // Fresh re-auth tokens should survive — not be clobbered by stale runtime read-back
+ expect(readFileSync(managedAuthPath, 'utf-8')).toBe('{"tokens":"reauthed"}\n')
+ expect(readFileSync(runtimeAuthPath, 'utf-8')).toBe('{"tokens":"reauthed"}\n')
+ })
+
it('preserves conflicting legacy session files under deterministic names', async () => {
const runtimeSessionsDir = join(testState.fakeHomeDir, '.codex', 'sessions')
mkdirSync(runtimeSessionsDir, { recursive: true })
diff --git a/src/main/codex-accounts/runtime-home-service.ts b/src/main/codex-accounts/runtime-home-service.ts
index f0cf6fd84..3ec95ecfa 100644
--- a/src/main/codex-accounts/runtime-home-service.ts
+++ b/src/main/codex-accounts/runtime-home-service.ts
@@ -24,6 +24,13 @@ export class CodexRuntimeHomeService {
// (e.g. user running `codex login` or another auth tool). The snapshot
// restore only fires on the managed→system-default transition.
private lastSyncedAccountId: string | null = null
+ // Why: tracks the auth.json content Orca last wrote to ~/.codex/auth.json.
+ // Between syncs, if the file differs, Codex CLI refreshed the token — so
+ // Orca writes back the refreshed token to managed storage before overwriting.
+ // On managed→system-default transition, if the file differs, an external
+ // login (e.g. `codex auth login`) overwrote it — so Orca adopts the file as
+ // the new system default instead of restoring a stale snapshot.
+ private lastWrittenAuthJson: string | null = null
constructor(private readonly store: Store) {
this.safeMigrateLegacyManagedState()
@@ -80,10 +87,51 @@ export class CodexRuntimeHomeService {
return
}
+ // Why: Codex CLI refreshes expired OAuth tokens and writes them back to
+ // ~/.codex/auth.json. If we detect the runtime file differs from what Orca
+ // last wrote, the CLI must have refreshed — so we preserve those tokens
+ // back to managed storage before overwriting runtime with managed state.
+ if (this.lastSyncedAccountId === activeAccount.id) {
+ this.readBackRefreshedTokens(activeAuthPath)
+ }
+
this.lastSyncedAccountId = activeAccount.id
this.writeRuntimeAuth(readFileSync(activeAuthPath, 'utf-8'))
}
+ // Why: called by CodexAccountService before syncForCurrentSelection() after
+ // re-auth or add-account. Those flows write fresh tokens to managed storage,
+ // so the read-back must be skipped to avoid overwriting them with stale
+ // runtime tokens.
+ clearLastWrittenAuthJson(): void {
+ this.lastWrittenAuthJson = null
+ }
+
+ private readBackRefreshedTokens(managedAuthPath: string): void {
+ try {
+ const runtimeAuthPath = this.getRuntimeAuthPath()
+ if (!existsSync(runtimeAuthPath)) {
+ return
+ }
+
+ if (this.lastWrittenAuthJson === null) {
+ return
+ }
+
+ const runtimeContents = readFileSync(runtimeAuthPath, 'utf-8')
+ if (runtimeContents === this.lastWrittenAuthJson) {
+ return
+ }
+
+ writeFileAtomically(managedAuthPath, runtimeContents, { mode: 0o600 })
+ } catch (error) {
+ // Why: read-back is best-effort. A transient fs error must not block the
+ // forward sync path — the worst case is one more stale-token cycle, which
+ // is strictly better than failing the entire sync.
+ console.warn('[codex-runtime-home] Failed to read back refreshed tokens:', error)
+ }
+ }
+
private safeSyncForCurrentSelection(): void {
try {
this.syncForCurrentSelection()
@@ -297,6 +345,13 @@ export class CodexRuntimeHomeService {
}
private restoreSystemDefaultSnapshot(): void {
+ // Why: detect whether an external tool (e.g. `codex auth login`) overwrote
+ // auth.json while a managed account was active. If so, that external login
+ // becomes the new system default — skip the stale snapshot restore.
+ if (this.detectExternalLoginAndUpdateSnapshot()) {
+ return
+ }
+
const snapshotPath = this.getSystemDefaultSnapshotPath()
if (!existsSync(snapshotPath)) {
return
@@ -305,10 +360,40 @@ export class CodexRuntimeHomeService {
this.writeRuntimeAuth(readFileSync(snapshotPath, 'utf-8'))
}
+ // Why: mirrors ClaudeRuntimeAuthService.detectExternalLoginAndUpdateSnapshot().
+ // If the runtime auth.json differs from what Orca last wrote, something
+ // external changed it. That external state should become the new system
+ // default rather than being overwritten by a potentially stale snapshot.
+ private detectExternalLoginAndUpdateSnapshot(): boolean {
+ if (this.lastWrittenAuthJson === null) {
+ return false
+ }
+
+ const runtimeAuthPath = this.getRuntimeAuthPath()
+ if (!existsSync(runtimeAuthPath)) {
+ return false
+ }
+
+ try {
+ const currentAuth = readFileSync(runtimeAuthPath, 'utf-8')
+ if (currentAuth === this.lastWrittenAuthJson) {
+ return false
+ }
+ } catch {
+ return false
+ }
+
+ const snapshotPath = this.getSystemDefaultSnapshotPath()
+ rmSync(snapshotPath, { force: true })
+ this.lastWrittenAuthJson = null
+ return true
+ }
+
private writeRuntimeAuth(contents: string): void {
// Why: auth.json contains sensitive credentials. Restrict to owner-only
// so other users on a shared Linux/macOS machine cannot read it.
writeFileAtomically(this.getRuntimeAuthPath(), contents, { mode: 0o600 })
+ this.lastWrittenAuthJson = contents
}
clearSystemDefaultSnapshot(): void {
diff --git a/src/main/codex-accounts/service.test.ts b/src/main/codex-accounts/service.test.ts
index bba54ebe3..cff5f956d 100644
--- a/src/main/codex-accounts/service.test.ts
+++ b/src/main/codex-accounts/service.test.ts
@@ -33,10 +33,12 @@ function createSettings(overrides: Partial = {}): GlobalSettings
theme: 'system',
editorAutoSave: false,
editorAutoSaveDelayMs: 1000,
+ editorMinimapEnabled: false,
terminalFontSize: 14,
terminalFontFamily: 'JetBrains Mono',
terminalFontWeight: 500,
terminalLineHeight: 1,
+ terminalGpuAcceleration: 'auto',
terminalLigatures: 'auto',
terminalCursorStyle: 'block',
terminalCursorBlink: false,
@@ -87,7 +89,9 @@ function createSettings(overrides: Partial = {}): GlobalSettings
terminalMacOptionAsAltMigrated: true,
experimentalAgentDashboard: false,
experimentalMobile: false,
+ experimentalSidekick: false,
terminalWindowsShell: 'powershell.exe',
+ terminalWindowsPowerShellImplementation: 'powershell.exe',
enableGitHubAttribution: true,
...overrides
}
@@ -119,7 +123,8 @@ function createRateLimits() {
function createRuntimeHome() {
return {
- syncForCurrentSelection: vi.fn()
+ syncForCurrentSelection: vi.fn(),
+ clearLastWrittenAuthJson: vi.fn()
}
}
diff --git a/src/main/codex-accounts/service.ts b/src/main/codex-accounts/service.ts
index f2344954b..2fcaa742c 100644
--- a/src/main/codex-accounts/service.ts
+++ b/src/main/codex-accounts/service.ts
@@ -106,6 +106,7 @@ export class CodexAccountService {
activeCodexManagedAccountId: account.id
})
this.safeSyncCanonicalConfigToManagedHomes()
+ this.runtimeHome.clearLastWrittenAuthJson()
this.runtimeHome.syncForCurrentSelection()
// Why: the new account becomes active, so the previous active account is
@@ -149,6 +150,7 @@ export class CodexAccountService {
codexManagedAccounts: updatedAccounts
})
this.safeSyncCanonicalConfigToManagedHomes()
+ this.runtimeHome.clearLastWrittenAuthJson()
this.runtimeHome.syncForCurrentSelection()
// Why: re-auth can change which actual Codex identity the managed home
diff --git a/src/main/daemon/daemon-health.test.ts b/src/main/daemon/daemon-health.test.ts
index 2b9884f07..a4c9ef206 100644
--- a/src/main/daemon/daemon-health.test.ts
+++ b/src/main/daemon/daemon-health.test.ts
@@ -1,11 +1,17 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { mkdtempSync, rmSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { createServer, connect, type Server } from 'net'
import { DaemonServer } from './daemon-server'
-import { getDaemonPidPath } from './daemon-spawner'
-import { healthCheckDaemon, killStaleDaemon } from './daemon-health'
+import { getDaemonPidPath, serializeDaemonPidFile } from './daemon-spawner'
+import {
+ getProcessStartedAtMs,
+ healthCheckDaemon,
+ killStaleDaemon,
+ parseDaemonPidFile,
+ startTimeMatches
+} from './daemon-health'
import type { SubprocessHandle } from './session'
function createMockSubprocess(): SubprocessHandle {
@@ -17,7 +23,8 @@ function createMockSubprocess(): SubprocessHandle {
forceKill() {},
signal() {},
onData() {},
- onExit() {}
+ onExit() {},
+ dispose() {}
}
}
@@ -107,3 +114,126 @@ describe('daemon health', () => {
}
})
})
+
+describe('parseDaemonPidFile', () => {
+ it('parses JSON pid files with startedAtMs', () => {
+ const serialized = serializeDaemonPidFile({ pid: 12345, startedAtMs: 1_700_000_000_000 })
+ expect(parseDaemonPidFile(serialized)).toEqual({
+ pid: 12345,
+ startedAtMs: 1_700_000_000_000
+ })
+ })
+
+ it('accepts JSON with startedAtMs missing and returns null for it', () => {
+ // Why: forward-compatible with hypothetical future daemons that might write
+ // pid without startedAtMs (platform where getProcessStartedAtMs returns null).
+ expect(parseDaemonPidFile('{"pid":9999}')).toEqual({ pid: 9999, startedAtMs: null })
+ })
+
+ it('falls back to bare-integer parsing for legacy pid files', () => {
+ // Why: pre-Phase-0 daemons wrote the pid file as a bare integer.
+ // parseDaemonPidFile must still accept those to avoid leaking a stale
+ // daemon across a single upgrade boundary.
+ expect(parseDaemonPidFile('12345')).toEqual({ pid: 12345, startedAtMs: null })
+ expect(parseDaemonPidFile(' 12345\n')).toEqual({ pid: 12345, startedAtMs: null })
+ })
+
+ it('returns null for malformed input', () => {
+ expect(parseDaemonPidFile('not-a-number')).toBeNull()
+ expect(parseDaemonPidFile('{"pid":"abc"}')).toBeNull()
+ expect(parseDaemonPidFile('{"not_pid":123}')).toBeNull()
+ })
+})
+
+describe('startTimeMatches', () => {
+ it('returns true when expected is null (legacy pid file)', () => {
+ // The real process pid is irrelevant here — null short-circuits before
+ // getProcessStartedAtMs is consulted.
+ expect(startTimeMatches(process.pid, null)).toBe(true)
+ })
+
+ it('returns true when actual start time cannot be read (fail-open)', () => {
+ if (process.platform === 'win32') {
+ // Windows always returns null from getProcessStartedAtMs, which is the
+ // fail-open case we want.
+ expect(startTimeMatches(process.pid, 1_700_000_000_000)).toBe(true)
+ return
+ }
+ // Pid 0 is the kernel scheduler — ps -p 0 / /proc/0 both fail, so
+ // getProcessStartedAtMs returns null and the check fails open.
+ expect(startTimeMatches(0, 1_700_000_000_000)).toBe(true)
+ })
+
+ it('returns true for matching start time within tolerance', () => {
+ if (process.platform === 'win32') {
+ // Skip on Windows — getProcessStartedAtMs always returns null.
+ return
+ }
+ const actual = getProcessStartedAtMs(process.pid)
+ if (actual === null) {
+ // Platform can't probe — skip
+ return
+ }
+ // Tolerance is ±1500ms. Shift expected by 500ms, still within tolerance.
+ expect(startTimeMatches(process.pid, actual + 500)).toBe(true)
+ })
+
+ it('returns false for start times outside tolerance', () => {
+ if (process.platform === 'win32') {
+ return
+ }
+ const actual = getProcessStartedAtMs(process.pid)
+ if (actual === null) {
+ return
+ }
+ // Shift expected by 10s — clearly outside the ±1500ms tolerance.
+ expect(startTimeMatches(process.pid, actual + 10_000)).toBe(false)
+ })
+})
+
+describe('killStaleDaemon pid identity guards', () => {
+ let dir: string
+ let socketPath: string
+ let tokenPath: string
+
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'daemon-health-pid-test-'))
+ socketPath = join(dir, 'daemon.sock')
+ tokenPath = join(dir, 'daemon.token')
+ })
+
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true })
+ })
+
+ it('does not SIGTERM when the saved startedAtMs mismatches the current process', async () => {
+ if (process.platform === 'win32') {
+ return
+ }
+
+ // Why: seed a pid file that claims the daemon is `process.pid` (us) but
+ // was started 1 hour ago. Our real start time is "now," so startTimeMatches
+ // returns false and isDaemonProcess rejects. killStaleDaemon must not call
+ // process.kill in that case.
+ const bogusStartedAtMs = Date.now() - 60 * 60 * 1000
+ writeFileSync(
+ getDaemonPidPath(dir),
+ serializeDaemonPidFile({ pid: process.pid, startedAtMs: bogusStartedAtMs }),
+ { mode: 0o600 }
+ )
+
+ // isDaemonProcess uses process.kill(pid, 0) as a liveness probe; that's
+ // expected and not a real kill. We only care that no actual termination
+ // signal is sent.
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true)
+ try {
+ await expect(killStaleDaemon(dir, socketPath, tokenPath)).resolves.toBe(false)
+ const terminationSignals = killSpy.mock.calls.filter(
+ ([, sig]) => sig === 'SIGTERM' || sig === 'SIGKILL'
+ )
+ expect(terminationSignals).toEqual([])
+ } finally {
+ killSpy.mockRestore()
+ }
+ })
+})
diff --git a/src/main/daemon/daemon-health.ts b/src/main/daemon/daemon-health.ts
index a0ab5025c..7d6126db9 100644
--- a/src/main/daemon/daemon-health.ts
+++ b/src/main/daemon/daemon-health.ts
@@ -1,3 +1,5 @@
+/* oxlint-disable max-lines -- Why: pid validation shares process-identity
+helpers with kill escalation so the SIGKILL safety checks stay co-located. */
import { execFileSync } from 'child_process'
import { existsSync, readFileSync, unlinkSync } from 'fs'
import { connect, type Socket } from 'net'
@@ -8,6 +10,12 @@ import { PROTOCOL_VERSION, type HelloMessage, type HelloResponse } from './types
const HEALTH_CHECK_TIMEOUT_MS = 3_000
const KILL_WAIT_MS = 3_000
const KILL_POLL_MS = 100
+const START_TIME_TOLERANCE_MS = 1_500
+
+type ParsedDaemonPid = {
+ pid: number
+ startedAtMs: number | null
+}
function canConnectSocket(socketPath: string): Promise {
return new Promise((resolve) => {
@@ -128,7 +136,94 @@ function commandLineMatchesDaemon(
)
}
-function isDaemonProcess(pid: number, socketPath: string, tokenPath: string): boolean {
+export function parseDaemonPidFile(contents: string): ParsedDaemonPid | null {
+ const trimmed = contents.trim()
+ try {
+ const parsed = JSON.parse(trimmed) as { pid?: unknown; startedAtMs?: unknown }
+ if (typeof parsed.pid === 'number' && Number.isFinite(parsed.pid)) {
+ return {
+ pid: parsed.pid,
+ startedAtMs:
+ typeof parsed.startedAtMs === 'number' && Number.isFinite(parsed.startedAtMs)
+ ? parsed.startedAtMs
+ : null
+ }
+ }
+ } catch {
+ // Legacy daemons wrote the pid file as a bare integer.
+ }
+
+ const pid = Number(trimmed)
+ return Number.isFinite(pid) ? { pid, startedAtMs: null } : null
+}
+
+function getLinuxProcessStartedAtMs(pid: number): number | null {
+ try {
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8')
+ const afterCommand = stat.slice(stat.lastIndexOf(')') + 2)
+ const fields = afterCommand.split(' ')
+ const startTicks = Number(fields[19])
+ const bootTimeLine = readFileSync('/proc/stat', 'utf8')
+ .split('\n')
+ .find((line) => line.startsWith('btime '))
+ const bootTimeSeconds = bootTimeLine ? Number(bootTimeLine.split(/\s+/)[1]) : Number.NaN
+ const ticksPerSecond = Number(
+ execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8', timeout: 1_000 }).trim()
+ )
+ if (
+ !Number.isFinite(startTicks) ||
+ !Number.isFinite(bootTimeSeconds) ||
+ !Number.isFinite(ticksPerSecond) ||
+ ticksPerSecond <= 0
+ ) {
+ return null
+ }
+ return bootTimeSeconds * 1000 + (startTicks / ticksPerSecond) * 1000
+ } catch {
+ return null
+ }
+}
+
+export function getProcessStartedAtMs(pid: number): number | null {
+ if (process.platform === 'linux') {
+ return getLinuxProcessStartedAtMs(pid)
+ }
+
+ if (process.platform === 'win32') {
+ return null
+ }
+
+ try {
+ const output = execFileSync('ps', ['-p', String(pid), '-o', 'lstart='], {
+ encoding: 'utf8',
+ timeout: 2_000
+ }).trim()
+ const startedAtMs = Date.parse(output)
+ return Number.isFinite(startedAtMs) ? startedAtMs : null
+ } catch {
+ return null
+ }
+}
+
+export function startTimeMatches(pid: number, expectedStartedAtMs: number | null): boolean {
+ if (expectedStartedAtMs === null) {
+ return true
+ }
+
+ const actualStartedAtMs = getProcessStartedAtMs(pid)
+ if (actualStartedAtMs === null) {
+ return true
+ }
+
+ return Math.abs(actualStartedAtMs - expectedStartedAtMs) <= START_TIME_TOLERANCE_MS
+}
+
+function isDaemonProcess(
+ pid: number,
+ socketPath: string,
+ tokenPath: string,
+ startedAtMs: number | null
+): boolean {
try {
process.kill(pid, 0)
} catch {
@@ -153,7 +248,10 @@ function isDaemonProcess(pid: number, socketPath: string, tokenPath: string): bo
// Why: image names are too broad after PID reuse. Match the daemon entry
// plus the exact socket/token args so we only kill the daemon for this
// userData protocol endpoint.
- return commandLineMatchesDaemon(output, socketPath, tokenPath)
+ return (
+ commandLineMatchesDaemon(output, socketPath, tokenPath) &&
+ startTimeMatches(pid, startedAtMs)
+ )
} catch {
return false
}
@@ -161,14 +259,19 @@ function isDaemonProcess(pid: number, socketPath: string, tokenPath: string): bo
try {
const cmdline = readFileSync(`/proc/${pid}/cmdline`, 'utf8')
- return commandLineMatchesDaemon(cmdline, socketPath, tokenPath)
+ return (
+ commandLineMatchesDaemon(cmdline, socketPath, tokenPath) && startTimeMatches(pid, startedAtMs)
+ )
} catch {
try {
const output = execFileSync('ps', ['-p', String(pid), '-o', 'command='], {
encoding: 'utf8',
timeout: 2_000
})
- return commandLineMatchesDaemon(output, socketPath, tokenPath)
+ return (
+ commandLineMatchesDaemon(output, socketPath, tokenPath) &&
+ startTimeMatches(pid, startedAtMs)
+ )
} catch {
return false
}
@@ -184,8 +287,9 @@ export async function killStaleDaemon(
const pidPath = getDaemonPidPath(runtimeDir, protocolVersion)
let killedDaemon = false
try {
- const pid = Number.parseInt(readFileSync(pidPath, 'utf8').trim(), 10)
- if (Number.isFinite(pid) && isDaemonProcess(pid, socketPath, tokenPath)) {
+ const parsedPid = parseDaemonPidFile(readFileSync(pidPath, 'utf8'))
+ if (parsedPid && isDaemonProcess(parsedPid.pid, socketPath, tokenPath, parsedPid.startedAtMs)) {
+ const { pid, startedAtMs } = parsedPid
process.kill(pid, 'SIGTERM')
const deadline = Date.now() + KILL_WAIT_MS
let exited = false
@@ -199,14 +303,24 @@ export async function killStaleDaemon(
await new Promise((resolve) => setTimeout(resolve, KILL_POLL_MS))
}
if (!exited) {
- try {
- process.kill(pid, 'SIGKILL')
+ // Why: re-check process identity before SIGKILL. The SIGTERM-then-wait
+ // window is long enough for the pid to be recycled if the original
+ // daemon died during the wait. Without this, we'd SIGKILL an unrelated
+ // process that happens to now own the same pid.
+ if (!isDaemonProcess(pid, socketPath, tokenPath, startedAtMs)) {
+ console.warn('[daemon] Skipping SIGKILL for stale daemon: reason=pid_recycled')
exited = true
- } catch {
- // Already dead
+ killedDaemon = true
+ } else {
+ try {
+ process.kill(pid, 'SIGKILL')
+ exited = true
+ } catch {
+ // Already dead
+ }
}
}
- killedDaemon = exited
+ killedDaemon = killedDaemon || exited
}
} catch {
// PID file missing or process already dead
diff --git a/src/main/daemon/daemon-init.test.ts b/src/main/daemon/daemon-init.test.ts
new file mode 100644
index 000000000..5b4cdfafc
--- /dev/null
+++ b/src/main/daemon/daemon-init.test.ts
@@ -0,0 +1,603 @@
+/* eslint-disable max-lines -- Why: this file covers the entire restart flow
+ of daemon-init — construction, the 7-step sequence from
+ docs/daemon-staleness-ux.md §Phase 1, and the concurrency coalescer. A
+ single describe block with shared mocks keeps setup in one place; splitting
+ across files would duplicate the vi.hoisted boundary mocks with no cleaner
+ ownership seam. */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { PROTOCOL_VERSION } from './types'
+
+// Why: the restart flow touches many boundary modules (electron app paths, fs
+// for dir creation, net for socket probe, DaemonClient over that socket, the
+// spawner's launcher, ipc/pty listener binders). We only care here about the
+// observable sequencing and identity invariants of runRestartDaemon, so every
+// non-daemon-init dependency is replaced by a minimal stub that records calls.
+const {
+ getPathMock,
+ probeSocketExistsMock,
+ netConnectMock,
+ healthCheckDaemonMock,
+ killStaleDaemonMock,
+ getProcessStartedAtMsMock,
+ daemonClientMock,
+ spawnerInstances,
+ adapterInstances,
+ setLocalPtyProviderMock,
+ unbindLocalProviderListenersMock,
+ rebindLocalProviderListenersMock
+} = vi.hoisted(() => {
+ const getPathMock = vi.fn(() => '/fake/userData')
+
+ const probeSocketExistsMock = vi.fn(() => false)
+ const netConnectMock = vi.fn(() => {
+ // Why: the real probeSocket() in daemon-init connects to the socket and
+ // resolves true on 'connect', false on 'error'. Our launcher never runs
+ // in these tests (healthCheckDaemon short-circuits), but probeSocket is
+ // also invoked by cleanupDaemonForProtocol — stub the socket object so
+ // the 'error' path fires synchronously and cleanupDaemonForProtocol's
+ // alive=false branch runs without side effects.
+ const handlers: Record void)[]> = { connect: [], error: [] }
+ return {
+ on(event: string, cb: () => void) {
+ handlers[event]?.push(cb)
+ if (event === 'error') {
+ // Fire after microtask so destroy()/resolve ordering matches real net
+ queueMicrotask(() => cb())
+ }
+ return this
+ },
+ destroy() {}
+ }
+ })
+
+ const healthCheckDaemonMock = vi.fn(async () => true)
+ const killStaleDaemonMock = vi.fn(async () => true)
+ const getProcessStartedAtMsMock = vi.fn(() => 1_000_000)
+
+ const daemonClientMock = vi.fn().mockImplementation(() => ({
+ ensureConnected: vi.fn(async () => {}),
+ request: vi.fn(async () => ({ sessions: [] })),
+ disconnect: vi.fn()
+ }))
+
+ // Why: every DaemonSpawner constructed under test pushes into this array so
+ // assertions can check "was the *same* spawner reused across restart?".
+ const spawnerInstances: MockSpawner[] = []
+ // Same for DaemonPtyAdapter. The test asserts the replacement adapter is a
+ // fresh instance whose respawn closure targets the *original* spawner.
+ const adapterInstances: MockAdapter[] = []
+
+ const setLocalPtyProviderMock = vi.fn()
+ const unbindLocalProviderListenersMock = vi.fn()
+ const rebindLocalProviderListenersMock = vi.fn()
+
+ return {
+ getPathMock,
+ probeSocketExistsMock,
+ netConnectMock,
+ healthCheckDaemonMock,
+ killStaleDaemonMock,
+ getProcessStartedAtMsMock,
+ daemonClientMock,
+ spawnerInstances,
+ adapterInstances,
+ setLocalPtyProviderMock,
+ unbindLocalProviderListenersMock,
+ rebindLocalProviderListenersMock
+ }
+})
+
+type MockSpawner = {
+ ensureRunning: ReturnType
+ resetHandle: ReturnType
+ shutdown: ReturnType
+ launcher: unknown
+}
+
+type MockAdapter = {
+ protocolVersion: number
+ options: {
+ socketPath: string
+ tokenPath: string
+ historyPath?: string
+ respawn?: () => Promise
+ protocolVersion?: number
+ }
+ getActiveSessionIds: ReturnType
+ fanoutSyntheticExits: ReturnType
+ listProcesses: ReturnType
+ listSessions: ReturnType
+ shutdown: ReturnType
+ dispose: ReturnType
+ disconnectOnly: ReturnType
+ onData: ReturnType
+ onExit: ReturnType
+ // Why: MockAdapter is fed through `new DaemonPtyRouter({ current, legacy })`
+ // during the "legacy preservation" test. The real router calls onData/onExit
+ // on each adapter; our stub returns a no-op unsubscribe so the router can
+ // subscribe without exploding.
+ callOrder: string[]
+}
+
+vi.mock('electron', () => ({
+ app: { getPath: getPathMock, getAppPath: () => '/fake/app' }
+}))
+
+vi.mock('fs', () => ({
+ mkdirSync: vi.fn(),
+ existsSync: (p: string) => probeSocketExistsMock() || p.includes('.pid'),
+ unlinkSync: vi.fn(),
+ writeFileSync: vi.fn()
+}))
+
+vi.mock('child_process', () => ({ fork: vi.fn() }))
+
+vi.mock('net', () => ({ connect: netConnectMock }))
+
+vi.mock('./daemon-health', () => ({
+ healthCheckDaemon: healthCheckDaemonMock,
+ killStaleDaemon: killStaleDaemonMock,
+ getProcessStartedAtMs: getProcessStartedAtMsMock
+}))
+
+vi.mock('./client', () => ({ DaemonClient: daemonClientMock }))
+
+vi.mock('./daemon-spawner', () => ({
+ DaemonSpawner: class MockDaemonSpawner {
+ readonly launcher: unknown
+ readonly ensureRunning: ReturnType
+ readonly resetHandle: ReturnType
+ readonly shutdown: ReturnType
+ private socketCounter: number
+ constructor(opts: { runtimeDir: string; launcher: unknown }) {
+ this.launcher = opts.launcher
+ this.socketCounter = 0
+ // Why: each ensureRunning bumps a counter into the returned socketPath
+ // so the test can verify the *replacement* adapter is constructed with
+ // info from the second ensureRunning call, not stale info from the first.
+ this.ensureRunning = vi.fn(async () => {
+ this.socketCounter += 1
+ return {
+ socketPath: `/fake/socket-${this.socketCounter}`,
+ tokenPath: `/fake/token-${this.socketCounter}`
+ }
+ })
+ this.resetHandle = vi.fn()
+ this.shutdown = vi.fn(async () => {})
+ spawnerInstances.push(this as unknown as MockSpawner)
+ }
+ },
+ getDaemonSocketPath: (_dir: string, version?: number) =>
+ `/fake/daemon/daemon-v${version ?? PROTOCOL_VERSION}.sock`,
+ getDaemonTokenPath: (_dir: string, version?: number) =>
+ `/fake/daemon/daemon-v${version ?? PROTOCOL_VERSION}.token`,
+ getDaemonPidPath: (_dir: string, version?: number) =>
+ `/fake/daemon/daemon-v${version ?? PROTOCOL_VERSION}.pid`,
+ serializeDaemonPidFile: (obj: unknown) => JSON.stringify(obj)
+}))
+
+vi.mock('./daemon-pty-adapter', () => ({
+ DaemonPtyAdapter: class MockDaemonPtyAdapter {
+ readonly protocolVersion: number
+ readonly options: MockAdapter['options']
+ readonly getActiveSessionIds: ReturnType
+ readonly fanoutSyntheticExits: ReturnType
+ readonly listProcesses: ReturnType
+ readonly listSessions: ReturnType
+ readonly shutdown: ReturnType
+ readonly dispose: ReturnType
+ readonly disconnectOnly: ReturnType
+ readonly onData: ReturnType
+ readonly onExit: ReturnType
+ readonly callOrder: string[]
+ constructor(opts: MockAdapter['options']) {
+ this.protocolVersion = opts.protocolVersion ?? PROTOCOL_VERSION
+ this.options = opts
+ this.callOrder = []
+ this.getActiveSessionIds = vi.fn(() => [] as string[])
+ this.fanoutSyntheticExits = vi.fn(() => {
+ this.callOrder.push('fanoutSyntheticExits')
+ })
+ this.listProcesses = vi.fn(async () => [])
+ this.listSessions = vi.fn(async () => [])
+ this.shutdown = vi.fn(async () => {})
+ this.dispose = vi.fn()
+ this.disconnectOnly = vi.fn(async () => {})
+ this.onData = vi.fn(() => () => {})
+ this.onExit = vi.fn(() => () => {})
+ adapterInstances.push(this as unknown as MockAdapter)
+ }
+ }
+}))
+
+vi.mock('../ipc/pty', () => ({
+ setLocalPtyProvider: setLocalPtyProviderMock,
+ unbindLocalProviderListeners: unbindLocalProviderListenersMock,
+ rebindLocalProviderListeners: rebindLocalProviderListenersMock
+}))
+
+async function importFresh() {
+ vi.resetModules()
+ spawnerInstances.length = 0
+ adapterInstances.length = 0
+ setLocalPtyProviderMock.mockClear()
+ unbindLocalProviderListenersMock.mockClear()
+ rebindLocalProviderListenersMock.mockClear()
+ healthCheckDaemonMock.mockClear()
+ killStaleDaemonMock.mockClear()
+ daemonClientMock.mockClear()
+ probeSocketExistsMock.mockClear()
+ // Why: importing daemon-init *after* resetModules means the module-level
+ // `spawner`/`adapter`/`restartInFlight` start fresh for every test, which is
+ // the only way to reliably exercise the "first-time init" path and the
+ // coalescer independently.
+ return import('./daemon-init')
+}
+
+describe('daemon-init: runRestartDaemon (7-step sequence)', () => {
+ beforeEach(() => {
+ probeSocketExistsMock.mockReturnValue(false)
+ })
+
+ afterEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('fans pty:exit for every active session *before* unbinding listeners, and killedCount is captured pre-fanout', async () => {
+ const mod = await importFresh()
+ await mod.initDaemonPtyProvider()
+
+ // Why: seed the original adapter with active sessions so
+ // fanoutSyntheticExits has something to do. The real adapter snapshots
+ // activeSessionIds then clears it; the mock emulates that so a regression
+ // that measures killedCount *after* fanout (when the set is empty) would
+ // surface as `killedCount === 0` here.
+ const originalAdapter = adapterInstances[0]
+ let activeIds = ['sess-a', 'sess-b', 'sess-c']
+ originalAdapter.getActiveSessionIds.mockImplementation(() => [...activeIds])
+
+ const order: string[] = []
+ originalAdapter.fanoutSyntheticExits.mockImplementation(() => {
+ order.push('fanout')
+ activeIds = []
+ })
+ unbindLocalProviderListenersMock.mockImplementation(() => {
+ order.push('unbind')
+ })
+
+ const result = await mod.restartDaemon()
+
+ // killedCount must be 3 — proves the count was taken *before* the fanout
+ // cleared the set. A bug that swapped these two lines in source would
+ // report 0 here.
+ expect(result.killedCount).toBe(3)
+ expect(originalAdapter.fanoutSyntheticExits).toHaveBeenCalledWith(-1)
+ // The load-bearing ordering invariant: the synthetic exits must reach
+ // the renderer *before* listeners are torn down. Step 1 before Step 2.
+ expect(order).toEqual(['fanout', 'unbind'])
+ })
+
+ it('reuses the existing DaemonSpawner across restart (resetHandle + ensureRunning on same instance)', async () => {
+ const mod = await importFresh()
+ await mod.initDaemonPtyProvider()
+
+ expect(spawnerInstances).toHaveLength(1)
+ const originalSpawner = spawnerInstances[0]
+ expect(originalSpawner.ensureRunning).toHaveBeenCalledTimes(1)
+
+ await mod.restartDaemon()
+
+ // No second DaemonSpawner was constructed — restart uses the one from init.
+ expect(spawnerInstances).toHaveLength(1)
+ expect(originalSpawner.resetHandle).toHaveBeenCalledTimes(1)
+ expect(originalSpawner.ensureRunning).toHaveBeenCalledTimes(2)
+ })
+
+ it('builds a fresh adapter whose respawn callback closes over the same spawner', async () => {
+ const mod = await importFresh()
+ await mod.initDaemonPtyProvider()
+
+ const originalSpawner = spawnerInstances[0]
+ const originalAdapter = adapterInstances[0]
+
+ await mod.restartDaemon()
+
+ // A new adapter was constructed against the replacement daemon's socket.
+ expect(adapterInstances).toHaveLength(2)
+ const replacementAdapter = adapterInstances[1]
+ expect(replacementAdapter).not.toBe(originalAdapter)
+ expect(replacementAdapter.options.socketPath).toBe('/fake/socket-2')
+ expect(replacementAdapter.options.tokenPath).toBe('/fake/token-2')
+
+ // Invoking the replacement adapter's respawn closure must drive the
+ // *same* original spawner (matches the crash-respawn closure baked into
+ // the first adapter — see daemon-init.ts step 5 comment).
+ originalSpawner.resetHandle.mockClear()
+ originalSpawner.ensureRunning.mockClear()
+ await replacementAdapter.options.respawn?.()
+ expect(originalSpawner.resetHandle).toHaveBeenCalledTimes(1)
+ expect(originalSpawner.ensureRunning).toHaveBeenCalledTimes(1)
+ // Still only one spawner in the whole test — nobody new was constructed.
+ expect(spawnerInstances).toHaveLength(1)
+ })
+
+ it('swaps the module-level adapter and re-binds listeners after the new provider is installed', async () => {
+ const mod = await importFresh()
+ await mod.initDaemonPtyProvider()
+
+ // initDaemonPtyProvider calls setLocalPtyProvider once with the original.
+ expect(setLocalPtyProviderMock).toHaveBeenCalledTimes(1)
+ const originalProvider = setLocalPtyProviderMock.mock.calls[0][0]
+ expect(originalProvider).toBe(adapterInstances[0])
+ expect(mod.getDaemonProvider()).toBe(originalProvider)
+
+ await mod.restartDaemon()
+
+ const replacementAdapter = adapterInstances[1]
+ // Second call: swap to the replacement provider (Step 6).
+ expect(setLocalPtyProviderMock).toHaveBeenCalledTimes(2)
+ expect(setLocalPtyProviderMock.mock.calls[1][0]).toBe(replacementAdapter)
+ expect(mod.getDaemonProvider()).toBe(replacementAdapter)
+
+ // Step 7: rebind must run *after* Step 6. The last rebind call index
+ // must be greater than the last setLocalPtyProvider call index.
+ const rebindOrder = rebindLocalProviderListenersMock.mock.invocationCallOrder.at(-1) ?? -1
+ const swapOrder = setLocalPtyProviderMock.mock.invocationCallOrder.at(-1) ?? -1
+ expect(rebindOrder).toBeGreaterThan(swapOrder)
+ })
+
+ it('preserves legacy adapter instances by identity, drains outgoing router via disposeRouterOnly, and re-discovers legacy sessions on the new router', async () => {
+ const mod = await importFresh()
+
+ // Why: initDaemonPtyProvider only constructs legacy adapters when
+ // probeSocket returns true for a legacy socket path. The real flow runs
+ // createLegacyDaemonAdapters which calls probeSocket per previous version.
+ // Simplest seam for this test: directly construct a router with a legacy
+ // adapter and install it via replaceDaemonProvider, bypassing
+ // createLegacyDaemonAdapters' socket-probe machinery.
+ await mod.initDaemonPtyProvider()
+
+ const { DaemonPtyRouter } = await import('./daemon-pty-router')
+ const { DaemonPtyAdapter } = await import('./daemon-pty-adapter')
+ const currentAtConstruction = adapterInstances[0]
+ // Construct a legacy adapter using the mocked constructor (pushes into
+ // adapterInstances) — index 1.
+ const legacyAdapter = new DaemonPtyAdapter({
+ socketPath: '/fake/legacy.sock',
+ tokenPath: '/fake/legacy.token',
+ protocolVersion: 3
+ })
+ const routerWithLegacy = new DaemonPtyRouter({
+ current: currentAtConstruction as unknown as InstanceType,
+ legacy: [legacyAdapter as unknown as InstanceType]
+ })
+ // Why: spy on the *outgoing* router's disposeRouterOnly so we can prove it
+ // was invoked (not just that legacy adapters survived — a no-op
+ // disposeRouterOnly would leak listeners but still leave adapters alive).
+ const disposeRouterOnlySpy = vi.spyOn(routerWithLegacy, 'disposeRouterOnly')
+ const oldRouterDispose = vi.spyOn(routerWithLegacy, 'dispose')
+ mod.replaceDaemonProvider(routerWithLegacy)
+
+ await mod.restartDaemon()
+
+ const provider = mod.getDaemonProvider()
+ expect(provider).toBeInstanceOf(DaemonPtyRouter)
+ const newRouter = provider as InstanceType
+ expect(newRouter).not.toBe(routerWithLegacy)
+
+ // Legacy adapter instance is preserved by identity — not reconstructed,
+ // not defensively copied, not disposed.
+ const legacies = newRouter.getLegacyAdapters()
+ expect(legacies).toHaveLength(1)
+ expect(legacies[0]).toBe(legacyAdapter)
+ expect(legacyAdapter.dispose).not.toHaveBeenCalled()
+ // The outgoing router was drained via disposeRouterOnly (router-only
+ // teardown), so legacy adapters' underlying connections are untouched.
+ expect(legacyAdapter.disconnectOnly).not.toHaveBeenCalled()
+ // The outgoing router's subscriptions were drained but the adapters
+ // behind it were NOT disposed — that's the whole point of disposeRouterOnly.
+ expect(disposeRouterOnlySpy).toHaveBeenCalledTimes(1)
+ expect(oldRouterDispose).not.toHaveBeenCalled()
+
+ // The replacement router must re-run discovery so spawns targeting a
+ // surviving legacy sessionId still route to the legacy adapter.
+ expect(legacyAdapter.listProcesses).toHaveBeenCalled()
+ })
+
+ it('restart path with no legacy adapters yields a bare DaemonPtyAdapter (not wrapped in a router)', async () => {
+ const mod = await importFresh()
+ await mod.initDaemonPtyProvider()
+
+ // initDaemonPtyProvider sets up a bare adapter when createLegacyDaemonAdapters
+ // finds nothing — confirm that shape persists across restart.
+ const { DaemonPtyAdapter } = await import('./daemon-pty-adapter')
+ const { DaemonPtyRouter } = await import('./daemon-pty-router')
+ expect(mod.getDaemonProvider()).toBeInstanceOf(DaemonPtyAdapter)
+
+ await mod.restartDaemon()
+
+ expect(mod.getDaemonProvider()).toBeInstanceOf(DaemonPtyAdapter)
+ expect(mod.getDaemonProvider()).not.toBeInstanceOf(DaemonPtyRouter)
+ })
+
+ it('orders Step 3 (cleanup) → Step 4 (resetHandle + ensureRunning) → Step 5 (new adapter) → Step 6 (replaceProvider) → Step 7 (rebind)', async () => {
+ const mod = await importFresh()
+ await mod.initDaemonPtyProvider()
+
+ const originalSpawner = spawnerInstances[0]
+ const originalAdapter = adapterInstances[0]
+
+ // Build an ordered trace by stamping each step as it fires. Cleanup is
+ // the tricky one — it's the `cleanupDaemonForProtocol` call, observable
+ // via the probeSocket→healthCheckDaemon→killStaleDaemon branch. We use
+ // healthCheckDaemon as the cleanup-start marker because it's the first
+ // call inside createOutOfProcessLauncher → and also fires inside
+ // cleanupDaemonForProtocol's alive branch… actually in the default
+ // (probeSocket=false) path cleanup is a no-op beyond pid-unlink. The
+ // load-bearing observable is `resetHandle` — it fires *after* cleanup
+ // returns. So we instrument the spawner instead.
+ const trace: string[] = []
+ originalAdapter.fanoutSyntheticExits.mockImplementation(() => trace.push('fanout'))
+ unbindLocalProviderListenersMock.mockImplementation(() => trace.push('unbind'))
+ originalSpawner.resetHandle.mockImplementation(() => trace.push('resetHandle'))
+ const originalEnsureRunning = originalSpawner.ensureRunning
+ originalSpawner.ensureRunning.mockImplementation(async () => {
+ trace.push('ensureRunning')
+ return {
+ socketPath: '/fake/socket-2',
+ tokenPath: '/fake/token-2'
+ }
+ })
+ setLocalPtyProviderMock.mockImplementation(() => trace.push('replaceProvider'))
+ rebindLocalProviderListenersMock.mockImplementation(() => trace.push('rebind'))
+
+ await mod.restartDaemon()
+ void originalEnsureRunning // keep ref so tslint doesn't complain
+
+ // The full 7-step sequence in order. Step 3 (cleanupDaemonForProtocol)
+ // has no unique observable in the dead-socket branch, so it's implicitly
+ // ordered by the fact that resetHandle runs after unbind; if cleanup
+ // ever moved *after* resetHandle, we'd see `resetHandle` precede its
+ // expected position.
+ expect(trace).toEqual([
+ 'fanout',
+ 'unbind',
+ 'resetHandle',
+ 'ensureRunning',
+ 'replaceProvider',
+ 'rebind'
+ ])
+
+ // A fresh adapter must have been constructed *between* ensureRunning
+ // and replaceProvider (Step 5 before Step 6). adapterInstances[1] is
+ // the replacement — its socketPath comes from the Step-4 ensureRunning
+ // result, so its existence proves the ordering.
+ expect(adapterInstances).toHaveLength(2)
+ expect(adapterInstances[1].options.socketPath).toBe('/fake/socket-2')
+ })
+
+ it('exercises the alive-daemon cleanup path: issues shutdown RPC via DaemonClient before spawning a replacement', async () => {
+ // Why: the default mock has probeSocket returning false, so Step 3's
+ // DaemonClient-based shutdown path is normally skipped. This test flips
+ // the socket to "alive" so cleanupDaemonForProtocol takes the
+ // client.ensureConnected → listSessions → shutdown RPC branch. Without
+ // this, the design doc's Risks section ("verify under both 'shutdown
+ // RPC succeeded' and 'fell back to killStaleDaemon' paths") is uncovered.
+
+ const requestMock = vi.fn(async (method: string) => {
+ if (method === 'listSessions') {
+ return { sessions: [{ sessionId: 'live-1', isAlive: true }] }
+ }
+ // `shutdown` RPC — daemon exits before reply lands; return undefined.
+ return undefined
+ })
+ const ensureConnectedMock = vi.fn(async () => {})
+ const disconnectMock = vi.fn()
+ // Why: DaemonClient is invoked via `new DaemonClient(...)`, so the mock
+ // factory must return a constructor-compatible function. Capture the
+ // existing impl so later tests aren't affected.
+ daemonClientMock.mockImplementationOnce(function MockDaemonClientForShutdown() {
+ return {
+ ensureConnected: ensureConnectedMock,
+ request: requestMock,
+ disconnect: disconnectMock
+ }
+ })
+
+ const mod = await importFresh()
+ await mod.initDaemonPtyProvider()
+
+ // Make probeSocket return true for the current-version path by toggling
+ // both the fs.existsSync proxy AND net.connect resolving "alive".
+ probeSocketExistsMock.mockReturnValue(true)
+ netConnectMock.mockImplementationOnce(() => {
+ const handlers: Record void)[]> = { connect: [], error: [] }
+ return {
+ on(event: string, cb: () => void) {
+ handlers[event]?.push(cb)
+ if (event === 'connect') {
+ queueMicrotask(() => cb())
+ }
+ return this
+ },
+ destroy() {}
+ }
+ })
+
+ await mod.restartDaemon()
+
+ // The shutdown RPC must have been issued with killSessions=true.
+ expect(ensureConnectedMock).toHaveBeenCalled()
+ expect(requestMock).toHaveBeenCalledWith('shutdown', { killSessions: true })
+ // The fallback killStaleDaemon must NOT fire when the RPC path worked.
+ expect(killStaleDaemonMock).not.toHaveBeenCalled()
+ })
+
+ it('coalesces concurrent restartDaemon() calls so the 7-step sequence runs exactly once', async () => {
+ const mod = await importFresh()
+ await mod.initDaemonPtyProvider()
+
+ const originalSpawner = spawnerInstances[0]
+
+ // Why: without an explicit gate, `Promise.all([restartDaemon(),
+ // restartDaemon()])` evaluates arguments left-to-right *synchronously* —
+ // the first call's promise could resolve before the second invocation
+ // begins if all internal awaits resolved in a single microtask, which
+ // would leave the coalescer untested. The deferred gate holds the first
+ // restart inside `ensureRunning` until we release it, guaranteeing the
+ // second call enters while the first is genuinely mid-flight.
+ let releaseEnsureRunning: (() => void) | undefined
+ const ensureRunningBarrier = new Promise((resolve) => {
+ releaseEnsureRunning = resolve
+ })
+ originalSpawner.ensureRunning.mockImplementationOnce(async () => {
+ await ensureRunningBarrier
+ return { socketPath: '/fake/socket-2', tokenPath: '/fake/token-2' }
+ })
+
+ const call1 = mod.restartDaemon()
+ // Yield microtasks so call1 progresses into runRestartDaemon and is
+ // definitely blocked on the barrier.
+ await Promise.resolve()
+ await Promise.resolve()
+ const call2 = mod.restartDaemon()
+
+ // Why: `async function restartDaemon` wraps each return in a fresh
+ // Promise, so `call1 === call2` does *not* hold even when the coalescer
+ // is working. The load-bearing proof is behavioral: while call1 is
+ // blocked on the ensureRunning barrier, call2 must NOT fork a parallel
+ // run of the 7-step sequence. If the coalescer fails, a second
+ // `runRestartDaemon` starts, which means a second `resetHandle` fires
+ // before we release the barrier. Check that counter at this exact
+ // moment — a non-coalescing implementation would already be at 2.
+ expect(originalSpawner.resetHandle).toHaveBeenCalledTimes(1)
+ expect(adapterInstances).toHaveLength(1)
+
+ releaseEnsureRunning?.()
+ const [r1, r2] = await Promise.all([call1, call2])
+ // Both resolved values must be structurally identical (same result
+ // object bubbled up through the shared runRestartDaemon promise).
+ expect(r1).toEqual(r2)
+
+ // resetHandle fires once per restart; ensureRunning fires once during
+ // init + once during restart. A second, un-coalesced restart would push
+ // these counters to 2 and 3 respectively.
+ expect(originalSpawner.resetHandle).toHaveBeenCalledTimes(1)
+ expect(originalSpawner.ensureRunning).toHaveBeenCalledTimes(2)
+ expect(adapterInstances).toHaveLength(2)
+
+ // After the in-flight promise settles, a fresh restart is allowed to run
+ // — proves `.finally(() => restartInFlight = null)` actually cleared the
+ // slot. A stale restartInFlight would skip the work entirely.
+ await mod.restartDaemon()
+ expect(originalSpawner.resetHandle).toHaveBeenCalledTimes(2)
+ expect(adapterInstances).toHaveLength(3)
+ })
+
+ it('throws when restartDaemon is called before initDaemonPtyProvider', async () => {
+ const mod = await importFresh()
+ await expect(mod.restartDaemon()).rejects.toThrow(
+ 'restartDaemon called before initDaemonPtyProvider'
+ )
+ })
+})
diff --git a/src/main/daemon/daemon-init.ts b/src/main/daemon/daemon-init.ts
index 7a0cad3ef..d1545a81d 100644
--- a/src/main/daemon/daemon-init.ts
+++ b/src/main/daemon/daemon-init.ts
@@ -1,3 +1,11 @@
+/* eslint-disable max-lines -- Why: this module owns the complete daemon
+lifecycle for the Electron main process — init, out-of-process launch,
+current+legacy adapter wiring, restart orchestration (the 7-step sequence
+from docs/daemon-staleness-ux.md §Phase 1), and teardown on app quit. Splitting
+it would scatter the "swap the running provider atomically" invariant across
+files with no cleaner ownership seam: restart, replaceDaemonProvider, and the
+module-level spawner/adapter singletons must stay co-located so a future
+change cannot leave them drifting out of sync. */
import { join } from 'path'
import { app } from 'electron'
import { mkdirSync, existsSync, unlinkSync, writeFileSync } from 'fs'
@@ -8,6 +16,7 @@ import {
getDaemonPidPath,
getDaemonSocketPath,
getDaemonTokenPath,
+ serializeDaemonPidFile,
type DaemonLauncher
} from './daemon-spawner'
import { DaemonPtyAdapter } from './daemon-pty-adapter'
@@ -18,11 +27,20 @@ import {
PROTOCOL_VERSION,
type ListSessionsResult
} from './types'
-import { healthCheckDaemon, killStaleDaemon } from './daemon-health'
-import { setLocalPtyProvider } from '../ipc/pty'
+import { getProcessStartedAtMs, healthCheckDaemon, killStaleDaemon } from './daemon-health'
+import {
+ setLocalPtyProvider,
+ unbindLocalProviderListeners,
+ rebindLocalProviderListeners
+} from '../ipc/pty'
let spawner: DaemonSpawner | null = null
let adapter: DaemonPtyRouter | DaemonPtyAdapter | null = null
+// Why: coalesce concurrent restartDaemon() calls so two clicks (or a UI
+// click racing an internal caller) can't both enter the 7-step sequence —
+// the second entry would read the already-disposed current adapter and
+// race cleanupDaemonForProtocol against a half-spawned replacement.
+let restartInFlight: Promise | null = null
function getRuntimeDir(): string {
const dir = join(app.getPath('userData'), 'daemon')
@@ -130,7 +148,18 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher {
if (msg && typeof msg === 'object' && (msg as { type?: string }).type === 'ready') {
clearTimeout(timer)
if (child.pid) {
- writeFileSync(getDaemonPidPath(runtimeDir), String(child.pid), { mode: 0o600 })
+ // Why: JSON pid file carries pid + process start time so later
+ // killStaleDaemon() can verify the pid still belongs to the daemon
+ // we forked before SIGTERMing it. Prevents pid-recycling hazard
+ // where the OS hands the daemon's old pid to an unrelated process.
+ writeFileSync(
+ getDaemonPidPath(runtimeDir),
+ serializeDaemonPidFile({
+ pid: child.pid,
+ startedAtMs: getProcessStartedAtMs(child.pid)
+ }),
+ { mode: 0o600 }
+ )
}
// Why: disconnect IPC channel and unref so Electron can exit
// without waiting for the daemon. The daemon keeps running.
@@ -208,6 +237,121 @@ export async function initDaemonPtyProvider(): Promise {
setLocalPtyProvider(routedAdapter)
}
+// Why: the Manage Sessions IPC handlers need read access to the current
+// adapter/router to list sessions, kill them, etc. Exposed as a narrow getter
+// rather than exporting the module-level variable to keep the "swap on
+// restart" invariant in one place (replaceDaemonProvider).
+export function getDaemonProvider(): DaemonPtyRouter | DaemonPtyAdapter | null {
+ return adapter
+}
+
+// Why: the "Restart daemon" flow rebuilds the current-protocol adapter and
+// must update both the module-level `adapter` singleton here and the
+// `localProvider` reference inside ipc/pty.ts. Without this helper they could
+// drift — app-quit would dispose a stale adapter reference.
+export function replaceDaemonProvider(newAdapter: DaemonPtyAdapter | DaemonPtyRouter): void {
+ adapter = newAdapter
+ setLocalPtyProvider(newAdapter)
+}
+
+export type RestartDaemonResult = {
+ killedCount: number
+}
+
+// Why: the 7-step sequence from docs/daemon-staleness-ux.md §Phase 1 restart.
+// Current-protocol only — legacy adapters are preserved and route to their
+// original daemons with no respawn path. See the design doc for rationale on
+// each step, notably why synthetic exits must fan out *before* the listener
+// unsubscribe.
+export async function restartDaemon(): Promise {
+ if (restartInFlight) {
+ return restartInFlight
+ }
+ restartInFlight = runRestartDaemon().finally(() => {
+ restartInFlight = null
+ })
+ return restartInFlight
+}
+
+async function runRestartDaemon(): Promise {
+ const currentSpawner = spawner
+ const currentAdapter = adapter
+ if (!currentSpawner || !currentAdapter) {
+ throw new Error('restartDaemon called before initDaemonPtyProvider')
+ }
+
+ const runtimeDir = getRuntimeDir()
+ const currentOnly =
+ currentAdapter instanceof DaemonPtyRouter ? currentAdapter.getCurrentAdapter() : currentAdapter
+ const legacyAdapters =
+ currentAdapter instanceof DaemonPtyRouter ? [...currentAdapter.getLegacyAdapters()] : []
+
+ // Step 1: synthesize pty:exit for every active session on the current
+ // adapter BEFORE any teardown. The daemon's kill-all-and-shutdown path
+ // explicitly does not fan onExit to clients (session.ts:246-252), so
+ // without this the renderer would never see exits and would black-hole
+ // writes against the disposed adapter.
+ const killedCount = currentOnly.getActiveSessionIds().length
+ currentOnly.fanoutSyntheticExits(-1)
+
+ // Step 2: detach renderer listeners from the current adapter. Must happen
+ // AFTER step 1 so the synthesized exits actually reach the renderer, and
+ // BEFORE step 6 so the new provider isn't bound with stale listeners.
+ unbindLocalProviderListeners()
+
+ // Step 3: kill the current-protocol daemon process (shutdown RPC → fallback
+ // killStaleDaemon → socket/pid unlink). Legacy adapters untouched.
+ await cleanupDaemonForProtocol(runtimeDir, PROTOCOL_VERSION)
+
+ // Step 4: reuse the existing spawner so the respawn closure baked into
+ // long-lived adapters stays valid. Do NOT construct a new DaemonSpawner.
+ currentSpawner.resetHandle()
+ const info = await currentSpawner.ensureRunning()
+
+ // Step 5: build a fresh current adapter against the respawned daemon. Its
+ // respawn callback closes over the same spawner instance (identical to the
+ // crash-respawn closure in initDaemonPtyProvider).
+ const newCurrent = new DaemonPtyAdapter({
+ socketPath: info.socketPath,
+ tokenPath: info.tokenPath,
+ historyPath: getHistoryDir(),
+ respawn: async () => {
+ console.warn('[daemon] Daemon process died — respawning')
+ currentSpawner.resetHandle()
+ await currentSpawner.ensureRunning()
+ }
+ })
+
+ // Re-wrap in router if there were legacy adapters at startup; otherwise
+ // point straight at the new adapter. Legacy instances are preserved by
+ // reference — they still route to the same pre-upgrade daemons.
+ const newProvider =
+ legacyAdapters.length > 0
+ ? new DaemonPtyRouter({ current: newCurrent, legacy: legacyAdapters })
+ : newCurrent
+ if (newProvider instanceof DaemonPtyRouter) {
+ await newProvider.discoverLegacySessions()
+ }
+
+ // Why: drain the outgoing router's subscriptions from the shared legacy
+ // adapters before installing the new router (which subscribes fresh). Must
+ // run *after* the new provider exists so no adapter event is unhandled in
+ // the narrow window, and *before* replaceDaemonProvider so the swap is
+ // atomic from the renderer's perspective. Plain dispose() would also tear
+ // down the legacy adapters themselves — use the router-only variant.
+ if (currentAdapter instanceof DaemonPtyRouter) {
+ currentAdapter.disposeRouterOnly()
+ }
+
+ // Step 6: swap module state (adapter + localProvider) atomically.
+ replaceDaemonProvider(newProvider)
+
+ // Step 7: rebind renderer listeners against the new provider.
+ rebindLocalProviderListeners()
+
+ return { killedCount }
+}
+
// Why: disconnect from the daemon without killing it. The daemon runs as a
// separate process and survives app quit — sessions stay alive for warm
// reattach on next launch. Leave history sessions marked "unclean" here so a
@@ -239,7 +383,7 @@ export type OrphanedDaemonCleanupResult = {
killedCount: number
}
-async function cleanupDaemonForProtocol(
+export async function cleanupDaemonForProtocol(
runtimeDir: string,
protocolVersion: number
): Promise {
diff --git a/src/main/daemon/daemon-main.test.ts b/src/main/daemon/daemon-main.test.ts
index 69613650e..c462fdcfb 100644
--- a/src/main/daemon/daemon-main.test.ts
+++ b/src/main/daemon/daemon-main.test.ts
@@ -101,6 +101,7 @@ function createMockSubprocess() {
onData(_cb: (data: string) => void) {},
onExit(cb: (code: number) => void) {
onExitCb = cb
- }
+ },
+ dispose: vi.fn()
}
}
diff --git a/src/main/daemon/daemon-pty-adapter.test.ts b/src/main/daemon/daemon-pty-adapter.test.ts
index 610937387..af8c7edac 100644
--- a/src/main/daemon/daemon-pty-adapter.test.ts
+++ b/src/main/daemon/daemon-pty-adapter.test.ts
@@ -31,6 +31,7 @@ function createMockSubprocess(): SubprocessHandle & {
onExit(cb) {
onExitCb = cb
},
+ dispose: vi.fn(),
_simulateData(data: string) {
onDataCb?.(data)
},
@@ -728,4 +729,70 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => {
respawnAdapter.dispose()
})
})
+
+ // Why: the restart flow (docs/daemon-staleness-ux.md §Phase 1 step 1) relies
+ // on these two primitives to fan synthetic pty:exit out to every attached
+ // session *before* tearing the adapter down. The design doc calls out
+ // session.ts:246-252 as the reason — the daemon's kill-all-and-shutdown
+ // explicitly does NOT fan exits back through onExit. Without the fanout the
+ // renderer would black-hole writes against a disposed adapter.
+ describe('fanoutSyntheticExits / getActiveSessionIds (restart primitives)', () => {
+ it('reports every live spawn in getActiveSessionIds', async () => {
+ const { id: id1 } = await adapter.spawn({ cols: 80, rows: 24 })
+ const { id: id2 } = await adapter.spawn({ cols: 80, rows: 24 })
+ const active = adapter.getActiveSessionIds()
+ expect(active).toContain(id1)
+ expect(active).toContain(id2)
+ expect(active).toHaveLength(2)
+ })
+
+ it('emits a synthetic exit for every active id with the supplied code', () => {
+ const exits: { id: string; code: number }[] = []
+ adapter.onExit((payload) => exits.push(payload))
+
+ const ids = ['sess-a', 'sess-b', 'sess-c']
+ const internals = adapter as unknown as { activeSessionIds: Set }
+ for (const id of ids) {
+ internals.activeSessionIds.add(id)
+ }
+
+ adapter.fanoutSyntheticExits(-1)
+
+ expect(exits).toHaveLength(3)
+ expect(exits.map((e) => e.id).sort()).toEqual([...ids].sort())
+ for (const { code } of exits) {
+ expect(code).toBe(-1)
+ }
+ })
+
+ it('clears activeSessionIds after fanout so a second call is a no-op', () => {
+ const exits: { id: string; code: number }[] = []
+ adapter.onExit((payload) => exits.push(payload))
+
+ const internals = adapter as unknown as { activeSessionIds: Set }
+ internals.activeSessionIds.add('sess-a')
+
+ adapter.fanoutSyntheticExits(-1)
+ expect(exits).toHaveLength(1)
+ expect(adapter.getActiveSessionIds()).toEqual([])
+
+ adapter.fanoutSyntheticExits(-1)
+ expect(exits).toHaveLength(1)
+ })
+
+ it('propagates to every registered exit listener in order', () => {
+ const aExits: { id: string; code: number }[] = []
+ const bExits: { id: string; code: number }[] = []
+ adapter.onExit((payload) => aExits.push(payload))
+ adapter.onExit((payload) => bExits.push(payload))
+
+ const internals = adapter as unknown as { activeSessionIds: Set }
+ internals.activeSessionIds.add('sess-a')
+
+ adapter.fanoutSyntheticExits(-1)
+
+ expect(aExits).toEqual([{ id: 'sess-a', code: -1 }])
+ expect(bExits).toEqual([{ id: 'sess-a', code: -1 }])
+ })
+ })
})
diff --git a/src/main/daemon/daemon-pty-adapter.ts b/src/main/daemon/daemon-pty-adapter.ts
index 1e4273ae5..349ca4d51 100644
--- a/src/main/daemon/daemon-pty-adapter.ts
+++ b/src/main/daemon/daemon-pty-adapter.ts
@@ -13,7 +13,8 @@ import {
type CreateOrAttachResult,
type DaemonEvent,
type GetSnapshotResult,
- type ListSessionsResult
+ type ListSessionsResult,
+ type SessionInfo
} from './types'
import type { IPtyProvider, PtySpawnOptions, PtySpawnResult } from '../providers/types'
@@ -39,6 +40,7 @@ export class TerminalKilledError extends Error {
}
export class DaemonPtyAdapter implements IPtyProvider {
+ readonly protocolVersion: number
private client: DaemonClient
private historyManager: HistoryManager | null
private historyReader: HistoryReader | null
@@ -71,6 +73,7 @@ export class DaemonPtyAdapter implements IPtyProvider {
private static CHECKPOINT_INTERVAL_MS = 5_000
constructor(opts: DaemonPtyAdapterOptions) {
+ this.protocolVersion = opts.protocolVersion ?? PROTOCOL_VERSION
this.client = new DaemonClient({
socketPath: opts.socketPath,
tokenPath: opts.tokenPath,
@@ -79,7 +82,7 @@ export class DaemonPtyAdapter implements IPtyProvider {
this.historyManager = opts.historyPath ? new HistoryManager(opts.historyPath) : null
this.historyReader = opts.historyPath ? new HistoryReader(opts.historyPath) : null
this.respawnFn = opts.respawn ?? null
- this.supportsCheckpoints = (opts.protocolVersion ?? PROTOCOL_VERSION) >= 4
+ this.supportsCheckpoints = this.protocolVersion >= 4
}
getHistoryManager(): HistoryManager | null {
@@ -120,6 +123,7 @@ export class DaemonPtyAdapter implements IPtyProvider {
// the override makes the daemon path behave the same as the in-process
// LocalPtyProvider.
shellOverride: opts.shellOverride,
+ terminalWindowsPowerShellImplementation: opts.terminalWindowsPowerShellImplementation,
shellReadySupported: opts.command ? supportsPtyStartupBarrier(opts.env ?? {}) : false
})
@@ -361,6 +365,42 @@ export class DaemonPtyAdapter implements IPtyProvider {
}))
}
+ // Why: the Manage Sessions panel needs the full SessionInfo (pid, state,
+ // createdAt) per session for display; listProcesses drops that detail for
+ // the IPtyProvider contract. Keep both in parallel rather than widening
+ // the provider surface.
+ async listSessions(): Promise {
+ await this.ensureConnected()
+ const result = await this.client.request('listSessions', undefined)
+ return result.sessions.filter((s) => s.isAlive)
+ }
+
+ getActiveSessionIds(): string[] {
+ return [...this.activeSessionIds]
+ }
+
+ // Why: used by the "Restart daemon" handler to synthesize pty:exit for every
+ // live session *before* tearing down the adapter. The daemon's own
+ // kill-all-and-shutdown path explicitly suppresses onExit fanout
+ // (session.ts:246-252), so without this the renderer panes would black-hole
+ // writes to a disposed adapter forever. Reuses the existing exitListeners
+ // path so downstream cleanup (clearProviderPtyState, markClaudePtyExited,
+ // renderer pty:exit) runs exactly as it does on natural exit.
+ fanoutSyntheticExits(code: number): void {
+ const ids = [...this.activeSessionIds]
+ this.activeSessionIds.clear()
+ for (const id of ids) {
+ // Why: listener throws are intentionally *not* caught — matches the
+ // natural onExit fanout in setupEventRouting, so synthetic exits don't
+ // diverge in error semantics from real ones. A throwing listener is a
+ // bug that should surface loudly, not be silently swallowed.
+ // oxlint-disable-next-line unicorn/no-useless-spread -- copy-safe: listeners may unsubscribe during iteration
+ for (const listener of [...this.exitListeners]) {
+ listener({ id, code })
+ }
+ }
+ }
+
async getDefaultShell(): Promise {
if (process.platform === 'win32') {
return process.env.COMSPEC || 'powershell.exe'
diff --git a/src/main/daemon/daemon-pty-provider.test.ts b/src/main/daemon/daemon-pty-provider.test.ts
index a8da8cead..a773a0720 100644
--- a/src/main/daemon/daemon-pty-provider.test.ts
+++ b/src/main/daemon/daemon-pty-provider.test.ts
@@ -29,6 +29,7 @@ function createMockSubprocess(): SubprocessHandle & {
onExit(cb) {
onExitCb = cb
},
+ dispose: vi.fn(),
_simulateData(data: string) {
onDataCb?.(data)
},
diff --git a/src/main/daemon/daemon-pty-router.test.ts b/src/main/daemon/daemon-pty-router.test.ts
index 1594da80d..fee4c11b5 100644
--- a/src/main/daemon/daemon-pty-router.test.ts
+++ b/src/main/daemon/daemon-pty-router.test.ts
@@ -153,4 +153,105 @@ describe('DaemonPtyRouter', () => {
expect(current.dispose).toHaveBeenCalled()
expect(legacy.dispose).toHaveBeenCalled()
})
+
+ // Why: docs/daemon-staleness-ux.md §Phase 1 step 5 requires the restart flow
+ // to preserve the legacy adapter instances across the current-adapter swap,
+ // and it reads them back via these accessors. Locking the return shape
+ // prevents a future refactor from quietly switching to a defensive copy
+ // (breaks instance identity) or a different list (breaks restart).
+ describe('restart accessors', () => {
+ it('returns the exact current adapter instance', () => {
+ const current = createAdapter('current')
+ const router = new DaemonPtyRouter({ current, legacy: [] })
+
+ expect(router.getCurrentAdapter()).toBe(current)
+ })
+
+ it('returns the exact legacy adapter instances', () => {
+ const current = createAdapter('current')
+ const legacy1 = createAdapter('legacy-1')
+ const legacy2 = createAdapter('legacy-2')
+ const router = new DaemonPtyRouter({ current, legacy: [legacy1, legacy2] })
+
+ const legacies = router.getLegacyAdapters()
+ expect(legacies.length).toBe(2)
+ expect(legacies[0]).toBe(legacy1)
+ expect(legacies[1]).toBe(legacy2)
+ })
+
+ it('getAllAdapters returns current first then legacy, by identity', () => {
+ const current = createAdapter('current')
+ const legacy1 = createAdapter('legacy-1')
+ const legacy2 = createAdapter('legacy-2')
+ const router = new DaemonPtyRouter({ current, legacy: [legacy1, legacy2] })
+
+ const all = router.getAllAdapters()
+ expect(all.length).toBe(3)
+ expect(all[0]).toBe(current)
+ expect(all[1]).toBe(legacy1)
+ expect(all[2]).toBe(legacy2)
+ })
+ })
+
+ // Why: the restart flow (daemon-init.runRestartDaemon step 5→6) relies on
+ // disposeRouterOnly draining the outgoing router's subscriptions WITHOUT
+ // tearing down the legacy adapters themselves. plain dispose() would
+ // cascade into the adapters and strand any legacy-backed sessions — see
+ // daemon-pty-router.ts §disposeRouterOnly comment. These tests lock the
+ // contract: no adapter teardown, subscriptions actually detached for both
+ // onData and onExit on both current and legacy, idempotent.
+ describe('disposeRouterOnly', () => {
+ it('does not call dispose or disconnectOnly on any adapter', () => {
+ const current = createAdapter('current')
+ const legacy = createAdapter('legacy')
+ const router = new DaemonPtyRouter({ current, legacy: [legacy] })
+
+ router.disposeRouterOnly()
+
+ expect(current.dispose).not.toHaveBeenCalled()
+ expect(legacy.dispose).not.toHaveBeenCalled()
+ expect(current.disconnectOnly).not.toHaveBeenCalled()
+ expect(legacy.disconnectOnly).not.toHaveBeenCalled()
+ })
+
+ it('stops forwarding adapter onData/onExit to subscribers registered before dispose', () => {
+ const current = createAdapter('current')
+ const legacy = createAdapter('legacy')
+ const router = new DaemonPtyRouter({ current, legacy: [legacy] })
+
+ // Realistic restart scenario: the local IPC layer subscribes at app
+ // start, THEN the restart flow later calls disposeRouterOnly. A spy
+ // registered *after* dispose proves the router→subscriber path is
+ // empty, but doesn't prove the router unsubscribed from the adapters.
+ const dataSpy = vi.fn()
+ const exitSpy = vi.fn()
+ router.onData(dataSpy)
+ router.onExit(exitSpy)
+
+ router.disposeRouterOnly()
+
+ // Both current- and legacy-adapter emissions must be silenced. A
+ // regression that only unsubscribed from one would pass a single-
+ // adapter test but fail this one.
+ current.emitData('current-id', 'hello')
+ current.emitExit('current-id', 0)
+ legacy.emitData('legacy-id', 'world')
+ legacy.emitExit('legacy-id', 1)
+
+ expect(dataSpy).not.toHaveBeenCalled()
+ expect(exitSpy).not.toHaveBeenCalled()
+ })
+
+ it('is idempotent — a second disposeRouterOnly call is a no-op and does not throw', () => {
+ const current = createAdapter('current')
+ const legacy = createAdapter('legacy')
+ const router = new DaemonPtyRouter({ current, legacy: [legacy] })
+
+ router.disposeRouterOnly()
+ expect(() => router.disposeRouterOnly()).not.toThrow()
+ // And still no adapter teardown on the second call.
+ expect(current.dispose).not.toHaveBeenCalled()
+ expect(legacy.dispose).not.toHaveBeenCalled()
+ })
+ })
})
diff --git a/src/main/daemon/daemon-pty-router.ts b/src/main/daemon/daemon-pty-router.ts
index e69b21aa6..d6ba74ef7 100644
--- a/src/main/daemon/daemon-pty-router.ts
+++ b/src/main/daemon/daemon-pty-router.ts
@@ -180,6 +180,19 @@ export class DaemonPtyRouter implements IPtyProvider {
}
}
+ // Why: restart swaps to a fresh router carrying the *same* legacy adapter
+ // instances. If we called dispose() on the outgoing router it would tear
+ // down those legacy adapters along with it. disposeRouterOnly() detaches
+ // only this router's subscriptions from the adapters — the adapters and
+ // their daemon connections keep running, and the new router re-subscribes.
+ // Without this, each restart leaked a router instance pinned by the legacy
+ // adapters' listener arrays (one pair per adapter per restart).
+ disposeRouterOnly(): void {
+ for (const unsubscribe of this.unsubscribers.splice(0)) {
+ unsubscribe()
+ }
+ }
+
async disconnectOnly(): Promise {
for (const unsubscribe of this.unsubscribers.splice(0)) {
unsubscribe()
@@ -187,6 +200,24 @@ export class DaemonPtyRouter implements IPtyProvider {
await Promise.all([...this.allAdapters()].map((adapter) => adapter.disconnectOnly()))
}
+ // Why: the Manage Sessions panel iterates all adapters to list sessions
+ // across every protocol version, and the restart handler needs to preserve
+ // surviving legacy adapters across the current-adapter swap. On this branch
+ // (pre-#1323) the legacy list is set once at construction and never mutated,
+ // so returning the internal array by reference is safe for the intended
+ // read-only use.
+ getCurrentAdapter(): DaemonPtyAdapter {
+ return this.current
+ }
+
+ getLegacyAdapters(): readonly DaemonPtyAdapter[] {
+ return this.legacy
+ }
+
+ getAllAdapters(): readonly DaemonPtyAdapter[] {
+ return this.allAdapters()
+ }
+
private adapterFor(sessionId: string): DaemonPtyAdapter {
return this.sessionAdapters.get(sessionId) ?? this.current
}
diff --git a/src/main/daemon/daemon-server.test.ts b/src/main/daemon/daemon-server.test.ts
index 1e982bd2f..a58895f1d 100644
--- a/src/main/daemon/daemon-server.test.ts
+++ b/src/main/daemon/daemon-server.test.ts
@@ -27,7 +27,8 @@ function createMockSubprocess(): SubprocessHandle {
},
onExit(cb) {
onExitCb = cb
- }
+ },
+ dispose: vi.fn()
}
}
diff --git a/src/main/daemon/daemon-server.ts b/src/main/daemon/daemon-server.ts
index 28bf56c62..956675784 100644
--- a/src/main/daemon/daemon-server.ts
+++ b/src/main/daemon/daemon-server.ts
@@ -201,6 +201,7 @@ export class DaemonServer {
env: p.env,
command: p.command,
shellOverride: p.shellOverride,
+ terminalWindowsPowerShellImplementation: p.terminalWindowsPowerShellImplementation,
shellReadySupported: p.shellReadySupported,
streamClient: {
onData: (data) => {
diff --git a/src/main/daemon/daemon-spawner.test.ts b/src/main/daemon/daemon-spawner.test.ts
index 63a65aeb2..c07953364 100644
--- a/src/main/daemon/daemon-spawner.test.ts
+++ b/src/main/daemon/daemon-spawner.test.ts
@@ -29,7 +29,8 @@ function createMockSubprocess(): SubprocessHandle {
onData(_cb: (data: string) => void) {},
onExit(cb: (code: number) => void) {
onExitCb = cb
- }
+ },
+ dispose: vi.fn()
}
}
diff --git a/src/main/daemon/daemon-spawner.ts b/src/main/daemon/daemon-spawner.ts
index 4b6144bca..d57b79e41 100644
--- a/src/main/daemon/daemon-spawner.ts
+++ b/src/main/daemon/daemon-spawner.ts
@@ -7,6 +7,11 @@ export type DaemonConnectionInfo = {
tokenPath: string
}
+export type DaemonPidFile = {
+ pid: number
+ startedAtMs: number | null
+}
+
export type DaemonProcessHandle = {
shutdown(): Promise
}
@@ -80,3 +85,7 @@ export function getDaemonTokenPath(runtimeDir: string, protocolVersion = PROTOCO
export function getDaemonPidPath(runtimeDir: string, protocolVersion = PROTOCOL_VERSION): string {
return join(runtimeDir, `daemon-v${protocolVersion}.pid`)
}
+
+export function serializeDaemonPidFile(pidFile: DaemonPidFile): string {
+ return JSON.stringify(pidFile)
+}
diff --git a/src/main/daemon/production-launcher.test.ts b/src/main/daemon/production-launcher.test.ts
index 53475f6a7..832f6c949 100644
--- a/src/main/daemon/production-launcher.test.ts
+++ b/src/main/daemon/production-launcher.test.ts
@@ -23,7 +23,8 @@ function createMockSubprocess(): SubprocessHandle {
onData(_cb: (data: string) => void) {},
onExit(cb: (code: number) => void) {
onExitCb = cb
- }
+ },
+ dispose: vi.fn()
}
}
diff --git a/src/main/daemon/pty-subprocess.test.ts b/src/main/daemon/pty-subprocess.test.ts
index 1c89be299..2580d98f4 100644
--- a/src/main/daemon/pty-subprocess.test.ts
+++ b/src/main/daemon/pty-subprocess.test.ts
@@ -1,13 +1,19 @@
-import { describe, expect, it, vi } from 'vitest'
+/* oxlint-disable max-lines -- Why: exercises full PTY subprocess surface (spawn setup, signal routing, data events, platform-specific shell configs, and Windows PowerShell implementations) with co-located test scenarios to prevent fixture drift. */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
-const { spawnMock } = vi.hoisted(() => ({
- spawnMock: vi.fn()
+const { spawnMock, isPwshAvailableMock } = vi.hoisted(() => ({
+ spawnMock: vi.fn(),
+ isPwshAvailableMock: vi.fn()
}))
vi.mock('node-pty', () => ({
spawn: spawnMock
}))
+vi.mock('../pwsh', () => ({
+ isPwshAvailable: isPwshAvailableMock
+}))
+
import { createPtySubprocess } from './pty-subprocess'
function mockPtyProcess(pid = 12345) {
@@ -33,6 +39,11 @@ function mockPtyProcess(pid = 12345) {
}
describe('createPtySubprocess', () => {
+ beforeEach(() => {
+ spawnMock.mockReset()
+ isPwshAvailableMock.mockReset()
+ isPwshAvailableMock.mockReturnValue(false)
+ })
it('spawns node-pty with correct options', () => {
const proc = mockPtyProcess()
spawnMock.mockReturnValue(proc)
@@ -262,4 +273,301 @@ describe('createPtySubprocess', () => {
expect.objectContaining({ cwd: 'D:\\Users\\orca' })
)
})
+
+ it('keeps powershell.exe when the inbox PowerShell implementation is selected on Windows', () => {
+ const proc = mockPtyProcess()
+ spawnMock.mockReturnValue(proc)
+ const platform = Object.getOwnPropertyDescriptor(process, 'platform')
+
+ Object.defineProperty(process, 'platform', { value: 'win32' })
+ isPwshAvailableMock.mockReturnValue(true)
+
+ try {
+ createPtySubprocess({
+ sessionId: 'test',
+ cols: 80,
+ rows: 24,
+ env: { COMSPEC: 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' },
+ terminalWindowsPowerShellImplementation: 'powershell.exe'
+ })
+ } finally {
+ if (platform) {
+ Object.defineProperty(process, 'platform', platform)
+ }
+ }
+
+ expect(spawnMock).toHaveBeenCalledWith(
+ 'powershell.exe',
+ [
+ '-NoExit',
+ '-Command',
+ 'try { . $PROFILE } catch {}; [Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Console]::InputEncoding = [System.Text.Encoding]::UTF8'
+ ],
+ expect.any(Object)
+ )
+ })
+
+ it('spawns pwsh.exe when PowerShell 7 is selected and available on Windows', () => {
+ const proc = mockPtyProcess()
+ spawnMock.mockReturnValue(proc)
+ const platform = Object.getOwnPropertyDescriptor(process, 'platform')
+
+ Object.defineProperty(process, 'platform', { value: 'win32' })
+ isPwshAvailableMock.mockReturnValue(true)
+
+ try {
+ createPtySubprocess({
+ sessionId: 'test',
+ cols: 80,
+ rows: 24,
+ env: { COMSPEC: 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' },
+ terminalWindowsPowerShellImplementation: 'pwsh.exe'
+ })
+ } finally {
+ if (platform) {
+ Object.defineProperty(process, 'platform', platform)
+ }
+ }
+
+ expect(spawnMock).toHaveBeenCalledWith(
+ 'pwsh.exe',
+ [
+ '-NoExit',
+ '-Command',
+ 'try { . $PROFILE } catch {}; [Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Console]::InputEncoding = [System.Text.Encoding]::UTF8'
+ ],
+ expect.any(Object)
+ )
+ })
+
+ it('falls back to powershell.exe when PowerShell 7 is selected but unavailable on Windows', () => {
+ const proc = mockPtyProcess()
+ spawnMock.mockReturnValue(proc)
+ const platform = Object.getOwnPropertyDescriptor(process, 'platform')
+
+ Object.defineProperty(process, 'platform', { value: 'win32' })
+ isPwshAvailableMock.mockReturnValue(false)
+
+ try {
+ createPtySubprocess({
+ sessionId: 'test',
+ cols: 80,
+ rows: 24,
+ env: { COMSPEC: 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' },
+ terminalWindowsPowerShellImplementation: 'pwsh.exe'
+ })
+ } finally {
+ if (platform) {
+ Object.defineProperty(process, 'platform', platform)
+ }
+ }
+
+ expect(spawnMock).toHaveBeenCalledWith(
+ 'powershell.exe',
+ [
+ '-NoExit',
+ '-Command',
+ 'try { . $PROFILE } catch {}; [Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Console]::InputEncoding = [System.Text.Encoding]::UTF8'
+ ],
+ expect.any(Object)
+ )
+ })
+
+ it('falls back to powershell.exe when shellOverride requests pwsh.exe but pwsh is unavailable on Windows', () => {
+ const proc = mockPtyProcess()
+ spawnMock.mockReturnValue(proc)
+ const platform = Object.getOwnPropertyDescriptor(process, 'platform')
+
+ Object.defineProperty(process, 'platform', { value: 'win32' })
+ isPwshAvailableMock.mockReturnValue(false)
+
+ try {
+ createPtySubprocess({
+ sessionId: 'test',
+ cols: 80,
+ rows: 24,
+ shellOverride: 'pwsh.exe',
+ terminalWindowsPowerShellImplementation: 'pwsh.exe'
+ })
+ } finally {
+ if (platform) {
+ Object.defineProperty(process, 'platform', platform)
+ }
+ }
+
+ expect(spawnMock).toHaveBeenCalledWith(
+ 'powershell.exe',
+ [
+ '-NoExit',
+ '-Command',
+ 'try { . $PROFILE } catch {}; [Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Console]::InputEncoding = [System.Text.Encoding]::UTF8'
+ ],
+ expect.any(Object)
+ )
+ })
+
+ it('ignores the PowerShell implementation setting for cmd.exe on Windows', () => {
+ const proc = mockPtyProcess()
+ spawnMock.mockReturnValue(proc)
+ const platform = Object.getOwnPropertyDescriptor(process, 'platform')
+
+ Object.defineProperty(process, 'platform', { value: 'win32' })
+ isPwshAvailableMock.mockReturnValue(true)
+
+ try {
+ createPtySubprocess({
+ sessionId: 'test',
+ cols: 80,
+ rows: 24,
+ shellOverride: 'cmd.exe',
+ terminalWindowsPowerShellImplementation: 'pwsh.exe'
+ })
+ } finally {
+ if (platform) {
+ Object.defineProperty(process, 'platform', platform)
+ }
+ }
+
+ expect(spawnMock).toHaveBeenCalledWith(
+ 'cmd.exe',
+ ['/K', 'chcp 65001 > nul'],
+ expect.any(Object)
+ )
+ })
+
+ // Why: node-pty's UnixTerminal.destroy() registers _socket.once('close', () =>
+ // this.kill('SIGHUP')), and the socket 'close' event can fire concurrently
+ // with onExit. If kill is not neutralized by the time close fires, SIGHUP
+ // targets a reaped pid that may have been recycled. These tests pin down the
+ // neutralization contract on both onExit (natural-exit path) and dispose()
+ // (forced-teardown path) for POSIX, and verify Windows is exempt.
+ describe('proc.kill neutralization for SIGHUP-to-recycled-pid hazard', () => {
+ const restorePlatform = (desc?: PropertyDescriptor) => {
+ if (desc) {
+ Object.defineProperty(process, 'platform', desc)
+ }
+ }
+
+ it('neutralizes proc.kill on POSIX inside proc.onExit synchronously', () => {
+ const proc = mockPtyProcess()
+ spawnMock.mockReturnValue(proc)
+ const origPlatform = Object.getOwnPropertyDescriptor(process, 'platform')
+ Object.defineProperty(process, 'platform', { value: 'linux' })
+ const originalKill = proc.kill
+ try {
+ createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 })
+ expect(proc.kill).toBe(originalKill)
+ proc._simulateExit(0)
+ expect(proc.kill).not.toBe(originalKill)
+ // Calling the neutralized kill is a safe no-op.
+ expect(() => (proc.kill as () => void)()).not.toThrow()
+ } finally {
+ restorePlatform(origPlatform)
+ }
+ })
+
+ it('DOES NOT neutralize proc.kill on Windows (WindowsTerminal.destroy needs kill)', () => {
+ const proc = mockPtyProcess()
+ spawnMock.mockReturnValue(proc)
+ const origPlatform = Object.getOwnPropertyDescriptor(process, 'platform')
+ Object.defineProperty(process, 'platform', { value: 'win32' })
+ const originalKill = proc.kill
+ try {
+ createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 })
+ proc._simulateExit(0)
+ expect(proc.kill).toBe(originalKill)
+ } finally {
+ restorePlatform(origPlatform)
+ }
+ })
+
+ it('dispose() neutralizes proc.kill on POSIX before calling destroy()', () => {
+ const proc = mockPtyProcess() as ReturnType & {
+ destroy: ReturnType
+ }
+ proc.destroy = vi.fn()
+ spawnMock.mockReturnValue(proc)
+ const origPlatform = Object.getOwnPropertyDescriptor(process, 'platform')
+ Object.defineProperty(process, 'platform', { value: 'darwin' })
+ const originalKill = proc.kill
+ try {
+ const handle = createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 })
+ handle.dispose()
+ expect(proc.kill).not.toBe(originalKill)
+ expect(proc.destroy).toHaveBeenCalledOnce()
+ } finally {
+ restorePlatform(origPlatform)
+ }
+ })
+
+ it('dispose() on Windows calls destroy() without neutralizing kill', () => {
+ const proc = mockPtyProcess() as ReturnType & {
+ destroy: ReturnType
+ }
+ proc.destroy = vi.fn()
+ spawnMock.mockReturnValue(proc)
+ const origPlatform = Object.getOwnPropertyDescriptor(process, 'platform')
+ Object.defineProperty(process, 'platform', { value: 'win32' })
+ const originalKill = proc.kill
+ try {
+ const handle = createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 })
+ handle.dispose()
+ expect(proc.kill).toBe(originalKill)
+ expect(proc.destroy).toHaveBeenCalledOnce()
+ } finally {
+ restorePlatform(origPlatform)
+ }
+ })
+
+ it('dispose() is idempotent — second call does not re-invoke destroy', () => {
+ const proc = mockPtyProcess() as ReturnType & {
+ destroy: ReturnType
+ }
+ proc.destroy = vi.fn()
+ spawnMock.mockReturnValue(proc)
+ const handle = createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 })
+ handle.dispose()
+ handle.dispose()
+ expect(proc.destroy).toHaveBeenCalledOnce()
+ })
+ })
+
+ // Why: after proc.onExit fires (dead=true), proc.pid refers to a reaped child
+ // whose pid may have been recycled to an unrelated process. forceKill and
+ // signal call process.kill(proc.pid, ...) directly, bypassing the
+ // proc.kill-neutralization applied to the node-pty instance. Without an
+ // internal dead-guard, they can deliver SIGKILL/SIGINT/etc to a stranger.
+ describe('forceKill/signal guard against recycled pid after exit', () => {
+ it('forceKill is a no-op once proc.onExit has fired', () => {
+ const proc = mockPtyProcess(55)
+ spawnMock.mockReturnValue(proc)
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true)
+ const handle = createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 })
+ proc._simulateExit(0)
+ handle.forceKill()
+ expect(killSpy).not.toHaveBeenCalled()
+ killSpy.mockRestore()
+ })
+
+ it('signal is a no-op once proc.onExit has fired', () => {
+ const proc = mockPtyProcess(55)
+ spawnMock.mockReturnValue(proc)
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true)
+ const handle = createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 })
+ proc._simulateExit(0)
+ handle.signal('SIGINT')
+ expect(killSpy).not.toHaveBeenCalled()
+ killSpy.mockRestore()
+ })
+
+ it('forceKill before exit still fires SIGKILL (live child)', () => {
+ const proc = mockPtyProcess(77)
+ spawnMock.mockReturnValue(proc)
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true)
+ const handle = createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 })
+ handle.forceKill()
+ expect(killSpy).toHaveBeenCalledWith(77, 'SIGKILL')
+ killSpy.mockRestore()
+ })
+ })
})
diff --git a/src/main/daemon/pty-subprocess.ts b/src/main/daemon/pty-subprocess.ts
index 8e6ceb4ca..bdeec2053 100644
--- a/src/main/daemon/pty-subprocess.ts
+++ b/src/main/daemon/pty-subprocess.ts
@@ -1,4 +1,5 @@
import * as pty from 'node-pty'
+import { win32 as pathWin32 } from 'path'
import type { SubprocessHandle } from './session'
import {
getAttributionShellLaunchConfig,
@@ -8,6 +9,8 @@ import {
import { isValidPtySize, normalizePtySize } from './daemon-pty-size'
import { ensureNodePtySpawnHelperExecutable } from '../providers/local-pty-utils'
import { resolveWindowsShellLaunchArgs } from '../providers/windows-shell-args'
+import { resolveEffectiveWindowsPowerShell } from '../providers/windows-powershell'
+import { isPwshAvailable } from '../pwsh'
export type PtySubprocessOptions = {
sessionId: string
@@ -20,6 +23,7 @@ export type PtySubprocessOptions = {
* Overrides env.COMSPEC / env.SHELL resolution inside the daemon so a user
* who picks "New WSL terminal" from the "+" menu actually gets WSL. */
shellOverride?: string
+ terminalWindowsPowerShellImplementation?: 'auto' | 'powershell.exe' | 'pwsh.exe'
}
function getDefaultCwd(): string {
@@ -67,16 +71,37 @@ export function createPtySubprocess(opts: PtySubprocessOptions): SubprocessHandl
// setting, relayed by main) takes priority over env.COMSPEC — otherwise
// Windows always resolves to cmd.exe (COMSPEC) or PowerShell by fallback,
// no matter which shell the user actually picked.
- const shellPath = opts.shellOverride || resolvePtyShellPath(env)
+ let shellPath = opts.shellOverride || resolvePtyShellPath(env)
let shellArgs: string[]
let spawnCwd = opts.cwd || getDefaultCwd()
if (process.platform === 'win32') {
+ const normalizedShellFamily = pathWin32.basename(shellPath).toLowerCase()
+ // Why: daemon spawn requests can carry either a canonical shell family
+ // (`powershell.exe`) or a concrete PowerShell executable path from a
+ // one-off override. Normalize both forms back to the PowerShell family so
+ // the shared resolver can still fall back to inbox powershell.exe when
+ // pwsh.exe was requested but is unavailable.
+ const shouldResolvePowerShellFamily =
+ opts.terminalWindowsPowerShellImplementation !== undefined ||
+ pathWin32.basename(shellPath) === shellPath
+ shellPath = shouldResolvePowerShellFamily
+ ? (resolveEffectiveWindowsPowerShell({
+ shellFamily:
+ normalizedShellFamily === 'powershell.exe' || normalizedShellFamily === 'pwsh.exe'
+ ? 'powershell.exe'
+ : normalizedShellFamily === 'cmd.exe' || normalizedShellFamily === 'wsl.exe'
+ ? normalizedShellFamily
+ : undefined,
+ implementation: opts.terminalWindowsPowerShellImplementation,
+ pwshAvailable: isPwshAvailable()
+ }) ?? shellPath)
+ : shellPath
// Why: matches LocalPtyProvider — CMD needs chcp 65001, PowerShell needs
// $PROFILE dot-sourcing, WSL needs a --bash entry with a translated cwd.
- // Previously the daemon passed `[]` here which made every shell launch as
- // a bare interactive process; that silently degraded PowerShell (no
- // profile) and never worked at all for WSL (which needs explicit args).
+ // Reuse the same shared launch-args helper after resolving the effective
+ // PowerShell executable so daemon-backed terminals preserve parity with the
+ // in-process PTY path.
const resolved = resolveWindowsShellLaunchArgs(shellPath, spawnCwd, getDefaultCwd())
shellArgs = resolved.shellArgs
spawnCwd = resolved.effectiveCwd
@@ -117,8 +142,21 @@ export function createPtySubprocess(opts: PtySubprocessOptions): SubprocessHandl
// exiting and the JS onExit callback firing. An uncaught Napi::Error
// propagates to std::terminate, killing the entire daemon process.
let dead = false
+ let disposed = false
proc.onExit(() => {
dead = true
+ // Why: UnixTerminal.destroy() registers `_socket.once('close', () => this.kill('SIGHUP'))`
+ // (unixTerminal.js:219-229). After the child exits, the master socket's
+ // 'close' event can fire before our dispose() path gets to neutralize
+ // proc.kill — the child's pid may have already been recycled, so SIGHUP
+ // lands on an unrelated process. Neutralizing here, synchronously inside
+ // the onExit callback, closes that window: once the child is reaped,
+ // proc.kill is a no-op no matter which teardown ordering wins.
+ // Windows is excluded because WindowsTerminal.destroy relies on kill() to
+ // close the ConPTY agent — neutralizing would leak the agent + fds.
+ if (process.platform !== 'win32') {
+ ;(proc as unknown as { kill: (sig?: string) => void }).kill = () => {}
+ }
})
return {
@@ -157,6 +195,13 @@ export function createPtySubprocess(opts: PtySubprocessOptions): SubprocessHandl
}
},
forceKill: () => {
+ // Why: once the child has been reaped (dead=true via onExit) or dispose
+ // has run, proc.pid refers to a recycled pid. Sending SIGKILL would
+ // terminate an unrelated process. The fd release is handled by
+ // dispose()/destroy(); forceKill is strictly for signalling a live child.
+ if (dead) {
+ return
+ }
try {
process.kill(proc.pid, 'SIGKILL')
} catch {
@@ -168,6 +213,11 @@ export function createPtySubprocess(opts: PtySubprocessOptions): SubprocessHandl
}
},
signal: (sig) => {
+ // Why: same recycled-pid hazard as forceKill. Once dead, silently drop
+ // the signal rather than risk sending it to an unrelated process.
+ if (dead) {
+ return
+ }
try {
process.kill(proc.pid, sig)
} catch {
@@ -179,6 +229,35 @@ export function createPtySubprocess(opts: PtySubprocessOptions): SubprocessHandl
},
onExit: (cb) => {
onExitCb = cb
+ },
+ dispose: () => {
+ if (disposed) {
+ return
+ }
+ disposed = true
+ dead = true
+ onDataCb = null
+ onExitCb = null
+ // Why: UnixTerminal.destroy() registers `_socket.once('close', () => this.kill('SIGHUP'))`
+ // (unixTerminal.js:219-229). The socket close fires asynchronously; by then
+ // the child may have exited and its pid been recycled to an unrelated
+ // process. Without this neutralization, SIGHUP can be delivered to a
+ // Chrome tab, editor, or other user process — silent cross-app corruption.
+ // `_socket.destroy()` still releases the fd; only the dangerous SIGHUP is
+ // removed.
+ //
+ // Platform guard: WindowsTerminal.destroy implements the ConPTY close by
+ // CALLING `this.kill()` via `_deferNoArgs` (windowsTerminal.js:141-146).
+ // Neutralizing kill on Windows turns destroy() into a no-op and leaks the
+ // ConPTY agent. The SIGHUP hazard is POSIX-only, so the guard is too.
+ if (process.platform !== 'win32') {
+ ;(proc as unknown as { kill: (sig?: string) => void }).kill = () => {}
+ }
+ try {
+ ;(proc as unknown as { destroy?: () => void }).destroy?.()
+ } catch {
+ /* swallow — already torn down, or native-side error we can't recover from */
+ }
}
}
}
diff --git a/src/main/daemon/reattach-snapshot.test.ts b/src/main/daemon/reattach-snapshot.test.ts
index e9f5813e1..c9a4bc32a 100644
--- a/src/main/daemon/reattach-snapshot.test.ts
+++ b/src/main/daemon/reattach-snapshot.test.ts
@@ -23,6 +23,7 @@ function createMockSubprocess(): SubprocessHandle & {
onExit(cb) {
onExitCb = cb
},
+ dispose: vi.fn(),
simulateData(data: string) {
onDataCb?.(data)
},
diff --git a/src/main/daemon/session.test.ts b/src/main/daemon/session.test.ts
index 5191f77fd..fc3123381 100644
--- a/src/main/daemon/session.test.ts
+++ b/src/main/daemon/session.test.ts
@@ -41,6 +41,7 @@ function createMockSubprocess() {
onExit(cb: (code: number) => void) {
onExit = cb
},
+ dispose() {},
// Helpers for tests to simulate subprocess events
simulateData(data: string) {
onData?.(data)
diff --git a/src/main/daemon/session.ts b/src/main/daemon/session.ts
index 4c398f5a2..b2cb46fd7 100644
--- a/src/main/daemon/session.ts
+++ b/src/main/daemon/session.ts
@@ -1,3 +1,4 @@
+/* oxlint-disable max-lines */
import { HeadlessEmulator } from './headless-emulator'
import { isValidPtySize, normalizePtySize } from './daemon-pty-size'
import { PostReadyFlushGate } from './post-ready-flush-gate'
@@ -16,6 +17,10 @@ export type SubprocessHandle = {
signal(sig: string): void
onData(cb: (data: string) => void): void
onExit(cb: (code: number) => void): void
+ /** Release the native PTY handle via node-pty's own destroy() path.
+ * Idempotent. Safe to call after exit. Called by Session on every teardown
+ * path (natural exit, kill, force-kill, native throw, session dispose). */
+ dispose(): void
}
export type SessionOptions = {
@@ -191,35 +196,31 @@ export class Session {
return
}
- // Why: if kill() was called but the subprocess hasn't exited yet, our
- // killTimer is the only thing that would forceKill a stuck subprocess.
- // Clearing it below without force-killing would leak an orphaned process,
- // so mirror forceDispose(): issue the force-kill, notify attached clients
- // (handleSubprocessExit is guarded by _disposed and won't broadcast later),
- // and clear the terminating flag for a consistent final state.
+ // Why: captured BEFORE the `_state = 'exited'` flip below. This check
+ // guards the "dispose while kill() was already in flight" case — if true,
+ // the child hasn't reaped yet and we need to forceKill it here (the 5s
+ // killTimer is also about to be cleared by #teardownSubprocess). Do NOT
+ // move this capture below #teardownSubprocess or the `_state = 'exited'`
+ // assignment — #teardownSubprocess flips `_disposed` but the invariant
+ // depends on the PRE-flip value of `_state`.
const wasTerminating = this._isTerminating && this._state !== 'exited'
const clientsToNotify = wasTerminating ? this.attachedClients.slice() : []
if (wasTerminating) {
- this.subprocess.forceKill()
+ try {
+ this.subprocess.forceKill()
+ } catch {
+ /* child may already be gone */
+ }
this._exitCode = -1
this._isTerminating = false
}
- this._disposed = true
+ this.#teardownSubprocess()
this._state = 'exited'
- if (this.shellReadyTimer) {
- clearTimeout(this.shellReadyTimer)
- this.shellReadyTimer = null
- }
- if (this.killTimer) {
- clearTimeout(this.killTimer)
- this.killTimer = null
- }
- this.postReadyFlushGate.clear()
-
this.attachedClients = []
this.preReadyStdinQueue = []
+ this.postReadyFlushGate.clear()
this.emulator.dispose()
for (const client of clientsToNotify) {
@@ -227,6 +228,72 @@ export class Session {
}
}
+ /** Public: fd-release-only teardown for sessions that have ALREADY exited
+ * (state === 'exited') but are still retained in the host's map. Callers
+ * MUST NOT use this on live sessions — it skips SIGKILL.
+ *
+ * Why a separate method: after handleSubprocessExit fires, proc.pid refers
+ * to a child that has been reaped; on POSIX that pid is eligible for reuse
+ * and may now belong to an unrelated process. forceKillAndDisposeSubprocess
+ * would send SIGKILL to that recycled pid. This method only releases the
+ * PTY master fd via node-pty's destroy() (which is neutralized against the
+ * SIGHUP-to-pid hazard by the onExit handler in pty-subprocess.ts). */
+ disposeSubprocess(): void {
+ this.#teardownSubprocess()
+ this._state = 'exited'
+ }
+
+ /** Public: orderly-shutdown path used by TerminalHost.dispose() for sessions
+ * that are still live. Force-kills the child (SIGKILL is not ignorable),
+ * then releases the PTY master fd synchronously via node-pty's destroy().
+ * Bypasses the 5s KILL_TIMEOUT_MS fallback so daemon shutdown reaps
+ * stubborn children AND frees the ptmx fd on the same tick. Does NOT fan
+ * out onExit to attached clients — renderer reconnects cold after daemon
+ * exit. Callers MUST check isAlive first; see disposeSubprocess() for the
+ * already-exited case. */
+ forceKillAndDisposeSubprocess(): void {
+ // Why: forceKill before #teardownSubprocess. The helper's subprocess.dispose()
+ // neutralizes node-pty's proc.kill on POSIX (to kill the SIGHUP-to-recycled-pid
+ // hazard). subprocess.forceKill uses process.kill(pid, 'SIGKILL') directly
+ // (pty-subprocess.ts) — unaffected by the neutralization, because it does not
+ // go through proc.kill. SIGKILL is not ignorable; any child that would have
+ // survived the 5s timer is reaped immediately.
+ try {
+ this.subprocess.forceKill()
+ } catch {
+ /* swallow — child may already be gone */
+ }
+ this.#teardownSubprocess()
+ this._state = 'exited'
+ }
+
+ /** Private: shared teardown helper called by dispose(), forceDispose(), and
+ * forceKillAndDisposeSubprocess(). Flips `_disposed`, clears pending timers,
+ * and forwards to subprocess.dispose() exactly once. Does NOT set `_state` —
+ * the caller owns the state transition AFTER capturing any invariants that
+ * depend on the pre-flip value (see the wasTerminating capture in dispose). */
+ #teardownSubprocess(): void {
+ if (this._disposed) {
+ return
+ }
+ this._disposed = true
+ if (this.killTimer) {
+ clearTimeout(this.killTimer)
+ this.killTimer = null
+ }
+ if (this.shellReadyTimer) {
+ clearTimeout(this.shellReadyTimer)
+ this.shellReadyTimer = null
+ }
+ try {
+ this.subprocess.dispose()
+ } catch (err) {
+ // Why: dispose() is documented never to throw, but if it does we must not
+ // prevent callers from completing their own cleanup (fanout, map removal).
+ console.warn('[Session] subprocess.dispose() threw:', err)
+ }
+ }
+
private handleSubprocessData(data: string): void {
if (this._disposed) {
return
@@ -265,6 +332,19 @@ export class Session {
}
this.postReadyFlushGate.clear()
+ // Why: release the ptmx fd on the natural-exit path. Without this, the
+ // node-pty wrapper's _socket stays alive until GC and the master fd leaks
+ // (see docs/fix-pty-fd-leak.md). Do NOT route through #teardownSubprocess:
+ // that helper flips `_disposed = true`, which would short-circuit a later
+ // Session.dispose() call from TerminalHost's dead-session cleanup at
+ // terminal-host.ts:83 — skipping attachedClients/emulator/postReadyFlushGate
+ // cleanup. Call subprocess.dispose() directly inside try/catch.
+ try {
+ this.subprocess.dispose()
+ } catch {
+ /* swallow — must not prevent exit-code fanout below */
+ }
+
for (const client of this.attachedClients) {
client.onExit(code)
}
@@ -320,25 +400,28 @@ export class Session {
if (this._state === 'exited') {
return
}
- this.subprocess.forceKill()
- this._disposed = true
+ // Why: forceKill BEFORE #teardownSubprocess. Order is load-bearing — the
+ // helper's subprocess.dispose() neutralizes proc.kill on POSIX (to defuse
+ // the SIGHUP-to-recycled-pid hazard inside node-pty). forceKill uses
+ // process.kill(pid, 'SIGKILL') directly and is unaffected by that
+ // neutralization. Must NOT flip `_disposed` here before #teardownSubprocess
+ // runs, or the helper would early-return and skip subprocess.dispose() —
+ // the ptmx fd would leak on every kill-timeout (this whole doc's target).
+ try {
+ this.subprocess.forceKill()
+ } catch {
+ /* already dead */
+ }
this._exitCode = -1
- this._state = 'exited'
this._isTerminating = false
- if (this.shellReadyTimer) {
- clearTimeout(this.shellReadyTimer)
- this.shellReadyTimer = null
- }
- if (this.killTimer) {
- clearTimeout(this.killTimer)
- this.killTimer = null
- }
- this.postReadyFlushGate.clear()
+ this.#teardownSubprocess()
+ this._state = 'exited'
const clients = this.attachedClients
this.attachedClients = []
this.preReadyStdinQueue = []
+ this.postReadyFlushGate.clear()
this.emulator.dispose()
for (const client of clients) {
diff --git a/src/main/daemon/terminal-host-startup.test.ts b/src/main/daemon/terminal-host-startup.test.ts
index 2f1a20242..9474b8704 100644
--- a/src/main/daemon/terminal-host-startup.test.ts
+++ b/src/main/daemon/terminal-host-startup.test.ts
@@ -11,7 +11,8 @@ function mockSubprocess(): SubprocessHandle {
forceKill: vi.fn(),
signal: vi.fn(),
onData: () => {},
- onExit: () => {}
+ onExit: () => {},
+ dispose: vi.fn()
} as SubprocessHandle
}
diff --git a/src/main/daemon/terminal-host.test.ts b/src/main/daemon/terminal-host.test.ts
index 3dcf673dc..b571f43cd 100644
--- a/src/main/daemon/terminal-host.test.ts
+++ b/src/main/daemon/terminal-host.test.ts
@@ -1,3 +1,4 @@
+/* oxlint-disable max-lines */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { TerminalHost } from './terminal-host'
import type { SubprocessHandle } from './session'
@@ -20,6 +21,7 @@ function createMockSubprocess(): SubprocessHandle {
onExit(cb) {
onExitCb = cb
},
+ dispose: vi.fn(),
// Test helpers
get _onDataCb() {
return onDataCb
@@ -314,7 +316,7 @@ describe('TerminalHost', () => {
})
describe('dispose', () => {
- it('kills live subprocesses before disposing sessions', async () => {
+ it('force-kills live subprocesses and releases PTY fds on dispose', async () => {
await host.createOrAttach({
sessionId: 'session-1',
cols: 80,
@@ -323,7 +325,13 @@ describe('TerminalHost', () => {
})
host.dispose()
- expect(lastSubprocess.kill).toHaveBeenCalled()
+ // Why: for LIVE sessions, dispose() calls session.forceKillAndDisposeSubprocess()
+ // which sends SIGKILL (forceKill) and releases the ptmx fd (subprocess.dispose)
+ // synchronously — no longer relies on the 5s KILL_TIMEOUT_MS fallback.
+ // Exited sessions take the disposeSubprocess() path instead (see the test
+ // below). See docs/fix-pty-fd-leak.md.
+ expect(lastSubprocess.forceKill).toHaveBeenCalled()
+ expect(lastSubprocess.dispose).toHaveBeenCalled()
})
it('does not list exited sessions', async () => {
@@ -337,5 +345,39 @@ describe('TerminalHost', () => {
lastSubprocess._onExitCb?.(0)
expect(host.listSessions()).toEqual([])
})
+
+ it('skips forceKill on already-exited sessions to avoid recycled-pid SIGKILL', async () => {
+ // Why: after a session's subprocess has exited (onExit fired), proc.pid
+ // refers to a reaped child whose pid may have been recycled. Calling
+ // forceKillAndDisposeSubprocess() on an exited session would
+ // process.kill(recycled_pid, 'SIGKILL') — killing a stranger. Dispose
+ // must detect isAlive=false and use disposeSubprocess() (fd release only).
+ await host.createOrAttach({
+ sessionId: 'session-1',
+ cols: 80,
+ rows: 24,
+ streamClient: { onData: vi.fn(), onExit: vi.fn() }
+ })
+
+ // Simulate natural exit — session is retained in map until dispose.
+ lastSubprocess._onExitCb?.(0)
+
+ // Re-create another session so the map has BOTH a live and dead entry.
+ const exitedSub = lastSubprocess
+ await host.createOrAttach({
+ sessionId: 'session-2',
+ cols: 80,
+ rows: 24,
+ streamClient: { onData: vi.fn(), onExit: vi.fn() }
+ })
+ const liveSub = lastSubprocess
+
+ host.dispose()
+
+ expect(exitedSub.forceKill).not.toHaveBeenCalled()
+ expect(exitedSub.dispose).toHaveBeenCalled()
+ expect(liveSub.forceKill).toHaveBeenCalled()
+ expect(liveSub.dispose).toHaveBeenCalled()
+ })
})
})
diff --git a/src/main/daemon/terminal-host.ts b/src/main/daemon/terminal-host.ts
index 68a1bd62a..d8bddb2fe 100644
--- a/src/main/daemon/terminal-host.ts
+++ b/src/main/daemon/terminal-host.ts
@@ -18,6 +18,7 @@ export type CreateOrAttachOptions = {
* daemon path honors per-tab shell selection the same way LocalPtyProvider
* does. */
shellOverride?: string
+ terminalWindowsPowerShellImplementation?: 'auto' | 'powershell.exe' | 'pwsh.exe'
shellReadySupported?: boolean
streamClient: { onData: (data: string) => void; onExit: (code: number) => void }
}
@@ -39,6 +40,7 @@ export type TerminalHostOptions = {
env?: Record
command?: string
shellOverride?: string
+ terminalWindowsPowerShellImplementation?: 'auto' | 'powershell.exe' | 'pwsh.exe'
}) => SubprocessHandle
// Why: on graceful shutdown, the host writes final checkpoints for all live
// sessions before killing them. This bypasses the RPC round-trip — the daemon
@@ -95,7 +97,8 @@ export class TerminalHost {
cwd: opts.cwd,
env: opts.env,
command: opts.command,
- shellOverride: opts.shellOverride
+ shellOverride: opts.shellOverride,
+ terminalWindowsPowerShellImplementation: opts.terminalWindowsPowerShellImplementation
})
const session = new Session({
@@ -233,7 +236,19 @@ export class TerminalHost {
for (const [, session] of this.sessions) {
session.detachAllClients()
- session.kill()
+ // Why: live-vs-exited is load-bearing. For LIVE sessions we use
+ // forceKillAndDisposeSubprocess (SIGKILL + destroy) to reap stubborn
+ // children AND release the ptmx fd on the same tick, bypassing the 5s
+ // KILL_TIMEOUT_MS fallback that would otherwise outlive the daemon
+ // process. For sessions that have already exited but are still in the
+ // map, SIGKILL would target a reaped pid — on POSIX that pid can be
+ // recycled to an unrelated process, so we MUST only release the fd via
+ // disposeSubprocess() (destroy without kill). See docs/fix-pty-fd-leak.md.
+ if (session.isAlive) {
+ session.forceKillAndDisposeSubprocess()
+ } else {
+ session.disposeSubprocess()
+ }
}
this.sessions.clear()
this.killedTombstones.clear()
diff --git a/src/main/daemon/types.ts b/src/main/daemon/types.ts
index 1a6db0db0..a7fba8f42 100644
--- a/src/main/daemon/types.ts
+++ b/src/main/daemon/types.ts
@@ -68,6 +68,11 @@ export type CreateOrAttachRequest = {
* instead of defaulting to COMSPEC (which is always cmd.exe on Windows)
* or the hard-coded powershell.exe fallback. */
shellOverride?: string
+ /** Why: the UI keeps PowerShell as one shell family, but the runtime may
+ * need to substitute pwsh.exe for powershell.exe when the user selected
+ * PowerShell 7+. Forward the persisted implementation choice so the daemon
+ * PTY path resolves the same effective executable as LocalPtyProvider. */
+ terminalWindowsPowerShellImplementation?: 'auto' | 'powershell.exe' | 'pwsh.exe'
shellReadySupported?: boolean
}
}
@@ -224,6 +229,14 @@ export type SessionInfo = {
createdAt: number
}
+// Why: SessionInfo + source protocol version, so the Manage Sessions UI can
+// label legacy-backed sessions. Populated by the router/adapter at RPC time;
+// never transmitted over the daemon wire (daemon only speaks its own
+// protocol version and doesn't know about other versions).
+export type DaemonSessionInfo = SessionInfo & {
+ protocolVersion: number
+}
+
// ─── Events (Daemon → Client, on stream socket) ────────────────────
export type DataEvent = {
diff --git a/src/main/git/remove-worktree.test.ts b/src/main/git/remove-worktree.test.ts
index eecf11344..97f8eee82 100644
--- a/src/main/git/remove-worktree.test.ts
+++ b/src/main/git/remove-worktree.test.ts
@@ -1,17 +1,38 @@
+/* eslint-disable max-lines -- Why: remove/list/sparse cleanup tests share one git runner
+ mock harness, and splitting them would duplicate setup without a clearer boundary. */
+import type * as FsPromises from 'fs/promises'
import { beforeEach, describe, expect, it, vi } from 'vitest'
-const { gitExecFileAsyncMock, gitExecFileSyncMock } = vi.hoisted(() => ({
+const {
+ gitExecFileAsyncMock,
+ gitExecFileSyncMock,
+ translateWslOutputPathsMock,
+ statMock,
+ resolveGitDirMock
+} = vi.hoisted(() => ({
gitExecFileAsyncMock: vi.fn(),
- gitExecFileSyncMock: vi.fn()
+ gitExecFileSyncMock: vi.fn(),
+ translateWslOutputPathsMock: vi.fn((output: string) => output),
+ statMock: vi.fn(),
+ resolveGitDirMock: vi.fn()
}))
vi.mock('./runner', () => ({
gitExecFileAsync: gitExecFileAsyncMock,
gitExecFileSync: gitExecFileSyncMock,
- translateWslOutputPaths: (output: string) => output
+ translateWslOutputPaths: translateWslOutputPathsMock
}))
-import { removeWorktree } from './worktree'
+vi.mock('./status', () => ({
+ resolveGitDir: resolveGitDirMock
+}))
+
+vi.mock('fs/promises', async () => {
+ const actual = await vi.importActual('fs/promises')
+ return { ...actual, stat: statMock }
+})
+
+import { addSparseWorktree, listWorktrees, removeWorktree } from './worktree'
type MockResult = {
error?: Error
@@ -54,11 +75,19 @@ describe('removeWorktree', () => {
beforeEach(() => {
gitExecFileAsyncMock.mockReset()
gitExecFileSyncMock.mockReset()
+ translateWslOutputPathsMock.mockReset()
+ translateWslOutputPathsMock.mockImplementation((output: string) => output)
+ statMock.mockReset()
+ // Default: no worktree has a sparse-checkout config file. Tests that need
+ // sparse detection override this.
+ statMock.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ resolveGitDirMock.mockReset()
+ resolveGitDirMock.mockImplementation(async (worktreePath: string) => `${worktreePath}/.git`)
})
it('removes the worktree, prunes stale refs, and deletes its local branch', async () => {
mockGitCommands({
- 'git worktree list --porcelain': {
+ 'git worktree list --porcelain -z': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
@@ -68,7 +97,7 @@ HEAD def456
branch refs/heads/feature/test
`
},
- 'git worktree list --porcelain#2': {
+ 'git worktree list --porcelain -z#2': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
@@ -92,7 +121,7 @@ branch refs/heads/main
it('skips branch deletion when another worktree still points at the branch', async () => {
mockGitCommands({
- 'git worktree list --porcelain': {
+ 'git worktree list --porcelain -z': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
@@ -106,7 +135,7 @@ HEAD def456
branch refs/heads/feature/test
`
},
- 'git worktree list --porcelain#2': {
+ 'git worktree list --porcelain -z#2': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
@@ -125,7 +154,7 @@ branch refs/heads/feature/test
expect.arrayContaining([
'git worktree remove /repo-feature',
'git worktree prune',
- 'git worktree list --porcelain'
+ 'git worktree list --porcelain -z'
])
)
expect(calls).not.toContain('git branch -D feature/test')
@@ -134,7 +163,7 @@ branch refs/heads/feature/test
it('deletes the branch after prune removes stale sibling worktree entries', async () => {
mockGitCommands({
- 'git worktree list --porcelain': {
+ 'git worktree list --porcelain -z': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
@@ -149,7 +178,7 @@ branch refs/heads/feature/test
prunable gitdir file points to non-existent location
`
},
- 'git worktree list --porcelain#2': {
+ 'git worktree list --porcelain -z#2': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
@@ -172,7 +201,7 @@ branch refs/heads/main
it('passes --force before the worktree path when forced removal is requested', async () => {
mockGitCommands({
- 'git worktree list --porcelain': {
+ 'git worktree list --porcelain -z': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
@@ -182,7 +211,7 @@ HEAD def456
branch refs/heads/feature/test
`
},
- 'git worktree list --porcelain#2': {
+ 'git worktree list --porcelain -z#2': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
@@ -197,7 +226,7 @@ branch refs/heads/main
it('matches Windows worktree paths before deleting the branch', async () => {
mockGitCommands({
- 'git worktree list --porcelain': {
+ 'git worktree list --porcelain -z': {
stdout: `worktree C:/repo
HEAD abc123
branch refs/heads/main
@@ -207,7 +236,7 @@ HEAD def456
branch refs/heads/feature/test
`
},
- 'git worktree list --porcelain#2': {
+ 'git worktree list --porcelain -z#2': {
stdout: `worktree C:/repo
HEAD abc123
branch refs/heads/main
@@ -230,7 +259,7 @@ branch refs/heads/main
it('keeps removal successful when branch cleanup fails', async () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
mockGitCommands({
- 'git worktree list --porcelain': {
+ 'git worktree list --porcelain -z': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
@@ -240,7 +269,7 @@ HEAD def456
branch refs/heads/feature/test
`
},
- 'git worktree list --porcelain#2': {
+ 'git worktree list --porcelain -z#2': {
stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
@@ -262,3 +291,181 @@ branch refs/heads/main
warnSpy.mockRestore()
})
})
+
+describe('listWorktrees', () => {
+ beforeEach(() => {
+ gitExecFileAsyncMock.mockReset()
+ gitExecFileSyncMock.mockReset()
+ translateWslOutputPathsMock.mockReset()
+ translateWslOutputPathsMock.mockImplementation((output: string) => output)
+ statMock.mockReset()
+ // Default: no worktree has a sparse-checkout config file. Tests that need
+ // sparse detection override this.
+ statMock.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ resolveGitDirMock.mockReset()
+ resolveGitDirMock.mockImplementation(async (worktreePath: string) => `${worktreePath}/.git`)
+ })
+
+ it('translates parsed path fields from NUL-delimited porcelain output', async () => {
+ gitExecFileAsyncMock.mockResolvedValueOnce({
+ stdout:
+ 'worktree /home/me/repo\0HEAD abc123\0branch refs/heads/main\0\0' +
+ 'worktree /home/me/repo-feature\0HEAD def456\0branch refs/heads/feature/test\0sparse\0\0'
+ })
+ translateWslOutputPathsMock.mockImplementation((output: string) => {
+ expect(output).not.toContain('\0')
+ return output.replace('/home/me/', '\\\\wsl.localhost\\Ubuntu\\home\\me\\')
+ })
+
+ await expect(listWorktrees('\\\\wsl.localhost\\Ubuntu\\home\\me\\repo')).resolves.toEqual([
+ {
+ path: '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo',
+ head: 'abc123',
+ branch: 'refs/heads/main',
+ isBare: false,
+ isMainWorktree: true
+ },
+ {
+ path: '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo-feature',
+ head: 'def456',
+ branch: 'refs/heads/feature/test',
+ isBare: false,
+ isSparse: true,
+ isMainWorktree: false
+ }
+ ])
+ // Why: the non-sparse main worktree gets an fs probe of its sparse config
+ // file; the linked worktree short-circuits on the parsed `sparse` token and
+ // does not. Only one git subprocess runs regardless of worktree count.
+ expect(getGitCalls()).toEqual(['git worktree list --porcelain -z'])
+ expect(statMock).toHaveBeenCalledTimes(1)
+ expect(translateWslOutputPathsMock).toHaveBeenCalledTimes(2)
+ })
+
+ it('detects sparse checkout after translating paths when porcelain omits sparse token', async () => {
+ gitExecFileAsyncMock.mockImplementation((args: string[]) => {
+ if (args.join(' ') === 'worktree list --porcelain -z') {
+ return {
+ stdout:
+ 'worktree /home/me/repo\0HEAD abc123\0branch refs/heads/main\0\0' +
+ 'worktree /home/me/repo-feature\0HEAD def456\0branch refs/heads/feature/test\0\0',
+ stderr: ''
+ }
+ }
+ throw new Error(`Unexpected git call: ${args.join(' ')}`)
+ })
+ translateWslOutputPathsMock.mockImplementation((output: string) => {
+ expect(output).not.toContain('\0')
+ return output.replace('/home/me/', '\\\\wsl.localhost\\Ubuntu\\home\\me\\')
+ })
+ const featureWorktreePath = '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo-feature'
+ resolveGitDirMock.mockImplementation(async (worktreePath: string) =>
+ worktreePath === featureWorktreePath
+ ? `${featureWorktreePath}\\.git-worktrees\\feature`
+ : `${worktreePath}/.git`
+ )
+ statMock.mockImplementation(async (filePath: string) => {
+ if (filePath.includes('repo-feature') && filePath.includes('sparse-checkout')) {
+ return { isFile: () => true, size: 32 }
+ }
+ throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' })
+ })
+
+ const worktrees = await listWorktrees('\\\\wsl.localhost\\Ubuntu\\home\\me\\repo')
+
+ expect(worktrees).toEqual([
+ {
+ path: '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo',
+ head: 'abc123',
+ branch: 'refs/heads/main',
+ isBare: false,
+ isMainWorktree: true
+ },
+ {
+ path: '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo-feature',
+ head: 'def456',
+ branch: 'refs/heads/feature/test',
+ isBare: false,
+ isSparse: true,
+ isMainWorktree: false
+ }
+ ])
+ expect(resolveGitDirMock).toHaveBeenCalledWith(featureWorktreePath)
+ // Why: the detection path must not spawn a git subprocess per worktree —
+ // the perf regression in #1131 came from `git sparse-checkout list` firing
+ // on every poll.
+ expect(getGitCalls()).toEqual(['git worktree list --porcelain -z'])
+ })
+})
+
+describe('addSparseWorktree', () => {
+ beforeEach(() => {
+ gitExecFileAsyncMock.mockReset()
+ gitExecFileSyncMock.mockReset()
+ translateWslOutputPathsMock.mockReset()
+ translateWslOutputPathsMock.mockImplementation((output: string) => output)
+ statMock.mockReset()
+ // Default: no worktree has a sparse-checkout config file. Tests that need
+ // sparse detection override this.
+ statMock.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ resolveGitDirMock.mockReset()
+ resolveGitDirMock.mockImplementation(async (worktreePath: string) => `${worktreePath}/.git`)
+ })
+
+ it('separates sparse checkout directory operands from options', async () => {
+ gitExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' })
+
+ await addSparseWorktree('/repo', '/repo-feature', 'feature/test', ['-docs', 'src'])
+
+ expect(gitExecFileAsyncMock).toHaveBeenCalledWith(
+ ['sparse-checkout', 'set', '--', '-docs', 'src'],
+ { cwd: '/repo-feature' }
+ )
+ })
+
+ it('removes the worktree and deletes the created branch when sparse setup fails', async () => {
+ mockGitCommands({
+ 'git sparse-checkout set -- packages/web': {
+ error: new Error('sparse setup failed')
+ },
+ 'git worktree list --porcelain -z': {
+ stdout: `worktree /repo
+HEAD abc123
+branch refs/heads/main
+
+worktree /repo-feature
+HEAD def456
+branch refs/heads/feature/test
+`
+ },
+ 'git worktree list --porcelain -z#2': {
+ stdout: `worktree /repo
+HEAD abc123
+branch refs/heads/main
+`
+ }
+ })
+
+ await expect(
+ addSparseWorktree('/repo', '/repo-feature', 'feature/test', ['packages/web'])
+ ).rejects.toThrow('sparse setup failed')
+
+ const calls = getGitCalls()
+ expect(calls).toEqual(
+ expect.arrayContaining([
+ 'git worktree add --no-checkout -b feature/test /repo-feature',
+ 'git sparse-checkout init --cone',
+ 'git sparse-checkout set -- packages/web',
+ 'git worktree remove --force /repo-feature',
+ 'git worktree prune',
+ 'git branch -D feature/test'
+ ])
+ )
+ expectGitCallOrder(
+ calls,
+ 'git sparse-checkout set -- packages/web',
+ 'git worktree remove --force /repo-feature'
+ )
+ expectGitCallOrder(calls, 'git worktree prune', 'git branch -D feature/test')
+ })
+})
diff --git a/src/main/git/status.ts b/src/main/git/status.ts
index 4e62e94f0..8678cbe74 100644
--- a/src/main/git/status.ts
+++ b/src/main/git/status.ts
@@ -268,7 +268,7 @@ export async function detectConflictOperation(worktreePath: string): Promise {
+export async function resolveGitDir(worktreePath: string): Promise {
const dotGitPath = path.join(worktreePath, '.git')
try {
diff --git a/src/main/git/worktree.ts b/src/main/git/worktree.ts
index c109d168d..b77b89e33 100644
--- a/src/main/git/worktree.ts
+++ b/src/main/git/worktree.ts
@@ -1,6 +1,12 @@
-import { posix, win32 } from 'path'
+import { stat } from 'fs/promises'
+import { join, posix, win32 } from 'path'
import type { GitWorktreeInfo } from '../../shared/types'
import { gitExecFileAsync, translateWslOutputPaths } from './runner'
+import { resolveGitDir } from './status'
+
+type SparseWorktreeCreateError = Error & {
+ cleanupFailed?: boolean
+}
function normalizeLocalBranchRef(branch: string): string {
return branch.replace(/^refs\/heads\//, '')
@@ -29,21 +35,23 @@ function looksLikeWindowsPath(pathValue: string): boolean {
*/
export function parseWorktreeList(output: string): GitWorktreeInfo[] {
const worktrees: GitWorktreeInfo[] = []
- // [Fix]: Use /\r?\n\r?\n/ to handle both LF and CRLF (\r\n) line endings,
- // which are common when running git on Windows.
- const blocks = output.trim().split(/\r?\n\r?\n/)
+ const blocks = output.includes('\0')
+ ? parseNullDelimitedWorktreeBlocks(output)
+ : output
+ .trim()
+ .split(/\r?\n\r?\n/)
+ .map((block) => block.trim().split(/\r?\n/))
- for (const block of blocks) {
- if (!block.trim()) {
+ for (const lines of blocks) {
+ if (lines.length === 0) {
continue
}
- // [Fix]: Use /\r?\n/ to handle both LF and CRLF (\r\n) line endings.
- const lines = block.trim().split(/\r?\n/)
let path = ''
let head = ''
let branch = ''
let isBare = false
+ let isSparse = false
for (const line of lines) {
if (line.startsWith('worktree ')) {
@@ -54,12 +62,21 @@ export function parseWorktreeList(output: string): GitWorktreeInfo[] {
branch = line.slice('branch '.length)
} else if (line === 'bare') {
isBare = true
+ } else if (line === 'sparse') {
+ isSparse = true
}
}
if (path) {
// `git worktree list` always emits the main working tree first.
- worktrees.push({ path, head, branch, isBare, isMainWorktree: worktrees.length === 0 })
+ worktrees.push({
+ path,
+ head,
+ branch,
+ isBare,
+ ...(isSparse ? { isSparse } : {}),
+ isMainWorktree: worktrees.length === 0
+ })
}
}
@@ -71,14 +88,24 @@ export function parseWorktreeList(output: string): GitWorktreeInfo[] {
*/
export async function listWorktrees(repoPath: string): Promise {
try {
- const { stdout } = await gitExecFileAsync(['worktree', 'list', '--porcelain'], {
+ const { stdout } = await gitExecFileAsync(['worktree', 'list', '--porcelain', '-z'], {
cwd: repoPath
})
- // Why: when git runs inside WSL, worktree paths are Linux-native
- // (e.g. /home/user/repo). Translate them back to Windows UNC paths
- // so the rest of Orca can access them via Node fs APIs.
- const translated = translateWslOutputPaths(stdout, repoPath)
- return parseWorktreeList(translated)
+ // Why: WSL path translation is line-oriented, but `-z` porcelain output is
+ // NUL-delimited. Parse first so only complete path fields are translated.
+ const worktrees = parseWorktreeList(stdout).map((worktree) => {
+ const translatedPath = translateWorktreePath(worktree.path, repoPath)
+ return translatedPath === worktree.path ? worktree : { ...worktree, path: translatedPath }
+ })
+ return Promise.all(
+ worktrees.map(async (worktree) => {
+ if (worktree.isBare || worktree.isSparse) {
+ return worktree
+ }
+ const isSparse = await detectSparseCheckout(worktree.path)
+ return isSparse ? { ...worktree, isSparse } : worktree
+ })
+ )
} catch {
return []
}
@@ -96,7 +123,8 @@ export async function addWorktree(
worktreePath: string,
branch: string,
baseBranch?: string,
- refreshLocalBaseRef = false
+ refreshLocalBaseRef = false,
+ noCheckout = false
): Promise {
// Why: Some users want Orca-created worktrees to make plain commands like
// `git diff main...HEAD` work out of the box, while others do not want
@@ -152,13 +180,49 @@ export async function addWorktree(
}
}
- const args = ['worktree', 'add', '-b', branch, worktreePath]
+ const args = ['worktree', 'add']
+ if (noCheckout) {
+ args.push('--no-checkout')
+ }
+ args.push('-b', branch, worktreePath)
if (baseBranch) {
args.push(baseBranch)
}
await gitExecFileAsync(args, { cwd: repoPath })
}
+export async function addSparseWorktree(
+ repoPath: string,
+ worktreePath: string,
+ branch: string,
+ directories: string[],
+ baseBranch?: string,
+ refreshLocalBaseRef = false
+): Promise {
+ let created = false
+ try {
+ await addWorktree(repoPath, worktreePath, branch, baseBranch, refreshLocalBaseRef, true)
+ created = true
+ await gitExecFileAsync(['sparse-checkout', 'init', '--cone'], { cwd: worktreePath })
+ await gitExecFileAsync(['sparse-checkout', 'set', '--', ...directories], { cwd: worktreePath })
+ await gitExecFileAsync(['checkout', branch], { cwd: worktreePath })
+ } catch (error) {
+ const wrapped: SparseWorktreeCreateError =
+ error instanceof Error ? (error as SparseWorktreeCreateError) : new Error(String(error))
+ if (created) {
+ try {
+ await removeWorktree(repoPath, worktreePath, true)
+ } catch {
+ wrapped.cleanupFailed = true
+ // Why: the user needs to know that manual cleanup may be required —
+ // otherwise a half-created worktree silently lingers on disk.
+ wrapped.message = `${wrapped.message} (cleanup also failed — the partially created worktree at "${worktreePath}" may need manual removal)`
+ }
+ }
+ throw wrapped
+ }
+}
+
/**
* Remove a worktree.
*/
@@ -208,3 +272,57 @@ export async function removeWorktree(
)
}
}
+
+function parseNullDelimitedWorktreeBlocks(output: string): string[][] {
+ const blocks: string[][] = []
+ let current: string[] = []
+
+ for (const token of output.split('\0')) {
+ if (!token) {
+ if (current.length > 0) {
+ blocks.push(current)
+ current = []
+ }
+ continue
+ }
+ current.push(token)
+ }
+
+ if (current.length > 0) {
+ blocks.push(current)
+ }
+
+ return blocks
+}
+
+function translateWorktreePath(worktreePath: string, repoPath: string): string {
+ const prefix = 'worktree '
+ const translated = translateWslOutputPaths(`${prefix}${worktreePath}`, repoPath)
+ return translated.startsWith(prefix) ? translated.slice(prefix.length) : worktreePath
+}
+
+async function detectSparseCheckout(worktreePath: string): Promise {
+ // Why: `listWorktrees` runs on every 3-second git-status poll and on every
+ // worktree refresh, so this probe fires N times per poll for N worktrees.
+ // The previous `git sparse-checkout list` subprocess made that N*poll extra
+ // git processes, which regressed app responsiveness on machines with many
+ // worktrees (see PR #1131 revert in #1290). A single fs.stat on the
+ // per-worktree sparse-checkout config file is ~two orders of magnitude
+ // cheaper and has the same truthiness semantics: Git writes this file when
+ // sparse checkout is enabled for the worktree and does not write it
+ // otherwise.
+ //
+ // Why per-worktree gitdir and not `/.git/info/sparse-checkout`:
+ // linked worktrees have a `.git` file that points at
+ // `/.git/worktrees/`, and that is where Git stores the
+ // worktree-local sparse-checkout config. `core.sparseCheckout` itself is
+ // shared across all worktrees, so the presence of the config file is the
+ // correct per-worktree signal.
+ try {
+ const gitDir = await resolveGitDir(worktreePath)
+ const stats = await stat(join(gitDir, 'info', 'sparse-checkout'))
+ return stats.isFile() && stats.size > 0
+ } catch {
+ return false
+ }
+}
diff --git a/src/main/github/client-issue-source.test.ts b/src/main/github/client-issue-source.test.ts
index 449449e1d..051f9ffeb 100644
--- a/src/main/github/client-issue-source.test.ts
+++ b/src/main/github/client-issue-source.test.ts
@@ -1,3 +1,7 @@
+/* eslint-disable max-lines -- Why: the issue-source test suite covers the
+heuristic split (#1076), the partial-failure envelope (feature 1), and the
+three-state preference matrix (feature 2) as one surface so a regression in
+any of them blocks the same merge gate. */
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type * as GhUtils from './gh-utils'
@@ -6,6 +10,8 @@ const {
ghExecFileAsyncMock,
getOwnerRepoMock,
getIssueOwnerRepoMock,
+ getOwnerRepoForRemoteMock,
+ resolveIssueSourceMock,
acquireMock,
releaseMock
} = vi.hoisted(() => ({
@@ -13,6 +19,8 @@ const {
ghExecFileAsyncMock: vi.fn(),
getOwnerRepoMock: vi.fn(),
getIssueOwnerRepoMock: vi.fn(),
+ getOwnerRepoForRemoteMock: vi.fn(),
+ resolveIssueSourceMock: vi.fn(),
acquireMock: vi.fn(),
releaseMock: vi.fn()
}))
@@ -25,6 +33,8 @@ vi.mock('./gh-utils', async () => {
ghExecFileAsync: ghExecFileAsyncMock,
getOwnerRepo: getOwnerRepoMock,
getIssueOwnerRepo: getIssueOwnerRepoMock,
+ getOwnerRepoForRemote: getOwnerRepoForRemoteMock,
+ resolveIssueSource: resolveIssueSourceMock,
acquire: acquireMock,
release: releaseMock,
_resetOwnerRepoCache: vi.fn()
@@ -39,9 +49,24 @@ describe('GitHub issue source split', () => {
ghExecFileAsyncMock.mockReset()
getOwnerRepoMock.mockReset()
getIssueOwnerRepoMock.mockReset()
+ getOwnerRepoForRemoteMock.mockReset()
+ resolveIssueSourceMock.mockReset()
acquireMock.mockReset()
releaseMock.mockReset()
acquireMock.mockResolvedValue(undefined)
+ // Why: default the preference-aware resolver to 'auto' semantics so the
+ // pre-existing test cases (which don't think about preference at all)
+ // still pass. `listWorkItems` now calls `resolveIssueSource` instead of
+ // `getIssueOwnerRepo` directly — we delegate back to the single-call
+ // mock to preserve the one-fetch-per-test invariant each test sets up.
+ resolveIssueSourceMock.mockImplementation(async () => ({
+ source: await getIssueOwnerRepoMock(),
+ fellBack: false
+ }))
+ // Default the upstream-candidate lookup to null so existing tests that
+ // only mock `getIssueOwnerRepo` + `getOwnerRepo` don't need to think
+ // about it. Tests that care set it explicitly.
+ getOwnerRepoForRemoteMock.mockResolvedValue(null)
_resetOwnerRepoCache()
})
@@ -223,6 +248,59 @@ describe('GitHub issue source split', () => {
expect(item?.type).toBe('pr')
})
+ it('surfaces a 403 from upstream issues through the listWorkItems envelope', async () => {
+ // Why: parent design doc §3 / acceptance criterion 2 — the IPC envelope
+ // must carry a classified error for the failing side so the renderer can
+ // swap the empty-state for a retryable banner. `sources` must stay
+ // populated so the banner copy can name the repo that failed.
+ getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
+ getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' })
+ ghExecFileAsyncMock
+ .mockRejectedValueOnce(new Error('HTTP 403: Resource not accessible by integration'))
+ .mockResolvedValueOnce({ stdout: '[]' })
+
+ const result = await listWorkItems('/repo-root', 10)
+
+ expect(result.items).toEqual([])
+ expect(result.sources).toMatchObject({
+ issues: { owner: 'stablyai', repo: 'orca' },
+ prs: { owner: 'fork', repo: 'orca' }
+ })
+ expect(result.errors?.issues?.type).toBe('permission_denied')
+ })
+
+ it('returns partial results when upstream issues fail but origin PRs succeed', async () => {
+ // Why: parent design doc §2 partial-failure rule — a failing source must
+ // not zero out the succeeding source. The UI renders origin PRs with a
+ // banner above the list, not an empty state. Ensures the IPC shape
+ // carries both the successful items and the error for the failing side.
+ getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
+ getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' })
+ ghExecFileAsyncMock
+ .mockRejectedValueOnce(new Error('HTTP 403: Resource not accessible by integration'))
+ .mockResolvedValueOnce({
+ stdout: JSON.stringify([
+ {
+ number: 42,
+ title: 'Fork PR',
+ state: 'open',
+ html_url: 'https://github.com/fork/orca/pull/42',
+ labels: [],
+ updated_at: '2026-03-31T00:00:00Z',
+ user: { login: 'octocat' },
+ draft: false,
+ head: { ref: 'feature' },
+ base: { ref: 'main' }
+ }
+ ])
+ })
+
+ const result = await listWorkItems('/repo-root', 10)
+
+ expect(result.items.map((i) => i.id)).toEqual(['pr:42'])
+ expect(result.errors?.issues?.type).toBe('permission_denied')
+ })
+
it('raw number lookup does not fall through on transient upstream errors', async () => {
// Why: with issue source split, a non-404 upstream failure must not silently
// route to origin's PR #N — that would return an unrelated item.
@@ -235,4 +313,170 @@ describe('GitHub issue source split', () => {
expect(getOwnerRepoMock).not.toHaveBeenCalled()
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1)
})
+
+ describe('per-repo issue-source preference', () => {
+ // Why: 3 preference states × 2 remote-topology states = 6 cases per the
+ // design doc §9. These tests isolate `listWorkItems` against a mocked
+ // `resolveIssueSource` to verify the preference is threaded all the way
+ // to the gh call and that `fellBack` propagates into the envelope.
+
+ it("preference='auto' + upstream exists → queries upstream", async () => {
+ resolveIssueSourceMock.mockResolvedValueOnce({
+ source: { owner: 'stablyai', repo: 'orca' },
+ fellBack: false
+ })
+ getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' })
+ ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '[]' }).mockResolvedValueOnce({
+ stdout: '[]'
+ })
+
+ const result = await listWorkItems('/repo-root', 10, undefined, undefined, 'auto')
+
+ expect(resolveIssueSourceMock).toHaveBeenCalledWith('/repo-root', 'auto')
+ expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
+ 1,
+ [
+ 'api',
+ '--cache',
+ '120s',
+ 'repos/stablyai/orca/issues?per_page=10&state=open&sort=updated&direction=desc'
+ ],
+ { cwd: '/repo-root' }
+ )
+ expect(result.issueSourceFellBack).toBeUndefined()
+ })
+
+ it("preference='auto' + no upstream → queries origin", async () => {
+ resolveIssueSourceMock.mockResolvedValueOnce({
+ source: { owner: 'solo', repo: 'orca' },
+ fellBack: false
+ })
+ getOwnerRepoMock.mockResolvedValueOnce({ owner: 'solo', repo: 'orca' })
+ ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '[]' }).mockResolvedValueOnce({
+ stdout: '[]'
+ })
+
+ await listWorkItems('/repo-root', 10, undefined, undefined, 'auto')
+
+ expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
+ 1,
+ [
+ 'api',
+ '--cache',
+ '120s',
+ 'repos/solo/orca/issues?per_page=10&state=open&sort=updated&direction=desc'
+ ],
+ { cwd: '/repo-root' }
+ )
+ })
+
+ it("preference='upstream' + upstream exists → queries upstream", async () => {
+ resolveIssueSourceMock.mockResolvedValueOnce({
+ source: { owner: 'stablyai', repo: 'orca' },
+ fellBack: false
+ })
+ getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' })
+ ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '[]' }).mockResolvedValueOnce({
+ stdout: '[]'
+ })
+
+ const result = await listWorkItems('/repo-root', 10, undefined, undefined, 'upstream')
+
+ expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
+ 1,
+ expect.arrayContaining([
+ 'repos/stablyai/orca/issues?per_page=10&state=open&sort=updated&direction=desc'
+ ]),
+ { cwd: '/repo-root' }
+ )
+ expect(result.issueSourceFellBack).toBeUndefined()
+ })
+
+ it("preference='upstream' + no upstream → falls back to origin with fellBack=true", async () => {
+ resolveIssueSourceMock.mockResolvedValueOnce({
+ source: { owner: 'solo', repo: 'orca' },
+ fellBack: true
+ })
+ getOwnerRepoMock.mockResolvedValueOnce({ owner: 'solo', repo: 'orca' })
+ ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '[]' }).mockResolvedValueOnce({
+ stdout: '[]'
+ })
+
+ const result = await listWorkItems('/repo-root', 10, undefined, undefined, 'upstream')
+
+ expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
+ 1,
+ expect.arrayContaining([
+ 'repos/solo/orca/issues?per_page=10&state=open&sort=updated&direction=desc'
+ ]),
+ { cwd: '/repo-root' }
+ )
+ expect(result.issueSourceFellBack).toBe(true)
+ })
+
+ it("preference='origin' + upstream exists → queries origin (not upstream)", async () => {
+ resolveIssueSourceMock.mockResolvedValueOnce({
+ source: { owner: 'fork', repo: 'orca' },
+ fellBack: false
+ })
+ getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' })
+ ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '[]' }).mockResolvedValueOnce({
+ stdout: '[]'
+ })
+
+ await listWorkItems('/repo-root', 10, undefined, undefined, 'origin')
+
+ expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
+ 1,
+ expect.arrayContaining([
+ 'repos/fork/orca/issues?per_page=10&state=open&sort=updated&direction=desc'
+ ]),
+ { cwd: '/repo-root' }
+ )
+ })
+
+ it("preference='origin' + no upstream → queries origin", async () => {
+ resolveIssueSourceMock.mockResolvedValueOnce({
+ source: { owner: 'solo', repo: 'orca' },
+ fellBack: false
+ })
+ getOwnerRepoMock.mockResolvedValueOnce({ owner: 'solo', repo: 'orca' })
+ ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '[]' }).mockResolvedValueOnce({
+ stdout: '[]'
+ })
+
+ await listWorkItems('/repo-root', 10, undefined, undefined, 'origin')
+
+ expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
+ 1,
+ expect.arrayContaining([
+ 'repos/solo/orca/issues?per_page=10&state=open&sort=updated&direction=desc'
+ ]),
+ { cwd: '/repo-root' }
+ )
+ })
+
+ it('surfaces upstreamCandidate in sources regardless of effective preference', async () => {
+ // Why: the renderer selector needs to keep rendering after the user picks
+ // 'origin'. That requires the envelope to carry the raw upstream even
+ // when `sources.issues` has collapsed onto origin.
+ resolveIssueSourceMock.mockResolvedValueOnce({
+ source: { owner: 'fork', repo: 'orca' },
+ fellBack: false
+ })
+ getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' })
+ getOwnerRepoForRemoteMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
+ ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '[]' }).mockResolvedValueOnce({
+ stdout: '[]'
+ })
+
+ const result = await listWorkItems('/repo-root', 10, undefined, undefined, 'origin')
+
+ expect(result.sources).toEqual({
+ issues: { owner: 'fork', repo: 'orca' },
+ prs: { owner: 'fork', repo: 'orca' },
+ upstreamCandidate: { owner: 'stablyai', repo: 'orca' }
+ })
+ })
+ })
})
diff --git a/src/main/github/client-work-items.test.ts b/src/main/github/client-work-items.test.ts
index 72ddfb494..3dadca518 100644
--- a/src/main/github/client-work-items.test.ts
+++ b/src/main/github/client-work-items.test.ts
@@ -1,3 +1,6 @@
+/* eslint-disable max-lines -- Why: work-items coverage stays in one file so
+the fan-out mock plumbing (issue + PR gh calls, allSettled handling) does
+not drift across split files. */
import { beforeEach, describe, expect, it, vi } from 'vitest'
const {
@@ -5,6 +8,8 @@ const {
ghExecFileAsyncMock,
getOwnerRepoMock,
getIssueOwnerRepoMock,
+ getOwnerRepoForRemoteMock,
+ resolveIssueSourceMock,
gitExecFileAsyncMock,
acquireMock,
releaseMock
@@ -13,6 +18,8 @@ const {
ghExecFileAsyncMock: vi.fn(),
getOwnerRepoMock: vi.fn(),
getIssueOwnerRepoMock: vi.fn(),
+ getOwnerRepoForRemoteMock: vi.fn(),
+ resolveIssueSourceMock: vi.fn(),
gitExecFileAsyncMock: vi.fn(),
acquireMock: vi.fn(),
releaseMock: vi.fn()
@@ -23,9 +30,13 @@ vi.mock('./gh-utils', () => ({
ghExecFileAsync: ghExecFileAsyncMock,
getOwnerRepo: getOwnerRepoMock,
getIssueOwnerRepo: getIssueOwnerRepoMock,
+ getOwnerRepoForRemote: getOwnerRepoForRemoteMock,
+ resolveIssueSource: resolveIssueSourceMock,
acquire: acquireMock,
release: releaseMock,
- _resetOwnerRepoCache: vi.fn()
+ _resetOwnerRepoCache: vi.fn(),
+ classifyGhError: (stderr: string) => ({ type: 'unknown', message: stderr }),
+ classifyListIssuesError: (stderr: string) => ({ type: 'unknown', message: stderr })
}))
vi.mock('../git/runner', () => ({
@@ -40,10 +51,20 @@ describe('listWorkItems', () => {
ghExecFileAsyncMock.mockReset()
getOwnerRepoMock.mockReset()
getIssueOwnerRepoMock.mockReset()
+ getOwnerRepoForRemoteMock.mockReset()
+ resolveIssueSourceMock.mockReset()
gitExecFileAsyncMock.mockReset()
acquireMock.mockReset()
releaseMock.mockReset()
acquireMock.mockResolvedValue(undefined)
+ // Why: preference-aware `listWorkItems` calls `resolveIssueSource`.
+ // Route through the same `getIssueOwnerRepoMock` so existing tests that
+ // only set up `getIssueOwnerRepoMock` continue to work.
+ resolveIssueSourceMock.mockImplementation(async () => ({
+ source: await getIssueOwnerRepoMock(),
+ fellBack: false
+ }))
+ getOwnerRepoForRemoteMock.mockResolvedValue(null)
_resetOwnerRepoCache()
})
@@ -80,7 +101,11 @@ describe('listWorkItems', () => {
}
])
})
- const items = await listWorkItems('/repo-root', 10, 'assignee:@me')
+ const { items, sources } = await listWorkItems('/repo-root', 10, 'assignee:@me')
+ expect(sources).toMatchObject({
+ issues: { owner: 'acme', repo: 'widgets' },
+ prs: { owner: 'acme', repo: 'widgets' }
+ })
expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith(
1,
[
@@ -160,7 +185,7 @@ describe('listWorkItems', () => {
}
])
})
- const items = await listWorkItems('/repo-root', 10, 'is:pr is:draft')
+ const { items } = await listWorkItems('/repo-root', 10, 'is:pr is:draft')
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1)
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(
[
@@ -246,7 +271,7 @@ describe('listWorkItems', () => {
}
])
})
- const items = await listWorkItems('/repo-root', 10, 'is:open')
+ const { items } = await listWorkItems('/repo-root', 10, 'is:open')
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(
[
'issue',
diff --git a/src/main/github/client.ts b/src/main/github/client.ts
index bbd8a1f91..ebf866f32 100644
--- a/src/main/github/client.ts
+++ b/src/main/github/client.ts
@@ -1,6 +1,9 @@
/* eslint-disable max-lines -- Why: co-locating all GitHub client functions keeps the
concurrency acquire/release pattern and error handling consistent across operations. */
import type {
+ ClassifiedError,
+ IssueSourcePreference,
+ ListWorkItemsResult,
PRInfo,
PRMergeableState,
PRCheckDetail,
@@ -20,7 +23,10 @@ import {
release,
getOwnerRepo,
getIssueOwnerRepo,
+ getOwnerRepoForRemote,
+ resolveIssueSource,
classifyGhError,
+ classifyListIssuesError,
type OwnerRepo
} from './gh-utils'
export { _resetOwnerRepoCache } from './gh-utils'
@@ -341,14 +347,27 @@ function buildWorkItemListArgs(args: {
return out
}
+// Why: internal shape shared by listRecentWorkItems / listQueriedWorkItems so
+// listWorkItems can lift per-side errors into the IPC envelope. The issue-side
+// error is the specific new class of silent wrongness introduced by #1076 —
+// PR-side errors existed before and are explicitly out of scope for this
+// feature per the parent design doc §6.
+type PartialWorkItemsResult = {
+ items: MainWorkItem[]
+ issuesError?: ClassifiedError
+}
+
async function listRecentWorkItems(
repoPath: string,
issueOwnerRepo: OwnerRepo | null,
prOwnerRepo: OwnerRepo | null,
limit: number
-): Promise {
+): Promise {
if (issueOwnerRepo || prOwnerRepo) {
- const [issuesResult, prsResult] = await Promise.all([
+ // Why: allSettled so a 403 on upstream issues doesn't zero out the origin
+ // PR half — the UI renders partial results plus a banner for the failing
+ // side, matching the parent design doc's partial-failure rule (§2).
+ const [issuesSettled, prsSettled] = await Promise.allSettled([
issueOwnerRepo
? ghExecFileAsync(
[
@@ -397,20 +416,61 @@ async function listRecentWorkItems(
)
])
- const issues = (JSON.parse(issuesResult.stdout) as Record[])
- // Why: the GitHub issues REST endpoint also returns pull requests with a
- // `pull_request` marker. The new-workspace task picker needs distinct
- // issue vs PR buckets, so drop PR-shaped issue rows here before merging.
- .filter((item) => !('pull_request' in item))
- .map(mapIssueWorkItem)
+ let issues: MainWorkItem[] = []
+ let issuesError: ClassifiedError | undefined
+ if (issuesSettled.status === 'fulfilled') {
+ issues = (JSON.parse(issuesSettled.value.stdout) as Record[])
+ // Why: the GitHub issues REST endpoint also returns pull requests with a
+ // `pull_request` marker. The new-workspace task picker needs distinct
+ // issue vs PR buckets, so drop PR-shaped issue rows here before merging.
+ .filter((item) => !('pull_request' in item))
+ .map(mapIssueWorkItem)
+ } else {
+ const stderr =
+ issuesSettled.reason instanceof Error
+ ? issuesSettled.reason.message
+ : String(issuesSettled.reason)
+ issuesError = classifyListIssuesError(stderr)
+ }
- const prs = (JSON.parse(prsResult.stdout) as Record[]).map((item) =>
- mapPullRequestWorkItem(item, prOwnerRepo?.owner ?? null)
- )
+ let prs: MainWorkItem[] = []
+ if (prsSettled.status === 'fulfilled') {
+ prs = (JSON.parse(prsSettled.value.stdout) as Record[]).map((item) =>
+ mapPullRequestWorkItem(item, prOwnerRepo?.owner ?? null)
+ )
+ } else {
+ // Why: PR-side failures must preserve the pre-diff behavior of
+ // Promise.all by re-throwing so the rejection propagates up through
+ // listWorkItems to the renderer's cross-repo aggregator (which counts
+ // the repo as failed). This feature is scoped to the issue-side silent
+ // wrongness from #1076; PR errors must not be silently swallowed here.
+ // Why: if the issue side ALSO failed, the classified issuesError would
+ // otherwise be silently dropped when we throw the PR reason. Log it so
+ // debugging both-sides-failed scenarios (e.g. 403 on both endpoints)
+ // isn't blind to the issue-side classification.
+ if (issuesError) {
+ console.warn(
+ 'listRecentWorkItems: both issue and PR sides failed; issuesError was classified:',
+ issuesError.type,
+ issuesError.message
+ )
+ }
+ throw prsSettled.reason
+ }
- return sortWorkItemsByUpdatedAt([...issues, ...prs]).slice(0, limit)
+ return {
+ items: sortWorkItemsByUpdatedAt([...issues, ...prs]).slice(0, limit),
+ issuesError
+ }
}
+ // Why: the fallback path (non-GitHub remote — neither issueOwnerRepo nor
+ // prOwnerRepo resolved) intentionally stays on Promise.all rather than the
+ // Promise.allSettled + per-side classification used above. There are no
+ // `sources` to surface on this branch and nothing for the partial-failure
+ // banner to render, so a single-side failure here means the whole call is
+ // effectively unusable for the feature — reject-all matches reality. If
+ // non-GitHub remotes ever grow source metadata, revisit this symmetry.
const [issuesResult, prsResult] = await Promise.all([
ghExecFileAsync(
[
@@ -447,7 +507,9 @@ async function listRecentWorkItems(
mapPullRequestWorkItem(item, null)
)
- return sortWorkItemsByUpdatedAt([...issues, ...prs]).slice(0, limit)
+ return {
+ items: sortWorkItemsByUpdatedAt([...issues, ...prs]).slice(0, limit)
+ }
}
async function listQueriedWorkItems(
@@ -457,67 +519,82 @@ async function listQueriedWorkItems(
query: ParsedTaskQuery,
limit: number,
before?: string
-): Promise {
- const fetchers: Promise[] = []
+): Promise {
const issueScope = query.scope !== 'pr'
const prScope = query.scope !== 'issue'
- if (issueScope) {
- fetchers.push(
- (async () => {
- const args = buildWorkItemListArgs({
- kind: 'issue',
- ownerRepo: issueOwnerRepo,
- limit,
- query,
- before
- })
- try {
- const { stdout } = await ghExecFileAsync(args, { cwd: repoPath })
- return (JSON.parse(stdout) as Record[]).map(mapIssueWorkItem)
- } catch {
- return []
- }
- })()
- )
- }
+ // Why: run the issue and PR fetches in parallel but surface the
+ // issue-side error separately so the IPC envelope can carry it up. PR-side
+ // failures retain the prior swallow-and-log behavior per parent doc §6.
+ const issueFetch = (async (): Promise => {
+ if (!issueScope) {
+ return { items: [] }
+ }
+ const args = buildWorkItemListArgs({
+ kind: 'issue',
+ ownerRepo: issueOwnerRepo,
+ limit,
+ query,
+ before
+ })
+ try {
+ const { stdout } = await ghExecFileAsync(args, { cwd: repoPath })
+ return {
+ items: (JSON.parse(stdout) as Record[]).map(mapIssueWorkItem)
+ }
+ } catch (err) {
+ const stderr = err instanceof Error ? err.message : String(err)
+ return { items: [], issuesError: classifyListIssuesError(stderr) }
+ }
+ })()
- if (prScope) {
- fetchers.push(
- (async () => {
- const args = buildWorkItemListArgs({
- kind: 'pr',
- ownerRepo: prOwnerRepo,
- limit,
- query,
- before
- })
- try {
- const { stdout } = await ghExecFileAsync(args, { cwd: repoPath })
- return (JSON.parse(stdout) as Record[]).map((item) =>
- mapPullRequestWorkItem(item, prOwnerRepo?.owner ?? null)
- )
- } catch {
- return []
- }
- })()
- )
- }
+ const prFetch = (async (): Promise => {
+ if (!prScope) {
+ return []
+ }
+ const args = buildWorkItemListArgs({
+ kind: 'pr',
+ ownerRepo: prOwnerRepo,
+ limit,
+ query,
+ before
+ })
+ try {
+ const { stdout } = await ghExecFileAsync(args, { cwd: repoPath })
+ return (JSON.parse(stdout) as Record[]).map((item) =>
+ mapPullRequestWorkItem(item, prOwnerRepo?.owner ?? null)
+ )
+ } catch (err) {
+ console.warn('listQueriedWorkItems PRs partial failure:', err)
+ return []
+ }
+ })()
- const results = await Promise.all(fetchers)
- return sortWorkItemsByUpdatedAt(results.flat()).slice(0, limit)
+ const [issueResult, prItems] = await Promise.all([issueFetch, prFetch])
+ return {
+ items: sortWorkItemsByUpdatedAt([...issueResult.items, ...prItems]).slice(0, limit),
+ issuesError: issueResult.issuesError
+ }
}
export async function listWorkItems(
repoPath: string,
limit = 24,
query?: string,
- before?: string
-): Promise {
- const [issueOwnerRepo, prOwnerRepo] = await Promise.all([
- getIssueOwnerRepo(repoPath),
- getOwnerRepo(repoPath)
+ before?: string,
+ preference?: IssueSourcePreference
+): Promise> {
+ // Why: resolve the raw upstream candidate alongside the preference-aware
+ // issue source. The selector needs to know whether an upstream remote
+ // *exists* to decide whether to render — independent of whether the user
+ // has picked 'origin' (which would otherwise make `sources.issues` equal
+ // origin and hide the selector permanently).
+ const [issueResolved, prOwnerRepo, upstreamCandidate] = await Promise.all([
+ resolveIssueSource(repoPath, preference),
+ getOwnerRepo(repoPath),
+ getOwnerRepoForRemote(repoPath, 'upstream')
])
+ const issueOwnerRepo = issueResolved.source
const trimmedQuery = query?.trim() ?? ''
await acquire()
try {
@@ -525,19 +602,28 @@ export async function listWorkItems(
// count this repo as failed and surface the partial-failure banner. A
// catch-all here would make an auth/network failure indistinguishable from
// an empty result and silently under-report per-repo failures.
- if (!trimmedQuery) {
- return await listRecentWorkItems(repoPath, issueOwnerRepo, prOwnerRepo, limit)
- }
+ const partial = !trimmedQuery
+ ? await listRecentWorkItems(repoPath, issueOwnerRepo, prOwnerRepo, limit)
+ : await listQueriedWorkItems(
+ repoPath,
+ issueOwnerRepo,
+ prOwnerRepo,
+ parseTaskQuery(trimmedQuery),
+ limit,
+ before
+ )
- const parsedQuery = parseTaskQuery(trimmedQuery)
- return await listQueriedWorkItems(
- repoPath,
- issueOwnerRepo,
- prOwnerRepo,
- parsedQuery,
- limit,
- before
- )
+ const errors = partial.issuesError ? { issues: partial.issuesError } : undefined
+ return {
+ items: partial.items,
+ sources: {
+ issues: issueOwnerRepo,
+ prs: prOwnerRepo,
+ upstreamCandidate: upstreamCandidate ?? null
+ },
+ ...(errors ? { errors } : {}),
+ ...(issueResolved.fellBack ? { issueSourceFellBack: true } : {})
+ }
} finally {
release()
}
@@ -631,11 +717,16 @@ function defaultOpenWorkItemQuery(): ParsedTaskQuery {
// Why: uses GitHub's search API to get total_count without fetching items.
// This powers the pagination bar so the user sees total pages upfront.
// Cached for 120s to avoid burning the search rate limit (30 req/min).
-export async function countWorkItems(repoPath: string, query?: string): Promise {
- const [issueOwnerRepo, prOwnerRepo] = await Promise.all([
- getIssueOwnerRepo(repoPath),
+export async function countWorkItems(
+ repoPath: string,
+ query?: string,
+ preference?: IssueSourcePreference
+): Promise {
+ const [issueResolved, prOwnerRepo] = await Promise.all([
+ resolveIssueSource(repoPath, preference),
getOwnerRepo(repoPath)
])
+ const issueOwnerRepo = issueResolved.source
const ownerRepo = prOwnerRepo ?? issueOwnerRepo
if (!ownerRepo) {
return 0
diff --git a/src/main/github/gh-utils.test.ts b/src/main/github/gh-utils.test.ts
index afb73e833..8e1b8d839 100644
--- a/src/main/github/gh-utils.test.ts
+++ b/src/main/github/gh-utils.test.ts
@@ -11,9 +11,12 @@ vi.mock('../git/runner', () => ({
import {
_resetOwnerRepoCache,
+ classifyGhError,
+ classifyListIssuesError,
getIssueOwnerRepo,
getOwnerRepo,
- parseGitHubOwnerRepo
+ parseGitHubOwnerRepo,
+ resolveIssueSource
} from './gh-utils'
describe('github owner/repo resolution', () => {
@@ -83,3 +86,113 @@ describe('github owner/repo resolution', () => {
await expect(getIssueOwnerRepo('/repo')).resolves.toEqual({ owner: 'stablyai', repo: 'orca' })
})
})
+
+describe('resolveIssueSource', () => {
+ beforeEach(() => {
+ gitExecFileAsyncMock.mockReset()
+ _resetOwnerRepoCache()
+ })
+
+ it("'auto' + upstream exists → upstream, fellBack=false", async () => {
+ gitExecFileAsyncMock.mockResolvedValueOnce({
+ stdout: 'git@github.com:stablyai/orca.git\n'
+ })
+
+ await expect(resolveIssueSource('/repo', 'auto')).resolves.toEqual({
+ source: { owner: 'stablyai', repo: 'orca' },
+ fellBack: false
+ })
+ })
+
+ it("'auto' + no upstream → origin, fellBack=false", async () => {
+ gitExecFileAsyncMock
+ .mockResolvedValueOnce({ stdout: 'git@example.com:stablyai/orca.git\n' })
+ .mockResolvedValueOnce({ stdout: 'git@github.com:solo/orca.git\n' })
+
+ await expect(resolveIssueSource('/repo', 'auto')).resolves.toEqual({
+ source: { owner: 'solo', repo: 'orca' },
+ fellBack: false
+ })
+ })
+
+ it("'upstream' + upstream exists → upstream, fellBack=false", async () => {
+ gitExecFileAsyncMock.mockResolvedValueOnce({
+ stdout: 'git@github.com:stablyai/orca.git\n'
+ })
+
+ await expect(resolveIssueSource('/repo', 'upstream')).resolves.toEqual({
+ source: { owner: 'stablyai', repo: 'orca' },
+ fellBack: false
+ })
+ })
+
+ it("'upstream' + no upstream remote → origin, fellBack=true", async () => {
+ // No upstream remote configured — the first call fails.
+ gitExecFileAsyncMock
+ .mockRejectedValueOnce(new Error('fatal: No such remote'))
+ .mockResolvedValueOnce({ stdout: 'git@github.com:solo/orca.git\n' })
+
+ await expect(resolveIssueSource('/repo', 'upstream')).resolves.toEqual({
+ source: { owner: 'solo', repo: 'orca' },
+ fellBack: true
+ })
+ })
+
+ it("'origin' + upstream exists → origin (ignores upstream), fellBack=false", async () => {
+ // Only one gh call should happen — origin. Upstream is never consulted.
+ gitExecFileAsyncMock.mockResolvedValueOnce({
+ stdout: 'git@github.com:fork/orca.git\n'
+ })
+
+ await expect(resolveIssueSource('/repo', 'origin')).resolves.toEqual({
+ source: { owner: 'fork', repo: 'orca' },
+ fellBack: false
+ })
+ expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1)
+ expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], {
+ cwd: '/repo'
+ })
+ })
+
+ it("'origin' + no upstream → origin, fellBack=false", async () => {
+ gitExecFileAsyncMock.mockResolvedValueOnce({
+ stdout: 'git@github.com:solo/orca.git\n'
+ })
+
+ await expect(resolveIssueSource('/repo', 'origin')).resolves.toEqual({
+ source: { owner: 'solo', repo: 'orca' },
+ fellBack: false
+ })
+ })
+
+ it('undefined preference is treated identically to auto', async () => {
+ gitExecFileAsyncMock.mockResolvedValueOnce({
+ stdout: 'git@github.com:stablyai/orca.git\n'
+ })
+
+ await expect(resolveIssueSource('/repo', undefined)).resolves.toEqual({
+ source: { owner: 'stablyai', repo: 'orca' },
+ fellBack: false
+ })
+ })
+})
+
+describe('gh error classification', () => {
+ // Why: a fork with Issues turned off triggers `gh issue list` stderr
+ // "the '' repository has disabled issues". Without a dedicated branch
+ // the raw "Command failed: gh issue list …" line leaks into the Tasks banner
+ // via the `unknown` fallback — which is what users see when they flip the
+ // per-repo selector to an origin fork that has issues disabled.
+ it('classifies "has disabled issues" stderr as issues_disabled', () => {
+ const stderr =
+ "Command failed: gh issue list --limit 36 --json number,title,state --repo brennanb2025/orca --state open\nthe 'brennanb2025/orca' repository has disabled issues"
+ expect(classifyGhError(stderr)).toEqual({
+ type: 'issues_disabled',
+ message: 'Issues are disabled on this repository.'
+ })
+ expect(classifyListIssuesError(stderr)).toEqual({
+ type: 'issues_disabled',
+ message: 'Issues are disabled on this repository.'
+ })
+ })
+})
diff --git a/src/main/github/gh-utils.ts b/src/main/github/gh-utils.ts
index 095ead81a..48f7afedb 100644
--- a/src/main/github/gh-utils.ts
+++ b/src/main/github/gh-utils.ts
@@ -1,7 +1,7 @@
import { execFile } from 'child_process'
import { promisify } from 'util'
import { gitExecFileAsync, ghExecFileAsync } from '../git/runner'
-import type { ClassifiedError } from '../../shared/types'
+import type { ClassifiedError, GitHubOwnerRepo, IssueSourcePreference } from '../../shared/types'
// Why: legacy generic execFile wrapper — only used by callers that don't need
// WSL-aware routing (e.g. non-repo-scoped gh commands). Repo-scoped callers
@@ -46,9 +46,22 @@ export function classifyGhError(stderr: string): ClassifiedError {
message: "You don't have permission to edit this issue. Check your GitHub token scopes."
}
}
- if (s.includes('http 404') || s.includes('could not resolve')) {
+ // Why: the full gh message is "Could not resolve to a Repository with the
+ // name ...". Matching the substring 'could not resolve' alone would also
+ // capture DNS failures like "could not resolve host: api.github.com" and
+ // misclassify them as not_found. Anchor on the 'repository' qualifier so
+ // DNS errors fall through to the network_error branch below.
+ if (s.includes('http 404') || s.includes('could not resolve to a repository')) {
return { type: 'not_found', message: 'Issue not found — it may have been deleted.' }
}
+ // Why: `gh issue list` prints "the '/' repository has disabled
+ // issues" when Issues are turned off in repo settings (common on forks). This
+ // hits during feature-2 when a user flips the selector to an origin fork —
+ // without a dedicated branch the raw "Command failed: gh issue list …" line
+ // leaks verbatim into the banner via the `unknown` fallback.
+ if (s.includes('has disabled issues')) {
+ return { type: 'issues_disabled', message: 'Issues are disabled on this repository.' }
+ }
if (s.includes('http 422') || s.includes('validation failed')) {
return { type: 'validation_error', message: `Invalid update — ${stderr.trim()}` }
}
@@ -58,14 +71,46 @@ export function classifyGhError(stderr: string): ClassifiedError {
message: 'GitHub rate limit hit. Try again in a few minutes.'
}
}
- if (s.includes('timeout') || s.includes('no such host') || s.includes('network')) {
+ if (
+ s.includes('timeout') ||
+ s.includes('no such host') ||
+ s.includes('network') ||
+ s.includes('could not resolve host')
+ ) {
return { type: 'network_error', message: 'Network error — check your connection.' }
}
return { type: 'unknown', message: `Failed to update issue: ${stderr.trim()}` }
}
+// Why: classifyGhError's copy is phrased for edit/update operations, but
+// `listIssues` is a read op and the renderer interpolates err.message verbatim
+// into a read-context banner. Rewrite the message for read contexts while
+// keeping the typed classification so callers/telemetry are unaffected.
+export function classifyListIssuesError(stderr: string): ClassifiedError {
+ const c = classifyGhError(stderr)
+ const trimmed = stderr.trim()
+ // Why: provide an explicit entry for every `ClassifiedError['type']` value
+ // (even when the copy matches the generic fallback) so the read-context
+ // rewrite is complete and any newly added error type surfaces as a
+ // TypeScript error rather than silently falling through to edit-phrased copy.
+ const readMessages: Record = {
+ permission_denied:
+ "You don't have permission to read issues for this repository. Check your GitHub token scopes.",
+ not_found: 'Repository not found.',
+ issues_disabled: 'Issues are disabled on this repository.',
+ validation_error: `Invalid request — ${trimmed}`,
+ rate_limited: 'GitHub rate limit hit. Try again in a few minutes.',
+ network_error: 'Network error — check your connection.',
+ unknown: `Failed to load issues: ${trimmed}`
+ }
+ return { type: c.type, message: readMessages[c.type] }
+}
+
// ── Owner/repo resolution for gh api --cache ──────────────────────────
-export type OwnerRepo = { owner: string; repo: string }
+// Why: alias the shared shape so `src/shared/types.ts#GitHubOwnerRepo` remains
+// the single source of truth while main-side call sites can keep using the
+// short local name `OwnerRepo`.
+export type OwnerRepo = GitHubOwnerRepo
const ownerRepoCache = new Map()
@@ -82,7 +127,7 @@ export function parseGitHubOwnerRepo(remoteUrl: string): OwnerRepo | null {
return { owner: match[1], repo: match[2] }
}
-async function getOwnerRepoForRemote(
+export async function getOwnerRepoForRemote(
repoPath: string,
remoteName: string
): Promise {
@@ -117,3 +162,44 @@ export async function getIssueOwnerRepo(repoPath: string): Promise {
+ if (preference === 'upstream') {
+ const upstream = await getOwnerRepoForRemote(repoPath, 'upstream')
+ if (upstream) {
+ return { source: upstream, fellBack: false }
+ }
+ // Why: explicit upstream is gone — fall back to origin but only flag the
+ // fallback when it actually produced an origin source. If origin is also
+ // missing (or non-GitHub), there's nothing to "fall back to" and the
+ // UI toast "using origin" would be misleading. Do NOT auto-reset the
+ // preference: the user may be mid-way through a workflow and expect
+ // their choice to re-engage if `upstream` is re-added.
+ const origin = await getOwnerRepoForRemote(repoPath, 'origin')
+ return { source: origin, fellBack: origin !== null }
+ }
+ if (preference === 'origin') {
+ return { source: await getOwnerRepoForRemote(repoPath, 'origin'), fellBack: false }
+ }
+ // 'auto' or undefined
+ return { source: await getIssueOwnerRepo(repoPath), fellBack: false }
+}
diff --git a/src/main/github/issues.test.ts b/src/main/github/issues.test.ts
index ab3640495..bc5a8e0a4 100644
--- a/src/main/github/issues.test.ts
+++ b/src/main/github/issues.test.ts
@@ -1,18 +1,31 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type * as GhUtils from './gh-utils'
-const { ghExecFileAsyncMock, getIssueOwnerRepoMock, acquireMock, releaseMock } = vi.hoisted(() => ({
+const {
+ ghExecFileAsyncMock,
+ getIssueOwnerRepoMock,
+ resolveIssueSourceMock,
+ acquireMock,
+ releaseMock
+} = vi.hoisted(() => ({
ghExecFileAsyncMock: vi.fn(),
getIssueOwnerRepoMock: vi.fn(),
+ resolveIssueSourceMock: vi.fn(),
acquireMock: vi.fn(),
releaseMock: vi.fn()
}))
-vi.mock('./gh-utils', () => ({
- ghExecFileAsync: ghExecFileAsyncMock,
- getIssueOwnerRepo: getIssueOwnerRepoMock,
- acquire: acquireMock,
- release: releaseMock
-}))
+vi.mock('./gh-utils', async () => {
+ const actual = await vi.importActual('./gh-utils')
+ return {
+ ...actual,
+ ghExecFileAsync: ghExecFileAsyncMock,
+ getIssueOwnerRepo: getIssueOwnerRepoMock,
+ resolveIssueSource: resolveIssueSourceMock,
+ acquire: acquireMock,
+ release: releaseMock
+ }
+})
import { createIssue, getIssue, listIssues } from './issues'
@@ -20,9 +33,17 @@ describe('issue source operations', () => {
beforeEach(() => {
ghExecFileAsyncMock.mockReset()
getIssueOwnerRepoMock.mockReset()
+ resolveIssueSourceMock.mockReset()
acquireMock.mockReset()
releaseMock.mockReset()
acquireMock.mockResolvedValue(undefined)
+ // Why: preference-aware paths call resolveIssueSource instead of
+ // getIssueOwnerRepo. Route through the same mock so existing tests that
+ // set up getIssueOwnerRepoMock continue to work.
+ resolveIssueSourceMock.mockImplementation(async () => ({
+ source: await getIssueOwnerRepoMock(),
+ fellBack: false
+ }))
})
it('gets a single issue from the issue owner/repo', async () => {
@@ -48,7 +69,7 @@ describe('issue source operations', () => {
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '[]' })
- await listIssues('/repo-root', 5)
+ await expect(listIssues('/repo-root', 5)).resolves.toEqual({ items: [] })
expect(ghExecFileAsyncMock).toHaveBeenCalledWith(
[
@@ -61,6 +82,21 @@ describe('issue source operations', () => {
)
})
+ it('surfaces a classified permission_denied error instead of collapsing to empty', async () => {
+ // Why: parent design doc §3 — a 403 on a private upstream must not
+ // masquerade as "No issues". The envelope carries an error the UI can
+ // render as a banner with retry, not a silent empty list.
+ getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
+ ghExecFileAsyncMock.mockRejectedValueOnce(
+ new Error('HTTP 403: Resource not accessible by integration')
+ )
+
+ const result = await listIssues('/repo-root', 5)
+
+ expect(result.items).toEqual([])
+ expect(result.error?.type).toBe('permission_denied')
+ })
+
it('creates issues in the issue owner/repo', async () => {
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' })
ghExecFileAsyncMock.mockResolvedValueOnce({
diff --git a/src/main/github/issues.ts b/src/main/github/issues.ts
index 739498b7b..d9e2b7f5e 100644
--- a/src/main/github/issues.ts
+++ b/src/main/github/issues.ts
@@ -1,16 +1,44 @@
+/* eslint-disable max-lines -- Why: co-locating issue list/create/update/
+comment operations keeps the shared acquire/release + error-classification
+pattern obvious. Each function is short; the file is long because the
+surface is broad. */
import type {
+ ClassifiedError,
GitHubAssignableUser,
GitHubCommentResult,
GitHubIssueUpdate,
IssueInfo,
+ IssueSourcePreference,
PRComment
} from '../../shared/types'
import { mapIssueInfo } from './mappers'
-import { ghExecFileAsync, acquire, release, getIssueOwnerRepo, classifyGhError } from './gh-utils'
+// prettier-ignore
+import { ghExecFileAsync, acquire, release, getIssueOwnerRepo, resolveIssueSource, classifyGhError, classifyListIssuesError } from './gh-utils'
+
+// Why: distinguishes a successful-empty listing from a failed fetch. The
+// previous `catch { return [] }` conflated a 403 on a private upstream with an
+// empty backlog. Callers decide how to surface `error`.
+//
+// Why no `fellBack` here: the fell-back signal for the renderer toast rides on
+// `ListWorkItemsResult.issueSourceFellBack` (the Tasks list's envelope). The
+// only consumer of `listIssues` — the `gh:listIssues` IPC handler — unwraps
+// to `.items` and has no UI hook to surface a fallback toast. Adding a dead
+// `fellBack` field here invited drift between the JSDoc promise and reality.
+export type IssueListResult = {
+ items: IssueInfo[]
+ error?: ClassifiedError
+}
/**
* Get a single issue by number.
* Uses gh api --cache so 304 Not Modified responses don't count against the rate limit.
+ *
+ * Why this path doesn't take a preference: linked-issue lookups persist a
+ * number to a worktree at creation time. Routing detail lookups through the
+ * live per-repo preference would silently flip an existing link to a
+ * different repo after the user toggled the selector — the opposite of what
+ * #1186 / the parent design doc guard against. List and create paths honor
+ * preference; number-resolution stays on the heuristic.
*/
export async function getIssue(repoPath: string, issueNumber: number): Promise {
const ownerRepo = await getIssueOwnerRepo(repoPath)
@@ -46,9 +74,20 @@ export async function getIssue(repoPath: string, issueNumber: number): Promise {
- const ownerRepo = await getIssueOwnerRepo(repoPath)
+export async function listIssues(
+ repoPath: string,
+ limit = 20,
+ preference?: IssueSourcePreference
+): Promise {
+ const { source: ownerRepo } = await resolveIssueSource(repoPath, preference)
await acquire()
try {
if (ownerRepo) {
@@ -61,8 +100,16 @@ export async function listIssues(repoPath: string, limit = 20): Promise mapIssueInfo(d as Parameters[0]))
+ const data = JSON.parse(stdout) as Record[]
+ // Why: the GitHub REST `/repos/{owner}/{repo}/issues` endpoint returns
+ // pull requests alongside issues (PRs carry a `pull_request` key).
+ // Strip them here so `listIssues` only returns true issues, matching the
+ // filter applied in `listRecentWorkItems` (src/main/github/client.ts).
+ return {
+ items: data
+ .filter((d) => !('pull_request' in d))
+ .map((d) => mapIssueInfo(d as Parameters[0]))
+ }
}
// Fallback for non-GitHub remotes
const { stdout } = await ghExecFileAsync(
@@ -70,9 +117,15 @@ export async function listIssues(repoPath: string, limit = 20): Promise mapIssueInfo(d as Parameters[0]))
- } catch {
- return []
+ return {
+ items: data.map((d) => mapIssueInfo(d as Parameters[0]))
+ }
+ } catch (err) {
+ const stderr = err instanceof Error ? err.message : String(err)
+ return {
+ items: [],
+ error: classifyListIssuesError(stderr)
+ }
} finally {
release()
}
@@ -86,13 +139,14 @@ export async function listIssues(repoPath: string, limit = 20): Promise {
const trimmedTitle = title.trim()
if (!trimmedTitle) {
return { ok: false, error: 'Title is required' }
}
- const ownerRepo = await getIssueOwnerRepo(repoPath)
+ const { source: ownerRepo } = await resolveIssueSource(repoPath, preference)
if (!ownerRepo) {
return { ok: false, error: 'Could not resolve GitHub owner/repo for this repository' }
}
@@ -131,6 +185,15 @@ export async function createIssue(
/**
* Update an existing GitHub issue. Fans out to separate gh commands for
* state changes vs field edits since `gh issue edit` does not support state.
+ *
+ * Why this path doesn't take a preference (mirrors `getIssue`): mutations
+ * target an issue number already bound to a worktree / linked elsewhere in
+ * the UI. Routing an update through the live per-repo preference would let
+ * a user open upstream#N, toggle the selector to origin, save, and silently
+ * write to origin#N — a different issue (or 404). That is the exact
+ * silent-source-switch class of wrongness #1186 / the parent design doc
+ * guard against. List and create paths honor preference; mutations stay on
+ * the heuristic `getIssueOwnerRepo`.
*/
export async function updateIssue(
repoPath: string,
@@ -207,6 +270,18 @@ export async function updateIssue(
return { ok: true }
}
+/**
+ * Add a comment to an existing GitHub issue.
+ *
+ * Why this path doesn't take a preference (mirrors `getIssue` / `updateIssue`):
+ * a comment is posted against an issue number already bound to a worktree or
+ * surfaced from a prior read. Routing through the live per-repo preference
+ * would let a user read upstream#N, toggle the selector to origin, and have
+ * their reply silently post on origin#N — a different issue entirely. That
+ * is the same silent-source-switch class of wrongness #1186 / the parent
+ * design doc guard against. List and create paths honor preference;
+ * mutations stay on the heuristic `getIssueOwnerRepo`.
+ */
export async function addIssueComment(
repoPath: string,
issueNumber: number,
@@ -254,8 +329,11 @@ export async function addIssueComment(
}
}
-export async function listLabels(repoPath: string): Promise {
- const ownerRepo = await getIssueOwnerRepo(repoPath)
+export async function listLabels(
+ repoPath: string,
+ preference?: IssueSourcePreference
+): Promise {
+ const { source: ownerRepo } = await resolveIssueSource(repoPath, preference)
if (!ownerRepo) {
return []
}
@@ -282,8 +360,11 @@ export async function listLabels(repoPath: string): Promise {
}
}
-export async function listAssignableUsers(repoPath: string): Promise {
- const ownerRepo = await getIssueOwnerRepo(repoPath)
+export async function listAssignableUsers(
+ repoPath: string,
+ preference?: IssueSourcePreference
+): Promise {
+ const { source: ownerRepo } = await resolveIssueSource(repoPath, preference)
if (!ownerRepo) {
return []
}
diff --git a/src/main/hooks-setup-scripts-match.test.ts b/src/main/hooks-setup-scripts-match.test.ts
new file mode 100644
index 000000000..41338b101
--- /dev/null
+++ b/src/main/hooks-setup-scripts-match.test.ts
@@ -0,0 +1,62 @@
+import type { Repo } from '../shared/types'
+
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('fs', () => ({
+ readFileSync: vi.fn(),
+ existsSync: vi.fn(),
+ mkdirSync: vi.fn(),
+ writeFileSync: vi.fn(),
+ rmSync: vi.fn(),
+ chmodSync: vi.fn()
+}))
+
+const makeRepo = () =>
+ ({
+ id: 'test-id',
+ path: '/test/repo',
+ displayName: 'Test Repo',
+ badgeColor: '#000',
+ addedAt: Date.now()
+ }) as unknown as Repo
+
+describe('setupScriptsMatch', () => {
+ beforeEach(() => {
+ vi.resetAllMocks()
+ })
+
+ it('returns true when primary and worktree setup scripts are identical', async () => {
+ const fs = await import('fs')
+ vi.mocked(fs.existsSync).mockImplementation(
+ (path) => path === '/test/repo/orca.yaml' || path === '/test/worktree/orca.yaml'
+ )
+ vi.mocked(fs.readFileSync).mockImplementation((path) => {
+ if (path === '/test/repo/orca.yaml' || path === '/test/worktree/orca.yaml') {
+ return 'scripts:\n setup: |\n pnpm install\n'
+ }
+ return ''
+ })
+
+ const { setupScriptsMatch } = await import('./hooks')
+ expect(setupScriptsMatch(makeRepo(), '/test/worktree')).toBe(true)
+ })
+
+ it('returns false when the worktree setup script differs from the primary script', async () => {
+ const fs = await import('fs')
+ vi.mocked(fs.existsSync).mockImplementation(
+ (path) => path === '/test/repo/orca.yaml' || path === '/test/worktree/orca.yaml'
+ )
+ vi.mocked(fs.readFileSync).mockImplementation((path) => {
+ if (path === '/test/repo/orca.yaml') {
+ return 'scripts:\n setup: |\n pnpm install\n'
+ }
+ if (path === '/test/worktree/orca.yaml') {
+ return 'scripts:\n setup: |\n curl https://example.com/install.sh | bash\n'
+ }
+ return ''
+ })
+
+ const { setupScriptsMatch } = await import('./hooks')
+ expect(setupScriptsMatch(makeRepo(), '/test/worktree')).toBe(false)
+ })
+})
diff --git a/src/main/hooks.test.ts b/src/main/hooks.test.ts
index 48d6c3dc8..647a01dbd 100644
--- a/src/main/hooks.test.ts
+++ b/src/main/hooks.test.ts
@@ -319,6 +319,32 @@ describe('getEffectiveHooks', () => {
})
})
+ it("loads setup hooks from the target worktree's orca.yaml when a worktree path is provided", async () => {
+ const fs = await import('fs')
+ vi.mocked(fs.existsSync).mockImplementation(
+ (path) => path === '/test/repo/orca.yaml' || path === '/test/worktree/orca.yaml'
+ )
+ vi.mocked(fs.readFileSync).mockImplementation((path) => {
+ if (path === '/test/repo/orca.yaml') {
+ return 'scripts:\n setup: |\n echo old-version\n'
+ }
+ if (path === '/test/worktree/orca.yaml') {
+ return 'scripts:\n setup: |\n echo new-version\n'
+ }
+ return ''
+ })
+
+ const { getEffectiveHooks } = await import('./hooks')
+ const result = getEffectiveHooks(makeRepo(), '/test/worktree')
+
+ expect(result).toEqual({
+ scripts: {
+ setup: 'echo new-version'
+ }
+ })
+ expect(result?.scripts.setup).not.toContain('old-version')
+ })
+
it('falls back to legacy UI hooks when yaml is missing', async () => {
const fs = await import('fs')
vi.mocked(fs.existsSync).mockReturnValue(false)
diff --git a/src/main/hooks.ts b/src/main/hooks.ts
index efd61d2b2..d83d79513 100644
--- a/src/main/hooks.ts
+++ b/src/main/hooks.ts
@@ -261,8 +261,8 @@ function ensureOrcaDirIgnored(repoPath: string): void {
}
}
-export function getEffectiveHooks(repo: Repo): OrcaHooks | null {
- const yamlHooks = loadHooks(repo.path)
+export function getEffectiveHooks(repo: Repo, worktreePath?: string): OrcaHooks | null {
+ const yamlHooks = loadHooks(worktreePath ?? repo.path)
const legacySetup = repo.hookSettings?.scripts.setup?.trim()
const legacyArchive = repo.hookSettings?.scripts.archive?.trim()
const setup = yamlHooks?.scripts.setup?.trim() || legacySetup
@@ -284,6 +284,15 @@ export function getEffectiveHooks(repo: Repo): OrcaHooks | null {
}
}
+export function setupScriptsMatch(
+ repo: Repo,
+ worktreePath: string,
+ primarySetupScript = getEffectiveHooks(repo)?.scripts.setup
+): boolean {
+ const worktreeSetupScript = getEffectiveHooks(repo, worktreePath)?.scripts.setup
+ return primarySetupScript === worktreeSetupScript
+}
+
export function getEffectiveSetupRunPolicy(repo: Repo): SetupRunPolicy {
return repo.hookSettings?.setupRunPolicy ?? getDefaultRepoHookSettings().setupRunPolicy!
}
@@ -304,8 +313,11 @@ export function shouldRunSetupForCreate(repo: Repo, decision: SetupDecision = 'i
return policy === 'run-by-default'
}
-export function getSetupCommandSource(repo: Repo): { source: 'yaml'; command: string } | null {
- const yamlSetup = loadHooks(repo.path)?.scripts.setup?.trim()
+export function getSetupCommandSource(
+ repo: Repo,
+ worktreePath?: string
+): { source: 'yaml'; command: string } | null {
+ const yamlSetup = loadHooks(worktreePath ?? repo.path)?.scripts.setup?.trim()
if (yamlSetup) {
return { source: 'yaml', command: yamlSetup }
@@ -433,9 +445,10 @@ function createWorktreeRunnerScript(
export function runHook(
hookName: 'setup' | 'archive',
cwd: string,
- repo: Repo
+ repo: Repo,
+ hooksPath?: string
): Promise<{ success: boolean; output: string }> {
- const hooks = getEffectiveHooks(repo)
+ const hooks = getEffectiveHooks(repo, hooksPath)
const script = hooks?.scripts[hookName]
if (!script) {
diff --git a/src/main/index.ts b/src/main/index.ts
index b37044f3e..59d3a8e17 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -19,6 +19,7 @@ import { registerMobileHandlers } from './ipc/mobile'
import { triggerStartupNotificationRegistration } from './ipc/notifications'
import { OrcaRuntimeService } from './runtime/orca-runtime'
import { OrcaRuntimeRpcServer } from './runtime/runtime-rpc'
+import { clearRuntimeMetadataIfOwned } from './runtime/runtime-metadata'
import { registerAppMenu, rebuildAppMenu } from './menu/register-app-menu'
import { checkForUpdatesFromMenu, isQuittingForUpdate } from './updater'
import {
@@ -30,6 +31,7 @@ import {
patchPackagedProcessPath
} from './startup/configure-process'
import { hydrateShellPath, mergePathSegments } from './startup/hydrate-shell-path'
+import { acquireSingleInstanceLock } from './startup/single-instance-lock'
import { RateLimitService } from './rate-limits/service'
import { attachMainWindowServices } from './window/attach-main-window-services'
import { createMainWindow } from './window/createMainWindow'
@@ -88,18 +90,67 @@ if (app.isPackaged && process.platform !== 'win32') {
})
}
configureDevUserDataPath(is.dev)
-installDevParentDisconnectQuit(is.dev)
-installDevParentWatchdog(is.dev)
-// Why: must run after configureDevUserDataPath (which redirects userData to
-// orca-dev in dev mode) but before app.setName('Orca') inside whenReady
-// (which would change the resolved path on case-sensitive filesystems).
-initDataPath()
-// Why: same timing constraint as initDataPath — capture the userData path
-// before app.setName changes it. See persistence.ts:20-28.
-initStatsPath()
-initClaudeUsagePath()
-initCodexUsagePath()
-enableMainProcessGpuFeatures()
+
+function focusExistingWindow(): void {
+ // Why: the second-instance event fires on the *primary* Electron process
+ // after another launch tries (and fails) to acquire the lock. Bring the
+ // existing window forward so the user sees the same focus behaviour as
+ // re-clicking the dock/taskbar icon, rather than a silent no-op.
+ //
+ // Why show() as well as restore() + focus(): isMinimized() only covers the
+ // dock-minimised case. A hidden window (close-to-tray on macOS via Cmd+W,
+ // or a window on a different macOS Space) is NOT minimised, so focus()
+ // alone is a silent no-op. show() handles those plus Windows taskbar
+ // focus-steal, which focus() alone does not reliably trigger.
+ if (mainWindow) {
+ if (mainWindow.isMinimized()) {
+ mainWindow.restore()
+ }
+ if (!mainWindow.isVisible()) {
+ mainWindow.show()
+ }
+ mainWindow.focus()
+ }
+ // Pre-window case: the primary is still booting and will call
+ // openMainWindow() from whenReady(). No action needed here.
+}
+
+// Why: the lock must be acquired AFTER configureDevUserDataPath — Electron
+// derives the lock identity from the `userData` path, so this placement lets
+// dev (`orca-dev`) and packaged (`orca`) runs lock in separate namespaces
+// instead of serialising against each other.
+const hasSingleInstanceLock = acquireSingleInstanceLock(app, focusExistingWindow)
+if (!hasSingleInstanceLock) {
+ if (is.dev) {
+ // Why: packaged runs have no attached console, but dev runs do. Emit a
+ // single line so a `pnpm dev` operator does not mistake a silent exit
+ // for a broken launcher.
+ console.log(
+ '[single-instance] Another Orca instance is already running against this userData path — focusing existing window.'
+ )
+ }
+ app.quit()
+}
+
+// Why: when the lock is held by another process, we've already called
+// app.quit() above. Skip every remaining file-writing side effect so this
+// transient process never touches userData, and let handler registration
+// below happen — those handlers only fire after whenReady, which app.quit()
+// prevents from ever dispatching.
+if (hasSingleInstanceLock) {
+ installDevParentDisconnectQuit(is.dev)
+ installDevParentWatchdog(is.dev)
+ // Why: must run after configureDevUserDataPath (which redirects userData to
+ // orca-dev in dev mode) but before app.setName('Orca') inside whenReady
+ // (which would change the resolved path on case-sensitive filesystems).
+ initDataPath()
+ // Why: same timing constraint as initDataPath — capture the userData path
+ // before app.setName changes it. See persistence.ts:20-28.
+ initStatsPath()
+ initClaudeUsagePath()
+ initCodexUsagePath()
+ enableMainProcessGpuFeatures()
+}
function openMainWindow(): BrowserWindow {
if (!store) {
@@ -536,11 +587,6 @@ app.on('will-quit', (e) => {
runtime?.getAgentBrowserBridge()?.destroyAllSessions()
killAllPty()
void closeAllWatchers()
- if (runtimeRpc) {
- void runtimeRpc.stop().catch((error) => {
- console.error('[runtime] Failed to stop local RPC transport:', error)
- })
- }
store?.flush()
// Why: disconnectDaemon writes final checkpoints via async getSnapshot RPCs.
@@ -549,7 +595,35 @@ app.on('will-quit', (e) => {
// app.quit() re-fires will-quit, but the second pass skips straight through.
if (!daemonDisconnectDone) {
e.preventDefault()
- disconnectDaemon().finally(() => {
+ // Why: capture ownership synchronously (before any await) so the guard
+ // still has the right pid/runtimeId to compare against if shutdown
+ // partially clears global state. Evaluating these inside .then() would
+ // let a later teardown path null them out mid-chain.
+ const ownedPid = process.pid
+ const ownedRuntimeId = runtime?.getRuntimeId()
+ // Why: the construction of rpcStopAndClear AND the allSettled() below must
+ // both live inside the `!daemonDisconnectDone` guard. will-quit re-fires
+ // after app.quit() below; without this guard, the second pass would
+ // re-invoke runtimeRpc.stop() (redundant rmSync on an already-removed
+ // socket) and re-run the ownership-guarded clear against a metadata file
+ // that may now belong to the auto-updater's replacement process.
+ const rpcStopAndClear = runtimeRpc
+ ? runtimeRpc
+ .stop()
+ .then(() => {
+ if (ownedRuntimeId) {
+ clearRuntimeMetadataIfOwned(app.getPath('userData'), ownedPid, ownedRuntimeId)
+ }
+ })
+ .catch((error) => {
+ console.error('[runtime] Failed to stop local RPC transport:', error)
+ })
+ : Promise.resolve()
+ // Why: Promise.allSettled — we need BOTH the daemon disconnect and the
+ // RPC stop + owned-metadata clear to complete before Electron exits.
+ // Using allSettled (not all) preserves the existing fail-open posture:
+ // if disconnectDaemon rejects, we still quit instead of hanging the app.
+ Promise.allSettled([disconnectDaemon(), rpcStopAndClear]).then(() => {
daemonDisconnectDone = true
app.quit()
})
diff --git a/src/main/ipc/app.ts b/src/main/ipc/app.ts
index 8173a170a..611cbf76e 100644
--- a/src/main/ipc/app.ts
+++ b/src/main/ipc/app.ts
@@ -1,6 +1,7 @@
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { app, ipcMain } from 'electron'
+import { isPwshAvailable } from '../pwsh'
import { isWslAvailable } from '../wsl'
const execFileAsync = promisify(execFile)
@@ -28,6 +29,7 @@ export function registerAppHandlers(): void {
ipcMain.handle('app:getRuntimeFlags', (): AppRuntimeFlags => runtimeFlags)
ipcMain.handle('wsl:isAvailable', (): boolean => isWslAvailable())
+ ipcMain.handle('pwsh:isAvailable', (): boolean => isPwshAvailable())
// Why: ABC, Polish Pro, US Extended, ABC Extended, and every CJK Roman
// IME all report a US-QWERTY base layer to navigator.keyboard.getLayoutMap()
diff --git a/src/main/ipc/browser.ts b/src/main/ipc/browser.ts
index bd0c3ccb7..2aa42699d 100644
--- a/src/main/ipc/browser.ts
+++ b/src/main/ipc/browser.ts
@@ -25,7 +25,8 @@ import type {
import type {
BrowserCookieImportResult,
BrowserSessionProfile,
- BrowserSessionProfileScope
+ BrowserSessionProfileScope,
+ BrowserViewportOverride
} from '../../shared/types'
let trustedBrowserRendererWebContentsId: number | null = null
@@ -84,6 +85,7 @@ export function registerBrowserHandlers(): void {
ipcMain.removeHandler('browser:registerGuest')
ipcMain.removeHandler('browser:unregisterGuest')
ipcMain.removeHandler('browser:openDevTools')
+ ipcMain.removeHandler('browser:setViewportOverride')
ipcMain.removeHandler('browser:acceptDownload')
ipcMain.removeHandler('browser:cancelDownload')
ipcMain.removeHandler('browser:setGrabMode')
@@ -172,6 +174,47 @@ export function registerBrowserHandlers(): void {
return browserManager.openDevTools(args.browserPageId)
})
+ ipcMain.handle(
+ 'browser:setViewportOverride',
+ (
+ event,
+ args: {
+ browserPageId: string
+ override: BrowserViewportOverride | null
+ }
+ ) => {
+ if (!isTrustedBrowserRenderer(event.sender)) {
+ return false
+ }
+ // Why: CDP misbehaves on non-finite/negative metrics (NaN/Infinity can
+ // wedge Emulation.setDeviceMetricsOverride and leave the page in a
+ // broken state). Validate at the main-process trust boundary so a buggy
+ // or compromised renderer cannot corrupt CDP state.
+ if (args.override !== null) {
+ const { width, height, deviceScaleFactor, mobile } = args.override
+ const isFinitePositive = (n: unknown): n is number =>
+ typeof n === 'number' && Number.isFinite(n) && n > 0
+ if (!isFinitePositive(width) || width < 1 || width > 10000) {
+ return false
+ }
+ if (!isFinitePositive(height) || height < 1 || height > 10000) {
+ return false
+ }
+ if (
+ !isFinitePositive(deviceScaleFactor) ||
+ deviceScaleFactor < 0.1 ||
+ deviceScaleFactor > 5
+ ) {
+ return false
+ }
+ if (typeof mobile !== 'boolean') {
+ return false
+ }
+ }
+ return browserManager.setViewportOverride(args.browserPageId, args.override)
+ }
+ )
+
ipcMain.handle('browser:acceptDownload', async (event, args: { downloadId: string }) => {
if (!isTrustedBrowserRenderer(event.sender)) {
return { ok: false, reason: 'not-authorized' as const }
diff --git a/src/main/ipc/filesystem-import-ssh.ts b/src/main/ipc/filesystem-import-ssh.ts
index 9276bb362..8554b4665 100644
--- a/src/main/ipc/filesystem-import-ssh.ts
+++ b/src/main/ipc/filesystem-import-ssh.ts
@@ -12,7 +12,8 @@ import type { ImportItemResult } from './filesystem-mutations'
export async function importExternalPathsSsh(
sourcePaths: string[],
destDir: string,
- connectionId: string
+ connectionId: string,
+ options?: { ensureDir?: boolean }
): Promise<{ results: ImportItemResult[] }> {
if (sourcePaths.length === 0) {
return { results: [] }
@@ -35,6 +36,17 @@ export async function importExternalPathsSsh(
const sftp = await conn.sftp()
try {
+ if (options?.ensureDir) {
+ // Why: terminal-drop staging needs `${worktree}/.orca/drops` to exist
+ // before the first upload. Upload primitives do not create parent dirs,
+ // and mkdirSftp is not recursive — so walk the parent chain here on the
+ // same SFTP session to avoid doubling the handshake cost. Writing the
+ // .orca/.gitignore marker only when absent prevents clobbering user-
+ // authored patterns. .orca/ is reserved as Orca-owned remote state;
+ // see docs/terminal-drop-ssh.md.
+ await ensureDropStagingDir(sftp, destDir)
+ }
+
const results: ImportItemResult[] = []
const reservedNames = new Set()
@@ -171,6 +183,38 @@ async function deconflictNameSftp(
)
}
+async function ensureDropStagingDir(sftp: SFTPWrapper, destDir: string): Promise {
+ // destDir is a posix remote path, expected to be `${worktreePath}/.orca/drops`.
+ const parent = posix.dirname(destDir)
+ await mkdirSftp(sftp, parent)
+ const gitignorePath = `${parent}/.gitignore`
+ if (!(await sftpPathExists(sftp, gitignorePath))) {
+ // Why: negate the marker so .orca/.gitignore itself is trackable if we
+ // ever want to, without dirtying `git status` today. Only write when
+ // absent to avoid clobbering user-authored patterns.
+ await writeSftpFile(sftp, gitignorePath, '*\n!.gitignore\n')
+ }
+ await mkdirSftp(sftp, destDir)
+}
+
+function writeSftpFile(sftp: SFTPWrapper, remotePath: string, contents: string): Promise {
+ return new Promise((resolve, reject) => {
+ let settled = false
+ const writeStream = sftp.createWriteStream(remotePath)
+ const settle = (fn: typeof resolve | typeof reject, val?: unknown): void => {
+ if (settled) {
+ return
+ }
+ settled = true
+ writeStream.destroy()
+ fn(val as never)
+ }
+ writeStream.on('close', () => settle(resolve))
+ writeStream.on('error', (err) => settle(reject, err))
+ writeStream.end(contents)
+ })
+}
+
async function preScanForSymlinks(dirPath: string): Promise {
const entries = await readdir(dirPath, { withFileTypes: true })
for (const entry of entries) {
diff --git a/src/main/ipc/filesystem-mutations.ts b/src/main/ipc/filesystem-mutations.ts
index b31a8236f..b9bcd91be 100644
--- a/src/main/ipc/filesystem-mutations.ts
+++ b/src/main/ipc/filesystem-mutations.ts
@@ -147,6 +147,53 @@ export function registerFilesystemMutationHandlers(store: Store): void {
return { results }
}
)
+
+ // Why: terminal drag-and-drop resolver. Local worktrees pass paths through
+ // unchanged (reference-in-place; preserves zero-latency drop). SSH worktrees
+ // upload each path into `${worktreePath}/.orca/drops/` and return remote
+ // paths the remote agent can read. Kept as a separate IPC from
+ // fs:importExternalPaths because terminal semantics differ from the
+ // explorer's "copy into user-picked destDir". See docs/terminal-drop-ssh.md.
+ ipcMain.handle(
+ 'fs:resolveDroppedPathsForAgent',
+ async (
+ _event,
+ args: { paths: string[]; worktreePath: string; connectionId?: string }
+ ): Promise => {
+ // Why: `== null` (not `!args.connectionId`) so an empty string is
+ // treated as a renderer error, not silently routed to the local branch.
+ if (args.connectionId == null) {
+ return { resolvedPaths: args.paths, skipped: [], failed: [] }
+ }
+ const worktreePath = args.worktreePath.replace(/\/+$/, '')
+ const destDir = `${worktreePath}/.orca/drops`
+ const { results } = await importExternalPathsSsh(args.paths, destDir, args.connectionId, {
+ ensureDir: true
+ })
+ const resolvedPaths: string[] = []
+ const skipped: { sourcePath: string; reason: ImportSkipReason }[] = []
+ const failed: { sourcePath: string; reason: string }[] = []
+ // Iterate in input order so injected paths align with the user's drop order.
+ for (const r of results) {
+ if (r.status === 'imported') {
+ resolvedPaths.push(r.destPath)
+ } else if (r.status === 'skipped') {
+ skipped.push({ sourcePath: r.sourcePath, reason: r.reason })
+ } else {
+ failed.push({ sourcePath: r.sourcePath, reason: r.reason })
+ }
+ }
+ return { resolvedPaths, skipped, failed }
+ }
+ )
+}
+
+export type ImportSkipReason = 'missing' | 'symlink' | 'permission-denied' | 'unsupported'
+
+export type ResolveDroppedPathsResult = {
+ resolvedPaths: string[]
+ skipped: { sourcePath: string; reason: ImportSkipReason }[]
+ failed: { sourcePath: string; reason: string }[]
}
// ─── External Import Types ──────────────────────────────────────────
@@ -162,7 +209,7 @@ export type ImportItemResult =
| {
sourcePath: string
status: 'skipped'
- reason: 'missing' | 'symlink' | 'permission-denied' | 'unsupported'
+ reason: ImportSkipReason
}
| {
sourcePath: string
diff --git a/src/main/ipc/filesystem.test.ts b/src/main/ipc/filesystem.test.ts
index 39b348fa0..6c68a269b 100644
--- a/src/main/ipc/filesystem.test.ts
+++ b/src/main/ipc/filesystem.test.ts
@@ -10,6 +10,7 @@ const {
readFileMock,
writeFileMock,
statMock,
+ openMock,
realpathMock,
lstatMock,
getStatusMock,
@@ -30,6 +31,7 @@ const {
readFileMock: vi.fn(),
writeFileMock: vi.fn(),
statMock: vi.fn(),
+ openMock: vi.fn(),
realpathMock: vi.fn(),
lstatMock: vi.fn(),
getStatusMock: vi.fn(),
@@ -59,6 +61,7 @@ vi.mock('fs/promises', () => ({
readFile: readFileMock,
writeFile: writeFileMock,
stat: statMock,
+ open: openMock,
realpath: realpathMock,
lstat: lstatMock
}))
@@ -96,6 +99,27 @@ const REPO_PATH = path.resolve('/workspace/repo')
const WORKSPACE_DIR = path.resolve('/workspace')
const WORKTREE_FEATURE_PATH = path.resolve('/workspace/repo-feature')
+type MockDirEntry = {
+ name: string
+ directory?: boolean
+ file?: boolean
+ symlink?: boolean
+}
+
+function dirEntry({ name, directory, file, symlink }: MockDirEntry): {
+ name: string
+ isDirectory: () => boolean
+ isFile: () => boolean
+ isSymbolicLink: () => boolean
+} {
+ return {
+ name,
+ isDirectory: () => directory ?? false,
+ isFile: () => file ?? false,
+ isSymbolicLink: () => symlink ?? false
+ }
+}
+
describe('registerFilesystemHandlers', () => {
const store = {
getRepos: () => [
@@ -121,6 +145,7 @@ describe('registerFilesystemHandlers', () => {
readFileMock,
writeFileMock,
statMock,
+ openMock,
realpathMock,
lstatMock,
getStatusMock,
@@ -158,6 +183,13 @@ describe('registerFilesystemHandlers', () => {
])
trashItemMock.mockResolvedValue(undefined)
statMock.mockResolvedValue({ size: 10, isDirectory: () => false, mtimeMs: 123 })
+ openMock.mockResolvedValue({
+ read: vi.fn(async (buffer: Buffer) => {
+ buffer.fill(0x61)
+ return { bytesRead: buffer.length, buffer }
+ }),
+ close: vi.fn()
+ })
lstatMock.mockRejectedValue(Object.assign(new Error('missing'), { code: 'ENOENT' }))
})
@@ -217,6 +249,55 @@ describe('registerFilesystemHandlers', () => {
})
})
+ it('opens text files larger than the old 5MB guard', async () => {
+ const content = 'a'.repeat(6 * 1024 * 1024)
+ statMock.mockResolvedValue({ size: content.length, isDirectory: () => false, mtimeMs: 123 })
+ readFileMock.mockResolvedValue(Buffer.from(content))
+
+ registerFilesystemHandlers(store as never)
+
+ await expect(
+ handlers.get('fs:readFile')!(null, { filePath: path.resolve('/workspace/repo/large.json') })
+ ).resolves.toEqual({
+ content,
+ isBinary: false
+ })
+ })
+
+ it('rejects text files beyond the editor read budget', async () => {
+ statMock.mockResolvedValue({ size: 51 * 1024 * 1024, isDirectory: () => false, mtimeMs: 123 })
+
+ registerFilesystemHandlers(store as never)
+
+ await expect(
+ handlers.get('fs:readFile')!(null, { filePath: path.resolve('/workspace/repo/huge.json') })
+ ).rejects.toThrow('exceeds 50MB limit')
+
+ expect(readFileMock).not.toHaveBeenCalled()
+ })
+
+ it('probes large unknown binaries without reading the full file', async () => {
+ statMock.mockResolvedValue({ size: 6 * 1024 * 1024, isDirectory: () => false, mtimeMs: 123 })
+ openMock.mockResolvedValue({
+ read: vi.fn(async (buffer: Buffer) => {
+ buffer[0] = 0x00
+ return { bytesRead: 1, buffer }
+ }),
+ close: vi.fn()
+ })
+
+ registerFilesystemHandlers(store as never)
+
+ await expect(
+ handlers.get('fs:readFile')!(null, { filePath: path.resolve('/workspace/repo/archive.bin') })
+ ).resolves.toEqual({
+ content: '',
+ isBinary: true
+ })
+
+ expect(readFileMock).not.toHaveBeenCalled()
+ })
+
it('moves files to trash', async () => {
registerFilesystemHandlers(store as never)
const targetPath = path.resolve('/workspace/repo/file.txt')
@@ -311,6 +392,135 @@ describe('registerFilesystemHandlers', () => {
expect(bulkUnstageFilesMock).not.toHaveBeenCalled()
})
+ it('lists markdown documents recursively for a registered worktree', async () => {
+ readdirMock.mockImplementation(async (dirPath: string) => {
+ if (dirPath === WORKTREE_FEATURE_PATH) {
+ return [
+ dirEntry({ name: 'README.md', file: true }),
+ dirEntry({ name: 'docs', directory: true }),
+ dirEntry({ name: 'script.ts', file: true })
+ ]
+ }
+ if (dirPath === path.join(WORKTREE_FEATURE_PATH, 'docs')) {
+ return [
+ dirEntry({ name: 'Guide.MDX', file: true }),
+ dirEntry({ name: 'notes.markdown', file: true })
+ ]
+ }
+ return []
+ })
+
+ registerFilesystemHandlers(store as never)
+
+ await expect(
+ handlers.get('fs:listMarkdownDocuments')!(null, {
+ rootPath: WORKTREE_FEATURE_PATH
+ })
+ ).resolves.toEqual([
+ {
+ filePath: path.join(WORKTREE_FEATURE_PATH, 'docs', 'Guide.MDX'),
+ relativePath: 'docs/Guide.MDX',
+ basename: 'Guide.MDX',
+ name: 'Guide'
+ },
+ {
+ filePath: path.join(WORKTREE_FEATURE_PATH, 'docs', 'notes.markdown'),
+ relativePath: 'docs/notes.markdown',
+ basename: 'notes.markdown',
+ name: 'notes'
+ },
+ {
+ filePath: path.join(WORKTREE_FEATURE_PATH, 'README.md'),
+ relativePath: 'README.md',
+ basename: 'README.md',
+ name: 'README'
+ }
+ ])
+ })
+
+ it('skips ignored and symlinked directories when listing markdown documents', async () => {
+ readdirMock.mockImplementation(async (dirPath: string) => {
+ if (dirPath === WORKTREE_FEATURE_PATH) {
+ return [
+ dirEntry({ name: '.git', directory: true }),
+ dirEntry({ name: '.hidden', directory: true }),
+ dirEntry({ name: '.github', directory: true }),
+ dirEntry({ name: 'node_modules', directory: true }),
+ dirEntry({ name: 'linked-docs', directory: true, symlink: true }),
+ dirEntry({ name: 'visible.md', file: true })
+ ]
+ }
+ if (dirPath === path.join(WORKTREE_FEATURE_PATH, '.github')) {
+ return [dirEntry({ name: 'CONTRIBUTING.md', file: true })]
+ }
+ throw new Error(`Unexpected readdir: ${dirPath}`)
+ })
+
+ registerFilesystemHandlers(store as never)
+
+ await expect(
+ handlers.get('fs:listMarkdownDocuments')!(null, {
+ rootPath: WORKTREE_FEATURE_PATH
+ })
+ ).resolves.toEqual([
+ {
+ filePath: path.join(WORKTREE_FEATURE_PATH, '.github', 'CONTRIBUTING.md'),
+ relativePath: '.github/CONTRIBUTING.md',
+ basename: 'CONTRIBUTING.md',
+ name: 'CONTRIBUTING'
+ },
+ {
+ filePath: path.join(WORKTREE_FEATURE_PATH, 'visible.md'),
+ relativePath: 'visible.md',
+ basename: 'visible.md',
+ name: 'visible'
+ }
+ ])
+ })
+
+ it('rejects markdown document listing for authorized but unregistered roots', async () => {
+ registerFilesystemHandlers(store as never)
+
+ await expect(
+ handlers.get('fs:listMarkdownDocuments')!(null, {
+ rootPath: path.resolve('/workspace/unregistered')
+ })
+ ).rejects.toThrow('Access denied: unknown repository or worktree path')
+
+ expect(readdirMock).not.toHaveBeenCalled()
+ })
+
+ it('lists remote markdown documents through the SSH filesystem provider', async () => {
+ const provider = {
+ listFiles: vi
+ .fn()
+ .mockResolvedValue(['README.md', 'docs/guide.mdx', '../outside.md', 'src/app.ts'])
+ }
+ getSshFilesystemProviderMock.mockReturnValue(provider)
+
+ registerFilesystemHandlers(store as never)
+
+ await expect(
+ handlers.get('fs:listMarkdownDocuments')!(null, {
+ rootPath: '/home/user/project',
+ connectionId: 'ssh-1'
+ })
+ ).resolves.toEqual([
+ {
+ filePath: '/home/user/project/docs/guide.mdx',
+ relativePath: 'docs/guide.mdx',
+ basename: 'guide.mdx',
+ name: 'guide'
+ },
+ {
+ filePath: '/home/user/project/README.md',
+ relativePath: 'README.md',
+ basename: 'README.md',
+ name: 'README'
+ }
+ ])
+ })
+
it('routes branch compare queries through the git compare helper', async () => {
getBranchCompareMock.mockResolvedValue({
summary: {
diff --git a/src/main/ipc/filesystem.ts b/src/main/ipc/filesystem.ts
index 50bbf5bcf..902462363 100644
--- a/src/main/ipc/filesystem.ts
+++ b/src/main/ipc/filesystem.ts
@@ -1,6 +1,6 @@
/* eslint-disable max-lines */
import { ipcMain, shell } from 'electron'
-import { readdir, readFile, writeFile, stat, lstat } from 'fs/promises'
+import { readdir, readFile, writeFile, stat, lstat, open } from 'fs/promises'
import { extname } from 'path'
import type { ChildProcess } from 'child_process'
import { wslAwareSpawn } from '../git/runner'
@@ -12,6 +12,7 @@ import type {
GitConflictOperation,
GitDiffResult,
GitStatusResult,
+ MarkdownDocument,
SearchOptions,
SearchResult
} from '../../shared/types'
@@ -47,11 +48,15 @@ import {
import { listQuickOpenFiles } from './filesystem-list-files'
import { registerFilesystemMutationHandlers } from './filesystem-mutations'
import { searchWithGitGrep } from './filesystem-search-git'
+import { listMarkdownDocuments, markdownDocumentsFromRelativePaths } from './markdown-documents'
import { checkRgAvailable } from './rg-availability'
import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch'
import { getSshGitProvider } from '../providers/ssh-git-dispatch'
-const MAX_FILE_SIZE = 5 * 1024 * 1024 // 5MB
+// Why: Monaco has large-file optimizations like VS Code; blocking at 5MB makes
+// ordinary JSON/log files inaccessible before the editor can degrade features.
+const MAX_TEXT_FILE_SIZE = 50 * 1024 * 1024 // 50MB
+const BINARY_PROBE_BYTES = 8192
// Why: previewable binaries (PDFs, images) are rendered by the viewer as
// base64 blobs, not parsed as text — 5MB is tight for real-world PDFs, and
// raising this cap only affects binary preview, not text/search paths.
@@ -85,6 +90,17 @@ function isBinaryBuffer(buffer: Buffer): boolean {
return false
}
+async function isBinaryFilePrefix(filePath: string): Promise {
+ const handle = await open(filePath, 'r')
+ try {
+ const probe = Buffer.alloc(BINARY_PROBE_BYTES)
+ const { bytesRead } = await handle.read(probe, 0, probe.length, 0)
+ return isBinaryBuffer(probe.subarray(0, bytesRead))
+ } finally {
+ await handle.close()
+ }
+}
+
export function registerFilesystemHandlers(store: Store): void {
void rebuildAuthorizedRootsCache(store)
const activeTextSearches = new Map()
@@ -133,15 +149,15 @@ export function registerFilesystemHandlers(store: Store): void {
const filePath = await resolveAuthorizedPath(args.filePath, store)
const stats = await stat(filePath)
const mimeType = PREVIEWABLE_BINARY_MIME_TYPES[extname(filePath).toLowerCase()]
- const sizeLimit = mimeType ? MAX_PREVIEWABLE_BINARY_SIZE : MAX_FILE_SIZE
+ const sizeLimit = mimeType ? MAX_PREVIEWABLE_BINARY_SIZE : MAX_TEXT_FILE_SIZE
if (stats.size > sizeLimit) {
throw new Error(
`File too large: ${(stats.size / 1024 / 1024).toFixed(1)}MB exceeds ${sizeLimit / 1024 / 1024}MB limit`
)
}
- const buffer = await readFile(filePath)
if (mimeType) {
+ const buffer = await readFile(filePath)
return {
content: buffer.toString('base64'),
isBinary: true,
@@ -153,6 +169,14 @@ export function registerFilesystemHandlers(store: Store): void {
}
}
+ // Why: the text cap is intentionally larger than the old binary cap.
+ // Probe unknown large files first so archives do not get fully buffered
+ // just to discover they are not editable text.
+ if (stats.size > BINARY_PROBE_BYTES && (await isBinaryFilePrefix(filePath))) {
+ return { content: '', isBinary: true }
+ }
+
+ const buffer = await readFile(filePath)
if (isBinaryBuffer(buffer)) {
return { content: '', isBinary: true }
}
@@ -161,6 +185,26 @@ export function registerFilesystemHandlers(store: Store): void {
}
)
+ ipcMain.handle(
+ 'fs:listMarkdownDocuments',
+ async (
+ _event,
+ args: { rootPath: string; connectionId?: string }
+ ): Promise => {
+ if (args.connectionId) {
+ const provider = getSshFilesystemProvider(args.connectionId)
+ if (!provider) {
+ throw new Error(`No filesystem provider for connection "${args.connectionId}"`)
+ }
+ const relativePaths = await provider.listFiles(args.rootPath)
+ return markdownDocumentsFromRelativePaths(args.rootPath, relativePaths)
+ }
+
+ const rootPath = await resolveRegisteredWorktreePath(args.rootPath, store)
+ return listMarkdownDocuments(rootPath)
+ }
+ )
+
ipcMain.handle(
'fs:writeFile',
async (
diff --git a/src/main/ipc/github.test.ts b/src/main/ipc/github.test.ts
index 3b27c64f7..8e0957530 100644
--- a/src/main/ipc/github.test.ts
+++ b/src/main/ipc/github.test.ts
@@ -1,13 +1,20 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
-const { handleMock, getPRForBranchMock, getIssueMock, listIssuesMock, getAuthenticatedViewerMock } =
- vi.hoisted(() => ({
- handleMock: vi.fn(),
- getPRForBranchMock: vi.fn(),
- getIssueMock: vi.fn(),
- listIssuesMock: vi.fn(),
- getAuthenticatedViewerMock: vi.fn()
- }))
+const {
+ handleMock,
+ getPRForBranchMock,
+ getIssueMock,
+ listIssuesMock,
+ listWorkItemsMock,
+ getAuthenticatedViewerMock
+} = vi.hoisted(() => ({
+ handleMock: vi.fn(),
+ getPRForBranchMock: vi.fn(),
+ getIssueMock: vi.fn(),
+ listIssuesMock: vi.fn(),
+ listWorkItemsMock: vi.fn(),
+ getAuthenticatedViewerMock: vi.fn()
+}))
vi.mock('electron', () => ({
ipcMain: {
@@ -19,6 +26,7 @@ vi.mock('../github/client', () => ({
getPRForBranch: getPRForBranchMock,
getIssue: getIssueMock,
listIssues: listIssuesMock,
+ listWorkItems: listWorkItemsMock,
getAuthenticatedViewer: getAuthenticatedViewerMock
}))
@@ -28,16 +36,17 @@ type HandlerMap = Record unknown>
describe('registerGitHubHandlers', () => {
const handlers: HandlerMap = {}
+ type FixtureRepo = {
+ id: string
+ path: string
+ displayName: string
+ badgeColor: string
+ addedAt: number
+ issueSourcePreference?: 'origin' | 'upstream'
+ }
+ let repos: FixtureRepo[] = []
const store = {
- getRepos: () => [
- {
- id: 'repo-1',
- path: '/workspace/repo',
- displayName: 'repo',
- badgeColor: '#000',
- addedAt: 0
- }
- ]
+ getRepos: () => repos
}
const stats = {
hasCountedPR: () => false,
@@ -49,11 +58,26 @@ describe('registerGitHubHandlers', () => {
getPRForBranchMock.mockReset()
getIssueMock.mockReset()
listIssuesMock.mockReset()
+ listWorkItemsMock.mockReset()
getAuthenticatedViewerMock.mockReset()
for (const key of Object.keys(handlers)) {
delete handlers[key]
}
+ // Reset fixture repos to the default single-repo fixture each test, so
+ // individual tests can mutate the list without leaking preferences across
+ // tests (e.g. a preference-threading test could otherwise shadow the
+ // default-undefined assertions in sibling tests).
+ repos = [
+ {
+ id: 'repo-1',
+ path: '/workspace/repo',
+ displayName: 'repo',
+ badgeColor: '#000',
+ addedAt: 0
+ }
+ ]
+
handleMock.mockImplementation((channel, handler) => {
handlers[channel] = handler
})
@@ -85,8 +109,55 @@ describe('registerGitHubHandlers', () => {
expect(getIssueMock).not.toHaveBeenCalled()
})
- it('forwards listIssues for registered repositories', async () => {
- listIssuesMock.mockResolvedValue([])
+ it('forwards listIssues for registered repositories and unwraps items', async () => {
+ listIssuesMock.mockResolvedValue({ items: [] })
+
+ registerGitHubHandlers(store as never, stats as never)
+
+ const result = await handlers['gh:listIssues'](null, {
+ repoPath: '/workspace/repo',
+ limit: 5
+ })
+
+ expect(listIssuesMock).toHaveBeenCalledWith('/workspace/repo', 5, undefined)
+ expect(result).toEqual([])
+ })
+
+ it('drops the error field from listIssues envelope at the IPC boundary', async () => {
+ // Why: src/main/ipc/github.ts intentionally unwraps the { items, error? }
+ // envelope to just `items` to preserve the pre-feature-1
+ // `Promise` contract for `gh:listIssues`. Feature 1's UI
+ // consumes the richer envelope through `gh:listWorkItems` instead. This
+ // test locks in that intentional drop so a future change that starts
+ // propagating the error through this channel (or that throws when an
+ // error is present) is caught.
+ listIssuesMock.mockResolvedValue({
+ items: [],
+ error: {
+ type: 'permission_denied',
+ message:
+ "You don't have permission to read issues for this repository. Check your GitHub token scopes."
+ }
+ })
+
+ registerGitHubHandlers(store as never, stats as never)
+
+ const result = await handlers['gh:listIssues'](null, {
+ repoPath: '/workspace/repo',
+ limit: 5
+ })
+
+ expect(listIssuesMock).toHaveBeenCalledWith('/workspace/repo', 5, undefined)
+ expect(result).toEqual([])
+ })
+
+ it('threads issueSourcePreference through gh:listIssues', async () => {
+ // Why: repo.issueSourcePreference must reach listIssues so the upstream
+ // repo is queried when configured. A regression that drops the arg would
+ // pass the default-fixture tests (which assert `undefined`) silently, so
+ // this test pins the non-undefined preference-threading contract.
+ repos[0].issueSourcePreference = 'upstream'
+ listIssuesMock.mockResolvedValue({ items: [] })
registerGitHubHandlers(store as never, stats as never)
@@ -95,7 +166,31 @@ describe('registerGitHubHandlers', () => {
limit: 5
})
- expect(listIssuesMock).toHaveBeenCalledWith('/workspace/repo', 5)
+ expect(listIssuesMock).toHaveBeenCalledWith('/workspace/repo', 5, 'upstream')
+ })
+
+ it('threads issueSourcePreference through gh:listWorkItems', async () => {
+ // Why: gh:listWorkItems must also forward repo.issueSourcePreference
+ // (5th arg) so the work-items view honors the per-repo source selector.
+ repos[0].issueSourcePreference = 'origin'
+ listWorkItemsMock.mockResolvedValue({ items: [] })
+
+ registerGitHubHandlers(store as never, stats as never)
+
+ await handlers['gh:listWorkItems'](null, {
+ repoPath: '/workspace/repo',
+ limit: 10,
+ query: 'is:open',
+ before: 'cursor-1'
+ })
+
+ expect(listWorkItemsMock).toHaveBeenCalledWith(
+ '/workspace/repo',
+ 10,
+ 'is:open',
+ 'cursor-1',
+ 'origin'
+ )
})
it('forwards the authenticated viewer lookup', async () => {
diff --git a/src/main/ipc/github.ts b/src/main/ipc/github.ts
index cf379f4f8..371bf6cd2 100644
--- a/src/main/ipc/github.ts
+++ b/src/main/ipc/github.ts
@@ -1,3 +1,7 @@
+/* eslint-disable max-lines -- Why: all GitHub IPC handlers stay co-located so
+the repo-path validation, preference-threading, and stats wiring patterns are
+reviewable as one surface. Splitting by feature area would risk drifting
+validation/gate conventions across handler files. */
import { ipcMain } from 'electron'
import { resolve } from 'path'
import type { Repo, GitHubIssueUpdate } from '../../shared/types'
@@ -67,14 +71,17 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi
ipcMain.handle('gh:listIssues', (_event, args: { repoPath: string; limit?: number }) => {
const repo = assertRegisteredRepo(args.repoPath, store)
- return listIssues(repo.path, args.limit)
+ // Why: listIssues now returns { items, error? }. The IPC handler unwraps to
+ // the items array for the existing contract; feature 1's UI consumes the
+ // richer envelope through `gh:listWorkItems` instead.
+ return listIssues(repo.path, args.limit, repo.issueSourcePreference).then((r) => r.items)
})
ipcMain.handle(
'gh:createIssue',
(_event, args: { repoPath: string; title: string; body: string }) => {
const repo = assertRegisteredRepo(args.repoPath, store)
- return createIssue(repo.path, args.title, args.body)
+ return createIssue(repo.path, args.title, args.body, repo.issueSourcePreference)
}
)
@@ -82,13 +89,19 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi
'gh:listWorkItems',
(_event, args: { repoPath: string; limit?: number; query?: string; before?: string }) => {
const repo = assertRegisteredRepo(args.repoPath, store)
- return listWorkItems(repo.path, args.limit, args.query, args.before)
+ return listWorkItems(
+ repo.path,
+ args.limit,
+ args.query,
+ args.before,
+ repo.issueSourcePreference
+ )
}
)
ipcMain.handle('gh:countWorkItems', (_event, args: { repoPath: string; query?: string }) => {
const repo = assertRegisteredRepo(args.repoPath, store)
- return countWorkItems(repo.path, args.query)
+ return countWorkItems(repo.path, args.query, repo.issueSourcePreference)
})
ipcMain.handle('gh:workItem', (_event, args: WorkItemArgs) =>
@@ -312,16 +325,23 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi
ipcMain.handle('gh:listLabels', (_event, args: { repoPath: string }) => {
const repo = assertRegisteredRepo(args.repoPath, store)
- return listLabels(repo.path)
+ return listLabels(repo.path, repo.issueSourcePreference)
})
ipcMain.handle('gh:listAssignableUsers', (_event, args: { repoPath: string }) => {
const repo = assertRegisteredRepo(args.repoPath, store)
- return listAssignableUsers(repo.path)
+ return listAssignableUsers(repo.path, repo.issueSourcePreference)
})
// Star operations target the Orca repo itself — no repoPath validation needed
ipcMain.handle('gh:viewer', () => getAuthenticatedViewer())
ipcMain.handle('gh:checkOrcaStarred', () => checkOrcaStarred())
ipcMain.handle('gh:starOrca', () => starOrca())
+
+ // Why: issue-source preference writes go through the generic `repos:update`
+ // IPC (extended in this PR to accept `issueSourcePreference`). Routing
+ // through the same channel keeps a single write path, guarantees the
+ // `repos:changed` broadcast is emitted, and avoids two channels racing to
+ // persist the same field with different validation and eviction semantics.
+ // Reads piggyback on the `Repo` record already delivered by `repos:list`.
}
diff --git a/src/main/ipc/markdown-documents.ts b/src/main/ipc/markdown-documents.ts
new file mode 100644
index 000000000..cedf854be
--- /dev/null
+++ b/src/main/ipc/markdown-documents.ts
@@ -0,0 +1,98 @@
+import { readdir } from 'fs/promises'
+import { basename as pathBasename, extname, join, relative } from 'path'
+import type { MarkdownDocument } from '../../shared/types'
+
+function normalizeRelativePath(path: string): string {
+ return path.replace(/[\\/]+/g, '/').replace(/^\/+/, '')
+}
+
+function isMarkdownDocumentName(name: string): boolean {
+ const extension = extname(name).toLowerCase()
+ return extension === '.md' || extension === '.mdx' || extension === '.markdown'
+}
+
+function basenameFromRelativePath(relativePath: string): string {
+ const normalizedPath = relativePath.replaceAll('\\', '/')
+ return normalizedPath.slice(normalizedPath.lastIndexOf('/') + 1)
+}
+
+function isSafeRelativePath(relativePath: string): boolean {
+ return !relativePath.split('/').includes('..')
+}
+
+function toMarkdownDocument(rootPath: string, filePath: string): MarkdownDocument {
+ const basename = pathBasename(filePath)
+ const extension = extname(basename)
+ return {
+ filePath,
+ relativePath: normalizeRelativePath(relative(rootPath, filePath)),
+ basename,
+ name: extension ? basename.slice(0, -extension.length) : basename
+ }
+}
+
+export function markdownDocumentFromRelativePath(
+ rootPath: string,
+ relativePath: string
+): MarkdownDocument | null {
+ const normalizedRelativePath = normalizeRelativePath(relativePath)
+ // Why: SSH providers should return root-relative paths; reject escape
+ // segments before building a synthetic absolute path for renderer use.
+ if (!isSafeRelativePath(normalizedRelativePath)) {
+ return null
+ }
+ const basename = basenameFromRelativePath(normalizedRelativePath)
+ if (!isMarkdownDocumentName(basename)) {
+ return null
+ }
+ const extension = extname(basename)
+ const normalizedRoot = rootPath.replace(/[\\/]+$/, '')
+ return {
+ filePath: `${normalizedRoot}/${normalizedRelativePath}`,
+ relativePath: normalizedRelativePath,
+ basename,
+ name: extension ? basename.slice(0, -extension.length) : basename
+ }
+}
+
+export function markdownDocumentsFromRelativePaths(
+ rootPath: string,
+ relativePaths: string[]
+): MarkdownDocument[] {
+ return relativePaths
+ .map((relativePath) => markdownDocumentFromRelativePath(rootPath, relativePath))
+ .filter((document): document is MarkdownDocument => document !== null)
+ .sort((a, b) => a.relativePath.localeCompare(b.relativePath))
+}
+
+export async function listMarkdownDocuments(rootPath: string): Promise {
+ const documents: MarkdownDocument[] = []
+
+ async function visitDirectory(dirPath: string): Promise {
+ const entries = await readdir(dirPath, { withFileTypes: true })
+ for (const entry of entries) {
+ if (entry.isSymbolicLink()) {
+ continue
+ }
+
+ const entryPath = join(dirPath, entry.name)
+ if (entry.isDirectory()) {
+ if (entry.name === '.git' || entry.name === 'node_modules') {
+ continue
+ }
+ if (entry.name.startsWith('.') && entry.name !== '.github') {
+ continue
+ }
+ await visitDirectory(entryPath)
+ continue
+ }
+
+ if (entry.isFile() && isMarkdownDocumentName(entry.name)) {
+ documents.push(toMarkdownDocument(rootPath, entryPath))
+ }
+ }
+ }
+
+ await visitDirectory(rootPath)
+ return documents.sort((a, b) => a.relativePath.localeCompare(b.relativePath))
+}
diff --git a/src/main/ipc/pty-management.test.ts b/src/main/ipc/pty-management.test.ts
new file mode 100644
index 000000000..9e4c6c93f
--- /dev/null
+++ b/src/main/ipc/pty-management.test.ts
@@ -0,0 +1,414 @@
+/* eslint-disable max-lines -- Why: covers every pty:management IPC channel
+against shared mocks (electron, fs, daemon-init, DaemonPtyRouter). Splitting
+across files would duplicate the vi.hoisted setup and the shared helpers,
+with no meaningful ownership seam. */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { DaemonSessionInfo } from '../daemon/types'
+
+const { handleMock, removeHandlerMock, getDaemonProviderMock, restartDaemonMock } = vi.hoisted(
+ () => ({
+ handleMock: vi.fn(),
+ removeHandlerMock: vi.fn(),
+ getDaemonProviderMock: vi.fn(),
+ restartDaemonMock: vi.fn()
+ })
+)
+
+vi.mock('electron', () => ({
+ ipcMain: { handle: handleMock, removeHandler: removeHandlerMock }
+}))
+
+vi.mock('../daemon/daemon-init', () => ({
+ getDaemonProvider: getDaemonProviderMock,
+ restartDaemon: restartDaemonMock
+}))
+
+// Why: the handler uses `provider instanceof DaemonPtyRouter` to branch
+// between "plain adapter" and "router with current + legacy adapters".
+// Mock the class here so tests can construct real instances via `new
+// DaemonPtyRouter(...)` and the instanceof check returns true. The real
+// router's constructor is side-effect heavy (subscribes to adapter events),
+// so we only keep the accessors that pty-management touches — enough to
+// satisfy the runtime type check without pulling in all the wiring.
+vi.mock('../daemon/daemon-pty-router', () => {
+ class DaemonPtyRouter {
+ private allAdapters: unknown[]
+ constructor(opts: { current: unknown; legacy: unknown[] }) {
+ this.allAdapters = [opts.current, ...opts.legacy]
+ }
+ getAllAdapters() {
+ return this.allAdapters
+ }
+ }
+ return { DaemonPtyRouter }
+})
+
+type HandlerMap = Record unknown>
+
+function buildHandlerMap(): HandlerMap {
+ const map: HandlerMap = {}
+ for (const call of handleMock.mock.calls) {
+ const [channel, handler] = call as [string, (event: unknown, args?: unknown) => unknown]
+ map[channel] = handler
+ }
+ return map
+}
+
+function makeSession(
+ sessionId: string,
+ overrides: Partial = {}
+): DaemonSessionInfo {
+ return {
+ sessionId,
+ state: 'running',
+ shellState: 'ready',
+ isAlive: true,
+ pid: 1234,
+ cwd: '/home/user',
+ cols: 80,
+ rows: 24,
+ createdAt: 0,
+ protocolVersion: 4,
+ ...overrides
+ }
+}
+
+type MockAdapter = {
+ protocolVersion: number
+ listSessions: ReturnType
+ shutdown: ReturnType
+}
+
+function makeAdapter(
+ protocolVersion: number,
+ sessions: DaemonSessionInfo[],
+ shutdownImpl?: (id: string, immediate: boolean) => Promise
+): MockAdapter {
+ // Why: collectSessions calls adapter.listSessions() (the daemon-side RPC)
+ // and then annotates with adapter.protocolVersion. The mock returns the
+ // *internal* SessionInfo shape (no protocolVersion) since the adapter adds
+ // it. Stripping it here mirrors production behavior.
+ return {
+ protocolVersion,
+ listSessions: vi.fn(async () => sessions.map(({ protocolVersion: _pv, ...rest }) => rest)),
+ shutdown: vi.fn(shutdownImpl ?? (async () => {}))
+ }
+}
+
+async function importFresh() {
+ vi.resetModules()
+ handleMock.mockClear()
+ removeHandlerMock.mockClear()
+ return import('./pty-management')
+}
+
+async function makeRouter(current: MockAdapter, legacy: MockAdapter[] = []) {
+ const { DaemonPtyRouter } = await import('../daemon/daemon-pty-router')
+ return new DaemonPtyRouter({ current: current as never, legacy: legacy as never })
+}
+
+describe('pty:management IPC handlers', () => {
+ beforeEach(() => {
+ getDaemonProviderMock.mockReset()
+ restartDaemonMock.mockReset()
+ })
+
+ afterEach(() => {
+ vi.clearAllMocks()
+ })
+
+ describe('listSessions', () => {
+ it('merges sessions across current + legacy adapters with protocolVersion', async () => {
+ const current = makeAdapter(4, [makeSession('new-1'), makeSession('new-2')])
+ const legacy = makeAdapter(3, [makeSession('old-1', { protocolVersion: 3 })])
+ const { registerDaemonManagementHandlers } = await importFresh()
+ getDaemonProviderMock.mockReturnValue(await makeRouter(current, [legacy]))
+ registerDaemonManagementHandlers()
+
+ const handlers = buildHandlerMap()
+ const result = (await handlers['pty:management:listSessions']({})) as {
+ sessions: DaemonSessionInfo[]
+ }
+
+ expect(result.sessions).toHaveLength(3)
+ const byId = new Map(result.sessions.map((s) => [s.sessionId, s]))
+ expect(byId.get('new-1')?.protocolVersion).toBe(4)
+ expect(byId.get('new-2')?.protocolVersion).toBe(4)
+ expect(byId.get('old-1')?.protocolVersion).toBe(3)
+ })
+
+ it('returns empty list when no daemon provider is installed', async () => {
+ getDaemonProviderMock.mockReturnValue(null)
+
+ const { registerDaemonManagementHandlers } = await importFresh()
+ registerDaemonManagementHandlers()
+
+ const handlers = buildHandlerMap()
+ const result = (await handlers['pty:management:listSessions']({})) as {
+ sessions: DaemonSessionInfo[]
+ }
+
+ expect(result.sessions).toEqual([])
+ })
+
+ it('tolerates a failing adapter by skipping its sessions', async () => {
+ const current = makeAdapter(4, [makeSession('new-1')])
+ const legacy = makeAdapter(3, [])
+ legacy.listSessions = vi.fn(async () => {
+ throw new Error('legacy socket dead')
+ })
+ const { registerDaemonManagementHandlers } = await importFresh()
+ getDaemonProviderMock.mockReturnValue(await makeRouter(current, [legacy]))
+ registerDaemonManagementHandlers()
+
+ const handlers = buildHandlerMap()
+ const result = (await handlers['pty:management:listSessions']({})) as {
+ sessions: DaemonSessionInfo[]
+ }
+
+ expect(result.sessions).toHaveLength(1)
+ expect(result.sessions[0].sessionId).toBe('new-1')
+ })
+ })
+
+ describe('killAll', () => {
+ // Why: the handler sleeps POLL_INTERVAL_MS between listSessions polls.
+ // Fake timers let the tests drive that loop deterministically — without
+ // them, a happy-path test that converges in ≥1 poll would take 100ms+
+ // of real wall time and the "refuses to die" test would take ~1s.
+ beforeEach(() => {
+ vi.useFakeTimers()
+ })
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ async function runKillAllWithPolls(
+ handler: (event: unknown, args?: unknown) => unknown,
+ pollCount: number = 65
+ ): Promise<{ killedCount: number; remainingCount: number }> {
+ const resultPromise = handler({}) as Promise<{
+ killedCount: number
+ remainingCount: number
+ }>
+ // Why: advance the loop's sleeps one at a time. Between each sleep the
+ // handler awaits collectSessions (a microtask), so we need to flush
+ // pending microtasks before advancing the next timer.
+ for (let i = 0; i < pollCount; i += 1) {
+ await Promise.resolve()
+ await Promise.resolve()
+ await vi.advanceTimersByTimeAsync(100)
+ }
+ return resultPromise
+ }
+
+ it('fires one shutdown per initial session and polls until empty', async () => {
+ const currentSessions = [makeSession('new-1'), makeSession('new-2')]
+ const legacySessions = [makeSession('old-1', { protocolVersion: 3 })]
+ const current = makeAdapter(4, [])
+ const legacy = makeAdapter(3, [])
+ // Why: shutdown removes the session from the adapter's backing list so
+ // the next poll observes the shrinking set — mirrors a daemon that
+ // actually reaped the processes.
+ const removeFrom = (list: DaemonSessionInfo[], id: string): void => {
+ const idx = list.findIndex((s) => s.sessionId === id)
+ if (idx !== -1) {
+ list.splice(idx, 1)
+ }
+ }
+ current.listSessions = vi.fn(async () =>
+ currentSessions.map(({ protocolVersion: _pv, ...rest }) => rest)
+ )
+ legacy.listSessions = vi.fn(async () =>
+ legacySessions.map(({ protocolVersion: _pv, ...rest }) => rest)
+ )
+ current.shutdown = vi.fn(async (id: string) => {
+ removeFrom(currentSessions, id)
+ })
+ legacy.shutdown = vi.fn(async (id: string) => {
+ removeFrom(legacySessions, id)
+ })
+ const { registerDaemonManagementHandlers } = await importFresh()
+ getDaemonProviderMock.mockReturnValue(await makeRouter(current, [legacy]))
+ registerDaemonManagementHandlers()
+
+ const handlers = buildHandlerMap()
+ const result = await runKillAllWithPolls(handlers['pty:management:killAll'])
+
+ expect(result).toEqual({ killedCount: 3, remainingCount: 0 })
+ // Each initial session receives exactly one shutdown — no retries.
+ expect(current.shutdown).toHaveBeenCalledTimes(2)
+ expect(current.shutdown).toHaveBeenCalledWith('new-1', true)
+ expect(current.shutdown).toHaveBeenCalledWith('new-2', true)
+ expect(legacy.shutdown).toHaveBeenCalledTimes(1)
+ expect(legacy.shutdown).toHaveBeenCalledWith('old-1', true)
+ })
+
+ it('reports remainingCount when sessions refuse to die after the poll window', async () => {
+ const sessions = [makeSession('stuck')]
+ const current = makeAdapter(4, [])
+ current.listSessions = vi.fn(async () =>
+ sessions.map(({ protocolVersion: _pv, ...rest }) => rest)
+ )
+ // Why: shutdown resolves but the session never leaves listSessions —
+ // simulates a process wedged in uninterruptible sleep. After the poll
+ // window (≈6.5s, past the daemon's 5s SIGTERM→SIGKILL ladder) the
+ // handler must return remainingCount=1 rather than loop forever.
+ current.shutdown = vi.fn(async () => {})
+ const { registerDaemonManagementHandlers } = await importFresh()
+ getDaemonProviderMock.mockReturnValue(await makeRouter(current))
+ registerDaemonManagementHandlers()
+
+ const handlers = buildHandlerMap()
+ const result = await runKillAllWithPolls(handlers['pty:management:killAll'])
+
+ expect(result).toEqual({ killedCount: 0, remainingCount: 1 })
+ // One shutdown fired — no per-session retry. Initial-snapshot
+ // accounting means the stuck session is counted once.
+ expect(current.shutdown).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not count respawned sessions with fresh IDs against remainingCount', async () => {
+ // Why: mounted panes may re-call pty:spawn with brand-new session IDs
+ // while killAll is polling (tab remount, navigate-back). Those fresh
+ // IDs are not part of the initial snapshot and must not inflate the
+ // "refused to exit" count — the user asked to kill what was alive
+ // when the button was pressed, not to chase new spawns.
+ const liveSessions = [makeSession('a'), makeSession('b')]
+ const current = makeAdapter(4, [])
+ let pollCalls = 0
+ current.listSessions = vi.fn(async () => {
+ pollCalls += 1
+ if (pollCalls === 1) {
+ // Initial snapshot: a and b are alive.
+ return liveSessions.map(({ protocolVersion: _pv, ...rest }) => rest)
+ }
+ // First poll onward: a and b have been reaped, but the renderer
+ // respawned a fresh pane with id 'c'. 'c' was never in the initial
+ // snapshot, so it must not count as remaining.
+ return [makeSession('c')].map(({ protocolVersion: _pv, ...rest }) => rest)
+ })
+ current.shutdown = vi.fn(async () => {})
+ const { registerDaemonManagementHandlers } = await importFresh()
+ getDaemonProviderMock.mockReturnValue(await makeRouter(current))
+ registerDaemonManagementHandlers()
+
+ const handlers = buildHandlerMap()
+ const result = await runKillAllWithPolls(handlers['pty:management:killAll'])
+
+ expect(result).toEqual({ killedCount: 2, remainingCount: 0 })
+ })
+
+ it('swallows per-session shutdown rejections without stopping the batch', async () => {
+ const sessionsList = [makeSession('a'), makeSession('b')]
+ const current = makeAdapter(4, [])
+ current.listSessions = vi.fn(async () =>
+ sessionsList.map(({ protocolVersion: _pv, ...rest }) => rest)
+ )
+ // Why: a rejecting shutdown for 'a' must not block the shutdown of 'b'.
+ // Since shutdowns fire in parallel (Promise.allSettled), both must be
+ // invoked regardless of 'a' throwing.
+ const removeFrom = (id: string): void => {
+ const idx = sessionsList.findIndex((s) => s.sessionId === id)
+ if (idx !== -1) {
+ sessionsList.splice(idx, 1)
+ }
+ }
+ current.shutdown = vi.fn(async (id: string) => {
+ if (id === 'a') {
+ throw new Error('a is stuck')
+ }
+ removeFrom(id)
+ })
+ const { registerDaemonManagementHandlers } = await importFresh()
+ getDaemonProviderMock.mockReturnValue(await makeRouter(current))
+ registerDaemonManagementHandlers()
+
+ const handlers = buildHandlerMap()
+ const result = await runKillAllWithPolls(handlers['pty:management:killAll'])
+
+ expect(current.shutdown).toHaveBeenCalledWith('a', true)
+ expect(current.shutdown).toHaveBeenCalledWith('b', true)
+ // 'a' rejected and is still alive → counts as remaining; 'b' reaped.
+ expect(result).toEqual({ killedCount: 1, remainingCount: 1 })
+ })
+ })
+
+ describe('killOne', () => {
+ it('routes to the adapter whose protocolVersion owns the session', async () => {
+ const current = makeAdapter(4, [makeSession('new-1')])
+ const legacy = makeAdapter(3, [makeSession('old-1', { protocolVersion: 3 })])
+ const { registerDaemonManagementHandlers } = await importFresh()
+ getDaemonProviderMock.mockReturnValue(await makeRouter(current, [legacy]))
+ registerDaemonManagementHandlers()
+
+ const handlers = buildHandlerMap()
+ const result = (await handlers['pty:management:killOne']({}, { sessionId: 'old-1' })) as {
+ success: boolean
+ }
+
+ expect(result.success).toBe(true)
+ expect(legacy.shutdown).toHaveBeenCalledWith('old-1', true)
+ expect(current.shutdown).not.toHaveBeenCalled()
+ })
+
+ it('returns success=false for unknown sessionId', async () => {
+ const current = makeAdapter(4, [makeSession('new-1')])
+ const { registerDaemonManagementHandlers } = await importFresh()
+ getDaemonProviderMock.mockReturnValue(await makeRouter(current))
+ registerDaemonManagementHandlers()
+
+ const handlers = buildHandlerMap()
+ const result = (await handlers['pty:management:killOne']({}, { sessionId: 'ghost' })) as {
+ success: boolean
+ }
+
+ expect(result.success).toBe(false)
+ expect(current.shutdown).not.toHaveBeenCalled()
+ })
+
+ it('rejects empty/missing sessionId without hitting the adapter', async () => {
+ const current = makeAdapter(4, [makeSession('new-1')])
+ const { registerDaemonManagementHandlers } = await importFresh()
+ getDaemonProviderMock.mockReturnValue(await makeRouter(current))
+ registerDaemonManagementHandlers()
+
+ const handlers = buildHandlerMap()
+ const result = (await handlers['pty:management:killOne']({}, { sessionId: '' })) as {
+ success: boolean
+ }
+
+ expect(result.success).toBe(false)
+ expect(current.listSessions).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('restart', () => {
+ it('delegates to restartDaemon and reports success', async () => {
+ restartDaemonMock.mockResolvedValue({ killedCount: 2 })
+
+ const { registerDaemonManagementHandlers } = await importFresh()
+ registerDaemonManagementHandlers()
+
+ const handlers = buildHandlerMap()
+ const result = (await handlers['pty:management:restart']({})) as { success: boolean }
+
+ expect(result.success).toBe(true)
+ expect(restartDaemonMock).toHaveBeenCalledTimes(1)
+ })
+
+ it('returns success=false when restartDaemon throws', async () => {
+ restartDaemonMock.mockRejectedValue(new Error('spawn failed'))
+
+ const { registerDaemonManagementHandlers } = await importFresh()
+ registerDaemonManagementHandlers()
+
+ const handlers = buildHandlerMap()
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const result = (await handlers['pty:management:restart']({})) as { success: boolean }
+ consoleErrorSpy.mockRestore()
+
+ expect(result.success).toBe(false)
+ })
+ })
+})
diff --git a/src/main/ipc/pty-management.ts b/src/main/ipc/pty-management.ts
new file mode 100644
index 000000000..05d8f4ab1
--- /dev/null
+++ b/src/main/ipc/pty-management.ts
@@ -0,0 +1,171 @@
+import { ipcMain } from 'electron'
+import { DaemonPtyRouter } from '../daemon/daemon-pty-router'
+import type { DaemonPtyAdapter } from '../daemon/daemon-pty-adapter'
+import { getDaemonProvider, restartDaemon } from '../daemon/daemon-init'
+import type { DaemonSessionInfo } from '../daemon/types'
+
+// Why: the daemon's session.kill() sends SIGTERM first and escalates to
+// SIGKILL after a 5s grace window (KILL_TIMEOUT_MS in session.ts). We have
+// to poll past that ladder, or well-behaved-but-slow shells (zsh hosting a
+// long-running agent) look like they "refused to exit" when they're actually
+// still inside their SIGTERM handler waiting for SIGKILL. 65 polls at 100ms
+// each (≈6.5s) covers the 5s ladder plus ~1.5s of slack for the final
+// SIGKILL reap and the adapter's listSessions IPC roundtrip. The user waits
+// during this window with a spinner; the alternative — reporting fake
+// "refused" numbers — is worse.
+const MAX_POLL_ATTEMPTS = 65
+const POLL_INTERVAL_MS = 100
+
+function sleep(ms: number): Promise {
+ return new Promise((resolve) => setTimeout(resolve, ms))
+}
+
+function getDaemonAdapters(): DaemonPtyAdapter[] {
+ const provider = getDaemonProvider()
+ if (!provider) {
+ return []
+ }
+ if (provider instanceof DaemonPtyRouter) {
+ return [...provider.getAllAdapters()]
+ }
+ return [provider]
+}
+
+async function collectSessions(adapters: DaemonPtyAdapter[]): Promise {
+ const results = await Promise.allSettled(
+ adapters.map(async (adapter) => {
+ const sessions = await adapter.listSessions()
+ return sessions.map((s) => ({
+ ...s,
+ protocolVersion: adapter.protocolVersion
+ }))
+ })
+ )
+ return results.flatMap((r) => (r.status === 'fulfilled' ? r.value : []))
+}
+
+export function registerDaemonManagementHandlers(): void {
+ ipcMain.removeHandler('pty:management:listSessions')
+ ipcMain.removeHandler('pty:management:killAll')
+ ipcMain.removeHandler('pty:management:killOne')
+ ipcMain.removeHandler('pty:management:restart')
+
+ ipcMain.handle(
+ 'pty:management:listSessions',
+ async (): Promise<{ sessions: DaemonSessionInfo[] }> => {
+ const sessions = await collectSessions(getDaemonAdapters())
+ return { sessions }
+ }
+ )
+
+ // Why: killAll operates on *sessions* (user-facing concept), not daemons, so
+ // it fans across every adapter — current + legacy — to match the user's
+ // "kill everything I might be attached to" mental model. The daemon
+ // processes themselves survive; only sessions are torn down. See
+ // docs/daemon-staleness-ux.md §Phase 1 "Scope rationale" for why legacy
+ // daemons aren't killed here.
+ ipcMain.handle(
+ 'pty:management:killAll',
+ async (): Promise<{ killedCount: number; remainingCount: number }> => {
+ const adapters = getDaemonAdapters()
+ // Why: snapshot the initial session set once, up front. All subsequent
+ // accounting is relative to these IDs. If the renderer respawns panes
+ // with *fresh* session IDs while we're polling (e.g. a remount fires
+ // pty:spawn mid-kill), those new sessions must not count as
+ // "remaining" — the user asked to kill what was alive at the moment
+ // they clicked the button, not to chase new spawns.
+ const initial = await collectSessions(adapters)
+ const initialIds = new Set(initial.map((s) => s.sessionId))
+ const initialCount = initial.length
+
+ if (initialCount === 0) {
+ return { killedCount: 0, remainingCount: 0 }
+ }
+
+ // Why: fire one shutdown per initial session, in parallel, once — no
+ // per-session retry. The daemon's session.kill() is idempotent and
+ // schedules its own SIGTERM→SIGKILL ladder; firing the RPC repeatedly
+ // in a tight retry loop before the grace window expires just races our
+ // own polling. Promise.allSettled ensures a single adapter failure (or
+ // rejected RPC — e.g. session already exiting) does not short-circuit
+ // the remaining shutdowns.
+ await Promise.allSettled(
+ initial.map(async (session) => {
+ // Why: protocolVersion is unique across adapters by construction —
+ // PROTOCOL_VERSION is always distinct from every entry in
+ // PREVIOUS_DAEMON_PROTOCOL_VERSIONS (see types.ts). If a future
+ // bump forgets to rotate the retired version into the previous
+ // list, this find() would silently route legacy sessions to the
+ // current adapter. Keep the two constants in lockstep.
+ const owner = adapters.find((a) => a.protocolVersion === session.protocolVersion)
+ if (!owner) {
+ return
+ }
+ // Why: immediate=true is the adapter's "kill it now" signal. The
+ // current adapter ignores the flag (the daemon's SIGTERM→SIGKILL
+ // ladder handles escalation) but preserve it for legacy adapters
+ // and so a future adapter could honor it. Rejections are swallowed
+ // per-session — remainingCount surfaces truly-stuck sessions in
+ // the toast.
+ await owner.shutdown(session.sessionId, true).catch(() => {})
+ })
+ )
+
+ // Why: poll listSessions every POLL_INTERVAL_MS until none of the
+ // *initial* IDs are still alive, or we've exhausted MAX_POLL_ATTEMPTS.
+ // Counting only the initial-snapshot intersection (not the total
+ // session count) is what keeps the math honest when the renderer
+ // respawns panes with fresh IDs mid-kill.
+ let remainingOriginalCount = initialCount
+ for (let attempt = 0; attempt < MAX_POLL_ATTEMPTS; attempt += 1) {
+ await sleep(POLL_INTERVAL_MS)
+ const current = await collectSessions(adapters)
+ remainingOriginalCount = current.reduce(
+ (count, s) => (initialIds.has(s.sessionId) ? count + 1 : count),
+ 0
+ )
+ if (remainingOriginalCount === 0) {
+ break
+ }
+ }
+
+ const killedCount = initialCount - remainingOriginalCount
+ return { killedCount, remainingCount: remainingOriginalCount }
+ }
+ )
+
+ ipcMain.handle(
+ 'pty:management:killOne',
+ async (_event, args: { sessionId: string }): Promise<{ success: boolean }> => {
+ if (typeof args?.sessionId !== 'string' || args.sessionId.length === 0) {
+ return { success: false }
+ }
+ const adapters = getDaemonAdapters()
+ const sessions = await collectSessions(adapters)
+ const match = sessions.find((s) => s.sessionId === args.sessionId)
+ if (!match) {
+ return { success: false }
+ }
+ const owner = adapters.find((a) => a.protocolVersion === match.protocolVersion)
+ if (!owner) {
+ return { success: false }
+ }
+ try {
+ await owner.shutdown(args.sessionId, true)
+ return { success: true }
+ } catch {
+ return { success: false }
+ }
+ }
+ )
+
+ ipcMain.handle('pty:management:restart', async (): Promise<{ success: boolean }> => {
+ try {
+ await restartDaemon()
+ return { success: true }
+ } catch (err) {
+ console.error('[pty:management] restart failed', err)
+ return { success: false }
+ }
+ })
+}
diff --git a/src/main/ipc/pty.test.ts b/src/main/ipc/pty.test.ts
index 8e34cb0f8..19e8626ff 100644
--- a/src/main/ipc/pty.test.ts
+++ b/src/main/ipc/pty.test.ts
@@ -20,7 +20,8 @@ const {
openCodeClearPtyMock,
buildAgentHookEnvMock,
piBuildPtyEnvMock,
- piClearPtyMock
+ piClearPtyMock,
+ isPwshAvailableMock
} = vi.hoisted(() => ({
handleMock: vi.fn(),
onMock: vi.fn(),
@@ -35,6 +36,7 @@ const {
getPathMock: vi.fn(),
spawnMock: vi.fn(),
openCodeBuildPtyEnvMock: vi.fn(),
+ isPwshAvailableMock: vi.fn(),
openCodeClearPtyMock: vi.fn(),
buildAgentHookEnvMock: vi.fn(),
piBuildPtyEnvMock: vi.fn(),
@@ -89,6 +91,10 @@ vi.mock('../pi/titlebar-extension-service', () => ({
clearPty: piClearPtyMock
}
}))
+
+vi.mock('../pwsh', () => ({
+ isPwshAvailable: isPwshAvailableMock
+}))
import { LocalPtyProvider } from '../providers/local-pty-provider'
import {
registerPtyHandlers,
@@ -135,6 +141,7 @@ describe('registerPtyHandlers', () => {
buildAgentHookEnvMock.mockReset()
piBuildPtyEnvMock.mockReset()
piClearPtyMock.mockReset()
+ isPwshAvailableMock.mockReset()
mainWindow.webContents.on.mockReset()
mainWindow.webContents.send.mockReset()
@@ -159,6 +166,7 @@ describe('registerPtyHandlers', () => {
? '/tmp/orca-pi-agent-overlay'
: '/tmp/orca-pi-agent-overlay'
}))
+ isPwshAvailableMock.mockReturnValue(false)
spawnMock.mockReturnValue({
onData: vi.fn(() => makeDisposable()),
onExit: vi.fn(() => makeDisposable()),
@@ -994,6 +1002,178 @@ describe('registerPtyHandlers', () => {
expect.any(Object)
)
})
+
+ it('spawns powershell.exe when PowerShell family keeps the inbox implementation', () => {
+ process.env.COMSPEC = 'C:\\Windows\\system32\\cmd.exe'
+
+ registerPtyHandlers(
+ mainWindow as never,
+ undefined,
+ undefined,
+ () =>
+ ({
+ terminalWindowsShell: 'powershell.exe',
+ terminalWindowsPowerShellImplementation: 'powershell.exe'
+ }) as never
+ )
+ handlers.get('pty:spawn')!(null, { cols: 80, rows: 24 })
+
+ expect(spawnMock).toHaveBeenCalledWith(
+ 'powershell.exe',
+ [
+ '-NoExit',
+ '-Command',
+ 'try { . $PROFILE } catch {}; [Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Console]::InputEncoding = [System.Text.Encoding]::UTF8'
+ ],
+ expect.any(Object)
+ )
+ })
+
+ it('spawns pwsh.exe when PowerShell 7 is selected and available', () => {
+ process.env.COMSPEC = 'C:\\Windows\\system32\\cmd.exe'
+ isPwshAvailableMock.mockReturnValue(true)
+
+ registerPtyHandlers(
+ mainWindow as never,
+ undefined,
+ undefined,
+ () =>
+ ({
+ terminalWindowsShell: 'powershell.exe',
+ terminalWindowsPowerShellImplementation: 'pwsh.exe'
+ }) as never
+ )
+ handlers.get('pty:spawn')!(null, { cols: 80, rows: 24 })
+
+ expect(spawnMock).toHaveBeenCalledWith(
+ 'pwsh.exe',
+ [
+ '-NoExit',
+ '-Command',
+ 'try { . $PROFILE } catch {}; [Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Console]::InputEncoding = [System.Text.Encoding]::UTF8'
+ ],
+ expect.any(Object)
+ )
+ })
+
+ it('falls back to powershell.exe when PowerShell 7 is selected but unavailable', () => {
+ process.env.COMSPEC = 'C:\\Windows\\system32\\cmd.exe'
+ isPwshAvailableMock.mockReturnValue(false)
+
+ registerPtyHandlers(
+ mainWindow as never,
+ undefined,
+ undefined,
+ () =>
+ ({
+ terminalWindowsShell: 'powershell.exe',
+ terminalWindowsPowerShellImplementation: 'pwsh.exe'
+ }) as never
+ )
+ handlers.get('pty:spawn')!(null, { cols: 80, rows: 24 })
+
+ expect(spawnMock).toHaveBeenCalledWith(
+ 'powershell.exe',
+ [
+ '-NoExit',
+ '-Command',
+ 'try { . $PROFILE } catch {}; [Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Console]::InputEncoding = [System.Text.Encoding]::UTF8'
+ ],
+ expect.any(Object)
+ )
+ })
+
+ it('falls back to powershell.exe when shellOverride requests pwsh.exe but pwsh is unavailable', () => {
+ process.env.COMSPEC = 'C:\\Windows\\system32\\cmd.exe'
+ isPwshAvailableMock.mockReturnValue(false)
+
+ registerPtyHandlers(
+ mainWindow as never,
+ undefined,
+ undefined,
+ () =>
+ ({
+ terminalWindowsShell: 'powershell.exe',
+ terminalWindowsPowerShellImplementation: 'pwsh.exe'
+ }) as never
+ )
+ handlers.get('pty:spawn')!(null, { cols: 80, rows: 24, shellOverride: 'pwsh.exe' })
+
+ expect(spawnMock).toHaveBeenCalledWith(
+ 'powershell.exe',
+ [
+ '-NoExit',
+ '-Command',
+ 'try { . $PROFILE } catch {}; [Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Console]::InputEncoding = [System.Text.Encoding]::UTF8'
+ ],
+ expect.any(Object)
+ )
+ })
+
+ it('ignores the PowerShell implementation setting for cmd.exe', () => {
+ process.env.COMSPEC = 'C:\\Windows\\system32\\powershell.exe'
+ isPwshAvailableMock.mockReturnValue(true)
+
+ registerPtyHandlers(
+ mainWindow as never,
+ undefined,
+ undefined,
+ () =>
+ ({
+ terminalWindowsShell: 'cmd.exe',
+ terminalWindowsPowerShellImplementation: 'pwsh.exe'
+ }) as never
+ )
+ handlers.get('pty:spawn')!(null, { cols: 80, rows: 24 })
+
+ expect(spawnMock).toHaveBeenCalledWith(
+ 'cmd.exe',
+ ['/K', 'chcp 65001 > nul'],
+ expect.any(Object)
+ )
+ })
+
+ it('ignores the PowerShell implementation setting for wsl.exe', () => {
+ process.env.COMSPEC = 'C:\\Windows\\system32\\powershell.exe'
+ isPwshAvailableMock.mockReturnValue(true)
+
+ registerPtyHandlers(
+ mainWindow as never,
+ undefined,
+ undefined,
+ () =>
+ ({
+ terminalWindowsShell: 'wsl.exe',
+ terminalWindowsPowerShellImplementation: 'pwsh.exe'
+ }) as never
+ )
+ handlers.get('pty:spawn')!(null, { cols: 80, rows: 24 })
+
+ expect(spawnMock).toHaveBeenCalledWith('wsl.exe', expect.any(Array), expect.any(Object))
+ })
+
+ it('keeps shellOverride priority for one-off tabs', () => {
+ process.env.COMSPEC = 'C:\\Windows\\system32\\cmd.exe'
+ isPwshAvailableMock.mockReturnValue(false)
+
+ registerPtyHandlers(
+ mainWindow as never,
+ undefined,
+ undefined,
+ () =>
+ ({
+ terminalWindowsShell: 'powershell.exe',
+ terminalWindowsPowerShellImplementation: 'pwsh.exe'
+ }) as never
+ )
+ handlers.get('pty:spawn')!(null, {
+ cols: 80,
+ rows: 24,
+ shellOverride: 'wsl.exe'
+ })
+
+ expect(spawnMock).toHaveBeenCalledWith('wsl.exe', expect.any(Array), expect.any(Object))
+ })
})
it('rejects missing WSL worktree cwd instead of validating only the fallback Windows cwd', async () => {
@@ -1309,12 +1489,17 @@ describe('registerPtyHandlers', () => {
it('disposes PTY listeners before manual kill IPC', async () => {
const onDataDisposable = makeDisposable()
const onExitDisposable = makeDisposable()
+ // Why: hold a stable reference to the kill spy. On POSIX, destroyPtyProcess
+ // in local-pty-provider reassigns proc.kill to a no-op to defuse the
+ // SIGHUP-to-recycled-pid hazard (see docs/fix-pty-fd-leak.md). Reading
+ // proc.kill.mock after that runs would yield a non-mock and crash.
+ const killSpy = vi.fn()
const proc = {
onData: vi.fn(() => onDataDisposable),
onExit: vi.fn(() => onExitDisposable),
write: vi.fn(),
resize: vi.fn(),
- kill: vi.fn(),
+ kill: killSpy,
process: 'zsh',
pid: 12345
}
@@ -1329,22 +1514,23 @@ describe('registerPtyHandlers', () => {
await handlers.get('pty:kill')!(null, { id: spawnResult.id })
expect(onDataDisposable.dispose.mock.invocationCallOrder[0]).toBeLessThan(
- proc.kill.mock.invocationCallOrder[0]
+ killSpy.mock.invocationCallOrder[0]
)
expect(onExitDisposable.dispose.mock.invocationCallOrder[0]).toBeLessThan(
- proc.kill.mock.invocationCallOrder[0]
+ killSpy.mock.invocationCallOrder[0]
)
})
it('disposes PTY listeners before runtime controller kill', async () => {
const onDataDisposable = makeDisposable()
const onExitDisposable = makeDisposable()
+ const killSpy = vi.fn()
const proc = {
onData: vi.fn(() => onDataDisposable),
onExit: vi.fn(() => onExitDisposable),
write: vi.fn(),
resize: vi.fn(),
- kill: vi.fn(),
+ kill: killSpy,
process: 'zsh',
pid: 12345
}
@@ -1368,22 +1554,23 @@ describe('registerPtyHandlers', () => {
expect(runtimeController.kill(spawnResult.id)).toBe(true)
expect(onDataDisposable.dispose.mock.invocationCallOrder[0]).toBeLessThan(
- proc.kill.mock.invocationCallOrder[0]
+ killSpy.mock.invocationCallOrder[0]
)
expect(onExitDisposable.dispose.mock.invocationCallOrder[0]).toBeLessThan(
- proc.kill.mock.invocationCallOrder[0]
+ killSpy.mock.invocationCallOrder[0]
)
})
it('disposes PTY listeners before did-finish-load orphan cleanup', async () => {
const onDataDisposable = makeDisposable()
const onExitDisposable = makeDisposable()
+ const killSpy = vi.fn()
const proc = {
onData: vi.fn(() => onDataDisposable),
onExit: vi.fn(() => onExitDisposable),
write: vi.fn(),
resize: vi.fn(),
- kill: vi.fn(),
+ kill: killSpy,
process: 'zsh',
pid: 12345
}
@@ -1409,10 +1596,10 @@ describe('registerPtyHandlers', () => {
didFinishLoad?.()
expect(onDataDisposable.dispose.mock.invocationCallOrder[0]).toBeLessThan(
- proc.kill.mock.invocationCallOrder[0]
+ killSpy.mock.invocationCallOrder[0]
)
expect(onExitDisposable.dispose.mock.invocationCallOrder[0]).toBeLessThan(
- proc.kill.mock.invocationCallOrder[0]
+ killSpy.mock.invocationCallOrder[0]
)
})
diff --git a/src/main/ipc/pty.ts b/src/main/ipc/pty.ts
index d9f4565f6..37bdada9b 100644
--- a/src/main/ipc/pty.ts
+++ b/src/main/ipc/pty.ts
@@ -12,6 +12,7 @@ import type { GlobalSettings } from '../../shared/types'
import { openCodeHookService } from '../opencode/hook-service'
import { agentHookServer } from '../agent-hooks/server'
import { piTitlebarExtensionService } from '../pi/titlebar-extension-service'
+import { isPwshAvailable } from '../pwsh'
import { LocalPtyProvider } from '../providers/local-pty-provider'
import type { IPtyProvider, PtySpawnOptions, PtySpawnResult } from '../providers/types'
import { mintPtySessionId, isSafePtySessionId } from '../daemon/pty-session-id'
@@ -323,6 +324,30 @@ let localDataUnsub: (() => void) | null = null
let localExitUnsub: (() => void) | null = null
let didFinishLoadHandler: (() => void) | null = null
+// Why: the "Restart daemon" path needs to re-bind provider→renderer listeners
+// against the freshly-created adapter after replaceDaemonProvider swaps the
+// module-level `localProvider` pointer. Without this, old subscribers stay
+// bound to the disposed adapter and new PTY data silently drops. Saved at
+// module scope so the restart flow (src/main/daemon/daemon-init.ts) can
+// trigger a rebind without re-running the full registerPtyHandlers setup.
+let rebindProviderListeners: (() => void) | null = null
+
+export function rebindLocalProviderListeners(): void {
+ rebindProviderListeners?.()
+}
+
+// Why: the "Restart daemon" flow needs to detach listeners from the current
+// adapter *after* synthetic pty:exit events fan out (so the renderer receives
+// them) but *before* replaceDaemonProvider swaps in the new adapter (so the
+// new provider isn't missing bindings). This export narrows that window to
+// the caller.
+export function unbindLocalProviderListeners(): void {
+ localDataUnsub?.()
+ localExitUnsub?.()
+ localDataUnsub = null
+ localExitUnsub = null
+}
+
// ─── IPC Registration ───────────────────────────────────────────────
export function registerPtyHandlers(
@@ -352,6 +377,11 @@ export function registerPtyHandlers(
localProvider.configure({
isHistoryEnabled: () => getSettings?.()?.terminalScopeHistoryByWorktree ?? true,
getWindowsShell: () => getSettings?.()?.terminalWindowsShell,
+ getWindowsPowerShellImplementation: () =>
+ getSettings
+ ? (getSettings()?.terminalWindowsPowerShellImplementation ?? 'auto')
+ : undefined,
+ pwshAvailable: () => isPwshAvailable(),
buildSpawnEnv: (id, baseEnv) => {
const env = buildPtyHostEnv(id, baseEnv, {
isPackaged: app.isPackaged,
@@ -378,10 +408,6 @@ export function registerPtyHandlers(
})
}
- // Wire up provider events → renderer IPC
- localDataUnsub?.()
- localExitUnsub?.()
-
// Why: batching PTY data into short flush windows (8ms ≈ half a frame)
// reduces IPC round-trips from hundreds/sec to ~120/sec under high
// throughput, with no perceptible latency increase for interactive use.
@@ -401,54 +427,66 @@ export function registerPtyHandlers(
pendingData.clear()
}
- // Why: LocalPtyProvider routes data to the runtime via configure().onData,
- // but daemon-backed providers don't have configure(). Without this, daemon
- // PTY data never reaches the runtime's tail buffer, so terminal.read returns
- // empty and agent-detection from raw data never fires.
- const isLocalProvider = localProvider instanceof LocalPtyProvider
+ // Why: extracted so the "Restart daemon" flow can rebind against the fresh
+ // adapter after replaceDaemonProvider runs. Both the startup registration
+ // and the post-restart rebind go through the same code path — no risk of
+ // drift between the two entry points.
+ const bindProviderListeners = (): void => {
+ localDataUnsub?.()
+ localExitUnsub?.()
- localDataUnsub = localProvider.onData((payload) => {
- if (!(localProvider instanceof LocalPtyProvider)) {
- // Why: daemon-backed PTYs emit through provider.onData, not the
- // LocalPtyProvider configure hook. Runtime tails power mobile read/stream.
- runtime?.onPtyData(payload.id, payload.data, Date.now())
- }
- if (mainWindow.isDestroyed()) {
- // Why: clear the pending flush timer so it doesn't fire after the window
- // is gone. Without this, macOS app re-activation leaks orphaned timers
- // from the previous window's registration.
- if (flushTimer) {
- clearTimeout(flushTimer)
- flushTimer = null
+ // Why: LocalPtyProvider routes data to the runtime via configure().onData,
+ // but daemon-backed providers don't have configure(). Without this, daemon
+ // PTY data never reaches the runtime's tail buffer, so terminal.read returns
+ // empty and agent-detection from raw data never fires. Runtime tails also
+ // power mobile read/stream, so they must be notified regardless of window
+ // state.
+ const isLocalProvider = localProvider instanceof LocalPtyProvider
+
+ localDataUnsub = localProvider.onData((payload) => {
+ if (!isLocalProvider) {
+ runtime?.onPtyData(payload.id, payload.data, Date.now())
}
- pendingData.clear()
- return
- }
- const existing = pendingData.get(payload.id)
- pendingData.set(payload.id, existing ? existing + payload.data : payload.data)
- if (!flushTimer) {
- flushTimer = setTimeout(flushPendingData, PTY_BATCH_INTERVAL_MS)
- }
- })
- localExitUnsub = localProvider.onExit((payload) => {
- if (!isLocalProvider) {
- clearProviderPtyState(payload.id)
- ptyOwnership.delete(payload.id)
- markClaudePtyExited(payload.id)
- runtime?.onPtyExit(payload.id, payload.code)
- }
- if (!mainWindow.isDestroyed()) {
- // Why: flush any batched data for this PTY before sending the exit event,
- // otherwise the last ≤8ms of output is silently lost because the renderer
- // tears down the terminal on pty:exit before the batch timer fires.
- const remaining = pendingData.get(payload.id)
- if (remaining) {
- mainWindow.webContents.send('pty:data', { id: payload.id, data: remaining })
- pendingData.delete(payload.id)
+ if (mainWindow.isDestroyed()) {
+ // Why: clear the pending flush timer so it doesn't fire after the window
+ // is gone. Without this, macOS app re-activation leaks orphaned timers
+ // from the previous window's registration.
+ if (flushTimer) {
+ clearTimeout(flushTimer)
+ flushTimer = null
+ }
+ pendingData.clear()
+ return
}
- mainWindow.webContents.send('pty:exit', payload)
- }
- })
+ const existing = pendingData.get(payload.id)
+ pendingData.set(payload.id, existing ? existing + payload.data : payload.data)
+ if (!flushTimer) {
+ flushTimer = setTimeout(flushPendingData, PTY_BATCH_INTERVAL_MS)
+ }
+ })
+ localExitUnsub = localProvider.onExit((payload) => {
+ if (!isLocalProvider) {
+ clearProviderPtyState(payload.id)
+ ptyOwnership.delete(payload.id)
+ markClaudePtyExited(payload.id)
+ runtime?.onPtyExit(payload.id, payload.code)
+ }
+ if (!mainWindow.isDestroyed()) {
+ // Why: flush any batched data for this PTY before sending the exit event,
+ // otherwise the last ≤8ms of output is silently lost because the renderer
+ // tears down the terminal on pty:exit before the batch timer fires.
+ const remaining = pendingData.get(payload.id)
+ if (remaining) {
+ mainWindow.webContents.send('pty:data', { id: payload.id, data: remaining })
+ pendingData.delete(payload.id)
+ }
+ mainWindow.webContents.send('pty:exit', payload)
+ }
+ })
+ }
+
+ bindProviderListeners()
+ rebindProviderListeners = bindProviderListeners
function requestSerializedBuffer(
ptyId: string
@@ -733,6 +771,15 @@ export function registerPtyHandlers(
// for those early bytes; otherwise they default to 80x24 and wrap TUIs.
ptySizes.set(effectiveSessionId, { cols: args.cols, rows: args.rows })
}
+ if (process.platform === 'win32' && !args.connectionId) {
+ // Why: the renderer only models PowerShell as one shell family. Thread
+ // the persisted implementation choice through spawnOptions so both the
+ // in-process and daemon-backed PTY paths can resolve the same effective
+ // executable without inventing a fourth top-level shell.
+ spawnOptions.terminalWindowsPowerShellImplementation = getSettings
+ ? (getSettings()?.terminalWindowsPowerShellImplementation ?? 'auto')
+ : undefined
+ }
let result: PtySpawnResult
try {
result = await provider.spawn(spawnOptions)
diff --git a/src/main/ipc/register-core-handlers.test.ts b/src/main/ipc/register-core-handlers.test.ts
index af3a220a6..25fde4203 100644
--- a/src/main/ipc/register-core-handlers.test.ts
+++ b/src/main/ipc/register-core-handlers.test.ts
@@ -13,6 +13,7 @@ const {
registerDeveloperPermissionHandlersMock,
registerSettingsHandlersMock,
registerShellHandlersMock,
+ registerSidekickHandlersMock,
registerSessionHandlersMock,
registerUIHandlersMock,
registerFilesystemHandlersMock,
@@ -43,6 +44,7 @@ const {
registerDeveloperPermissionHandlersMock: vi.fn(),
registerSettingsHandlersMock: vi.fn(),
registerShellHandlersMock: vi.fn(),
+ registerSidekickHandlersMock: vi.fn(),
registerSessionHandlersMock: vi.fn(),
registerUIHandlersMock: vi.fn(),
registerFilesystemHandlersMock: vi.fn(),
@@ -114,6 +116,10 @@ vi.mock('./shell', () => ({
registerShellHandlers: registerShellHandlersMock
}))
+vi.mock('./sidekick', () => ({
+ registerSidekickHandlers: registerSidekickHandlersMock
+}))
+
vi.mock('./session', () => ({
registerSessionHandlers: registerSessionHandlersMock
}))
@@ -185,6 +191,7 @@ describe('registerCoreHandlers', () => {
registerDeveloperPermissionHandlersMock.mockReset()
registerSettingsHandlersMock.mockReset()
registerShellHandlersMock.mockReset()
+ registerSidekickHandlersMock.mockReset()
registerSessionHandlersMock.mockReset()
registerUIHandlersMock.mockReset()
registerFilesystemHandlersMock.mockReset()
@@ -229,6 +236,7 @@ describe('registerCoreHandlers', () => {
expect(registerCodexUsageHandlersMock).toHaveBeenCalledWith(codexUsage)
expect(registerCodexAccountHandlersMock).toHaveBeenCalledWith(codexAccounts)
expect(registerAgentHookHandlersMock).toHaveBeenCalled()
+ expect(registerSidekickHandlersMock).toHaveBeenCalled()
expect(registerClaudeAccountHandlersMock).toHaveBeenCalledWith(claudeAccounts)
expect(registerRateLimitHandlersMock).toHaveBeenCalledWith(rateLimits)
expect(registerGitHubHandlersMock).toHaveBeenCalledWith(store, stats)
diff --git a/src/main/ipc/register-core-handlers.ts b/src/main/ipc/register-core-handlers.ts
index 002cbde24..cc59c3ac3 100644
--- a/src/main/ipc/register-core-handlers.ts
+++ b/src/main/ipc/register-core-handlers.ts
@@ -24,6 +24,7 @@ import { registerSettingsHandlers } from './settings'
import { registerBrowserHandlers } from './browser'
import { browserSessionRegistry } from '../browser/browser-session-registry'
import { registerShellHandlers } from './shell'
+import { registerSidekickHandlers } from './sidekick'
import { registerUIHandlers } from './ui'
import { registerCodexAccountHandlers } from './codex-accounts'
import { registerAgentHookHandlers } from './agent-hooks'
@@ -89,6 +90,7 @@ export function registerCoreHandlers(
browserSessionRegistry.applyPendingCookieImport()
browserSessionRegistry.restorePersistedUserAgent()
registerShellHandlers()
+ registerSidekickHandlers()
registerSessionHandlers(store)
registerUIHandlers(store)
registerFilesystemHandlers(store)
diff --git a/src/main/ipc/repos-sparse-presets.test.ts b/src/main/ipc/repos-sparse-presets.test.ts
new file mode 100644
index 000000000..71ab88b6a
--- /dev/null
+++ b/src/main/ipc/repos-sparse-presets.test.ts
@@ -0,0 +1,223 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type * as CryptoModule from 'crypto'
+import type { SparsePreset } from '../../shared/types'
+
+const { handleMock, randomUUIDMock, mockStore } = vi.hoisted(() => ({
+ handleMock: vi.fn(),
+ randomUUIDMock: vi.fn(() => 'preset-new'),
+ mockStore: {
+ getRepos: vi.fn().mockReturnValue([]),
+ addRepo: vi.fn(),
+ removeRepo: vi.fn(),
+ getRepo: vi.fn(),
+ updateRepo: vi.fn(),
+ getSparsePresets: vi.fn(),
+ saveSparsePreset: vi.fn(),
+ removeSparsePreset: vi.fn()
+ }
+}))
+
+vi.mock('crypto', async (importOriginal) => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ randomUUID: randomUUIDMock
+ }
+})
+
+vi.mock('electron', () => ({
+ dialog: { showOpenDialog: vi.fn() },
+ ipcMain: {
+ handle: handleMock,
+ removeHandler: vi.fn()
+ }
+}))
+
+vi.mock('../git/repo', () => ({
+ isGitRepo: vi.fn().mockReturnValue(true),
+ getGitUsername: vi.fn().mockReturnValue(''),
+ getRepoName: vi.fn().mockImplementation((path: string) => path.split('/').pop()),
+ getBaseRefDefault: vi.fn().mockResolvedValue('origin/main'),
+ searchBaseRefs: vi.fn().mockResolvedValue([]),
+ BASE_REF_SEARCH_ARGS: ['for-each-ref'],
+ filterBaseRefSearchOutput: vi.fn().mockReturnValue([])
+}))
+
+vi.mock('./filesystem-auth', () => ({
+ rebuildAuthorizedRootsCache: vi.fn().mockResolvedValue(undefined)
+}))
+
+vi.mock('../providers/ssh-git-dispatch', () => ({
+ getSshGitProvider: vi.fn()
+}))
+
+vi.mock('./ssh', () => ({
+ getActiveMultiplexer: vi.fn()
+}))
+
+import { registerRepoHandlers } from './repos'
+
+type HandlerMap = Map unknown>
+
+function makePreset(
+ overrides: Partial & { id: string; repoId: string }
+): SparsePreset {
+ return {
+ name: overrides.id,
+ directories: ['packages/web'],
+ createdAt: 10,
+ updatedAt: 20,
+ ...overrides
+ }
+}
+
+describe('sparse preset repo IPC handlers', () => {
+ const handlers: HandlerMap = new Map()
+ const mainWindow = {
+ isDestroyed: () => false,
+ webContents: { send: vi.fn() }
+ }
+
+ beforeEach(() => {
+ handlers.clear()
+ handleMock.mockReset()
+ handleMock.mockImplementation((channel: string, handler: (...a: unknown[]) => unknown) => {
+ handlers.set(channel, handler)
+ })
+ randomUUIDMock.mockReturnValue('preset-new')
+ mainWindow.webContents.send.mockReset()
+ mockStore.getRepo.mockReset().mockReturnValue({
+ id: 'repo-1',
+ path: '/repo',
+ displayName: 'repo',
+ badgeColor: '#000',
+ addedAt: 0
+ })
+ mockStore.getSparsePresets.mockReset().mockReturnValue([])
+ mockStore.saveSparsePreset.mockReset().mockImplementation((preset: SparsePreset) => preset)
+ mockStore.removeSparsePreset.mockReset()
+
+ registerRepoHandlers(mainWindow as never, mockStore as never)
+ })
+
+ it('normalizes and de-duplicates saved sparse preset directories', () => {
+ const saved = handlers.get('sparsePresets:save')!(null, {
+ repoId: 'repo-1',
+ name: ' Web preset ',
+ directories: [' packages/web ', 'apps\\api\\', 'packages/web/', '.', '']
+ })
+
+ expect(mockStore.saveSparsePreset).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: 'preset-new',
+ repoId: 'repo-1',
+ name: 'Web preset',
+ directories: ['packages/web', 'apps/api']
+ })
+ )
+ expect(saved).toEqual(
+ expect.objectContaining({
+ name: 'Web preset',
+ directories: ['packages/web', 'apps/api']
+ })
+ )
+ expect(mainWindow.webContents.send).toHaveBeenCalledWith('sparsePresets:changed', {
+ repoId: 'repo-1'
+ })
+ })
+
+ it('preserves createdAt and id when editing an existing preset', () => {
+ mockStore.getSparsePresets.mockReturnValue([
+ makePreset({ id: 'preset-1', repoId: 'repo-1', name: 'Old', createdAt: 123 })
+ ])
+
+ const saved = handlers.get('sparsePresets:save')!(null, {
+ repoId: 'repo-1',
+ id: 'preset-1',
+ name: 'New',
+ directories: ['packages/new']
+ })
+
+ expect(saved).toEqual(
+ expect.objectContaining({
+ id: 'preset-1',
+ name: 'New',
+ createdAt: 123,
+ directories: ['packages/new']
+ })
+ )
+ })
+
+ it('rejects invalid sparse preset saves before persistence', () => {
+ expect(() =>
+ handlers.get('sparsePresets:save')!(null, {
+ repoId: 'repo-1',
+ name: 'Web',
+ directories: ['../secrets']
+ })
+ ).toThrow('Preset directories must be repo-relative paths.')
+
+ expect(() =>
+ handlers.get('sparsePresets:save')!(null, {
+ repoId: 'repo-1',
+ name: ' ',
+ directories: ['packages/web']
+ })
+ ).toThrow('Preset name is required.')
+
+ expect(() =>
+ handlers.get('sparsePresets:save')!(null, {
+ repoId: 'repo-1',
+ name: 'Web',
+ directories: ['.', '']
+ })
+ ).toThrow('Preset must have at least one directory.')
+
+ expect(mockStore.saveSparsePreset).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ '/Users/me/repo/packages/web',
+ 'C:\\repo\\packages\\web',
+ '\\\\server\\share\\repo',
+ '\\repo\\packages\\web'
+ ])('rejects absolute sparse preset directory before normalization: %s', (directory) => {
+ expect(() =>
+ handlers.get('sparsePresets:save')!(null, {
+ repoId: 'repo-1',
+ name: 'Web',
+ directories: ['packages/web', directory]
+ })
+ ).toThrow('Preset directories must be repo-relative paths.')
+
+ expect(mockStore.saveSparsePreset).not.toHaveBeenCalled()
+ })
+
+ it('rejects sparse preset saves for unknown repos', () => {
+ mockStore.getRepo.mockReturnValue(null)
+
+ expect(() =>
+ handlers.get('sparsePresets:save')!(null, {
+ repoId: 'missing',
+ name: 'Web',
+ directories: ['packages/web']
+ })
+ ).toThrow('Repo "missing" not found')
+ })
+
+ it('rejects sparse preset removals for unknown repos before persistence', () => {
+ mockStore.getRepo.mockReturnValue(null)
+
+ expect(() =>
+ handlers.get('sparsePresets:remove')!(null, {
+ repoId: 'missing',
+ presetId: 'preset-1'
+ })
+ ).toThrow('Repo "missing" not found')
+
+ expect(mockStore.removeSparsePreset).not.toHaveBeenCalled()
+ expect(mainWindow.webContents.send).not.toHaveBeenCalledWith('sparsePresets:changed', {
+ repoId: 'missing'
+ })
+ })
+})
diff --git a/src/main/ipc/repos.ts b/src/main/ipc/repos.ts
index b59aa8fb7..d35624fac 100644
--- a/src/main/ipc/repos.ts
+++ b/src/main/ipc/repos.ts
@@ -5,7 +5,7 @@ import type { BrowserWindow } from 'electron'
import { dialog, ipcMain } from 'electron'
import { randomUUID } from 'crypto'
import type { Store } from '../persistence'
-import type { Repo, BaseRefDefaultResult } from '../../shared/types'
+import type { Repo, BaseRefDefaultResult, SparsePreset } from '../../shared/types'
import { isFolderRepo } from '../../shared/repo-kind'
import { REPO_COLORS } from '../../shared/constants'
import { rebuildAuthorizedRootsCache } from './filesystem-auth'
@@ -28,6 +28,7 @@ import {
} from '../git/repo'
import { getSshGitProvider } from '../providers/ssh-git-dispatch'
import { getActiveMultiplexer } from './ssh'
+import { normalizeSparseDirectories } from './sparse-checkout-directories'
// Why: module-scoped so the abort handle survives window re-creation on macOS.
// registerRepoHandlers is called again when a new BrowserWindow is created,
@@ -50,6 +51,9 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v
ipcMain.removeHandler('repos:getBaseRefDefault')
ipcMain.removeHandler('repos:searchBaseRefs')
ipcMain.removeHandler('repos:addRemote')
+ ipcMain.removeHandler('sparsePresets:list')
+ ipcMain.removeHandler('sparsePresets:save')
+ ipcMain.removeHandler('sparsePresets:remove')
ipcMain.handle('repos:list', () => {
return store.getRepos()
@@ -207,11 +211,35 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v
args: {
repoId: string
updates: Partial<
- Pick
+ Pick<
+ Repo,
+ | 'displayName'
+ | 'badgeColor'
+ | 'hookSettings'
+ | 'worktreeBaseRef'
+ | 'kind'
+ | 'issueSourcePreference'
+ >
>
}
) => {
- const updated = store.updateRepo(args.repoId, args.updates)
+ // Why: validate the persisted preference string at the IPC boundary
+ // — the TypeScript signature is erased at runtime, and a preload
+ // version skew or renderer bug could otherwise persist a garbage
+ // string that silently collapses to 'auto' in `resolveIssueSource`
+ // (see gh-utils.ts#resolveIssueSource). Strip rather than throw so
+ // other valid fields in the same call still persist.
+ const updates = { ...args.updates }
+ if (
+ 'issueSourcePreference' in updates &&
+ updates.issueSourcePreference !== undefined &&
+ updates.issueSourcePreference !== 'upstream' &&
+ updates.issueSourcePreference !== 'origin' &&
+ updates.issueSourcePreference !== 'auto'
+ ) {
+ delete updates.issueSourcePreference
+ }
+ const updated = store.updateRepo(args.repoId, updates)
if (updated) {
notifyReposChanged(mainWindow)
}
@@ -219,6 +247,55 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v
}
)
+ // ── Sparse presets ─────────────────────────────────────────────
+ // Why: presets are repo-scoped reusable directory lists used by the
+ // new-workspace composer. Persisted via Store and broadcast back to the
+ // renderer so any open composer reflects new/edited/deleted presets
+ // immediately.
+
+ ipcMain.handle('sparsePresets:list', (_event, args: { repoId: string }) => {
+ return store.getSparsePresets(args.repoId)
+ })
+
+ ipcMain.handle(
+ 'sparsePresets:save',
+ (
+ _event,
+ args: { repoId: string; id?: string; name: string; directories: string[] }
+ ): SparsePreset => {
+ const repo = store.getRepo(args.repoId)
+ if (!repo) {
+ throw new Error(`Repo "${args.repoId}" not found`)
+ }
+ const name = normalizeSparsePresetName(args.name)
+ const directories = normalizeSparsePresetDirectories(args.directories)
+ const now = Date.now()
+ const existing = args.id
+ ? store.getSparsePresets(args.repoId).find((preset) => preset.id === args.id)
+ : undefined
+ const preset: SparsePreset = {
+ id: existing?.id ?? randomUUID(),
+ repoId: args.repoId,
+ name,
+ directories,
+ createdAt: existing?.createdAt ?? now,
+ updatedAt: now
+ }
+ const saved = store.saveSparsePreset(preset)
+ notifySparsePresetsChanged(mainWindow, args.repoId)
+ return saved
+ }
+ )
+
+ ipcMain.handle('sparsePresets:remove', (_event, args: { repoId: string; presetId: string }) => {
+ const repo = store.getRepo(args.repoId)
+ if (!repo) {
+ throw new Error(`Repo "${args.repoId}" not found`)
+ }
+ store.removeSparsePreset(args.repoId, args.presetId)
+ notifySparsePresetsChanged(mainWindow, args.repoId)
+ })
+
ipcMain.handle('repos:pickFolder', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openDirectory']
@@ -514,3 +591,39 @@ function notifyReposChanged(mainWindow: BrowserWindow): void {
mainWindow.webContents.send('repos:changed')
}
}
+
+function notifySparsePresetsChanged(mainWindow: BrowserWindow, repoId: string): void {
+ if (!mainWindow.isDestroyed()) {
+ mainWindow.webContents.send('sparsePresets:changed', { repoId })
+ }
+}
+
+function normalizeSparsePresetName(name: string): string {
+ const trimmed = name.trim()
+ if (!trimmed) {
+ throw new Error('Preset name is required.')
+ }
+ if (trimmed.length > 80) {
+ throw new Error('Preset name is too long.')
+ }
+ return trimmed
+}
+
+function normalizeSparsePresetDirectories(directories: string[]): string[] {
+ let normalized: string[]
+ try {
+ normalized = normalizeSparseDirectories(directories)
+ } catch (err) {
+ if (
+ err instanceof Error &&
+ err.message === 'Sparse checkout directories must be repo-relative paths.'
+ ) {
+ throw new Error('Preset directories must be repo-relative paths.')
+ }
+ throw err
+ }
+ if (normalized.length === 0) {
+ throw new Error('Preset must have at least one directory.')
+ }
+ return normalized
+}
diff --git a/src/main/ipc/sidekick.ts b/src/main/ipc/sidekick.ts
new file mode 100644
index 000000000..ee8e97b68
--- /dev/null
+++ b/src/main/ipc/sidekick.ts
@@ -0,0 +1,164 @@
+import { app, BrowserWindow, dialog, ipcMain } from 'electron'
+import { copyFile, mkdir, readFile, rm, stat } from 'node:fs/promises'
+import { randomUUID } from 'node:crypto'
+import { basename, extname, join, normalize, sep } from 'node:path'
+import type { CustomSidekick } from '../../shared/types'
+
+// Why: image-only sidekick uploads. Static + animated variants render natively
+// via , so no 3D engine is needed. Main owns the accepted-format table as
+// the single source of truth for what the renderer will try to display.
+const IMAGE_FORMATS: Record = {
+ '.png': 'image/png',
+ '.apng': 'image/apng',
+ '.jpg': 'image/jpeg',
+ '.jpeg': 'image/jpeg',
+ '.gif': 'image/gif',
+ '.webp': 'image/webp',
+ '.svg': 'image/svg+xml'
+}
+
+function classifyFile(src: string): { mimeType: string; ext: string } | null {
+ const ext = extname(src).toLowerCase()
+ const mime = IMAGE_FORMATS[ext]
+ if (!mime) {
+ return null
+ }
+ return { mimeType: mime, ext }
+}
+
+// Why: custom user-uploaded images live in a dedicated folder under userData
+// so they persist across updates but are scoped to the Orca install. We never
+// trust paths the renderer hands us — the renderer only ever knows the opaque
+// CustomSidekick.id; main resolves it to an absolute path inside this folder.
+function getSidekicksDir(): string {
+ return join(app.getPath('userData'), 'sidekicks', 'custom')
+}
+
+const MAX_BYTES = 64 * 1024 * 1024 // 64 MB — generous but bounded so a user can't point at a multi-GB file and OOM the renderer when it builds a Blob URL.
+
+function isSafeId(id: string): boolean {
+ // UUIDs only; blocks path traversal and unexpected characters.
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)
+}
+
+function resolveSidekickFile(id: string, fileName: string): string | null {
+ if (!isSafeId(id)) {
+ return null
+ }
+ // Why: the renderer hands back the persisted fileName (which includes the
+ // original extension so Blob MIME detection works). We still normalize and
+ // prefix-check against the sidekicks dir to defend against any edge case that
+ // slipped the id regex.
+ const safeName = basename(fileName)
+ if (!safeName.startsWith(`${id}.`)) {
+ return null
+ }
+ const filePath = normalize(join(getSidekicksDir(), safeName))
+ if (!filePath.startsWith(normalize(getSidekicksDir()) + sep)) {
+ return null
+ }
+ return filePath
+}
+
+export function registerSidekickHandlers(): void {
+ ipcMain.handle('sidekick:import', async (event): Promise => {
+ // Why: parent the file picker to the sender window so the dialog opens as
+ // a sheet attached to the main window. Without a parent, on macOS the
+ // dialog can land behind the main window.
+ const senderWindow =
+ BrowserWindow.fromWebContents(event.sender) ?? BrowserWindow.getFocusedWindow()
+ const options: Electron.OpenDialogOptions = {
+ title: 'Pick sidekick',
+ properties: ['openFile'],
+ // Why: single filter and no `apng` extension. macOS file dialogs map
+ // filter extensions to UTIs; `apng` has no registered UTI, so including
+ // it can drop sibling extensions (notably `webp`) from the allowed set.
+ // APNG files carry the `.png` extension and are detected from magic
+ // bytes by the browser.
+ filters: [
+ {
+ name: 'Sidekick image',
+ extensions: ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg']
+ }
+ ]
+ }
+ const result = senderWindow
+ ? await dialog.showOpenDialog(senderWindow, options)
+ : await dialog.showOpenDialog(options)
+ if (result.canceled || result.filePaths.length === 0) {
+ return null
+ }
+ const src = result.filePaths[0]
+ const classified = classifyFile(src)
+ if (!classified) {
+ throw new Error('Unsupported file. Pick a PNG, APNG, JPG, GIF, WebP, or SVG.')
+ }
+ let srcStat: Awaited>
+ try {
+ srcStat = await stat(src)
+ } catch {
+ throw new Error('Could not read the selected file.')
+ }
+ if (!srcStat.isFile()) {
+ throw new Error('Selected path is not a file')
+ }
+ if (srcStat.size > MAX_BYTES) {
+ throw new Error(
+ `File is too large (${(srcStat.size / (1024 * 1024)).toFixed(1)} MB). Max is ${MAX_BYTES / (1024 * 1024)} MB.`
+ )
+ }
+
+ const dir = getSidekicksDir()
+ await mkdir(dir, { recursive: true })
+ const id = randomUUID()
+ // Why: preserve original extension in the on-disk name so sidekick:read can
+ // rebuild the right Blob MIME via resolveSidekickFile without a separate
+ // lookup. The extension is only ever written by main (never the renderer).
+ const fileName = `${id}${classified.ext}`
+ const dest = join(dir, fileName)
+ try {
+ await copyFile(src, dest)
+ } catch {
+ await rm(dest, { force: true }).catch(() => {})
+ throw new Error('Could not save the sidekick.')
+ }
+
+ const rawLabel = basename(src, extname(src)).trim()
+ const label = rawLabel.length > 0 ? rawLabel.slice(0, 40) : 'Custom sidekick'
+ return {
+ id,
+ label,
+ fileName,
+ mimeType: classified.mimeType
+ }
+ })
+
+ ipcMain.handle(
+ 'sidekick:read',
+ async (_event, id: string, fileName: string): Promise => {
+ const filePath = resolveSidekickFile(id, fileName)
+ if (!filePath) {
+ return null
+ }
+ try {
+ const buf = await readFile(filePath)
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
+ } catch (error) {
+ console.warn('[sidekick-overlay] sidekick:read failed', error)
+ return null
+ }
+ }
+ )
+
+ ipcMain.handle('sidekick:delete', async (_event, id: string, fileName: string): Promise => {
+ const filePath = resolveSidekickFile(id, fileName)
+ if (!filePath) {
+ return
+ }
+ try {
+ await rm(filePath, { force: true })
+ } catch (error) {
+ console.warn('[sidekick-overlay] sidekick:delete failed', error)
+ }
+ })
+}
diff --git a/src/main/ipc/sparse-checkout-directories.ts b/src/main/ipc/sparse-checkout-directories.ts
new file mode 100644
index 000000000..74f2873d0
--- /dev/null
+++ b/src/main/ipc/sparse-checkout-directories.ts
@@ -0,0 +1,29 @@
+const WINDOWS_DRIVE_PATH_PATTERN = /^[A-Za-z]:/
+
+function isAbsoluteSparseDirectoryPath(entry: string): boolean {
+ return entry.startsWith('/') || entry.startsWith('\\') || WINDOWS_DRIVE_PATH_PATTERN.test(entry)
+}
+
+export function normalizeSparseDirectories(directories: string[]): string[] {
+ const seen = new Set()
+ return directories
+ .map((entry) => entry.trim())
+ .map((entry) => {
+ // Why: absolute paths can look repo-relative after slash normalization.
+ if (isAbsoluteSparseDirectoryPath(entry)) {
+ throw new Error('Sparse checkout directories must be repo-relative paths.')
+ }
+ return entry.replace(/\\/g, '/').replace(/^\/+|\/+$/g, '')
+ })
+ .filter((entry) => entry.length > 0 && entry !== '.')
+ .filter((entry) => {
+ if (entry.split('/').includes('..')) {
+ throw new Error('Sparse checkout directories must be repo-relative paths.')
+ }
+ if (seen.has(entry)) {
+ return false
+ }
+ seen.add(entry)
+ return true
+ })
+}
diff --git a/src/main/ipc/worktree-logic.ts b/src/main/ipc/worktree-logic.ts
index 70e60f2ef..f4fc0e292 100644
--- a/src/main/ipc/worktree-logic.ts
+++ b/src/main/ipc/worktree-logic.ts
@@ -160,6 +160,7 @@ export function mergeWorktree(
head: git.head,
branch: git.branch,
isBare: git.isBare,
+ ...(git.isSparse === true ? { isSparse: true } : {}),
isMainWorktree: git.isMainWorktree,
displayName: meta?.displayName || branchShort || defaultDisplayName || basename(git.path),
comment: meta?.comment || '',
@@ -171,6 +172,13 @@ export function mergeWorktree(
isPinned: meta?.isPinned ?? false,
sortOrder: meta?.sortOrder ?? 0,
lastActivityAt: meta?.lastActivityAt ?? 0,
+ ...(git.isSparse === true
+ ? {
+ sparseDirectories: meta?.sparseDirectories,
+ sparseBaseRef: meta?.sparseBaseRef,
+ sparsePresetId: meta?.sparsePresetId
+ }
+ : {}),
// Why: diff comments are persisted on WorktreeMeta (see `WorktreeMeta` in
// shared/types) and forwarded verbatim so the renderer store mirrors
// on-disk state. `undefined` here means the worktree has no comments yet.
diff --git a/src/main/ipc/worktree-remote.ts b/src/main/ipc/worktree-remote.ts
index 548dcc7ce..79e97e339 100644
--- a/src/main/ipc/worktree-remote.ts
+++ b/src/main/ipc/worktree-remote.ts
@@ -1,6 +1,11 @@
+/* eslint-disable max-lines */
// Why: extracted from worktrees.ts to keep the main IPC module under the
// max-lines threshold. Worktree creation helpers (local and remote) live
-// here so the IPC dispatch file stays focused on handler wiring.
+// here so the IPC dispatch file stays focused on handler wiring. The
+// recently added sparse-checkout flow plus the worktree-bound setup-script
+// trust gate pushed this file marginally over the per-file limit; matches
+// the eslint-disable pattern other files in src/renderer use when a
+// cohesive flow would split awkwardly.
import type { BrowserWindow } from 'electron'
import { join } from 'path'
@@ -13,11 +18,16 @@ import type {
WorktreeMeta
} from '../../shared/types'
import { getPRForBranch } from '../github/client'
-import { listWorktrees, addWorktree } from '../git/worktree'
+import { listWorktrees, addWorktree, addSparseWorktree } from '../git/worktree'
import { getGitUsername, getDefaultBaseRef, getBranchConflictKind } from '../git/repo'
import { gitExecFileAsync } from '../git/runner'
import { isWslPath, parseWslPath, getWslHome } from '../wsl'
-import { createSetupRunnerScript, getEffectiveHooks, shouldRunSetupForCreate } from '../hooks'
+import {
+ createSetupRunnerScript,
+ getEffectiveHooks,
+ setupScriptsMatch,
+ shouldRunSetupForCreate
+} from '../hooks'
import { getSshGitProvider } from '../providers/ssh-git-dispatch'
import { getActiveMultiplexer } from './ssh'
import type { SshGitProvider } from '../providers/ssh-git-provider'
@@ -31,6 +41,7 @@ import {
areWorktreePathsEqual
} from './worktree-logic'
import { invalidateAuthorizedRootsCache } from './filesystem-auth'
+import { normalizeSparseDirectories } from './sparse-checkout-directories'
export function notifyWorktreesChanged(mainWindow: BrowserWindow, repoId: string): void {
if (!mainWindow.isDestroyed()) {
@@ -44,6 +55,10 @@ export async function createRemoteWorktree(
store: Store,
mainWindow: BrowserWindow
): Promise {
+ if (args.sparseCheckout) {
+ throw new Error('Sparse checkout is not supported for remote SSH repos yet.')
+ }
+
const provider = getSshGitProvider(repo.connectionId!) as SshGitProvider | undefined
if (!provider) {
throw new Error(`No git provider for connection "${repo.connectionId}"`)
@@ -302,11 +317,41 @@ export async function createLocalWorktree(
'Could not resolve a default base ref for this repo. Pick a base branch explicitly and try again.'
)
}
- const setupScript = getEffectiveHooks(repo)?.scripts.setup
+ const primarySetupScript = getEffectiveHooks(repo)?.scripts.setup
// Why: `ask` is a pre-create choice gate, not a post-create side effect.
// Resolve it before mutating git state so missing UI input cannot strand
- // a real worktree on disk while the renderer reports "create failed".
- const shouldLaunchSetup = setupScript ? shouldRunSetupForCreate(repo, args.setupDecision) : false
+ // a real worktree on disk while the renderer reports "create failed". The
+ // actual run/skip decision is recomputed after the worktree exists, gated
+ // on the worktree's own setup script matching the primary's preview.
+ if (primarySetupScript) {
+ shouldRunSetupForCreate(repo, args.setupDecision)
+ }
+ const sparseDirectories = args.sparseCheckout
+ ? normalizeSparseDirectories(args.sparseCheckout.directories)
+ : []
+ if (args.sparseCheckout && sparseDirectories.length === 0) {
+ throw new Error('Sparse checkout requires at least one repo-relative directory.')
+ }
+ let sparsePresetId: string | undefined
+ if (args.sparseCheckout?.presetId) {
+ const preset = store
+ .getSparsePresets(repo.id)
+ .find((entry) => entry.id === args.sparseCheckout?.presetId)
+ if (preset?.repoId === repo.id) {
+ try {
+ const presetDirectories = normalizeSparseDirectories(preset.directories)
+ // Why: use Set-based comparison so directory order does not affect
+ // attribution — matches the renderer's sparseDirectoriesMatch logic.
+ const presetSet = new Set(presetDirectories)
+ const directoriesMatch =
+ presetDirectories.length === sparseDirectories.length &&
+ sparseDirectories.every((entry) => presetSet.has(entry))
+ sparsePresetId = directoriesMatch ? preset.id : undefined
+ } catch {
+ // Why: corrupt preset data should not block creation or falsely label the new worktree.
+ }
+ }
+ }
// Why: `git fetch` previously blocked worktree creation for 1–5s on every
// click, even though the fetch result isn't actually required — the
@@ -319,13 +364,22 @@ export async function createLocalWorktree(
// Fetch is best-effort — don't block worktree creation if offline
})
- await addWorktree(
- repo.path,
- worktreePath,
- branchName,
- baseBranch,
- settings.refreshLocalBaseRefOnWorktreeCreate
- )
+ await (sparseDirectories.length > 0
+ ? addSparseWorktree(
+ repo.path,
+ worktreePath,
+ branchName,
+ sparseDirectories,
+ baseBranch,
+ settings.refreshLocalBaseRefOnWorktreeCreate
+ )
+ : addWorktree(
+ repo.path,
+ worktreePath,
+ branchName,
+ baseBranch,
+ settings.refreshLocalBaseRefOnWorktreeCreate
+ ))
// Re-list to get the freshly created worktree info
const gitWorktrees = await listWorktrees(repo.path)
@@ -342,6 +396,13 @@ export async function createLocalWorktree(
lastActivityAt: Date.now(),
...(shouldSetDisplayName(effectiveRequestedName, branchName, effectiveSanitizedName)
? { displayName: effectiveRequestedName }
+ : {}),
+ ...(sparseDirectories.length > 0
+ ? {
+ sparseDirectories,
+ sparseBaseRef: baseBranch,
+ sparsePresetId
+ }
: {})
}
const meta = store.setWorktreeMeta(worktreeId, metaUpdates)
@@ -354,6 +415,24 @@ export async function createLocalWorktree(
invalidateAuthorizedRootsCache()
let setup: CreateWorktreeResult['setup']
+ const setupScript = getEffectiveHooks(repo, worktreePath)?.scripts.setup
+ const setupMatchesPreview = setupScriptsMatch(repo, worktreePath, primarySetupScript)
+ let shouldLaunchSetup = false
+ if (setupScript && !setupMatchesPreview) {
+ console.warn(
+ `[hooks] setup hook skipped for ${worktreePath}: worktree setup script differs from the primary checkout setup script shown to the user`
+ )
+ } else if (setupScript) {
+ try {
+ shouldLaunchSetup = shouldRunSetupForCreate(repo, args.setupDecision)
+ } catch (error) {
+ // Why: if the target branch introduces setup hooks that the primary
+ // checkout did not expose, the renderer may not have collected an ask
+ // decision. The worktree already exists, so skip setup instead of
+ // turning successful git creation into an IPC failure.
+ console.warn(`[hooks] setup hook skipped for ${worktreePath}:`, error)
+ }
+ }
if (setupScript && shouldLaunchSetup) {
try {
// Why: setup now runs in a visible terminal owned by the renderer so users
diff --git a/src/main/ipc/worktrees-windows.test.ts b/src/main/ipc/worktrees-windows.test.ts
index 3c8f6a791..9d35ecb57 100644
--- a/src/main/ipc/worktrees-windows.test.ts
+++ b/src/main/ipc/worktrees-windows.test.ts
@@ -17,6 +17,7 @@ const {
runHookMock,
hasHooksFileMock,
loadHooksMock,
+ setupScriptsMatchMock,
computeWorktreePathMock,
ensurePathWithinWorkspaceMock
} = vi.hoisted(() => ({
@@ -33,6 +34,7 @@ const {
createIssueCommandRunnerScriptMock: vi.fn(),
createSetupRunnerScriptMock: vi.fn(),
shouldRunSetupForCreateMock: vi.fn(),
+ setupScriptsMatchMock: vi.fn(() => true),
runHookMock: vi.fn(),
hasHooksFileMock: vi.fn(),
loadHooksMock: vi.fn(),
@@ -78,7 +80,8 @@ vi.mock('../hooks', () => ({
loadHooks: loadHooksMock,
runHook: runHookMock,
hasHooksFile: hasHooksFileMock,
- shouldRunSetupForCreate: shouldRunSetupForCreateMock
+ shouldRunSetupForCreate: shouldRunSetupForCreateMock,
+ setupScriptsMatch: setupScriptsMatchMock
}))
vi.mock('./worktree-logic', async (importOriginal) => {
diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts
index 0bbba1a6a..53057e826 100644
--- a/src/main/ipc/worktrees.test.ts
+++ b/src/main/ipc/worktrees.test.ts
@@ -6,6 +6,7 @@ const {
removeHandlerMock,
listWorktreesMock,
addWorktreeMock,
+ addSparseWorktreeMock,
removeWorktreeMock,
getGitUsernameMock,
getDefaultBaseRefMock,
@@ -18,6 +19,7 @@ const {
runHookMock,
hasHooksFileMock,
loadHooksMock,
+ setupScriptsMatchMock,
computeWorktreePathMock,
ensurePathWithinWorkspaceMock,
gitExecFileAsyncMock
@@ -26,6 +28,7 @@ const {
removeHandlerMock: vi.fn(),
listWorktreesMock: vi.fn(),
addWorktreeMock: vi.fn(),
+ addSparseWorktreeMock: vi.fn(),
removeWorktreeMock: vi.fn(),
getGitUsernameMock: vi.fn(),
getDefaultBaseRefMock: vi.fn(),
@@ -35,6 +38,7 @@ const {
createIssueCommandRunnerScriptMock: vi.fn(),
createSetupRunnerScriptMock: vi.fn(),
shouldRunSetupForCreateMock: vi.fn(),
+ setupScriptsMatchMock: vi.fn(() => true),
runHookMock: vi.fn(),
hasHooksFileMock: vi.fn(),
loadHooksMock: vi.fn(),
@@ -53,6 +57,7 @@ vi.mock('electron', () => ({
vi.mock('../git/worktree', () => ({
listWorktrees: listWorktreesMock,
addWorktree: addWorktreeMock,
+ addSparseWorktree: addSparseWorktreeMock,
removeWorktree: removeWorktreeMock
}))
@@ -78,7 +83,8 @@ vi.mock('../hooks', () => ({
loadHooks: loadHooksMock,
runHook: runHookMock,
hasHooksFile: hasHooksFileMock,
- shouldRunSetupForCreate: shouldRunSetupForCreateMock
+ shouldRunSetupForCreate: shouldRunSetupForCreateMock,
+ setupScriptsMatch: setupScriptsMatchMock
}))
vi.mock('./worktree-logic', async (importOriginal) => {
@@ -113,6 +119,7 @@ describe('registerWorktreeHandlers', () => {
const store = {
getRepos: vi.fn(),
getRepo: vi.fn(),
+ getSparsePresets: vi.fn(),
getSettings: vi.fn(),
getWorktreeMeta: vi.fn(),
setWorktreeMeta: vi.fn(),
@@ -125,6 +132,7 @@ describe('registerWorktreeHandlers', () => {
removeHandlerMock,
listWorktreesMock,
addWorktreeMock,
+ addSparseWorktreeMock,
removeWorktreeMock,
getGitUsernameMock,
getDefaultBaseRefMock,
@@ -143,6 +151,7 @@ describe('registerWorktreeHandlers', () => {
mainWindow.webContents.send,
store.getRepos,
store.getRepo,
+ store.getSparsePresets,
store.getSettings,
store.getWorktreeMeta,
store.setWorktreeMeta,
@@ -168,6 +177,7 @@ describe('registerWorktreeHandlers', () => {
}
store.getRepos.mockReturnValue([repo])
store.getRepo.mockReturnValue({ ...repo, worktreeBaseRef: null })
+ store.getSparsePresets.mockReturnValue([])
store.getSettings.mockReturnValue({
branchPrefix: 'none',
nestWorkspaces: false,
@@ -471,6 +481,173 @@ describe('registerWorktreeHandlers', () => {
)
})
+ it('creates a sparse worktree and persists its sparse metadata', async () => {
+ listWorktreesMock.mockResolvedValue([
+ {
+ ...createdWorktreeList[0],
+ isSparse: true
+ }
+ ])
+ store.setWorktreeMeta.mockReturnValue({
+ sparseDirectories: ['packages/web', 'apps/api'],
+ sparseBaseRef: 'origin/main',
+ sparsePresetId: 'preset-1'
+ })
+ store.getSparsePresets.mockReturnValue([
+ {
+ id: 'preset-1',
+ repoId: 'repo-1',
+ name: 'Frontend and API',
+ directories: ['packages/web', 'apps/api'],
+ createdAt: 1,
+ updatedAt: 1
+ }
+ ])
+
+ const result = await handlers['worktrees:create'](null, {
+ repoId: 'repo-1',
+ name: 'improve-dashboard',
+ sparseCheckout: {
+ directories: [' packages/web ', 'apps\\api\\', 'packages/web/'],
+ presetId: 'preset-1'
+ }
+ })
+
+ expect(addWorktreeMock).not.toHaveBeenCalled()
+ expect(addSparseWorktreeMock).toHaveBeenCalledWith(
+ '/workspace/repo',
+ '/workspace/improve-dashboard',
+ 'improve-dashboard',
+ ['packages/web', 'apps/api'],
+ 'origin/main',
+ false
+ )
+ expect(store.setWorktreeMeta).toHaveBeenCalledWith(
+ 'repo-1::/workspace/improve-dashboard',
+ expect.objectContaining({
+ sparseDirectories: ['packages/web', 'apps/api'],
+ sparseBaseRef: 'origin/main',
+ sparsePresetId: 'preset-1'
+ })
+ )
+ expect(result).toEqual({
+ worktree: expect.objectContaining({
+ repoId: 'repo-1',
+ path: '/workspace/improve-dashboard',
+ sparseDirectories: ['packages/web', 'apps/api'],
+ sparseBaseRef: 'origin/main',
+ sparsePresetId: 'preset-1'
+ })
+ })
+ })
+
+ it('clears sparse preset attribution when the preset id does not belong to the repo', async () => {
+ listWorktreesMock.mockResolvedValue([
+ {
+ ...createdWorktreeList[0],
+ isSparse: true
+ }
+ ])
+ store.getSparsePresets.mockReturnValue([
+ {
+ id: 'preset-2',
+ repoId: 'repo-1',
+ name: 'Other preset',
+ directories: ['packages/web'],
+ createdAt: 1,
+ updatedAt: 1
+ }
+ ])
+
+ await handlers['worktrees:create'](null, {
+ repoId: 'repo-1',
+ name: 'improve-dashboard',
+ sparseCheckout: {
+ directories: ['packages/web'],
+ presetId: 'preset-1'
+ }
+ })
+
+ expect(store.setWorktreeMeta).toHaveBeenCalledWith(
+ 'repo-1::/workspace/improve-dashboard',
+ expect.objectContaining({
+ sparseDirectories: ['packages/web'],
+ sparseBaseRef: 'origin/main',
+ sparsePresetId: undefined
+ })
+ )
+ })
+
+ it('clears sparse preset attribution when normalized directories do not match', async () => {
+ listWorktreesMock.mockResolvedValue([
+ {
+ ...createdWorktreeList[0],
+ isSparse: true
+ }
+ ])
+ store.getSparsePresets.mockReturnValue([
+ {
+ id: 'preset-1',
+ repoId: 'repo-1',
+ name: 'Frontend and API',
+ directories: ['packages/web', 'apps/api'],
+ createdAt: 1,
+ updatedAt: 1
+ }
+ ])
+
+ await handlers['worktrees:create'](null, {
+ repoId: 'repo-1',
+ name: 'improve-dashboard',
+ sparseCheckout: {
+ directories: ['packages/web'],
+ presetId: 'preset-1'
+ }
+ })
+
+ expect(store.setWorktreeMeta).toHaveBeenCalledWith(
+ 'repo-1::/workspace/improve-dashboard',
+ expect.objectContaining({
+ sparseDirectories: ['packages/web'],
+ sparseBaseRef: 'origin/main',
+ sparsePresetId: undefined
+ })
+ )
+ })
+
+ it('rejects sparse checkout directories that traverse above the repo root', async () => {
+ await expect(
+ handlers['worktrees:create'](null, {
+ repoId: 'repo-1',
+ name: 'improve-dashboard',
+ sparseCheckout: {
+ directories: ['packages/web', '../secrets']
+ }
+ })
+ ).rejects.toThrow('Sparse checkout directories must be repo-relative paths.')
+
+ expect(addSparseWorktreeMock).not.toHaveBeenCalled()
+ expect(addWorktreeMock).not.toHaveBeenCalled()
+ })
+
+ it.each(['/Users/me/repo/packages/web', 'C:\\repo\\packages\\web', '\\\\server\\share\\repo'])(
+ 'rejects absolute sparse checkout directory before normalization: %s',
+ async (directory) => {
+ await expect(
+ handlers['worktrees:create'](null, {
+ repoId: 'repo-1',
+ name: 'improve-dashboard',
+ sparseCheckout: {
+ directories: ['packages/web', directory]
+ }
+ })
+ ).rejects.toThrow('Sparse checkout directories must be repo-relative paths.')
+
+ expect(addSparseWorktreeMock).not.toHaveBeenCalled()
+ expect(addWorktreeMock).not.toHaveBeenCalled()
+ }
+ )
+
it('still returns the created worktree when setup runner generation fails', async () => {
listWorktreesMock.mockResolvedValue(createdWorktreeList)
getEffectiveHooksMock.mockReturnValue({
diff --git a/src/main/persistence.test.ts b/src/main/persistence.test.ts
index 2f8081757..53560349c 100644
--- a/src/main/persistence.test.ts
+++ b/src/main/persistence.test.ts
@@ -249,6 +249,34 @@ describe('Store', () => {
expect(store.updateRepo('nope', { displayName: 'x' })).toBeNull()
})
+ it('updateRepo persists issueSourcePreference across reloads', async () => {
+ const store = await createStore()
+ store.addRepo(makeRepo())
+
+ const updated = store.updateRepo('r1', { issueSourcePreference: 'upstream' })
+ expect(updated!.issueSourcePreference).toBe('upstream')
+
+ store.flush()
+ const reloaded = await createStore()
+ expect(reloaded.getRepo('r1')!.issueSourcePreference).toBe('upstream')
+ })
+
+ it('updateRepo with issueSourcePreference=undefined clears the preference', async () => {
+ const store = await createStore()
+ store.addRepo(makeRepo({ issueSourcePreference: 'origin' }))
+ expect(store.getRepo('r1')!.issueSourcePreference).toBe('origin')
+
+ // Why: passing the key with value `undefined` must clear the preference.
+ // Plain `Object.assign` skips undefined values, so without the explicit
+ // delete branch in updateRepo, the persisted record would keep 'origin'.
+ store.updateRepo('r1', { issueSourcePreference: undefined })
+ expect(store.getRepo('r1')!.issueSourcePreference).toBeUndefined()
+
+ store.flush()
+ const reloaded = await createStore()
+ expect(reloaded.getRepo('r1')!.issueSourcePreference).toBeUndefined()
+ })
+
// ── 8. setWorktreeMeta and getWorktreeMeta ─────────────────────────
it('setWorktreeMeta creates meta with defaults for missing fields', async () => {
@@ -551,6 +579,98 @@ describe('Store', () => {
expect(store.getSettings().terminalMacOptionAsAltMigrated).toBe(true)
})
+ // ── inline-agents card-property migration ──────────────────────────
+ //
+ // Why: 'inline-agents' was added to DEFAULT_WORKTREE_CARD_PROPERTIES after
+ // the experimentalAgentDashboard toggle. Users who had the toggle on in a
+ // prior rc already had worktreeCardProperties persisted without the new
+ // entry, so the defaults-merge in load() wouldn't reach them and the
+ // inline agent list stayed hidden after upgrade. The migration appends
+ // 'inline-agents' once and sets a flag so a later deliberate uncheck
+ // from the Workspaces view options menu sticks across restarts.
+
+ it('adds inline-agents to persisted cardProps when experimental toggle is on', async () => {
+ writeDataFile({
+ schemaVersion: 1,
+ repos: [],
+ worktreeMeta: {},
+ settings: { experimentalAgentDashboard: true },
+ ui: {
+ worktreeCardProperties: ['status', 'unread', 'ci', 'issue', 'pr', 'comment']
+ },
+ githubCache: { pr: {}, issue: {} },
+ workspaceSession: {}
+ })
+ const store = await createStore()
+ expect(store.getUI().worktreeCardProperties).toContain('inline-agents')
+ expect(store.getUI()._inlineAgentsDefaultedForExperiment).toBe(true)
+ })
+
+ it('does not add inline-agents when experimental toggle is off', async () => {
+ // Why: the experimental toggle gates whether inline agents render at all,
+ // so there's no value in checking the view-mode option for opted-out users.
+ writeDataFile({
+ schemaVersion: 1,
+ repos: [],
+ worktreeMeta: {},
+ settings: { experimentalAgentDashboard: false },
+ ui: {
+ worktreeCardProperties: ['status', 'unread', 'ci', 'issue', 'pr', 'comment']
+ },
+ githubCache: { pr: {}, issue: {} },
+ workspaceSession: {}
+ })
+ const store = await createStore()
+ expect(store.getUI().worktreeCardProperties).not.toContain('inline-agents')
+ expect(store.getUI()._inlineAgentsDefaultedForExperiment).toBe(true)
+ })
+
+ it('respects a deliberate uncheck after migration flag is set', async () => {
+ // Why: once migrated, an empty-of-inline-agents array is treated as a
+ // user choice — not a legacy pre-migration state — so we must not
+ // re-add it on every subsequent launch.
+ writeDataFile({
+ schemaVersion: 1,
+ repos: [],
+ worktreeMeta: {},
+ settings: { experimentalAgentDashboard: true },
+ ui: {
+ worktreeCardProperties: ['status', 'unread', 'ci', 'issue', 'pr', 'comment'],
+ _inlineAgentsDefaultedForExperiment: true
+ },
+ githubCache: { pr: {}, issue: {} },
+ workspaceSession: {}
+ })
+ const store = await createStore()
+ expect(store.getUI().worktreeCardProperties).not.toContain('inline-agents')
+ })
+
+ it('leaves cardProps alone when inline-agents is already present', async () => {
+ writeDataFile({
+ schemaVersion: 1,
+ repos: [],
+ worktreeMeta: {},
+ settings: { experimentalAgentDashboard: true },
+ ui: {
+ worktreeCardProperties: [
+ 'status',
+ 'unread',
+ 'ci',
+ 'issue',
+ 'pr',
+ 'comment',
+ 'inline-agents'
+ ]
+ },
+ githubCache: { pr: {}, issue: {} },
+ workspaceSession: {}
+ })
+ const store = await createStore()
+ const props = store.getUI().worktreeCardProperties
+ expect(props.filter((p) => p === 'inline-agents')).toHaveLength(1)
+ expect(store.getUI()._inlineAgentsDefaultedForExperiment).toBe(true)
+ })
+
// ── GitHub Cache ───────────────────────────────────────────────────
it('get/set GitHub cache round-trips', async () => {
diff --git a/src/main/persistence.ts b/src/main/persistence.ts
index 7c4601775..2815254ec 100644
--- a/src/main/persistence.ts
+++ b/src/main/persistence.ts
@@ -6,7 +6,13 @@ import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync, unlinkS
import { writeFile, rename, mkdir, rm } from 'fs/promises'
import { join, dirname } from 'path'
import { homedir } from 'os'
-import type { PersistedState, Repo, WorktreeMeta, GlobalSettings } from '../shared/types'
+import type {
+ PersistedState,
+ Repo,
+ SparsePreset,
+ WorktreeMeta,
+ GlobalSettings
+} from '../shared/types'
import type { SshTarget } from '../shared/ssh-types'
import { isFolderRepo } from '../shared/repo-kind'
import { getGitUsername } from './git/repo'
@@ -157,11 +163,40 @@ export class Store {
const rawSort = parsed.ui?.sortBy
const sort = normalizeSortBy(rawSort)
const migrate = !parsed.ui?._sortBySmartMigrated && rawSort === 'recent'
+ // Why: the 'inline-agents' card property was added after the
+ // experimentalAgentDashboard toggle. Users who had the toggle on
+ // in a prior rc already had worktreeCardProperties persisted
+ // without the new entry, so a simple defaults merge wouldn't
+ // reach them and the inline agent list stayed hidden after
+ // upgrade. One-shot append 'inline-agents' to their persisted
+ // array when the experimental toggle is true; the flag prevents
+ // re-firing so a deliberate uncheck from the Workspaces view
+ // options menu sticks across restarts.
+ // The flag is stamped on every successful load — including when
+ // the experiment is off — so that a later flip-on is handled by
+ // the renderer's ExperimentalPane handler rather than re-firing
+ // this migration.
+ const rawCardProps = parsed.ui?.worktreeCardProperties
+ const inlineAgentsMigrated = parsed.ui?._inlineAgentsDefaultedForExperiment === true
+ const experimentOn = parsed.settings?.experimentalAgentDashboard === true
+ const needsInlineAgentsMigration =
+ !inlineAgentsMigrated &&
+ experimentOn &&
+ Array.isArray(rawCardProps) &&
+ !rawCardProps.includes('inline-agents')
+ const migratedCardProps =
+ needsInlineAgentsMigration && Array.isArray(rawCardProps)
+ ? [...rawCardProps, 'inline-agents' as const]
+ : undefined
return {
...defaults.ui,
...parsed.ui,
sortBy: migrate ? ('smart' as const) : sort,
- _sortBySmartMigrated: true
+ _sortBySmartMigrated: true,
+ ...(migratedCardProps !== undefined
+ ? { worktreeCardProperties: migratedCardProps }
+ : {}),
+ _inlineAgentsDefaultedForExperiment: true
}
})(),
// Why: the workspace session is the most volatile persisted surface
@@ -314,6 +349,9 @@ export class Store {
removeRepo(id: string): void {
this.state.repos = this.state.repos.filter((r) => r.id !== id)
+ // Why: presets are repo-scoped, so removing the repo means the presets
+ // can never be referenced again — drop them with the parent.
+ delete this.state.sparsePresetsByRepo[id]
// Clean up worktree meta for this repo
const prefix = `${id}::`
for (const key of Object.keys(this.state.worktreeMeta)) {
@@ -327,14 +365,33 @@ export class Store {
updateRepo(
id: string,
updates: Partial<
- Pick
+ Pick<
+ Repo,
+ | 'displayName'
+ | 'badgeColor'
+ | 'hookSettings'
+ | 'worktreeBaseRef'
+ | 'kind'
+ | 'issueSourcePreference'
+ >
>
): Repo | null {
const repo = this.state.repos.find((r) => r.id === id)
if (!repo) {
return null
}
- Object.assign(repo, updates)
+ // Why: `issueSourcePreference === undefined` in the patch means "reset to
+ // auto" (and the persisted record should drop the key, not preserve a
+ // stale explicit value via Object.assign's skip-on-undefined behavior).
+ // Without this delete branch, toggling explicit → auto would silently
+ // leave the old preference in place on disk.
+ if ('issueSourcePreference' in updates && updates.issueSourcePreference === undefined) {
+ delete repo.issueSourcePreference
+ const { issueSourcePreference: _drop, ...rest } = updates
+ Object.assign(repo, rest)
+ } else {
+ Object.assign(repo, updates)
+ }
this.scheduleSave()
return this.hydrateRepo(repo)
}
@@ -364,6 +421,31 @@ export class Store {
}
}
+ // ── Sparse Presets ─────────────────────────────────────────────────
+
+ getSparsePresets(repoId: string): SparsePreset[] {
+ return [...(this.state.sparsePresetsByRepo[repoId] ?? [])].sort((left, right) =>
+ left.name.localeCompare(right.name)
+ )
+ }
+
+ saveSparsePreset(preset: SparsePreset): SparsePreset {
+ const existing = this.state.sparsePresetsByRepo[preset.repoId] ?? []
+ const index = existing.findIndex((entry) => entry.id === preset.id)
+ this.state.sparsePresetsByRepo[preset.repoId] =
+ index === -1
+ ? [...existing, preset]
+ : existing.map((entry, i) => (i === index ? preset : entry))
+ this.scheduleSave()
+ return preset
+ }
+
+ removeSparsePreset(repoId: string, presetId: string): void {
+ const existing = this.state.sparsePresetsByRepo[repoId] ?? []
+ this.state.sparsePresetsByRepo[repoId] = existing.filter((entry) => entry.id !== presetId)
+ this.scheduleSave()
+ }
+
// ── Worktree Meta ──────────────────────────────────────────────────
getWorktreeMeta(worktreeId: string): WorktreeMeta | undefined {
diff --git a/src/main/providers/local-pty-provider.test.ts b/src/main/providers/local-pty-provider.test.ts
index 78274a4fa..25cdabc46 100644
--- a/src/main/providers/local-pty-provider.test.ts
+++ b/src/main/providers/local-pty-provider.test.ts
@@ -1,3 +1,4 @@
+/* oxlint-disable max-lines */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const {
@@ -204,9 +205,14 @@ describe('LocalPtyProvider', () => {
describe('shutdown', () => {
it('kills the PTY process', async () => {
+ // Why: capture the spy reference before shutdown triggers onExit →
+ // POSIX kill neutralization. After neutralization, mockProc.kill is
+ // replaced with a non-spy no-op to close the UnixTerminal.destroy() →
+ // socket-close → SIGHUP-to-recycled-pid race (see docs/fix-pty-fd-leak.md).
+ const killSpy = mockProc.kill
const { id } = await provider.spawn({ cols: 80, rows: 24 })
await provider.shutdown(id, true)
- expect(mockProc.kill).toHaveBeenCalled()
+ expect(killSpy).toHaveBeenCalled()
})
it('invokes onExit callback via the node-pty exit handler', async () => {
@@ -319,12 +325,40 @@ describe('LocalPtyProvider', () => {
describe('killAll', () => {
it('kills all PTY processes', async () => {
+ // Why: each spawn needs its own proc so the onExit-triggered POSIX kill
+ // neutralization on one proc does not replace the kill function on the
+ // other (mockProc is shared by default in beforeEach). Each proc also
+ // needs its own exitCb holder — the default mockProc.onExit assigns to
+ // the shared `exitCb` variable, so the second spawn would overwrite the
+ // first's exit callback, and mock1Kill firing would trigger cleanup for
+ // id2 (removing it from the map before killAll iterates to it).
+ let exit1: ((e: { exitCode: number }) => void) | undefined
+ let exit2: ((e: { exitCode: number }) => void) | undefined
+ const mock1Kill = vi.fn(() => exit1?.({ exitCode: -1 }))
+ const mock2Kill = vi.fn(() => exit2?.({ exitCode: -1 }))
+ spawnMock
+ .mockReturnValueOnce({
+ ...mockProc,
+ kill: mock1Kill,
+ onExit: vi.fn((cb) => {
+ exit1 = cb
+ })
+ })
+ .mockReturnValueOnce({
+ ...mockProc,
+ kill: mock2Kill,
+ onExit: vi.fn((cb) => {
+ exit2 = cb
+ })
+ })
+
await provider.spawn({ cols: 80, rows: 24 })
await provider.spawn({ cols: 80, rows: 24 })
provider.killAll()
- expect(mockProc.kill).toHaveBeenCalled()
+ expect(mock1Kill).toHaveBeenCalled()
+ expect(mock2Kill).toHaveBeenCalled()
const list = await provider.listProcesses()
expect(list).toHaveLength(0)
})
diff --git a/src/main/providers/local-pty-provider.ts b/src/main/providers/local-pty-provider.ts
index 790ef67f8..e156f429c 100644
--- a/src/main/providers/local-pty-provider.ts
+++ b/src/main/providers/local-pty-provider.ts
@@ -3,7 +3,9 @@
tightly coupled PTY lifecycle logic (scan → ready → write → exit cleanup) across
files without a cleaner ownership seam. */
import { basename } from 'path'
+import { win32 as pathWin32 } from 'path'
import { resolveWindowsShellLaunchArgs } from './windows-shell-args'
+import { resolveEffectiveWindowsPowerShell } from './windows-powershell'
import { resolveProcessCwd } from './process-cwd'
import { existsSync } from 'fs'
import * as pty from 'node-pty'
@@ -80,6 +82,27 @@ function clearPtyState(id: string): void {
ptyLoadGeneration.delete(id)
}
+function destroyPtyProcess(proc: pty.IPty): void {
+ // Why: node-pty's UnixTerminal.destroy() closes the master socket, which
+ // releases the ptmx fd to the OS — without this call the fd leaks until GC
+ // (see docs/fix-pty-fd-leak.md). destroy() also registers a close listener
+ // that fires `this.kill('SIGHUP')` AFTER the socket closes. On POSIX, by
+ // the time that listener runs the child may have exited and its pid been
+ // recycled to an unrelated user process — SIGHUP would land on a Chrome tab,
+ // editor, etc. Neutralize proc.kill on this instance before calling
+ // destroy() to defuse the hazard. Windows exempt: WindowsTerminal.destroy
+ // IS a kill() call via _deferNoArgs, so neutralizing it would leak the
+ // ConPTY agent.
+ if (process.platform !== 'win32') {
+ ;(proc as unknown as { kill: (sig?: string) => void }).kill = () => {}
+ }
+ try {
+ ;(proc as unknown as { destroy?: () => void }).destroy?.()
+ } catch {
+ /* swallow — already torn down */
+ }
+}
+
function safeKillAndClean(id: string, proc: pty.IPty): void {
disposePtyListeners(id)
try {
@@ -87,6 +110,7 @@ function safeKillAndClean(id: string, proc: pty.IPty): void {
} catch {
/* Process may already be dead */
}
+ destroyPtyProcess(proc)
clearPtyState(id)
}
@@ -100,6 +124,8 @@ export type LocalPtyProviderOptions = {
* IPC layer inject the persisted setting without coupling the provider to the
* settings store. Returns undefined when no preference is set. */
getWindowsShell?: () => string | undefined
+ getWindowsPowerShellImplementation?: () => 'auto' | 'powershell.exe' | 'pwsh.exe' | undefined
+ pwshAvailable?: () => boolean
onSpawned?: (id: string) => void
onExit?: (id: string, code: number) => void
onData?: (id: string, data: string, timestamp: number) => void
@@ -139,11 +165,35 @@ export class LocalPtyProvider implements IPtyProvider {
// Why: shellOverride lets a single tab open in a different shell than the
// persisted default (e.g. "New WSL terminal" from the "+" submenu) without
// changing the user's setting. It takes priority over the setting.
- shellPath =
+ const shellFamily =
args.shellOverride ||
this.opts.getWindowsShell?.() ||
process.env.COMSPEC ||
'powershell.exe'
+ const normalizedShellFamily = pathWin32.basename(shellFamily).toLowerCase()
+ // Why: shell selection can arrive either as a canonical setting value
+ // ('powershell.exe') or as a concrete PowerShell executable path from a
+ // one-off override. Normalize both forms back to the PowerShell family so
+ // the shared resolver can still fall back to inbox powershell.exe when
+ // pwsh.exe was requested but is unavailable.
+ const powerShellImplementation = this.opts.getWindowsPowerShellImplementation?.()
+ const shouldResolvePowerShellFamily =
+ powerShellImplementation !== undefined || pathWin32.basename(shellFamily) === shellFamily
+ shellPath = shouldResolvePowerShellFamily
+ ? (resolveEffectiveWindowsPowerShell({
+ shellFamily:
+ normalizedShellFamily === 'powershell.exe' || normalizedShellFamily === 'pwsh.exe'
+ ? 'powershell.exe'
+ : normalizedShellFamily === 'cmd.exe' || normalizedShellFamily === 'wsl.exe'
+ ? normalizedShellFamily
+ : undefined,
+ implementation: powerShellImplementation,
+ pwshAvailable: this.opts.pwshAvailable?.() ?? false
+ }) ?? shellFamily)
+ : shellFamily
+ // Why: one-off overrides and persisted shell-family selection keep the
+ // same priority, while the shared resolver chooses which PowerShell
+ // executable is safe to run right now if that family is selected.
// Why: both this path and the daemon-subprocess path must derive the
// same shellArgs for the same (shell, cwd) pair. The helper keeps CJK
// UTF-8 setup (chcp 65001), PowerShell $PROFILE dot-sourcing, and the
@@ -310,12 +360,28 @@ export class LocalPtyProvider implements IPtyProvider {
}
const onExitDisposable = proc.onExit(({ exitCode }) => {
+ // Why: neutralize proc.kill the instant the child is reaped, before any
+ // other work in this callback. node-pty's UnixTerminal installs a
+ // `_socket.once('close', () => this.kill('SIGHUP'))` handler at destroy
+ // time, but the master socket can also emit 'close' on natural exit
+ // between this onExit callback starting and destroyPtyProcess() running
+ // below. If 'close' wins, SIGHUP is dispatched to proc.pid — which on
+ // POSIX has already been reaped and may have been recycled to an
+ // unrelated process. Synchronous neutralization here closes that window.
+ // Windows is exempt: WindowsTerminal.destroy is implemented via kill().
+ if (process.platform !== 'win32') {
+ ;(proc as unknown as { kill: (sig?: string) => void }).kill = () => {}
+ }
if (shellReadyTimeout) {
clearTimeout(shellReadyTimeout)
shellReadyTimeout = null
}
startupCommandCleanup?.()
clearPtyState(id)
+ // Why: release the master ptmx fd on the natural-exit path — without
+ // this, a shell that exits cleanly (the common case) never releases its
+ // fd until the next GC. See docs/fix-pty-fd-leak.md.
+ destroyPtyProcess(proc)
this.opts.onExit?.(id, exitCode)
for (const cb of exitListeners) {
cb({ id, code: exitCode })
@@ -365,6 +431,7 @@ export class LocalPtyProvider implements IPtyProvider {
} catch {
/* Process may already be dead */
}
+ destroyPtyProcess(proc)
ptyProcesses.delete(id)
ptyShellName.delete(id)
ptyLoadGeneration.delete(id)
diff --git a/src/main/providers/process-cwd.ts b/src/main/providers/process-cwd.ts
index 3ff4a2528..326a61b42 100644
--- a/src/main/providers/process-cwd.ts
+++ b/src/main/providers/process-cwd.ts
@@ -70,7 +70,11 @@ async function doResolve(pid: number): Promise {
}
try {
- const { stdout } = await execFile('lsof', ['-p', String(pid), '-d', 'cwd', '-Fn'], {
+ // Why: `-a` ANDs the -p and -d filters. Without it, macOS lsof ORs them
+ // and emits cwd records for every process on the system, so the n-line
+ // scan below picks up the first unrelated process (often pid ~391 with
+ // cwd `/`) and returns `/` regardless of the target pid's real cwd.
+ const { stdout } = await execFile('lsof', ['-a', '-p', String(pid), '-d', 'cwd', '-Fn'], {
encoding: 'utf-8',
timeout: LSOF_TIMEOUT_MS
})
diff --git a/src/main/providers/types.ts b/src/main/providers/types.ts
index 3125ba797..db7fc4d3c 100644
--- a/src/main/providers/types.ts
+++ b/src/main/providers/types.ts
@@ -30,6 +30,12 @@ export type PtySpawnOptions = {
* changing the user's persistent default shell setting. Only consulted on
* Windows; ignored on macOS/Linux where shell selection is not exposed. */
shellOverride?: string
+ /** Why: PowerShell is the top-level shell family in product terms, but on
+ * Windows we may need to choose between inbox Windows PowerShell 5.1 and
+ * pwsh.exe at spawn time. Threading the persisted implementation choice
+ * through spawn options keeps local PTY and daemon PTY semantics aligned
+ * without promoting pwsh into a separate shell family. */
+ terminalWindowsPowerShellImplementation?: 'auto' | 'powershell.exe' | 'pwsh.exe'
}
export type PtySpawnResult = {
diff --git a/src/main/providers/windows-powershell.test.ts b/src/main/providers/windows-powershell.test.ts
new file mode 100644
index 000000000..6a9a69468
--- /dev/null
+++ b/src/main/providers/windows-powershell.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, it } from 'vitest'
+import { resolveEffectiveWindowsPowerShell } from './windows-powershell'
+
+describe('resolveEffectiveWindowsPowerShell', () => {
+ it('returns null for non-PowerShell shell families', () => {
+ expect(
+ resolveEffectiveWindowsPowerShell({
+ shellFamily: 'cmd.exe',
+ implementation: 'pwsh.exe',
+ pwshAvailable: true
+ })
+ ).toBeNull()
+
+ expect(
+ resolveEffectiveWindowsPowerShell({
+ shellFamily: 'wsl.exe',
+ implementation: 'powershell.exe',
+ pwshAvailable: true
+ })
+ ).toBeNull()
+
+ expect(
+ resolveEffectiveWindowsPowerShell({
+ shellFamily: undefined,
+ implementation: 'pwsh.exe',
+ pwshAvailable: true
+ })
+ ).toBeNull()
+ })
+
+ it('returns powershell.exe when the saved implementation is powershell.exe', () => {
+ expect(
+ resolveEffectiveWindowsPowerShell({
+ shellFamily: 'powershell.exe',
+ implementation: 'powershell.exe',
+ pwshAvailable: true
+ })
+ ).toBe('powershell.exe')
+ })
+
+ it('returns pwsh.exe when the saved implementation is pwsh.exe and pwsh is available', () => {
+ expect(
+ resolveEffectiveWindowsPowerShell({
+ shellFamily: 'powershell.exe',
+ implementation: 'pwsh.exe',
+ pwshAvailable: true
+ })
+ ).toBe('pwsh.exe')
+ })
+
+ it('falls back to powershell.exe when pwsh is preferred but unavailable', () => {
+ expect(
+ resolveEffectiveWindowsPowerShell({
+ shellFamily: 'powershell.exe',
+ implementation: 'pwsh.exe',
+ pwshAvailable: false
+ })
+ ).toBe('powershell.exe')
+ })
+
+ it('uses pwsh.exe for Auto when pwsh is available', () => {
+ expect(
+ resolveEffectiveWindowsPowerShell({
+ shellFamily: 'powershell.exe',
+ implementation: 'auto',
+ pwshAvailable: true
+ })
+ ).toBe('pwsh.exe')
+ })
+
+ it('uses powershell.exe for Auto when pwsh is unavailable', () => {
+ expect(
+ resolveEffectiveWindowsPowerShell({
+ shellFamily: 'powershell.exe',
+ implementation: 'auto',
+ pwshAvailable: false
+ })
+ ).toBe('powershell.exe')
+ })
+
+ it('defaults to Auto when no implementation is persisted', () => {
+ expect(
+ resolveEffectiveWindowsPowerShell({
+ shellFamily: 'powershell.exe',
+ implementation: undefined,
+ pwshAvailable: true
+ })
+ ).toBe('pwsh.exe')
+ })
+})
diff --git a/src/main/providers/windows-powershell.ts b/src/main/providers/windows-powershell.ts
new file mode 100644
index 000000000..7b0917fc4
--- /dev/null
+++ b/src/main/providers/windows-powershell.ts
@@ -0,0 +1,27 @@
+export type WindowsPowerShellImplementation = 'auto' | 'powershell.exe' | 'pwsh.exe'
+
+/** Resolve which PowerShell executable to spawn right now on Windows.
+ *
+ * Why: keep the saved pwsh preference intact even when pwsh is temporarily
+ * unavailable, so runtime falls back safely without mutating user settings.
+ */
+export function resolveEffectiveWindowsPowerShell(args: {
+ shellFamily: 'powershell.exe' | 'cmd.exe' | 'wsl.exe' | undefined
+ implementation: WindowsPowerShellImplementation | undefined
+ pwshAvailable: boolean
+}): 'powershell.exe' | 'pwsh.exe' | null {
+ if (args.shellFamily !== 'powershell.exe') {
+ return null
+ }
+
+ if (
+ (args.implementation === undefined ||
+ args.implementation === 'auto' ||
+ args.implementation === 'pwsh.exe') &&
+ args.pwshAvailable
+ ) {
+ return 'pwsh.exe'
+ }
+
+ return 'powershell.exe'
+}
diff --git a/src/main/pwsh.test.ts b/src/main/pwsh.test.ts
new file mode 100644
index 000000000..2aeb91fa1
--- /dev/null
+++ b/src/main/pwsh.test.ts
@@ -0,0 +1,87 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const { execFileSyncMock } = vi.hoisted(() => ({
+ execFileSyncMock: vi.fn()
+}))
+
+vi.mock('child_process', () => ({
+ execFileSync: execFileSyncMock
+}))
+
+function setPlatform(platform: NodeJS.Platform): () => void {
+ const originalPlatform = process.platform
+ Object.defineProperty(process, 'platform', {
+ configurable: true,
+ value: platform
+ })
+
+ return () => {
+ Object.defineProperty(process, 'platform', {
+ configurable: true,
+ value: originalPlatform
+ })
+ }
+}
+
+describe('isPwshAvailable', () => {
+ beforeEach(() => {
+ vi.resetModules()
+ execFileSyncMock.mockReset()
+ })
+
+ it('returns false on non-Windows platforms', async () => {
+ const restorePlatform = setPlatform('linux')
+
+ try {
+ const { isPwshAvailable } = await import('./pwsh')
+ expect(isPwshAvailable()).toBe(false)
+ expect(execFileSyncMock).not.toHaveBeenCalled()
+ } finally {
+ restorePlatform()
+ }
+ })
+
+ it('returns true when pwsh.exe is available on Windows', async () => {
+ const restorePlatform = setPlatform('win32')
+ execFileSyncMock.mockReturnValue('PowerShell 7.5.0')
+
+ try {
+ const { isPwshAvailable } = await import('./pwsh')
+ expect(isPwshAvailable()).toBe(true)
+ expect(execFileSyncMock).toHaveBeenCalledWith('pwsh.exe', ['-Version'], {
+ stdio: ['pipe', 'pipe', 'pipe'],
+ timeout: 5000
+ })
+ } finally {
+ restorePlatform()
+ }
+ })
+
+ it('returns false when pwsh.exe probe throws on Windows', async () => {
+ const restorePlatform = setPlatform('win32')
+ execFileSyncMock.mockImplementation(() => {
+ throw new Error('missing pwsh')
+ })
+
+ try {
+ const { isPwshAvailable } = await import('./pwsh')
+ expect(isPwshAvailable()).toBe(false)
+ } finally {
+ restorePlatform()
+ }
+ })
+
+ it('reuses the cached result across repeated calls', async () => {
+ const restorePlatform = setPlatform('win32')
+ execFileSyncMock.mockReturnValue('PowerShell 7.5.0')
+
+ try {
+ const { isPwshAvailable } = await import('./pwsh')
+ expect(isPwshAvailable()).toBe(true)
+ expect(isPwshAvailable()).toBe(true)
+ expect(execFileSyncMock).toHaveBeenCalledTimes(1)
+ } finally {
+ restorePlatform()
+ }
+ })
+})
diff --git a/src/main/pwsh.ts b/src/main/pwsh.ts
new file mode 100644
index 000000000..c29881aa7
--- /dev/null
+++ b/src/main/pwsh.ts
@@ -0,0 +1,31 @@
+import { execFileSync } from 'child_process'
+
+// Cached pwsh availability check — evaluated once per process lifetime
+let pwshAvailableCache: boolean | null = null
+
+/**
+ * Check whether pwsh.exe is available on this Windows machine.
+ * Result is cached for the process lifetime.
+ */
+export function isPwshAvailable(): boolean {
+ if (pwshAvailableCache !== null) {
+ return pwshAvailableCache
+ }
+
+ if (process.platform !== 'win32') {
+ pwshAvailableCache = false
+ return false
+ }
+
+ try {
+ execFileSync('pwsh.exe', ['-Version'], {
+ stdio: ['pipe', 'pipe', 'pipe'],
+ timeout: 5000
+ })
+ pwshAvailableCache = true
+ } catch {
+ pwshAvailableCache = false
+ }
+
+ return pwshAvailableCache
+}
diff --git a/src/main/rate-limits/gemini-usage-fetcher.fallback.test.ts b/src/main/rate-limits/gemini-usage-fetcher.fallback.test.ts
index 0d978a14f..fddd0a77d 100644
--- a/src/main/rate-limits/gemini-usage-fetcher.fallback.test.ts
+++ b/src/main/rate-limits/gemini-usage-fetcher.fallback.test.ts
@@ -175,18 +175,12 @@ describe('fetchGeminiRateLimits fallback oauth creds', () => {
expect(result.error).toContain('Gemini project ID not found')
})
- it('returns unavailable when geminiCliOAuthEnabled=false and no google entry in auth.json', async () => {
- readFileMock.mockImplementation(async (filePath: string) => {
- if (filePath.includes('auth.json')) {
- return JSON.stringify({ 'opencode-go': { type: 'api', key: 'k' } })
- }
- throw { code: 'ENOENT' }
- })
-
+ it('returns unavailable without reading OAuth files when geminiCliOAuthEnabled=false', async () => {
const result = await fetchGeminiRateLimits(false)
expect(result.status).toBe('unavailable')
expect(result.error).toContain('disabled')
+ expect(readFileMock).not.toHaveBeenCalled()
// No network calls should have been made.
expect(netFetchMock).not.toHaveBeenCalled()
})
diff --git a/src/main/rate-limits/gemini-usage-fetcher.ts b/src/main/rate-limits/gemini-usage-fetcher.ts
index 95b710ef9..1f214b4b5 100644
--- a/src/main/rate-limits/gemini-usage-fetcher.ts
+++ b/src/main/rate-limits/gemini-usage-fetcher.ts
@@ -203,22 +203,25 @@ async function fetchViaOauthCreds(
export async function fetchGeminiRateLimits(
geminiCliOAuthEnabled = false
): Promise {
+ if (!geminiCliOAuthEnabled) {
+ // Why: the OAuth sources include other apps' data folders on macOS.
+ // Do not touch them during background polling unless the user opts in.
+ return {
+ provider: 'gemini',
+ session: null,
+ weekly: null,
+ updatedAt: Date.now(),
+ error: 'Gemini CLI OAuth is disabled in settings',
+ status: 'unavailable'
+ }
+ }
+
try {
const authJson = await readAuthJson()
const result =
authJson?.google?.type === 'oauth'
? await fetchViaAuthJson(authJson.google, geminiCliOAuthEnabled)
: await (async () => {
- if (!geminiCliOAuthEnabled) {
- return {
- provider: 'gemini',
- session: null,
- weekly: null,
- updatedAt: Date.now(),
- error: 'Gemini CLI OAuth is disabled in settings',
- status: 'unavailable'
- } as ProviderRateLimits
- }
const creds = await readGeminiCredentials()
return !creds
? ({
diff --git a/src/main/rate-limits/service.ts b/src/main/rate-limits/service.ts
index fc63a49e3..ef827a820 100644
--- a/src/main/rate-limits/service.ts
+++ b/src/main/rate-limits/service.ts
@@ -37,7 +37,12 @@ type InternalRateLimitState = {
}
export class RateLimitService {
- private state: InternalRateLimitState = { claude: null, codex: null, gemini: null, opencodeGo: null }
+ private state: InternalRateLimitState = {
+ claude: null,
+ codex: null,
+ gemini: null,
+ opencodeGo: null
+ }
private pollInterval: number = DEFAULT_POLL_MS
private timer: ReturnType | null = null
private lastFetchAt = 0
diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts
index a88070803..afcad8ce8 100644
--- a/src/main/runtime/orca-runtime.ts
+++ b/src/main/runtime/orca-runtime.ts
@@ -2066,7 +2066,10 @@ export class OrcaRuntimeService {
let setup: CreateWorktreeResult['setup']
let warning: string | undefined
- const hooks = getEffectiveHooks(repo)
+ // Why: CLI-created worktrees do not have a renderer preview to mismatch
+ // against. Trust is granted by the direct CLI invocation (`--run-hooks`),
+ // so loading the setup hook from the created worktree is intentional here.
+ const hooks = getEffectiveHooks(repo, worktreePath)
// Why: setupDecision lets mobile/CLI callers control whether the setup
// script runs. 'skip' suppresses it, 'run' forces it, 'inherit' (default)
// defers to the repo's orca.yaml setupRunPolicy. runHooks === true maps
@@ -2088,7 +2091,7 @@ export class OrcaRuntimeService {
console.error(`[hooks] Failed to prepare setup runner for ${worktreePath}:`, error)
}
} else {
- void runHook('setup', worktreePath, repo).then((result) => {
+ void runHook('setup', worktreePath, repo, worktreePath).then((result) => {
if (!result.success) {
console.error(`[hooks] setup hook failed for ${worktreePath}:`, result.output)
}
diff --git a/src/main/runtime/runtime-metadata.test.ts b/src/main/runtime/runtime-metadata.test.ts
index 4cea991f6..4e93e909d 100644
--- a/src/main/runtime/runtime-metadata.test.ts
+++ b/src/main/runtime/runtime-metadata.test.ts
@@ -3,7 +3,12 @@ import { tmpdir } from 'os'
import { join } from 'path'
import { afterEach, describe, expect, it } from 'vitest'
import { getRuntimeMetadataPath } from '../../shared/runtime-bootstrap'
-import { clearRuntimeMetadata, readRuntimeMetadata, writeRuntimeMetadata } from './runtime-metadata'
+import {
+ clearRuntimeMetadata,
+ clearRuntimeMetadataIfOwned,
+ readRuntimeMetadata,
+ writeRuntimeMetadata
+} from './runtime-metadata'
const tempDirs: string[] = []
@@ -63,6 +68,73 @@ describe('runtime metadata', () => {
expect(getRuntimeMetadataPath(userDataPath)).toContain('orca-runtime.json')
})
+ describe('clearRuntimeMetadataIfOwned', () => {
+ it('clears metadata when pid and runtimeId both match', () => {
+ const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-metadata-'))
+ tempDirs.push(userDataPath)
+ writeRuntimeMetadata(userDataPath, {
+ runtimeId: 'rt_owner',
+ pid: 42,
+ transports: [],
+ authToken: null,
+ startedAt: 100
+ })
+
+ clearRuntimeMetadataIfOwned(userDataPath, 42, 'rt_owner')
+
+ expect(readRuntimeMetadata(userDataPath)).toBeNull()
+ })
+
+ it('retains metadata when the pid does not match (simulates auto-update handoff)', () => {
+ const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-metadata-'))
+ tempDirs.push(userDataPath)
+ writeRuntimeMetadata(userDataPath, {
+ runtimeId: 'rt_replacement',
+ pid: 999,
+ transports: [],
+ authToken: null,
+ startedAt: 200
+ })
+
+ clearRuntimeMetadataIfOwned(userDataPath, 42, 'rt_owner')
+
+ expect(readRuntimeMetadata(userDataPath)).toMatchObject({
+ pid: 999,
+ runtimeId: 'rt_replacement'
+ })
+ })
+
+ it('retains metadata when only the runtimeId differs', () => {
+ // Why: pid reuse is possible across an auto-update (fork+exec keeps the
+ // old pid if the OS reassigns it quickly). The runtimeId check is the
+ // second-level guard that catches this even when pid collides.
+ const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-metadata-'))
+ tempDirs.push(userDataPath)
+ writeRuntimeMetadata(userDataPath, {
+ runtimeId: 'rt_replacement',
+ pid: 42,
+ transports: [],
+ authToken: null,
+ startedAt: 200
+ })
+
+ clearRuntimeMetadataIfOwned(userDataPath, 42, 'rt_owner')
+
+ expect(readRuntimeMetadata(userDataPath)).toMatchObject({
+ pid: 42,
+ runtimeId: 'rt_replacement'
+ })
+ })
+
+ it('is a no-op when no metadata exists', () => {
+ const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-metadata-'))
+ tempDirs.push(userDataPath)
+
+ expect(() => clearRuntimeMetadataIfOwned(userDataPath, 42, 'rt_owner')).not.toThrow()
+ expect(readRuntimeMetadata(userDataPath)).toBeNull()
+ })
+ })
+
it.runIf(process.platform !== 'win32')(
'restricts runtime metadata permissions to the current user on Unix',
() => {
diff --git a/src/main/runtime/runtime-metadata.ts b/src/main/runtime/runtime-metadata.ts
index 3818dc253..95a7f707c 100644
--- a/src/main/runtime/runtime-metadata.ts
+++ b/src/main/runtime/runtime-metadata.ts
@@ -30,6 +30,38 @@ export function clearRuntimeMetadata(userDataPath: string): void {
rmSync(getRuntimeMetadataPath(userDataPath), { force: true })
}
+/**
+ * Why: clearing metadata unconditionally on quit would race with a sibling
+ * Orca process during auto-updater handoff (the new process may already
+ * have written its own metadata before the old process finishes tearing
+ * down). The ownership guard — pid + runtimeId must both match the values
+ * the caller recorded at its own startup — keeps the clean-exit case honest
+ * ('not_running' instead of 'stale_bootstrap') while refusing to erase the
+ * replacement process's fresh bootstrap.
+ *
+ * Callers MUST capture `ownedPid` and `ownedRuntimeId` synchronously at
+ * startup (or at least before any shutdown await) so the comparison below
+ * reflects the process that actually wrote the file, not whatever state
+ * globals happen to hold mid-teardown.
+ */
+export function clearRuntimeMetadataIfOwned(
+ userDataPath: string,
+ ownedPid: number,
+ ownedRuntimeId: string
+): void {
+ const current = readRuntimeMetadata(userDataPath)
+ if (!current) {
+ return
+ }
+ if (current.pid !== ownedPid) {
+ return
+ }
+ if (current.runtimeId !== ownedRuntimeId) {
+ return
+ }
+ clearRuntimeMetadata(userDataPath)
+}
+
function writeMetadataFile(path: string, metadata: RuntimeMetadata): void {
const dir = dirname(path)
if (!existsSync(dir)) {
diff --git a/src/main/runtime/runtime-rpc.ts b/src/main/runtime/runtime-rpc.ts
index c592e6540..ab8f7f0e2 100644
--- a/src/main/runtime/runtime-rpc.ts
+++ b/src/main/runtime/runtime-rpc.ts
@@ -4,6 +4,7 @@
// one on-disk file. Method handling lives in `rpc/` and transport specifics
// live in `rpc/unix-socket-transport.ts` and `rpc/ws-transport.ts`.
import { randomBytes } from 'crypto'
+import { readdirSync, rmSync } from 'fs'
import { join } from 'path'
import type { RuntimeMetadata, RuntimeTransportMetadata } from '../../shared/runtime-bootstrap'
import type { OrcaRuntimeService } from './orca-runtime'
@@ -91,6 +92,16 @@ export class OrcaRuntimeRpcServer {
return
}
+ // Why: processes killed by SIGKILL / OOM-kill / forced-shutdown skip
+ // stop() and leave behind `o--*.sock` files in userData. Sweeping
+ // dead-pid sockets at startup keeps the directory from accumulating
+ // orphans over the app's lifetime. Named-pipe transports on Windows do
+ // not leave filesystem entries in userData, so the sweep is a no-op
+ // there.
+ if (this.platform !== 'win32') {
+ sweepOrphanedRuntimeSockets(this.userDataPath, this.pid)
+ }
+
const transportMeta = createRuntimeTransportMetadata(
this.userDataPath,
this.pid,
@@ -323,6 +334,61 @@ export class OrcaRuntimeRpcServer {
}
}
+/**
+ * Why: the regex MUST stay in lockstep with createRuntimeTransportMetadata()
+ * below, which emits `o-${pid}-${endpointSuffix}.sock` where endpointSuffix
+ * is `[A-Za-z0-9_-]{1,4}` (derived from a sanitised runtimeId prefix, or
+ * `'rt'` as the fallback). The invariant is covered by a unit test so any
+ * future change to the transport-name shape trips CI.
+ */
+export const RUNTIME_SOCKET_NAME_REGEX = /^o-(\d+)-[A-Za-z0-9_-]+\.sock$/
+
+export function sweepOrphanedRuntimeSockets(userDataPath: string, ownPid: number): void {
+ let entries: string[]
+ try {
+ entries = readdirSync(userDataPath)
+ } catch {
+ // Why: first-launch userData may not exist yet; the cold-start path
+ // below will create it. Nothing to sweep in that case.
+ return
+ }
+ for (const entry of entries) {
+ const match = RUNTIME_SOCKET_NAME_REGEX.exec(entry)
+ if (!match) {
+ continue
+ }
+ const pid = Number(match[1])
+ if (!Number.isFinite(pid)) {
+ continue
+ }
+ // Why: never touch the current process's socket. start() already
+ // rmSync's it if it exists, but belt-and-braces — a bug in the own-pid
+ // path here would rmSync a socket we're about to bind to.
+ if (pid === ownPid) {
+ continue
+ }
+ try {
+ // Why: signal 0 is the POSIX liveness probe — it delivers no signal
+ // but returns success iff the pid resolves AND the caller has
+ // permission to signal it. ESRCH = no such process; EPERM = pid
+ // exists but owned by another user, which is extremely unusual on a
+ // desktop app's userData dir but we conservatively leave those
+ // sockets alone.
+ process.kill(pid, 0)
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ESRCH') {
+ try {
+ rmSync(join(userDataPath, entry), { force: true })
+ } catch {
+ // Why: best-effort sweep — a permission error on unlink is fine
+ // to ignore; the socket will be cleaned by a later start() or
+ // by the OS on reboot.
+ }
+ }
+ }
+ }
+}
+
export function createRuntimeTransportMetadata(
userDataPath: string,
pid: number,
diff --git a/src/main/runtime/runtime-socket-sweep.test.ts b/src/main/runtime/runtime-socket-sweep.test.ts
new file mode 100644
index 000000000..d21650393
--- /dev/null
+++ b/src/main/runtime/runtime-socket-sweep.test.ts
@@ -0,0 +1,83 @@
+import { existsSync, mkdtempSync, writeFileSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { describe, expect, it } from 'vitest'
+import {
+ createRuntimeTransportMetadata,
+ RUNTIME_SOCKET_NAME_REGEX,
+ sweepOrphanedRuntimeSockets
+} from './runtime-rpc'
+
+describe('sweepOrphanedRuntimeSockets', () => {
+ // Why: a pid we know is always alive and is never the test runner's own
+ // pid — init on POSIX, so process.kill(1, 0) resolves without ESRCH. Using
+ // this synthetic pid for ownPid cleanly separates three retention branches
+ // (own-pid-skipped / alive-non-own-retained / dead-swept) into distinct
+ // observations.
+ const SYNTHETIC_OWN_PID = 1
+ const KNOWN_DEAD_PID = 99999999
+
+ it.runIf(process.platform !== 'win32')(
+ 'sweeps dead-pid sockets while retaining own, alive, and non-matching entries',
+ () => {
+ const userDataPath = mkdtempSync(join(tmpdir(), 'orca-sweep-'))
+
+ const ownPidSocket = join(userDataPath, `o-${SYNTHETIC_OWN_PID}-aaaa.sock`)
+ const aliveSocket = join(userDataPath, `o-${process.pid}-bbbb.sock`)
+ const deadSocket = join(userDataPath, `o-${KNOWN_DEAD_PID}-cccc.sock`)
+ const unrelatedFile = join(userDataPath, 'foo.sock')
+
+ writeFileSync(ownPidSocket, '')
+ writeFileSync(aliveSocket, '')
+ writeFileSync(deadSocket, '')
+ writeFileSync(unrelatedFile, '')
+
+ sweepOrphanedRuntimeSockets(userDataPath, SYNTHETIC_OWN_PID)
+
+ // Why: own pid (1) is skipped by the ownPid === pid early-exit.
+ expect(existsSync(ownPidSocket)).toBe(true)
+ // Why: alive non-own pid — process.kill(pid, 0) succeeds without
+ // throwing, so the sweep leaves it alone.
+ expect(existsSync(aliveSocket)).toBe(true)
+ // Why: dead pid — process.kill throws ESRCH, sweep removes it.
+ expect(existsSync(deadSocket)).toBe(false)
+ // Why: regex miss — not `o--.sock` shape, so the
+ // sweep never touches it.
+ expect(existsSync(unrelatedFile)).toBe(true)
+ }
+ )
+
+ it('tolerates a non-existent userData directory', () => {
+ const userDataPath = join(tmpdir(), `orca-sweep-missing-${Date.now()}`)
+
+ expect(() => sweepOrphanedRuntimeSockets(userDataPath, SYNTHETIC_OWN_PID)).not.toThrow()
+ })
+
+ it('regex invariant: matches sockets produced by createRuntimeTransportMetadata', () => {
+ // Why: if the socket-name factory ever changes shape (e.g. adds a new
+ // separator or allows different characters), the sweep will silently
+ // stop matching real sockets. Assert the two stay in lockstep.
+ const userDataPath = '/tmp'
+ const transport = createRuntimeTransportMetadata(userDataPath, 12345, 'linux', 'rt_abcdef')
+ expect(transport.kind).toBe('unix')
+ if (transport.kind !== 'unix') {
+ throw new Error('expected unix transport')
+ }
+ const basename = transport.endpoint.slice(transport.endpoint.lastIndexOf('/') + 1)
+ expect(RUNTIME_SOCKET_NAME_REGEX.test(basename)).toBe(true)
+ })
+
+ it('regex invariant: also matches the fallback runtimeId suffix ("rt")', () => {
+ // Why: createRuntimeTransportMetadata falls back to the literal 'rt'
+ // suffix when the runtimeId contains no allowed characters; the sweep
+ // regex must still match that shape.
+ const userDataPath = '/tmp'
+ const transport = createRuntimeTransportMetadata(userDataPath, 99, 'darwin', '!!!!')
+ if (transport.kind !== 'unix') {
+ throw new Error('expected unix transport')
+ }
+ const basename = transport.endpoint.slice(transport.endpoint.lastIndexOf('/') + 1)
+ expect(RUNTIME_SOCKET_NAME_REGEX.test(basename)).toBe(true)
+ expect(basename).toBe('o-99-rt.sock')
+ })
+})
diff --git a/src/main/startup/configure-process.test.ts b/src/main/startup/configure-process.test.ts
index a20dd7c6e..a58e85dab 100644
--- a/src/main/startup/configure-process.test.ts
+++ b/src/main/startup/configure-process.test.ts
@@ -13,7 +13,8 @@ vi.mock('electron', () => {
exit: vi.fn(),
isPackaged: false,
commandLine: {
- appendSwitch: vi.fn()
+ appendSwitch: vi.fn(),
+ getSwitchValue: vi.fn(() => '')
}
}
}
@@ -246,97 +247,31 @@ describe('installDevParentWatchdog', () => {
})
describe('enableMainProcessGpuFeatures', () => {
- const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')
- const originalWaylandDisplay = process.env.WAYLAND_DISPLAY
- const originalXdgSessionType = process.env.XDG_SESSION_TYPE
-
- function setPlatform(platform: NodeJS.Platform): void {
- Object.defineProperty(process, 'platform', {
- configurable: true,
- value: platform
- })
- }
-
- afterEach(() => {
- if (originalPlatform) {
- Object.defineProperty(process, 'platform', originalPlatform)
- }
- if (originalWaylandDisplay === undefined) {
- delete process.env.WAYLAND_DISPLAY
- } else {
- process.env.WAYLAND_DISPLAY = originalWaylandDisplay
- }
- if (originalXdgSessionType === undefined) {
- delete process.env.XDG_SESSION_TYPE
- } else {
- process.env.XDG_SESSION_TYPE = originalXdgSessionType
- }
- })
-
- it('appends Orca GPU flags on darwin', async () => {
+ it('appends VS Code-style GPU channel flags without unsafe WebGPU/Vulkan opt-ins', async () => {
const { app } = await import('electron')
const { enableMainProcessGpuFeatures } = await import('./configure-process')
vi.mocked(app.commandLine.appendSwitch).mockClear()
- setPlatform('darwin')
enableMainProcessGpuFeatures()
expect(app.commandLine.appendSwitch).toHaveBeenCalledWith(
'enable-features',
- 'Vulkan,UseSkiaGraphite'
+ 'EarlyEstablishGpuChannel,EstablishGpuChannelAsync'
)
- expect(app.commandLine.appendSwitch).toHaveBeenCalledWith('enable-unsafe-webgpu')
+ expect(app.commandLine.appendSwitch).not.toHaveBeenCalledWith('enable-unsafe-webgpu')
})
- it('appends Orca GPU flags on linux X11 sessions', async () => {
- // Why: Chromium's X11 Vulkan path works, so we keep Skia Graphite / WebGPU
- // acceleration on X11. Only Wayland hits the wayland_surface_factory.cc
- // incompatibility and needs the gate.
+ it('preserves existing enable-features switches', async () => {
const { app } = await import('electron')
const { enableMainProcessGpuFeatures } = await import('./configure-process')
vi.mocked(app.commandLine.appendSwitch).mockClear()
- setPlatform('linux')
- delete process.env.WAYLAND_DISPLAY
- process.env.XDG_SESSION_TYPE = 'x11'
+ vi.mocked(app.commandLine.getSwitchValue).mockReturnValue('ExistingFeature')
enableMainProcessGpuFeatures()
expect(app.commandLine.appendSwitch).toHaveBeenCalledWith(
'enable-features',
- 'Vulkan,UseSkiaGraphite'
+ 'EarlyEstablishGpuChannel,EstablishGpuChannelAsync,ExistingFeature'
)
- expect(app.commandLine.appendSwitch).toHaveBeenCalledWith('enable-unsafe-webgpu')
- })
-
- it('skips Vulkan/SkiaGraphite/WebGPU switches when WAYLAND_DISPLAY is set', async () => {
- // Why: Chromium's Ozone/Wayland surface factory hard-aborts with Vulkan
- // enabled (wayland_surface_factory.cc:251), producing a blank/transparent
- // window on Wayland-default distros (Arch/Omarchy/Hyprland, GNOME-Wayland).
- const { app } = await import('electron')
- const { enableMainProcessGpuFeatures } = await import('./configure-process')
-
- vi.mocked(app.commandLine.appendSwitch).mockClear()
- setPlatform('linux')
- process.env.WAYLAND_DISPLAY = 'wayland-0'
- delete process.env.XDG_SESSION_TYPE
- enableMainProcessGpuFeatures()
-
- expect(app.commandLine.appendSwitch).not.toHaveBeenCalled()
- })
-
- it('skips switches when XDG_SESSION_TYPE=wayland without WAYLAND_DISPLAY', async () => {
- // Why: belt-and-suspenders — some nested/manually-started Wayland sessions
- // advertise XDG_SESSION_TYPE=wayland without yet having WAYLAND_DISPLAY
- // set in the process's environment at launch time.
- const { app } = await import('electron')
- const { enableMainProcessGpuFeatures } = await import('./configure-process')
-
- vi.mocked(app.commandLine.appendSwitch).mockClear()
- setPlatform('linux')
- delete process.env.WAYLAND_DISPLAY
- process.env.XDG_SESSION_TYPE = 'wayland'
- enableMainProcessGpuFeatures()
-
- expect(app.commandLine.appendSwitch).not.toHaveBeenCalled()
})
})
diff --git a/src/main/startup/configure-process.ts b/src/main/startup/configure-process.ts
index fe1c309e5..bf64bc4a3 100644
--- a/src/main/startup/configure-process.ts
+++ b/src/main/startup/configure-process.ts
@@ -169,33 +169,17 @@ export function installDevParentWatchdog(isDev: boolean): void {
timer.unref()
}
-function isLinuxWaylandSession(): boolean {
- // Why: WAYLAND_DISPLAY is set directly by the Wayland compositor and is the
- // same signal Electron's own ELECTRON_OZONE_PLATFORM_HINT=auto logic uses.
- // XDG_SESSION_TYPE is the login-manager/PAM signal and is the belt-and-
- // suspenders check for sessions where WAYLAND_DISPLAY isn't set at process
- // start (nested Wayland, manual session startup). Both are inherited from
- // the parent process, so they're available before app.whenReady where the
- // GPU command-line switches must be appended.
- return (
- process.platform === 'linux' &&
- (Boolean(process.env.WAYLAND_DISPLAY) || process.env.XDG_SESSION_TYPE === 'wayland')
- )
-}
-
export function enableMainProcessGpuFeatures(): void {
- // Why: Chromium's Ozone/Wayland surface factory hard-aborts when Vulkan is
- // enabled (see wayland_surface_factory.cc:251 — "--ozone-platform=wayland is
- // not compatible with Vulkan"), leaving the renderer unable to compose and
- // showing a blank/transparent window on Wayland-default distros like
- // Arch/Omarchy/Hyprland and GNOME-Wayland. Skia Graphite is Vulkan-only on
- // Linux (no OpenGL backend), so enabling it with Vulkan off would silently
- // fall back to software rendering — gate it on the same Wayland signal.
- // The X11 Vulkan path works, so we keep the acceleration there and on
- // macOS/Windows.
- if (isLinuxWaylandSession()) {
- return
- }
- app.commandLine.appendSwitch('enable-features', 'Vulkan,UseSkiaGraphite')
- app.commandLine.appendSwitch('enable-unsafe-webgpu')
+ const existingFeatures = app.commandLine.getSwitchValue('enable-features')
+ const features = [
+ // Why: mirror VS Code's conservative Electron GPU-channel startup flags
+ // instead of opting into Vulkan/SkiaGraphite/unsafe WebGPU globally.
+ // Terminal acceleration is controlled by xterm WebGL in the renderer.
+ 'EarlyEstablishGpuChannel',
+ 'EstablishGpuChannelAsync',
+ existingFeatures
+ ]
+ .filter(Boolean)
+ .join(',')
+ app.commandLine.appendSwitch('enable-features', features)
}
diff --git a/src/main/startup/single-instance-lock.test.ts b/src/main/startup/single-instance-lock.test.ts
new file mode 100644
index 000000000..4b1fe7a1c
--- /dev/null
+++ b/src/main/startup/single-instance-lock.test.ts
@@ -0,0 +1,67 @@
+import type { App } from 'electron'
+import { describe, expect, it, vi } from 'vitest'
+import { acquireSingleInstanceLock } from './single-instance-lock'
+
+type Listener = (...args: unknown[]) => void
+
+function makeFakeApp(lockResult: boolean): {
+ app: App
+ requestSingleInstanceLock: ReturnType
+ on: ReturnType
+ listeners: Record
+} {
+ const listeners: Record = {}
+ const requestSingleInstanceLock = vi.fn(() => lockResult)
+ const on = vi.fn((event: string, cb: Listener) => {
+ listeners[event] = listeners[event] ?? []
+ listeners[event].push(cb)
+ })
+ const app = {
+ requestSingleInstanceLock,
+ on
+ } as unknown as App
+ return { app, requestSingleInstanceLock, on, listeners }
+}
+
+describe('acquireSingleInstanceLock', () => {
+ it('returns false and does NOT register second-instance when the lock is held', () => {
+ const onSecondInstance = vi.fn()
+ const fake = makeFakeApp(false)
+
+ const acquired = acquireSingleInstanceLock(fake.app, onSecondInstance)
+
+ expect(acquired).toBe(false)
+ expect(fake.requestSingleInstanceLock).toHaveBeenCalledTimes(1)
+ // Why: if we registered the listener on a losing process, focusing the
+ // existing window would become our job even though the primary owns
+ // that UX surface. Verify no listener was added.
+ expect(fake.on).not.toHaveBeenCalled()
+ expect(fake.listeners['second-instance']).toBeUndefined()
+ })
+
+ it('returns true and registers exactly one second-instance listener when the lock is acquired', () => {
+ const onSecondInstance = vi.fn()
+ const fake = makeFakeApp(true)
+
+ const acquired = acquireSingleInstanceLock(fake.app, onSecondInstance)
+
+ expect(acquired).toBe(true)
+ expect(fake.requestSingleInstanceLock).toHaveBeenCalledTimes(1)
+ expect(fake.on).toHaveBeenCalledTimes(1)
+ expect(fake.on).toHaveBeenCalledWith('second-instance', onSecondInstance)
+ expect(fake.listeners['second-instance']).toHaveLength(1)
+ })
+
+ it('fires the registered callback when second-instance dispatches', () => {
+ const onSecondInstance = vi.fn()
+ const fake = makeFakeApp(true)
+
+ acquireSingleInstanceLock(fake.app, onSecondInstance)
+
+ const [registered] = fake.listeners['second-instance'] ?? []
+ expect(registered).toBeDefined()
+ registered?.()
+
+ expect(onSecondInstance).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/src/main/startup/single-instance-lock.ts b/src/main/startup/single-instance-lock.ts
new file mode 100644
index 000000000..0227d454c
--- /dev/null
+++ b/src/main/startup/single-instance-lock.ts
@@ -0,0 +1,27 @@
+import type { App } from 'electron'
+
+/**
+ * Why: Orca writes two canonical discovery files into `/`:
+ * `orca-runtime.json` (RPC endpoint + authToken for the bundled CLI) and
+ * `agent-hooks/endpoint.env` (hook port + token for cursor-agent/claude/codex
+ * scripts). Without a single-instance lock, every AppImage/.app double-click
+ * boots a fresh Electron main that clobbers both files. When the most recent
+ * instance quits, metadata points at a dead pid and `orca status` reports
+ * `stale_bootstrap` even though the original process is still running.
+ *
+ * This helper centralises the lock gate so it is testable in isolation and
+ * so `src/main/index.ts` has one clean call site rather than two spread-out
+ * Electron calls.
+ *
+ * Electron derives the lock identity from the current `userData` path, so
+ * callers MUST invoke this AFTER `configureDevUserDataPath(is.dev)` — that
+ * way dev (`orca-dev` userData) and packaged (`orca` userData) runs lock in
+ * separate namespaces instead of serialising against each other.
+ */
+export function acquireSingleInstanceLock(app: App, onSecondInstance: () => void): boolean {
+ if (!app.requestSingleInstanceLock()) {
+ return false
+ }
+ app.on('second-instance', onSecondInstance)
+ return true
+}
diff --git a/src/main/window/attach-main-window-services.test.ts b/src/main/window/attach-main-window-services.test.ts
index a6b279e66..1a11ddd2f 100644
--- a/src/main/window/attach-main-window-services.test.ts
+++ b/src/main/window/attach-main-window-services.test.ts
@@ -196,7 +196,7 @@ describe('attachMainWindowServices', () => {
}
})
- it('denies browser-session permissions, display capture, and downloads by default', () => {
+ it('denies browser-session permissions, display capture, and downloads by default', async () => {
const browserSessionOnMock = vi.fn()
sessionFromPartitionMock.mockReturnValue({
setPermissionRequestHandler: setPermissionRequestHandlerMock,
@@ -214,35 +214,39 @@ describe('attachMainWindowServices', () => {
const browserPermissionHandler = setPermissionRequestHandlerMock.mock.calls[1][0] as (
wc: unknown,
permission: string,
- callback: (allowed: boolean) => void
+ callback: (allowed: boolean) => void,
+ details?: unknown
) => void
- const permissionCallback = vi.fn()
- const guestWebContents = { id: 401, getURL: vi.fn(() => 'https://example.com/account') }
- browserPermissionHandler(guestWebContents, 'fullscreen', permissionCallback)
- browserPermissionHandler(guestWebContents, 'media', permissionCallback)
-
- expect(permissionCallback.mock.calls).toEqual([[true], [false]])
+ const cb = vi.fn()
+ const guestWc = { id: 401, getURL: vi.fn(() => 'https://example.com/account') }
+ browserPermissionHandler(guestWc, 'fullscreen', cb)
+ browserPermissionHandler(guestWc, 'notifications', cb)
+ // Why: `media` routes through macOS TCC instead of being denied outright,
+ // so pages inside the in-app browser can use camera/mic once Orca has been
+ // granted Camera/Microphone at the OS level.
+ browserPermissionHandler(guestWc, 'media', cb, { mediaTypes: ['video'] })
+ await vi.waitFor(() => expect(cb.mock.calls).toEqual([[true], [false], [true]]))
expect(browserManagerNotifyPermissionDeniedMock).toHaveBeenCalledTimes(1)
expect(browserManagerNotifyPermissionDeniedMock).toHaveBeenCalledWith({
guestWebContentsId: 401,
- permission: 'media',
+ permission: 'notifications',
rawUrl: 'https://example.com/account'
})
- const browserPermissionCheckHandler = setPermissionCheckHandlerMock.mock.calls[1][0] as (
+ const browserCheckHandler = setPermissionCheckHandlerMock.mock.calls[1][0] as (
wc: unknown,
- permission: string
+ permission: string,
+ origin: string,
+ details?: { mediaType?: 'video' | 'audio' | 'unknown' }
) => boolean
- expect(browserPermissionCheckHandler(null, 'fullscreen')).toBe(true)
- expect(browserPermissionCheckHandler(null, 'notifications')).toBe(false)
+ expect(browserCheckHandler(null, 'fullscreen', '')).toBe(true)
+ expect(browserCheckHandler(null, 'notifications', '')).toBe(false)
+ expect(browserCheckHandler(null, 'media', '', { mediaType: 'video' })).toBe(true)
- const displayMediaHandler = setDisplayMediaRequestHandlerMock.mock.calls[0][0] as (
- request: unknown,
- callback: (streams: { video: null; audio: null }) => void
- ) => void
- const displayCallback = vi.fn()
- displayMediaHandler(null, displayCallback)
- expect(displayCallback).toHaveBeenCalledWith({ video: undefined, audio: undefined })
+ const displayMediaHandler = setDisplayMediaRequestHandlerMock.mock.calls[0][0]
+ const displayCb = vi.fn()
+ displayMediaHandler(null, displayCb)
+ expect(displayCb).toHaveBeenCalledWith({ video: undefined, audio: undefined })
const willDownloadHandler = browserSessionOnMock.mock.calls.find(
([eventName]) => eventName === 'will-download'
diff --git a/src/main/window/attach-main-window-services.ts b/src/main/window/attach-main-window-services.ts
index eb601eaa0..fce7efc10 100644
--- a/src/main/window/attach-main-window-services.ts
+++ b/src/main/window/attach-main-window-services.ts
@@ -1,16 +1,18 @@
import fs from 'node:fs/promises'
import path from 'node:path'
-import { app, clipboard, ipcMain, nativeImage, session, systemPreferences } from 'electron'
-import type { BrowserWindow, MediaAccessPermissionRequest } from 'electron'
+import { app, clipboard, ipcMain, nativeImage, session } from 'electron'
+import type { BrowserWindow } from 'electron'
import type { Store } from '../persistence'
import type { CreateWorktreeResult, WorktreeStartupLaunch } from '../../shared/types'
import { ORCA_BROWSER_PARTITION } from '../../shared/constants'
import { registerRepoHandlers } from '../ipc/repos'
import { registerWorktreeHandlers } from '../ipc/worktrees'
import { registerPtyHandlers } from '../ipc/pty'
+import { registerDaemonManagementHandlers } from '../ipc/pty-management'
import { registerSshHandlers } from '../ipc/ssh'
import { browserManager } from '../browser/browser-manager'
+import { hasSystemMediaAccess, requestSystemMediaAccess } from '../browser/browser-media-access'
import type { OrcaRuntimeService } from '../runtime/orca-runtime'
import {
checkForUpdatesFromMenu,
@@ -40,6 +42,13 @@ export function attachMainWindowServices(
() => store.getSettings(),
prepareClaudeAuth
)
+ // Why: the Manage Sessions settings panel (docs/daemon-staleness-ux.md §Phase 1)
+ // uses a narrow `pty:management:*` IPC surface that reads the live
+ // DaemonPtyRouter via getDaemonProvider(). Registering here — after
+ // registerPtyHandlers — keeps this wiring alongside the rest of the PTY IPC
+ // and ensures the handlers are re-installed on macOS app re-activation when
+ // the main window is recreated.
+ registerDaemonManagementHandlers()
// Why: GC runs on a 10s delay so live worktree enumeration completes first.
// Uses git worktree list (not store.getWorktreeMeta) because untouched
// worktrees have no metadata entries — see design doc §7.6.
@@ -106,10 +115,42 @@ export function attachMainWindowServices(
)
const browserSession = session.fromPartition(ORCA_BROWSER_PARTITION)
- browserSession.setPermissionRequestHandler((webContents, permission, callback) => {
+ browserSession.setPermissionRequestHandler((webContents, permission, callback, details) => {
// Why: the in-app browser is for dev previews and lightweight browsing, not
// trusted desktop-app privileges. Denying by default keeps arbitrary sites
// from silently escalating into camera/mic/notification prompts inside Orca.
+ // Why `media` is allowed through: camera/mic are still gated by macOS TCC
+ // at the app-process level, so granting here only *permits* Chromium to
+ // use whatever the OS has already authorized for Orca. Denying at this
+ // layer would make pages inside the in-app browser throw NotAllowedError
+ // even after the user granted Camera/Microphone via Settings → Permissions
+ // or System Settings — the bug #1273 partially addressed.
+ if (permission === 'media') {
+ void requestSystemMediaAccess(
+ details as Electron.MediaAccessPermissionRequest | undefined
+ ).then(
+ (granted) => {
+ if (!granted) {
+ browserManager.notifyPermissionDenied({
+ guestWebContentsId: webContents.id,
+ permission,
+ rawUrl: webContents.getURL()
+ })
+ }
+ callback(granted)
+ },
+ (error: unknown) => {
+ console.error('[permissions] Browser media access failed:', error)
+ browserManager.notifyPermissionDenied({
+ guestWebContentsId: webContents.id,
+ permission,
+ rawUrl: webContents.getURL()
+ })
+ callback(false)
+ }
+ )
+ return
+ }
const allowed = permission === 'fullscreen'
if (!allowed) {
browserManager.notifyPermissionDenied({
@@ -120,8 +161,14 @@ export function attachMainWindowServices(
}
callback(allowed)
})
- browserSession.setPermissionCheckHandler((_webContents, permission) => {
- return permission === 'fullscreen'
+ browserSession.setPermissionCheckHandler((_webContents, permission, _origin, details) => {
+ if (permission === 'fullscreen') {
+ return true
+ }
+ if (permission === 'media') {
+ return hasSystemMediaAccess(details?.mediaType)
+ }
+ return false
})
browserSession.setDisplayMediaRequestHandler((_request, callback) => {
// Why: arbitrary sites inside Orca should never be able to capture the
@@ -147,54 +194,6 @@ export function attachMainWindowServices(
})
}
-function requestedMediaTypes(
- details: MediaAccessPermissionRequest | undefined
-): Set<'audio' | 'video'> {
- return new Set(details?.mediaTypes ?? [])
-}
-
-function hasSystemMediaAccess(mediaType: string | undefined): boolean {
- if (process.platform !== 'darwin') {
- return true
- }
- if (mediaType === 'audio') {
- return systemPreferences.getMediaAccessStatus('microphone') === 'granted'
- }
- if (mediaType === 'video') {
- return systemPreferences.getMediaAccessStatus('camera') === 'granted'
- }
- return false
-}
-
-async function requestSystemMediaAccess(
- details: MediaAccessPermissionRequest | undefined
-): Promise {
- if (process.platform !== 'darwin') {
- return true
- }
-
- const mediaTypes = requestedMediaTypes(details)
- if (mediaTypes.size === 0) {
- return false
- }
-
- if (mediaTypes.has('audio')) {
- // Why: macOS only shows the TCC prompt from the app process, so Chromium's
- // media grant is paired with the OS-level request at the actual media ask.
- const granted = await systemPreferences.askForMediaAccess('microphone')
- if (!granted) {
- return false
- }
- }
- if (mediaTypes.has('video')) {
- const granted = await systemPreferences.askForMediaAccess('camera')
- if (!granted) {
- return false
- }
- }
- return true
-}
-
function registerRuntimeWindowLifecycle(
mainWindow: BrowserWindow,
runtime: OrcaRuntimeService
diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts
index 449c4a25e..2fca06e4e 100644
--- a/src/preload/api-types.ts
+++ b/src/preload/api-types.ts
@@ -6,9 +6,12 @@ import type {
BrowserSessionProfile,
BrowserSessionProfileScope,
BrowserSessionProfileSource,
+ BrowserViewportOverride,
ClaudeRateLimitAccountsState,
CodexRateLimitAccountsState,
+ CreateWorktreeArgs,
CreateWorktreeResult,
+ CustomSidekick,
DirEntry,
FsChangedPayload,
GhosttyImportPreview,
@@ -25,6 +28,7 @@ import type {
GitHubWorkItem,
GitHubWorkItemDetails,
GitHubViewer,
+ ListWorkItemsResult,
IssueInfo,
LinearViewer,
LinearConnectionStatus,
@@ -35,6 +39,7 @@ import type {
LinearLabel,
LinearMember,
LinearTeam,
+ MarkdownDocument,
GitHubIssueUpdate,
NotificationDispatchRequest,
NotificationDispatchResult,
@@ -44,6 +49,7 @@ import type {
PRComment,
PRInfo,
Repo,
+ SparsePreset,
SearchOptions,
SearchResult,
StatsSummary,
@@ -123,6 +129,10 @@ export type BrowserApi = {
}) => Promise
unregisterGuest: (args: { browserPageId: string }) => Promise
openDevTools: (args: { browserPageId: string }) => Promise
+ setViewportOverride: (args: {
+ browserPageId: string
+ override: BrowserViewportOverride | null
+ }) => Promise
onGuestLoadFailed: (
callback: (args: { browserPageId: string; loadError: BrowserLoadError }) => void
) => () => void
@@ -207,6 +217,32 @@ export type PreflightApi = {
detectRemoteAgents: (args: { connectionId: string }) => Promise
}
+// Why: renderer-facing mirror of the daemon's `SessionInfo` + protocolVersion
+// annotation (src/main/daemon/types.ts `DaemonSessionInfo`). Kept here instead
+// of imported from main because the preload boundary must not depend on
+// main-only protocol types — those are subprocess-facing. Keep the two shapes
+// in sync when adding fields on either side; the Manage Sessions panel reads
+// these directly.
+export type PtyManagementSession = {
+ sessionId: string
+ state: 'created' | 'spawning' | 'running' | 'exiting' | 'exited'
+ shellState: 'pending' | 'ready' | 'timed_out' | 'unsupported'
+ isAlive: boolean
+ pid: number | null
+ cwd: string | null
+ cols: number
+ rows: number
+ createdAt: number
+ protocolVersion: number
+}
+
+export type PtyManagementApi = {
+ listSessions: () => Promise<{ sessions: PtyManagementSession[] }>
+ killAll: () => Promise<{ killedCount: number; remainingCount: number }>
+ killOne: (args: { sessionId: string }) => Promise<{ success: boolean }>
+ restart: () => Promise<{ success: boolean }>
+}
+
export type ExportApi = {
htmlToPdf: (args: {
html: string
@@ -308,7 +344,15 @@ export type PreloadApi = {
update: (args: {
repoId: string
updates: Partial<
- Pick
+ Pick<
+ Repo,
+ | 'displayName'
+ | 'badgeColor'
+ | 'hookSettings'
+ | 'worktreeBaseRef'
+ | 'kind'
+ | 'issueSourcePreference'
+ >
>
}) => Promise
pickFolder: () => Promise
@@ -328,15 +372,21 @@ export type PreloadApi = {
searchBaseRefs: (args: { repoId: string; query: string; limit?: number }) => Promise
onChanged: (callback: () => void) => () => void
}
+ sparsePresets: {
+ list: (args: { repoId: string }) => Promise
+ save: (args: {
+ repoId: string
+ id?: string
+ name: string
+ directories: string[]
+ }) => Promise
+ remove: (args: { repoId: string; presetId: string }) => Promise
+ onChanged: (callback: (data: { repoId: string }) => void) => () => void
+ }
worktrees: {
list: (args: { repoId: string }) => Promise
listAll: () => Promise
- create: (args: {
- repoId: string
- name: string
- baseBranch?: string
- setupDecision?: 'inherit' | 'run' | 'skip'
- }) => Promise
+ create: (args: CreateWorktreeArgs) => Promise
resolvePrBase: (args: {
repoId: string
prNumber: number
@@ -392,6 +442,7 @@ export type PreloadApi = {
requestId: string,
snapshot: { data: string; cols: number; rows: number } | null
) => void
+ management: PtyManagementApi
}
feedback: {
submit: (args: {
@@ -437,7 +488,7 @@ export type PreloadApi = {
limit?: number
query?: string
before?: string
- }) => Promise[]>
+ }) => Promise>>
prChecks: (args: {
repoPath: string
prNumber: number
@@ -581,6 +632,11 @@ export type PreloadApi = {
pickDirectory: (args: { defaultPath?: string }) => Promise
copyFile: (args: { srcPath: string; destPath: string }) => Promise
}
+ sidekick: {
+ import: () => Promise
+ read: (id: string, fileName: string) => Promise
+ delete: (id: string, fileName: string) => Promise
+ }
browser: BrowserApi
hooks: {
check: (args: {
@@ -637,6 +693,10 @@ export type PreloadApi = {
filePath: string
connectionId?: string
}) => Promise<{ content: string; isBinary: boolean; isImage?: boolean; mimeType?: string }>
+ listMarkdownDocuments: (args: {
+ rootPath: string
+ connectionId?: string
+ }) => Promise
writeFile: (args: { filePath: string; content: string; connectionId?: string }) => Promise
createFile: (args: { filePath: string; connectionId?: string }) => Promise
createDir: (args: { dirPath: string; connectionId?: string }) => Promise
@@ -682,6 +742,18 @@ export type PreloadApi = {
}
)[]
}>
+ resolveDroppedPathsForAgent: (args: {
+ paths: string[]
+ worktreePath: string
+ connectionId?: string
+ }) => Promise<{
+ resolvedPaths: string[]
+ skipped: {
+ sourcePath: string
+ reason: 'missing' | 'symlink' | 'permission-denied' | 'unsupported'
+ }[]
+ failed: { sourcePath: string; reason: string }[]
+ }>
watchWorktree: (args: { worktreePath: string; connectionId?: string }) => Promise
unwatchWorktree: (args: { worktreePath: string; connectionId?: string }) => Promise
onFsChanged: (callback: (payload: FsChangedPayload) => void) => () => void
@@ -927,6 +999,9 @@ export type PreloadApi = {
wsl: {
isAvailable: () => Promise
}
+ pwsh: {
+ isAvailable: () => Promise
+ }
agentStatus: {
/** Listen for agent status updates forwarded from native hook receivers. */
onSet: (
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 56e965734..01eb98bf5 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -9,10 +9,15 @@ import type { CliInstallStatus } from '../shared/cli-install-types'
import type { AgentHookInstallStatus } from '../shared/agent-hook-types'
import type {
BaseRefDefaultResult,
+ BrowserViewportOverride,
+ CreateWorktreeArgs,
+ CustomSidekick,
FsChangedPayload,
GitHubAssignableUser,
GitHubCommentResult,
+ GitHubWorkItem,
GhosttyImportPreview,
+ ListWorkItemsResult,
MemorySnapshot,
NotificationDispatchResult,
SearchResult
@@ -190,6 +195,10 @@ const api = {
isAvailable: (): Promise => ipcRenderer.invoke('wsl:isAvailable')
},
+ pwsh: {
+ isAvailable: (): Promise => ipcRenderer.invoke('pwsh:isAvailable')
+ },
+
repos: {
list: (): Promise => ipcRenderer.invoke('repos:list'),
@@ -244,18 +253,36 @@ const api = {
}
},
+ sparsePresets: {
+ list: (args: { repoId: string }): Promise =>
+ ipcRenderer.invoke('sparsePresets:list', args),
+
+ save: (args: {
+ repoId: string
+ id?: string
+ name: string
+ directories: string[]
+ }): Promise => ipcRenderer.invoke('sparsePresets:save', args),
+
+ remove: (args: { repoId: string; presetId: string }): Promise =>
+ ipcRenderer.invoke('sparsePresets:remove', args),
+
+ onChanged: (callback: (data: { repoId: string }) => void): (() => void) => {
+ const listener = (_event: Electron.IpcRendererEvent, data: { repoId: string }) =>
+ callback(data)
+ ipcRenderer.on('sparsePresets:changed', listener)
+ return () => ipcRenderer.removeListener('sparsePresets:changed', listener)
+ }
+ },
+
worktrees: {
list: (args: { repoId: string }): Promise =>
ipcRenderer.invoke('worktrees:list', args),
listAll: (): Promise => ipcRenderer.invoke('worktrees:listAll'),
- create: (args: {
- repoId: string
- name: string
- baseBranch?: string
- setupDecision?: 'inherit' | 'run' | 'skip'
- }): Promise => ipcRenderer.invoke('worktrees:create', args),
+ create: (args: CreateWorktreeArgs): Promise