Merge remote-tracking branch 'origin/main' into Jinwoo-H/windows-update-survival

This commit is contained in:
Jinwoo Hong
2026-07-07 15:10:02 -04:00
81 changed files with 4568 additions and 501 deletions
+68 -16
View File
@@ -1,6 +1,6 @@
{
"schemaVersion": 1,
"updatedAt": "2026-07-03",
"updatedAt": "2026-07-07",
"policy": {
"maturityLevels": [
"experimental",
@@ -1273,7 +1273,7 @@
"macos"
],
"coveredProviders": [],
"coverageNotes": "Local macOS evidence on main@1282f5c2d; identical files to the pending stack. Real OS IME automation, Windows ConPTY post-agent reset, and the CJK/Vietnamese/Arabic matrix remain registered gaps.",
"coverageNotes": "Local macOS evidence on main@1282f5c2d, deterministic renderer-unit coverage for the Linux/Sogou candidate-key policy, and a local Electron/CDP live-PTY Sogou-style repro. Real Linux/Sogou OS IME automation, Windows ConPTY post-agent reset, and the CJK/Vietnamese/Arabic matrix remain registered gaps.",
"motivatingLinks": [
"https://github.com/stablyai/orca/pull/6699",
"https://github.com/stablyai/orca/pull/6682",
@@ -1281,14 +1281,20 @@
"https://github.com/stablyai/orca/pull/6999"
],
"invariant": "Composition, native text forwarding, synthetic input, paste, and platform keyboard bypass paths must not send preedit/control bytes before commit and must commit text exactly once to the intended PTY.",
"oracle": "The current renderer-unit slice asserts native text commits route to the intended PTY once, composition/preedit bookkeeping does not leak premature text, input-source classification handles synthetic/native paths, and paste/runtime forwarding avoids duplicate terminal payloads for covered fixtures. Real IME paths and the full CJK/Vietnamese/Arabic/JIS-yen matrix run in follow-up platform soak where automation is possible.",
"oracle": "The current renderer-unit slice asserts native text commits route to the intended PTY once, composition/preedit bookkeeping does not leak premature text, input-source classification handles synthetic/native paths, paste/runtime forwarding avoids duplicate terminal payloads for covered fixtures, and Linux/Sogou candidate Space/digit selectors do not leak keydown/keypress/keyup while ordinary post-IME typing remains available. The Electron/CDP live-PTY repro verifies Sogou-style Space and digit candidate selectors submit only the committed Chinese text. Real IME paths and the full CJK/Vietnamese/Arabic/JIS-yen matrix run in follow-up platform soak where automation is possible.",
"commands": [
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/terminal-ime-input-source.test.ts src/renderer/src/components/terminal-pane/terminal-paste-runtime.test.ts"
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/terminal-ime-input-source.test.ts src/renderer/src/components/terminal-pane/terminal-paste-runtime.test.ts src/renderer/src/components/terminal-pane/terminal-ime-composition-tracker.test.ts src/renderer/src/components/terminal-pane/terminal-ime-candidate-key-release-guard.test.ts src/renderer/src/components/terminal-pane/xterm-bypass-policy-non-mac.test.ts src/renderer/src/components/terminal-pane/xterm-bypass-policy.test.ts",
"pnpm run test:e2e -- tests/e2e/chinese-ime-chat-input-repro.spec.ts"
],
"testFiles": [
"src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.test.ts",
"src/renderer/src/components/terminal-pane/terminal-ime-input-source.test.ts",
"src/renderer/src/components/terminal-pane/terminal-paste-runtime.test.ts"
"src/renderer/src/components/terminal-pane/terminal-paste-runtime.test.ts",
"src/renderer/src/components/terminal-pane/terminal-ime-composition-tracker.test.ts",
"src/renderer/src/components/terminal-pane/terminal-ime-candidate-key-release-guard.test.ts",
"src/renderer/src/components/terminal-pane/xterm-bypass-policy-non-mac.test.ts",
"src/renderer/src/components/terminal-pane/xterm-bypass-policy.test.ts",
"tests/e2e/chinese-ime-chat-input-repro.spec.ts"
],
"assertionRefs": [
{
@@ -1309,34 +1315,80 @@
"assertions": [
"paste/runtime forwarding avoids duplicate terminal payloads"
]
},
{
"file": "src/renderer/src/components/terminal-pane/terminal-ime-composition-tracker.test.ts",
"assertions": [
"empty Sogou-style compositionupdate keeps composition active",
"stale composition state expires so editing keys cannot stay suppressed indefinitely",
"post-composition candidate guard is armed only by Sogou-style empty updates and clears after real typing"
]
},
{
"file": "src/renderer/src/components/terminal-pane/terminal-ime-candidate-key-release-guard.test.ts",
"assertions": [
"suppressed candidate keydown arms only the matching keypress/keyup release guard",
"held-key repeat keydowns stay guarded until their keyup, even past expiry",
"fresh keydowns, other keys, modified keys, and expired keypresses are not guarded, and a fresh press drops a stale pending release"
]
},
{
"file": "src/renderer/src/components/terminal-pane/xterm-bypass-policy-non-mac.test.ts",
"assertions": [
"standalone Linux 229 keydowns reach xterm while Windows 229 keydowns stay suppressed",
"candidate Space/digit selectors are suppressed only while candidate guards are active"
]
},
{
"file": "src/renderer/src/components/terminal-pane/xterm-bypass-policy.test.ts",
"assertions": [
"macOS standalone Process key behavior and composition-owned key suppression stay intact"
]
},
{
"file": "tests/e2e/chinese-ime-chat-input-repro.spec.ts",
"assertions": [
"Sogou-style Space candidate selection submits only the committed Chinese character",
"Sogou-style digit candidate selection submits only the committed Chinese phrase",
"Post-composition Sogou-style digit selection stays out of the PTY after compositionend"
]
}
],
"evidenceRuns": [
{
"date": "2026-07-03",
"date": "2026-07-07",
"runner": "local",
"platform": "macos",
"command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/terminal-ime-input-source.test.ts src/renderer/src/components/terminal-pane/terminal-paste-runtime.test.ts",
"command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/terminal-ime-input-source.test.ts src/renderer/src/components/terminal-pane/terminal-paste-runtime.test.ts src/renderer/src/components/terminal-pane/terminal-ime-composition-tracker.test.ts src/renderer/src/components/terminal-pane/terminal-ime-candidate-key-release-guard.test.ts src/renderer/src/components/terminal-pane/xterm-bypass-policy-non-mac.test.ts src/renderer/src/components/terminal-pane/xterm-bypass-policy.test.ts",
"result": "passed",
"durationSeconds": 0.9,
"summary": "3 test file(s) passed, 63 tests passed on main@1282f5c2d in a clean checkout."
"durationSeconds": 0.7,
"summary": "7 test file(s) passed, 144 tests passed on the Linux/Sogou candidate-key branch (includes held-key repeat guard coverage)."
},
{
"date": "2026-07-07",
"runner": "local",
"platform": "macos",
"command": "pnpm run test:e2e -- tests/e2e/chinese-ime-chat-input-repro.spec.ts",
"result": "passed",
"durationSeconds": 72.0,
"summary": "Electron/CDP IME repro passed: Sogou candidate selection, post-composition candidate selection, and existing Chinese IME harness passed; real Codex IME test was skipped behind ORCA_E2E_REAL_CODEX_IME."
}
],
"runtimeBudget": {
"p95Seconds": 30,
"scope": "renderer unit plus platform soak"
"p95Seconds": 90,
"scope": "renderer unit plus focused Electron/CDP IME repro"
},
"flakeHistory": {
"status": "unknown",
"evidence": "Focused renderer input tests are now registered; needs soak history and platform IME evidence before promotion."
"evidence": "Focused renderer input tests and the Electron/CDP Sogou-style repro are now registered; needs soak history and true platform IME evidence before promotion."
},
"redGreenEvidence": {
"status": "partial",
"evidence": "Focused tests cover existing native-text, input-source, and paste/runtime forwarding contracts. Needs intentional-break proof for duplicate native text forwarding and composition preedit leakage, plus the broader language/platform matrix."
"evidence": "Focused tests cover existing native-text, input-source, paste/runtime forwarding, Linux/Sogou candidate selector, post-composition guard contracts, and live-PTY Sogou-style candidate commits. Needs intentional-break proof for duplicate native text forwarding and composition preedit leakage, plus the broader language/platform matrix."
},
"performanceBudget": {
"required": false,
"evidence": "Required if input forwarding adds polling, repeated event listeners, or renderer hot-path work."
"required": true,
"evidence": "Terminal IME hot-path audit clean on 2026-07-07: candidate guard adds O(1) boolean checks plus a bounded Space/digit release map; composition listeners are disposed with pane lifecycle; no polling, IPC fan-out, subprocess work, or SSH/remote transport cost added."
},
"promotionCriteria": [
"Cover deterministic byte/cell oracles first.",
@@ -1344,7 +1396,7 @@
"Pair with Windows ConPTY keyboard reset for Windows standard-key behavior."
],
"knownGaps": [
"Current command is a renderer-unit slice; real OS IME automation may need manual or soak evidence.",
"Current commands include renderer-unit coverage and a CDP-driven Electron repro; real OS IME automation may need manual or soak evidence.",
"Backspace/Enter during composition, JIS yen, Arabic/RTL, paste edge cases, and Windows ConPTY post-agent key reset still need representative gate coverage."
],
"demotionRule": "Cannot promote if success is based only on DOM text without PTY byte/cell evidence."
+4 -4
View File
@@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="113" height="20" role="img" aria-label="downloads: 3.7m">
<title>downloads: 3.7m</title>
<svg xmlns="http://www.w3.org/2000/svg" width="113" height="20" role="img" aria-label="downloads: 3.9m">
<title>downloads: 3.9m</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
@@ -15,7 +15,7 @@
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="11">
<text x="37" y="15" fill="#010101" fill-opacity=".3">downloads</text>
<text x="37" y="14">downloads</text>
<text x="93.5" y="15" fill="#010101" fill-opacity=".3">3.7m</text>
<text x="93.5" y="14">3.7m</text>
<text x="93.5" y="15" fill="#010101" fill-opacity=".3">3.9m</text>
<text x="93.5" y="14">3.9m</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 943 B

After

Width:  |  Height:  |  Size: 943 B

+8
View File
@@ -102,6 +102,14 @@ export default function RootLayout() {
return
}
handledNotificationIdsRef.current.add(notificationId)
// Why: RootLayout never unmounts, so cap this tap-dedup set (FIFO) rather
// than letting it grow one id per notification tapped for the app's life.
if (handledNotificationIdsRef.current.size > 256) {
const oldest = handledNotificationIdsRef.current.values().next().value
if (oldest !== undefined) {
handledNotificationIdsRef.current.delete(oldest)
}
}
const path = await getNavigationPath(response.notification.request.content.data)
clearLastNotificationResponse()
@@ -1,6 +1,9 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import * as Notifications from 'expo-notifications'
import { subscribeToDesktopNotifications } from './mobile-notifications'
import {
setScheduledNotificationsMaxForTests,
subscribeToDesktopNotifications
} from './mobile-notifications'
import type { RpcClient } from '../transport/rpc-client'
import { loadPushNotificationsEnabled } from '../storage/preferences'
@@ -268,4 +271,48 @@ describe('subscribeToDesktopNotifications', () => {
expect(Notifications.dismissNotificationAsync).not.toHaveBeenCalled()
})
// Why: notificationId is unique per completion, so the map grew unbounded when
// the desktop never sent a dismiss (the remote-mobile case). It is now capped.
it('evicts the oldest scheduled entry once the cap is exceeded', async () => {
setScheduledNotificationsMaxForTests(1)
try {
vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true)
vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({
status: 'granted',
canAskAgain: true
} as never)
vi.mocked(Notifications.scheduleNotificationAsync)
.mockResolvedValueOnce('scheduled-old')
.mockResolvedValueOnce('scheduled-new')
vi.mocked(Notifications.dismissNotificationAsync).mockResolvedValue(undefined)
let onEvent: ((data: unknown) => void) | null = null
const client = {
subscribe: vi.fn((_method, _params, callback: (data: unknown) => void) => {
onEvent = callback
return vi.fn()
}),
getState: vi.fn(() => 'connected'),
sendRequest: vi.fn()
} as unknown as RpcClient
subscribeToDesktopNotifications(client, 'host-1')
onEvent?.({ type: 'notification', title: 't', body: 'b', notificationId: 'agent:old' })
await flushAsync()
onEvent?.({ type: 'notification', title: 't', body: 'b', notificationId: 'agent:new' })
await flushAsync()
// The older entry was evicted by the cap: dismissing it is a no-op...
onEvent?.({ type: 'dismiss', notificationId: 'agent:old' })
await flushAsync()
expect(Notifications.dismissNotificationAsync).not.toHaveBeenCalledWith('scheduled-old')
// ...while the most-recent entry is retained and still dismissable.
onEvent?.({ type: 'dismiss', notificationId: 'agent:new' })
await flushAsync()
expect(Notifications.dismissNotificationAsync).toHaveBeenCalledWith('scheduled-new')
} finally {
setScheduledNotificationsMaxForTests()
}
})
})
@@ -31,10 +31,42 @@ type ScheduledNotificationState = {
const scheduledNotificationsByHostAndNotificationId = new Map<string, ScheduledNotificationState>()
// Why: notificationId embeds a per-completion timestamp (buildAgentNotificationId),
// so every agent-task-complete inserts a new, never-reused key. Entries are only
// removed when the desktop sends a matching dismiss — which a remote mobile user
// (not at the desktop) frequently never gets — so the map grew for the app's whole
// life. Bound it; a settled entry only retains a small identifier used for later
// programmatic dismissal, unnecessary for long-past completions.
const MAX_SCHEDULED_NOTIFICATIONS = 256
let maxScheduledNotifications = MAX_SCHEDULED_NOTIFICATIONS
function getStoredNotificationKey(hostId: string, notificationId: string): string {
return `${encodeURIComponent(hostId)}:${encodeURIComponent(notificationId)}`
}
// Evict the oldest SETTLED entries (never one mid-schedule) until within the cap.
// Map iteration is insertion order, so the first match is the oldest.
function boundScheduledNotifications(): void {
while (scheduledNotificationsByHostAndNotificationId.size > maxScheduledNotifications) {
let evicted = false
for (const [key, state] of scheduledNotificationsByHostAndNotificationId) {
if (!state.pending) {
scheduledNotificationsByHostAndNotificationId.delete(key)
evicted = true
break
}
}
if (!evicted) {
break
}
}
}
/** Test-only: override the cap (pass no arg to restore the default). */
export function setScheduledNotificationsMaxForTests(max?: number): void {
maxScheduledNotifications = max ?? MAX_SCHEDULED_NOTIFICATIONS
}
export type NotificationPermissionState = {
granted: boolean
status: string
@@ -155,6 +187,7 @@ async function showLocalNotification(event: NotificationEvent, hostId: string):
return
}
notificationState.identifier = scheduledIdentifier
boundScheduledNotifications()
} finally {
if (notificationState.pending === pending) {
notificationState.pending = undefined
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "orca",
"version": "1.4.126",
"version": "1.4.127-rc.0",
"description": "Next-gen IDE for parallel agentic development",
"homepage": "https://github.com/stablyai/orca",
"author": "stablyai",
@@ -533,6 +533,56 @@ describe('CodexRuntimeHomeService', () => {
}
})
it('bridges WSL history from a configured per-distro source-home override', async () => {
const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
const startWslCodexSessionBridgeInBackground = vi.fn(() => Promise.resolve())
vi.doMock('../codex/wsl-codex-session-bridge', () => ({
startWslCodexSessionBridgeInBackground
}))
const wslHome = join(testState.userDataDir, 'wsl-home')
vi.doMock('../wsl', () => ({
getDefaultWslDistro: () => 'Ubuntu',
getWslHome: () => wslHome
}))
const store = createStore(
createSettings({
activeCodexManagedAccountId: null,
activeCodexManagedAccountIdsByRuntime: { host: null, wsl: { Ubuntu: null } },
// Why: the override is a Linux path inside the distro, not <wslHome>/.codex.
codexSessionSourceHome: { wsl: { Ubuntu: '/home/me/.config/codex' } }
})
)
try {
const { CodexRuntimeHomeService } = await import('./runtime-home-service')
const service = new CodexRuntimeHomeService(store as never)
const wslRuntimeHomePath = join(
wslHome,
'.local',
'share',
'orca',
'codex-runtime-home',
'home'
)
service.prepareForCodexLaunch({ runtime: 'wsl', wslDistro: 'Ubuntu' })
expect(startWslCodexSessionBridgeInBackground).toHaveBeenCalledTimes(1)
expect(startWslCodexSessionBridgeInBackground).toHaveBeenCalledWith({
distro: 'Ubuntu',
systemCodexHomePath: '/home/me/.config/codex',
managedCodexHomePath: wslRuntimeHomePath
})
} finally {
vi.doUnmock('../codex/wsl-codex-session-bridge')
vi.doUnmock('../wsl')
if (originalPlatform) {
Object.defineProperty(process, 'platform', originalPlatform)
}
}
})
it('starts WSL session bridging for the distro used by the materialized runtime home', async () => {
const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
@@ -40,6 +40,10 @@ import {
syncSystemCodexResourcesIntoManagedHome
} from '../codex/codex-home-paths'
import { startSystemCodexSessionBridgeInBackground } from '../codex/codex-session-bridge'
import {
resolveHostCodexSessionSourceHome,
resolveWslCodexSessionSourceHome
} from '../codex/codex-session-source-home'
import { startWslCodexSessionBridgeInBackground } from '../codex/wsl-codex-session-bridge'
import {
prepareSystemConfigForFreshRuntimeMirror,
@@ -146,7 +150,10 @@ export class CodexRuntimeHomeService {
syncSystemConfigIntoManagedCodexHome()
// Why: historical Codex sessions can be large; bridge them after launch
// setup so starting a fresh Codex TUI never waits on a full tree walk.
void startSystemCodexSessionBridgeInBackground()
void startSystemCodexSessionBridgeInBackground(
{},
resolveHostCodexSessionSourceHome(this.store.getSettings())
)
return this.getRuntimeHomePath()
}
@@ -162,10 +169,11 @@ export class CodexRuntimeHomeService {
if (!distro) {
return
}
const systemCodexHomePath = this.getWslSystemCodexHomePath({
runtime: 'wsl',
wslDistro: distro
})
// Why: history-only override lets custom-CODEX_HOME users bridge from their
// real home; falls back to <wslHome>/.codex, which auth/config still use.
const systemCodexHomePath =
resolveWslCodexSessionSourceHome(this.store.getSettings(), distro) ??
this.getWslSystemCodexHomePath({ runtime: 'wsl', wslDistro: distro })
if (!systemCodexHomePath || systemCodexHomePath === runtimeHomePath) {
return
}
@@ -215,6 +215,51 @@ describe('syncSystemCodexSessionsIntoManagedHome', () => {
).toBe(false)
})
it('bridges from a custom source home override instead of ~/.codex', () => {
// Why: users with a custom CODEX_HOME point history discovery at that
// folder; the default ~/.codex must be ignored when an override is given.
const customSourceHome = join(fakeHomeDir, 'custom-codex')
const customSessionPath = join(
customSourceHome,
'sessions',
'2026',
'05',
'26',
'rollout-custom.jsonl'
)
mkdirSync(dirname(customSessionPath), { recursive: true })
writeFileSync(customSessionPath, '{"id":"custom"}\n', 'utf-8')
// A session under the default ~/.codex should NOT be bridged when overridden.
const defaultSessionPath = join(
getSystemCodexHomePath(),
'sessions',
'2026',
'05',
'26',
'rollout-default.jsonl'
)
mkdirSync(dirname(defaultSessionPath), { recursive: true })
writeFileSync(defaultSessionPath, '{"id":"default"}\n', 'utf-8')
syncSystemCodexSessionsIntoManagedHome(customSourceHome)
const bridgedCustomPath = join(
getRuntimeCodexHomePath(),
'sessions',
'2026',
'05',
'26',
'rollout-custom.jsonl'
)
expect(readFileSync(bridgedCustomPath, 'utf-8')).toBe('{"id":"custom"}\n')
expect(
existsSync(
join(getRuntimeCodexHomePath(), 'sessions', '2026', '05', '26', 'rollout-default.jsonl')
)
).toBe(false)
})
it('falls back to symlinks when hardlinks are unavailable', () => {
fsMockState.failLink = true
const systemSessionPath = join(
+11 -6
View File
@@ -42,9 +42,12 @@ let backgroundSessionBridgeTask: Promise<void> | null = null
/**
* Synchronously mirrors system session files into the managed runtime home.
*
* `sourceCodexHomePath` overrides the default ~/.codex history source for users
* who run Codex with a custom CODEX_HOME; it only affects history discovery.
*/
export function syncSystemCodexSessionsIntoManagedHome(): void {
const systemSessionsRoot = join(getSystemCodexHomePath(), 'sessions')
export function syncSystemCodexSessionsIntoManagedHome(sourceCodexHomePath?: string): void {
const systemSessionsRoot = join(sourceCodexHomePath || getSystemCodexHomePath(), 'sessions')
if (!existsSync(systemSessionsRoot)) {
return
}
@@ -62,12 +65,13 @@ export function syncSystemCodexSessionsIntoManagedHome(): void {
* background bridging without starting duplicate directory walks.
*/
export function startSystemCodexSessionBridgeInBackground(
options: CodexSessionBridgeIncrementalOptions = {}
options: CodexSessionBridgeIncrementalOptions = {},
sourceCodexHomePath?: string
): Promise<void> {
if (backgroundSessionBridgeTask) {
return backgroundSessionBridgeTask
}
const task = syncSystemCodexSessionsIntoManagedHomeIncrementally(options)
const task = syncSystemCodexSessionsIntoManagedHomeIncrementally(options, sourceCodexHomePath)
.catch((error: unknown) => {
console.warn('[codex-session-bridge] Background session bridge failed:', error)
})
@@ -88,9 +92,10 @@ export function startSystemCodexSessionBridgeInBackground(
* bridge operation equivalent to the synchronous path.
*/
export async function syncSystemCodexSessionsIntoManagedHomeIncrementally(
options: CodexSessionBridgeIncrementalOptions = {}
options: CodexSessionBridgeIncrementalOptions = {},
sourceCodexHomePath?: string
): Promise<CodexSessionBridgeSummary> {
const systemSessionsRoot = join(getSystemCodexHomePath(), 'sessions')
const systemSessionsRoot = join(sourceCodexHomePath || getSystemCodexHomePath(), 'sessions')
if (!existsSync(systemSessionsRoot)) {
return { scannedFiles: 0, linkedFiles: 0 }
}
@@ -0,0 +1,72 @@
import { describe, expect, it } from 'vitest'
import {
resolveHostCodexSessionSourceHome,
resolveWslCodexSessionSourceHome
} from './codex-session-source-home'
describe('resolveHostCodexSessionSourceHome', () => {
it('returns undefined when no override is configured', () => {
expect(resolveHostCodexSessionSourceHome({})).toBeUndefined()
expect(resolveHostCodexSessionSourceHome({ codexSessionSourceHome: {} })).toBeUndefined()
})
it('returns undefined for blank/whitespace overrides so the default is kept', () => {
expect(
resolveHostCodexSessionSourceHome({ codexSessionSourceHome: { host: ' ' } })
).toBeUndefined()
})
it('returns the trimmed host override path', () => {
expect(
resolveHostCodexSessionSourceHome({ codexSessionSourceHome: { host: ' /custom/codex ' } })
).toBe('/custom/codex')
})
})
describe('resolveWslCodexSessionSourceHome', () => {
it('returns undefined when no per-distro override exists', () => {
expect(resolveWslCodexSessionSourceHome({}, 'Ubuntu')).toBeUndefined()
expect(
resolveWslCodexSessionSourceHome(
{ codexSessionSourceHome: { wsl: { Debian: '/home/me/.codex' } } },
'Ubuntu'
)
).toBeUndefined()
})
it('resolves a per-distro override for the matching distro', () => {
expect(
resolveWslCodexSessionSourceHome(
{ codexSessionSourceHome: { wsl: { Ubuntu: '/home/me/.config/codex' } } },
'Ubuntu'
)
).toBe('/home/me/.config/codex')
})
it('matches distro names case-insensitively, mirroring WSL', () => {
expect(
resolveWslCodexSessionSourceHome(
{ codexSessionSourceHome: { wsl: { Ubuntu: '/home/me/.config/codex' } } },
'ubuntu'
)
).toBe('/home/me/.config/codex')
})
it('ignores blank per-distro overrides so the default is kept', () => {
expect(
resolveWslCodexSessionSourceHome(
{ codexSessionSourceHome: { wsl: { Ubuntu: ' ' } } },
'Ubuntu'
)
).toBeUndefined()
})
it('does not leak the host override into WSL resolution', () => {
expect(
resolveWslCodexSessionSourceHome(
{ codexSessionSourceHome: { host: '/custom/codex' } },
'Ubuntu'
)
).toBeUndefined()
})
})
@@ -0,0 +1,43 @@
import type { GlobalSettings } from '../../shared/types'
/**
* Resolves the user-configured Codex *session history* source home, if any.
*
* Why: Orca relocates CODEX_HOME to a managed home, then bridges history from
* the user's real Codex home so /resume finds it. That source defaults to
* ~/.codex, but users who run Codex with a custom CODEX_HOME need to point
* history discovery at that folder. This override affects history only; auth,
* config, and hooks continue to read from ~/.codex.
*/
/** Host override; returns undefined to keep the default ~/.codex source. */
export function resolveHostCodexSessionSourceHome(
settings: Pick<GlobalSettings, 'codexSessionSourceHome'>
): string | undefined {
return normalizeSourceHome(settings.codexSessionSourceHome?.host)
}
/** Per-distro WSL override; returns undefined to keep the default <wslHome>/.codex source. */
export function resolveWslCodexSessionSourceHome(
settings: Pick<GlobalSettings, 'codexSessionSourceHome'>,
distro: string
): string | undefined {
const perDistro = settings.codexSessionSourceHome?.wsl
if (!perDistro) {
return undefined
}
// Why: distro keys are matched case-insensitively so "Ubuntu" and "ubuntu"
// resolve the same override, mirroring how WSL treats distro names.
const normalizedDistro = distro.trim().toLowerCase()
for (const [key, value] of Object.entries(perDistro)) {
if (key.trim().toLowerCase() === normalizedDistro) {
return normalizeSourceHome(value)
}
}
return undefined
}
function normalizeSourceHome(value: string | undefined): string | undefined {
const trimmed = value?.trim()
return trimmed ? trimmed : undefined
}
+10 -6
View File
@@ -122,7 +122,7 @@ import {
_resetMergeQueueCacheForTests,
__resetTrackedUpstreamBranchCacheForTests
} from './client'
import { __resetPRConflictSummaryGitCapabilityCacheForTests } from './conflict-summary'
import { __resetPRConflictSummaryCachesForTests } from './conflict-summary'
import { resetMergedPRCommitMembershipCacheForTest } from './merged-pr-commit-membership'
describe('checkOrcaStarred', () => {
@@ -194,7 +194,7 @@ describe('getPRForBranch', () => {
_resetOwnerRepoCache()
_resetMergeQueueCacheForTests()
__resetTrackedUpstreamBranchCacheForTests()
__resetPRConflictSummaryGitCapabilityCacheForTests()
__resetPRConflictSummaryCachesForTests()
resetMergedPRCommitMembershipCacheForTest()
})
@@ -2987,11 +2987,16 @@ describe('getPRForBranch', () => {
baseRefOid: 'base-oid',
headRefOid: 'head-oid'
}
// Why a second head OID: identical inputs now hit the summary result
// cache outright; a pushed head re-derives and must still skip the
// unsupported --merge-base retry via the capability cache.
const pushedBranchLookup = { ...branchLookup, head: { ref: 'feature/test', sha: 'head-oid-2' } }
const pushedExactLookup = { ...exactLookup, headRefOid: 'head-oid-2' }
ghExecFileAsyncMock
.mockResolvedValueOnce({ stdout: JSON.stringify([branchLookup]) })
.mockResolvedValueOnce({ stdout: JSON.stringify(exactLookup) })
.mockResolvedValueOnce({ stdout: JSON.stringify([branchLookup]) })
.mockResolvedValueOnce({ stdout: JSON.stringify(exactLookup) })
.mockResolvedValueOnce({ stdout: JSON.stringify([pushedBranchLookup]) })
.mockResolvedValueOnce({ stdout: JSON.stringify(pushedExactLookup) })
gitExecFileAsyncMock
.mockResolvedValueOnce({ stdout: '' })
.mockResolvedValueOnce({ stdout: 'latest-base-oid\n' })
@@ -2999,8 +3004,6 @@ describe('getPRForBranch', () => {
.mockResolvedValueOnce({ stdout: '2\n' })
.mockRejectedValueOnce({ stderr: "error: unknown option `merge-base'" })
.mockRejectedValueOnce({ stdout: 'result-tree-oid\u0000src/conflict.ts\u0000' })
.mockResolvedValueOnce({ stdout: '' })
.mockResolvedValueOnce({ stdout: 'latest-base-oid\n' })
.mockResolvedValueOnce({ stdout: 'merge-base-oid\n' })
.mockResolvedValueOnce({ stdout: '2\n' })
.mockRejectedValueOnce({ stdout: 'result-tree-oid\u0000src/conflict.ts\u0000' })
@@ -3567,6 +3570,7 @@ describe('GitHub GraphQL rate-limit guard', () => {
acquireMock.mockResolvedValue(undefined)
_resetOwnerRepoCache()
_resetMergeQueueCacheForTests()
__resetPRConflictSummaryCachesForTests()
})
it('skips PR review-thread GraphQL fetch while preserving REST comments', async () => {
+150
View File
@@ -0,0 +1,150 @@
import type { PRConflictSummary } from '../../shared/types'
// Why 60s: the hottest coordinator cadences that re-derive a CONFLICTING PR
// (10s mergeability-pending, 2.5s manual-pending) previously each ran a
// network fetch; one fetch per base branch per minute matches the 60s minimum
// background refresh cadence, so the tracked base tip is never staler than the
// PR data around it. Manual refresh intentionally shares the window: GitHub's
// own mergeability recompute is async too, and the card self-corrects within
// a minute.
export const CONFLICT_SUMMARY_BASE_FETCH_WINDOW_MS = 60_000
// Why bounded: the main process is long-lived; cap the maps so repos and PRs
// that stop refreshing can't accumulate entries forever.
const BASE_OID_CACHE_MAX = 64
const SUMMARY_CACHE_MAX = 128
export type FreshBaseTipResolution =
| { kind: 'resolved'; oid: string }
| { kind: 'fallback-unresolved' }
type CachedBaseTipResolution = {
oid: string | null
resolvedAt: number
}
type CachedSummary = {
value: PRConflictSummary | undefined
// Why: a successful summary is a pure function of two immutable commit OIDs
// and never goes stale; a failed derivation depends on which objects exist
// locally, which the next fetch window can change, so it carries an expiry.
staleAt: number | null
}
const baseOidCache = new Map<string, CachedBaseTipResolution>()
const summaryCache = new Map<string, CachedSummary>()
const inFlightBaseOidResolves = new Map<string, Promise<FreshBaseTipResolution>>()
const inFlightSummaryDerivations = new Map<string, Promise<PRConflictSummary | undefined>>()
// Why: WSL distros have their own git binary, filesystem view, and remote
// access, so cached state must never leak across the host/distro boundary.
export function getConflictSummaryGitRuntimeKey(wslDistro: string | undefined): string {
return wslDistro ? `wsl:${wslDistro}` : 'local:host'
}
// Why JSON: repo paths and git ref names may contain any printable joiner
// character (git allows `|` in branch names), so a delimiter-joined key could
// alias distinct identities onto one cache entry.
export function buildConflictSummaryCacheKey(...parts: string[]): string {
return JSON.stringify(parts)
}
export function readFreshBaseTipResolution(baseKey: string): FreshBaseTipResolution | null {
const entry = baseOidCache.get(baseKey)
if (!entry) {
return null
}
if (Date.now() - entry.resolvedAt >= CONFLICT_SUMMARY_BASE_FETCH_WINDOW_MS) {
baseOidCache.delete(baseKey)
return null
}
return entry.oid ? { kind: 'resolved', oid: entry.oid } : { kind: 'fallback-unresolved' }
}
export function storeResolvedBaseTip(baseKey: string, oid: string): void {
setBoundedMapEntry(baseOidCache, baseKey, { oid, resolvedAt: Date.now() }, BASE_OID_CACHE_MAX)
}
export function rememberUnresolvedBaseTip(baseKey: string): void {
setBoundedMapEntry(
baseOidCache,
baseKey,
{ oid: null, resolvedAt: Date.now() },
BASE_OID_CACHE_MAX
)
}
export function readCachedSummary(summaryKey: string): CachedSummary | null {
const entry = summaryCache.get(summaryKey)
if (!entry) {
return null
}
if (entry.staleAt !== null && Date.now() >= entry.staleAt) {
summaryCache.delete(summaryKey)
return null
}
return entry
}
export function storeCachedSummary(summaryKey: string, value: PRConflictSummary | undefined): void {
setBoundedMapEntry(
summaryCache,
summaryKey,
{
value,
staleAt: value === undefined ? Date.now() + CONFLICT_SUMMARY_BASE_FETCH_WINDOW_MS : null
},
SUMMARY_CACHE_MAX
)
}
export function dedupeBaseOidResolve(
key: string,
factory: () => Promise<FreshBaseTipResolution>
): Promise<FreshBaseTipResolution> {
return dedupeInFlight(inFlightBaseOidResolves, key, factory)
}
export function dedupeSummaryDerivation(
key: string,
factory: () => Promise<PRConflictSummary | undefined>
): Promise<PRConflictSummary | undefined> {
return dedupeInFlight(inFlightSummaryDerivations, key, factory)
}
function dedupeInFlight<T>(
map: Map<string, Promise<T>>,
key: string,
factory: () => Promise<T>
): Promise<T> {
const existing = map.get(key)
if (existing) {
return existing
}
const promise = factory().finally(() => {
map.delete(key)
})
map.set(key, promise)
return promise
}
function setBoundedMapEntry<K, V>(map: Map<K, V>, key: K, value: V, maxEntries: number): void {
if (map.has(key)) {
map.delete(key)
}
map.set(key, value)
while (map.size > maxEntries) {
const oldest = map.keys().next()
if (oldest.done) {
return
}
map.delete(oldest.value)
}
}
export function __resetPRConflictSummaryDerivationCachesForTests(): void {
baseOidCache.clear()
summaryCache.clear()
inFlightBaseOidResolves.clear()
inFlightSummaryDerivations.clear()
}
+331
View File
@@ -0,0 +1,331 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
// Why these tests exist: the conflict-summary derivation used to re-run a
// network `git fetch` plus a four-subprocess chain on every PR refresh tick
// (measured ~490 full derivations in 2.1h on one machine). They pin the
// regression contract by counting subprocess spawns: unchanged inputs must
// cost zero subprocesses, and the base fetch must run at most once per
// throttle window.
const gitExecFileAsyncMock = vi.hoisted(() => vi.fn())
vi.mock('../git/runner', () => ({ gitExecFileAsync: gitExecFileAsyncMock }))
import { CONFLICT_SUMMARY_BASE_FETCH_WINDOW_MS } from './conflict-summary-cache'
import { __resetPRConflictSummaryCachesForTests, getPRConflictSummary } from './conflict-summary'
type GitResult = { stdout: string }
type GitHandler = (argv: string[]) => Promise<GitResult>
const defaultHandlers: Record<string, GitHandler> = {
fetch: async () => ({ stdout: '' }),
'rev-parse': async () => ({ stdout: 'base-tip-1\n' }),
'merge-base': async () => ({ stdout: 'merge-base-1\n' }),
'rev-list': async () => ({ stdout: '3\n' }),
'merge-tree': async () => ({ stdout: 'tree-oid\u0000src/conflict.ts\u0000' })
}
function mockGitDispatch(overrides: Record<string, GitHandler> = {}): void {
gitExecFileAsyncMock.mockImplementation((argv: string[]) => {
const handler = overrides[argv[0]] ?? defaultHandlers[argv[0]]
if (!handler) {
return Promise.reject(new Error(`unexpected git command: ${argv.join(' ')}`))
}
return handler(argv)
})
}
function spawnCount(command?: string): number {
const calls = gitExecFileAsyncMock.mock.calls
if (!command) {
return calls.length
}
return calls.filter(([argv]) => Array.isArray(argv) && argv[0] === command).length
}
const expectedSummary = {
baseRef: 'main',
baseCommit: 'base-ti',
commitsBehind: 3,
files: ['src/conflict.ts']
}
function deriveSummary(headRefOid = 'head-oid-1', wslDistro?: string) {
return getPRConflictSummary(
'/repo-root',
'main',
'github-base-oid',
headRefOid,
wslDistro ? { wslDistro } : {}
)
}
describe('getPRConflictSummary caching', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(1_750_000_000_000)
gitExecFileAsyncMock.mockReset()
__resetPRConflictSummaryCachesForTests()
})
afterEach(() => {
vi.useRealTimers()
})
it('runs exactly one fetch and one derivation chain, then zero subprocesses on repeat calls', async () => {
mockGitDispatch()
const first = await deriveSummary()
expect(first).toEqual(expectedSummary)
expect(spawnCount('fetch')).toBe(1)
expect(spawnCount()).toBe(5)
const second = await deriveSummary()
const third = await deriveSummary()
expect(second).toEqual(expectedSummary)
expect(third).toEqual(expectedSummary)
expect(spawnCount()).toBe(5)
})
it('re-derives when headRefOid changes without re-fetching inside the throttle window', async () => {
mockGitDispatch()
await deriveSummary('head-oid-1')
const afterPush = await deriveSummary('head-oid-2')
expect(afterPush).toEqual(expectedSummary)
expect(spawnCount('fetch')).toBe(1)
expect(spawnCount('rev-parse')).toBe(1)
expect(spawnCount('merge-base')).toBe(2)
expect(spawnCount('rev-list')).toBe(2)
expect(spawnCount('merge-tree')).toBe(2)
})
it('fetches again after the throttle window and skips derivation when the base tip is unchanged', async () => {
mockGitDispatch()
await deriveSummary()
vi.setSystemTime(1_750_000_000_000 + CONFLICT_SUMMARY_BASE_FETCH_WINDOW_MS + 1_000)
const afterExpiry = await deriveSummary()
expect(afterExpiry).toEqual(expectedSummary)
expect(spawnCount('fetch')).toBe(2)
expect(spawnCount('rev-parse')).toBe(2)
// Why: same (headRefOid, latestBaseOid) pair — the summary cache still hits.
expect(spawnCount('merge-base')).toBe(1)
expect(spawnCount('rev-list')).toBe(1)
expect(spawnCount('merge-tree')).toBe(1)
})
it('re-derives after the throttle window when the base tip moved', async () => {
mockGitDispatch()
await deriveSummary()
vi.setSystemTime(1_750_000_000_000 + CONFLICT_SUMMARY_BASE_FETCH_WINDOW_MS + 1_000)
mockGitDispatch({
'rev-parse': async () => ({ stdout: 'base-tip-2\n' }),
'rev-list': async () => ({ stdout: '5\n' })
})
const afterBaseMove = await deriveSummary()
expect(afterBaseMove).toEqual({ ...expectedSummary, baseCommit: 'base-ti', commitsBehind: 5 })
expect(spawnCount('fetch')).toBe(2)
expect(spawnCount('merge-base')).toBe(2)
expect(spawnCount('rev-list')).toBe(2)
expect(spawnCount('merge-tree')).toBe(2)
})
it('dedupes concurrent identical calls onto one in-flight subprocess chain', async () => {
let releaseFetch: ((value: GitResult) => void) | undefined
mockGitDispatch({
fetch: () =>
new Promise<GitResult>((resolve) => {
releaseFetch = resolve
})
})
const firstCall = deriveSummary()
const secondCall = deriveSummary()
releaseFetch?.({ stdout: '' })
const [first, second] = await Promise.all([firstCall, secondCall])
expect(first).toEqual(expectedSummary)
expect(second).toEqual(expectedSummary)
expect(spawnCount()).toBe(5)
})
it('dedupes overlapping derivations after resolving the same live base tip', async () => {
let releaseFetch: ((value: GitResult) => void) | undefined
mockGitDispatch({
fetch: () =>
new Promise<GitResult>((resolve) => {
releaseFetch = resolve
})
})
const backgroundRefresh = getPRConflictSummary(
'/repo-root',
'main',
'older-github-base-oid',
'head-oid-1',
{}
)
const manualRefresh = getPRConflictSummary(
'/repo-root',
'main',
'newer-github-base-oid',
'head-oid-1',
{}
)
releaseFetch?.({ stdout: '' })
const [backgroundSummary, manualSummary] = await Promise.all([backgroundRefresh, manualRefresh])
expect(backgroundSummary).toEqual(expectedSummary)
expect(manualSummary).toEqual(expectedSummary)
expect(spawnCount('fetch')).toBe(1)
expect(spawnCount('rev-parse')).toBe(1)
expect(spawnCount('merge-base')).toBe(1)
expect(spawnCount('rev-list')).toBe(1)
expect(spawnCount('merge-tree')).toBe(1)
})
it('shares one base fetch across concurrent PRs on the same base branch', async () => {
let releaseFetch: ((value: GitResult) => void) | undefined
mockGitDispatch({
fetch: () =>
new Promise<GitResult>((resolve) => {
releaseFetch = resolve
})
})
const prA = deriveSummary('head-oid-a')
const prB = deriveSummary('head-oid-b')
releaseFetch?.({ stdout: '' })
const [summaryA, summaryB] = await Promise.all([prA, prB])
expect(summaryA).toEqual(expectedSummary)
expect(summaryB).toEqual(expectedSummary)
expect(spawnCount('fetch')).toBe(1)
expect(spawnCount('rev-parse')).toBe(1)
expect(spawnCount('merge-base')).toBe(2)
})
it('keeps concurrent fallback base OIDs isolated per PR when the base ref is unavailable', async () => {
let releaseFetch: ((value: GitResult) => void) | undefined
mockGitDispatch({
fetch: () =>
new Promise<GitResult>((resolve) => {
releaseFetch = resolve
}),
'rev-parse': () => Promise.reject(new Error('missing remote-tracking ref')),
'rev-list': async (argv) => ({
stdout: argv[2]?.includes('bbbb2222-base') ? '7\n' : '4\n'
}),
'merge-tree': async (argv) => ({
stdout: argv.includes('bbbb2222-base')
? 'tree-oid\u0000src/b.ts\u0000'
: 'tree-oid\u0000src/a.ts\u0000'
})
})
const prA = getPRConflictSummary('/repo-root', 'main', 'aaaa1111-base', 'head-oid-a', {})
const prB = getPRConflictSummary('/repo-root', 'main', 'bbbb2222-base', 'head-oid-b', {})
releaseFetch?.({ stdout: '' })
const [summaryA, summaryB] = await Promise.all([prA, prB])
expect(summaryA).toEqual({
baseRef: 'main',
baseCommit: 'aaaa111',
commitsBehind: 4,
files: ['src/a.ts']
})
expect(summaryB).toEqual({
baseRef: 'main',
baseCommit: 'bbbb222',
commitsBehind: 7,
files: ['src/b.ts']
})
expect(spawnCount('fetch')).toBe(1)
expect(spawnCount('merge-base')).toBe(2)
})
it('falls back to the local remote-tracking ref when fetch fails', async () => {
mockGitDispatch({
fetch: () => Promise.reject(new Error('offline'))
})
const summary = await deriveSummary()
expect(summary).toEqual(expectedSummary)
expect(spawnCount('fetch')).toBe(1)
// Why: a failed fetch attempt must also be throttled — offline machines
// were the worst case, paying the 10s fetch timeout on every tick.
const repeat = await deriveSummary()
expect(repeat).toEqual(expectedSummary)
expect(spawnCount('fetch')).toBe(1)
expect(spawnCount()).toBe(5)
})
it("falls back to GitHub's baseRefOid when fetch and remote-tracking refs are unavailable", async () => {
mockGitDispatch({
fetch: () => Promise.reject(new Error('offline')),
'rev-parse': () => Promise.reject(new Error('unknown revision'))
})
const summary = await deriveSummary()
expect(summary).toEqual({ ...expectedSummary, baseCommit: 'github-' })
expect(
gitExecFileAsyncMock.mock.calls.some(
([argv]) => argv[0] === 'merge-base' && argv.includes('github-base-oid')
)
).toBe(true)
})
it('keeps WSL-distro derivations isolated from host derivations', async () => {
mockGitDispatch()
await deriveSummary()
await deriveSummary('head-oid-1', 'Ubuntu')
expect(spawnCount('fetch')).toBe(2)
expect(
gitExecFileAsyncMock.mock.calls.filter(
([argv, options]) =>
argv[0] === 'fetch' && (options as { wslDistro?: string })?.wslDistro === 'Ubuntu'
)
).toHaveLength(1)
})
it('keeps identities distinct when paths or ref names contain a joiner character', async () => {
mockGitDispatch()
// Why: these two calls alias under naive pipe-joined keys — the segment
// boundary shifts between repoPath and baseRefName.
await getPRConflictSummary('/repo|x', 'main', 'github-base-oid', 'head-oid-1', {})
await getPRConflictSummary('/repo', 'x|main', 'github-base-oid', 'head-oid-1', {})
expect(spawnCount('fetch')).toBe(2)
expect(spawnCount('merge-base')).toBe(2)
})
it('caches failed derivations only until the throttle window expires', async () => {
mockGitDispatch({
'merge-base': () => Promise.reject(new Error('bad object'))
})
await expect(deriveSummary()).resolves.toBeUndefined()
const failureSpawns = spawnCount()
// Within the window the failure is negative-cached: zero subprocesses.
await expect(deriveSummary()).resolves.toBeUndefined()
expect(spawnCount()).toBe(failureSpawns)
// After expiry the derivation retries (a fetch may have brought objects in).
vi.setSystemTime(1_750_000_000_000 + CONFLICT_SUMMARY_BASE_FETCH_WINDOW_MS + 1_000)
mockGitDispatch()
await expect(deriveSummary()).resolves.toEqual(expectedSummary)
expect(spawnCount('merge-base')).toBe(2)
})
})
+106 -20
View File
@@ -1,5 +1,17 @@
import type { PRConflictSummary } from '../../shared/types'
import { gitExecFileAsync } from '../git/runner'
import {
__resetPRConflictSummaryDerivationCachesForTests,
buildConflictSummaryCacheKey,
dedupeBaseOidResolve,
dedupeSummaryDerivation,
getConflictSummaryGitRuntimeKey,
readCachedSummary,
readFreshBaseTipResolution,
rememberUnresolvedBaseTip,
storeResolvedBaseTip,
storeCachedSummary
} from './conflict-summary-cache'
type LocalGitExecOptions = {
wslDistro?: string
@@ -7,8 +19,9 @@ type LocalGitExecOptions = {
const mergeTreeMergeBaseUnsupportedRuntimes = new Set<string>()
export function __resetPRConflictSummaryGitCapabilityCacheForTests(): void {
export function __resetPRConflictSummaryCachesForTests(): void {
mergeTreeMergeBaseUnsupportedRuntimes.clear()
__resetPRConflictSummaryDerivationCachesForTests()
}
export async function getPRConflictSummary(
@@ -18,45 +31,122 @@ export async function getPRConflictSummary(
headRefOid: string,
localGitOptions: LocalGitExecOptions = {}
): Promise<PRConflictSummary | undefined> {
try {
// Why: the renderer only needs a read-only merge-conflict snapshot. We
// derive it from local git state so the PR card can show GitHub-style
// detail without spending additional gh API calls on every refresh. We use
// GitHub's head OID directly because the registered repo path may not have
// a matching local branch name for the PR head. For the base side, prefer a
// freshly-fetched remote-tracking ref so Orca matches GitHub's portal,
// which compares against the latest base branch tip rather than the PR's
// older pinned baseRefOid snapshot.
const latestBaseOid = await resolveLatestBaseOid(
// Why: the renderer only needs a read-only merge-conflict snapshot. We
// derive it from local git state so the PR card can show GitHub-style
// detail without spending additional gh API calls on every refresh. We use
// GitHub's head OID directly because the registered repo path may not have
// a matching local branch name for the PR head. For the base side, prefer a
// freshly-fetched remote-tracking ref so Orca matches GitHub's portal,
// which compares against the latest base branch tip rather than the PR's
// older pinned baseRefOid snapshot.
const latestBaseOid = await resolveLatestBaseOidThrottled(
repoPath,
baseRefName,
baseRefOid,
localGitOptions
)
// Why: the summary is a pure function of the two commit OIDs, so a key hit
// can skip the whole merge-base/rev-list/merge-tree subprocess chain.
const runtimeKey = getConflictSummaryGitRuntimeKey(localGitOptions.wslDistro)
const summaryKey = buildConflictSummaryCacheKey(
runtimeKey,
repoPath,
baseRefName,
headRefOid,
latestBaseOid
)
const cached = readCachedSummary(summaryKey)
if (cached) {
return cached.value
}
// Why: different GitHub reads can report different pinned baseRefOid values
// while still resolving to the same live base tip; dedupe the expensive
// local derivation on the actual summary identity.
return dedupeSummaryDerivation(summaryKey, () =>
derivePRConflictSummary(
repoPath,
baseRefName,
baseRefOid,
headRefOid,
latestBaseOid,
summaryKey,
localGitOptions
)
)
}
async function derivePRConflictSummary(
repoPath: string,
baseRefName: string,
headRefOid: string,
latestBaseOid: string,
summaryKey: string,
localGitOptions: LocalGitExecOptions
): Promise<PRConflictSummary | undefined> {
const cached = readCachedSummary(summaryKey)
if (cached) {
return cached.value
}
try {
const mergeBase = await resolveMergeBase(repoPath, headRefOid, latestBaseOid, localGitOptions)
const [commitsBehind, files] = await Promise.all([
countCommits(repoPath, `${headRefOid}..${latestBaseOid}`, localGitOptions),
loadConflictingFiles(repoPath, mergeBase, headRefOid, latestBaseOid, localGitOptions)
])
return {
const summary = {
baseRef: baseRefName,
baseCommit: latestBaseOid.slice(0, 7),
commitsBehind,
files,
...(files.length === 0 ? { localMergeState: 'clean' as const } : {})
}
storeCachedSummary(summaryKey, summary)
return summary
} catch {
storeCachedSummary(summaryKey, undefined)
return undefined
}
}
async function resolveLatestBaseOid(
async function resolveLatestBaseOidThrottled(
repoPath: string,
baseRefName: string,
fallbackBaseOid: string,
localGitOptions: LocalGitExecOptions
): Promise<string> {
const runtimeKey = getConflictSummaryGitRuntimeKey(localGitOptions.wslDistro)
const baseKey = buildConflictSummaryCacheKey(runtimeKey, repoPath, baseRefName)
const cachedResolution = readFreshBaseTipResolution(baseKey)
if (cachedResolution) {
return cachedResolution.kind === 'resolved' ? cachedResolution.oid : fallbackBaseOid
}
return dedupeBaseOidResolve(baseKey, async () => {
// Why re-check inside the dedupe slot: a sibling caller may have finished
// resolving between our cache read and this factory starting.
const freshResolution = readFreshBaseTipResolution(baseKey)
if (freshResolution) {
return freshResolution
}
const oid = await resolveLatestBaseOid(repoPath, baseRefName, localGitOptions)
if (oid) {
storeResolvedBaseTip(baseKey, oid)
return { kind: 'resolved', oid }
}
// Why cache the unresolved probe, not the caller fallback: the fetch
// attempt is branch-wide expensive work, but GitHub's baseRefOid is
// PR-specific and must not leak to sibling PRs on the same base branch.
rememberUnresolvedBaseTip(baseKey)
return { kind: 'fallback-unresolved' }
}).then((resolution) => (resolution.kind === 'resolved' ? resolution.oid : fallbackBaseOid))
}
async function resolveLatestBaseOid(
repoPath: string,
baseRefName: string,
localGitOptions: LocalGitExecOptions
): Promise<string | null> {
const remoteName = 'origin'
try {
@@ -88,7 +178,7 @@ async function resolveLatestBaseOid(
}
}
return fallbackBaseOid
return null
}
async function resolveMergeBase(
@@ -123,7 +213,7 @@ async function loadConflictingFiles(
baseOid: string,
localGitOptions: LocalGitExecOptions
): Promise<string[]> {
const capabilityKey = getMergeTreeCapabilityKey(localGitOptions)
const capabilityKey = getConflictSummaryGitRuntimeKey(localGitOptions.wslDistro)
const modernArgs = [
'merge-tree',
'--write-tree',
@@ -193,10 +283,6 @@ async function loadConflictingFilesWithLegacyMergeTree(
}
}
function getMergeTreeCapabilityKey(localGitOptions: LocalGitExecOptions): string {
return localGitOptions.wslDistro ? `wsl:${localGitOptions.wslDistro}` : 'local:host'
}
function parseMergeTreeNameOnlyOutput(stdout: string): string[] {
const entries = stdout.split('\0').filter(Boolean)
if (entries.length === 0) {
+53 -14
View File
@@ -3,14 +3,19 @@ request timestamps, and follow-up scheduling against shared module state. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { GitHubPRRefreshCandidate, PRInfo } from '../../shared/types'
const { sendMock, getAllWebContentsMock, getPRForBranchOutcomeMock, getRateLimitMock } = vi.hoisted(
() => ({
sendMock: vi.fn(),
getAllWebContentsMock: vi.fn(),
getPRForBranchOutcomeMock: vi.fn(),
getRateLimitMock: vi.fn()
})
)
const {
sendMock,
getAllWebContentsMock,
getPRForBranchOutcomeMock,
getRateLimitMock,
rateLimitGuardMock
} = vi.hoisted(() => ({
sendMock: vi.fn(),
getAllWebContentsMock: vi.fn(),
getPRForBranchOutcomeMock: vi.fn(),
getRateLimitMock: vi.fn(),
rateLimitGuardMock: vi.fn()
}))
vi.mock('electron', () => ({
webContents: {
@@ -25,7 +30,7 @@ vi.mock('./client', () => ({
vi.mock('./rate-limit', () => ({
getRateLimit: getRateLimitMock,
noteRateLimitSpend: vi.fn(),
rateLimitGuard: vi.fn(() => ({ blocked: false }))
rateLimitGuard: rateLimitGuardMock
}))
function makeCandidate(
@@ -80,6 +85,8 @@ describe('pr-refresh-coordinator', () => {
getAllWebContentsMock.mockReset()
getPRForBranchOutcomeMock.mockReset()
getRateLimitMock.mockReset()
rateLimitGuardMock.mockReset()
rateLimitGuardMock.mockReturnValue({ blocked: false })
getAllWebContentsMock.mockReturnValue([
{
id: 1,
@@ -505,13 +512,45 @@ describe('pr-refresh-coordinator', () => {
expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(5)
})
it('proceeds with background refreshes when the budget probe fails (fail open)', async () => {
const { enqueuePRRefresh } = await import('./pr-refresh-coordinator')
// Why: regression for #7553 — GHES with rate limiting disabled 404s every
// probe; an unreadable budget must not pause refreshes.
getRateLimitMock.mockResolvedValue({
ok: false,
error: 'HTTP 404: Rate limiting is not enabled.'
})
getPRForBranchOutcomeMock.mockResolvedValue({
kind: 'no-pr',
fetchedAt: Date.now()
})
enqueuePRRefresh(makeCandidate(), 'active', 80, 1)
await vi.advanceTimersByTimeAsync(0)
expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1)
const pausedEvents = sendMock.mock.calls
.map(([, event]) => event)
.filter((event) => event.status === 'paused' && event.skippedReason === 'rate-limit')
expect(pausedEvents).toHaveLength(0)
})
it('does not consume active burst slots for rate-limit pauses', async () => {
const { enqueuePRRefresh } = await import('./pr-refresh-coordinator')
getRateLimitMock
.mockResolvedValueOnce({ ok: false })
.mockResolvedValueOnce({ ok: false })
.mockResolvedValueOnce({ ok: false })
.mockResolvedValue({ ok: true })
// Why: keyed on drained items (one getRateLimit call each) rather than
// guard-call counts, so the guard's per-bucket evaluation order stays free
// to change without breaking the slot-accounting assertion.
let drainedItems = 0
getRateLimitMock.mockImplementation(async () => {
drainedItems += 1
return { ok: true }
})
rateLimitGuardMock.mockImplementation(() =>
drainedItems <= 3
? { blocked: true, remaining: 0, limit: 5000, resetAt: 61 }
: { blocked: false }
)
getPRForBranchOutcomeMock.mockResolvedValue({
kind: 'upstream-error',
errorType: 'unknown',
+5 -14
View File
@@ -708,20 +708,11 @@ async function drainQueue(): Promise<void> {
)
if (isBackground(next.reason)) {
const rateLimit = await getRateLimit()
if (!rateLimit.ok) {
const retryAt = Date.now() + 30_000
queue.set(next.key, { ...next, dueAt: retryAt })
broadcast({
aliases,
reason: next.reason,
status: 'paused',
pausedUntil: retryAt,
skippedReason: 'rate-limit'
})
scheduleDrain(30_000)
continue
}
// Why: the probe only warms rateLimitGuard's cached snapshot, so a
// failed probe must fail open — GHES with rate limiting disabled 404s
// every probe (#7553). A genuinely broken gh surfaces per-key as typed
// fetch outcomes instead (visible keys additionally back off).
await getRateLimit()
const buckets = backgroundRefreshBuckets()
const blockedGuard = buckets
.map((bucket) => rateLimitGuard(bucket))
+138
View File
@@ -0,0 +1,138 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const { ghExecFileAsyncMock } = vi.hoisted(() => ({
ghExecFileAsyncMock: vi.fn()
}))
vi.mock('../git/runner', () => ({
ghExecFileAsync: ghExecFileAsyncMock
}))
vi.mock('./gh-utils', () => ({
acquire: vi.fn(),
release: vi.fn()
}))
import { getRateLimit, rateLimitGuard, _resetRateLimitCache } from './rate-limit'
const PAYLOAD = JSON.stringify({
resources: {
core: { limit: 5000, remaining: 4200, reset: 1_700_000_000 },
search: { limit: 30, remaining: 28, reset: 1_700_000_000 },
graphql: { limit: 5000, remaining: 4900, reset: 1_700_000_000 }
}
})
describe('getRateLimit', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(1_000)
ghExecFileAsyncMock.mockReset()
_resetRateLimitCache()
})
afterEach(() => {
vi.useRealTimers()
})
it('parses bucket counts from gh api rate_limit', async () => {
ghExecFileAsyncMock.mockResolvedValue({ stdout: PAYLOAD })
const result = await getRateLimit()
expect(result).toEqual({
ok: true,
snapshot: {
core: { limit: 5000, remaining: 4200, resetAt: 1_700_000_000 },
search: { limit: 30, remaining: 28, resetAt: 1_700_000_000 },
graphql: { limit: 5000, remaining: 4900, resetAt: 1_700_000_000 },
fetchedAt: 1_000
}
})
})
it('caches a failed probe for the TTL instead of re-spawning gh', async () => {
// Why: regression for #7553 — GHES with rate limiting disabled fails every
// probe. Refreshes fail open past the failure, so without a negative cache
// each queued refresh would spawn its own doomed gh subprocess.
ghExecFileAsyncMock.mockRejectedValue(new Error('HTTP 404: Rate limiting is not enabled.'))
const first = await getRateLimit()
const second = await getRateLimit()
expect(first).toEqual({ ok: false, error: 'HTTP 404: Rate limiting is not enabled.' })
expect(second).toEqual(first)
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1)
})
it('re-probes after the failure TTL elapses and recovers on success', async () => {
ghExecFileAsyncMock.mockRejectedValueOnce(new Error('boom'))
ghExecFileAsyncMock.mockResolvedValue({ stdout: PAYLOAD })
expect((await getRateLimit()).ok).toBe(false)
expect((await getRateLimit()).ok).toBe(false)
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1)
vi.setSystemTime(1_000 + 30_000)
expect((await getRateLimit()).ok).toBe(true)
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2)
})
it('bypasses the failure cache when forced', async () => {
ghExecFileAsyncMock.mockRejectedValueOnce(new Error('boom'))
ghExecFileAsyncMock.mockResolvedValue({ stdout: PAYLOAD })
expect((await getRateLimit()).ok).toBe(false)
expect((await getRateLimit({ force: true })).ok).toBe(true)
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2)
})
})
describe('rateLimitGuard', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(1_000)
ghExecFileAsyncMock.mockReset()
_resetRateLimitCache()
})
afterEach(() => {
vi.useRealTimers()
})
async function cacheExhaustedSnapshot(resetEpochSeconds: number): Promise<void> {
ghExecFileAsyncMock.mockResolvedValueOnce({
stdout: JSON.stringify({
resources: {
core: { limit: 5000, remaining: 3, reset: resetEpochSeconds },
search: { limit: 30, remaining: 28, reset: resetEpochSeconds },
graphql: { limit: 5000, remaining: 4900, reset: resetEpochSeconds }
}
})
})
expect((await getRateLimit()).ok).toBe(true)
}
it('blocks below the floor while resetAt is in the future', async () => {
await cacheExhaustedSnapshot(61)
expect(rateLimitGuard('core')).toEqual({
blocked: true,
remaining: 3,
limit: 5000,
resetAt: 61
})
})
it('fails open once the blocking bucket resetAt has elapsed', async () => {
// Why: probes can fail indefinitely (sleep past resetAt, network blip), so
// a stale exhausted snapshot must not block once GitHub has already reset
// the budget — a past-due pause would spin the coordinator drain loop.
await cacheExhaustedSnapshot(61)
vi.setSystemTime(61_000)
expect(rateLimitGuard('core')).toEqual({ blocked: false })
})
})
+11
View File
@@ -35,6 +35,11 @@ import {
// 1-per-second "is it safe now?" polling pattern UIs tend to fall into.
const RATE_LIMIT_CACHE_TTL_MS = 30_000
let cached: GitHubRateLimitSnapshot | null = null
// Why: failed probes are cached for the same TTL as successes. Refreshes fail
// open past a failed probe, so on a host that can never report a budget (GHES
// with rate limiting disabled 404s every probe) an uncached failure would cost
// a gh subprocess per queued refresh.
let probeFailure: { at: number; error: string } | null = null
type GhRateLimitPayload = {
resources?: {
@@ -66,6 +71,7 @@ function parseBucket(
/** @internal — test-only */
export function _resetRateLimitCache(): void {
cached = null
probeFailure = null
}
// Why: hard-stop thresholds for the circuit breaker. We refuse to issue a new
@@ -196,6 +202,9 @@ export async function getRateLimit(options?: { force?: boolean }): Promise<GetRa
if (!options?.force && cached && Date.now() - cached.fetchedAt < RATE_LIMIT_CACHE_TTL_MS) {
return { ok: true, snapshot: cached }
}
if (!options?.force && probeFailure && Date.now() - probeFailure.at < RATE_LIMIT_CACHE_TTL_MS) {
return { ok: false, error: probeFailure.error }
}
if (!options?.force && probeInFlight) {
return probeInFlight
}
@@ -222,9 +231,11 @@ async function fetchRateLimitSnapshot(): Promise<GetRateLimitResult> {
fetchedAt: Date.now()
}
cached = snapshot
probeFailure = null
return { ok: true, snapshot }
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
probeFailure = { at: Date.now(), error: message }
return { ok: false, error: message }
} finally {
release()
+118
View File
@@ -3311,6 +3311,124 @@ describe('registerPtyHandlers', () => {
}
})
// Why: the unsent main->renderer backlog was only bounded by renderer ACKs. A
// background-throttled/frozen renderer (Win/Linux) stops ACKing while a busy
// pane keeps producing, so the per-pty pending string grew at raw PTY rate
// (MB->GB). The cap trims it to the most-recent span and flags droppedBacklog
// exactly once so the renderer rebuilds the dropped span from the main snapshot.
it('caps the unsent pending backlog and flags droppedBacklog once when the renderer never acks', async () => {
vi.useFakeTimers()
let seq = 0
const runtime = {
setPtyController: vi.fn(),
registerPty: vi.fn(),
onPtySpawned: vi.fn(),
onPtyExit: vi.fn(),
onPtyData: vi.fn((_id: string, data: string) => {
seq += data.length
return seq
}),
createPreAllocatedTerminalHandle: vi.fn(() => 'terminal-handle-cap'),
registerPreAllocatedHandleForPty: vi.fn()
}
try {
registerPtyHandlers(
mainWindow as never,
runtime as never,
undefined,
undefined,
undefined,
undefined,
{ awaitLocalPtyStartup: () => Promise.resolve() }
)
const pendingSpawn = handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
sessionId: 'backlog-cap-session'
}) as Promise<{ id: string }>
await Promise.resolve()
const daemon = installObservableDaemonTestProvider()
rebindLocalProviderListeners()
const result = await pendingSpawn
// Never ack: in-flight pins at the high-water and the flush gates, so the
// unsent backlog would grow unbounded. Emit far more than the 2 MB cap.
const HUGE = 'x'.repeat(5 * 1024 * 1024)
daemon.emitData(result.id, HUGE)
await vi.advanceTimersByTimeAsync(50)
const dataSends = mainWindow.webContents.send.mock.calls.filter(
(call) => call[0] === 'pty:data' && (call[1] as { id: string }).id === result.id
)
expect(dataSends.length).toBeGreaterThan(0)
// Sanity bound only: with no acks the sent total is already gated by the
// pre-existing in-flight high-water caps, so this holds independent of the
// trim. The actual retained-backlog cap is proven by droppedBacklog below.
const totalChars = dataSends.reduce(
(sum, call) => sum + (call[1] as { data: string }).data.length,
0
)
expect(totalChars).toBeLessThan(3 * 1024 * 1024)
// The trim signals the renderer exactly once, on the first emitted chunk.
expect((dataSends[0][1] as { droppedBacklog?: boolean }).droppedBacklog).toBe(true)
expect(
dataSends.filter(
(call) => (call[1] as { droppedBacklog?: boolean }).droppedBacklog === true
)
).toHaveLength(1)
} finally {
vi.useRealTimers()
}
})
// Why: the cap and its flag must never fire in the common case (renderer keeps
// up), so ordinary small output carries no droppedBacklog.
it('does not flag droppedBacklog for ordinary small output under the cap', async () => {
vi.useFakeTimers()
const runtime = {
setPtyController: vi.fn(),
registerPty: vi.fn(),
onPtySpawned: vi.fn(),
onPtyExit: vi.fn(),
onPtyData: vi.fn(() => 12),
createPreAllocatedTerminalHandle: vi.fn(() => 'terminal-handle-small'),
registerPreAllocatedHandleForPty: vi.fn()
}
try {
registerPtyHandlers(
mainWindow as never,
runtime as never,
undefined,
undefined,
undefined,
undefined,
{ awaitLocalPtyStartup: () => Promise.resolve() }
)
const pendingSpawn = handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
sessionId: 'small-output-session'
}) as Promise<{ id: string }>
await Promise.resolve()
const daemon = installObservableDaemonTestProvider()
rebindLocalProviderListeners()
const result = await pendingSpawn
daemon.emitData(result.id, 'small output')
await vi.advanceTimersByTimeAsync(50)
const dataSends = mainWindow.webContents.send.mock.calls.filter(
(call) => call[0] === 'pty:data' && (call[1] as { id: string }).id === result.id
)
expect(dataSends.length).toBeGreaterThan(0)
for (const call of dataSends) {
expect((call[1] as { droppedBacklog?: boolean }).droppedBacklog).toBeUndefined()
}
} finally {
vi.useRealTimers()
}
})
it('waits for the desktop startup barrier before runtime local spawns resolve the provider', async () => {
const barrier = makeDeferred()
const runtime = {
+73 -20
View File
@@ -1364,6 +1364,10 @@ export function registerPtyHandlers(
data: string
startSeq?: number
containsBackgroundOutput?: boolean
/** Set once this pty's unsent backlog was trimmed past the cap; rides the
* next payload so the renderer rebuilds the dropped span from the main
* headless snapshot (see appendPendingPtyData / dataCallback). */
droppedBacklog?: boolean
}
type PtyDataPayload = {
@@ -1372,6 +1376,7 @@ export function registerPtyHandlers(
seq?: number
rawLength?: number
background?: boolean
droppedBacklog?: boolean
}
const pendingData = new Map<string, PendingPtyData>()
@@ -1385,6 +1390,15 @@ export function registerPtyHandlers(
const PTY_BATCH_FLUSH_MAX_WRITES = 2
const PTY_RENDERER_IN_FLIGHT_HIGH_WATER_CHARS = 512 * 1024
const PTY_RENDERER_TOTAL_IN_FLIGHT_HIGH_WATER_CHARS = 8 * 1024 * 1024
// Why: the in-flight caps above bound only SENT-but-unacked bytes; the unsent
// `pendingData` backlog is drained only when the renderer ACKs. A background-
// throttled/frozen renderer (Win/Linux — macOS disables throttling) stops
// ACKing while a busy pane keeps producing, so without this the per-pty queue
// grows at raw PTY throughput (MB->GB). Cap it (matching the daemon 2 MB
// pendingOutput and renderer 2 MB scheduler caps); the trimmed span is
// recovered from the main headless buffer via the renderer's hidden-output
// snapshot restore, flagged by droppedBacklog — so no output is lost.
const PENDING_DATA_MAX_CHARS = 2 * 1024 * 1024
const PTY_RENDERER_INTERACTIVE_RESERVE_CHARS = 256 * 1024
// Why: active panes need a bounded lane through old hidden bulk output so a
// keystroke redraw can reach the renderer before every background ACK lands.
@@ -1503,7 +1517,8 @@ export function registerPtyHandlers(
id: string,
data: string,
startSeq: number | undefined,
containsBackgroundOutput: boolean | undefined
containsBackgroundOutput: boolean | undefined,
droppedBacklog?: boolean
): PtyDataPayload {
const payload: PtyDataPayload = { id, data }
if (typeof startSeq === 'number') {
@@ -1513,6 +1528,9 @@ export function registerPtyHandlers(
if (containsBackgroundOutput === true) {
payload.background = true
}
if (droppedBacklog === true) {
payload.droppedBacklog = true
}
return payload
}
@@ -1584,6 +1602,28 @@ export function registerPtyHandlers(
return [...active, ...background]
}
// Why: bound the unsent backlog to the most-recent PENDING_DATA_MAX_CHARS,
// advancing startSeq by the dropped-char count (same arithmetic flushPendingData
// uses when it slices) so the remaining tail's seq stays correct. Flags
// droppedBacklog so the next payload tells the renderer to rebuild the dropped
// span from the main headless snapshot. A no-op when under the cap (the common
// case: the renderer is ACKing and pendingData stays tiny).
function capPendingPtyData(pending: PendingPtyData): PendingPtyData {
if (pending.data.length <= PENDING_DATA_MAX_CHARS) {
return pending
}
const trimmed = pending.data.slice(pending.data.length - PENDING_DATA_MAX_CHARS)
const droppedChars = pending.data.length - trimmed.length
const next: PendingPtyData = { data: trimmed, droppedBacklog: true }
if (typeof pending.startSeq === 'number') {
next.startSeq = pending.startSeq + droppedChars
}
if (pending.containsBackgroundOutput === true) {
next.containsBackgroundOutput = true
}
return next
}
function appendPendingPtyData(
existing: PendingPtyData | undefined,
data: string,
@@ -1593,27 +1633,29 @@ export function registerPtyHandlers(
): PendingPtyData {
const nextContainsBackgroundOutput =
existing?.containsBackgroundOutput === true || containsBackgroundOutput
// Carry a prior drop flag forward until it actually rides an outgoing payload.
const inheritedDropped = existing?.droppedBacklog === true
const base: PendingPtyData = { data: '' }
if (!preservesSeq) {
return {
data: (existing?.data ?? '') + data,
...(nextContainsBackgroundOutput ? { containsBackgroundOutput: true } : {})
base.data = (existing?.data ?? '') + data
} else if (!existing) {
base.data = data
if (typeof startSeq === 'number') {
base.startSeq = startSeq
}
} else {
base.data = existing.data + data
if (typeof existing.startSeq === 'number') {
base.startSeq = existing.startSeq
}
}
if (!existing) {
return {
data,
...(typeof startSeq === 'number' ? { startSeq } : {}),
...(nextContainsBackgroundOutput ? { containsBackgroundOutput: true } : {})
}
if (nextContainsBackgroundOutput) {
base.containsBackgroundOutput = true
}
const next: PendingPtyData = {
data: existing.data + data,
...(nextContainsBackgroundOutput ? { containsBackgroundOutput: true } : {})
if (inheritedDropped) {
base.droppedBacklog = true
}
if (typeof existing.startSeq === 'number') {
next.startSeq = existing.startSeq
}
return next
return capPendingPtyData(base)
}
function schedulePendingDataFlush(delayMs: number): void {
@@ -1654,9 +1696,18 @@ export function registerPtyHandlers(
}
pendingData.set(id, nextPending)
}
// Why: the drop flag rides the first emitted chunk (renderer restore is
// idempotent) and is intentionally not copied onto `remaining` above, so a
// single backlog trim signals the renderer exactly once.
sendPtyDataToRenderer(
id,
makePtyDataPayload(id, chunk, pending.startSeq, pending.containsBackgroundOutput)
makePtyDataPayload(
id,
chunk,
pending.startSeq,
pending.containsBackgroundOutput,
pending.droppedBacklog
)
)
writes++
}
@@ -1720,7 +1771,8 @@ export function registerPtyHandlers(
payload.id,
remaining.data,
remaining.startSeq,
remaining.containsBackgroundOutput
remaining.containsBackgroundOutput,
remaining.droppedBacklog
)
)
pendingData.delete(payload.id)
@@ -1833,7 +1885,8 @@ export function registerPtyHandlers(
...(typeof pending.startSeq === 'number'
? { seq: pending.startSeq + nextData.length, rawLength: nextData.length }
: {}),
...(pending.containsBackgroundOutput === true ? { background: true } : {})
...(pending.containsBackgroundOutput === true ? { background: true } : {}),
...(pending.droppedBacklog === true ? { droppedBacklog: true } : {})
})
return
}
+282
View File
@@ -25,6 +25,16 @@ function createMockChannel(): EventEmitter & { stderr: EventEmitter } {
})
}
// Recover the PowerShell script from a `powershell.exe ... -EncodedCommand <b64>`
// command so tests can assert on the actual (UTF-16LE) payload sent to the host.
function decodeEncodedCommand(command: string): string {
const match = /-EncodedCommand (\S+)/.exec(command)
if (!match) {
throw new Error(`no -EncodedCommand in: ${command}`)
}
return Buffer.from(match[1], 'base64').toString('utf16le')
}
describe('registerSshBrowseHandler', () => {
let handler: BrowseHandler
@@ -88,6 +98,275 @@ describe('registerSshBrowseHandler', () => {
expect(exec).toHaveBeenCalledWith("cd '/tmp/it'\\''s here' && pwd && command ls -1Ap")
})
it('falls back to PowerShell when a Windows SSH shell rejects POSIX exec', async () => {
const posixChannel = createMockChannel()
const windowsChannel = createMockChannel()
const exec = vi.fn().mockResolvedValueOnce(posixChannel).mockResolvedValueOnce(windowsChannel)
const getConnectionManager = () => ({
getConnection: () => ({ exec })
})
registerSshBrowseHandler(getConnectionManager as never)
const resultPromise = handler(null, { targetId: 'ssh-1', dirPath: 'C:/Users/alice' })
await Promise.resolve()
posixChannel.stderr.emit(
'data',
Buffer.from('"exec" no se reconoce como un comando interno o externo')
)
posixChannel.emit('exit', 1)
posixChannel.emit('close')
await vi.waitFor(() => {
expect(windowsChannel.listenerCount('close')).toBe(1)
})
// Windows OpenSSH exec emits CRLF; the parser must strip \r so directories
// aren't misclassified as files with a stray carriage return in the name.
// The script emits a forward-slash resolvedPath (the -replace '\\','/' line)
// so the renderer's parentPath/joinPath, which only split on `/`, still work.
windowsChannel.emit('data', Buffer.from('C:/Users/alice\r\nDesktop/\r\nnotes.txt\r\n'))
windowsChannel.emit('exit', 0)
windowsChannel.emit('close')
await expect(resultPromise).resolves.toEqual({
resolvedPath: 'C:/Users/alice',
entries: [
{ name: 'Desktop', isDirectory: true },
{ name: 'notes.txt', isDirectory: false }
]
})
expect(exec).toHaveBeenCalledTimes(2)
expect(exec).toHaveBeenNthCalledWith(1, "cd 'C:/Users/alice' && pwd && command ls -1Ap")
expect(exec.mock.calls[1]?.[0]).toMatch(/^powershell\.exe /)
expect(exec.mock.calls[1]?.[1]).toEqual({ wrapCommand: false })
// Decode the -EncodedCommand payload so an accidental switch from the
// single-quote-escaped PowerShell literal to raw interpolation (an injection
// regression) is caught, and to lock in the UTF-8 output pin.
const script = decodeEncodedCommand(exec.mock.calls[1]?.[0] ?? '')
expect(script).toContain('[Console]::OutputEncoding = [System.Text.Encoding]::UTF8')
expect(script).toContain("$dir = 'C:/Users/alice'")
expect(script).toContain('Get-ChildItem -LiteralPath $resolved -Force')
// resolvedPath must be emitted with forward slashes so the renderer's
// parentPath/joinPath (which only split on `/`) keep working on Windows.
expect(script).toContain("Write-Output ($resolved -replace '\\\\', '/')")
})
it('falls back for a non-English cmd.exe reject (exit 1, localized stderr)', async () => {
// Regression: real Windows OpenSSH + cmd.exe forwards exit 1 (not 9009) with
// localized stderr. The old 9009/English-string trigger silently missed this,
// so German/Japanese/etc. hosts never fell back. Keying off the non-zero exit
// of a RemoteBrowseError fixes it regardless of OS display language.
const posixChannel = createMockChannel()
const windowsChannel = createMockChannel()
const exec = vi.fn().mockResolvedValueOnce(posixChannel).mockResolvedValueOnce(windowsChannel)
const getConnectionManager = () => ({
getConnection: () => ({ exec })
})
registerSshBrowseHandler(getConnectionManager as never)
const resultPromise = handler(null, { targetId: 'ssh-1', dirPath: 'C:/Users' })
await Promise.resolve()
// Japanese cmd.exe "not recognized" text — matches none of the removed English
// /Spanish substrings, and exit 1 is not the removed 9009 sentinel.
posixChannel.stderr.emit(
'data',
Buffer.from("'exec' は、内部コマンドとして認識されていません。")
)
posixChannel.emit('exit', 1)
posixChannel.emit('close')
await vi.waitFor(() => {
expect(windowsChannel.listenerCount('close')).toBe(1)
})
windowsChannel.emit('data', Buffer.from('C:/Users\r\nAdmin/\r\n'))
windowsChannel.emit('exit', 0)
windowsChannel.emit('close')
await expect(resultPromise).resolves.toEqual({
resolvedPath: 'C:/Users',
entries: [{ name: 'Admin', isDirectory: true }]
})
expect(exec).toHaveBeenCalledTimes(2)
})
it('escapes single quotes in the PowerShell literal path', async () => {
const posixChannel = createMockChannel()
const windowsChannel = createMockChannel()
const exec = vi.fn().mockResolvedValueOnce(posixChannel).mockResolvedValueOnce(windowsChannel)
const getConnectionManager = () => ({
getConnection: () => ({ exec })
})
registerSshBrowseHandler(getConnectionManager as never)
const resultPromise = handler(null, { targetId: 'ssh-1', dirPath: "C:/O'Brien" })
await Promise.resolve()
// A cmd.exe reject exits 1 over SSH (its 9009 ERRORLEVEL never crosses the
// process boundary) with localized German stderr. The fallback must still fire,
// since it keys off the non-zero exit, not the (localized, unmatchable) text.
posixChannel.stderr.emit('data', Buffer.from('Der Befehl "exec" ist falsch geschrieben'))
posixChannel.emit('exit', 1)
posixChannel.emit('close')
await vi.waitFor(() => {
expect(windowsChannel.listenerCount('close')).toBe(1)
})
windowsChannel.emit('data', Buffer.from("C:/O'Brien\r\n"))
windowsChannel.emit('exit', 0)
windowsChannel.emit('close')
await expect(resultPromise).resolves.toEqual({
resolvedPath: "C:/O'Brien",
entries: []
})
const script = decodeEncodedCommand(exec.mock.calls[1]?.[0] ?? '')
// Single quote must be doubled inside the PowerShell literal, not passed raw.
expect(script).toContain("$dir = 'C:/O''Brien'")
})
it('expands ~ to $HOME in the PowerShell fallback (the default browse path)', async () => {
const posixChannel = createMockChannel()
const windowsChannel = createMockChannel()
const exec = vi.fn().mockResolvedValueOnce(posixChannel).mockResolvedValueOnce(windowsChannel)
const getConnectionManager = () => ({
getConnection: () => ({ exec })
})
registerSshBrowseHandler(getConnectionManager as never)
const resultPromise = handler(null, { targetId: 'ssh-1', dirPath: '~' })
await Promise.resolve()
posixChannel.stderr.emit('data', Buffer.from('"exec" is not recognized'))
posixChannel.emit('exit', 1)
posixChannel.emit('close')
await vi.waitFor(() => {
expect(windowsChannel.listenerCount('close')).toBe(1)
})
windowsChannel.emit('data', Buffer.from('C:/Users/alice\r\n'))
windowsChannel.emit('exit', 0)
windowsChannel.emit('close')
await expect(resultPromise).resolves.toEqual({ resolvedPath: 'C:/Users/alice', entries: [] })
const script = decodeEncodedCommand(exec.mock.calls[1]?.[0] ?? '')
// ~ must expand to $HOME, not be passed literally to Set-Location.
expect(script).toContain('$dir = $HOME')
})
// The renderer rebuilds forward-slash Windows paths with POSIX helpers: the
// breadcrumb prepends a spurious leading '/' before the drive, and "Up" from a
// first-level dir yields a bare drive letter. Both must be rooted for
// Set-Location, or navigation lands in the drive-relative cwd / errors.
it.each([
{ dirPath: '/C:/Users', expected: "$dir = 'C:/Users'" },
{ dirPath: 'C:', expected: "$dir = 'C:/'" },
// Combined strip + root, so a future refactor can't break the ordering.
{ dirPath: '/C:', expected: "$dir = 'C:/'" }
])(
'roots the Windows drive path $dirPath in the PowerShell fallback',
async ({ dirPath, expected }) => {
const posixChannel = createMockChannel()
const windowsChannel = createMockChannel()
const exec = vi.fn().mockResolvedValueOnce(posixChannel).mockResolvedValueOnce(windowsChannel)
const getConnectionManager = () => ({
getConnection: () => ({ exec })
})
registerSshBrowseHandler(getConnectionManager as never)
const resultPromise = handler(null, { targetId: 'ssh-1', dirPath })
await Promise.resolve()
posixChannel.stderr.emit('data', Buffer.from('"exec" is not recognized'))
posixChannel.emit('exit', 1)
posixChannel.emit('close')
await vi.waitFor(() => {
expect(windowsChannel.listenerCount('close')).toBe(1)
})
windowsChannel.emit('data', Buffer.from('C:/Users\r\n'))
windowsChannel.emit('exit', 0)
windowsChannel.emit('close')
await expect(resultPromise).resolves.toEqual({ resolvedPath: 'C:/Users', entries: [] })
const script = decodeEncodedCommand(exec.mock.calls[1]?.[0] ?? '')
expect(script).toContain(expected)
}
)
it('surfaces the original POSIX failure when the PowerShell retry shows the host is not Windows', async () => {
const posixChannel = createMockChannel()
const windowsChannel = createMockChannel()
const exec = vi.fn().mockResolvedValueOnce(posixChannel).mockResolvedValueOnce(windowsChannel)
const getConnectionManager = () => ({
getConnection: () => ({ exec })
})
registerSshBrowseHandler(getConnectionManager as never)
const resultPromise = handler(null, { targetId: 'ssh-1', dirPath: '/root/secret' })
await Promise.resolve()
// A genuine POSIX permission failure exits non-zero; it's indistinguishable
// from a Windows shell reject without probing, so the fallback is attempted...
posixChannel.stderr.emit('data', Buffer.from('ls: /root/secret: Permission denied'))
posixChannel.emit('exit', 1)
posixChannel.emit('close')
await vi.waitFor(() => {
expect(windowsChannel.listenerCount('close')).toBe(1)
})
// ...but on a POSIX host the login shell can't find powershell.exe (exit 127),
// so the original permission error is surfaced, never masked by the retry.
windowsChannel.stderr.emit('data', Buffer.from('bash: powershell.exe: command not found'))
windowsChannel.emit('exit', 127)
windowsChannel.emit('close')
await expect(resultPromise).rejects.toThrow('Permission denied')
expect(exec).toHaveBeenCalledTimes(2)
})
it('surfaces the PowerShell error when the Windows fallback runs but fails', async () => {
const posixChannel = createMockChannel()
const windowsChannel = createMockChannel()
const exec = vi.fn().mockResolvedValueOnce(posixChannel).mockResolvedValueOnce(windowsChannel)
const getConnectionManager = () => ({
getConnection: () => ({ exec })
})
registerSshBrowseHandler(getConnectionManager as never)
const resultPromise = handler(null, { targetId: 'ssh-1', dirPath: 'C:/missing' })
await Promise.resolve()
posixChannel.stderr.emit('data', Buffer.from('"exec" is not recognized'))
posixChannel.emit('exit', 1)
posixChannel.emit('close')
await vi.waitFor(() => {
expect(windowsChannel.listenerCount('close')).toBe(1)
})
windowsChannel.stderr.emit('data', Buffer.from('Cannot find path C:/missing'))
windowsChannel.emit('exit', 1)
windowsChannel.emit('close')
// PowerShell exited non-127, so it genuinely ran on a Windows host — its error
// is the real cause. Surface it rather than the cmd.exe "not recognized" prose.
await expect(resultPromise).rejects.toThrow('Cannot find path')
})
it('surfaces the original POSIX error when the fallback shows powershell.exe is missing', async () => {
const posixChannel = createMockChannel()
const windowsChannel = createMockChannel()
const exec = vi.fn().mockResolvedValueOnce(posixChannel).mockResolvedValueOnce(windowsChannel)
const getConnectionManager = () => ({
getConnection: () => ({ exec })
})
registerSshBrowseHandler(getConnectionManager as never)
const resultPromise = handler(null, { targetId: 'ssh-1', dirPath: '/opt/exec' })
await Promise.resolve()
// A non-zero POSIX failure triggers the fallback probe on any host...
posixChannel.stderr.emit('data', Buffer.from('exec: command not found'))
posixChannel.emit('exit', 127)
posixChannel.emit('close')
await vi.waitFor(() => {
expect(windowsChannel.listenerCount('close')).toBe(1)
})
windowsChannel.stderr.emit('data', Buffer.from('sh: powershell.exe: not found'))
windowsChannel.emit('exit', 127)
windowsChannel.emit('close')
// The original POSIX failure is the real one — don't mask it with the
// misleading "powershell.exe: not found" from the doomed retry.
await expect(resultPromise).rejects.toThrow('exec: command not found')
})
it('rejects and detaches listeners when the browse channel errors', async () => {
const channel = createMockChannel()
const exec = vi.fn().mockResolvedValue(channel)
@@ -101,6 +380,9 @@ describe('registerSshBrowseHandler', () => {
channel.emit('error', new Error('remote disconnected'))
await expect(resultPromise).rejects.toThrow('remote disconnected')
// A transport failure is not a RemoteBrowseError, so it must not trigger a
// pointless PowerShell retry.
expect(exec).toHaveBeenCalledTimes(1)
expect(channel.listenerCount('data')).toBe(0)
expect(channel.listenerCount('exit')).toBe(0)
expect(channel.listenerCount('close')).toBe(0)
+267 -144
View File
@@ -1,5 +1,7 @@
import { ipcMain } from 'electron'
import type { SshConnectionManager } from '../ssh/ssh-connection'
import type { SshExecOptions } from '../ssh/ssh-connection-utils'
import { powerShellCommand, powerShellLiteral } from '../ssh/ssh-remote-powershell'
export type RemoteDirEntry = {
name: string
@@ -8,6 +10,33 @@ export type RemoteDirEntry = {
const SSH_BROWSE_TIMEOUT_MS = 15_000
// Why: a POSIX login shell that can't find powershell.exe exits 127 (the POSIX
// "command not found" convention, identical across sh/bash/zsh and locales). It's
// the locale-independent signal that the Windows fallback never actually ran, so
// the original POSIX failure — not the doomed retry — is the real error.
//
// Note: cmd.exe's ERRORLEVEL for an unrecognized command is 9009, but that value
// never crosses cmd.exe's process boundary. sshd forwards cmd.exe's *process* exit
// code, which is 1 — verified on real Windows OpenSSH + cmd.exe over both the ssh2
// and system-ssh transports. So a Windows host rejecting Orca's POSIX `exec`
// wrapper is detected by "the remote command ran and exited non-zero"
// (RemoteBrowseError), not by a magic exit code or localized stderr text.
const POSIX_COMMAND_NOT_FOUND_EXIT = 127
// Carries the raw exit code so the fallback can (a) recognize that the remote
// command actually ran and failed — the locale-independent trigger for the
// Windows retry — and (b) tell a POSIX "powershell.exe not found" (127) apart
// from a genuine PowerShell error, without parsing localized shell prose.
class RemoteBrowseError extends Error {
constructor(
message: string,
readonly exitCode: number | null
) {
super(message)
this.name = 'RemoteBrowseError'
}
}
// Why: the relay's fs.readDir enforces workspace root ACLs, which aren't
// registered until a repo is added. This handler uses a raw SSH exec channel
// to list directories, allowing the user to browse the remote filesystem
@@ -32,156 +61,229 @@ export function registerSshBrowseHandler(
throw new Error(`SSH connection "${args.targetId}" not found`)
}
// Why: using one line per entry preserves filenames containing spaces.
// `command ls` bypasses user aliases/functions like `ls='eza ...'`.
// The -1 flag outputs one entry per line. The -p flag appends / to directories.
// We resolve ~ and get the absolute path via `cd <path> && pwd`.
// `cd` and `ls` are chained with `&&` so a failing `ls` (e.g. permission
// denied after a readable `cd ... && pwd`) propagates as a non-zero exit
// code rather than being indistinguishable from an empty directory.
const command = `cd ${shellEscape(args.dirPath)} && pwd && command ls -1Ap`
const channel = await conn.exec(command)
return new Promise((resolve, reject) => {
let stdout = ''
let stderr = ''
let exitCode: number | null = null
let settled = false
let timeout: ReturnType<typeof setTimeout> | null = null
const cleanup = (): void => {
if (timeout) {
clearTimeout(timeout)
timeout = null
}
channel.off('data', onStdoutData)
channel.stderr.off('data', onStderrData)
channel.off('exit', onExit)
channel.off('close', onClose)
channel.off('error', onError)
channel.stderr.off('error', onError)
try {
return await browseWithPosixShell(conn, args.dirPath)
} catch (posixError) {
// Why: a Windows login shell (cmd.exe/PowerShell) rejects Orca's POSIX
// `exec` wrapper, and the only locale-independent signal for that is "the
// remote command executed and exited non-zero" (RemoteBrowseError). Its
// stderr prose is localized, and cmd.exe's 9009 ERRORLEVEL never reaches
// us (sshd forwards process exit 1). Transport errors/timeouts aren't
// RemoteBrowseErrors, so a dropped connection is never retried as Windows.
if (!(posixError instanceof RemoteBrowseError)) {
throw posixError
}
const rejectOnce = (error: Error): void => {
if (settled) {
return
}
settled = true
cleanup()
reject(error)
try {
return await browseWithWindowsPowerShell(conn, args.dirPath)
} catch (fallbackError) {
// Why: if the login shell couldn't find powershell.exe (exit 127) the
// host isn't Windows — surface the original POSIX failure rather than a
// misleading "powershell.exe: not found". Otherwise PowerShell genuinely
// ran and its error (e.g. "Cannot find path") is the real cause.
throw isPosixCommandNotFound(fallbackError) ? posixError : fallbackError
}
const closeChannel = (): void => {
const closable = channel as { close?: () => void; destroy?: () => void }
try {
if (typeof closable.close === 'function') {
closable.close()
} else if (typeof closable.destroy === 'function') {
closable.destroy()
}
} catch {
/* best effort */
}
}
const onTimeout = (): void => {
// Why: remote browsing runs before a relay workspace root exists, so
// it cannot rely on relay request deadlines. Bound this raw exec
// channel directly to keep Add Remote Project from hanging forever.
rejectOnce(new Error('Remote directory listing timed out'))
closeChannel()
}
const resolveOnce = (result: { entries: RemoteDirEntry[]; resolvedPath: string }): void => {
if (settled) {
return
}
settled = true
cleanup()
resolve(result)
}
const onStdoutData = (data: Buffer): void => {
stdout += data.toString()
}
const onStderrData = (data: Buffer): void => {
stderr += data.toString()
}
// `exit` fires before `close`; capture the code so we can distinguish
// a failed `ls` that still produced `pwd` output from an empty listing.
const onExit = (code: number | null): void => {
exitCode = code
}
const onError = (error: Error): void => {
rejectOnce(error)
}
const onClose = (): void => {
// A null exitCode means the server closed the channel without
// sending an exit-status message (or signalled termination). We
// can't assume success — falling back to "empty stdout = empty
// directory" is exactly the bug the exit-code branch was added to
// fix. Treat any non-zero OR null exit as a failure when stderr
// has content, and otherwise require stdout to contain at least
// the resolved `pwd` line before accepting the result.
if (exitCode !== 0) {
const msg =
stderr.trim() ||
(exitCode === null
? 'Remote listing failed (channel closed without exit status)'
: `Remote listing failed (exit ${exitCode})`)
rejectOnce(new Error(msg))
return
}
if (stderr.trim() && !stdout.trim()) {
rejectOnce(new Error(stderr.trim()))
return
}
const lines = stdout.trim().split('\n')
if (lines.length === 0) {
rejectOnce(new Error('Empty response from remote'))
return
}
const resolvedPath = lines[0]
const entries: RemoteDirEntry[] = []
for (let i = 1; i < lines.length; i++) {
const line = lines[i]
if (!line || line === './' || line === '../') {
continue
}
if (line.endsWith('/')) {
entries.push({ name: line.slice(0, -1), isDirectory: true })
} else {
entries.push({ name: line, isDirectory: false })
}
}
// Sort: directories first, then alphabetical
entries.sort((a, b) => {
if (a.isDirectory !== b.isDirectory) {
return a.isDirectory ? -1 : 1
}
return a.name.localeCompare(b.name)
})
resolveOnce({ entries, resolvedPath })
}
channel.on('data', onStdoutData)
channel.stderr.on('data', onStderrData)
channel.on('exit', onExit)
channel.on('close', onClose)
// Why: SSH exec streams emit `error` on transport loss; without a
// scoped listener, a disappearing remote can become process-fatal.
channel.on('error', onError)
channel.stderr.on('error', onError)
timeout = setTimeout(onTimeout, SSH_BROWSE_TIMEOUT_MS)
if (typeof timeout.unref === 'function') {
timeout.unref()
}
})
}
}
)
}
type SshBrowseConnection = NonNullable<ReturnType<SshConnectionManager['getConnection']>>
function browseWithPosixShell(
conn: SshBrowseConnection,
dirPath: string
): Promise<{ entries: RemoteDirEntry[]; resolvedPath: string }> {
// Why: using one line per entry preserves filenames containing spaces.
// `command ls` bypasses user aliases/functions like `ls='eza ...'`.
// The -1 flag outputs one entry per line. The -p flag appends / to directories.
// We resolve ~ and get the absolute path via `cd <path> && pwd`.
// `cd` and `ls` are chained with `&&` so a failing `ls` (e.g. permission
// denied after a readable `cd ... && pwd`) propagates as a non-zero exit
// code rather than being indistinguishable from an empty directory.
return runBrowseCommand(conn, `cd ${shellEscape(dirPath)} && pwd && command ls -1Ap`)
}
function browseWithWindowsPowerShell(
conn: SshBrowseConnection,
dirPath: string
): Promise<{ entries: RemoteDirEntry[]; resolvedPath: string }> {
const script = [
"$ErrorActionPreference = 'Stop'",
// Why: Windows PowerShell 5.1 writes redirected stdout in the legacy OEM
// code page, but runBrowseCommand decodes as UTF-8; pin UTF-8 output so
// non-ASCII names (e.g. C:\Users\José, CJK, Cyrillic) don't come back mojibake.
'[Console]::OutputEncoding = [System.Text.Encoding]::UTF8',
`$dir = ${powerShellPathExpression(dirPath)}`,
'Set-Location -LiteralPath $dir',
'$resolved = (Get-Location).ProviderPath',
// Why: the renderer's parentPath/joinPath only split on `/`, so a native
// backslash path (C:\Users\alice) breaks "Up" and mixes separators. Emit a
// forward-slash resolvedPath (matching the POSIX branch) while keeping the
// native $resolved for Get-ChildItem -LiteralPath.
"Write-Output ($resolved -replace '\\\\', '/')",
'Get-ChildItem -LiteralPath $resolved -Force | ForEach-Object {',
" if ($_.PSIsContainer) { Write-Output ($_.Name + '/') } else { Write-Output $_.Name }",
'}'
].join('; ')
return runBrowseCommand(conn, powerShellCommand(script), { wrapCommand: false })
}
async function runBrowseCommand(
conn: SshBrowseConnection,
command: string,
options?: SshExecOptions
): Promise<{ entries: RemoteDirEntry[]; resolvedPath: string }> {
const channel = options ? await conn.exec(command, options) : await conn.exec(command)
return new Promise((resolve, reject) => {
let stdout = ''
let stderr = ''
let exitCode: number | null = null
let settled = false
let timeout: ReturnType<typeof setTimeout> | null = null
const cleanup = (): void => {
if (timeout) {
clearTimeout(timeout)
timeout = null
}
channel.off('data', onStdoutData)
channel.stderr.off('data', onStderrData)
channel.off('exit', onExit)
channel.off('close', onClose)
channel.off('error', onError)
channel.stderr.off('error', onError)
}
const rejectOnce = (error: Error): void => {
if (settled) {
return
}
settled = true
cleanup()
reject(error)
}
const closeChannel = (): void => {
const closable = channel as { close?: () => void; destroy?: () => void }
try {
if (typeof closable.close === 'function') {
closable.close()
} else if (typeof closable.destroy === 'function') {
closable.destroy()
}
} catch {
/* best effort */
}
}
const onTimeout = (): void => {
// Why: remote browsing runs before a relay workspace root exists, so
// it cannot rely on relay request deadlines. Bound this raw exec
// channel directly to keep Add Remote Project from hanging forever.
rejectOnce(new Error('Remote directory listing timed out'))
closeChannel()
}
const resolveOnce = (result: { entries: RemoteDirEntry[]; resolvedPath: string }): void => {
if (settled) {
return
}
settled = true
cleanup()
resolve(result)
}
const onStdoutData = (data: Buffer): void => {
stdout += data.toString()
}
const onStderrData = (data: Buffer): void => {
stderr += data.toString()
}
// `exit` fires before `close`; capture the code so we can distinguish
// a failed `ls` that still produced `pwd` output from an empty listing.
const onExit = (code: number | null): void => {
exitCode = code
}
const onError = (error: Error): void => {
rejectOnce(error)
}
const onClose = (): void => {
// A null exitCode means the server closed the channel without
// sending an exit-status message (or signalled termination). We
// can't assume success — falling back to "empty stdout = empty
// directory" is exactly the bug the exit-code branch was added to
// fix. Treat any non-zero OR null exit as a failure when stderr
// has content, and otherwise require stdout to contain at least
// the resolved `pwd` line before accepting the result.
if (exitCode !== 0) {
const msg =
stderr.trim() ||
(exitCode === null
? 'Remote listing failed (channel closed without exit status)'
: `Remote listing failed (exit ${exitCode})`)
rejectOnce(new RemoteBrowseError(msg, exitCode))
return
}
if (stderr.trim() && !stdout.trim()) {
rejectOnce(new Error(stderr.trim()))
return
}
// Why: Windows OpenSSH exec emits CRLF, so split on \r?\n — otherwise a
// trailing \r defeats the endsWith('/') dir check and leaves a stray CR
// in every name.
const lines = stdout.trim().split(/\r?\n/)
if (lines.length === 0) {
rejectOnce(new Error('Empty response from remote'))
return
}
const resolvedPath = lines[0]
const entries: RemoteDirEntry[] = []
for (let i = 1; i < lines.length; i++) {
const line = lines[i]
if (!line || line === './' || line === '../') {
continue
}
if (line.endsWith('/')) {
entries.push({ name: line.slice(0, -1), isDirectory: true })
} else {
entries.push({ name: line, isDirectory: false })
}
}
// Sort: directories first, then alphabetical
entries.sort((a, b) => {
if (a.isDirectory !== b.isDirectory) {
return a.isDirectory ? -1 : 1
}
return a.name.localeCompare(b.name)
})
resolveOnce({ entries, resolvedPath })
}
channel.on('data', onStdoutData)
channel.stderr.on('data', onStderrData)
channel.on('exit', onExit)
channel.on('close', onClose)
// Why: SSH exec streams emit `error` on transport loss; without a
// scoped listener, a disappearing remote can become process-fatal.
channel.on('error', onError)
channel.stderr.on('error', onError)
timeout = setTimeout(onTimeout, SSH_BROWSE_TIMEOUT_MS)
if (typeof timeout.unref === 'function') {
timeout.unref()
}
})
}
// Why: a POSIX login shell that can't find powershell.exe exits 127, marking the
// Windows fallback as "never ran" — the host isn't Windows, so the original POSIX
// failure, not the doomed retry, is the error worth surfacing.
function isPosixCommandNotFound(error: unknown): boolean {
return error instanceof RemoteBrowseError && error.exitCode === POSIX_COMMAND_NOT_FOUND_EXIT
}
// Why: prevent shell injection in the directory path. Single-quote wrapping
// with escaped internal single quotes is the safest approach for sh/bash.
// Tilde must be expanded by the shell, so paths starting with ~ use $HOME
@@ -199,3 +301,24 @@ function shellEscape(s: string): string {
function shellEscapeRaw(s: string): string {
return `'${s.replace(/'/g, "'\\''")}'`
}
function powerShellPathExpression(s: string): string {
if (s === '~') {
return '$HOME'
}
if (s.startsWith('~/') || s.startsWith('~\\')) {
return `Join-Path $HOME ${powerShellLiteral(s.slice(2))}`
}
return powerShellLiteral(normalizeWindowsDrivePath(s))
}
// Why: browse emits forward-slash Windows paths, so the renderer rebuilds them
// with POSIX helpers — the breadcrumb prepends a spurious leading '/' before the
// drive (/C:/Users) and "Up" from a first-level dir yields a bare drive letter
// (C:). Both are wrong for Set-Location: a leading '/' means the current drive's
// root, and 'C:' is drive-relative (the process cwd), not 'C:\'. Normalize both
// back to a rooted drive path here so navigation lands where the user clicked.
function normalizeWindowsDrivePath(s: string): string {
const stripped = s.replace(/^\/(?=[A-Za-z]:(?:[/\\]|$))/, '')
return /^[A-Za-z]:$/.test(stripped) ? `${stripped}/` : stripped
}
+21
View File
@@ -267,6 +267,27 @@ describe('SshPortForwardManager', () => {
)
})
it('keeps only a bounded tail of a chatty forward stderr (memory-leak regression)', async () => {
const onForwardClosed = vi.fn()
manager.setCallbacks({ onForwardClosed })
const forward = createFakeSystemSshForward()
startSystemSshPortForwardProcessMock.mockReturnValue(forward)
const conn = createSystemSshConn()
await manager.addForward('conn-1', conn as never, 3000, '127.0.0.1', 8080)
// A long-lived forward against a chatty remote sshd: emit >64 KB of stderr.
forward.process.stderr.emit('data', Buffer.from(`HEAD_MARKER${'x'.repeat(70 * 1024)}`))
forward.process.stderr.emit('data', Buffer.from('TAIL_MARKER'))
forward.process.emit('exit', 255)
const detail = onForwardClosed.mock.calls[0]?.[1]?.detail as string
// The oldest bytes are trimmed; the most-recent tail is retained.
expect(detail).toContain('TAIL_MARKER')
expect(detail).not.toContain('HEAD_MARKER')
// Bounded well below the ~70 KB produced.
expect(detail.length).toBeLessThan(66 * 1024)
})
it('lists forwards filtered by connectionId', async () => {
const conn = createMockConn()
await manager.addForward('conn-1', conn as never, 3000, 'localhost', 8080)
@@ -33,9 +33,17 @@ export class SystemSshPortForwardProvider implements SshPortForwardProvider {
)
await forward.waitForStartup()
// Why: this stderr stays attached for the forward's whole lifetime but is
// only used to build the exit-error detail, so keep a bounded tail — a chatty
// remote sshd could otherwise grow it unbounded on a long-lived forward
// (mirrors MAX_RELAY_STARTUP_BUFFER_BYTES in ssh-relay-deploy-helpers).
const MAX_STDERR_TAIL_BYTES = 64 * 1024
let stderr = ''
const onStderr = (chunk: Buffer): void => {
stderr += chunk.toString('utf-8')
if (stderr.length > MAX_STDERR_TAIL_BYTES) {
stderr = stderr.slice(-MAX_STDERR_TAIL_BYTES)
}
}
forward.process.stderr?.on('data', onStderr)
+1
View File
@@ -1198,6 +1198,7 @@ export type PreloadApi = {
seq?: number
rawLength?: number
background?: boolean
droppedBacklog?: boolean
}) => void
) => () => void
onReplay: (callback: (data: { id: string; data: string }) => void) => () => void
+2
View File
@@ -897,6 +897,7 @@ const api = {
seq?: number
rawLength?: number
background?: boolean
droppedBacklog?: boolean
}) => void
): (() => void) => {
const listener = (
@@ -907,6 +908,7 @@ const api = {
seq?: number
rawLength?: number
background?: boolean
droppedBacklog?: boolean
}
) => callback(data)
ipcRenderer.on('pty:data', listener)
+69 -1
View File
@@ -14,7 +14,10 @@ import {
const { mockPtySpawn, mockPtyInstance } = vi.hoisted(() => ({
mockPtySpawn: vi.fn(),
mockPtyInstance: {
pid: 12345,
// Why: attach now proves the backing pid is alive before replaying, so the
// default managed PTY must report a live pid. Reuse the test runner's own
// pid — always alive — so unrelated attach tests are not seen as dead.
pid: process.pid,
onData: vi.fn(),
onExit: vi.fn(),
write: vi.fn(),
@@ -609,6 +612,71 @@ describe('PtyHandler', () => {
}
)
it('reports not-found and reaps a reattach whose backing shell is dead', async () => {
// Why: a lingering managed entry whose child died without an onExit would
// otherwise attach-succeed with an empty replay and strand the pane on a
// black shell. A provably-dead pid must surface as not-found so the SSH
// provider maps it to SSH_SESSION_EXPIRED and the pane respawns fresh.
let onExitCb: ((evt: { exitCode: number }) => void) | undefined
mockPtySpawn.mockReturnValue({
...mockPtyInstance,
onData: vi.fn(),
onExit: vi.fn((cb: (evt: { exitCode: number }) => void) => {
onExitCb = cb
})
})
const exits: { id: string; paneKey?: string }[] = []
handler.setExitListener((evt) => exits.push(evt))
await dispatcher.callRequest('pty.spawn', { env: { ORCA_PANE_KEY: 'tab-dead:0' } })
expect(handler.activePtyCount).toBe(1)
expect(onExitCb).toBeDefined()
const aliveSpy = vi.spyOn(ptyShellUtils, 'isProcessAlive').mockReturnValue(false)
try {
await expect(
dispatcher.callRequest('pty.attach', { id: 'pty-1', suppressReplayNotification: true })
).rejects.toThrow('PTY "pty-1" not found')
} finally {
aliveSpy.mockRestore()
}
// The stale entry is reaped: cache-eviction observers fire and the map slot
// is freed so a later attach also cleanly reports not-found.
expect(exits).toEqual([{ id: 'pty-1', paneKey: 'tab-dead:0' }])
expect(handler.activePtyCount).toBe(0)
await expect(
dispatcher.callRequest('pty.attach', { id: 'pty-1', suppressReplayNotification: true })
).rejects.toThrow('PTY "pty-1" not found')
})
it('replays for a reattach whose backing shell is still alive', async () => {
// Guard the other direction: a live pid must never be reaped, so a quiet
// but live session still returns its buffered replay on reattach.
let dataCallback: ((data: string) => void) | undefined
mockPtySpawn.mockReturnValue({
...mockPtyInstance,
onData: vi.fn((cb: (data: string) => void) => {
dataCallback = cb
}),
onExit: vi.fn()
})
await dispatcher.callRequest('pty.spawn', {})
dataCallback?.('prompt$ ')
const aliveSpy = vi.spyOn(ptyShellUtils, 'isProcessAlive').mockReturnValue(true)
try {
const result = await dispatcher.callRequest('pty.attach', {
id: 'pty-1',
suppressReplayNotification: true
})
expect(result).toEqual({ replay: 'prompt$ ' })
} finally {
aliveSpy.mockRestore()
}
expect(handler.activePtyCount).toBe(1)
})
it('terminates spawned PTY when request becomes stale before response', async () => {
const killSpy = vi.fn()
const term = { ...mockPtyInstance, kill: killSpy, onData: vi.fn(), onExit: vi.fn() }
+17
View File
@@ -10,6 +10,7 @@ import {
resolveProcessCwd,
processHasChildren,
getForegroundProcessName,
isProcessAlive,
listShellProfiles
} from './pty-shell-utils'
import { getRelayShellLaunchConfig } from './pty-shell-launch'
@@ -692,6 +693,22 @@ export class PtyHandler {
throw new Error(`PTY "${id}" not found`)
}
// Why: a reattach can arrive for a relay PTY whose backing shell already
// died without node-pty delivering onExit (e.g. the child was reaped out of
// band while the SSH channel was down). The map entry lingers, so attach
// would otherwise "succeed" with an empty replay and strand the reattached
// pane on a black, unresponsive shell. Prove liveness here; if the pid is
// provably gone, reap the stale entry and report not-found so the caller
// drops the dead lease and spawns fresh — the same recovery path an expired
// grace window already takes.
if (managed.pty.pid && !isProcessAlive(managed.pty.pid)) {
this.notifyExitListener(managed)
disposeManagedPty(managed)
this.ptys.delete(id)
this.clearPtyFlowState(id)
throw new Error(`PTY "${id}" not found`)
}
// Why: PTY ids are a per-relay-process counter (pty-1, pty-2, …). When the
// relay changes generation — an app update deploys a new content-hashed
// relay dir, or a grace-expired relay restarts — the counter resets, so an
+35
View File
@@ -11,6 +11,7 @@ vi.mock('child_process', () => ({
import { resetProcessTableSnapshotForTests } from '../shared/process-table-snapshot'
import {
getForegroundProcessName,
isProcessAlive,
resolveDefaultCwd,
resolveWindowsDefaultShell
} from './pty-shell-utils'
@@ -51,6 +52,40 @@ beforeEach(() => {
resetProcessTableSnapshotForTests()
})
describe('isProcessAlive', () => {
it('reports the test runner process as alive', () => {
expect(isProcessAlive(process.pid)).toBe(true)
})
it('reports a process as dead ONLY on ESRCH', () => {
// Why: attach() reaps a lingering managed PTY based on this, so a false
// positive would kill a live remote shell. Only "no such process" counts.
const spy = vi.spyOn(process, 'kill').mockImplementation(() => {
const err = new Error('no such process') as NodeJS.ErrnoException
err.code = 'ESRCH'
throw err
})
try {
expect(isProcessAlive(2147483646)).toBe(false)
} finally {
spy.mockRestore()
}
})
it('treats an unsignalable process (EPERM) as alive', () => {
const spy = vi.spyOn(process, 'kill').mockImplementation(() => {
const err = new Error('operation not permitted') as NodeJS.ErrnoException
err.code = 'EPERM'
throw err
})
try {
expect(isProcessAlive(1)).toBe(true)
} finally {
spy.mockRestore()
}
})
})
describe('resolveWindowsDefaultShell', () => {
it('uses an existing SHELL override when one is provided', () => {
expect(
+13
View File
@@ -147,6 +147,19 @@ export async function processHasChildren(pid: number): Promise<boolean> {
}
}
// Why: signal 0 probes existence without delivering a signal. Only ESRCH ("no
// such process") proves the pid is gone; EPERM means it exists but is
// unsignalable, so treat every non-ESRCH outcome as alive. Kept conservative so
// a liveness check can only ever declare a *provably* dead process dead.
export function isProcessAlive(pid: number): boolean {
try {
process.kill(pid, 0)
return true
} catch (err) {
return (err as NodeJS.ErrnoException).code !== 'ESRCH'
}
}
function collectDescendants(
rows: ProcessTableRow[],
rootPid: number
+24 -4
View File
@@ -57,7 +57,7 @@ import {
import TabGroupSplitLayout from './tab-group/TabGroupSplitLayout'
import AiVaultSessionDropLayer from './tab-group/AiVaultSessionDropLayer'
import { shouldAutoCreateInitialTerminal } from './terminal/initial-terminal'
import { shouldRepairActiveTerminalTab } from './terminal/active-terminal-repair'
import { resolveRepairedActiveTerminalTabId } from './terminal/active-terminal-repair'
import { scheduleBackgroundTerminalWorktreeMeasure } from './terminal/background-terminal-worktree-visibility'
import {
getEffectiveLayoutForWorktree as getEffectiveLayout,
@@ -224,6 +224,7 @@ function Terminal(): React.JSX.Element | null {
const activeView = useAppStore((s) => s.activeView)
const tabsByWorktree = useAppStore((s) => s.tabsByWorktree)
const activeTabId = useAppStore((s) => s.activeTabId)
const activeTabIdByWorktree = useAppStore((s) => s.activeTabIdByWorktree)
const createTab = useAppStore((s) => s.createTab)
const closeTab = useAppStore((s) => s.closeTab)
const setActiveTab = useAppStore((s) => s.setActiveTab)
@@ -692,19 +693,38 @@ function Terminal(): React.JSX.Element | null {
}, [queueEditorCloseRequests])
useEffect(() => {
if (!shouldRepairActiveTerminalTab({ activeTabType, activeTabId, tabs })) {
const rememberedTabId = renderedActiveWorktreeId
? (activeTabIdByWorktree[renderedActiveWorktreeId] ?? null)
: null
// Why: prefer the worktree's remembered active tab over the first tab so a
// repair firing on a transient worktree-switch render restores the tab the
// user left on instead of permanently resetting the selection to Terminal 1.
const repairedTabId = resolveRepairedActiveTerminalTabId({
activeTabType,
activeTabId,
rememberedTabId,
tabs
})
if (!repairedTabId) {
return
}
// Why: mutating Zustand during render trips React's "Cannot update a
// component while rendering a different component" warning. Keep the repair
// terminal-only so inactive CLI-created tabs cannot steal editor/browser focus.
setActiveTab(tabs[0].id)
setActiveTab(repairedTabId)
// Why: `tabs` is intentionally the dependency here because the repair must
// react to tab-order/content changes, not just scalar IDs. The list comes
// from Zustand selectors and is small in practice, so this explicit repair
// effect is preferred over duplicating reconciliation state.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeTabId, activeTabType, setActiveTab, tabs])
}, [
activeTabId,
activeTabType,
setActiveTab,
tabs,
activeTabIdByWorktree,
renderedActiveWorktreeId
])
// Track which worktrees have been activated during this app session.
// Only mount TerminalPanes for visited worktrees to prevent mass PTY
@@ -347,3 +347,42 @@ describe('applyCommandMarkerBoundaries', () => {
).toEqual(['new'])
})
})
describe('scope-cache key counts stay bounded (memory-leak regression)', () => {
// The per-key arrays were capped at 8, but the KEY count (paneKey/agent/session,
// all ephemeral) was unbounded, so distinct panes/sessions accumulated forever.
// Both caches now LRU-bound the key count at 128 (shared helper, #7566).
const CAP = 128
it('appendCommandMarkerCache evicts the oldest scope key past the cap', () => {
clearCommandMarkerCacheForTests()
for (let i = 0; i < CAP + 5; i++) {
appendCommandMarkerCache(
{ paneKey: 'tab:leaf', agent: 'claude', sessionId: `s${i}` },
'/clear'
)
}
// Oldest sessions evicted; the most-recent CAP survive.
expect(
readCommandMarkerCache({ paneKey: 'tab:leaf', agent: 'claude', sessionId: 's0' })
).toEqual([])
expect(
readCommandMarkerCache({ paneKey: 'tab:leaf', agent: 'claude', sessionId: 's4' })
).toEqual([])
expect(
readCommandMarkerCache({ paneKey: 'tab:leaf', agent: 'claude', sessionId: `s${CAP + 4}` })
).toHaveLength(1)
})
it('writePendingSendCache evicts the oldest scope key past the cap', () => {
clearPendingSendCacheForTests()
const send = (id: string): NativeChatPendingSend => ({ id, text: id, sentAt: 1 })
for (let i = 0; i < CAP + 5; i++) {
writePendingSendCache({ paneKey: `tab-${i}:leaf`, agent: 'claude' }, [send(`m${i}`)])
}
expect(readPendingSendCache({ paneKey: 'tab-0:leaf', agent: 'claude' })).toEqual([])
expect(readPendingSendCache({ paneKey: `tab-${CAP + 4}:leaf`, agent: 'claude' })).toHaveLength(
1
)
})
})
@@ -5,6 +5,7 @@
import { isTextBlock, type NativeChatMessage } from '../../../../shared/native-chat-types'
import { stripImagePromptMarker } from './native-chat-image-transcript-markers'
import { setBoundedScopeCacheEntry } from './native-chat-composer-scope-cache'
import type { NativeChatLaunchPrompt } from '@/lib/native-chat-launch-prompt'
/** An optimistic, not-yet-confirmed composer send. */
@@ -44,7 +45,10 @@ export function writePendingSendCache(
if (next.length === 0) {
pendingSendCache.delete(key)
} else {
pendingSendCache.set(key, next)
// Why: the empty-drain path above clears keys on the normal confirm flow,
// but a pane closed with an unconfirmed send (agent crash / early close)
// would strand its entry forever. LRU-bound the key count too.
setBoundedScopeCacheEntry(pendingSendCache, key, next)
}
return [...next]
}
@@ -233,7 +237,11 @@ export function appendCommandMarkerCache(
...(commandMarkerCache.get(key) ?? []),
{ id: `${sentAt}-${commandMarkerCounter}`, command, sentAt }
].slice(-COMMAND_MARKER_LIMIT)
commandMarkerCache.set(key, next)
// Why: the per-key array is capped at 8, but the KEY (paneKey\0agent\0sessionId,
// sessionId changes on every /clear) is ephemeral and was never evicted, so it
// grew one entry per (pane, session) for the renderer's whole life. LRU-bound
// the key count (mirrors the #7566 draft/attachment caches in this folder).
setBoundedScopeCacheEntry(commandMarkerCache, key, next)
return [...next]
}
@@ -250,6 +250,32 @@ describe('isMutablePRConversationComment', () => {
})
describe('PRCommentsList', () => {
it('pins the comments header while scrolling the sidebar', () => {
const comments: PRComment[] = [
{
id: 1,
author: 'AmethystLiang',
authorAvatarUrl: '',
body: 'Existing review context',
createdAt: '2026-05-14T00:00:00Z',
url: 'https://github.com/acme/widgets/pull/42#issuecomment-1'
}
]
const markup = renderWithTooltips(
React.createElement(PRCommentsList, {
comments,
commentsLoading: false,
onAddComment: () => Promise.resolve({ ok: true as const })
})
)
const commentsHeaderIndex = markup.indexOf('Comments')
const stickyIndex = markup.indexOf('sticky top-0 z-10 bg-sidebar/95 backdrop-blur-sm')
expect(stickyIndex).toBeGreaterThan(-1)
expect(stickyIndex).toBeLessThan(commentsHeaderIndex)
})
it('places the collapsed add-comment action in the comments header', () => {
const comments: PRComment[] = [
{
@@ -2358,7 +2358,14 @@ export function PRCommentsList({
return (
<div className="border-t border-border">
{/* Header */}
<div className={presentation.sectionHeader}>
<div
className={cn(
presentation.sectionHeader,
// Why: the checks sidebar scrolls as one column; pinning this header keeps
// filter and add-comment actions reachable while reading long threads.
'sticky top-0 z-10 bg-sidebar/95 backdrop-blur-sm'
)}
>
<div className="flex min-w-0 items-center gap-2">
<MessageSquare className="size-3.5 text-muted-foreground" />
<span className={presentation.sectionHeaderLabel}>
@@ -13,6 +13,11 @@ import { cn } from '@/lib/utils'
import { AgentAwakeSetting } from './AgentAwakeSetting'
import { AgentCacheTimerSection } from './AgentCacheTimerSection'
import { AgentRuntimeSetting } from './AgentRuntimeSetting'
import {
AgentSessionSourceHomeInput,
buildCodexSessionSourceHomeControl,
type AgentSessionSourceHomeControl
} from './codex-session-source-home-control'
import {
getAgentGeneratedTabTitlesDescription,
getAgentGeneratedTabTitlesTitle
@@ -81,6 +86,8 @@ type AgentRowProps = {
onSaveOverride: (value: string) => void
onSaveArgs: (value: string) => void
onSaveEnv: (value: Record<string, string>) => void
/** Codex-only: current runtime scope label + persisted history-source override. */
sessionSourceHome?: AgentSessionSourceHomeControl
}
type AgentCommandOverrideInputProps = {
@@ -277,42 +284,44 @@ function AgentCommandOverrideInput({
}
return (
<div className="flex items-center gap-2">
<span className="shrink-0 text-xs text-muted-foreground">
<div className="flex flex-col gap-1">
<span className="text-xs text-muted-foreground">
{translate('auto.components.settings.AgentsPane.2e45ca29b6', 'Command')}
</span>
<Input
value={cmdDraft}
onChange={(e) => setCmdDraft(e.target.value)}
onBlur={commitCmd}
onKeyDown={(e) => {
if (e.key === 'Enter') {
commitCmd()
e.currentTarget.blur()
}
if (e.key === 'Escape') {
setCmdDraft(draftSeed)
e.currentTarget.blur()
}
}}
placeholder={defaultCmd}
spellCheck={false}
className="h-7 flex-1 font-mono text-xs"
/>
{cmdOverride && (
<Button
type="button"
variant="ghost"
size="xs"
onClick={() => {
onSaveOverride('')
setCmdDraft(defaultCmd)
<div className="flex items-center gap-2">
<Input
value={cmdDraft}
onChange={(e) => setCmdDraft(e.target.value)}
onBlur={commitCmd}
onKeyDown={(e) => {
if (e.key === 'Enter') {
commitCmd()
e.currentTarget.blur()
}
if (e.key === 'Escape') {
setCmdDraft(draftSeed)
e.currentTarget.blur()
}
}}
className="h-7 shrink-0 text-xs text-muted-foreground hover:text-foreground"
>
{translate('auto.components.settings.AgentsPane.5200dac9da', 'Reset')}
</Button>
)}
placeholder={defaultCmd}
spellCheck={false}
className="h-7 flex-1 font-mono text-xs"
/>
{cmdOverride && (
<Button
type="button"
variant="ghost"
size="xs"
onClick={() => {
onSaveOverride('')
setCmdDraft(defaultCmd)
}}
className="h-7 shrink-0 text-xs text-muted-foreground hover:text-foreground"
>
{translate('auto.components.settings.AgentsPane.5200dac9da', 'Reset')}
</Button>
)}
</div>
</div>
)
}
@@ -330,45 +339,47 @@ function AgentDefaultArgsInput({
}
return (
<div className="flex items-center gap-2">
<span className="shrink-0 text-xs text-muted-foreground">
<div className="flex flex-col gap-1">
<span className="text-xs text-muted-foreground">
{translate('auto.components.settings.AgentsPane.cfb3f35775', 'Arguments')}
</span>
<Input
value={argsDraft}
onChange={(e) => setArgsDraft(e.target.value)}
onBlur={commitArgs}
onKeyDown={(e) => {
if (e.key === 'Enter') {
commitArgs()
e.currentTarget.blur()
}
if (e.key === 'Escape') {
setArgsDraft(draftSeed)
e.currentTarget.blur()
}
}}
placeholder={
defaultArgs ||
translate('auto.components.settings.AgentsPane.6f99bf5dd0', 'No default arguments')
}
spellCheck={false}
className="h-7 flex-1 font-mono text-xs"
/>
{argsOverride !== defaultArgs && (
<Button
type="button"
variant="ghost"
size="xs"
onClick={() => {
onSaveArgs(defaultArgs)
setArgsDraft(defaultArgs)
<div className="flex items-center gap-2">
<Input
value={argsDraft}
onChange={(e) => setArgsDraft(e.target.value)}
onBlur={commitArgs}
onKeyDown={(e) => {
if (e.key === 'Enter') {
commitArgs()
e.currentTarget.blur()
}
if (e.key === 'Escape') {
setArgsDraft(draftSeed)
e.currentTarget.blur()
}
}}
className="h-7 shrink-0 text-xs text-muted-foreground hover:text-foreground"
>
{translate('auto.components.settings.AgentsPane.5200dac9da', 'Reset')}
</Button>
)}
placeholder={
defaultArgs ||
translate('auto.components.settings.AgentsPane.6f99bf5dd0', 'No default arguments')
}
spellCheck={false}
className="h-7 flex-1 font-mono text-xs"
/>
{argsOverride !== defaultArgs && (
<Button
type="button"
variant="ghost"
size="xs"
onClick={() => {
onSaveArgs(defaultArgs)
setArgsDraft(defaultArgs)
}}
className="h-7 shrink-0 text-xs text-muted-foreground hover:text-foreground"
>
{translate('auto.components.settings.AgentsPane.5200dac9da', 'Reset')}
</Button>
)}
</div>
</div>
)
}
@@ -394,11 +405,11 @@ function AgentDefaultEnvInput({
}
return (
<div>
<div className="flex flex-col gap-1">
<span className="text-xs text-muted-foreground">
{translate('auto.components.settings.AgentsPane.8fbe1f37c1', 'Environment')}
</span>
<div className="flex items-center gap-2">
<span className="shrink-0 text-xs text-muted-foreground">
{translate('auto.components.settings.AgentsPane.8fbe1f37c1', 'Environment')}
</span>
<Input
value={envDraft}
onChange={(e) => {
@@ -476,7 +487,8 @@ function AgentRow({
onSetEnabled,
onSaveOverride,
onSaveArgs,
onSaveEnv
onSaveEnv,
sessionSourceHome
}: AgentRowProps): React.JSX.Element {
const envSummary = stringifyAgentDefaultEnvDraft(envOverride)
const defaultEnvSummary = stringifyAgentDefaultEnvDraft(defaultEnv)
@@ -494,15 +506,6 @@ function AgentRow({
<div className="min-w-0 flex-1 sm:min-w-[12rem]">
<div className="flex items-center gap-2">
<span className="text-sm font-medium leading-none">{label}</span>
{isDetected ? (
<SettingsBadge tone="accent">
{translate('auto.components.settings.AgentsPane.c8794e622e', 'Detected')}
</SettingsBadge>
) : (
<SettingsBadge tone="muted">
{translate('auto.components.settings.AgentsPane.df123171d1', 'Not installed')}
</SettingsBadge>
)}
{!isEnabled && (
<SettingsBadge tone="muted">
{translate('auto.components.settings.AgentsPane.8dc0192e48', 'Disabled')}
@@ -523,7 +526,7 @@ function AgentRow({
</div>
</div>
<div className="ml-auto grid shrink-0 grid-cols-[max-content_6.5rem_1.75rem_1.75rem_1.75rem] items-center gap-1.5">
<div className="ml-auto grid shrink-0 grid-cols-[max-content_6.5rem_1.75rem_1.75rem] items-center gap-1.5">
<AgentAvailabilityControl
label={label}
isEnabled={isEnabled}
@@ -552,28 +555,6 @@ function AgentRow({
)}
</div>
<div className="flex size-7 items-center justify-center">
{isDetected && (
<Button
type="button"
variant="ghost"
size="icon-sm"
onClick={() => setCmdOpen((prev) => !prev)}
title={translate(
'auto.components.settings.AgentsPane.db9e9e5887',
'Customize command'
)}
aria-expanded={cmdOpen}
className={cn(
'size-7 text-muted-foreground hover:text-foreground',
(cmdOpen || cmdOverride) && 'text-foreground'
)}
>
<Terminal className="size-3.5" />
</Button>
)}
</div>
<a
href={homepageUrl}
target="_blank"
@@ -644,7 +625,17 @@ function AgentRow({
/>
</div>
)}
<p className="mt-1.5 text-[11px] text-muted-foreground">
{sessionSourceHome && (
<div className="mt-2">
<AgentSessionSourceHomeInput
key={`${agentId}:${sessionSourceHome.runtimeLabel}:${sessionSourceHome.value}`}
runtimeLabel={sessionSourceHome.runtimeLabel}
value={sessionSourceHome.value}
onSave={sessionSourceHome.onSave}
/>
</div>
)}
<p className="mt-2 text-[11px] text-muted-foreground">
{translate(
'auto.components.settings.AgentsPane.f9f127d664',
'Override the binary path or name, and edit the default launch arguments or environment for this agent.'
@@ -902,6 +893,11 @@ export function AgentsPane({
onSaveOverride={(v) => saveOverride(agent.id, v)}
onSaveArgs={(v) => saveAgentArgs(agent.id, v)}
onSaveEnv={(v) => saveAgentEnv(agent.id, v)}
sessionSourceHome={
agent.id === 'codex'
? buildCodexSessionSourceHomeControl(settings, updateSettings)
: undefined
}
/>
))}
</div>
@@ -0,0 +1,108 @@
import { describe, expect, it, vi } from 'vitest'
import type { GlobalSettings } from '../../../../shared/types'
import { buildCodexSessionSourceHomeControl } from './codex-session-source-home-control'
function settingsWith(
overrides: Partial<Pick<GlobalSettings, 'codexSessionSourceHome' | 'localWindowsRuntimeDefault'>>
): Pick<GlobalSettings, 'codexSessionSourceHome' | 'localWindowsRuntimeDefault'> {
return {
codexSessionSourceHome: overrides.codexSessionSourceHome,
localWindowsRuntimeDefault: overrides.localWindowsRuntimeDefault ?? { kind: 'windows-host' }
}
}
describe('buildCodexSessionSourceHomeControl', () => {
it('reads and writes the host override on the host runtime', () => {
const updateSettings = vi.fn()
const control = buildCodexSessionSourceHomeControl(
settingsWith({ codexSessionSourceHome: { host: '/custom/codex' } }),
updateSettings
)
expect(control.runtimeLabel).toBe('~/.codex')
expect(control.value).toBe('/custom/codex')
control.onSave('/new/codex')
expect(updateSettings).toHaveBeenCalledWith({
codexSessionSourceHome: { host: '/new/codex' }
})
})
it('scopes to the selected WSL distro', () => {
const updateSettings = vi.fn()
const control = buildCodexSessionSourceHomeControl(
settingsWith({
codexSessionSourceHome: { wsl: { Ubuntu: '/home/me/.codex' } },
localWindowsRuntimeDefault: { kind: 'wsl', distro: 'Ubuntu' }
}),
updateSettings
)
expect(control.value).toBe('/home/me/.codex')
control.onSave('/home/me/.config/codex')
expect(updateSettings).toHaveBeenCalledWith({
codexSessionSourceHome: { wsl: { Ubuntu: '/home/me/.config/codex' } }
})
})
it('reads a stored WSL value when the reported distro casing differs', () => {
// Stored as "Ubuntu"; the runtime reports "ubuntu". The launch-time resolver
// matches case-insensitively, so the UI must surface the active value too.
const control = buildCodexSessionSourceHomeControl(
settingsWith({
codexSessionSourceHome: { wsl: { Ubuntu: '/home/me/.codex' } },
localWindowsRuntimeDefault: { kind: 'wsl', distro: 'ubuntu' }
}),
vi.fn()
)
expect(control.value).toBe('/home/me/.codex')
})
it('updates the existing WSL key in place instead of creating a duplicate casing', () => {
const updateSettings = vi.fn()
const control = buildCodexSessionSourceHomeControl(
settingsWith({
codexSessionSourceHome: { wsl: { Ubuntu: '/home/me/.codex' } },
localWindowsRuntimeDefault: { kind: 'wsl', distro: 'ubuntu' }
}),
updateSettings
)
control.onSave('/home/me/.config/codex')
// No stray "ubuntu" key alongside "Ubuntu".
expect(updateSettings).toHaveBeenCalledWith({
codexSessionSourceHome: { wsl: { Ubuntu: '/home/me/.config/codex' } }
})
})
it('clears the matching WSL key regardless of casing when reset', () => {
const updateSettings = vi.fn()
const control = buildCodexSessionSourceHomeControl(
settingsWith({
codexSessionSourceHome: { wsl: { Ubuntu: '/home/me/.codex' } },
localWindowsRuntimeDefault: { kind: 'wsl', distro: 'ubuntu' }
}),
updateSettings
)
control.onSave('')
// Removing the only key leaves no dangling wsl object.
expect(updateSettings).toHaveBeenCalledWith({
codexSessionSourceHome: { wsl: undefined }
})
})
it('falls back to the host control when a WSL scope has no selected distro', () => {
const control = buildCodexSessionSourceHomeControl(
settingsWith({
codexSessionSourceHome: { host: '/custom/codex' },
localWindowsRuntimeDefault: { kind: 'wsl', distro: null }
}),
vi.fn()
)
expect(control.runtimeLabel).toBe('~/.codex')
expect(control.value).toBe('/custom/codex')
})
})
@@ -0,0 +1,169 @@
import { useState } from 'react'
import { Info } from 'lucide-react'
import type { GlobalSettings } from '../../../../shared/types'
import { normalizeGlobalWindowsRuntimeDefault } from '../../../../shared/project-execution-runtime'
import { Button } from '../ui/button'
import { Input } from '../ui/input'
import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/tooltip'
import { translate } from '@/i18n/i18n'
export type AgentSessionSourceHomeControl = {
runtimeLabel: string
value: string
onSave: (value: string) => void
}
type UpdateSettings = (updates: Partial<GlobalSettings>) => void | Promise<void>
/**
* Builds the Codex session-history source control scoped to the runtime the
* Agents pane is showing (host or the selected WSL distro), so it mirrors how
* detected agents are scoped. History-only: it never touches auth/config.
*/
// Why: the launch-time resolver matches distro keys case-insensitively, so the
// UI must resolve to the SAME stored key. Otherwise a casing mismatch would show
// an empty override for an active value and, on edit, create a duplicate key.
function findWslSourceHomeKey(
wsl: Record<string, string> | undefined,
distro: string
): string | undefined {
const normalized = distro.trim().toLowerCase()
return Object.keys(wsl ?? {}).find((key) => key.trim().toLowerCase() === normalized)
}
export function buildCodexSessionSourceHomeControl(
settings: Pick<GlobalSettings, 'codexSessionSourceHome' | 'localWindowsRuntimeDefault'>,
updateSettings: UpdateSettings
): AgentSessionSourceHomeControl {
const runtimeScope = normalizeGlobalWindowsRuntimeDefault(settings.localWindowsRuntimeDefault)
const sourceHome = settings.codexSessionSourceHome
// Why: a WSL scope with no selected distro can't target a per-distro history
// home, so fall back to the host control rather than a null distro key.
const wslDistro = runtimeScope.kind === 'wsl' ? runtimeScope.distro?.trim() : undefined
if (wslDistro) {
const existingKey = findWslSourceHomeKey(sourceHome?.wsl, wslDistro)
return {
runtimeLabel: `${wslDistro}: ~/.codex`,
value: (existingKey ? sourceHome?.wsl?.[existingKey] : undefined) ?? '',
// Save under the existing key when one matches (case-insensitively), so
// editing updates it in place instead of adding a differently-cased key.
onSave: (value: string) =>
saveCodexSessionSourceHome(settings, updateSettings, {
runtime: 'wsl',
distro: existingKey ?? wslDistro,
value
})
}
}
return {
runtimeLabel: '~/.codex',
value: sourceHome?.host ?? '',
onSave: (value: string) =>
saveCodexSessionSourceHome(settings, updateSettings, { runtime: 'host', value })
}
}
function saveCodexSessionSourceHome(
settings: Pick<GlobalSettings, 'codexSessionSourceHome'>,
updateSettings: UpdateSettings,
args: { runtime: 'host'; value: string } | { runtime: 'wsl'; distro: string; value: string }
): void {
const current = settings.codexSessionSourceHome ?? {}
const trimmed = args.value.trim()
if (args.runtime === 'host') {
updateSettings({ codexSessionSourceHome: { ...current, host: trimmed || undefined } })
return
}
const nextWsl = { ...current.wsl }
// Why: reuse an existing case-insensitive match so we never leave a stale
// duplicate key behind when the caller passes a differently-cased distro.
const targetKey = findWslSourceHomeKey(nextWsl, args.distro) ?? args.distro
if (trimmed) {
nextWsl[targetKey] = trimmed
} else {
delete nextWsl[targetKey]
}
updateSettings({
codexSessionSourceHome: {
...current,
wsl: Object.keys(nextWsl).length > 0 ? nextWsl : undefined
}
})
}
export function AgentSessionSourceHomeInput({
runtimeLabel,
value,
onSave
}: AgentSessionSourceHomeControl): React.JSX.Element {
const [draft, setDraft] = useState(value)
const commit = (): void => {
onSave(draft.trim())
}
return (
<div className="flex flex-col gap-1">
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
{translate(
'auto.components.settings.AgentsPane.codexSessionSource',
'Codex home to import from'
)}
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
aria-label={translate(
'auto.components.settings.AgentsPane.codexSessionSourceInfo',
'About importing Codex history'
)}
className="grid size-4 place-items-center rounded text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50"
>
<Info className="size-3" />
</button>
</TooltipTrigger>
<TooltipContent side="top" sideOffset={6} className="max-w-xs">
{translate(
'auto.components.settings.AgentsPane.codexSessionSourceTooltip',
'Orca runs Codex in an isolated home. Point this at your existing Codex home to import that session history. Empty uses ~/.codex.'
)}
</TooltipContent>
</Tooltip>
</span>
<div className="flex items-center gap-2">
<Input
value={draft}
onChange={(e) => setDraft(e.target.value)}
onBlur={commit}
onKeyDown={(e) => {
if (e.key === 'Enter') {
commit()
e.currentTarget.blur()
}
if (e.key === 'Escape') {
setDraft(value)
e.currentTarget.blur()
}
}}
placeholder={runtimeLabel}
spellCheck={false}
className="h-7 flex-1 font-mono text-xs"
/>
{value.trim() && (
<Button
type="button"
variant="ghost"
size="xs"
onClick={() => {
onSave('')
setDraft('')
}}
className="h-7 shrink-0 text-xs text-muted-foreground hover:text-foreground"
>
{translate('auto.components.settings.AgentsPane.5200dac9da', 'Reset')}
</Button>
)}
</div>
</div>
)
}
@@ -968,6 +968,34 @@ describe('connectPanePty', () => {
)
})
it('drops keystrokes while the replay guard is engaged, then forwards once it releases', async () => {
// Regression for the cold-restore reattach lockout: handleReattachResult's
// replay writes engaged the per-pane replay guard, and because xterm's parse
// callback never fired for the just-mounted pane the counter stuck non-zero.
// The onData handler then dropped EVERY keystroke — a live but unresponsive
// pane ("can't type after reconnecting"). This locks in the drop-site
// contract: engaged guard suppresses input, released guard forwards it.
const { connectPanePty } = await import('./pty-connection')
const pane = createPane(1)
const transport = createMockTransport('ssh:ssh-1@@pty-1')
transportFactoryQueue.push(transport)
const deps = createDeps()
connectPanePty(pane as never, createManager(1, 1) as never, deps as never)
await flushAsyncTicks()
transport.sendInput.mockClear()
// Engaged (as a stuck reattach would leave it): input must be suppressed.
deps.replayingPanesRef.current.set(pane.id, 3)
sendTerminalInputThroughPane(pane, 'echo hi\r')
expect(transport.sendInput).not.toHaveBeenCalled()
// Released (via the guard's fallback or parse completion): input flows again.
deps.replayingPanesRef.current.delete(pane.id)
sendTerminalInputThroughPane(pane, 'echo hi\r')
expect(transport.sendInput).toHaveBeenCalledWith('echo hi\r')
})
it('normalizes Pi-compatible remote runtime status to OMP after typed omp command', async () => {
const { connectPanePty } = await import('./pty-connection')
enableActiveRuntimeEnvironment()
@@ -4100,7 +4128,11 @@ describe('connectPanePty', () => {
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] },
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }]
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }],
// Why: startup delivery assumes a live connection; a disconnected
// target now routes through the deferred-connect gate instead of
// spawning synchronously.
sshConnectionStates: new Map([['ssh-conn-1', { status: 'connected' }]])
}
const pane = createPane(1)
@@ -4150,7 +4182,11 @@ describe('connectPanePty', () => {
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] },
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }]
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }],
// Why: startup delivery assumes a live connection; a disconnected
// target now routes through the deferred-connect gate instead of
// spawning synchronously.
sshConnectionStates: new Map([['ssh-conn-1', { status: 'connected' }]])
}
const pane = createPane(1)
@@ -4288,7 +4324,11 @@ describe('connectPanePty', () => {
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] },
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }]
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }],
// Why: startup delivery assumes a live connection; a disconnected
// target now routes through the deferred-connect gate instead of
// spawning synchronously.
sshConnectionStates: new Map([['ssh-conn-1', { status: 'connected' }]])
}
const pane = createPane(1)
@@ -4343,7 +4383,11 @@ describe('connectPanePty', () => {
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] },
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }]
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }],
// Why: startup delivery assumes a live connection; a disconnected
// target now routes through the deferred-connect gate instead of
// spawning synchronously.
sshConnectionStates: new Map([['ssh-conn-1', { status: 'connected' }]])
}
const pane = createPane(1)
@@ -4398,7 +4442,11 @@ describe('connectPanePty', () => {
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] },
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }]
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }],
// Why: startup delivery assumes a live connection; a disconnected
// target now routes through the deferred-connect gate instead of
// spawning synchronously.
sshConnectionStates: new Map([['ssh-conn-1', { status: 'connected' }]])
}
const pane = createPane(1)
@@ -4450,7 +4498,11 @@ describe('connectPanePty', () => {
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] },
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }]
repos: [{ id: 'repo1', connectionId: 'ssh-conn-1' }],
// Why: startup delivery assumes a live connection; a disconnected
// target now routes through the deferred-connect gate instead of
// spawning synchronously.
sshConnectionStates: new Map([['ssh-conn-1', { status: 'connected' }]])
}
const wrapperCommand = 'bash -lc wait-for-setup-wrapper'
@@ -4921,6 +4973,67 @@ describe('connectPanePty', () => {
expect(deps.updateTabPtyId).toHaveBeenCalledWith('tab-1', 'fresh-pty')
})
it('reattaches via the tab-level SSH pty id when deferred bookkeeping missed the tab', async () => {
// Why: restore can miss the deferred maps (e.g. activeConnectionIdsAtShutdown
// wasn't persisted). The tab's own app SSH pty id must still drive a
// connect-then-reattach instead of a fresh spawn into a missing provider.
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport()
transportFactoryQueue.push(transport)
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: 'ssh:conn-1@@pty-7' }] },
ptyIdsByTabId: { 'tab-1': [] },
repos: [{ id: 'repo1', connectionId: 'conn-1' }],
sshConnectionStates: new Map()
} as StoreState
const pane = createPane(1)
const manager = createManager(1)
const deps = createDeps()
connectPanePty(pane as never, manager as never, deps as never)
await flushAsyncTicks(12)
const windowApi = (globalThis as unknown as { window: { api: { ssh: { connect: unknown } } } })
.window.api
expect(windowApi.ssh.connect).toHaveBeenCalledWith({ targetId: 'conn-1' })
expect(transport.connect).toHaveBeenCalledWith(
expect.objectContaining({ sessionId: 'ssh:conn-1@@pty-7' })
)
expect(deps.onPtyErrorRef.current).not.toHaveBeenCalled()
})
it('connects a disconnected SSH target before fresh-spawning instead of erroring', async () => {
// Why: spawning against a disconnected target throws "No PTY provider"
// and strands the pane behind a toast that never retries.
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport('fresh-ssh-pty')
transportFactoryQueue.push(transport)
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] },
ptyIdsByTabId: { 'tab-1': [] },
repos: [{ id: 'repo1', connectionId: 'conn-1' }],
sshConnectionStates: new Map()
} as StoreState
const pane = createPane(1)
const manager = createManager(1)
const deps = createDeps()
connectPanePty(pane as never, manager as never, deps as never)
// Why: no spawn may fire before the SSH connection is established.
expect(transport.connect).not.toHaveBeenCalled()
await flushAsyncTicks(12)
const windowApi = (globalThis as unknown as { window: { api: { ssh: { connect: unknown } } } })
.window.api
expect(windowApi.ssh.connect).toHaveBeenCalledWith({ targetId: 'conn-1' })
expect(transport.connect).toHaveBeenCalledWith(
expect.not.objectContaining({ sessionId: expect.any(String) })
)
expect(deps.onPtyErrorRef.current).not.toHaveBeenCalled()
})
it('spawns a fresh PTY when a non-deferred SSH reattach reports expired via onError', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport()
@@ -88,6 +88,7 @@ import { makePaneKey, parseLegacyNumericPaneKey } from '../../../../shared/stabl
import { createTerminalCommandLifecycle } from './terminal-command-lifecycle'
import { createPaneForegroundAgentTracker } from './pane-foreground-agent-tracker'
import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id'
import { resolveSshPaneConnectGate } from './ssh-pane-connect-gate'
import { dispatchTerminalCommandFinishedEvent } from '@/hooks/terminal-command-finished-event'
import { e2eConfig } from '@/lib/e2e-config'
import {
@@ -5193,6 +5194,13 @@ export function connectPanePty(
}
observeStartupDraftPasteReadiness(data)
resetHiddenOutputRestoreIfPtyChanged()
if (meta?.droppedBacklog === true) {
// Why: main trimmed this pty's unsent backlog (the renderer was
// background-throttled/frozen and stopped ACKing). Rebuild the dropped
// span from the main headless snapshot — same recovery the renderer's
// own 2 MB scheduler overflow uses. No-op cost when already visible+synced.
markHiddenOutputRestoreNeeded()
}
respondToTerminalPixelSizeQueries(data)
observeTerminalBracketedPasteModeOutput(pane.terminal, data)
for (const link of observeTerminalGitHubPRLink(data)) {
@@ -5463,13 +5471,23 @@ export function connectPanePty(
deps.restoredLeafId && deps.restoredPtyIdByLeafId
? (deps.restoredPtyIdByLeafId[deps.restoredLeafId] ?? null)
: null
const pendingSessionId =
restoredLeafSessionId ?? storeState.deferredSshSessionIdsByTabId[deps.tabId]
const isDeferredTarget = storeState.deferredSshReconnectTargets.includes(connectionId)
const gate = resolveSshPaneConnectGate({
connectionId,
sshStatus: storeState.sshConnectionStates.get(connectionId)?.status,
isDeferredTarget: storeState.deferredSshReconnectTargets.includes(connectionId),
restoredLeafSessionId,
deferredTabSessionId: storeState.deferredSshSessionIdsByTabId[deps.tabId],
tabPtyId: storeState.tabsByWorktree[deps.worktreeId]?.find((t) => t.id === deps.tabId)
?.ptyId,
hasLeafSessionMap: Boolean(
deps.restoredPtyIdByLeafId && Object.keys(deps.restoredPtyIdByLeafId).length > 0
)
})
const pendingSessionId = gate.pendingSessionId
console.warn(
`[pty-connection] SSH tab=${deps.tabId} connectionId=${connectionId} pendingSessionId=${pendingSessionId} isDeferredTarget=${isDeferredTarget}`
`[pty-connection] SSH tab=${deps.tabId} connectionId=${connectionId} pendingSessionId=${pendingSessionId} sshConnected=${gate.sshConnected}`
)
if (pendingSessionId || isDeferredTarget) {
if (gate.enterDeferredFlow) {
void (async () => {
// Why: if the target requires a passphrase/password and no credential
// is cached yet, auto-firing ssh.connect would surprise the user —
@@ -25,6 +25,9 @@ export type PtyDataMeta = {
seq?: number
rawLength?: number
background?: boolean
/** Main trimmed this pty's unsent backlog past its cap; the handler should
* rebuild the dropped span from the main headless snapshot. */
droppedBacklog?: boolean
}
export const ptyDataHandlers = new Map<string, (data: string, meta?: PtyDataMeta) => void>()
@@ -120,6 +123,10 @@ export function ensurePtyDispatcher(): void {
meta ??= {}
meta.background = true
}
if (payload.droppedBacklog === true) {
meta ??= {}
meta.droppedBacklog = true
}
const handler = ptyDataHandlers.get(payload.id)
if (handler) {
handler(payload.data, meta)
@@ -1324,6 +1324,50 @@ describe('createIpcPtyTransport', () => {
expect(onError).not.toHaveBeenCalled()
})
it('recovers a stale cross-connection SSH reattach as expired instead of a red error toast', async () => {
// Why: a restored SSH pty id embeds the connection it was created under. If
// the pane reattaches under a different connection the main-side router
// rejects with "belongs to SSH connection" — that session is unreachable, so
// we drop it (sessionExpired) and spawn fresh rather than surfacing a crash.
const { createIpcPtyTransport } = await import('./pty-transport')
const spawnMock = vi
.fn()
.mockRejectedValue(
new Error(
'PTY ssh:ssh-1779863656395-57g1q1@@pty-3 belongs to SSH connection "ssh-1779863656395-57g1q1"'
)
)
;(globalThis as { window: typeof window }).window = {
...originalWindow,
api: {
...originalWindow?.api,
pty: {
...originalWindow?.api?.pty,
spawn: spawnMock,
write: vi.fn(),
resize: vi.fn(),
kill: vi.fn(),
onData: vi.fn(() => () => {}),
onReplay: vi.fn(() => () => {}),
onExit: vi.fn(() => () => {})
}
}
} as unknown as typeof window
const onError = vi.fn()
const result = await createIpcPtyTransport({ connectionId: 'ssh-other' }).connect({
url: '',
sessionId: 'ssh:ssh-1779863656395-57g1q1@@pty-3',
callbacks: { onError }
})
expect(onError).not.toHaveBeenCalled()
expect(result).toEqual({
id: 'ssh:ssh-1779863656395-57g1q1@@pty-3',
sessionExpired: true
})
})
it('surfaces terminal session state save failures without the Electron IPC wrapper', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const wrappedMessage = `Error invoking remote method 'pty:spawn': Error: ${createTerminalSessionStateSaveFailureMessage()}`
@@ -57,6 +57,12 @@ export type {
export { extractLastOscTitle } from '../../../../shared/agent-detection'
const SSH_SESSION_EXPIRED_ERROR = 'SSH_SESSION_EXPIRED'
// Why: an app SSH PTY id embeds the connection it was created under. When a pane
// restored after a workspace/host change reattaches a session that belongs to a
// *different* connection, the main-side id router rejects it with this phrase.
// That session is unreachable from this pane, so it is stale like an expired one
// — recover by spawning fresh rather than surfacing a red "file an issue" crash.
const SSH_PTY_CONNECTION_MISMATCH_MARKER = 'belongs to SSH connection'
const STALE_TITLE_TIMEOUT = 3000 // ms before stale working title is cleared
const MAX_PTY_SIDE_EFFECTS_PER_DRAIN = 64
@@ -677,7 +683,12 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra
return spawnResult.id
} catch (err) {
const msg = extractIpcErrorMessage(err, err instanceof Error ? err.message : String(err))
if (connectionId && options.sessionId && msg.includes(SSH_SESSION_EXPIRED_ERROR)) {
if (
connectionId &&
options.sessionId &&
(msg.includes(SSH_SESSION_EXPIRED_ERROR) ||
msg.includes(SSH_PTY_CONNECTION_MISMATCH_MARKER))
) {
return {
id: options.sessionId,
sessionExpired: true
@@ -1,6 +1,11 @@
import { describe, expect, it } from 'vitest'
import { describe, expect, it, vi } from 'vitest'
import type { ManagedPane } from '@/lib/pane-manager/pane-manager'
import { isPaneReplaying, replayIntoTerminal, type ReplayingPanesRef } from './replay-guard'
import {
isPaneReplaying,
replayIntoTerminal,
replayIntoTerminalAsync,
type ReplayingPanesRef
} from './replay-guard'
function makeRef(): ReplayingPanesRef {
return { current: new Map() } as ReplayingPanesRef
@@ -136,6 +141,72 @@ describe('replay-guard', () => {
expect(ref.current.has(1)).toBe(false)
})
it('auto-releases the guard when xterm never fires the parse callback', () => {
// Repro of the cold-restore reattach lockout: handleReattachResult replays
// three chunks into a just-mounted / offscreen pane whose terminal never
// flushes, so xterm's parse callback never runs and the counter would stay
// pinned at 3 — isPaneReplaying() stuck true drops EVERY keystroke. The
// fallback must release the guard so input is not swallowed forever.
vi.useFakeTimers()
try {
const ref = makeRef()
const { pane } = makeFakePane(1)
replayIntoTerminal(pane, ref, '\x1b[2J\x1b[3J\x1b[H')
replayIntoTerminal(pane, ref, 'scrollback bytes')
replayIntoTerminal(pane, ref, '--- session restored ---')
expect(isPaneReplaying(ref, 1)).toBe(true)
// Never flush — simulate the missing parse callback for an unflushed pane.
vi.advanceTimersByTime(1000)
expect(isPaneReplaying(ref, 1)).toBe(false)
expect(ref.current.has(1)).toBe(false)
} finally {
vi.useRealTimers()
}
})
it('parse completion cancels the fallback without over-releasing', () => {
vi.useFakeTimers()
try {
const ref = makeRef()
const { pane, terminal } = makeFakePane(1)
replayIntoTerminal(pane, ref, 'a')
replayIntoTerminal(pane, ref, 'b')
terminal.flush()
expect(isPaneReplaying(ref, 1)).toBe(false)
// The already-cancelled fallback must not fire and underflow the counter.
vi.advanceTimersByTime(1000)
expect(isPaneReplaying(ref, 1)).toBe(false)
expect(ref.current.has(1)).toBe(false)
} finally {
vi.useRealTimers()
}
})
it('async replay resolves even when the parse callback never fires', async () => {
vi.useFakeTimers()
try {
const ref = makeRef()
const { pane } = makeFakePane(1)
let resolved = false
const promise = replayIntoTerminalAsync(pane, ref, 'x').then(() => {
resolved = true
})
expect(isPaneReplaying(ref, 1)).toBe(true)
await vi.advanceTimersByTimeAsync(1000)
await promise
expect(resolved).toBe(true)
expect(isPaneReplaying(ref, 1)).toBe(false)
} finally {
vi.useRealTimers()
}
})
it('schedules a follow-up repaint for replayed cursor restores', () => {
const scheduledFrames: FrameRequestCallback[] = []
const originalRequestAnimationFrame = globalThis.requestAnimationFrame
@@ -27,10 +27,57 @@ import { writeForegroundTerminalChunk } from '@/lib/pane-manager/pane-terminal-f
export type ReplayingPanesRef = React.RefObject<Map<number, number>>
// Why: the guard normally releases in xterm's write-completion callback, but
// that callback never fires for a pane whose terminal has not been flushed —
// e.g. a cold-restore reattach that replays into a just-mounted / offscreen
// pane. Without a ceiling the counter leaks, isPaneReplaying() stays true, and
// the onData handler silently drops EVERY keystroke (the pane looks alive but
// ignores input). Release deterministically after this bound so the guard
// always clears; in the normal path onParsed fires within milliseconds and
// cancels it first. Tradeoff: if the callback is lost and the pane parses the
// replayed buffer only after this bound elapses (e.g. rendering resumes long
// after restore), xterm's auto-replies to any device queries in that buffer can
// leak to the shell as input. Accepted as strictly preferable to a permanent
// input lockout, and bounded by the ~100 KB replay cap.
const REPLAY_GUARD_RELEASE_FALLBACK_MS = 1000
export function isPaneReplaying(ref: ReplayingPanesRef, paneId: number): boolean {
return (ref.current.get(paneId) ?? 0) > 0
}
/** Engage the per-pane replay guard and return a `finish` callback that
* releases it exactly once. The guard also auto-releases after
* REPLAY_GUARD_RELEASE_FALLBACK_MS so a missing xterm parse callback can never
* strand it engaged. `onReleased` runs once when the guard actually releases
* (via `finish` or the fallback), so async callers can settle either way. */
function engageReplayGuard(
replayingPanesRef: ReplayingPanesRef,
paneId: number,
onReleased?: () => void
): () => void {
const map = replayingPanesRef.current
map.set(paneId, (map.get(paneId) ?? 0) + 1)
let released = false
const release = (): void => {
if (released) {
return
}
released = true
const remaining = (map.get(paneId) ?? 1) - 1
if (remaining <= 0) {
map.delete(paneId)
} else {
map.set(paneId, remaining)
}
onReleased?.()
}
const fallback = setTimeout(release, REPLAY_GUARD_RELEASE_FALLBACK_MS)
return () => {
clearTimeout(fallback)
release()
}
}
/** Writes `data` into the pane's terminal with the replay guard engaged,
* so xterm's auto-replies to embedded query sequences do not leak to the
* shell as input. The counter increments/decrements so nested replays
@@ -43,22 +90,13 @@ export function replayIntoTerminal(
if (!data) {
return
}
const map = replayingPanesRef.current
map.set(pane.id, (map.get(pane.id) ?? 0) + 1)
const onParsed = (): void => {
const remaining = (map.get(pane.id) ?? 1) - 1
if (remaining <= 0) {
map.delete(pane.id)
} else {
map.set(pane.id, remaining)
}
}
const finishReplay = engageReplayGuard(replayingPanesRef, pane.id)
// Why: hidden/snapshot replay bypasses the live foreground write path, but
// WebGL/canvas renderers still need a post-parse repaint to drop stale cells.
writeForegroundTerminalChunk(pane.terminal, data, {
forceViewportRefresh: true,
followupViewportRefresh: true,
onParsed
onParsed: finishReplay
})
}
@@ -70,21 +108,15 @@ export function replayIntoTerminalAsync(
if (!data) {
return Promise.resolve()
}
const map = replayingPanesRef.current
map.set(pane.id, (map.get(pane.id) ?? 0) + 1)
return new Promise((resolve) => {
// Why: settle the promise when the guard releases — via parse completion or
// the fallback — so an awaiting caller never hangs if xterm's callback for a
// just-mounted/offscreen pane never arrives.
const finishReplay = engageReplayGuard(replayingPanesRef, pane.id, resolve)
writeForegroundTerminalChunk(pane.terminal, data, {
forceViewportRefresh: true,
followupViewportRefresh: true,
onParsed: () => {
const remaining = (map.get(pane.id) ?? 1) - 1
if (remaining <= 0) {
map.delete(pane.id)
} else {
map.set(pane.id, remaining)
}
resolve()
}
onParsed: finishReplay
})
})
}
@@ -0,0 +1,87 @@
import { describe, expect, it } from 'vitest'
import { resolveSshPaneConnectGate } from './ssh-pane-connect-gate'
const BASE = {
connectionId: 'conn-1',
sshStatus: undefined as string | undefined,
isDeferredTarget: false,
restoredLeafSessionId: null as string | null,
deferredTabSessionId: undefined as string | undefined,
tabPtyId: null as string | null,
hasLeafSessionMap: false
}
describe('resolveSshPaneConnectGate', () => {
it('routes a disconnected target through the deferred flow even without a session id', () => {
const gate = resolveSshPaneConnectGate(BASE)
expect(gate).toEqual({ pendingSessionId: null, enterDeferredFlow: true, sshConnected: false })
})
it('skips the deferred flow for a connected target with no restore state', () => {
const gate = resolveSshPaneConnectGate({ ...BASE, sshStatus: 'connected' })
expect(gate).toEqual({ pendingSessionId: null, enterDeferredFlow: false, sshConnected: true })
})
it('falls back to the tab-level app SSH pty id when the deferred maps missed the tab', () => {
const gate = resolveSshPaneConnectGate({ ...BASE, tabPtyId: 'ssh:conn-1@@pty-7' })
expect(gate.pendingSessionId).toBe('ssh:conn-1@@pty-7')
expect(gate.enterDeferredFlow).toBe(true)
})
it('ignores a tab pty id that belongs to a different connection', () => {
const gate = resolveSshPaneConnectGate({ ...BASE, tabPtyId: 'ssh:conn-2@@pty-7' })
expect(gate.pendingSessionId).toBeNull()
})
it('ignores the tab-level fallback when a per-leaf session map exists', () => {
// Why: every leaf of a split mounts its own pane; the tab-level id must
// not be reattached by all of them.
const gate = resolveSshPaneConnectGate({
...BASE,
tabPtyId: 'ssh:conn-1@@pty-7',
hasLeafSessionMap: true
})
expect(gate.pendingSessionId).toBeNull()
})
it('ignores the tab-level fallback once connected — live panes attach normally', () => {
const gate = resolveSshPaneConnectGate({
...BASE,
sshStatus: 'connected',
tabPtyId: 'ssh:conn-1@@pty-7'
})
expect(gate.pendingSessionId).toBeNull()
expect(gate.enterDeferredFlow).toBe(false)
})
it('prefers the restored leaf session, then the deferred map, then the fallback', () => {
const gate = resolveSshPaneConnectGate({
...BASE,
restoredLeafSessionId: 'ssh:conn-1@@pty-1',
deferredTabSessionId: 'ssh:conn-1@@pty-2',
tabPtyId: 'ssh:conn-1@@pty-3'
})
expect(gate.pendingSessionId).toBe('ssh:conn-1@@pty-1')
})
it('still enters the deferred flow for deferred targets that already connected', () => {
// Why: connecting via Settings does not remove the target from the
// deferred list; the gate consumes it and reattaches.
const gate = resolveSshPaneConnectGate({
...BASE,
sshStatus: 'connected',
isDeferredTarget: true
})
expect(gate.enterDeferredFlow).toBe(true)
})
it('does not force a connect for runtime-owned targets', () => {
// Why: their relay health is owned by the runtime layer; users cannot
// connect to them directly, so a reconnect flow would strand the pane.
const gate = resolveSshPaneConnectGate({
...BASE,
connectionId: 'runtime-ssh-env-1'
})
expect(gate.enterDeferredFlow).toBe(false)
})
})
@@ -0,0 +1,51 @@
import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id'
import { isRuntimeOwnedSshTargetId } from '../../../../shared/execution-host'
export type SshPaneConnectGate = {
/** Session the pane should reattach after connecting (null → fresh spawn). */
pendingSessionId: string | null
/** True when the pane must run the deferred-connect flow before any spawn. */
enterDeferredFlow: boolean
sshConnected: boolean
}
// Why: an SSH pane must never call pty:spawn while its target's provider is
// unregistered — main rejects with "No PTY provider" and the pane strands
// behind an error toast that never retries. This decides, from restore
// bookkeeping plus the live connection state, whether the pane needs the
// deferred-connect flow first and which session it should reattach.
export function resolveSshPaneConnectGate(input: {
connectionId: string
sshStatus: string | undefined
isDeferredTarget: boolean
restoredLeafSessionId: string | null
deferredTabSessionId: string | undefined
tabPtyId: string | null | undefined
hasLeafSessionMap: boolean
}): SshPaneConnectGate {
const sshConnected = input.sshStatus === 'connected'
// Why: the deferred maps can miss a tab (e.g. activeConnectionIdsAtShutdown
// wasn't persisted, so restore registered no deferred target). The tab's own
// restored app SSH pty id still names the session — reattach it rather than
// spawning a replacement shell. Skipped when a per-leaf session map exists:
// leaves carry their own ids and the tab-level id must not be attached by
// every leaf of a split.
const fallbackTabSessionId =
!sshConnected &&
!input.hasLeafSessionMap &&
input.tabPtyId &&
parseAppSshPtyId(input.tabPtyId)?.connectionId === input.connectionId
? input.tabPtyId
: null
const pendingSessionId =
input.restoredLeafSessionId ?? input.deferredTabSessionId ?? fallbackTabSessionId ?? null
// Why: runtime-owned targets are excluded — their relay health is owned by
// the runtime layer and users cannot connect to them directly.
const needsConnectBeforeSpawn = !sshConnected && !isRuntimeOwnedSshTargetId(input.connectionId)
return {
pendingSessionId,
enterDeferredFlow:
Boolean(pendingSessionId) || input.isDeferredTarget || needsConnectBeforeSpawn,
sshConnected
}
}
@@ -0,0 +1,171 @@
import { describe, expect, it } from 'vitest'
import {
armTerminalImePendingCandidateKeyRelease,
clearTerminalImePendingCandidateKeyRelease,
createTerminalImePendingCandidateKeyReleases,
isTerminalImeCandidateSelectionKeyEvent,
shouldApplyTerminalImePendingCandidateKeyRelease
} from './terminal-ime-candidate-key-release-guard'
import { TERMINAL_IME_CANDIDATE_GUARD_POST_COMPOSITION_MS } from './terminal-ime-composition-tracker'
import { event } from './xterm-bypass-event-fixture'
describe('terminal IME candidate key release guard', () => {
it('recognizes only unmodified Space and digit candidate selectors', () => {
expect(isTerminalImeCandidateSelectionKeyEvent(event({ key: ' ' }))).toBe(true)
expect(isTerminalImeCandidateSelectionKeyEvent(event({ key: '2' }))).toBe(true)
expect(isTerminalImeCandidateSelectionKeyEvent(event({ key: 'a' }))).toBe(false)
expect(isTerminalImeCandidateSelectionKeyEvent(event({ key: ' ', ctrlKey: true }))).toBe(false)
// Shift+Space is fcitx's full-/half-width toggle, not a candidate selector.
expect(isTerminalImeCandidateSelectionKeyEvent(event({ key: ' ', shiftKey: true }))).toBe(false)
})
it('arms a pending release guard from a suppressed candidate keydown', () => {
const releases = createTerminalImePendingCandidateKeyReleases()
armTerminalImePendingCandidateKeyRelease(releases, event({ key: '2' }), 10)
expect(releases.get('2')).toBe(10 + TERMINAL_IME_CANDIDATE_GUARD_POST_COMPOSITION_MS)
})
it('does not arm from keyup, non-candidate, or Shift-modified keys', () => {
const releases = createTerminalImePendingCandidateKeyReleases()
armTerminalImePendingCandidateKeyRelease(releases, event({ type: 'keyup', key: '2' }), 10)
armTerminalImePendingCandidateKeyRelease(releases, event({ key: 'a' }), 10)
armTerminalImePendingCandidateKeyRelease(releases, event({ key: ' ', shiftKey: true }), 10)
expect(releases.size).toBe(0)
})
it('guards the matching keypress and keyup after insertText clears the tracker', () => {
const releases = createTerminalImePendingCandidateKeyReleases()
armTerminalImePendingCandidateKeyRelease(releases, event({ key: ' ' }), 10)
expect(
shouldApplyTerminalImePendingCandidateKeyRelease(
event({ type: 'keypress', key: ' ' }),
releases,
20
)
).toBe(true)
expect(
shouldApplyTerminalImePendingCandidateKeyRelease(
event({ type: 'keyup', key: ' ' }),
releases,
20
)
).toBe(true)
})
it('does not guard fresh keydowns, other keys, modified keypresses, or expired keypresses', () => {
const releases = createTerminalImePendingCandidateKeyReleases()
armTerminalImePendingCandidateKeyRelease(releases, event({ key: '2' }), 10)
expect(shouldApplyTerminalImePendingCandidateKeyRelease(event({ key: '2' }), releases, 20)).toBe(
false
)
expect(
shouldApplyTerminalImePendingCandidateKeyRelease(event({ type: 'keyup', key: '3' }), releases, 20)
).toBe(false)
expect(
shouldApplyTerminalImePendingCandidateKeyRelease(
event({ type: 'keypress', key: '2', ctrlKey: true }),
releases,
20
)
).toBe(false)
expect(
shouldApplyTerminalImePendingCandidateKeyRelease(
event({ type: 'keypress', key: '2' }),
releases,
10 + TERMINAL_IME_CANDIDATE_GUARD_POST_COMPOSITION_MS + 1
)
).toBe(false)
expect(
shouldApplyTerminalImePendingCandidateKeyRelease(
event({ type: 'keyup', key: '2' }),
releases,
10 + TERMINAL_IME_CANDIDATE_GUARD_POST_COMPOSITION_MS + 1
)
).toBe(true)
})
it('guards held-key repeat keydowns while the release is pending, even past expiry', () => {
const releases = createTerminalImePendingCandidateKeyReleases()
armTerminalImePendingCandidateKeyRelease(releases, event({ key: '2' }), 10)
// Linux auto-repeat delay (~500ms) outlives the 250ms guard window; the
// held selector's repeats must stay suppressed until its keyup.
expect(
shouldApplyTerminalImePendingCandidateKeyRelease(
event({ key: '2', repeat: true }),
releases,
10 + TERMINAL_IME_CANDIDATE_GUARD_POST_COMPOSITION_MS + 500
)
).toBe(true)
})
it('does not guard repeat keydowns without a pending release for that key', () => {
const releases = createTerminalImePendingCandidateKeyReleases()
armTerminalImePendingCandidateKeyRelease(releases, event({ key: '2' }), 10)
expect(
shouldApplyTerminalImePendingCandidateKeyRelease(
event({ key: '3', repeat: true }),
releases,
20
)
).toBe(false)
expect(
shouldApplyTerminalImePendingCandidateKeyRelease(
event({ key: '2', repeat: true, ctrlKey: true }),
releases,
20
)
).toBe(false)
})
it('clears a stale pending release on a fresh non-repeat keydown but not on repeats', () => {
const releases = createTerminalImePendingCandidateKeyReleases()
armTerminalImePendingCandidateKeyRelease(releases, event({ key: '2' }), 10)
clearTerminalImePendingCandidateKeyRelease(releases, event({ key: '2', repeat: true }))
expect(releases.has('2')).toBe(true)
// A new physical press means the prior keyup was missed (focus change
// mid-hold); its stale entry must not guard the new press's repeats.
clearTerminalImePendingCandidateKeyRelease(releases, event({ key: '2' }))
expect(releases.has('2')).toBe(false)
})
it('guards a pending matching keyup even if modifier state changed after keydown', () => {
const releases = createTerminalImePendingCandidateKeyReleases()
armTerminalImePendingCandidateKeyRelease(releases, event({ key: '2' }), 10)
expect(
shouldApplyTerminalImePendingCandidateKeyRelease(
event({ type: 'keyup', key: '2', shiftKey: true }),
releases,
10 + TERMINAL_IME_CANDIDATE_GUARD_POST_COMPOSITION_MS + 1
)
).toBe(true)
})
it('clears on the matching keyup', () => {
const releases = createTerminalImePendingCandidateKeyReleases()
armTerminalImePendingCandidateKeyRelease(releases, event({ key: '2' }), 10)
clearTerminalImePendingCandidateKeyRelease(releases, event({ type: 'keypress', key: '2' }))
expect(releases.has('2')).toBe(true)
clearTerminalImePendingCandidateKeyRelease(releases, event({ type: 'keyup', key: '3' }))
expect(releases.has('2')).toBe(true)
clearTerminalImePendingCandidateKeyRelease(releases, event({ type: 'keyup', key: '2' }))
expect(releases.has('2')).toBe(false)
})
it('tracks overlapping candidate keys independently so each keyup clears its own guard', () => {
const releases = createTerminalImePendingCandidateKeyReleases()
// Second candidate keydown arrives before the first key's keyup.
armTerminalImePendingCandidateKeyRelease(releases, event({ key: '2' }), 10)
armTerminalImePendingCandidateKeyRelease(releases, event({ key: '3' }), 12)
expect(
shouldApplyTerminalImePendingCandidateKeyRelease(event({ type: 'keyup', key: '2' }), releases, 20)
).toBe(true)
expect(
shouldApplyTerminalImePendingCandidateKeyRelease(event({ type: 'keyup', key: '3' }), releases, 20)
).toBe(true)
// The first key's keyup no longer strands the second key's pending release.
clearTerminalImePendingCandidateKeyRelease(releases, event({ type: 'keyup', key: '2' }))
expect(releases.has('3')).toBe(true)
clearTerminalImePendingCandidateKeyRelease(releases, event({ type: 'keyup', key: '3' }))
expect(releases.size).toBe(0)
})
})
@@ -0,0 +1,94 @@
import type { XtermBypassEvent } from './xterm-bypass-policy'
import { TERMINAL_IME_CANDIDATE_GUARD_POST_COMPOSITION_MS } from './terminal-ime-composition-tracker'
// Why: candidate keys can overlap (a second selector keydown before the first
// keyup), so pending releases are tracked per key rather than in one slot;
// otherwise an overwritten key's keyup can no longer clear its own guard.
export type TerminalImePendingCandidateKeyReleases = Map<string, number>
// Why: Sogou/fcitx can deliver candidate-selection keys as plain key events
// (#7543: digit selection inserts only the digit). While the IME owns them,
// they must not reach xterm's encoders or Chromium's default text insertion.
const TERMINAL_IME_CANDIDATE_SELECTION_KEYS = new Set([
' ',
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9'
])
function isTerminalImeCandidateSelectionKey(key: string): boolean {
return TERMINAL_IME_CANDIDATE_SELECTION_KEYS.has(key)
}
export function isTerminalImeCandidateSelectionKeyEvent(event: XtermBypassEvent): boolean {
// Modified chords are never candidate selectors: Ctrl/Meta/Alt are IME
// toggles, and Shift+Space is fcitx's full-/half-width width toggle.
if (event.ctrlKey || event.metaKey || event.altKey || event.shiftKey) {
return false
}
return isTerminalImeCandidateSelectionKey(event.key)
}
export function createTerminalImePendingCandidateKeyReleases(): TerminalImePendingCandidateKeyReleases {
return new Map()
}
export function armTerminalImePendingCandidateKeyRelease(
releases: TerminalImePendingCandidateKeyReleases,
event: XtermBypassEvent,
now: number
): void {
if (event.type !== 'keydown' || !isTerminalImeCandidateSelectionKeyEvent(event)) {
return
}
releases.set(event.key, now + TERMINAL_IME_CANDIDATE_GUARD_POST_COMPOSITION_MS)
}
export function shouldApplyTerminalImePendingCandidateKeyRelease(
event: XtermBypassEvent,
releases: TerminalImePendingCandidateKeyReleases,
now: number
): boolean {
if (event.type === 'keydown') {
// Why: key auto-repeat outlives the 250ms window (Linux repeat delay is
// ~500ms), so a held selector's repeats stay owned by its pending release;
// a fresh press means the prior keyup was missed and the entry is stale.
return (
event.repeat === true &&
isTerminalImeCandidateSelectionKeyEvent(event) &&
releases.has(event.key)
)
}
if (event.type === 'keyup') {
// Why: keyup modifier flags can reflect keys pressed after the original
// selector keydown, so release suppression matches only the pending key.
return isTerminalImeCandidateSelectionKey(event.key) && releases.has(event.key)
}
if (!isTerminalImeCandidateSelectionKeyEvent(event)) {
return false
}
const expiresAt = releases.get(event.key)
if (expiresAt === undefined) {
return false
}
return now <= expiresAt
}
export function clearTerminalImePendingCandidateKeyRelease(
releases: TerminalImePendingCandidateKeyReleases,
event: XtermBypassEvent
): void {
// Why: a non-repeat keydown is a new physical press, so any surviving entry
// for that key lost its keyup (focus change mid-hold) and must not guard the
// new press's repeats. Callers clear before arming.
if (event.type === 'keyup' || (event.type === 'keydown' && event.repeat !== true)) {
releases.delete(event.key)
}
}
@@ -0,0 +1,167 @@
// @vitest-environment happy-dom
import { describe, expect, it } from 'vitest'
import {
installTerminalImeCompositionTracker,
TERMINAL_IME_CANDIDATE_GUARD_POST_COMPOSITION_MS,
TERMINAL_IME_CANDIDATE_GUARD_STALE_COMPOSITION_EXPIRY_MS,
type TerminalImeCompositionTracker
} from './terminal-ime-composition-tracker'
type TrackerHarness = {
tracker: TerminalImeCompositionTracker
element: HTMLElement
advance: (ms: number) => void
composition: (type: 'compositionstart' | 'compositionupdate' | 'compositionend', data: string) => void
input: (inputType: string) => void
blur: () => void
}
function installTracker(): TrackerHarness {
let now = 0
const element = document.createElement('div')
const tracker = installTerminalImeCompositionTracker(element, { now: () => now })
return {
tracker,
element,
advance: (ms) => {
now += ms
},
composition: (type, data) => {
const event = new CompositionEvent(type, { bubbles: true })
Object.defineProperty(event, 'data', { value: data })
element.dispatchEvent(event)
},
input: (inputType) => {
element.dispatchEvent(new InputEvent('input', { inputType, bubbles: true }))
},
blur: () => {
element.dispatchEvent(new Event('blur', { bubbles: true }))
}
}
}
describe('installTerminalImeCompositionTracker', () => {
it('activates on compositionstart', () => {
const harness = installTracker()
harness.composition('compositionstart', '')
expect(harness.tracker.isActive()).toBe(true)
})
it('keeps composition active through Sogou-style empty compositionupdate', () => {
const harness = installTracker()
harness.composition('compositionstart', '')
harness.composition('compositionupdate', 'ni')
harness.composition('compositionupdate', '')
expect(harness.tracker.isActive()).toBe(true)
})
it('clears on compositionend', () => {
const harness = installTracker()
harness.composition('compositionstart', '')
harness.composition('compositionupdate', '你')
harness.composition('compositionend', '你')
expect(harness.tracker.isActive()).toBe(false)
})
it('still clears on non-composition input', () => {
const harness = installTracker()
harness.composition('compositionstart', '')
harness.input('insertText')
expect(harness.tracker.isActive()).toBe(false)
})
it('does not clear on insertCompositionText input', () => {
const harness = installTracker()
harness.composition('compositionstart', '')
harness.input('insertCompositionText')
expect(harness.tracker.isActive()).toBe(true)
})
it('clears on blur', () => {
const harness = installTracker()
harness.composition('compositionstart', '')
harness.blur()
expect(harness.tracker.isActive()).toBe(false)
expect(harness.tracker.isCandidateKeyGuardActive()).toBe(false)
})
describe('candidate key guard', () => {
it('is active while a composition is live', () => {
const harness = installTracker()
expect(harness.tracker.isCandidateKeyGuardActive()).toBe(false)
harness.composition('compositionstart', '')
expect(harness.tracker.isCandidateKeyGuardActive()).toBe(true)
})
it('stays active through empty compositionupdate events', () => {
const harness = installTracker()
harness.composition('compositionstart', '')
harness.composition('compositionupdate', '')
expect(harness.tracker.isCandidateKeyGuardActive()).toBe(true)
})
it('expires after prolonged composition-event silence so stale IME state cannot keep terminal keys dead', () => {
const harness = installTracker()
harness.composition('compositionstart', '')
harness.advance(TERMINAL_IME_CANDIDATE_GUARD_STALE_COMPOSITION_EXPIRY_MS)
expect(harness.tracker.isCandidateKeyGuardActive()).toBe(true)
expect(harness.tracker.isActive()).toBe(true)
harness.advance(1)
expect(harness.tracker.isCandidateKeyGuardActive()).toBe(false)
expect(harness.tracker.isActive()).toBe(false)
})
it('refreshes the expiry window on composition activity', () => {
const harness = installTracker()
harness.composition('compositionstart', '')
harness.advance(TERMINAL_IME_CANDIDATE_GUARD_STALE_COMPOSITION_EXPIRY_MS)
harness.composition('compositionupdate', '')
harness.advance(TERMINAL_IME_CANDIDATE_GUARD_STALE_COMPOSITION_EXPIRY_MS)
expect(harness.tracker.isCandidateKeyGuardActive()).toBe(true)
})
it('does not arm the post-composition window without Sogou-style empty updates', () => {
const harness = installTracker()
harness.composition('compositionstart', '')
harness.composition('compositionupdate', '你')
harness.composition('compositionend', '你')
expect(harness.tracker.isCandidateKeyGuardActive()).toBe(false)
})
it('absorbs the Sogou-style committing key after compositionend, then expires', () => {
const harness = installTracker()
harness.composition('compositionstart', '')
harness.composition('compositionupdate', '你')
harness.composition('compositionupdate', '')
harness.composition('compositionend', '你')
expect(harness.tracker.isCandidateKeyGuardActive()).toBe(true)
harness.advance(TERMINAL_IME_CANDIDATE_GUARD_POST_COMPOSITION_MS)
expect(harness.tracker.isCandidateKeyGuardActive()).toBe(true)
harness.advance(1)
expect(harness.tracker.isCandidateKeyGuardActive()).toBe(false)
})
it('drops the post-composition window once ordinary typing resumes', () => {
const harness = installTracker()
harness.composition('compositionstart', '')
harness.composition('compositionupdate', '')
harness.composition('compositionend', '你')
harness.input('insertText')
expect(harness.tracker.isCandidateKeyGuardActive()).toBe(false)
})
})
it('handles a missing terminal element', () => {
const tracker = installTerminalImeCompositionTracker(null)
expect(tracker.isActive()).toBe(false)
expect(tracker.isCandidateKeyGuardActive()).toBe(false)
expect(() => tracker.dispose()).not.toThrow()
})
it('stops tracking after dispose', () => {
const harness = installTracker()
harness.tracker.dispose()
harness.composition('compositionstart', '')
expect(harness.tracker.isActive()).toBe(false)
})
})
@@ -2,47 +2,112 @@ import type { IDisposable } from '@xterm/xterm'
export type TerminalImeCompositionTracker = IDisposable & {
isActive: () => boolean
/** True while candidate-selection keys (Space/digits) should be treated as
* IME-owned: during a live composition, and briefly after compositionend to
* absorb the committing key's trailing press/release. */
isCandidateKeyGuardActive: () => boolean
}
// Why: suppressed candidate keys are preventDefault-ed and fire no input
// event, so a stale tracker (missed compositionend) has no natural unstick
// path. Expire the guard so Space/digits cannot stay dead indefinitely.
export const TERMINAL_IME_CANDIDATE_GUARD_STALE_COMPOSITION_EXPIRY_MS = 10_000
// Why: Sogou/fcitx can deliver the committing Space/digit as plain keydown and
// keyup after compositionend; a narrow window absorbs those trailing events
// without making the keys globally unavailable after IME use.
export const TERMINAL_IME_CANDIDATE_GUARD_POST_COMPOSITION_MS = 250
export function installTerminalImeCompositionTracker(
terminalElement: HTMLElement | null | undefined
terminalElement: HTMLElement | null | undefined,
options?: { now?: () => number }
): TerminalImeCompositionTracker {
const now = options?.now ?? ((): number => Date.now())
let active = false
let lastCompositionEventAt: number | null = null
let compositionEndedAt: number | null = null
let sawEmptyCompositionUpdate = false
const isActiveAt = (at: number): boolean =>
active &&
(lastCompositionEventAt === null ||
at - lastCompositionEventAt <= TERMINAL_IME_CANDIDATE_GUARD_STALE_COMPOSITION_EXPIRY_MS)
const isCandidateKeyGuardActive = (): boolean => {
const at = now()
if (isActiveAt(at)) {
return true
}
return (
compositionEndedAt !== null &&
at - compositionEndedAt <= TERMINAL_IME_CANDIDATE_GUARD_POST_COMPOSITION_MS
)
}
if (!terminalElement) {
return {
isActive: () => active,
isCandidateKeyGuardActive,
dispose: () => undefined
}
}
const markActive = (): void => {
active = true
lastCompositionEventAt = now()
compositionEndedAt = null
sawEmptyCompositionUpdate = false
}
const updateComposition = (event: Event): void => {
active = !(event instanceof CompositionEvent) || event.data !== ''
lastCompositionEventAt = now()
// Why: Sogou/fcitx can emit empty compositionupdate data while its
// candidate popup is still open — empty data must not deactivate.
// compositionend, non-composition input, and blur own deactivation.
if (!(event instanceof CompositionEvent)) {
return
}
if (event.data === '') {
sawEmptyCompositionUpdate = true
return
}
active = true
}
const handleCompositionEnd = (): void => {
active = false
// Why: only Sogou/fcitx-style empty updates prove a trailing plain
// Space/digit is likely IME-owned; broad post-end guards drop real typing.
compositionEndedAt = sawEmptyCompositionUpdate ? now() : null
sawEmptyCompositionUpdate = false
}
const handleInput = (event: Event): void => {
if (event instanceof InputEvent && event.inputType === 'insertCompositionText') {
return
}
active = false
// Why: real non-composition input means ordinary typing resumed; keeping
// the post-end window would swallow a legitimate Space/digit.
compositionEndedAt = null
sawEmptyCompositionUpdate = false
}
const markInactive = (): void => {
active = false
lastCompositionEventAt = null
compositionEndedAt = null
sawEmptyCompositionUpdate = false
}
terminalElement.addEventListener('compositionstart', markActive, true)
terminalElement.addEventListener('compositionupdate', updateComposition, true)
terminalElement.addEventListener('compositionend', markInactive, true)
terminalElement.addEventListener('compositionend', handleCompositionEnd, true)
terminalElement.addEventListener('input', handleInput, true)
terminalElement.addEventListener('blur', markInactive, true)
return {
isActive: () => active,
isActive: () => isActiveAt(now()),
isCandidateKeyGuardActive,
dispose: () => {
terminalElement.removeEventListener('compositionstart', markActive, true)
terminalElement.removeEventListener('compositionupdate', updateComposition, true)
terminalElement.removeEventListener('compositionend', markInactive, true)
terminalElement.removeEventListener('compositionend', handleCompositionEnd, true)
terminalElement.removeEventListener('input', handleInput, true)
terminalElement.removeEventListener('blur', markInactive, true)
}
@@ -64,6 +64,12 @@ import { showOsc52ClipboardBlockedToast } from './osc52-clipboard-blocked-toast'
import { parseOsc7 } from './parse-osc7'
import { resolveTerminalJisYenInput } from './terminal-jis-yen-input'
import { installTerminalImeCompositionTracker } from './terminal-ime-composition-tracker'
import {
armTerminalImePendingCandidateKeyRelease,
clearTerminalImePendingCandidateKeyRelease,
createTerminalImePendingCandidateKeyReleases,
shouldApplyTerminalImePendingCandidateKeyRelease
} from './terminal-ime-candidate-key-release-guard'
import {
DISABLED_MAC_NATIVE_TEXT_INPUT_SOURCE_FEATURES,
getMacNativeTextInputSourceTracker
@@ -72,6 +78,7 @@ import { installTerminalImeNativeTextForwarder } from './terminal-ime-native-tex
import {
shouldBypassXtermKeyboardEvent,
shouldHandleTerminalInterruptKeyboardEvent,
shouldPreventDefaultTerminalImeCandidateKey,
shouldSuppressTerminalImeKeyboardEvent,
shouldSuppressTerminalInterruptKeyup,
shouldSuppressTerminalModifierKeyboardEvent,
@@ -842,7 +849,16 @@ export function useTerminalPaneLifecycle({
// encoder runs, letting the browser and Electron paths fire normally.
// See xterm-bypass-policy.ts for the rule derivation.
let pendingTerminalInterruptKeyup = false
const pendingTerminalImeCandidateKeyReleases =
createTerminalImePendingCandidateKeyReleases()
const isMac = navigator.userAgent.includes('Mac')
// Why: Android/ChromeOS UAs also contain "Linux"; keep the Sogou/fcitx
// candidate-key policy scoped to desktop Linux so paired web clients on
// those platforms keep their previous IME behavior.
const isLinux =
!isMac &&
navigator.userAgent.includes('Linux') &&
!/Android|CrOS/.test(navigator.userAgent)
const macNativeTextInputSourceTracker = isMac ? getMacNativeTextInputSourceTracker() : null
const imeCompositionTracker = installTerminalImeCompositionTracker(pane.terminal.element)
imeCompositionDisposablesRef.current.set(pane.id, imeCompositionTracker)
@@ -864,14 +880,38 @@ export function useTerminalPaneLifecycle({
}
imeNativeTextForwarderDisposablesRef.current.set(pane.id, imeNativeTextForwarder)
pane.terminal.attachCustomKeyEventHandler((e) => {
if (
shouldSuppressTerminalImeKeyboardEvent(e, {
compositionActive: imeCompositionTracker.isActive(),
isMac
})
) {
const now = Date.now()
const pendingCandidateReleaseGuardActive = shouldApplyTerminalImePendingCandidateKeyRelease(
e,
pendingTerminalImeCandidateKeyReleases,
now
)
const imeKeyboardOptions = {
compositionActive: imeCompositionTracker.isActive(),
candidateKeyGuardActive:
imeCompositionTracker.isCandidateKeyGuardActive() ||
pendingCandidateReleaseGuardActive,
pendingCandidateKeyReleaseActive: pendingCandidateReleaseGuardActive,
isMac,
isLinux
}
if (shouldSuppressTerminalImeKeyboardEvent(e, imeKeyboardOptions)) {
// Why: clear before arm — a fresh keydown drops any stale pending
// release for its key before the new press arms its own.
clearTerminalImePendingCandidateKeyRelease(pendingTerminalImeCandidateKeyReleases, e)
if (shouldPreventDefaultTerminalImeCandidateKey(e, imeKeyboardOptions)) {
// Why: without preventDefault the suppressed candidate keydown
// still fires a keypress and mutates the helper textarea.
e.preventDefault()
armTerminalImePendingCandidateKeyRelease(
pendingTerminalImeCandidateKeyReleases,
e,
now
)
}
return false
}
clearTerminalImePendingCandidateKeyRelease(pendingTerminalImeCandidateKeyReleases, e)
if (pendingTerminalInterruptKeyup && shouldSuppressTerminalInterruptKeyup(e)) {
pendingTerminalInterruptKeyup = false
return false
@@ -0,0 +1,17 @@
import type { XtermBypassEvent } from './xterm-bypass-policy'
// Shared test fixture: builds a fully-defaulted XtermBypassEvent so the bypass
// and IME candidate-guard suites all stay in sync when the event shape changes.
export function event(overrides: Partial<XtermBypassEvent>): XtermBypassEvent {
return {
type: 'keydown',
key: '',
code: '',
defaultPrevented: false,
metaKey: false,
ctrlKey: false,
altKey: false,
shiftKey: false,
...overrides
}
}
@@ -1,23 +1,10 @@
import { describe, expect, it } from 'vitest'
import {
shouldBypassXtermKeyboardEvent,
shouldSuppressTerminalImeKeyboardEvent,
type XtermBypassEvent
shouldPreventDefaultTerminalImeCandidateKey,
shouldSuppressTerminalImeKeyboardEvent
} from './xterm-bypass-policy'
function event(overrides: Partial<XtermBypassEvent>): XtermBypassEvent {
return {
type: 'keydown',
key: '',
code: '',
defaultPrevented: false,
metaKey: false,
ctrlKey: false,
altKey: false,
shiftKey: false,
...overrides
}
}
import { event } from './xterm-bypass-event-fixture'
describe('shouldBypassXtermKeyboardEvent — Windows/Linux', () => {
const withSel = { isMac: false, hasSelection: true }
@@ -161,60 +148,256 @@ describe('shouldBypassXtermKeyboardEvent — Windows/Linux', () => {
})
describe('shouldSuppressTerminalImeKeyboardEvent — Windows/Linux', () => {
const idle = { isMac: false, compositionActive: false }
const composing = { isMac: false, compositionActive: true }
const windowsIdle = {
isMac: false,
isLinux: false,
compositionActive: false,
candidateKeyGuardActive: false,
pendingCandidateKeyReleaseActive: false
}
const linuxIdle = {
isMac: false,
isLinux: true,
compositionActive: false,
candidateKeyGuardActive: false,
pendingCandidateKeyReleaseActive: false
}
const linuxComposing = { ...linuxIdle, compositionActive: true, candidateKeyGuardActive: true }
// Post-compositionend guard: the tracker is already inactive but the
// committing key's trailing press/release must still be absorbed.
const linuxPostCompositionGuard = { ...linuxIdle, candidateKeyGuardActive: true }
const windowsComposing = { ...windowsIdle, compositionActive: true, candidateKeyGuardActive: true }
it('suppresses keyboard events while Chromium reports active IME composition', () => {
expect(
shouldSuppressTerminalImeKeyboardEvent(
event({ key: 'Backspace', code: 'Backspace', isComposing: true }),
idle
)
).toBe(true)
for (const options of [windowsIdle, linuxIdle]) {
expect(
shouldSuppressTerminalImeKeyboardEvent(
event({ key: 'Backspace', code: 'Backspace', isComposing: true }),
options
)
).toBe(true)
}
})
it('suppresses Windows IME Process keys', () => {
// Why: Windows preedit can hit the textarea before compositionstart;
// letting the 229 keydown through would flush it via xterm's textarea diff.
expect(
shouldSuppressTerminalImeKeyboardEvent(
event({ key: 'Process', code: 'KeyN', keyCode: 229 }),
idle
windowsIdle
)
).toBe(true)
})
it('does not suppress ordinary Backspace outside IME composition', () => {
it('lets standalone Linux 229 keydowns reach xterm so its CompositionHelper can diff text', () => {
// Why: Sogou/fcitx candidate commits can ride a bare 229 keydown outside a
// composition session; xterm must see it to schedule its textarea diff.
expect(
shouldSuppressTerminalImeKeyboardEvent(event({ key: 'Backspace', code: 'Backspace' }), idle)
shouldSuppressTerminalImeKeyboardEvent(
event({ key: 'Process', code: 'KeyN', keyCode: 229 }),
linuxIdle
)
).toBe(false)
})
it('suppresses Linux 229 keydowns while the composition tracker is active', () => {
expect(
shouldSuppressTerminalImeKeyboardEvent(
event({ key: 'Process', code: 'KeyN', keyCode: 229 }),
linuxComposing
)
).toBe(true)
})
it('suppresses 229 / Process keyups so kitty release reporting cannot leak', () => {
for (const options of [windowsIdle, linuxIdle]) {
expect(
shouldSuppressTerminalImeKeyboardEvent(
event({ type: 'keyup', key: 'Process', code: 'KeyN', keyCode: 229 }),
options
)
).toBe(true)
}
})
it('does not suppress ordinary Backspace outside IME composition', () => {
for (const options of [windowsIdle, linuxIdle]) {
expect(
shouldSuppressTerminalImeKeyboardEvent(
event({ key: 'Backspace', code: 'Backspace' }),
options
)
).toBe(false)
}
})
it('suppresses IME-owned editing keys while composition is active', () => {
expect(
shouldSuppressTerminalImeKeyboardEvent(
event({ key: 'Backspace', code: 'Backspace' }),
composing
linuxComposing
)
).toBe(true)
expect(
shouldSuppressTerminalImeKeyboardEvent(
event({ key: 'ArrowDown', code: 'ArrowDown' }),
composing
linuxComposing
)
).toBe(true)
})
it('does not suppress ordinary text keys solely because composition is active', () => {
expect(
shouldSuppressTerminalImeKeyboardEvent(event({ key: 'a', code: 'KeyA' }), composing)
shouldSuppressTerminalImeKeyboardEvent(event({ key: 'a', code: 'KeyA' }), linuxComposing)
).toBe(false)
})
it('does not suppress keypress events because they carry committed text', () => {
expect(
shouldSuppressTerminalImeKeyboardEvent(
event({ type: 'keypress', key: '中', code: '', isComposing: true }),
idle
)
).toBe(false)
for (const options of [windowsIdle, linuxIdle]) {
expect(
shouldSuppressTerminalImeKeyboardEvent(
event({ type: 'keypress', key: '中', code: '', isComposing: true }),
options
)
).toBe(false)
}
})
describe('candidate-selection keys (Sogou Space/digit commit)', () => {
it('suppresses Space and digit keydowns and keyups while the candidate guard is active', () => {
for (const options of [linuxComposing, linuxPostCompositionGuard]) {
for (const key of [' ', '0', '2', '9']) {
expect(
shouldSuppressTerminalImeKeyboardEvent(event({ key, code: '' }), options)
).toBe(true)
expect(
shouldSuppressTerminalImeKeyboardEvent(event({ type: 'keyup', key, code: '' }), options)
).toBe(true)
}
}
})
it('suppresses the follow-on candidate keypress so _keyPress cannot forward the selector', () => {
expect(
shouldSuppressTerminalImeKeyboardEvent(
event({ type: 'keypress', key: ' ', code: 'Space' }),
linuxPostCompositionGuard
)
).toBe(true)
expect(
shouldSuppressTerminalImeKeyboardEvent(
event({ type: 'keypress', key: '2', code: 'Digit2' }),
linuxComposing
)
).toBe(true)
})
it('leaves Space and digits alone once the guard has expired', () => {
for (const type of ['keydown', 'keyup', 'keypress']) {
expect(
shouldSuppressTerminalImeKeyboardEvent(event({ type, key: ' ', code: 'Space' }), linuxIdle)
).toBe(false)
expect(
shouldSuppressTerminalImeKeyboardEvent(
event({ type, key: '2', code: 'Digit2' }),
linuxIdle
)
).toBe(false)
}
})
it('does not treat modified chords such as Ctrl+Space (IME toggle) as candidate keys', () => {
expect(
shouldSuppressTerminalImeKeyboardEvent(
event({ key: ' ', code: 'Space', ctrlKey: true }),
linuxPostCompositionGuard
)
).toBe(false)
})
it('does not treat Shift+Space (fcitx full-/half-width toggle) as a candidate key', () => {
expect(
shouldSuppressTerminalImeKeyboardEvent(
event({ key: ' ', code: 'Space', shiftKey: true }),
linuxPostCompositionGuard
)
).toBe(false)
})
it('leaves ordinary letters unsuppressed while the guard is active', () => {
expect(
shouldSuppressTerminalImeKeyboardEvent(
event({ key: 'a', code: 'KeyA' }),
linuxPostCompositionGuard
)
).toBe(false)
})
it('does not apply the Linux/Sogou candidate guard to Windows', () => {
expect(
shouldSuppressTerminalImeKeyboardEvent(
event({ key: ' ', code: 'Space' }),
windowsComposing
)
).toBe(false)
expect(
shouldSuppressTerminalImeKeyboardEvent(
event({ type: 'keypress', key: '2', code: 'Digit2' }),
windowsComposing
)
).toBe(false)
})
it('suppresses a pending Linux candidate release even if modifier state changed after keydown', () => {
expect(
shouldSuppressTerminalImeKeyboardEvent(
event({ type: 'keyup', key: '2', code: 'Digit2', shiftKey: true }),
{
...linuxIdle,
candidateKeyGuardActive: true,
pendingCandidateKeyReleaseActive: true
}
)
).toBe(true)
})
})
describe('shouldPreventDefaultTerminalImeCandidateKey', () => {
it('prevents the default on candidate keydowns while the guard is active', () => {
expect(
shouldPreventDefaultTerminalImeCandidateKey(
event({ key: ' ', code: 'Space' }),
linuxComposing
)
).toBe(true)
expect(
shouldPreventDefaultTerminalImeCandidateKey(
event({ key: '2', code: 'Digit2' }),
linuxPostCompositionGuard
)
).toBe(true)
})
it('does not prevent the default for keyups, expired guards, or non-candidate keys', () => {
expect(
shouldPreventDefaultTerminalImeCandidateKey(
event({ type: 'keyup', key: ' ', code: 'Space' }),
linuxComposing
)
).toBe(false)
expect(
shouldPreventDefaultTerminalImeCandidateKey(event({ key: ' ', code: 'Space' }), linuxIdle)
).toBe(false)
expect(
shouldPreventDefaultTerminalImeCandidateKey(event({ key: 'a', code: 'KeyA' }), linuxComposing)
).toBe(false)
expect(
shouldPreventDefaultTerminalImeCandidateKey(
event({ key: ' ', code: 'Space' }),
windowsComposing
)
).toBe(false)
})
})
})
@@ -1,23 +1,10 @@
import { describe, expect, it } from 'vitest'
import {
shouldBypassXtermKeyboardEvent,
shouldSuppressTerminalImeKeyboardEvent,
type XtermBypassEvent
shouldPreventDefaultTerminalImeCandidateKey,
shouldSuppressTerminalImeKeyboardEvent
} from './xterm-bypass-policy'
function event(overrides: Partial<XtermBypassEvent>): XtermBypassEvent {
return {
type: 'keydown',
key: '',
code: '',
defaultPrevented: false,
metaKey: false,
ctrlKey: false,
altKey: false,
shiftKey: false,
...overrides
}
}
import { event } from './xterm-bypass-event-fixture'
describe('shouldBypassXtermKeyboardEvent — macOS', () => {
const opts = { isMac: true, hasSelection: true }
@@ -164,8 +151,20 @@ describe('shouldBypassXtermKeyboardEvent — macOS', () => {
})
describe('shouldSuppressTerminalImeKeyboardEvent — macOS', () => {
const idle = { isMac: true, compositionActive: false }
const composing = { isMac: true, compositionActive: true }
const idle = {
isMac: true,
isLinux: false,
compositionActive: false,
candidateKeyGuardActive: false,
pendingCandidateKeyReleaseActive: false
}
const composing = {
isMac: true,
isLinux: false,
compositionActive: true,
candidateKeyGuardActive: true,
pendingCandidateKeyReleaseActive: false
}
it('suppresses keyboard events while Chromium reports active IME composition', () => {
expect(
@@ -238,4 +237,19 @@ describe('shouldSuppressTerminalImeKeyboardEvent — macOS', () => {
)
).toBe(false)
})
it('does not apply the Linux/Sogou candidate guard to macOS', () => {
expect(
shouldSuppressTerminalImeKeyboardEvent(event({ key: ' ', code: 'Space' }), composing)
).toBe(false)
expect(
shouldSuppressTerminalImeKeyboardEvent(
event({ type: 'keypress', key: '2', code: 'Digit2' }),
composing
)
).toBe(false)
expect(
shouldPreventDefaultTerminalImeCandidateKey(event({ key: ' ', code: 'Space' }), composing)
).toBe(false)
})
})
@@ -1,4 +1,5 @@
import { keybindingMatchesInput } from '../../../../shared/keybindings'
import { isTerminalImeCandidateSelectionKeyEvent } from './terminal-ime-candidate-key-release-guard'
// Why: when a CLI activates kitty progressive enhancement (CSI > N u), xterm's
// KittyKeyboard encoder turns every modifier chord — including plain Cmd+C —
@@ -18,6 +19,7 @@ export type XtermBypassEvent = {
code?: string
keyCode?: number
isComposing?: boolean
repeat?: boolean
defaultPrevented?: boolean
metaKey: boolean
ctrlKey: boolean
@@ -35,9 +37,18 @@ export type XtermBypassOptions = {
export type XtermImeKeyboardOptions = {
compositionActive: boolean
/** True while Linux/Sogou candidate-selection keys (Space/digits) are
* IME-owned: live composition plus a short post-compositionend window. */
candidateKeyGuardActive: boolean
/** True when the pending-release guard already matched this specific event. */
pendingCandidateKeyReleaseActive: boolean
// Required so no caller silently falls back to non-mac 229 suppression,
// which re-swallows the first key after a macOS IME input-source switch.
isMac: boolean
// Required Linux/Windows split: Linux passes standalone 229 keydowns like
// macOS; the Windows-only suppression guards its preedit-diff race (preedit
// can hit the textarea before compositionstart and be flushed by the diff).
isLinux: boolean
}
export const TERMINAL_INTERRUPT_INPUT = '\x03'
@@ -74,18 +85,55 @@ export function shouldSuppressTerminalImeKeyboardEvent(
event: XtermBypassEvent,
options: XtermImeKeyboardOptions
): boolean {
const {
compositionActive,
candidateKeyGuardActive,
pendingCandidateKeyReleaseActive,
isMac,
isLinux
} = options
const suppressCandidateKey =
isLinux &&
(pendingCandidateKeyReleaseActive ||
(candidateKeyGuardActive && isTerminalImeCandidateSelectionKeyEvent(event)))
if (event.type === 'keypress') {
// Why: a suppressed candidate keydown is not preventDefault-ed by xterm,
// so its native keypress still fires and _keyPress would forward the
// literal Space/digit to the PTY.
return suppressCandidateKey
}
if (!isXtermHandledKeyEvent(event.type)) {
return false
}
const { compositionActive, isMac } = options
// Why: IMEs own Process-key / composing keystrokes — letting xterm translate
// them corrupts committed CJK text. Bare macOS keydown 229 is exempt: it must
// reach xterm's CompositionHelper or the first key after an input-source
// switch is swallowed.
// them corrupts committed CJK text. Bare macOS/Linux keydown 229 is exempt:
// it must reach xterm's CompositionHelper so it can schedule its textarea
// diff (macOS: first key after an input-source switch; Linux: Sogou/fcitx
// candidate commits outside a composition session). Windows keeps full
// suppression until verified against its preedit-diff race.
const passesStandalone229Keydown = isMac || isLinux
return (
event.isComposing === true ||
(event.keyCode === 229 && (event.type !== 'keydown' || compositionActive || !isMac)) ||
(compositionActive && TERMINAL_IME_OWNED_KEYS.has(event.key))
(event.keyCode === 229 &&
(event.type !== 'keydown' || compositionActive || !passesStandalone229Keydown)) ||
(compositionActive && TERMINAL_IME_OWNED_KEYS.has(event.key)) ||
suppressCandidateKey
)
}
export function shouldPreventDefaultTerminalImeCandidateKey(
event: XtermBypassEvent,
options: XtermImeKeyboardOptions
): boolean {
// Why: returning false from attachCustomKeyEventHandler does not
// preventDefault — the candidate keydown would still fire a keypress and
// write into the helper textarea, where a later 229 diff could flush the
// leaked selector to the PTY.
return (
event.type === 'keydown' &&
options.isLinux &&
options.candidateKeyGuardActive &&
isTerminalImeCandidateSelectionKeyEvent(event)
)
}
@@ -1,6 +1,9 @@
import { describe, expect, it } from 'vitest'
import type { TerminalTab } from '../../../../shared/types'
import { shouldRepairActiveTerminalTab } from './active-terminal-repair'
import {
resolveRepairedActiveTerminalTabId,
shouldRepairActiveTerminalTab
} from './active-terminal-repair'
function tab(id: string): TerminalTab {
return {
@@ -50,3 +53,49 @@ describe('shouldRepairActiveTerminalTab', () => {
).toBe(false)
})
})
describe('resolveRepairedActiveTerminalTabId', () => {
it('returns null when no repair is needed', () => {
expect(
resolveRepairedActiveTerminalTabId({
activeTabType: 'terminal',
activeTabId: 'terminal-2',
rememberedTabId: 'terminal-1',
tabs: [tab('terminal-1'), tab('terminal-2')]
})
).toBeNull()
})
it('restores the remembered tab instead of the first tab when repairing', () => {
// Why (regression): a repair firing on a transient worktree-switch render
// must not reset the selection to Terminal 1 — it should land on the tab
// the worktree remembers the user was on.
expect(
resolveRepairedActiveTerminalTabId({
activeTabType: 'terminal',
activeTabId: 'stale-from-other-worktree',
rememberedTabId: 'terminal-2',
tabs: [tab('terminal-1'), tab('terminal-2')]
})
).toBe('terminal-2')
})
it('falls back to the first tab when the remembered tab is missing or stale', () => {
expect(
resolveRepairedActiveTerminalTabId({
activeTabType: 'terminal',
activeTabId: 'missing',
rememberedTabId: null,
tabs: [tab('terminal-1'), tab('terminal-2')]
})
).toBe('terminal-1')
expect(
resolveRepairedActiveTerminalTabId({
activeTabType: 'terminal',
activeTabId: 'missing',
rememberedTabId: 'no-longer-open',
tabs: [tab('terminal-1'), tab('terminal-2')]
})
).toBe('terminal-1')
})
})
@@ -16,3 +16,19 @@ export function shouldRepairActiveTerminalTab(args: {
}
return true
}
// Resolve which terminal tab to open after a project/agent is selected, or null if no repair is needed.
export function resolveRepairedActiveTerminalTabId(args: {
activeTabType: WorkspaceVisibleTabType
activeTabId: string | null
rememberedTabId: string | null | undefined
tabs: TerminalTab[]
}): string | null {
if (!shouldRepairActiveTerminalTab(args)) {
return null
}
if (args.rememberedTabId && args.tabs.some((tab) => tab.id === args.rememberedTabId)) {
return args.rememberedTabId
}
return args.tabs[0].id
}
@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest'
import { shouldRetryPaneSpawnOnSshReconnect } from './ssh-reconnect-pane-retry'
describe('shouldRetryPaneSpawnOnSshReconnect', () => {
it('retries tabs with no ptyId at all', () => {
expect(
shouldRetryPaneSpawnOnSshReconnect({
targetId: 'conn-1',
tabPtyId: null,
deferredSessionId: undefined
})
).toBe(true)
})
it('retries tabs still holding a deferred session for this target', () => {
// Why: the stale wake-hint ptyId reads as live, but an unconsumed deferred
// entry proves no pane ever reattached — the pane is stranded.
expect(
shouldRetryPaneSpawnOnSshReconnect({
targetId: 'conn-1',
tabPtyId: 'ssh:conn-1@@pty-7',
deferredSessionId: 'ssh:conn-1@@pty-7'
})
).toBe(true)
})
it('leaves tabs whose deferred entry was already consumed alone', () => {
expect(
shouldRetryPaneSpawnOnSshReconnect({
targetId: 'conn-1',
tabPtyId: 'ssh:conn-1@@pty-7',
deferredSessionId: undefined
})
).toBe(false)
})
it('ignores deferred sessions that belong to another target', () => {
expect(
shouldRetryPaneSpawnOnSshReconnect({
targetId: 'conn-1',
tabPtyId: 'ssh:conn-2@@pty-3',
deferredSessionId: 'ssh:conn-2@@pty-3'
})
).toBe(false)
})
})
@@ -0,0 +1,22 @@
import { parseAppSshPtyId } from '../../../shared/ssh-pty-id'
// Why: on SSH (re)connect, panes that never got a live PTY must remount and
// retry. Two shapes qualify: tabs with no ptyId at all (their spawn failed
// outright), and tabs still holding a deferred reattach session for this
// target — their restored wake-hint ptyId reads as live but nothing is
// attached. The deferred entry is consumed synchronously the moment a pane
// starts reattaching, so a remaining entry proves the tab is stranded (e.g.
// the user cancelled the passphrase prompt and connected later via Settings).
export function shouldRetryPaneSpawnOnSshReconnect(args: {
targetId: string
tabPtyId: string | null | undefined
deferredSessionId: string | undefined
}): boolean {
if (!args.tabPtyId) {
return true
}
return (
args.deferredSessionId != null &&
parseAppSshPtyId(args.deferredSessionId)?.connectionId === args.targetId
)
}
+13 -5
View File
@@ -2,6 +2,7 @@
import { useEffect } from 'react'
import { toast } from 'sonner'
import { useAppStore } from '../store'
import { shouldRetryPaneSpawnOnSshReconnect } from './ssh-reconnect-pane-retry'
import { getWorktreeMapFromState, getRepoMapFromState } from '@/store/selectors'
import { applyUIZoom } from '@/lib/ui-zoom'
import { activateAndRevealWorktree } from '@/lib/worktree-activation'
@@ -2615,8 +2616,10 @@ export function useIpcEvents(): void {
void Promise.all(remoteRepos.map((r) => store.fetchWorktrees(r.id))).then(async () => {
await useAppStore.getState().fetchWorktreeLineage()
// Why: terminal panes that failed to spawn (no PTY provider on cold
// start) sit inert. Bumping generation forces TerminalPane to remount
// and retry pty:spawn. Only bump tabs with no live ptyId.
// start) or whose deferred reattach never ran sit inert. Bumping
// generation forces TerminalPane to remount and retry; the remount
// routes through the deferred-connect gate, which reattaches the
// stranded session or spawns fresh now that the provider exists.
const freshStore = useAppStore.getState()
const remoteRepoIds = new Set(remoteRepos.map((r) => r.id))
const worktreeIds = Object.values(freshStore.worktreesByRepo)
@@ -2626,13 +2629,18 @@ export function useIpcEvents(): void {
for (const worktreeId of worktreeIds) {
const tabs = freshStore.tabsByWorktree[worktreeId] ?? []
const hasDead = tabs.some((t) => !t.ptyId)
if (hasDead) {
const needsRetry = (t: { id: string; ptyId?: string | null }): boolean =>
shouldRetryPaneSpawnOnSshReconnect({
targetId,
tabPtyId: t.ptyId,
deferredSessionId: freshStore.deferredSshSessionIdsByTabId[t.id]
})
if (tabs.some(needsRetry)) {
useAppStore.setState((s) => ({
tabsByWorktree: {
...s.tabsByWorktree,
[worktreeId]: (s.tabsByWorktree[worktreeId] ?? []).map((t) =>
t.ptyId ? t : { ...t, generation: (t.generation ?? 0) + 1 }
needsRetry(t) ? { ...t, generation: (t.generation ?? 0) + 1 } : t
)
}
}))
+4 -1
View File
@@ -4758,7 +4758,10 @@
"agentPermissionsDescription": "Choose whether Orca launches agents with fewer permission prompts or with manual checks.",
"agentPermissionsYolo": "Yolo",
"agentPermissionsManual": "Manual",
"3f1bdf3cb4": "Environment text is too large to parse safely."
"3f1bdf3cb4": "Environment text is too large to parse safely.",
"codexSessionSource": "Codex home to import from",
"codexSessionSourceInfo": "About importing Codex history",
"codexSessionSourceTooltip": "Orca runs Codex in an isolated home. Point this at your existing Codex home to import that session history. Empty uses ~/.codex."
},
"AppIconSelector": {
"d5a112dc9b": "Next icon",
+4 -1
View File
@@ -4758,7 +4758,10 @@
"agentPermissionsDescription": "Elige si Orca lanza agents con menos prompts de permisos o con checks manuales.",
"agentPermissionsYolo": "Yolo",
"agentPermissionsManual": "Manual",
"3f1bdf3cb4": "El texto de entorno es demasiado grande para analizarlo de forma segura."
"3f1bdf3cb4": "El texto de entorno es demasiado grande para analizarlo de forma segura.",
"codexSessionSource": "Codex home to import from",
"codexSessionSourceInfo": "About importing Codex history",
"codexSessionSourceTooltip": "Orca runs Codex in an isolated home. Point this at your existing Codex home to import that session history. Empty uses ~/.codex."
},
"AppIconSelector": {
"d5a112dc9b": "Icono siguiente",
+4 -1
View File
@@ -4743,7 +4743,10 @@
"agentPermissionsDescription": "Choose whether Orca launches agents with fewer permission prompts or with manual checks.",
"agentPermissionsYolo": "Yolo",
"agentPermissionsManual": "手動",
"3f1bdf3cb4": "環境テキストが大きすぎるため安全に解析できません。"
"3f1bdf3cb4": "環境テキストが大きすぎるため安全に解析できません。",
"codexSessionSource": "Codex home to import from",
"codexSessionSourceInfo": "About importing Codex history",
"codexSessionSourceTooltip": "Orca runs Codex in an isolated home. Point this at your existing Codex home to import that session history. Empty uses ~/.codex."
},
"AppIconSelector": {
"d5a112dc9b": "次へのアイコン",
+4 -1
View File
@@ -4743,7 +4743,10 @@
"agentPermissionsDescription": "Orca가 agents를 실행할 때 권한 프롬프트를 줄일지, 수동 확인을 유지할지 선택합니다.",
"agentPermissionsYolo": "Yolo",
"agentPermissionsManual": "수동",
"3f1bdf3cb4": "환경 텍스트가 너무 커서 안전하게 파싱할 수 없습니다."
"3f1bdf3cb4": "환경 텍스트가 너무 커서 안전하게 파싱할 수 없습니다.",
"codexSessionSource": "Codex home to import from",
"codexSessionSourceInfo": "About importing Codex history",
"codexSessionSourceTooltip": "Orca runs Codex in an isolated home. Point this at your existing Codex home to import that session history. Empty uses ~/.codex."
},
"AppIconSelector": {
"d5a112dc9b": "다음 아이콘",
+4 -1
View File
@@ -4743,7 +4743,10 @@
"agentPermissionsDescription": "选择 Orca 是以更少的权限提示启动智能体,还是手动检查。",
"agentPermissionsYolo": "Yolo",
"agentPermissionsManual": "手动",
"3f1bdf3cb4": "环境文本过长,无法安全解析。"
"3f1bdf3cb4": "环境文本过长,无法安全解析。",
"codexSessionSource": "Codex home to import from",
"codexSessionSourceInfo": "About importing Codex history",
"codexSessionSourceTooltip": "Orca runs Codex in an isolated home. Point this at your existing Codex home to import that session history. Empty uses ~/.codex."
},
"AppIconSelector": {
"d5a112dc9b": "下一个图标",
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { AgentStatusEntry } from '../../../../shared/agent-status-types'
import type { TerminalTab } from '../../../../shared/types'
import type { RetainedAgentEntry } from './agent-status'
import { RECENTLY_CLOSED_AGENT_STATUS_TAB_IDS_MAX } from './agent-status'
import { createTestStore } from './store-test-helpers'
// Why: dropAgentStatus and dismissRetainedAgentsByWorktree mirror the renderer-
@@ -119,6 +120,24 @@ describe('dropAgentStatusByTabPrefix -> IPC fan-out', () => {
'tab-new': true
})
})
it('FIFO-caps recentlyClosedAgentStatusTabIds so it cannot grow unbounded', () => {
stubWindowApi()
const store = createTestStore()
const cap = RECENTLY_CLOSED_AGENT_STATUS_TAB_IDS_MAX
for (let i = 0; i < cap + 5; i++) {
store.getState().dropAgentStatusByTabPrefix(`tab-${i}`)
}
const closed = store.getState().recentlyClosedAgentStatusTabIds
expect(Object.keys(closed)).toHaveLength(cap)
// Oldest evicted, most-recent retained (a status event for a tab closed
// >cap tabs ago cannot still arrive, so suppression is unaffected).
expect(closed['tab-0']).toBeUndefined()
expect(closed['tab-4']).toBeUndefined()
expect(closed[`tab-${cap + 4}`]).toBe(true)
})
})
describe('dismissRetainedAgentsByWorktree → IPC fan-out', () => {
+33 -4
View File
@@ -733,6 +733,35 @@ function getLaunchConfigForEntry(
: undefined
}
// Why: the renderer twin of the main-process closedAgentStatusTabIds set that
// #7561 FIFO-capped. It suppresses late hook/status events for a just-closed tab,
// so it must outlive the tab briefly — but tabId is ephemeral and it was only
// ever added to, growing one entry per tab-close for the renderer's whole life.
export const RECENTLY_CLOSED_AGENT_STATUS_TAB_IDS_MAX = 1024
// delete-then-set for LRU recency, then evict the oldest keys past the cap (Record
// key order is insertion order for non-integer string keys). A status event for a
// tab closed >MAX tabs ago cannot still arrive, so eviction is safe.
function boundRecentlyClosedAgentStatusTabIds(
existing: Record<string, true>,
tabId: string
): Record<string, true> {
const next: Record<string, true> = {}
for (const key of Object.keys(existing)) {
if (key !== tabId) {
next[key] = true
}
}
next[tabId] = true
const keys = Object.keys(next)
if (keys.length > RECENTLY_CLOSED_AGENT_STATUS_TAB_IDS_MAX) {
for (const stale of keys.slice(0, keys.length - RECENTLY_CLOSED_AGENT_STATUS_TAB_IDS_MAX)) {
delete next[stale]
}
}
return next
}
function getLaunchConfigForStatusMetadata(
state: AppState,
metadata: AgentLaunchConfigStatusMetadata
@@ -1632,10 +1661,10 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
delete nextAck[k]
}
}
const nextClosedTabs: Record<string, true> = {
...s.recentlyClosedAgentStatusTabIds,
[tabIdPrefix]: true
}
const nextClosedTabs = boundRecentlyClosedAgentStatusTabIds(
s.recentlyClosedAgentStatusTabIds,
tabIdPrefix
)
if (
liveKeys.length === 0 &&
@@ -307,6 +307,37 @@ describe('buildHydratedTabState – legacy format', () => {
expect(group.activeTabId).toBe('/f1')
})
it('restores each worktree remembered terminal, not the globally-active one', () => {
// Why (regression): the legacy branch used the global session.activeTabId,
// so every worktree except the last-focused one lost its remembered
// terminal on restart and reopened on the first tab. Use the per-worktree
// activeTabIdByWorktree map instead.
const terminal = (id: string, worktreeId: string, sortOrder: number) => ({
id,
ptyId: null,
worktreeId,
title: id,
customTitle: null,
color: null,
sortOrder,
createdAt: 100 + sortOrder
})
const session: WorkspaceSessionState = {
...makeBaseSession(),
// The globally-active tab belongs to w1.
activeTabId: 'w1-terminal-1',
tabsByWorktree: {
w1: [terminal('w1-terminal-1', 'w1', 0)],
w2: [terminal('w2-terminal-1', 'w2', 0), terminal('w2-terminal-2', 'w2', 1)]
},
activeTabIdByWorktree: { w1: 'w1-terminal-1', w2: 'w2-terminal-2' }
}
const result = buildHydratedTabState(session, new Set(['w1', 'w2']))
expect(result.groupsByWorktree.w2[0].activeTabId).toBe('w2-terminal-2')
expect(result.groupsByWorktree.w1[0].activeTabId).toBe('w1-terminal-1')
})
it('skips worktrees with no tabs or files', () => {
const session: WorkspaceSessionState = {
...makeBaseSession(),
@@ -251,8 +251,17 @@ function hydrateLegacyFormat(
let activeTabId: string | null = null
if (activeTabType === 'editor') {
activeTabId = session.activeFileIdByWorktree?.[worktreeId] ?? null
} else if (session.activeTabId && terminalTabs.some((t) => t.id === session.activeTabId)) {
activeTabId = session.activeTabId
} else {
// Why: honor this worktree's own remembered terminal before the global
// active tab. The global session.activeTabId only names the last-focused
// worktree's tab, so using it here reset every other worktree to its
// first terminal on restart.
const rememberedTabId = session.activeTabIdByWorktree?.[worktreeId]
if (rememberedTabId && terminalTabs.some((t) => t.id === rememberedTabId)) {
activeTabId = rememberedTabId
} else if (session.activeTabId && terminalTabs.some((t) => t.id === session.activeTabId)) {
activeTabId = session.activeTabId
}
}
if (activeTabId && !tabs.some((t) => t.id === activeTabId)) {
activeTabId = tabs[0]?.id ?? null
@@ -2125,6 +2125,59 @@ describe('TabsSlice', () => {
})
})
it('promotes legacy terminals to the worktree remembered tab, not always the first one', () => {
// Why (regression): selecting a non-first terminal, switching to another
// worktree, then returning must land on the remembered tab. Reconcile
// used to seed a freshly-ensured group with restoredLegacyTabs[0], so the
// remembered selection in activeTabIdByWorktree was silently dropped and
// the worktree always reopened on Terminal 1.
const firstTerminalId = 'runtime-terminal-1'
const secondTerminalId = 'runtime-terminal-2'
store.setState({
tabsByWorktree: {
[WT]: [
{
id: firstTerminalId,
ptyId: 'pty-1',
worktreeId: WT,
title: 'Terminal 1',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
},
{
id: secondTerminalId,
ptyId: 'pty-2',
worktreeId: WT,
title: 'Terminal 2',
customTitle: null,
color: null,
sortOrder: 1,
createdAt: 2
}
]
},
ptyIdsByTabId: {
[firstTerminalId]: ['pty-1'],
[secondTerminalId]: ['pty-2']
},
unifiedTabsByWorktree: { [WT]: [] },
groupsByWorktree: { [WT]: [] },
activeGroupIdByWorktree: {},
// The user had Terminal 2 active before leaving this worktree.
activeTabIdByWorktree: { [WT]: secondTerminalId }
})
const result = store.getState().reconcileWorktreeTabModel(WT)
const restoredGroup = store.getState().groupsByWorktree[WT]?.[0]
expect(result.renderableTabCount).toBe(2)
expect(result.activeRenderableTabId).toBe(secondTerminalId)
expect(restoredGroup?.activeTabId).toBe(secondTerminalId)
})
it('keeps a sole terminal renderable after its PTY exits so a failed direnv does not strand the worktree', () => {
// Why (regression): a PR worktree's only terminal can die on startup (a
// failing .envrc/direnv). pty-connection keeps that dead pane mounted
+11 -1
View File
@@ -1871,6 +1871,16 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
}))
const reconciledUnifiedTabs =
restoredLegacyTabs.length > 0 ? [...unifiedTabs, ...restoredLegacyTabs] : unifiedTabs
// Why: when a freshly-ensured group has no active tab yet, seed it from the
// worktree's remembered selection before the first restored tab. Otherwise
// returning to a worktree whose terminals only exist in the runtime slice
// always reopens on Terminal 1 and drops the tab the user left on.
const rememberedLegacyActiveTabId = state.activeTabIdByWorktree[worktreeId]
const restoredLegacyTabIds = new Set(restoredLegacyTabs.map((tab) => tab.id))
const legacyFallbackActiveTabId =
rememberedLegacyActiveTabId && restoredLegacyTabIds.has(rememberedLegacyActiveTabId)
? rememberedLegacyActiveTabId
: (restoredLegacyTabs[0]?.id ?? null)
const reconciledGroups =
restoredLegacyTabs.length > 0 && reconciliationGroup
? updateGroup(ensuredGroupState!.groupsByWorktree[worktreeId] ?? [], {
@@ -1879,7 +1889,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
// after split groups became the source of truth. Restoring them
// into the active/root group keeps existing live PTYs reachable
// instead of making activation spawn a duplicate "Terminal 2".
activeTabId: reconciliationGroup.activeTabId ?? restoredLegacyTabs[0]?.id ?? null,
activeTabId: reconciliationGroup.activeTabId ?? legacyFallbackActiveTabId,
tabOrder: dedupeTabOrder([
...reconciliationGroup.tabOrder,
...restoredLegacyTabs.map((tab) => tab.id)
@@ -97,7 +97,14 @@ import {
getDefaultWorkspaceSession
} from '../../../../shared/constants'
import { folderWorkspaceKey, worktreeWorkspaceKey } from '../../../../shared/workspace-scope'
import { createTestStore, makeLayout, makeTab, makeWorktree, seedStore } from './store-test-helpers'
import {
createTestStore,
makeLayout,
makeTab,
makeWorktree,
seedStore,
TEST_REPO
} from './store-test-helpers'
import { canGoBackWorktreeHistory } from './worktree-nav-history'
describe('hydrateWorkspaceSession', () => {
@@ -418,6 +425,40 @@ describe('hydrateWorkspaceSession', () => {
])
})
it('stashes deferred SSH session ids for worktrees not yet in worktreesByRepo', async () => {
// Why: at cold start SSH worktrees are absent from worktreesByRepo (relay
// discovery needs the connection). The deferred stash must fall back to
// the repo id embedded in the composite worktree id — otherwise restored
// SSH panes fresh-spawn into a missing PTY provider and strand an
// "SSH connection is not active" toast.
const store = createTestStore()
const worktreeId = 'repo1::/home/user/remote-project'
const sshSessionId = 'ssh:ssh-target-1@@pty-7'
seedStore(store, {
repos: [{ ...TEST_REPO, connectionId: 'ssh-target-1' }],
worktreesByRepo: {}
})
const session: WorkspaceSessionState = {
activeRepoId: 'repo1',
activeWorktreeId: worktreeId,
activeTabId: 'tab-1',
tabsByWorktree: {
[worktreeId]: [makeTab({ id: 'tab-1', worktreeId, ptyId: null })]
},
terminalLayoutsByTabId: {},
activeWorktreeIdsOnShutdown: [worktreeId],
remoteSessionIdsByTabId: { 'tab-1': sshSessionId }
}
store.getState().hydrateWorkspaceSession(session)
await store.getState().reconnectPersistedTerminals()
expect(store.getState().deferredSshSessionIdsByTabId).toMatchObject({
'tab-1': sshSessionId
})
})
it('resets persisted agent titles to the fallback label on hydration', () => {
const store = createTestStore()
const worktreeId = 'repo1::/wt-1'
+6 -1
View File
@@ -3315,7 +3315,12 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
const worktree = Object.values(get().worktreesByRepo)
.flat()
.find((entry) => entry.id === worktreeId)
const repo = worktree ? get().repos.find((entry) => entry.id === worktree.repoId) : null
// Why: SSH worktrees aren't in worktreesByRepo at cold start (relay
// discovery needs the connection). Fall back to the repo id embedded in
// the composite worktree id so their sessions still reach the deferred
// map — otherwise panes fresh-spawn into a missing PTY provider.
const repoId = worktree?.repoId ?? getRepoIdFromWorktreeId(worktreeId)
const repo = repoId ? get().repos.find((entry) => entry.id === repoId) : null
if (!repo?.connectionId) {
continue
}
+38
View File
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest'
import { toSshExecutionHostId } from './execution-host'
import { parseAppSshPtyId, toAppSshPtyId, toRelaySshPtyId } from './ssh-pty-id'
describe('ssh pty id routing', () => {
const CONNECTION = 'ssh-1779863656395-57g1q1'
const HOST_ID = toSshExecutionHostId(CONNECTION) // "ssh:ssh-1779863656395-57g1q1"
const APP_ID = toAppSshPtyId(CONNECTION, 'pty-3') // "ssh:ssh-1779863656395-57g1q1@@pty-3"
it('encodes the bare target id into the app pty id', () => {
expect(APP_ID).toBe('ssh:ssh-1779863656395-57g1q1@@pty-3')
expect(parseAppSshPtyId(APP_ID)).toEqual({ connectionId: CONNECTION, relayPtyId: 'pty-3' })
})
it('round-trips app <-> relay ids for the matching bare connection', () => {
expect(toRelaySshPtyId(CONNECTION, APP_ID)).toBe('pty-3')
expect(toAppSshPtyId(CONNECTION, APP_ID)).toBe(APP_ID)
})
// Why: reconnect/restore callers may pass the execution-host id form
// ("ssh:<targetId>") from a workspace `hostId`; it names the same connection
// as the bare id embedded in the app pty id and must not throw or misencode.
it('accepts the execution-host id form as the same connection', () => {
expect(toRelaySshPtyId(HOST_ID, APP_ID)).toBe('pty-3')
expect(toAppSshPtyId(HOST_ID, APP_ID)).toBe(APP_ID)
// A fresh app id built from the host-id form still stores the bare id.
expect(toAppSshPtyId(HOST_ID, 'pty-7')).toBe('ssh:ssh-1779863656395-57g1q1@@pty-7')
})
it('still rejects a pty id owned by a genuinely different connection', () => {
expect(() => toRelaySshPtyId('ssh-other', APP_ID)).toThrow(
`belongs to SSH connection "${CONNECTION}"`
)
expect(() => toAppSshPtyId(toSshExecutionHostId('ssh-other'), APP_ID)).toThrow(
`belongs to SSH connection "${CONNECTION}"`
)
})
})
+16 -3
View File
@@ -1,6 +1,18 @@
import { parseExecutionHostId } from './execution-host'
const SSH_PTY_ID_PREFIX = 'ssh:'
const SSH_PTY_ID_SEPARATOR = '@@'
// Why: reconnect/restore paths sometimes hand these routers the execution-host
// id form ("ssh:<targetId>", from a workspace `hostId`) instead of the bare SSH
// target id that app PTY ids embed. Both name the same connection, so collapse
// to the bare id before comparing/encoding — otherwise a valid reattach throws a
// spurious "belongs to SSH connection" error at the user.
function normalizeConnectionId(connectionId: string): string {
const parsed = parseExecutionHostId(connectionId)
return parsed?.kind === 'ssh' ? parsed.targetId : connectionId
}
// Why: SSH relays allocate target-local ids like "pty-1"; app-wide routing
// needs the target id embedded so two relays cannot collide after restore.
export type ParsedSshPtyId = {
@@ -32,14 +44,15 @@ export function parseAppSshPtyId(ptyId: string): ParsedSshPtyId | null {
}
export function toAppSshPtyId(connectionId: string, relayPtyId: string): string {
const normalizedConnectionId = normalizeConnectionId(connectionId)
const parsed = parseAppSshPtyId(relayPtyId)
if (parsed) {
if (parsed.connectionId !== connectionId) {
if (parsed.connectionId !== normalizedConnectionId) {
throw new Error(`PTY ${relayPtyId} belongs to SSH connection "${parsed.connectionId}"`)
}
return relayPtyId
}
return `${SSH_PTY_ID_PREFIX}${encodeURIComponent(connectionId)}${SSH_PTY_ID_SEPARATOR}${relayPtyId}`
return `${SSH_PTY_ID_PREFIX}${encodeURIComponent(normalizedConnectionId)}${SSH_PTY_ID_SEPARATOR}${relayPtyId}`
}
export function toRelaySshPtyId(connectionId: string, ptyId: string): string {
@@ -47,7 +60,7 @@ export function toRelaySshPtyId(connectionId: string, ptyId: string): string {
if (!parsed) {
return ptyId
}
if (parsed.connectionId !== connectionId) {
if (parsed.connectionId !== normalizeConnectionId(connectionId)) {
throw new Error(`PTY ${ptyId} belongs to SSH connection "${parsed.connectionId}"`)
}
return parsed.relayPtyId
+10
View File
@@ -2784,6 +2784,16 @@ export type GlobalSettings = {
geminiCliOAuthEnabled: boolean
/** Per-agent CLI command overrides. A missing key means use the catalog default binary name. */
agentCmdOverrides: Partial<Record<TuiAgent, string>>
/** Why: Orca bridges Codex session history from the user's real Codex home into
* its managed home so /resume finds it, but defaults to ~/.codex. Users who run
* Codex with a custom CODEX_HOME can point history discovery at that folder here.
* History-only: this does not change which account/config/hooks Orca uses. */
codexSessionSourceHome?: {
/** Absolute host path; empty/undefined falls back to ~/.codex. */
host?: string
/** Per-WSL-distro absolute Linux path; missing distro falls back to <wslHome>/.codex. */
wsl?: Record<string, string>
}
/** Per-agent default CLI arguments appended after the binary/path and before prompts. */
agentDefaultArgs?: Partial<Record<TuiAgent, string>>
/** Per-agent launch environment defaults used when yolo mode is exposed as env. */
@@ -79,6 +79,9 @@ type HiddenPressureAckGate = {
// a loaded OSS runner the drain-plus-poll overhead was seen at ~3.2s, so keep a
// ceiling with headroom that still catches an order-of-magnitude regression.
const MAX_HIDDEN_RESTORE_LATENCY_MS = 4_000
// Why: in this hidden real-PTY pressure case, maxTimerDriftMs and worst-key
// latency catch the same isolated CI starvation spike; median remains strict.
const MAX_HIDDEN_PRESSURE_TIMER_DRIFT_MS = 3_000
export function pressureOutputScript(runId: string): string {
return `
@@ -215,11 +218,7 @@ export async function runHiddenRealPtyPressureScenario<
// detector — the original regression (input freezing for seconds) shows up in
// the median too. Aligns with ssh-docker-relay-perf's 2s worst-key tolerance.
expect(measurement.worstLatencyMs).toBeLessThan(3_000)
// Why: maxTimerDriftMs is a single-worst-tick metric that spikes on a loaded
// OSS runner (seen at 155ms under 8MB of in-flight backpressure). Median above
// is the real responsiveness guard; align the spike tolerance with the sibling
// terminal-load suite's MAX_TIMER_DRIFT_MS.
expect(measurement.maxTimerDriftMs).toBeLessThan(250)
expect(measurement.maxTimerDriftMs).toBeLessThan(MAX_HIDDEN_PRESSURE_TIMER_DRIFT_MS)
await deps.releaseTerminalAckGate(orcaPage)
const restoreLatencyMs = await measureHiddenOutputRestoreLatency(
@@ -79,6 +79,8 @@ function stripTerminalControls(value: string): string {
const CODEX_READY_RE = /Ask Codex|OpenAI/i
const CODEX_TRUST_PROMPT_RE = /Do you trust|trust this folder|Trust this/i
const CODEX_UPDATE_PROMPT_RE = /update available|install update|Skip for now/i
const LINUX_IME_POLICY_USER_AGENT =
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/146 Safari/537.36'
function terminalImeHarnessScript(runId: string): string {
return `
@@ -229,6 +231,9 @@ async function installImeEventProbe(page: Page): Promise<void> {
]) {
textarea.addEventListener(type, record, true)
}
// Why: the Linux/Sogou post-composition guard lives on the terminal
// element; record terminal-targeted compositionend without doubling key logs.
pane.terminal.element?.addEventListener('compositionend', record, true)
})
}
@@ -239,6 +244,19 @@ async function readImeEventLog(page: Page): Promise<ImeEventLogEntry[]> {
})
}
async function reloadWithLinuxImePolicy(page: Page): Promise<void> {
await page.addInitScript((userAgent) => {
Object.defineProperty(navigator, 'userAgent', {
get: () => userAgent,
configurable: true
})
}, LINUX_IME_POLICY_USER_AGENT)
// Why: the Sogou repro validates Linux-gated terminal IME policy on macOS
// runners; reload before the terminal pane mounts so lifecycle code sees it.
await page.reload({ waitUntil: 'domcontentloaded' })
await page.waitForFunction(() => Boolean(window.__store), null, { timeout: 30_000 })
}
async function readPromptState(page: Page): Promise<TerminalPromptState | null> {
const content = stripTerminalControls(await getTerminalContent(page, 20_000))
const matches = [...content.matchAll(/\[SUBMITTED_JSON_[^\]]+\]("[\s\S]*?")/g)]
@@ -320,6 +338,64 @@ async function dispatchImeProcessKey(session: CDPSession, code: string): Promise
})
}
async function dispatchCandidateSelectionKey(
session: CDPSession,
candidate: { key: string; code: string; keyCode: number },
commitBetweenKeys?: () => Promise<void>
): Promise<void> {
// Why: #7543 proves Sogou can forward candidate selectors as plain key
// events, not Process/229. `text` is set so keyDown produces the natural
// keypress — rawKeyDown generates none and would prove nothing about leaks.
await session.send('Input.dispatchKeyEvent', {
type: 'keyDown',
key: candidate.key,
code: candidate.code,
windowsVirtualKeyCode: candidate.keyCode,
nativeVirtualKeyCode: candidate.keyCode,
text: candidate.key,
unmodifiedText: candidate.key
})
// Why: committing between keyDown and keyUp keeps xterm's _keyDownSeen set,
// matching the trace shape where an insertText commit is actually at risk.
await commitBetweenKeys?.()
await session.send('Input.dispatchKeyEvent', {
type: 'keyUp',
key: candidate.key,
code: candidate.code,
windowsVirtualKeyCode: candidate.keyCode,
nativeVirtualKeyCode: candidate.keyCode
})
}
async function dispatchSogouEmptyCompositionUpdate(page: Page): Promise<void> {
// Why: Sogou/fcitx emits empty compositionupdate data while its candidate
// popup is still open (#6765); Orca's tracker must not flip inactive on it.
await page.evaluate(() => {
const active = document.activeElement
if (!(active instanceof HTMLTextAreaElement)) {
throw new Error('xterm helper textarea is not focused')
}
active.dispatchEvent(new CompositionEvent('compositionupdate', { data: '', bubbles: true }))
})
}
async function dispatchSogouPostCompositionEnd(page: Page, data: string): Promise<void> {
// Why: some Sogou/fcitx traces deliver the plain selector key after
// compositionend; target the terminal element so Orca's tracker sees the end
// without making xterm finalize a synthetic preedit string.
await page.evaluate((data) => {
const active = document.activeElement
if (!(active instanceof HTMLTextAreaElement)) {
throw new Error('xterm helper textarea is not focused')
}
const terminalElement = active.closest('.xterm')
if (!(terminalElement instanceof HTMLElement)) {
throw new Error('xterm terminal element was not found')
}
terminalElement.dispatchEvent(new CompositionEvent('compositionend', { data, bubbles: false }))
}, data)
}
async function composeAndCommitChineseText(
session: CDPSession,
page: Page,
@@ -473,6 +549,124 @@ test.describe('Chinese IME terminal chat input repro', () => {
}
})
test('keeps Sogou-style candidate selection keys out of the PTY while committing Chinese text', async ({
orcaPage,
testRepoPath
}, testInfo) => {
await reloadWithLinuxImePolicy(orcaPage)
await waitForSessionReady(orcaPage)
await waitForActiveWorktree(orcaPage)
await ensureTerminalVisible(orcaPage)
await waitForActiveTerminalManager(orcaPage, 30_000)
const ptyId = await waitForActivePanePtyId(orcaPage)
const runId = randomUUID()
const scriptPath = path.join(testRepoPath, `.orca-sogou-ime-harness-${runId}.cjs`)
let session: CDPSession | null = null
let harnessStarted = false
try {
// Why: create the session/harness inside the try so a mid-setup throw
// still hits finally and removes the harness script.
writeFileSync(scriptPath, terminalImeHarnessScript(runId))
session = await orcaPage.context().newCDPSession(orcaPage)
await sendToTerminal(orcaPage, ptyId, `node ${JSON.stringify(scriptPath)}\r`)
harnessStarted = true
await waitForTerminalOutput(orcaPage, `IME_HARNESS_READY_${runId}`, 10_000, 20_000)
await focusActiveTerminalInput(orcaPage)
await installImeEventProbe(orcaPage)
// Space selects the first candidate. Sogou keeps emitting empty
// compositionupdate frames while the popup is open, and the plain Space
// press arrives around the commit rather than as a Process/229 key.
await setImeComposition(session, 'n')
await orcaPage.waitForTimeout(80)
await setImeComposition(session, 'ni')
await orcaPage.waitForTimeout(80)
await dispatchSogouEmptyCompositionUpdate(orcaPage)
await dispatchCandidateSelectionKey(session, { key: ' ', code: 'Space', keyCode: 32 }, () =>
commitImeText(session, '你')
)
await waitForLivePrompt(orcaPage, '你')
await attachImeEvidence(orcaPage, testInfo, 'sogou-after-space-commit')
await orcaPage.keyboard.press('Enter')
await expect
.poll(async () => (await readPromptState(orcaPage))?.submitted.at(-1) ?? null, {
timeout: 5_000,
message: 'space-selected candidate did not submit the committed Chinese character'
})
.toBe('你')
// Digit selects a non-first candidate for a word/phrase commit — the
// #7543 shape where only the number used to reach the TUI.
await setImeComposition(session, 'nihao')
await orcaPage.waitForTimeout(80)
await dispatchSogouEmptyCompositionUpdate(orcaPage)
await dispatchCandidateSelectionKey(session, { key: '2', code: 'Digit2', keyCode: 50 }, () =>
commitImeText(session, '你好')
)
await waitForLivePrompt(orcaPage, '你好')
await attachImeEvidence(orcaPage, testInfo, 'sogou-after-digit-commit')
await orcaPage.keyboard.press('Enter')
await expect
.poll(async () => (await readPromptState(orcaPage))?.submitted.at(-1) ?? null, {
timeout: 5_000,
message: 'digit-selected candidate did not submit the committed Chinese phrase'
})
.toBe('你好')
// Post-composition traces can deliver the selector after compositionend;
// the short post-end guard must still keep that plain digit out of the PTY.
const postCompositionLogStart = (await readImeEventLog(orcaPage)).length
await setImeComposition(session, 'zaijian')
await orcaPage.waitForTimeout(80)
await dispatchSogouEmptyCompositionUpdate(orcaPage)
await dispatchSogouPostCompositionEnd(orcaPage, '再见')
await dispatchCandidateSelectionKey(session, { key: '3', code: 'Digit3', keyCode: 51 }, () =>
commitImeText(session, '再见')
)
await waitForLivePrompt(orcaPage, '再见')
const postCompositionLog = await readImeEventLog(orcaPage)
const postCompositionEndIndex = postCompositionLog.findIndex(
(entry, index) =>
index >= postCompositionLogStart && entry.type === 'compositionend' && entry.data === '再见'
)
const postCompositionSelectorIndex = postCompositionLog.findIndex(
(entry, index) =>
index > postCompositionEndIndex && entry.type === 'keydown' && entry.key === '3'
)
expect(
postCompositionEndIndex,
'Sogou post-composition repro must dispatch compositionend before the plain selector'
).toBeGreaterThanOrEqual(postCompositionLogStart)
expect(
postCompositionSelectorIndex,
'plain digit selector must arrive after compositionend in the post-composition repro'
).toBeGreaterThan(postCompositionEndIndex)
await attachImeEvidence(orcaPage, testInfo, 'sogou-after-post-composition-digit-commit')
await orcaPage.keyboard.press('Enter')
await expect
.poll(async () => (await readPromptState(orcaPage))?.submitted.at(-1) ?? null, {
timeout: 5_000,
message: 'post-composition digit-selected candidate did not submit cleanly'
})
.toBe('再见')
const promptState = await readPromptState(orcaPage)
expect(
promptState?.submitted,
'candidate Space/digit selectors and pinyin preedit must not leak into the PTY'
).toEqual(['你', '你好', '再见'])
} finally {
await attachImeEvidence(orcaPage, testInfo, 'sogou-final-ime-evidence').catch(() => undefined)
await session?.detach().catch(() => undefined)
if (harnessStarted) {
await sendToTerminal(orcaPage, ptyId, '\x03').catch(() => undefined)
}
rmSync(scriptPath, { force: true })
}
})
test('keeps composed Chinese text stable in the real Codex TUI input @real-codex-ime', async ({
orcaPage
}, testInfo) => {