Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/main/ipc/pty/runtime/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
writePtyFromRuntimeController
} from './operations'
import { recordUnconfirmedExplicitSshStop } from './undelivered-ssh-kill'
import { requestPtyRedrawFromRuntimeController } from './pty-redraw'
import { supportsForegroundProcessEvidenceFromRuntimeController } from './foreground-process-evidence-capability'
import {
listProcessesFromRuntimeController,
Expand Down Expand Up @@ -91,6 +92,7 @@ export function installPtyRuntimeController(deps: PtyRuntimeControllerDeps): voi
waitForRendererSerializer: (ptyId, afterGeneration, timeoutMs, signal) =>
waitForRendererSerializerFromRuntimeController(ptyId, afterGeneration, timeoutMs, signal),
getSize: (ptyId) => getSizeFromRuntimeController(ptyId),
resize: (ptyId, cols, rows) => resizePtyFromRuntimeController(ptyId, cols, rows)
resize: (ptyId, cols, rows) => resizePtyFromRuntimeController(ptyId, cols, rows),
requestRedraw: requestPtyRedrawFromRuntimeController
})
}
38 changes: 38 additions & 0 deletions src/main/ipc/pty/runtime/pty-redraw.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { requestPtyRedrawFromRuntimeController } from './pty-redraw'

const { getProviderForPty, sendSignal } = vi.hoisted(() => ({
getProviderForPty: vi.fn(),
sendSignal: vi.fn()
}))
vi.mock('../provider/registry', () => ({ getProviderForPty }))

describe('execution-host PTY redraw', () => {
beforeEach(() => {
vi.resetAllMocks()
getProviderForPty.mockReturnValue({ sendSignal })
sendSignal.mockResolvedValue(undefined)
})

it.each(['daemon-pane', 'ssh:connection-1:pty-1'])(
'routes %s through its provider',
async (id) => {
expect(await requestPtyRedrawFromRuntimeController(id)).toBe(true)
expect(getProviderForPty).toHaveBeenCalledExactlyOnceWith(id)
expect(sendSignal).toHaveBeenCalledExactlyOnceWith(id, 'SIGWINCH')
}
)

it('does not substitute a local provider when the execution host is unavailable', async () => {
getProviderForPty.mockImplementation(() => {
throw new Error('provider unavailable')
})
expect(await requestPtyRedrawFromRuntimeController('ssh:connection-1:pty-1')).toBe(false)
expect(sendSignal).not.toHaveBeenCalled()
})

it('treats an unsupported or failed signal as best-effort', async () => {
sendSignal.mockRejectedValue(new Error('signal unsupported'))
expect(await requestPtyRedrawFromRuntimeController('daemon-pane')).toBe(false)
})
})
11 changes: 11 additions & 0 deletions src/main/ipc/pty/runtime/pty-redraw.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { getProviderForPty } from '../provider/registry'

export async function requestPtyRedrawFromRuntimeController(ptyId: string): Promise<boolean> {
try {
// The provider routes SIGWINCH to the foreground group on the execution host.
await getProviderForPty(ptyId).sendSignal(ptyId, 'SIGWINCH')
return true
} catch {
return false
}
}
16 changes: 16 additions & 0 deletions src/main/runtime/orca-runtime-serialize-main-terminal-buffer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,22 @@ export class OrcaRuntimeWithSerializeMainTerminalBuffer extends OrcaRuntimeWithA
return { handle, reset: true }
}

async requestTerminalRedraw(
handle: string,
viewport: { cols: number; rows: number }
): Promise<boolean> {
// Re-resolve after the viewport await: a replacement or mobile takeover invalidates the kick.
const leaf = this.resolveLiveLeafForHandle(handle)
if (!leaf?.ptyId || this.getDriver(leaf.ptyId).kind === 'mobile') {
return false
}
const size = this.getTerminalSize(leaf.ptyId)
if (size?.cols !== viewport.cols || size.rows !== viewport.rows) {
return false
}
return (await this.ptyController?.requestRedraw?.(leaf.ptyId)) ?? false
}

getTerminalSize(ptyId: string): { cols: number; rows: number } | null {
return this.ptyController?.getSize?.(ptyId) ?? null
}
Expand Down
10 changes: 10 additions & 0 deletions src/main/runtime/rpc/methods/terminal/terminal-viewport-methods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export const TERMINAL_VIEWPORT_METHODS_BEFORE_STREAMS = [
if (!leaf?.ptyId) {
throw new Error('no_connected_pty')
}
const previousSize = params.redraw ? runtime.getTerminalSize(leaf.ptyId) : null
const viewportUpdate = await updateViewportForClient(
runtime,
leaf.ptyId,
Expand All @@ -73,6 +74,15 @@ export const TERMINAL_VIEWPORT_METHODS_BEFORE_STREAMS = [
'refresh',
params.claim === true
)
if (
params.redraw === true &&
params.client.type === 'desktop' &&
viewportUpdate.applied &&
previousSize?.cols === params.viewport.cols &&
previousSize.rows === params.viewport.rows
) {
await runtime.requestTerminalRedraw(params.terminal, params.viewport)
}
return { ...viewportUpdate, seq: runtime.getLayout(leaf.ptyId)?.seq }
}
})
Expand Down
132 changes: 132 additions & 0 deletions src/main/runtime/rpc/terminal-reattach-redraw.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import { describe, expect, it, vi } from 'vitest'
import { OrcaRuntimeService } from '../orca-runtime'
import { RpcDispatcher } from './dispatcher'
import { TERMINAL_METHODS } from './methods/terminal'

