fix(run-actions): follow cloud tabs adopted as web-terminal-<id>, settle tab-list churn before forgetting a run, retire the dead tab after a relaunch; honor a host-pinned ORCA_PORT

Found on a real Orca Cloud VM (m4air): a remote host adopts the run's tab under web-terminal-<id>,
so the run was pruned at once and Stop/status/relaunch lost it; a window reload's empty tab list
pruned local runs too. Pruning now waits for the list to settle (3 s; 15 s after startup).
A one-workspace host (the VM launcher sets ORCA_PORT=3000) keeps its pinned block.
This commit is contained in:
Neil
2026-11-10 02:22:07 -08:00
parent ebec244447
commit 2cf08c221e
12 changed files with 154 additions and 27 deletions
+1 -1
View File
@@ -133,7 +133,7 @@ scripts:
- `autoRunAfterSetup` starts the action once the Setup terminal's script succeeds.
- Shared `orca.yaml` actions go through the same approval prompt as setup scripts. Actions imported into local settings are treated as your own.
Every terminal in a worktree gets a stable block of 10 ports: `ORCA_PORT` through `ORCA_PORT+9` (`ORCA_PORT_COUNT` is `10`). Two worktrees on the same host never share a block, so the same dev server can run in each without port collisions. `CONDUCTOR_PORT` is set to the same value, so imported Conductor scripts work unchanged. Ports a run opens appear in the Run menu and the **Ports** panel.
Every terminal in a worktree gets a stable block of 10 ports: `ORCA_PORT` through `ORCA_PORT+9` (`ORCA_PORT_COUNT` is `10`). Two worktrees on the same host never share a block, so the same dev server can run in each without port collisions. `CONDUCTOR_PORT` is set to the same value, so imported Conductor scripts work unchanged. A host that runs a single workspace can pin the block by starting Orca with `ORCA_PORT` (and optionally `ORCA_PORT_COUNT`) set. Ports a run opens appear in the Run menu and the **Ports** panel.
### Terminal defaults and issue commands
+3 -1
View File
@@ -8,6 +8,7 @@ import { isTerminalLeafId, makePaneKey } from '../../../shared/workspace-layout/
import { isValidTerminalTabId } from '../../../shared/workspace-layout/terminal-tab-id'
import {
buildWorkspacePortEnv,
hostPinnedPortBlock,
WORKSPACE_PORT_ENV_KEYS
} from '../../../shared/workspace-port-block'
import { getWorkspacePortBlockForWorktreeId } from '../../workspace-ports/workspace-port-block-registry'
@@ -95,7 +96,8 @@ export async function stampWorkspacePortEnv(
return
}
try {
const block = await getWorkspacePortBlockForWorktreeId(worktreeId)
const block =
hostPinnedPortBlock(process.env) ?? (await getWorkspacePortBlockForWorktreeId(worktreeId))
if (block) {
Object.assign(env, buildWorkspacePortEnv(block))
}
@@ -1,7 +1,7 @@
import { getRuntimePathBasename } from '../../shared/cross-platform-path'
import { TERMINAL_GIT_CREDENTIAL_GUARD_POLICY_ENV } from '../../shared/shell/launch/terminal-git-credential-guard'
import type { Repo } from '../../shared/repo-types'
import { buildWorkspacePortEnv } from '../../shared/workspace-port-block'
import { buildWorkspacePortEnv, hostPinnedPortBlock } from '../../shared/workspace-port-block'
import { peekWorkspacePortBlock } from '../workspace-ports/workspace-port-block-registry'
// Path-valued keys only, so WSL and posix-shell launches translate them; names are not paths.
@@ -33,7 +33,7 @@ export function getSetupEnvVars(
function getWorkspacePortEnv(worktreePath: string): Record<string, string> {
try {
// Setup terminals get the block from their own spawn; this covers hook processes run directly.
const block = peekWorkspacePortBlock(worktreePath)
const block = hostPinnedPortBlock(process.env) ?? peekWorkspacePortBlock(worktreePath)
return block ? buildWorkspacePortEnv(block) : {}
} catch {
return {}
@@ -6,7 +6,8 @@ import {
WORKSPACE_PORT_BLOCK_SIZE,
WORKSPACE_PORT_RANGE_END,
WORKSPACE_PORT_RANGE_START,
buildWorkspacePortEnv
buildWorkspacePortEnv,
hostPinnedPortBlock
} from '../../shared/workspace-port-block'
import { WorkspacePortBlockRegistry } from './workspace-port-block-registry'
@@ -124,3 +125,21 @@ describe('peekBlock', () => {
expect(new Set(blocks.map((block) => block.base)).size).toBe(20)
})
})
describe('hostPinnedPortBlock', () => {
it('honors a launcher-pinned ORCA_PORT on a one-workspace host', () => {
expect(hostPinnedPortBlock({ ORCA_PORT: '3000' })).toEqual({ base: 3000, count: 10 })
expect(hostPinnedPortBlock({ ORCA_PORT: '3000', ORCA_PORT_COUNT: '5' })).toEqual({
base: 3000,
count: 5
})
})
it('ignores a block inherited from a parent Orca pane, and bad values', () => {
expect(hostPinnedPortBlock({ ORCA_PORT: '28570', ORCA_WORKTREE_ID: 'r::/w' })).toBeNull()
expect(hostPinnedPortBlock({ ORCA_PORT: '28570', ORCA_PANE_KEY: 't:l' })).toBeNull()
expect(hostPinnedPortBlock({ ORCA_PORT: 'abc' })).toBeNull()
expect(hostPinnedPortBlock({ ORCA_PORT: '80' })).toBeNull()
expect(hostPinnedPortBlock({})).toBeNull()
})
})
@@ -13,6 +13,7 @@ import { startRunAction, stopRunAction } from '@/lib/run-actions/run-action-cont
import { useWorktreeRunActionRuns, type RunActionRun } from '@/lib/run-actions/run-actions-store'
import type { WorkspacePort } from '../../../../shared/workspace-ports'
import { RunActionButtonView } from './RunActionButtonView'
import { findLiveRunTabId } from '@/lib/run-actions/run-action-tabs'
const EMPTY_PORTS: WorkspacePort[] = []
@@ -57,7 +58,7 @@ function useWorktreePorts(worktreeId: string): WorkspacePort[] {
function focusRunTab(run: RunActionRun): void {
const state = useAppStore.getState()
state.setActiveTabType('terminal', run.worktreeId)
state.setActiveTab(run.tabId)
state.setActiveTab(findLiveRunTabId(state, run.worktreeId, run.tabId) ?? run.tabId)
}
function openPortsPanel(): void {
@@ -34,7 +34,12 @@ export function resolveRunActionTarget(
state: AppState,
worktreeId: string
): RunActionTarget | null {
const worktree = findWorktreeById(state, worktreeId)
// The active-host hint can disagree for remote workspaces; fall back to the catalog row itself.
const worktree =
findWorktreeById(state, worktreeId) ??
Object.values(state.worktreesByRepo ?? {})
.flat()
.find((candidate) => candidate.id === worktreeId)
if (!worktree) {
return null
}
@@ -318,16 +318,44 @@ describe('run actions', () => {
expect(getRunActionRun(WT_A, 'web')?.status).toBe('running')
})
it('forgets a run when its terminal is closed', async () => {
it('forgets a run only when its terminal is still gone after the tab list settles', async () => {
await startRunAction(WT_A, web, config([web]))
const previous = { tabsByWorktree: { ...state.tabsByWorktree } }
state.tabsByWorktree = { [WT_A]: [] }
for (const listener of mocks.subscribers) {
listener(state, previous)
const { tabId } = getRunActionRun(WT_A, 'web')!
const notify = (): void => {
const previous = { tabsByWorktree: {} }
for (const listener of mocks.subscribers) {
listener(state, previous)
}
}
// A window reload briefly shows an empty list, then the tab comes back: keep the run.
const kept = state.tabsByWorktree[WT_A]
state.tabsByWorktree = { [WT_A]: [] }
notify()
state.tabsByWorktree = { [WT_A]: kept }
await vi.advanceTimersByTimeAsync(16_000)
expect(getRunActionRun(WT_A, 'web')?.tabId).toBe(tabId)
// Really closed: gone after the settle delay.
state.tabsByWorktree = { [WT_A]: [] }
notify()
await vi.advanceTimersByTimeAsync(3_500)
expect(getRunActionRun(WT_A, 'web')).toBeNull()
})
it('follows a run whose tab a remote host adopted under a web-terminal- id', async () => {
await startRunAction(WT_A, web, config([web]))
const { tabId } = getRunActionRun(WT_A, 'web')!
const adopted = `web-terminal-${tabId}`
state.tabsByWorktree = { [WT_A]: [{ id: adopted }] }
state.ptyIdsByTabId[adopted] = ['pty-adopted']
for (const listener of mocks.subscribers) {
listener(state, { tabsByWorktree: {} })
}
await vi.advanceTimersByTimeAsync(16_000)
expect(getRunActionRun(WT_A, 'web')?.status).toBe('running')
dispatchTerminalCommandFinishedEvent(WT_A, 2, adopted)
expect(getRunActionRun(WT_A, 'web')).toMatchObject({ status: 'failed', exitCode: 2 })
})
it('merges local actions over orca.yaml ones and filters by host', async () => {
const remoteOnly: OrcaRunAction = {
id: 'cloud',
@@ -20,10 +20,12 @@ import {
type RunActionTarget,
type WorktreeRunActions
} from './run-action-config'
import { findLiveRunTabId, sameRunTab } from './run-action-tabs'
/** Conductor's grace period: an interrupted dev server gets this long before its shell is closed. */
export const RUN_ACTION_STOP_GRACE_MS = 5_000
const INTERRUPT = '\x03'
const RELAUNCH_TAB_SETTLE_MS = 5_000
function joinWorkspacePath(root: string, relative: string | undefined): string | undefined {
if (!relative) {
@@ -34,21 +36,22 @@ function joinWorkspacePath(root: string, relative: string | undefined): string |
}
export function tabExists(state: AppState, worktreeId: string, tabId: string): boolean {
return (state.tabsByWorktree[worktreeId] ?? []).some((tab) => tab.id === tabId)
return findLiveRunTabId(state, worktreeId, tabId) !== null
}
function tabGroupId(state: AppState, worktreeId: string, tabId: string): string | undefined {
return (
state.unifiedTabsByWorktree[worktreeId]?.find(
(tab) => tab.entityId === tabId && tab.contentType === 'terminal'
(tab) => sameRunTab(tab.entityId, tabId) && tab.contentType === 'terminal'
)?.groupId ?? undefined
)
}
function closeRunTab(run: RunActionRun): void {
const state = useAppStore.getState()
if (tabExists(state, run.worktreeId, run.tabId)) {
state.closeTab(run.tabId, { recordInteraction: false, captureRecentlyClosed: false })
const liveTabId = findLiveRunTabId(state, run.worktreeId, run.tabId)
if (liveTabId) {
state.closeTab(liveTabId, { recordInteraction: false, captureRecentlyClosed: false })
}
}
@@ -97,8 +100,9 @@ async function stopRunActionOnce(worktreeId: string, actionId: string): Promise<
return
}
const state = useAppStore.getState()
const ptyId = state.ptyIdsByTabId[run.tabId]?.[0]
if (!ptyId || !tabExists(state, worktreeId, run.tabId)) {
const liveTabId = findLiveRunTabId(state, worktreeId, run.tabId)
const ptyId = liveTabId ? state.ptyIdsByTabId[liveTabId]?.[0] : undefined
if (!ptyId) {
deleteRunActionRun(worktreeId, actionId)
return
}
@@ -314,6 +318,13 @@ export async function relaunchInterruptedRunActions(worktreeId: string): Promise
})
if (ok) {
started += 1
// The restarted host republishes its old tabs after a moment; retire the dead run tab then.
setTimeout(() => {
const current = getRunActionRun(worktreeId, run.actionId)
if (!current || !sameRunTab(current.tabId, run.tabId)) {
closeRunTab(run)
}
}, RELAUNCH_TAB_SETTLE_MS)
}
}
return started
@@ -16,6 +16,7 @@ import {
patchRunActionRun
} from './run-actions-store'
import { loadWorktreeRunActions, pickPrimaryRunAction } from './run-action-config'
import { findLiveRunTabId, sameRunTab } from './run-action-tabs'
import {
isRunActionRelaunchArmed,
notifyRunActionStopped,
@@ -46,9 +47,10 @@ function handleCommandFinished(detail: TerminalCommandFinishedEventDetail): void
if (!tabId) {
return
}
const setupWorktreeId = autoRunSetupTabs.get(tabId)
if (setupWorktreeId) {
autoRunSetupTabs.delete(tabId)
const setupTabId = [...autoRunSetupTabs.keys()].find((armed) => sameRunTab(armed, tabId))
const setupWorktreeId = setupTabId ? autoRunSetupTabs.get(setupTabId) : undefined
if (setupTabId && setupWorktreeId) {
autoRunSetupTabs.delete(setupTabId)
if (exitCode === 0) {
void autoRunAfterSetup(setupWorktreeId)
}
@@ -76,14 +78,14 @@ function pruneClosedRunTabs(state: AppState): void {
}
const tabs = state.tabsByWorktree[run.worktreeId]
// Unhydrated workspaces have no tab list yet; only a loaded list proves the tab is gone.
if (tabs && !tabs.some((tab) => tab.id === run.tabId)) {
if (tabs && !findLiveRunTabId(state, run.worktreeId, run.tabId)) {
deleteRunActionRun(run.worktreeId, run.actionId)
notifyRunActionStopped(run.tabId)
}
}
for (const [tabId, worktreeId] of autoRunSetupTabs) {
const tabs = state.tabsByWorktree[worktreeId]
if (tabs && !tabs.some((tab) => tab.id === tabId)) {
if (tabs && !findLiveRunTabId(state, worktreeId, tabId)) {
autoRunSetupTabs.delete(tabId)
}
}
@@ -97,10 +99,19 @@ export function installRunActionEvents(): () => void {
}
}
window.addEventListener(ORCA_TERMINAL_COMMAND_FINISHED_EVENT, onFinished)
// Tab lists churn while a window hydrates or a host republishes its tabs: only a tab still
// missing after things settle was really closed.
let pruneTimer: ReturnType<typeof setTimeout> | null = null
const installedAt = Date.now()
const unsubscribe = useAppStore.subscribe((state, previous) => {
if (state.tabsByWorktree !== previous.tabsByWorktree) {
pruneClosedRunTabs(state)
if (state.tabsByWorktree === previous.tabsByWorktree || pruneTimer) {
return
}
const delay = Math.max(PRUNE_SETTLE_MS, installedAt + STARTUP_PRUNE_GRACE_MS - Date.now())
pruneTimer = setTimeout(() => {
pruneTimer = null
pruneClosedRunTabs(useAppStore.getState())
}, delay)
})
// After a restart, a run recorded as running may have ended while nobody watched its terminal.
const reconcileTimer = setTimeout(
@@ -111,16 +122,22 @@ export function installRunActionEvents(): () => void {
window.removeEventListener(ORCA_TERMINAL_COMMAND_FINISHED_EVENT, onFinished)
unsubscribe()
clearTimeout(reconcileTimer)
if (pruneTimer) {
clearTimeout(pruneTimer)
}
}
}
const STARTUP_RECONCILE_MS = 5_000
const PRUNE_SETTLE_MS = 3_000
const STARTUP_PRUNE_GRACE_MS = 15_000
/** Local terminals can say whether anything still runs under the shell; remote ones are left as recorded. */
async function reconcileLocalRunsAfterStartup(): Promise<void> {
const state = useAppStore.getState()
for (const run of listRunActionRuns()) {
const ptyId = state.ptyIdsByTabId[run.tabId]?.[0]
const liveTabId = findLiveRunTabId(state, run.worktreeId, run.tabId)
const ptyId = liveTabId ? state.ptyIdsByTabId[liveTabId]?.[0] : undefined
if (run.status !== 'running' || !ptyId || getRemoteRuntimePtyOwner(ptyId)) {
continue
}
@@ -0,0 +1,23 @@
import type { AppState } from '@/store/types'
/** A remote host adopts a tab the window created under `web-terminal-<id>`; both name one tab. */
const MIRRORED_TAB_PREFIX = 'web-terminal-'
export function baseRunTabId(tabId: string): string {
return tabId.startsWith(MIRRORED_TAB_PREFIX) ? tabId.slice(MIRRORED_TAB_PREFIX.length) : tabId
}
export function sameRunTab(a: string, b: string): boolean {
return baseRunTabId(a) === baseRunTabId(b)
}
/** The id the run's tab has now, or null when the workspace no longer has it. */
export function findLiveRunTabId(
state: Pick<AppState, 'tabsByWorktree'>,
worktreeId: string,
tabId: string
): string | null {
return (
(state.tabsByWorktree[worktreeId] ?? []).find((tab) => sameRunTab(tab.id, tabId))?.id ?? null
)
}
@@ -1,4 +1,5 @@
import { useSyncExternalStore } from 'react'
import { sameRunTab } from './run-action-tabs'
/** `stopping` waits for the process to leave after an interrupt; `stopped` was the user's doing. */
export type RunActionStatus = 'running' | 'stopping' | 'stopped' | 'exited' | 'failed'
@@ -112,7 +113,7 @@ export function listRunActionRuns(): RunActionRun[] {
}
export function findRunActionRunByTab(tabId: string): RunActionRun | null {
return listRunActionRuns().find((run) => run.tabId === tabId) ?? null
return listRunActionRuns().find((run) => sameRunTab(run.tabId, tabId)) ?? null
}
export function setRunActionRun(run: RunActionRun): void {
+20
View File
@@ -24,3 +24,23 @@ export function buildWorkspacePortEnv(block: WorkspacePortBlock): Record<string,
export function isPortInWorkspaceBlock(port: number, block: WorkspacePortBlock): boolean {
return port >= block.base && port < block.base + block.count
}
/**
* A host that runs exactly one workspace (a VM launcher, say) may pin the block by starting Orca
* with ORCA_PORT set. A copy inherited from a parent Orca pane (it also carries pane identity)
* names that pane's workspace and doesn't count.
*/
export function hostPinnedPortBlock(env: NodeJS.ProcessEnv): WorkspacePortBlock | null {
if (env.ORCA_PANE_KEY || env.ORCA_WORKTREE_ID) {
return null
}
const base = Number(env.ORCA_PORT)
if (!Number.isInteger(base) || base < 1024 || base > 65535 - WORKSPACE_PORT_BLOCK_SIZE) {
return null
}
const count = Number(env.ORCA_PORT_COUNT)
return {
base,
count: Number.isInteger(count) && count > 0 && count <= 100 ? count : WORKSPACE_PORT_BLOCK_SIZE
}
}