From 99e750805c0de90ce5fd7cd50ed864acf89377b0 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:55:59 -0800 Subject: [PATCH] fix(agent-sleep): a tab a paired client is showing or typing into is in use (#38768) Agent sleep only treated the host window's own foreground tabs and phone driver locks as in use. A paired desktop showing a tab, or anyone typing into it from another client, never reached the planner, so the host slept the tab the user was looking at. The runtime now answers "is this PTY in use elsewhere": a remote view that reports hidden panes (it pauses output while hidden) and is not paused, a phone driver, and the last user input from any client. The host window asks its main process over IPC for its own PTYs; a client planning runtime-hosted tabs gets the same facts from terminal.list (includeAttention). The planner treats a shown PTY like a phone-driven one and folds remote input into its input guard. Clients too old to report hidden panes never count as showing a tab, and hosts too old to report attention leave sleep as it was, so a missing signal never turns into never-sleep. Fixes #36427 --- src/main/ipc/pty/ipc/terminal-attention.ts | 37 ++++ src/main/ipc/pty/ipc/write.ts | 3 + .../rpc/methods/terminal/stream-schemas.ts | 2 + ...erminal-multiplex-stream-initialization.ts | 3 +- .../terminal/terminal-query-methods.ts | 10 +- .../rpc/terminal-multiplex-shown-pane.test.ts | 100 ++++++++++ .../terminal/layout/terminal-view-presence.ts | 21 ++- .../view/runtime-terminal-view-subscribers.ts | 26 ++- src/preload/api/pty-api.ts | 3 + src/preload/api/pty-bridge-session-control.ts | 3 + ...-pty-transport-attach-subscription.test.ts | 1 + .../remote-runtime-pty-transport.ts | 1 + ...nt-hibernation-coordinator-test-fixture.ts | 11 ++ .../lib/agent-hibernation-coordinator.test.ts | 74 ++++++++ .../src/lib/agent-hibernation-coordinator.ts | 130 ++----------- .../lib/agent-hibernation-host-evidence.ts | 175 ++++++++++++++++++ .../lib/agent-hibernation-pane-eligibility.ts | 36 ++-- .../lib/agent-hibernation-planner-snapshot.ts | 10 +- .../src/lib/agent-hibernation-planner.test.ts | 31 +++- .../src/lib/agent-hibernation-planner.ts | 5 +- ...ime-terminal-multiplexer-implementation.ts | 3 + .../agent-hibernation-live-anchor-e2e.test.ts | 2 +- .../src/web/preload-api/web-terminal-api.ts | 2 + .../rpc-contract/terminal-unary-params.ts | 2 + src/shared/runtime-terminal-contracts.ts | 10 + 25 files changed, 559 insertions(+), 142 deletions(-) create mode 100644 src/main/ipc/pty/ipc/terminal-attention.ts create mode 100644 src/main/runtime/rpc/terminal-multiplex-shown-pane.test.ts create mode 100644 src/renderer/src/lib/agent-hibernation-host-evidence.ts diff --git a/src/main/ipc/pty/ipc/terminal-attention.ts b/src/main/ipc/pty/ipc/terminal-attention.ts new file mode 100644 index 00000000000..5aa542998da --- /dev/null +++ b/src/main/ipc/pty/ipc/terminal-attention.ts @@ -0,0 +1,37 @@ +import type { RuntimeTerminalAttention } from '../../../../shared/runtime-terminal-contracts' +import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' +import { getPtyIpc } from '../pty-host-bindings' +import type { PtyRendererDelivery } from '../session' +import { isMainWindowPtyIpcEvent } from './write-input' + +const MAX_ATTENTION_PTY_IDS = 10_000 + +/** Agent sleep in this window must see what paired clients and phones are doing with its PTYs. */ +export function installPtyTerminalAttentionIpcHandler(deps: { + mainWindow?: PtyRendererDelivery + runtime?: OrcaRuntimeService +}): void { + const ipcMain = getPtyIpc() + ipcMain.removeHandler('pty:getTerminalAttention') + ipcMain.handle( + 'pty:getTerminalAttention', + (event, ids: unknown): Record => { + const { runtime } = deps + if ( + !runtime || + !isMainWindowPtyIpcEvent(event, deps.mainWindow) || + !Array.isArray(ids) || + ids.length > MAX_ATTENTION_PTY_IDS + ) { + return {} + } + const attention: Record = {} + for (const id of ids) { + if (typeof id === 'string' && id.length > 0) { + attention[id] = runtime.getTerminalAttention(id) + } + } + return attention + } + ) +} diff --git a/src/main/ipc/pty/ipc/write.ts b/src/main/ipc/pty/ipc/write.ts index 8fdaa61ee1f..30e67581775 100644 --- a/src/main/ipc/pty/ipc/write.ts +++ b/src/main/ipc/pty/ipc/write.ts @@ -2,6 +2,7 @@ import type { PtyRendererDelivery } from '../session' import { getPtyIpc } from '../pty-host-bindings' import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' import { createPtyWriteInput } from './write-input' +import { installPtyTerminalAttentionIpcHandler } from './terminal-attention' export function installPtyWriteIpcHandlers(deps: { mainWindow?: PtyRendererDelivery @@ -18,6 +19,8 @@ export function installPtyWriteIpcHandlers(deps: { } = createPtyWriteInput(deps) const hostViewportClaimTails = new Map>() + // Input from every client lands here; agent sleep reads it back with who else is viewing. + installPtyTerminalAttentionIpcHandler(deps) ipcMain.on('pty:write', (event, args: unknown) => { if (!isPtyWriteEventFromMainWindow(event) || !isPtyWritePayload(args)) { diff --git a/src/main/runtime/rpc/methods/terminal/stream-schemas.ts b/src/main/runtime/rpc/methods/terminal/stream-schemas.ts index 2d9535eea3e..6fb09cfc035 100644 --- a/src/main/runtime/rpc/methods/terminal/stream-schemas.ts +++ b/src/main/runtime/rpc/methods/terminal/stream-schemas.ts @@ -19,6 +19,8 @@ export const TerminalMultiplexSubscribeFrame = TerminalHandle.extend({ desktopViewportClaims: z.literal(1).optional(), outputPause: z.literal(1).optional(), outputPauseDropNotice: z.literal(1).optional(), + // Only a view that pauses output while its pane is hidden can say it is showing the terminal. + paneVisibility: z.literal(1).optional(), writeUnavailable: z.literal(1).optional(), // Old clients quarantine input after writeUnavailable; send host-lost semantics only to clients that understand them. endpointLossNotice: z.literal(1).optional(), diff --git a/src/main/runtime/rpc/methods/terminal/terminal-multiplex-stream-initialization.ts b/src/main/runtime/rpc/methods/terminal/terminal-multiplex-stream-initialization.ts index e8f518c155c..771d88bd115 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-multiplex-stream-initialization.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-multiplex-stream-initialization.ts @@ -109,7 +109,8 @@ export async function initializeMultiplexStream( const releaseViewSubscriber = runtime.registerRemoteTerminalViewSubscriber( ptyId, () => stream.outputPaused, - isMobile ? request.client?.id : undefined + isMobile ? request.client?.id : undefined, + stream.supportsOutputPause && request.capabilities?.paneVisibility === 1 ) // Report daemon death now, before the next refused keystroke. const unsubscribeEndpointLoss = stream.supportsEndpointLossNotice diff --git a/src/main/runtime/rpc/methods/terminal/terminal-query-methods.ts b/src/main/runtime/rpc/methods/terminal/terminal-query-methods.ts index dab93fafaab..34aa7d99937 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-query-methods.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-query-methods.ts @@ -31,12 +31,18 @@ export const TERMINAL_QUERY_METHODS = [ requireFreshPtyLiveness: params.requireFreshPtyLiveness, includeVisualLayouts: params.includeVisualLayouts }) - if (params.includePreview !== false) { + if (params.includePreview !== false && !params.includeAttention) { return result } return { ...result, - terminals: result.terminals.map(({ preview: _preview, ...terminal }) => terminal) + terminals: result.terminals.map(({ preview, ...terminal }) => ({ + ...terminal, + ...(params.includePreview !== false ? { preview } : {}), + ...(params.includeAttention && terminal.ptyId + ? { attention: runtime.getTerminalAttention(terminal.ptyId) } + : {}) + })) } } }), diff --git a/src/main/runtime/rpc/terminal-multiplex-shown-pane.test.ts b/src/main/runtime/rpc/terminal-multiplex-shown-pane.test.ts new file mode 100644 index 00000000000..abdca58b3b3 --- /dev/null +++ b/src/main/runtime/rpc/terminal-multiplex-shown-pane.test.ts @@ -0,0 +1,100 @@ +import './unused-default-rpc-methods.test-fixture' +import { describe, expect, it, vi } from 'vitest' +import { + TerminalStreamOpcode, + decodeTerminalStreamFrame, + encodeTerminalStreamFrame, + encodeTerminalStreamJson +} from '../../../shared/terminal/stream/terminal-stream-protocol' +import { startDesktopMultiplexSubscribe } from './terminal-multiplex-test-harness' +import { RuntimeTerminalViewSubscribers } from '../terminal/view/runtime-terminal-view-subscribers' + +async function subscribeDesktop(capabilities: Record) { + const viewSubscribers = new RuntimeTerminalViewSubscribers({ + notifyPresenceChanged: () => {}, + hasMobileSubscribers: () => false, + ensureProviderAttach: () => {} + }) + // Mirrors OrcaRuntime: only a view that reports hidden panes may count as showing one. + const harness = startDesktopMultiplexSubscribe({ + subscribeToTerminalData: vi.fn(() => vi.fn()), + registerRemoteTerminalViewSubscriber: ( + ptyId, + isOutputPaused, + _mobileClientId, + reportsHiddenPane + ) => + viewSubscribers.registerRemote( + ptyId, + isOutputPaused, + reportsHiddenPane ? isOutputPaused : undefined + ) + }) + await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) + harness.handlers.get(0)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Subscribe, + streamId: 0, + seq: 1, + payload: encodeTerminalStreamJson({ + streamId: 1, + terminal: 'terminal-1', + client: { id: 'desktop-1', type: 'desktop' }, + capabilities + }) + }) + )! + ) + await vi.waitFor(() => + expect( + harness.messages + .map((message) => JSON.parse(message).result) + .some((event) => event?.type === 'subscribed' && event.streamId === 1) + ).toBe(true) + ) + let frameSeq = 10 + return { + shown: () => viewSubscribers.isShownRemotely('pty-1'), + setPaused: (paused: boolean): void => + harness.handlers.get(1)?.( + decodeTerminalStreamFrame( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.SetOutputPaused, + streamId: 1, + seq: frameSeq++, + payload: encodeTerminalStreamJson({ paused }) + }) + )! + ), + close: async (): Promise => { + harness.registry.cleanupSubscription('terminal-multiplex:conn-desktop-first-paint') + await harness.dispatchPromise + } + } +} + +describe('a paired desktop showing a terminal (#36427)', () => { + it('counts as showing it until it hides the pane or disconnects', async () => { + const client = await subscribeDesktop({ outputPause: 1, paneVisibility: 1 }) + expect(client.shown()).toBe(true) + client.setPaused(true) + expect(client.shown()).toBe(false) + client.setPaused(false) + expect(client.shown()).toBe(true) + await client.close() + expect(client.shown()).toBe(false) + }) + + it('never counts a client too old to report hidden panes', async () => { + const client = await subscribeDesktop({}) + expect(client.shown()).toBe(false) + await client.close() + }) + + it('never counts a pausable reader that is not a terminal pane, such as a dashboard preview', async () => { + const client = await subscribeDesktop({ outputPause: 1 }) + expect(client.shown()).toBe(false) + await client.close() + }) +}) diff --git a/src/main/runtime/terminal/layout/terminal-view-presence.ts b/src/main/runtime/terminal/layout/terminal-view-presence.ts index 0c818d0c298..630058c24ea 100644 --- a/src/main/runtime/terminal/layout/terminal-view-presence.ts +++ b/src/main/runtime/terminal/layout/terminal-view-presence.ts @@ -8,6 +8,7 @@ import type { WriteSettlement } from '../../../../shared/terminal/pty/lifecycle/ import type { RuntimeTerminalDriverState as DriverState } from '../../../../shared/runtime-session-contracts' import { addListenerToMap } from './terminal-listener-map' import { notifyRuntimeListeners } from '../../events/runtime-listener-delivery' +import type { RuntimeTerminalAttention } from '../../../../shared/runtime-terminal-contracts' import type { RuntimeTerminalBufferSnapshot } from '../records/runtime-terminal-state-records' import { AUTHORITATIVE_TERMINAL_SNAPSHOT_TIMEOUT_MS } from '../output/provider-snapshot-budget' import { assertTerminalInputWithinLimitWithYield } from '../../terminal-send-payload' @@ -57,7 +58,9 @@ export abstract class OrcaRuntimeWithNotifyRemoteTerminalViewPresenceChanged ext registerRemoteTerminalViewSubscriber( ptyId: string, isOutputPaused?: () => boolean, - mobileClientId?: string + mobileClientId?: string, + /** Only for views that pause output while their pane is hidden, so "unpaused" means on screen. */ + reportsHiddenPane = false ): () => void { const isSilent = mobileClientId === undefined @@ -65,7 +68,21 @@ export abstract class OrcaRuntimeWithNotifyRemoteTerminalViewPresenceChanged ext : () => isOutputPaused?.() === true || !this.isMobileTerminalQueryReplyAuthority(ptyId, mobileClientId) - return this.terminalViewSubscribers.registerRemote(ptyId, isSilent) + return this.terminalViewSubscribers.registerRemote( + ptyId, + isSilent, + reportsHiddenPane ? isOutputPaused : undefined + ) + } + + /** Whether any viewer other than this host's own window shows the PTY, or the user last typed into it, from any client. */ + getTerminalAttention(ptyId: string): RuntimeTerminalAttention { + return { + shownRemotely: + this.getDriver(ptyId).kind === 'mobile' || + this.terminalViewSubscribers.isShownRemotely(ptyId), + lastInputAt: this.terminalRunFacts.readLastDrivingInputAt(ptyId) + } } /** Live local daemon sessions with no ingested bytes need attachment; existing headless state or snapshot reconciliation means attach already began. */ diff --git a/src/main/runtime/terminal/view/runtime-terminal-view-subscribers.ts b/src/main/runtime/terminal/view/runtime-terminal-view-subscribers.ts index 8da7e33956d..76603e8fdf7 100644 --- a/src/main/runtime/terminal/view/runtime-terminal-view-subscribers.ts +++ b/src/main/runtime/terminal/view/runtime-terminal-view-subscribers.ts @@ -5,11 +5,14 @@ type RuntimeTerminalViewSubscriberDependencies = { } type SilenceableRemoteView = { isSilent: () => boolean } +/** Only views that report when their pane is hidden can claim to be on screen. */ +type PaneReportingRemoteView = { isHidden: () => boolean } export class RuntimeTerminalViewSubscribers { private readonly remoteCounts = new Map() private readonly silenceableRemoteViews = new Map>() private readonly rawCounts = new Map() + private readonly paneReportingRemoteViews = new Map>() constructor(private readonly deps: RuntimeTerminalViewSubscriberDependencies) {} @@ -17,9 +20,10 @@ export class RuntimeTerminalViewSubscribers { this.remoteCounts.delete(ptyId) this.silenceableRemoteViews.delete(ptyId) this.rawCounts.delete(ptyId) + this.paneReportingRemoteViews.delete(ptyId) } - registerRemote(ptyId: string, isSilent?: () => boolean): () => void { + registerRemote(ptyId: string, isSilent?: () => boolean, isHidden?: () => boolean): () => void { this.remoteCounts.set(ptyId, (this.remoteCounts.get(ptyId) ?? 0) + 1) const view = isSilent ? { isSilent } : null if (view) { @@ -27,6 +31,12 @@ export class RuntimeTerminalViewSubscribers { views.add(view) this.silenceableRemoteViews.set(ptyId, views) } + const paneView = isHidden ? { isHidden } : null + if (paneView) { + const views = this.paneReportingRemoteViews.get(ptyId) ?? new Set() + views.add(paneView) + this.paneReportingRemoteViews.set(ptyId, views) + } this.deps.ensureProviderAttach(ptyId) this.deps.notifyPresenceChanged(ptyId) return this.releaseOnce(() => { @@ -35,10 +45,24 @@ export class RuntimeTerminalViewSubscribers { if (view && views?.delete(view) && views.size === 0) { this.silenceableRemoteViews.delete(ptyId) } + const paneViews = this.paneReportingRemoteViews.get(ptyId) + if (paneView && paneViews?.delete(paneView) && paneViews.size === 0) { + this.paneReportingRemoteViews.delete(ptyId) + } this.deps.notifyPresenceChanged(ptyId) }) } + /** A remote client is displaying this PTY's pane right now. */ + isShownRemotely(ptyId: string): boolean { + for (const view of this.paneReportingRemoteViews.get(ptyId) ?? []) { + if (!view.isHidden()) { + return true + } + } + return false + } + registerRaw(ptyId: string): () => void { this.rawCounts.set(ptyId, (this.rawCounts.get(ptyId) ?? 0) + 1) this.deps.notifyPresenceChanged(ptyId) diff --git a/src/preload/api/pty-api.ts b/src/preload/api/pty-api.ts index f7fe1563410..25b72dd846a 100644 --- a/src/preload/api/pty-api.ts +++ b/src/preload/api/pty-api.ts @@ -1,3 +1,4 @@ +import type { RuntimeTerminalAttention } from '../../shared/runtime-terminal-contracts' import type { PaintedRestorePane } from '../../shared/painted-restore-ack' import type { PtyFencedTerminationRequest, @@ -121,6 +122,8 @@ export type PtyApi = { onWriteUnavailable?: (callback: (payload: { id: string }) => void) => () => void resize: (id: string, cols: number, rows: number) => void claimViewport: (id: string, cols: number, rows: number) => void + /** Who besides this window is viewing or typing into these PTYs; empty for unknown ids. */ + getTerminalAttention: (ids: string[]) => Promise> reportGeometry: (id: string, cols: number, rows: number) => void signal: (id: string, signal: string) => void clearBuffer: (id: string) => void diff --git a/src/preload/api/pty-bridge-session-control.ts b/src/preload/api/pty-bridge-session-control.ts index 24fbb9bf47e..71a86f01b6d 100644 --- a/src/preload/api/pty-bridge-session-control.ts +++ b/src/preload/api/pty-bridge-session-control.ts @@ -1,3 +1,4 @@ +import type { RuntimeTerminalAttention } from '../../shared/runtime-terminal-contracts' import type { PaintedRestorePane } from '../../shared/painted-restore-ack' import type { PtyFencedTerminationRequest, @@ -116,6 +117,8 @@ export const ptySessionControlApi = { claimViewport: (id: string, cols: number, rows: number): void => { ipcRenderer.send('pty:claimViewport', { id, cols, rows }) }, + getTerminalAttention: (ids: string[]): Promise> => + ipcRenderer.invoke('pty:getTerminalAttention', ids), reportGeometry: (id: string, cols: number, rows: number): void => { ipcRenderer.send('pty:reportGeometry', { id, cols, rows }) }, diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-attach-subscription.test.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-attach-subscription.test.ts index fa98c3c7d1a..07716628265 100644 --- a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-attach-subscription.test.ts +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-attach-subscription.test.ts @@ -77,6 +77,7 @@ describe('createRemoteRuntimePtyTransport', () => { desktopViewportClaims: 1, outputPause: 1, outputPauseDropNotice: 1, + paneVisibility: 1, writeUnavailable: 1, endpointLossNotice: 1, inputAck: 1 diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts index 5afd759c18f..76cf05a2a0c 100644 --- a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts @@ -3037,6 +3037,7 @@ export function createRemoteRuntimePtyTransport( client: { id: clientId, type: 'desktop' }, viewport: subscribedViewport ?? undefined, inputSessionId: inputJournal.sessionId, + reportsPaneVisibility: true, callbacks: { onData: (data, meta) => { if (isCurrentSubscription()) { diff --git a/src/renderer/src/lib/agent-hibernation-coordinator-test-fixture.ts b/src/renderer/src/lib/agent-hibernation-coordinator-test-fixture.ts index ebddc1a45db..ca0f7d23471 100644 --- a/src/renderer/src/lib/agent-hibernation-coordinator-test-fixture.ts +++ b/src/renderer/src/lib/agent-hibernation-coordinator-test-fixture.ts @@ -20,6 +20,7 @@ import { type RuntimeEnvironmentCallRequest } from '../runtime/runtime-compatibility-test-fixture' import { clearRuntimeCompatibilityCacheForTests } from '../runtime/runtime-rpc-client' +import type { RuntimeTerminalAttention } from '../../../shared/runtime-terminal-contracts' export const NOW = 10_000_000 export const LEAF = '11111111-1111-4111-8111-111111111111' @@ -28,10 +29,18 @@ export type RuntimeEnvironmentCallStub = Mock<(args: RuntimeEnvironmentCallReque export const mockRuntimeEnvironmentCall: RuntimeEnvironmentCallStub = vi.fn() +/** This window's main process: who else shows or types into its own PTYs. */ +export const mockGetTerminalAttention: Mock< + (ids: string[]) => Promise> +> = vi.fn(async () => ({})) + vi.stubGlobal('window', { api: { runtimeEnvironments: { call: mockRuntimeEnvironmentCall + }, + pty: { + getTerminalAttention: mockGetTerminalAttention } } }) @@ -193,5 +202,7 @@ export function resetAgentHibernationCoordinatorFixture(): void { resetHibernationPaneAgeForTests() hydrateDrivers([]) mockRuntimeEnvironmentCall.mockReset() + mockGetTerminalAttention.mockReset() + mockGetTerminalAttention.mockImplementation(async () => ({})) vi.useRealTimers() } diff --git a/src/renderer/src/lib/agent-hibernation-coordinator.test.ts b/src/renderer/src/lib/agent-hibernation-coordinator.test.ts index d09abf36ea2..371fb7da57e 100644 --- a/src/renderer/src/lib/agent-hibernation-coordinator.test.ts +++ b/src/renderer/src/lib/agent-hibernation-coordinator.test.ts @@ -18,6 +18,7 @@ import { installRuntimeListResponses, layout, LEAF, + mockGetTerminalAttention, mockRuntimeEnvironmentCall, NOW, resetAgentHibernationCoordinatorFixture, @@ -257,6 +258,79 @@ describe('agent sleep coordinator', () => { expect(shutdown).not.toHaveBeenCalled() }) + it('keeps a tab a paired client is showing, and sleeps it once the client hides it (#36427)', async () => { + vi.useFakeTimers() + const shutdown = installEligibleState(vi.fn().mockResolvedValue(undefined)) + let shownRemotely = true + mockGetTerminalAttention.mockImplementation(async (ids) => + Object.fromEntries(ids.map((id) => [id, { shownRemotely, lastInputAt: null }])) + ) + startAgentHibernationCoordinator({ intervalMs: 1000, now: () => NOW }) + + await vi.advanceTimersByTimeAsync(3000) + expect(shutdown).not.toHaveBeenCalled() + expect(mockGetTerminalAttention).toHaveBeenCalledWith(['pty-1']) + + shownRemotely = false + await vi.advanceTimersByTimeAsync(2000) + expect(shutdown).toHaveBeenCalledOnce() + }) + + it('treats typing from a paired client after the turn as input that keeps the tab (#36427)', async () => { + vi.useFakeTimers() + const shutdown = installEligibleState(vi.fn().mockResolvedValue(undefined)) + mockGetTerminalAttention.mockImplementation(async (ids) => + Object.fromEntries(ids.map((id) => [id, { shownRemotely: false, lastInputAt: NOW - 1 }])) + ) + startAgentHibernationCoordinator({ intervalMs: 1000, now: () => NOW }) + + await vi.advanceTimersByTimeAsync(3000) + + expect(shutdown).not.toHaveBeenCalled() + }) + + it('keeps a runtime-hosted tab another client is showing, but not on hosts that report nothing', async () => { + vi.useFakeTimers() + const shown = runtimeListResult(['pty-1']) + const withAttention = { + ...shown, + terminals: shown.terminals.map((terminal) => ({ + ...terminal, + attention: { shownRemotely: true, lastInputAt: null } + })) + } + installRuntimeListResponses(withAttention, withAttention, withAttention, withAttention) + const runtimeState = { + settings: { + experimentalAgentHibernation: true, + agentHibernationIdleMs: DEFAULT_AGENT_HIBERNATION_IDLE_MS, + activeRuntimeEnvironmentId: 'runtime-1' + } as never, + ptyIdsByTabId: { 'tab-1': [] } + } + const shutdown = installEligibleState(vi.fn().mockResolvedValue(undefined), runtimeState) + startAgentHibernationCoordinator({ intervalMs: 1000, now: () => NOW }) + + await vi.advanceTimersByTimeAsync(3000) + expect(shutdown).not.toHaveBeenCalled() + expect(mockRuntimeEnvironmentCall).toHaveBeenCalledWith( + expect.objectContaining({ + method: 'terminal.list', + params: expect.objectContaining({ includeAttention: true }) + }) + ) + + // An older host omits attention; agent sleep must keep working there. + resetAgentHibernationCoordinatorFixture() + vi.useFakeTimers() + installRuntimeListResponses(shown, shown, shown) + const legacyShutdown = installEligibleState(vi.fn().mockResolvedValue(undefined), runtimeState) + startAgentHibernationCoordinator({ intervalMs: 1000, now: () => NOW }) + + await vi.advanceTimersByTimeAsync(2000) + expect(legacyShutdown).toHaveBeenCalledOnce() + }) + it.each(['wt-bg', 'folder:folder-1'])( 'hibernates a runtime-backed candidate in %s with fresh liveness and exact PTYs', async (worktreeId) => { diff --git a/src/renderer/src/lib/agent-hibernation-coordinator.ts b/src/renderer/src/lib/agent-hibernation-coordinator.ts index 4649c36e6b5..8ec8dbb6344 100644 --- a/src/renderer/src/lib/agent-hibernation-coordinator.ts +++ b/src/renderer/src/lib/agent-hibernation-coordinator.ts @@ -22,16 +22,13 @@ import { observeHibernationPtyBindings } from './agent-hibernation-pane-age' import { mergePendingTerminalInputActivity } from './terminal-input-activity-coalescing' -import { resolveTerminalPtyOwner } from './terminal-worktree-route' -import { toAgentHibernationRuntimeOwner } from './agent-hibernation-runtime-owner' -import { callRuntimeRpc } from '@/runtime/runtime-rpc-client' -import { toRuntimeWorktreeSelector } from '@/runtime/runtime-worktree-selector' -import type { - RuntimeTerminalListResult, - RuntimeTerminalSummary -} from '../../../shared/runtime-types' +import { + collectHostPtyEvidence, + getRuntimeLivenessTargetWorktrees, + resolveAgentHibernationRuntimeOwner, + type HostPtyEvidence +} from './agent-hibernation-host-evidence' import { getWindowParkVisible, subscribeWindowParkVisibility } from './window-park-visibility' -import { getEntryTabId } from './agent-hibernation-pane-eligibility' export const AGENT_HIBERNATION_TICK_MS = 60 * 1000 @@ -60,15 +57,10 @@ const coordinator: AgentHibernationCoordinatorState = { now: () => Date.now() } -type RuntimePtyLivenessSample = { - runtimeLivePtyIdsByWorktreeId: Record - runtimeLivenessRequiredWorktreeIds: string[] -} - function snapshotFromState( state: AppState, now: number, - runtimeLiveness: RuntimePtyLivenessSample, + hostEvidence: HostPtyEvidence, targetWorktreeId?: string ): AgentHibernationPlannerSnapshot { return { @@ -80,15 +72,15 @@ function snapshotFromState( : state.tabsByWorktree, terminalLayoutsByTabId: state.terminalLayoutsByTabId, ptyIdsByTabId: state.ptyIdsByTabId, - runtimeLivePtyIdsByWorktreeId: runtimeLiveness.runtimeLivePtyIdsByWorktreeId, + runtimeLivePtyIdsByWorktreeId: hostEvidence.runtimeLivePtyIdsByWorktreeId, // Union fresh owners with pre-await targets so newly resolved workspaces fail closed without host evidence; never narrow that set. runtimeLivenessRequiredWorktreeIds: [ ...new Set([ - ...runtimeLiveness.runtimeLivenessRequiredWorktreeIds, + ...hostEvidence.runtimeLivenessRequiredWorktreeIds, ...getRuntimeLivenessTargetWorktrees(state, targetWorktreeId).keys() ]) ], - mobileLockedPtyIds: [...getAllDrivers()] + inUsePtyIds: [...getAllDrivers()] .filter(([, driver]) => driver.kind === 'mobile') .map(([ptyId]) => ptyId), agentStatusByPaneKey: state.agentStatusByPaneKey, @@ -97,6 +89,7 @@ function snapshotFromState( lastTerminalInputAtByPaneKey: mergePendingTerminalInputActivity( state.lastTerminalInputAtByPaneKey ), + attentionByWorktreeId: hostEvidence.attentionByWorktreeId, foregroundTerminalLastSeenAtByTabId: getForegroundTerminalTabLastSeenAtById(), ptyBindingFirstSeenAtByPaneKey: getHibernationPtyBindingFirstSeenAtByPaneKey(), boundaryResolvedAtByPaneKey: getHibernationBoundaryResolvedAtByPaneKey(), @@ -104,105 +97,8 @@ function snapshotFromState( } } -function resolveAgentHibernationRuntimeOwner(state: AppState, worktreeId: string) { - const tabs = state.tabsByWorktree[worktreeId] ?? [] - const ptyIds = tabs.flatMap((tab) => state.ptyIdsByTabId[tab.id] ?? []) - return toAgentHibernationRuntimeOwner(resolveTerminalPtyOwner(state, worktreeId), ptyIds) -} - -/** Worktree → owning runtime; `null` means liveness is required but no host can be asked. */ -function getRuntimeLivenessTargetWorktrees( - state: AppState, - targetWorktreeId?: string -): Map { - const targets = new Map() - const worktreeIds = targetWorktreeId - ? Object.hasOwn(state.tabsByWorktree, targetWorktreeId) - ? [targetWorktreeId] - : [] - : Object.keys(state.tabsByWorktree) - for (const worktreeId of worktreeIds) { - const owner = resolveAgentHibernationRuntimeOwner(state, worktreeId) - if (owner.kind !== 'non-runtime') { - targets.set(worktreeId, owner.kind === 'runtime' ? owner.environmentId : null) - } - } - return targets -} - -function getTypedRuntimePtyId(terminal: RuntimeTerminalSummary): string | null { - if (terminal.ptyId) { - return terminal.ptyId - } - if (terminal.tabId.startsWith('pty:') && terminal.tabId === terminal.leafId) { - return terminal.tabId.slice('pty:'.length) || null - } - return null -} - -async function collectRuntimePtyLiveness( - state: AppState, - targetWorktreeId?: string -): Promise { - const targets = getRuntimeLivenessTargetWorktrees(state, targetWorktreeId) - const runtimeLivePtyIdsByWorktreeId: Record = {} - const runtimeLivenessRequiredWorktreeIds = [...targets.keys()] - if (targets.size === 0) { - // Why: an all-local install has nothing to ask, so it must not pay the status scan below. - return { runtimeLivePtyIdsByWorktreeId, runtimeLivenessRequiredWorktreeIds } - } - const completedTabIds = new Set() - for (const entry of Object.values(state.agentStatusByPaneKey)) { - const tabId = entry?.state === 'done' ? getEntryTabId(entry) : null - if (tabId) { - completedTabIds.add(tabId) - } - } - await Promise.all( - [...targets].map(async ([worktreeId, runtimeEnvironmentId]) => { - if ( - !runtimeEnvironmentId || - !state.tabsByWorktree[worktreeId]?.some((tab) => completedTabIds.has(tab.id)) - ) { - // Skipped owners still require host evidence if an agent completes during this pass. - return - } - try { - const result = await callRuntimeRpc( - { kind: 'environment', environmentId: runtimeEnvironmentId }, - 'terminal.list', - { - worktree: toRuntimeWorktreeSelector(worktreeId), - limit: 10_000, - requireFreshPtyLiveness: true, - includeVisualLayouts: false - }, - { timeoutMs: 10_000 } - ) - if (result.truncated) { - return - } - const ptyIds = new Set() - for (const terminal of result.terminals) { - if (!terminal.connected || terminal.worktreeId !== worktreeId) { - continue - } - const ptyId = getTypedRuntimePtyId(terminal) - if (ptyId) { - ptyIds.add(ptyId) - } - } - runtimeLivePtyIdsByWorktreeId[worktreeId] = [...ptyIds].sort() - } catch { - // Omit stale runtime evidence so the planner fails closed for this pass. - } - }) - ) - return { runtimeLivePtyIdsByWorktreeId, runtimeLivenessRequiredWorktreeIds } -} - async function currentCandidates(now: number, targetWorktreeId?: string) { - const runtimeLiveness = await collectRuntimePtyLiveness(useAppStore.getState(), targetWorktreeId) + const hostEvidence = await collectHostPtyEvidence(useAppStore.getState(), targetWorktreeId) const freshState = useAppStore.getState() // Sample binding ages from the plan’s state so a first-seen pane cannot already qualify as long-idle. observeHibernationPtyBindings({ @@ -212,7 +108,7 @@ async function currentCandidates(now: number, targetWorktreeId?: string) { idleMs: getEffectiveAgentHibernationIdleMs(freshState.settings?.agentHibernationIdleMs) }) return planAgentHibernationCandidates( - snapshotFromState(freshState, now, runtimeLiveness, targetWorktreeId) + snapshotFromState(freshState, now, hostEvidence, targetWorktreeId) ) .filter((candidate) => { const owner = resolveAgentHibernationRuntimeOwner(freshState, candidate.worktreeId) diff --git a/src/renderer/src/lib/agent-hibernation-host-evidence.ts b/src/renderer/src/lib/agent-hibernation-host-evidence.ts new file mode 100644 index 00000000000..a6f52bd7659 --- /dev/null +++ b/src/renderer/src/lib/agent-hibernation-host-evidence.ts @@ -0,0 +1,175 @@ +import type { AppState } from '@/store/types' +import { callRuntimeRpc } from '@/runtime/runtime-rpc-client' +import { toRuntimeWorktreeSelector } from '@/runtime/runtime-worktree-selector' +import type { + RuntimeTerminalListResult, + RuntimeTerminalSummary +} from '../../../shared/runtime-types' +import type { RuntimeTerminalAttention } from '../../../shared/runtime-terminal-contracts' +import { resolveTerminalPtyOwner } from './terminal-worktree-route' +import { toAgentHibernationRuntimeOwner } from './agent-hibernation-runtime-owner' +import { getEntryTabId } from './agent-hibernation-pane-eligibility' + +export type HostPtyEvidence = { + runtimeLivePtyIdsByWorktreeId: Record + runtimeLivenessRequiredWorktreeIds: string[] + /** Per worktree, keyed by its host's PTY id: two hosts can reuse one PTY id. Only hosts that report attention contribute. */ + attentionByWorktreeId: Record> +} + +export function resolveAgentHibernationRuntimeOwner(state: AppState, worktreeId: string) { + const tabs = state.tabsByWorktree[worktreeId] ?? [] + const ptyIds = tabs.flatMap((tab) => state.ptyIdsByTabId[tab.id] ?? []) + return toAgentHibernationRuntimeOwner(resolveTerminalPtyOwner(state, worktreeId), ptyIds) +} + +/** Worktree → owning runtime; `null` means liveness is required but no host can be asked. */ +export function getRuntimeLivenessTargetWorktrees( + state: AppState, + targetWorktreeId?: string +): Map { + const targets = new Map() + const worktreeIds = targetWorktreeId + ? Object.hasOwn(state.tabsByWorktree, targetWorktreeId) + ? [targetWorktreeId] + : [] + : Object.keys(state.tabsByWorktree) + for (const worktreeId of worktreeIds) { + const owner = resolveAgentHibernationRuntimeOwner(state, worktreeId) + if (owner.kind !== 'non-runtime') { + targets.set(worktreeId, owner.kind === 'runtime' ? owner.environmentId : null) + } + } + return targets +} + +function getTypedRuntimePtyId(terminal: RuntimeTerminalSummary): string | null { + if (terminal.ptyId) { + return terminal.ptyId + } + if (terminal.tabId.startsWith('pty:') && terminal.tabId === terminal.leafId) { + return terminal.tabId.slice('pty:'.length) || null + } + return null +} + +export async function collectHostPtyEvidence( + state: AppState, + targetWorktreeId?: string +): Promise { + const targets = getRuntimeLivenessTargetWorktrees(state, targetWorktreeId) + const runtimeLivePtyIdsByWorktreeId: Record = {} + const runtimeLivenessRequiredWorktreeIds = [...targets.keys()] + const attentionByWorktreeId: HostPtyEvidence['attentionByWorktreeId'] = {} + const completedTabIds = new Set() + for (const entry of Object.values(state.agentStatusByPaneKey)) { + const tabId = entry?.state === 'done' ? getEntryTabId(entry) : null + if (tabId) { + completedTabIds.add(tabId) + } + } + // Why: only completed agents can sleep, so idle installs ask nothing. + if (completedTabIds.size === 0) { + return { + runtimeLivePtyIdsByWorktreeId, + runtimeLivenessRequiredWorktreeIds, + attentionByWorktreeId + } + } + const localPtyIds = collectLocalCompletedPtyIds(state, targets, completedTabIds, targetWorktreeId) + await Promise.all([ + collectLocalTerminalAttention(localPtyIds, attentionByWorktreeId), + ...[...targets].map(async ([worktreeId, runtimeEnvironmentId]) => { + if ( + !runtimeEnvironmentId || + !state.tabsByWorktree[worktreeId]?.some((tab) => completedTabIds.has(tab.id)) + ) { + // Skipped owners still require host evidence if an agent completes during this pass. + return + } + try { + const result = await callRuntimeRpc( + { kind: 'environment', environmentId: runtimeEnvironmentId }, + 'terminal.list', + { + worktree: toRuntimeWorktreeSelector(worktreeId), + limit: 10_000, + requireFreshPtyLiveness: true, + includeVisualLayouts: false, + includeAttention: true + }, + { timeoutMs: 10_000 } + ) + if (result.truncated) { + return + } + const ptyIds = new Set() + const attention: Record = {} + for (const terminal of result.terminals) { + if (!terminal.connected || terminal.worktreeId !== worktreeId) { + continue + } + const ptyId = getTypedRuntimePtyId(terminal) + if (ptyId) { + ptyIds.add(ptyId) + if (terminal.attention) { + attention[ptyId] = terminal.attention + } + } + } + runtimeLivePtyIdsByWorktreeId[worktreeId] = [...ptyIds].sort() + attentionByWorktreeId[worktreeId] = attention + } catch { + // Omit stale runtime evidence so the planner fails closed for this pass. + } + }) + ]) + return { + runtimeLivePtyIdsByWorktreeId, + runtimeLivenessRequiredWorktreeIds, + attentionByWorktreeId + } +} + +function collectLocalCompletedPtyIds( + state: AppState, + runtimeTargets: Map, + completedTabIds: Set, + targetWorktreeId?: string +): Map { + const worktreeIds = targetWorktreeId ? [targetWorktreeId] : Object.keys(state.tabsByWorktree) + const ptyIdsByWorktreeId = new Map() + for (const worktreeId of worktreeIds) { + const ptyIds = runtimeTargets.has(worktreeId) + ? [] + : (state.tabsByWorktree[worktreeId] ?? []) + .filter((tab) => completedTabIds.has(tab.id)) + .flatMap((tab) => state.ptyIdsByTabId[tab.id] ?? []) + if (ptyIds.length > 0) { + ptyIdsByWorktreeId.set(worktreeId, ptyIds) + } + } + return ptyIdsByWorktreeId +} + +/** This window's own PTYs can also be shown or typed into by paired clients and phones. */ +async function collectLocalTerminalAttention( + ptyIdsByWorktreeId: Map, + attentionByWorktreeId: HostPtyEvidence['attentionByWorktreeId'] +): Promise { + if (ptyIdsByWorktreeId.size === 0) { + return + } + try { + const attention = await window.api.pty.getTerminalAttention( + [...ptyIdsByWorktreeId.values()].flat() + ) + for (const [worktreeId, ptyIds] of ptyIdsByWorktreeId) { + attentionByWorktreeId[worktreeId] = Object.fromEntries( + ptyIds.flatMap((ptyId) => (attention[ptyId] ? [[ptyId, attention[ptyId]]] : [])) + ) + } + } catch { + // No attention evidence leaves only this window's view and input, as before. + } +} diff --git a/src/renderer/src/lib/agent-hibernation-pane-eligibility.ts b/src/renderer/src/lib/agent-hibernation-pane-eligibility.ts index 8e5c531c174..e4964e6f453 100644 --- a/src/renderer/src/lib/agent-hibernation-pane-eligibility.ts +++ b/src/renderer/src/lib/agent-hibernation-pane-eligibility.ts @@ -11,6 +11,7 @@ import { lastInputBlocksHibernation } from './agent-hibernation-input-guard' import { isLiveResumeAnchorForCompletedAgent } from '../../../shared/agent-session/lifecycle/live-resume-anchor-record' import { agentTurnEndedUncleanly } from '../../../shared/agent-status/lifecycle/agent-main-agent-verdict' import type { AgentHibernationPlannerSnapshot } from './agent-hibernation-planner-snapshot' +import type { RuntimeTerminalAttention } from '../../../shared/runtime-terminal-contracts' export type EligiblePane = { paneKey: string @@ -64,10 +65,11 @@ export function getEligiblePane(args: { livePtyIds: Set sleepingAgentSessionsByPaneKey: AgentHibernationPlannerSnapshot['sleepingAgentSessionsByPaneKey'] lastTerminalInputAtByPaneKey: AgentHibernationPlannerSnapshot['lastTerminalInputAtByPaneKey'] + attentionByPtyId: Record foregroundTerminalLastSeenAtByTabId: AgentHibernationPlannerSnapshot['foregroundTerminalLastSeenAtByTabId'] ptyBindingFirstSeenAtByPaneKey: Record boundaryResolvedAtByPaneKey: Record - mobileLockedPtyIds: Set + inUsePtyIds: Set now: number idleMs: number }): EligiblePane | null { @@ -81,7 +83,7 @@ export function getEligiblePane(args: { foregroundTerminalLastSeenAtByTabId, ptyBindingFirstSeenAtByPaneKey, boundaryResolvedAtByPaneKey, - mobileLockedPtyIds + inUsePtyIds } = args const sleepingRecord = sleepingAgentSessionsByPaneKey[entry.paneKey] // Every resumable agent has a live anchor after completion; it is not a sleep capture and must not block hibernation. @@ -124,22 +126,23 @@ export function getEligiblePane(args: { if (args.now - effectiveIdleStart < args.idleMs) { return null } - const inputAt = lastTerminalInputAtByPaneKey[entry.paneKey] - // Killing the PTY loses drafts/queued input typed during working too; input-after-done alone misses them. - if ( - typeof inputAt === 'number' && - Number.isFinite(inputAt) && - lastInputBlocksHibernation(entry, inputAt) - ) { - return null - } const livePane = getPaneLivePtyId(entry, layout) if (!livePane) { return null } const { leafId, ptyId } = livePane const runtimePtyId = toRuntimePtyId(ptyId) - if (!livePtyIds.has(runtimePtyId) || mobileLockedPtyIds.has(runtimePtyId)) { + const attention = args.attentionByPtyId[runtimePtyId] + if (!livePtyIds.has(runtimePtyId) || inUsePtyIds.has(runtimePtyId) || attention?.shownRemotely) { + return null + } + // Input from a paired client or phone reaches the host, not this window's own input stamps. + const inputAt = latestFinite( + lastTerminalInputAtByPaneKey[entry.paneKey], + attention?.lastInputAt ?? undefined + ) + // Killing the PTY loses drafts/queued input typed during working too; input-after-done alone misses them. + if (inputAt !== null && lastInputBlocksHibernation(entry, inputAt)) { return null } return { @@ -155,6 +158,13 @@ export function getEligiblePane(args: { state: entry.state, stateStartedAt: entry.stateStartedAt, effectiveIdleStart, - inputAt: typeof inputAt === 'number' && Number.isFinite(inputAt) ? inputAt : 0 + inputAt: inputAt ?? 0 } } + +function latestFinite(...values: (number | undefined)[]): number | null { + const finite = values.filter( + (value): value is number => typeof value === 'number' && Number.isFinite(value) + ) + return finite.length > 0 ? Math.max(...finite) : null +} diff --git a/src/renderer/src/lib/agent-hibernation-planner-snapshot.ts b/src/renderer/src/lib/agent-hibernation-planner-snapshot.ts index 7d4a2463f39..3e45012e752 100644 --- a/src/renderer/src/lib/agent-hibernation-planner-snapshot.ts +++ b/src/renderer/src/lib/agent-hibernation-planner-snapshot.ts @@ -1,6 +1,7 @@ import type { AgentStatusEntry } from '../../../shared/agent-status/contracts/agent-status-types' import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' import type { GlobalSettings } from '../../../shared/global-settings-types' +import type { RuntimeTerminalAttention } from '../../../shared/runtime-terminal-contracts' import type { TerminalLayoutSnapshot, TerminalTab @@ -15,10 +16,17 @@ export type AgentHibernationPlannerSnapshot = { ptyIdsByTabId: Record runtimeLivePtyIdsByWorktreeId?: Record runtimeLivenessRequiredWorktreeIds?: string[] - mobileLockedPtyIds: string[] + /** Driven by a phone; this window's own view is foregroundTerminalTabIds. */ + inUsePtyIds: string[] agentStatusByPaneKey: Record sleepingAgentSessionsByPaneKey: Record lastTerminalInputAtByPaneKey: Record + /** Per worktree, keyed by its host's PTY id: shown on a paired client or phone, and input from any client. + * Absent where the host can't report it. */ + attentionByWorktreeId?: Record< + string, + Record | undefined + > foregroundTerminalLastSeenAtByTabId: Record ptyBindingFirstSeenAtByPaneKey?: Record boundaryResolvedAtByPaneKey?: Record diff --git a/src/renderer/src/lib/agent-hibernation-planner.test.ts b/src/renderer/src/lib/agent-hibernation-planner.test.ts index 249bd13d2a6..a0a816b939e 100644 --- a/src/renderer/src/lib/agent-hibernation-planner.test.ts +++ b/src/renderer/src/lib/agent-hibernation-planner.test.ts @@ -69,7 +69,7 @@ function snapshot( tabsByWorktree: { 'wt-bg': [tab()] }, terminalLayoutsByTabId: { 'tab-1': layout() }, ptyIdsByTabId: { 'tab-1': ['pty-1'] }, - mobileLockedPtyIds: [], + inUsePtyIds: [], agentStatusByPaneKey: { [agentEntry.paneKey]: agentEntry }, sleepingAgentSessionsByPaneKey: {}, lastTerminalInputAtByPaneKey: {}, @@ -454,11 +454,38 @@ describe('agent sleep planner', () => { ptyIdsByTabId: { 'tab-1': ['remote:env-1@@terminal-1'] }, runtimeLivePtyIdsByWorktreeId: { 'wt-bg': ['terminal-1'] }, runtimeLivenessRequiredWorktreeIds: ['wt-bg'], - mobileLockedPtyIds: ['remote:env-1@@terminal-1'] + inUsePtyIds: ['remote:env-1@@terminal-1'] }) ) ).toEqual([]) }) + + it("judges another client's view and input on the PTY's own host, though two hosts reuse its id", () => { + const onB = entry({ paneKey: `tab-b:${LEAF}`, tabId: 'tab-b', worktreeId: 'wt-b' }) + const twoHosts = (attention: { shownRemotely: boolean; lastInputAt: number | null }) => + snapshot({ + tabsByWorktree: { 'wt-bg': [tab()], 'wt-b': [tab('tab-b', 'wt-b')] }, + terminalLayoutsByTabId: { + 'tab-1': layout(LEAF, 'remote:env-a@@terminal-1'), + 'tab-b': layout(LEAF, 'remote:env-b@@terminal-1') + }, + ptyIdsByTabId: { + 'tab-1': ['remote:env-a@@terminal-1'], + 'tab-b': ['remote:env-b@@terminal-1'] + }, + runtimeLivePtyIdsByWorktreeId: { 'wt-bg': ['terminal-1'], 'wt-b': ['terminal-1'] }, + runtimeLivenessRequiredWorktreeIds: ['wt-bg', 'wt-b'], + agentStatusByPaneKey: { [`tab-1:${LEAF}`]: entry(), [onB.paneKey]: onB }, + attentionByWorktreeId: { 'wt-b': { 'terminal-1': attention } } + }) + + expect(plannedWorktrees(twoHosts({ shownRemotely: true, lastInputAt: null }))).toEqual([ + 'wt-bg' + ]) + expect(plannedWorktrees(twoHosts({ shownRemotely: false, lastInputAt: NOW - 1 }))).toEqual([ + 'wt-bg' + ]) + }) }) describe('idle clock anchors on stateStartedAt, not updatedAt', () => { diff --git a/src/renderer/src/lib/agent-hibernation-planner.ts b/src/renderer/src/lib/agent-hibernation-planner.ts index 65cabb43d87..7f5c538bb5f 100644 --- a/src/renderer/src/lib/agent-hibernation-planner.ts +++ b/src/renderer/src/lib/agent-hibernation-planner.ts @@ -103,7 +103,7 @@ export function planAgentHibernationCandidates( return [] } const idleMs = getEffectiveAgentHibernationIdleMs(snapshot.settings.agentHibernationIdleMs) - const mobileLockedPtyIds = new Set(snapshot.mobileLockedPtyIds.map(toRuntimePtyId)) + const inUsePtyIds = new Set(snapshot.inUsePtyIds.map(toRuntimePtyId)) const foregroundTerminalTabIds = new Set(snapshot.foregroundTerminalTabIds) const runtimeLivenessRequiredWorktreeIds = new Set( snapshot.runtimeLivenessRequiredWorktreeIds ?? [] @@ -147,10 +147,11 @@ export function planAgentHibernationCandidates( livePtyIds: new Set(tabLivePtyIds), sleepingAgentSessionsByPaneKey: snapshot.sleepingAgentSessionsByPaneKey, lastTerminalInputAtByPaneKey: snapshot.lastTerminalInputAtByPaneKey, + attentionByPtyId: snapshot.attentionByWorktreeId?.[worktreeId] ?? {}, foregroundTerminalLastSeenAtByTabId: snapshot.foregroundTerminalLastSeenAtByTabId, ptyBindingFirstSeenAtByPaneKey: snapshot.ptyBindingFirstSeenAtByPaneKey ?? {}, boundaryResolvedAtByPaneKey: snapshot.boundaryResolvedAtByPaneKey ?? {}, - mobileLockedPtyIds, + inUsePtyIds, now: snapshot.now, idleMs }) diff --git a/src/renderer/src/runtime/remote-runtime-terminal-multiplexer-implementation.ts b/src/renderer/src/runtime/remote-runtime-terminal-multiplexer-implementation.ts index 889161de0ba..0f64addc8ee 100644 --- a/src/renderer/src/runtime/remote-runtime-terminal-multiplexer-implementation.ts +++ b/src/renderer/src/runtime/remote-runtime-terminal-multiplexer-implementation.ts @@ -23,6 +23,8 @@ export class RemoteRuntimeTerminalMultiplexer extends RemoteRuntimeTerminalBinar viewport?: { cols: number; rows: number } /** Stable across this pane's reattaches so the host can dedupe replayed input. */ inputSessionId?: string + /** A terminal pane pauses output while hidden, so the host may count it as showing the terminal. */ + reportsPaneVisibility?: boolean callbacks: RemoteRuntimeMultiplexedTerminalCallbacks }): Promise { const streamId = this.allocateStreamId() @@ -150,6 +152,7 @@ export class RemoteRuntimeTerminalMultiplexer extends RemoteRuntimeTerminalBinar ackOutputSourceRanges: 1, outputPause: 1, outputPauseDropNotice: 1, + ...(args.reportsPaneVisibility ? { paneVisibility: 1 } : {}), writeUnavailable: 1, ...(args.client.type === 'desktop' ? { desktopViewportClaims: 1, endpointLossNotice: 1 } diff --git a/src/renderer/src/store/slices/agent-hibernation-live-anchor-e2e.test.ts b/src/renderer/src/store/slices/agent-hibernation-live-anchor-e2e.test.ts index 8766eed073c..e078e8f13ba 100644 --- a/src/renderer/src/store/slices/agent-hibernation-live-anchor-e2e.test.ts +++ b/src/renderer/src/store/slices/agent-hibernation-live-anchor-e2e.test.ts @@ -45,7 +45,7 @@ function planFrom(state: AppState, ptyBindingFirstSeenAt: number): string[] { tabsByWorktree: state.tabsByWorktree, terminalLayoutsByTabId: state.terminalLayoutsByTabId, ptyIdsByTabId: state.ptyIdsByTabId, - mobileLockedPtyIds: [], + inUsePtyIds: [], agentStatusByPaneKey: state.agentStatusByPaneKey, sleepingAgentSessionsByPaneKey: state.sleepingAgentSessionsByPaneKey, lastTerminalInputAtByPaneKey: {}, diff --git a/src/renderer/src/web/preload-api/web-terminal-api.ts b/src/renderer/src/web/preload-api/web-terminal-api.ts index 4f6cfa0fe88..2c3db8c79d0 100644 --- a/src/renderer/src/web/preload-api/web-terminal-api.ts +++ b/src/renderer/src/web/preload-api/web-terminal-api.ts @@ -13,6 +13,8 @@ export function createPtyApi(): NonNullable['pty']> { writeAccepted: () => Promise.resolve(false), resize: () => {}, claimViewport: () => {}, + // Web clients have no local PTYs; runtime attention arrives through terminal.list. + getTerminalAttention: () => Promise.resolve({}), reportGeometry: () => {}, signal: () => {}, // Web panes clear the host buffer via the terminal.clearBuffer runtime RPC. diff --git a/src/shared/rpc-contract/terminal-unary-params.ts b/src/shared/rpc-contract/terminal-unary-params.ts index 8e27a4ce7be..82b44a5160e 100644 --- a/src/shared/rpc-contract/terminal-unary-params.ts +++ b/src/shared/rpc-contract/terminal-unary-params.ts @@ -98,6 +98,8 @@ export const TerminalListParams = z.object({ includeVisualLayouts: z.boolean().optional(), // Readers that never show the output tail drop it; absent includes it, as older hosts always do. includePreview: z.boolean().optional(), + // Agent sleep asks who else is viewing or typing; older hosts ignore it and report nothing. + includeAttention: z.boolean().optional(), // Layout-owner hosts show the workspace's unshown live terminals before listing (a window's // activation sweep); other hosts drop it, as they did before it existed. placeUnshownLiveTerminals: z.boolean().optional() diff --git a/src/shared/runtime-terminal-contracts.ts b/src/shared/runtime-terminal-contracts.ts index bd55ac2f07b..886b9ab201b 100644 --- a/src/shared/runtime-terminal-contracts.ts +++ b/src/shared/runtime-terminal-contracts.ts @@ -44,6 +44,16 @@ export type RuntimeTerminalSummary = { executionHostId?: ExecutionHostId /** Read verdict for host liveness: legacy connected can stay true while unreachable. Absent on older hosts. */ verdict?: PtyLivenessVerdict['status'] + /** Only when the caller asked for it; absent on older hosts. */ + attention?: RuntimeTerminalAttention +} + +/** Use of a PTY that its host's own window can't see: a remote client showing it, or input from anywhere. */ +export type RuntimeTerminalAttention = { + /** A paired client or phone is displaying it. Clients too old to report hidden panes never count. */ + shownRemotely: boolean + /** Last user input from any client; null if none reached its current process. */ + lastInputAt: number | null } export type RuntimeTerminalVisualTerminalNode = {