function createRedrawRuntime(initialSize = { cols: 80, rows: 24 }) {
const runtime = new OrcaRuntimeService()
const requestRedraw = vi.fn(async () => true)
let size = initialSize
runtime.setPtyController({
write: () => true,
kill: () => true,
getForegroundProcess: async () => null,
getSize: () => size,
requestRedraw
})
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: These handlers read only ptyId from the resolved leaf.
const leaf = { ptyId: 'pty-1' } as NonNullable<
ReturnType<typeof runtime.resolveLiveLeafForHandle>
>
const resolve = vi.spyOn(runtime, 'resolveLiveLeafForHandle').mockReturnValue(leaf)
const refresh = vi.spyOn(runtime, 'refreshRemoteDesktopViewer').mockResolvedValue(true)
vi.spyOn(runtime, 'getLayout').mockReturnValue(null)
const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS })
const update = (extra: { redraw?: boolean; claim?: boolean } = { redraw: true }) =>
dispatcher.dispatch({
id: 'req-1',
authToken: 'token',
method: 'terminal.updateViewport',
params: {
terminal: 'terminal-1',
client: { id: 'client-1', type: 'desktop' },
viewport: initialSize,
...extra
}
})
return {
runtime,
requestRedraw,
resolve,
refresh,
update,
setSize: (next: typeof size) => {
size = next
}
}
}

