mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 10:58:10 +00:00
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
This commit is contained in:
@@ -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<string, RuntimeTerminalAttention> => {
|
||||
const { runtime } = deps
|
||||
if (
|
||||
!runtime ||
|
||||
!isMainWindowPtyIpcEvent(event, deps.mainWindow) ||
|
||||
!Array.isArray(ids) ||
|
||||
ids.length > MAX_ATTENTION_PTY_IDS
|
||||
) {
|
||||
return {}
|
||||
}
|
||||
const attention: Record<string, RuntimeTerminalAttention> = {}
|
||||
for (const id of ids) {
|
||||
if (typeof id === 'string' && id.length > 0) {
|
||||
attention[id] = runtime.getTerminalAttention(id)
|
||||
}
|
||||
}
|
||||
return attention
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -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<string, Promise<boolean>>()
|
||||
// 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)) {
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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) }
|
||||
: {})
|
||||
}))
|
||||
}
|
||||
}
|
||||
}),
|
||||
|
||||
@@ -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<string, 1>) {
|
||||
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<void> => {
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -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. */
|
||||
|
||||
@@ -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<string, number>()
|
||||
private readonly silenceableRemoteViews = new Map<string, Set<SilenceableRemoteView>>()
|
||||
private readonly rawCounts = new Map<string, number>()
|
||||
private readonly paneReportingRemoteViews = new Map<string, Set<PaneReportingRemoteView>>()
|
||||
|
||||
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)
|
||||
|
||||
@@ -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<Record<string, RuntimeTerminalAttention>>
|
||||
reportGeometry: (id: string, cols: number, rows: number) => void
|
||||
signal: (id: string, signal: string) => void
|
||||
clearBuffer: (id: string) => void
|
||||
|
||||
@@ -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<Record<string, RuntimeTerminalAttention>> =>
|
||||
ipcRenderer.invoke('pty:getTerminalAttention', ids),
|
||||
reportGeometry: (id: string, cols: number, rows: number): void => {
|
||||
ipcRenderer.send('pty:reportGeometry', { id, cols, rows })
|
||||
},
|
||||
|
||||
+1
@@ -77,6 +77,7 @@ describe('createRemoteRuntimePtyTransport', () => {
|
||||
desktopViewportClaims: 1,
|
||||
outputPause: 1,
|
||||
outputPauseDropNotice: 1,
|
||||
paneVisibility: 1,
|
||||
writeUnavailable: 1,
|
||||
endpointLossNotice: 1,
|
||||
inputAck: 1
|
||||
|
||||
@@ -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()) {
|
||||
|
||||
@@ -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<Record<string, RuntimeTerminalAttention>>
|
||||
> = 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()
|
||||
}
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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<string, string[]>
|
||||
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<string, string | null> {
|
||||
const targets = new Map<string, string | null>()
|
||||
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<RuntimePtyLivenessSample> {
|
||||
const targets = getRuntimeLivenessTargetWorktrees(state, targetWorktreeId)
|
||||
const runtimeLivePtyIdsByWorktreeId: Record<string, string[]> = {}
|
||||
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<string>()
|
||||
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<RuntimeTerminalListResult>(
|
||||
{ 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<string>()
|
||||
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)
|
||||
|
||||
@@ -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<string, string[]>
|
||||
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<string, Record<string, RuntimeTerminalAttention>>
|
||||
}
|
||||
|
||||
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<string, string | null> {
|
||||
const targets = new Map<string, string | null>()
|
||||
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<HostPtyEvidence> {
|
||||
const targets = getRuntimeLivenessTargetWorktrees(state, targetWorktreeId)
|
||||
const runtimeLivePtyIdsByWorktreeId: Record<string, string[]> = {}
|
||||
const runtimeLivenessRequiredWorktreeIds = [...targets.keys()]
|
||||
const attentionByWorktreeId: HostPtyEvidence['attentionByWorktreeId'] = {}
|
||||
const completedTabIds = new Set<string>()
|
||||
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<RuntimeTerminalListResult>(
|
||||
{ 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<string>()
|
||||
const attention: Record<string, RuntimeTerminalAttention> = {}
|
||||
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<string, string | null>,
|
||||
completedTabIds: Set<string>,
|
||||
targetWorktreeId?: string
|
||||
): Map<string, string[]> {
|
||||
const worktreeIds = targetWorktreeId ? [targetWorktreeId] : Object.keys(state.tabsByWorktree)
|
||||
const ptyIdsByWorktreeId = new Map<string, string[]>()
|
||||
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<string, string[]>,
|
||||
attentionByWorktreeId: HostPtyEvidence['attentionByWorktreeId']
|
||||
): Promise<void> {
|
||||
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.
|
||||
}
|
||||
}
|
||||
@@ -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<string>
|
||||
sleepingAgentSessionsByPaneKey: AgentHibernationPlannerSnapshot['sleepingAgentSessionsByPaneKey']
|
||||
lastTerminalInputAtByPaneKey: AgentHibernationPlannerSnapshot['lastTerminalInputAtByPaneKey']
|
||||
attentionByPtyId: Record<string, RuntimeTerminalAttention | undefined>
|
||||
foregroundTerminalLastSeenAtByTabId: AgentHibernationPlannerSnapshot['foregroundTerminalLastSeenAtByTabId']
|
||||
ptyBindingFirstSeenAtByPaneKey: Record<string, number | undefined>
|
||||
boundaryResolvedAtByPaneKey: Record<string, number | undefined>
|
||||
mobileLockedPtyIds: Set<string>
|
||||
inUsePtyIds: Set<string>
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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<string, string[] | undefined>
|
||||
runtimeLivePtyIdsByWorktreeId?: Record<string, string[] | undefined>
|
||||
runtimeLivenessRequiredWorktreeIds?: string[]
|
||||
mobileLockedPtyIds: string[]
|
||||
/** Driven by a phone; this window's own view is foregroundTerminalTabIds. */
|
||||
inUsePtyIds: string[]
|
||||
agentStatusByPaneKey: Record<string, AgentStatusEntry | undefined>
|
||||
sleepingAgentSessionsByPaneKey: Record<string, SleepingAgentSessionRecord | undefined>
|
||||
lastTerminalInputAtByPaneKey: Record<string, number | undefined>
|
||||
/** 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<string, RuntimeTerminalAttention | undefined> | undefined
|
||||
>
|
||||
foregroundTerminalLastSeenAtByTabId: Record<string, number | undefined>
|
||||
ptyBindingFirstSeenAtByPaneKey?: Record<string, number | undefined>
|
||||
boundaryResolvedAtByPaneKey?: Record<string, number | undefined>
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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
|
||||
})
|
||||
|
||||
@@ -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<RemoteRuntimeMultiplexedTerminal> {
|
||||
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 }
|
||||
|
||||
@@ -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: {},
|
||||
|
||||
@@ -13,6 +13,8 @@ export function createPtyApi(): NonNullable<Partial<PreloadApi>['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.
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
Reference in New Issue
Block a user