describe('remote reattach redraw through the existing viewport RPC', () => {
it('kicks an unchanged grid once without claiming control', async () => {
const { update, requestRedraw, refresh } = createRedrawRuntime()
expect((await update()).ok).toBe(true)
expect(requestRedraw).toHaveBeenCalledExactlyOnceWith('pty-1')
expect(refresh).toHaveBeenCalledWith('pty-1', 'client-1', 80, 24, false)
})

it.each([
{ cols: 20, rows: 8 },
{ cols: 240, rows: 120 }
])('kicks an unchanged host-clamped $cols×$rows grid', async (viewport) => {
const { update, requestRedraw } = createRedrawRuntime(viewport)
expect((await update()).ok).toBe(true)
expect(requestRedraw).toHaveBeenCalledExactlyOnceWith('pty-1')
})

it('leaves ordinary viewport updates unchanged', async () => {
const { update, requestRedraw } = createRedrawRuntime()
expect((await update({})).ok).toBe(true)
expect(requestRedraw).not.toHaveBeenCalled()
})

it('does not double-signal a real geometry change', async () => {
const { update, requestRedraw, setSize, refresh } = createRedrawRuntime()
setSize({ cols: 100, rows: 30 })
refresh.mockImplementation(async () => {
setSize({ cols: 80, rows: 24 })
return true
})
expect((await update()).ok).toBe(true)
expect(requestRedraw).not.toHaveBeenCalled()
})

it('does not kick a viewer whose stream has gone away', async () => {
const { update, requestRedraw, refresh } = createRedrawRuntime()
refresh.mockResolvedValue(false)
expect((await update()).ok).toBe(true)
expect(requestRedraw).not.toHaveBeenCalled()
})

it('rechecks mobile ownership after the viewport await', async () => {
const { runtime, update, requestRedraw, refresh } = createRedrawRuntime()
refresh.mockImplementation(async () => {
runtime.markMobileActor('pty-1', 'phone-1')
return true
})
expect((await update()).ok).toBe(true)
expect(requestRedraw).not.toHaveBeenCalled()
})

it('rechecks the applied grid after the viewport await', async () => {
const { update, requestRedraw, refresh, setSize } = createRedrawRuntime()
refresh.mockImplementation(async () => {
setSize({ cols: 100, rows: 30 })
return true
})
expect((await update()).ok).toBe(true)
expect(requestRedraw).not.toHaveBeenCalled()
})

it('refuses a replaced handle after the viewport await', async () => {
const { update, requestRedraw, resolve, refresh } = createRedrawRuntime()
refresh.mockImplementation(async () => {
resolve.mockImplementation(() => {
throw new Error('terminal_handle_stale')
})
return true
})
expect((await update()).ok).toBe(false)
expect(requestRedraw).not.toHaveBeenCalled()
})

it('degrades safely when the controller cannot request redraw', async () => {
const { runtime, update } = createRedrawRuntime()
runtime.setPtyController({
write: () => true,
kill: () => true,
getForegroundProcess: async () => null,
getSize: () => ({ cols: 80, rows: 24 })
})
expect((await update()).ok).toBe(true)
})
})
1 change: 1 addition & 0 deletions src/main/runtime/runtime-pty-controller-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ export type RuntimePtyController = {
clearBuffer?(ptyId: string): Promise<void>
resetInputModes?(ptyId: string): Promise<void>
resize?(ptyId: string, cols: number, rows: number): boolean
requestRedraw?(ptyId: string): Promise<boolean>
// Why: exact-id mobile polls should not enumerate every local and SSH PTY.
hasPty?(ptyId: string): boolean | null
listProcesses?(
Expand Down
8 changes: 1 addition & 7 deletions src/main/runtime/terminal-viewport.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1 @@
// Clamp terminal dimensions to the PTY's supported range (cols 20–240, rows 8–120).
export function clampTerminalViewport(cols: number, rows: number): { cols: number; rows: number } {
return {
cols: Math.max(20, Math.min(240, Math.round(cols))),
rows: Math.max(8, Math.min(120, Math.round(rows)))
}
}
export { clampTerminalViewport } from '../../shared/terminal-viewport'
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import type { RecognizedAgentProcess } from '../../../../shared/agent-process-recognition'
import type { TuiAgent } from '../../../../shared/tui-agent'
import type { PaneForegroundAgentEntry } from '@/store/slices/pane-foreground-agent'
import type { RuntimeTerminalProcessInspection } from '@/runtime/runtime-terminal-inspection'

export type PaneForegroundAgentTrackerDeps = {
getPtyId: () => string | null
/** Local panes only — remote/SSH foreground reads are expensive RPCs and
* their replayed OSC streams must not produce process evidence. */
isTrackablePtyId: (ptyId: string) => boolean
readForegroundProcess: (
ptyId: string,
options?: { expectedIncarnationId?: string }
) => Promise<string | null | RuntimeTerminalProcessInspection>
/** Fresh, provider-owned evidence used only when input routing may change. */
confirmForegroundProcess?: (
ptyId: string,
options?: { expectedIncarnationId?: string }
) => Promise<string | null | RuntimeTerminalProcessInspection>
/** Remote authorities must provide fenced evidence; local panes retain the string path. */
isRemotePtyId?: (ptyId: string) => boolean
getExpectedIncarnationId?: () => string | null
publish: (entry: PaneForegroundAgentEntry) => void
/** The entry currently published for this pane, whoever wrote it. */
getPublishedEntry?: () => PaneForegroundAgentEntry | undefined
/** A local read recognized an agent; lets the pane's process monitor watch for its exit. */
onAgentProcessRead?: (process: RecognizedAgentProcess) => void
/** Launch/hook evidence retained until a foreground read confirms ownership. */
hasKnownAgentIdentity?: () => boolean
/** Clears an agent title only after a confirmed foreground shell or process exit. */
onConfirmedShellForeground?: (reason: 'visible-pty' | 'command-finished' | 'process-exit') => void
onCommandFinishedUnavailable?: () => void
onVisibleForegroundSettled?: (outcome: 'agent' | 'shell' | 'inconclusive') => void
}

export type PaneForegroundAgentTracker = {
/** True while any read is scheduled or running, whatever its authority. */
hasReadInFlight: () => boolean
onVisiblePtyBound: (expectsAgent?: boolean) => boolean
onCommandStarted: (expectedAgent?: TuiAgent | null) => void
/** True when pane identity must remain visible until an async shell confirmation. */
onCommandFinished: () => boolean
resetForPtyReplacement: () => void
/** The process monitor confirmed this agent exited (no agent, no children, settled). */
onProcessExitConfirmed: (process: RecognizedAgentProcess) => void
dispose: () => void
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,36 @@ describe('createPaneForegroundAgentTracker', () => {
vi.useRealTimers()
})

it('retires a pending predecessor read when an incarnation reuses its PTY ID', async () => {
let resolveRead!: (value: string | null) => void
readForegroundProcess.mockImplementation(
() =>
new Promise((resolve) => {
resolveRead = resolve
})
)
const tracker = makeTracker()
tracker.onVisiblePtyBound(true)
await flushSettleRead(VISIBLE_PTY_SETTLE_MS)
tracker.resetForPtyReplacement()
expect(tracker.hasReadInFlight()).toBe(false)
resolveRead('pi')
await flushSettleRead(SECOND_WRAPPER_RETRY_MS)
expect(publish).not.toHaveBeenCalled()
expect(onConfirmedShellForeground).not.toHaveBeenCalled()
expect(onVisibleForegroundSettled).not.toHaveBeenCalled()
expect(readForegroundProcess).toHaveBeenCalledOnce()
readForegroundProcess.mockResolvedValue('codex')
tracker.onCommandStarted()
await flushSettleRead(COMMAND_SETTLE_MS)
expect(publish).toHaveBeenCalledWith({
agent: 'codex',
shellForeground: false,
agentEvidence: 'process-read'
})
tracker.dispose()
})

// Why: detach/remount emits no PTY exit, so the store entry outlives this tracker.
// A capability retained pending the disposed read would latch there forever.
it('releases a retained capability when disposed mid-read', async () => {
Expand Down
Loading