Keep hibernated agent completions visible (#5689)
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -19,6 +19,7 @@ export type DashboardAgentRow = {
|
||||
entry: AgentStatusEntry
|
||||
tab: TerminalTab
|
||||
agentType: AgentType
|
||||
rowSource?: 'live' | 'retained'
|
||||
state: AgentStatusState | 'idle'
|
||||
/** When this agent first began reporting status. Derived from the oldest
|
||||
* stateHistory entry, falling back to updatedAt when no history exists yet.
|
||||
@@ -83,6 +84,7 @@ function buildAgentRowsForWorktree(
|
||||
entry,
|
||||
tab,
|
||||
agentType: entry.agentType ?? 'unknown',
|
||||
rowSource: 'live',
|
||||
state: shouldDecay ? 'idle' : entry.state,
|
||||
// Why: the oldest stateHistory entry's startedAt is the agent's original
|
||||
// "first seen" timestamp. When history is empty the entry has never
|
||||
|
||||
@@ -9,6 +9,7 @@ type MockAgentOptions = {
|
||||
paneKey?: string
|
||||
tabId?: string
|
||||
agentType?: string
|
||||
rowSource?: DashboardAgentRowData['rowSource']
|
||||
state?: string
|
||||
startedAt?: number
|
||||
prompt?: string
|
||||
@@ -32,6 +33,7 @@ function mockAgent({
|
||||
paneKey = 'tab-1:1',
|
||||
tabId = paneKey.split(':')[0],
|
||||
agentType,
|
||||
rowSource,
|
||||
state = 'working',
|
||||
startedAt,
|
||||
prompt,
|
||||
@@ -45,6 +47,7 @@ function mockAgent({
|
||||
paneKey,
|
||||
tab: { id: tabId },
|
||||
agentType,
|
||||
rowSource,
|
||||
state,
|
||||
startedAt,
|
||||
entry: {
|
||||
@@ -63,6 +66,15 @@ function mockAgent({
|
||||
let mockAgents: unknown[] = [mockAgent()]
|
||||
let mockFocusedAgentPaneKey: string | null = null
|
||||
let mockAgentActivityDisplayMode: 'compact' | 'full' | undefined
|
||||
let capturedRowActivations: {
|
||||
paneKey: string
|
||||
onActivate: (tabId: string, paneKey: string) => void
|
||||
}[] = []
|
||||
|
||||
const activationMocks = vi.hoisted(() => ({
|
||||
activateAndRevealWorktree: vi.fn(),
|
||||
activateTabAndFocusPane: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('@/store', () => ({
|
||||
useAppStore: (selector: (state: unknown) => unknown) =>
|
||||
@@ -80,6 +92,14 @@ vi.mock('@/store', () => ({
|
||||
})
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/worktree-activation', () => ({
|
||||
activateAndRevealWorktree: activationMocks.activateAndRevealWorktree
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/activate-tab-and-focus-pane', () => ({
|
||||
activateTabAndFocusPane: activationMocks.activateTabAndFocusPane
|
||||
}))
|
||||
|
||||
vi.mock('./useWorktreeAgentRows', () => ({
|
||||
useWorktreeAgentRows: vi.fn(() => mockAgents)
|
||||
}))
|
||||
@@ -98,7 +118,8 @@ vi.mock('@/components/dashboard/DashboardAgentRow', () => ({
|
||||
childAgentCount,
|
||||
childAgentsExpanded,
|
||||
onToggleChildAgents,
|
||||
reserveDisclosureGutter
|
||||
reserveDisclosureGutter,
|
||||
onActivate
|
||||
}: {
|
||||
agent: { paneKey: string }
|
||||
isFocusedPane?: boolean
|
||||
@@ -109,31 +130,35 @@ vi.mock('@/components/dashboard/DashboardAgentRow', () => ({
|
||||
childAgentsExpanded?: boolean
|
||||
onToggleChildAgents?: () => void
|
||||
reserveDisclosureGutter?: boolean
|
||||
}) => (
|
||||
<div
|
||||
data-testid="agent-row"
|
||||
data-focused={isFocusedPane ? 'true' : 'false'}
|
||||
data-agent-send-target={sendTargetStatus}
|
||||
data-disabled-reason={sendTargetDisabledReason}
|
||||
data-has-send-handler={typeof onSendTargetClick === 'function' ? 'true' : 'false'}
|
||||
data-pane-key={agent.paneKey}
|
||||
data-reserve-disclosure-gutter={reserveDisclosureGutter ? 'true' : 'false'}
|
||||
>
|
||||
{agent.paneKey}
|
||||
{typeof childAgentCount === 'number' && childAgentCount > 0 ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`${childAgentsExpanded ? 'Hide' : 'Show'} ${childAgentCount} child ${
|
||||
childAgentCount === 1 ? 'agent' : 'agents'
|
||||
}`}
|
||||
aria-expanded={childAgentsExpanded ?? false}
|
||||
onClick={onToggleChildAgents}
|
||||
>
|
||||
+{childAgentCount}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
onActivate: (tabId: string, paneKey: string) => void
|
||||
}) => {
|
||||
capturedRowActivations.push({ paneKey: agent.paneKey, onActivate })
|
||||
return (
|
||||
<div
|
||||
data-testid="agent-row"
|
||||
data-focused={isFocusedPane ? 'true' : 'false'}
|
||||
data-agent-send-target={sendTargetStatus}
|
||||
data-disabled-reason={sendTargetDisabledReason}
|
||||
data-has-send-handler={typeof onSendTargetClick === 'function' ? 'true' : 'false'}
|
||||
data-pane-key={agent.paneKey}
|
||||
data-reserve-disclosure-gutter={reserveDisclosureGutter ? 'true' : 'false'}
|
||||
>
|
||||
{agent.paneKey}
|
||||
{typeof childAgentCount === 'number' && childAgentCount > 0 ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`${childAgentsExpanded ? 'Hide' : 'Show'} ${childAgentCount} child ${
|
||||
childAgentCount === 1 ? 'agent' : 'agents'
|
||||
}`}
|
||||
aria-expanded={childAgentsExpanded ?? false}
|
||||
onClick={onToggleChildAgents}
|
||||
>
|
||||
+{childAgentCount}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('./focused-agent-row-highlight', () => ({
|
||||
@@ -152,6 +177,7 @@ describe('WorktreeCardAgents', () => {
|
||||
mockAgents = [mockAgent()]
|
||||
mockFocusedAgentPaneKey = null
|
||||
mockAgentActivityDisplayMode = undefined
|
||||
capturedRowActivations = []
|
||||
})
|
||||
|
||||
it('renders ordinary rows in full mode without a child disclosure', async () => {
|
||||
@@ -193,6 +219,19 @@ describe('WorktreeCardAgents', () => {
|
||||
expect(markup).toContain('data-pane-key="tab-1:2"')
|
||||
})
|
||||
|
||||
it('keeps retained completion rows passive when activated', async () => {
|
||||
mockAgentActivityDisplayMode = 'full'
|
||||
mockAgents = [mockAgent({ rowSource: 'retained', state: 'done' })]
|
||||
const { default: WorktreeCardAgents } = await import('./WorktreeCardAgents')
|
||||
|
||||
renderToStaticMarkup(<WorktreeCardAgents worktreeId="wt-1" />)
|
||||
expect(capturedRowActivations).toHaveLength(1)
|
||||
capturedRowActivations[0].onActivate('tab-1', 'tab-1:1')
|
||||
|
||||
expect(activationMocks.activateAndRevealWorktree).not.toHaveBeenCalled()
|
||||
expect(activationMocks.activateTabAndFocusPane).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows orchestration child agent rows under their parent by default', async () => {
|
||||
mockAgentActivityDisplayMode = 'full'
|
||||
mockAgents = [
|
||||
|
||||
@@ -208,6 +208,10 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({
|
||||
},
|
||||
[worktreeId]
|
||||
)
|
||||
const handleActivateRetainedAgent = useCallback(() => {
|
||||
// Why: hibernation-retained rows are passive completion evidence. Activating
|
||||
// the worktree would resume sleeping sessions, so the row itself is inert.
|
||||
}, [])
|
||||
|
||||
// Why: own one 30s tick per non-empty inline list. Cards with zero agents
|
||||
// never mount this component (see WorktreeCardAgents), so idle worktrees
|
||||
@@ -290,7 +294,9 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({
|
||||
<DashboardAgentRow
|
||||
agent={agent}
|
||||
onDismiss={handleDismissAgent}
|
||||
onActivate={handleActivateAgentTab}
|
||||
onActivate={
|
||||
agent.rowSource === 'retained' ? handleActivateRetainedAgent : handleActivateAgentTab
|
||||
}
|
||||
now={now}
|
||||
// Why: bold an agent row until the user has visited its tab.
|
||||
// useAutoAckViewedAgent acks automatically when the user
|
||||
@@ -356,7 +362,9 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({
|
||||
<CompactAgentRow
|
||||
agent={agent}
|
||||
now={now}
|
||||
onActivate={handleActivateAgentTab}
|
||||
onActivate={
|
||||
agent.rowSource === 'retained' ? handleActivateRetainedAgent : handleActivateAgentTab
|
||||
}
|
||||
childAgentCount={hasChildAgents ? childAgents.length : undefined}
|
||||
childAgentsExpanded={expanded}
|
||||
onToggleChildAgents={
|
||||
|
||||
@@ -247,6 +247,7 @@ export function buildWorktreeAgentRows(args: {
|
||||
entry: rowEntry,
|
||||
tab,
|
||||
agentType: resolveRowAgentType(rowEntry, tab),
|
||||
rowSource: 'live',
|
||||
state: shouldDecay ? 'idle' : rowEntry.state,
|
||||
startedAt: rowEntry.stateHistory[0]?.startedAt ?? rowEntry.stateStartedAt
|
||||
})
|
||||
@@ -286,6 +287,7 @@ export function buildWorktreeAgentRows(args: {
|
||||
entry: rowEntry,
|
||||
tab,
|
||||
agentType: resolveRowAgentType(rowEntry, tab),
|
||||
rowSource: 'live',
|
||||
state: shouldDecay ? 'idle' : rowEntry.state,
|
||||
startedAt: rowEntry.stateHistory[0]?.startedAt ?? rowEntry.stateStartedAt
|
||||
})
|
||||
@@ -314,6 +316,7 @@ export function buildWorktreeAgentRows(args: {
|
||||
entry: rowEntry,
|
||||
tab: ra.tab,
|
||||
agentType: resolveRowAgentType(rowEntry, ra.tab),
|
||||
rowSource: 'retained',
|
||||
state: 'done',
|
||||
startedAt: ra.startedAt
|
||||
})
|
||||
|
||||
@@ -152,6 +152,7 @@ function buildTitleDerivedAgentRow(args: {
|
||||
entry,
|
||||
tab: args.tab,
|
||||
agentType,
|
||||
rowSource: 'live',
|
||||
state: rowState,
|
||||
startedAt: 0
|
||||
}
|
||||
|
||||
@@ -180,6 +180,7 @@ describe('agent hibernation coordinator', () => {
|
||||
await vi.advanceTimersByTimeAsync(1000)
|
||||
expect(shutdown).toHaveBeenCalledWith('wt-bg', {
|
||||
keepIdentifiers: true,
|
||||
shutdownReason: 'auto-hibernate-completed-agent',
|
||||
sleepingPaneKeys: [`tab-1:${LEAF}`]
|
||||
})
|
||||
})
|
||||
@@ -318,6 +319,7 @@ describe('agent hibernation coordinator', () => {
|
||||
|
||||
expect(shutdown).toHaveBeenCalledWith('wt-bg', {
|
||||
keepIdentifiers: true,
|
||||
shutdownReason: 'auto-hibernate-completed-agent',
|
||||
sleepingPaneKeys: [`tab-1:${LEAF}`],
|
||||
expectedRuntimePtyIds: ['pty-1']
|
||||
})
|
||||
|
||||
@@ -173,6 +173,7 @@ async function hibernateWorktreeIfStillEligible(
|
||||
const runtimeEnvironmentId = getRuntimeEnvironmentIdForWorktree(state, worktreeId)
|
||||
await state.shutdownWorktreeTerminals(worktreeId, {
|
||||
keepIdentifiers: true,
|
||||
shutdownReason: 'auto-hibernate-completed-agent',
|
||||
sleepingPaneKeys: confirmedCandidate.paneKeys,
|
||||
...(runtimeEnvironmentId
|
||||
? { expectedRuntimePtyIds: confirmedCandidate.expectedRuntimePtyIds }
|
||||
|
||||
@@ -41,6 +41,17 @@ export type RetainedAgentEntry = {
|
||||
startedAt: number
|
||||
}
|
||||
|
||||
export type AgentStatusWorktreeShutdownReason =
|
||||
| 'manual-sleep'
|
||||
| 'remove-worktree'
|
||||
| 'auto-hibernate-completed-agent'
|
||||
|
||||
type DropAgentStatusByWorktreeOptions = {
|
||||
shutdownReason?: AgentStatusWorktreeShutdownReason
|
||||
sleepingPaneKeys?: readonly string[] | ReadonlySet<string>
|
||||
retainedCompletionEvidence?: readonly RetainedAgentEntry[]
|
||||
}
|
||||
|
||||
export type AgentStatusSlice = {
|
||||
/** Explicit agent status entries keyed by `${tabId}:${leafId}` composite.
|
||||
* Real-time only — lives in renderer memory, not persisted to disk. */
|
||||
@@ -110,7 +121,7 @@ export type AgentStatusSlice = {
|
||||
* Live entries are swept by tab prefix and by main-stamped worktree
|
||||
* attribution so worker rows that arrive before their tab exists do not
|
||||
* survive sleep/remove. */
|
||||
dropAgentStatusByWorktree: (worktreeId: string) => void
|
||||
dropAgentStatusByWorktree: (worktreeId: string, opts?: DropAgentStatusByWorktreeOptions) => void
|
||||
|
||||
captureSleepingAgentSessionsByWorktree: (worktreeId: string, paneKeys?: string[]) => void
|
||||
/** Capture resumable agent sessions across every worktree. Called from the
|
||||
@@ -186,6 +197,64 @@ function findTabForAgentEntry(
|
||||
return (state.tabsByWorktree[worktreeId] ?? []).find((tab) => tab.id === tabId)
|
||||
}
|
||||
|
||||
function getRetainedFallbackTab(entry: AgentStatusEntry, worktreeId: string): TerminalTab {
|
||||
const tabId = entry.tabId ?? getTabIdFromPaneKey(entry.paneKey) ?? entry.paneKey
|
||||
return {
|
||||
id: tabId,
|
||||
ptyId: null,
|
||||
worktreeId,
|
||||
title: entry.terminalTitle ?? 'Agent',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: entry.stateStartedAt
|
||||
}
|
||||
}
|
||||
|
||||
function retainedAgentEntryFromLive(
|
||||
state: AppState,
|
||||
worktreeId: string,
|
||||
entry: AgentStatusEntry,
|
||||
agentType: AgentType
|
||||
): RetainedAgentEntry {
|
||||
const tab =
|
||||
findTabForAgentEntry(state, worktreeId, entry) ?? getRetainedFallbackTab(entry, worktreeId)
|
||||
return {
|
||||
entry,
|
||||
worktreeId,
|
||||
tab,
|
||||
agentType,
|
||||
startedAt: entry.stateHistory[0]?.startedAt ?? entry.stateStartedAt
|
||||
}
|
||||
}
|
||||
|
||||
function shouldReplaceRetainedWithLive(
|
||||
retained: RetainedAgentEntry | undefined,
|
||||
live: RetainedAgentEntry
|
||||
): boolean {
|
||||
if (!retained) {
|
||||
return true
|
||||
}
|
||||
if (live.startedAt !== retained.startedAt) {
|
||||
return live.startedAt > retained.startedAt
|
||||
}
|
||||
const retainedSessionId = retained.entry.providerSession?.id
|
||||
const liveSessionId = live.entry.providerSession?.id
|
||||
if (retainedSessionId && liveSessionId && retainedSessionId !== liveSessionId) {
|
||||
return live.entry.updatedAt >= retained.entry.updatedAt
|
||||
}
|
||||
return live.entry.updatedAt > retained.entry.updatedAt
|
||||
}
|
||||
|
||||
function normalizePaneKeySet(
|
||||
paneKeys: DropAgentStatusByWorktreeOptions['sleepingPaneKeys']
|
||||
): ReadonlySet<string> | null {
|
||||
if (!paneKeys) {
|
||||
return null
|
||||
}
|
||||
return paneKeys instanceof Set ? paneKeys : new Set(paneKeys)
|
||||
}
|
||||
|
||||
function sleepingRecordFromEntry(args: {
|
||||
state: AppState
|
||||
entry: AgentStatusEntry
|
||||
@@ -274,6 +343,37 @@ export function collectSleepingAgentSessionRecordsForWorktree(
|
||||
return records
|
||||
}
|
||||
|
||||
export function collectHibernatedCompletionEvidenceForWorktree(
|
||||
state: AppState,
|
||||
worktreeId: string,
|
||||
paneKeys?: readonly string[]
|
||||
): RetainedAgentEntry[] {
|
||||
const allowedPaneKeys = normalizePaneKeySet(paneKeys)
|
||||
if (!allowedPaneKeys || allowedPaneKeys.size === 0) {
|
||||
return []
|
||||
}
|
||||
const tabPrefixes = (state.tabsByWorktree[worktreeId] ?? []).map((tab) => `${tab.id}:`)
|
||||
const retained: RetainedAgentEntry[] = []
|
||||
for (const [paneKey, entry] of Object.entries(state.agentStatusByPaneKey)) {
|
||||
const agentType = entry.agentType
|
||||
if (
|
||||
!allowedPaneKeys.has(paneKey) ||
|
||||
entry.state !== 'done' ||
|
||||
agentType === undefined ||
|
||||
entry.interrupted === true
|
||||
) {
|
||||
continue
|
||||
}
|
||||
const belongsToWorktree =
|
||||
entry.worktreeId === worktreeId || paneKeyMatchesAnyTabPrefix(paneKey, tabPrefixes)
|
||||
if (!belongsToWorktree) {
|
||||
continue
|
||||
}
|
||||
retained.push(retainedAgentEntryFromLive(state, worktreeId, entry, agentType))
|
||||
}
|
||||
return retained
|
||||
}
|
||||
|
||||
function recoveryRecordMatches(
|
||||
existing: SleepingAgentSessionRecord | undefined,
|
||||
next: SleepingAgentSessionRecord
|
||||
@@ -1011,16 +1111,15 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
|
||||
}
|
||||
},
|
||||
|
||||
dropAgentStatusByWorktree: (worktreeId) => {
|
||||
dropAgentStatusByWorktree: (worktreeId, opts) => {
|
||||
let hadLive = false
|
||||
set((s) => {
|
||||
const tabPrefixes = (s.tabsByWorktree[worktreeId] ?? []).map((tab) => `${tab.id}:`)
|
||||
const liveKeys = Object.entries(s.agentStatusByPaneKey)
|
||||
.filter(
|
||||
([paneKey, entry]) =>
|
||||
entry.worktreeId === worktreeId || paneKeyMatchesAnyTabPrefix(paneKey, tabPrefixes)
|
||||
)
|
||||
.map(([paneKey]) => paneKey)
|
||||
const liveEntries = Object.entries(s.agentStatusByPaneKey).filter(
|
||||
([paneKey, entry]) =>
|
||||
entry.worktreeId === worktreeId || paneKeyMatchesAnyTabPrefix(paneKey, tabPrefixes)
|
||||
)
|
||||
const liveKeys = liveEntries.map(([paneKey]) => paneKey)
|
||||
const liveKeySet = new Set(liveKeys)
|
||||
const retainedKeys = Object.entries(s.retainedAgentsByPaneKey)
|
||||
.filter(
|
||||
@@ -1035,13 +1134,50 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
|
||||
entry.worktreeId === worktreeId ||
|
||||
(entry.paneKey ? paneKeyMatchesAnyTabPrefix(entry.paneKey, tabPrefixes) : false)
|
||||
)
|
||||
const allowedPaneKeys = normalizePaneKeySet(opts?.sleepingPaneKeys)
|
||||
const preserveHibernatedEvidence =
|
||||
opts?.shutdownReason === 'auto-hibernate-completed-agent' &&
|
||||
allowedPaneKeys !== null &&
|
||||
allowedPaneKeys.size > 0
|
||||
const liveEntryByPaneKey = new Map(liveEntries)
|
||||
const retainedEvidence = new Map<string, RetainedAgentEntry>()
|
||||
if (preserveHibernatedEvidence) {
|
||||
for (const retained of opts?.retainedCompletionEvidence ?? []) {
|
||||
if (
|
||||
allowedPaneKeys.has(retained.entry.paneKey) &&
|
||||
!liveEntryByPaneKey.has(retained.entry.paneKey) &&
|
||||
shouldReplaceRetainedWithLive(retainedEvidence.get(retained.entry.paneKey), retained)
|
||||
) {
|
||||
retainedEvidence.set(retained.entry.paneKey, retained)
|
||||
}
|
||||
}
|
||||
for (const [paneKey, entry] of liveEntries) {
|
||||
const agentType = entry.agentType
|
||||
if (
|
||||
allowedPaneKeys.has(paneKey) &&
|
||||
entry.state === 'done' &&
|
||||
agentType !== undefined &&
|
||||
entry.interrupted !== true
|
||||
) {
|
||||
retainedEvidence.set(
|
||||
paneKey,
|
||||
retainedAgentEntryFromLive(s, worktreeId, entry, agentType)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
const retainedEvidenceKeys = new Set(retainedEvidence.keys())
|
||||
// See removeAgentStatus for rationale on ack cleanup. Current tabs are
|
||||
// swept by prefix; attributed live rows and orphan retained rows are
|
||||
// swept by their retained/lifecycle key.
|
||||
// swept by their retained/lifecycle key. Auto-hibernated completion
|
||||
// evidence keeps its read state so a slept card does not turn bold again.
|
||||
let nextAck = s.acknowledgedAgentsByPaneKey
|
||||
const ackKeys = Object.keys(nextAck).filter(
|
||||
(k) =>
|
||||
paneKeyMatchesAnyTabPrefix(k, tabPrefixes) || liveKeySet.has(k) || retainedKeySet.has(k)
|
||||
!retainedEvidenceKeys.has(k) &&
|
||||
(paneKeyMatchesAnyTabPrefix(k, tabPrefixes) ||
|
||||
liveKeySet.has(k) ||
|
||||
retainedKeySet.has(k))
|
||||
)
|
||||
if (ackKeys.length > 0) {
|
||||
nextAck = { ...nextAck }
|
||||
@@ -1053,7 +1189,12 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
|
||||
// changed, narrow the return to just the ack delta (or s) so we don't
|
||||
// emit a new top-level state object that re-renders full-state
|
||||
// subscribers for nothing.
|
||||
if (liveKeys.length === 0 && retainedKeys.length === 0 && !migrationUnsupported.changed) {
|
||||
if (
|
||||
liveKeys.length === 0 &&
|
||||
retainedKeys.length === 0 &&
|
||||
retainedEvidence.size === 0 &&
|
||||
!migrationUnsupported.changed
|
||||
) {
|
||||
if (nextAck !== s.acknowledgedAgentsByPaneKey) {
|
||||
return { acknowledgedAgentsByPaneKey: nextAck }
|
||||
}
|
||||
@@ -1068,15 +1209,27 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
|
||||
}
|
||||
|
||||
const nextRetained =
|
||||
retainedKeys.length > 0 ? { ...s.retainedAgentsByPaneKey } : s.retainedAgentsByPaneKey
|
||||
retainedKeys.length > 0 || retainedEvidence.size > 0
|
||||
? { ...s.retainedAgentsByPaneKey }
|
||||
: s.retainedAgentsByPaneKey
|
||||
for (const key of retainedKeys) {
|
||||
delete nextRetained[key]
|
||||
if (!retainedEvidenceKeys.has(key)) {
|
||||
delete nextRetained[key]
|
||||
}
|
||||
}
|
||||
for (const [paneKey, retained] of retainedEvidence) {
|
||||
if (shouldReplaceRetainedWithLive(nextRetained[paneKey], retained)) {
|
||||
nextRetained[paneKey] = retained
|
||||
}
|
||||
}
|
||||
|
||||
// Why: a worktree-level teardown folds the whole surface. Current live
|
||||
// rows need one-shot suppressors so the retention sync cannot recreate a
|
||||
// done row from the previous render after sleep/remove has hidden it.
|
||||
const suppressorAdds = liveKeys.filter((k) => !(k in s.retentionSuppressedPaneKeys))
|
||||
// Why: normal worktree teardown folds the surface, so live rows need
|
||||
// suppressors. Auto-hibernated `done` rows become retained evidence
|
||||
// immediately, so suppressing those same pane keys would erase them on
|
||||
// the next retention sync.
|
||||
const suppressorAdds = liveKeys.filter(
|
||||
(k) => !retainedEvidenceKeys.has(k) && !(k in s.retentionSuppressedPaneKeys)
|
||||
)
|
||||
let nextRetentionSuppressedPaneKeys = s.retentionSuppressedPaneKeys
|
||||
if (suppressorAdds.length > 0) {
|
||||
nextRetentionSuppressedPaneKeys = { ...s.retentionSuppressedPaneKeys }
|
||||
|
||||
@@ -3126,6 +3126,140 @@ describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('commits pre-stop retained evidence when exact-stop clears live status during hibernation', async () => {
|
||||
const store = createTestStore()
|
||||
const wt = 'repo1::/path/wt1'
|
||||
mockApi.runtimeEnvironments.call.mockImplementation((args: { method: string }) => {
|
||||
if (args.method === 'terminal.stopExact') {
|
||||
store.getState().removeAgentStatus('tab-1:live')
|
||||
return Promise.resolve({
|
||||
id: 'rpc-default',
|
||||
ok: true,
|
||||
result: { stoppedPtyIds: ['pty-1'], livePtyIds: ['pty-1'], postStopVerified: true },
|
||||
_meta: { runtimeId: 'remote-runtime' }
|
||||
})
|
||||
}
|
||||
return Promise.resolve(
|
||||
createCompatibleRuntimeStatusResponseIfNeeded(args) ?? {
|
||||
id: 'rpc-default',
|
||||
ok: true,
|
||||
result: {},
|
||||
_meta: { runtimeId: 'remote-runtime' }
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
seedStore(store, {
|
||||
settings: { ...getDefaultSettings('/tmp'), activeRuntimeEnvironmentId: 'runtime-1' },
|
||||
worktreesByRepo: {
|
||||
repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
|
||||
},
|
||||
tabsByWorktree: {
|
||||
[wt]: [makeTab({ id: 'tab-1', worktreeId: wt, title: 'Codex' })]
|
||||
},
|
||||
ptyIdsByTabId: { 'tab-1': [] }
|
||||
})
|
||||
store.getState().setAgentStatus(
|
||||
'tab-1:live',
|
||||
{
|
||||
state: 'done',
|
||||
prompt: 'resume live',
|
||||
agentType: 'codex',
|
||||
lastAssistantMessage: 'done'
|
||||
},
|
||||
'Codex',
|
||||
{ updatedAt: 1000, stateStartedAt: 1000 },
|
||||
{ tabId: 'tab-1', worktreeId: wt },
|
||||
{ providerSession: { key: 'session_id', id: 'live-session' } }
|
||||
)
|
||||
|
||||
await store.getState().shutdownWorktreeTerminals(wt, {
|
||||
keepIdentifiers: true,
|
||||
shutdownReason: 'auto-hibernate-completed-agent',
|
||||
sleepingPaneKeys: ['tab-1:live'],
|
||||
expectedRuntimePtyIds: ['pty-1']
|
||||
})
|
||||
|
||||
expect(store.getState().agentStatusByPaneKey['tab-1:live']).toBeUndefined()
|
||||
expect(store.getState().retainedAgentsByPaneKey['tab-1:live']).toMatchObject({
|
||||
worktreeId: wt,
|
||||
entry: {
|
||||
prompt: 'resume live',
|
||||
lastAssistantMessage: 'done',
|
||||
providerSession: { key: 'session_id', id: 'live-session' }
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('does not commit stale pre-stop evidence when exact-stop changes live status', async () => {
|
||||
const store = createTestStore()
|
||||
const wt = 'repo1::/path/wt1'
|
||||
mockApi.runtimeEnvironments.call.mockImplementation((args: { method: string }) => {
|
||||
if (args.method === 'terminal.stopExact') {
|
||||
store.getState().setAgentStatus(
|
||||
'tab-1:live',
|
||||
{
|
||||
state: 'working',
|
||||
prompt: 'still active',
|
||||
agentType: 'codex'
|
||||
},
|
||||
'Codex',
|
||||
{ updatedAt: 1500, stateStartedAt: 1500 },
|
||||
{ tabId: 'tab-1', worktreeId: wt },
|
||||
{ providerSession: { key: 'session_id', id: 'live-session' } }
|
||||
)
|
||||
return Promise.resolve({
|
||||
id: 'rpc-default',
|
||||
ok: true,
|
||||
result: { stoppedPtyIds: ['pty-1'], livePtyIds: ['pty-1'], postStopVerified: true },
|
||||
_meta: { runtimeId: 'remote-runtime' }
|
||||
})
|
||||
}
|
||||
return Promise.resolve(
|
||||
createCompatibleRuntimeStatusResponseIfNeeded(args) ?? {
|
||||
id: 'rpc-default',
|
||||
ok: true,
|
||||
result: {},
|
||||
_meta: { runtimeId: 'remote-runtime' }
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
seedStore(store, {
|
||||
settings: { ...getDefaultSettings('/tmp'), activeRuntimeEnvironmentId: 'runtime-1' },
|
||||
worktreesByRepo: {
|
||||
repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
|
||||
},
|
||||
tabsByWorktree: {
|
||||
[wt]: [makeTab({ id: 'tab-1', worktreeId: wt, title: 'Codex' })]
|
||||
},
|
||||
ptyIdsByTabId: { 'tab-1': [] }
|
||||
})
|
||||
store.getState().setAgentStatus(
|
||||
'tab-1:live',
|
||||
{
|
||||
state: 'done',
|
||||
prompt: 'stale done',
|
||||
agentType: 'codex'
|
||||
},
|
||||
'Codex',
|
||||
{ updatedAt: 1000, stateStartedAt: 1000 },
|
||||
{ tabId: 'tab-1', worktreeId: wt },
|
||||
{ providerSession: { key: 'session_id', id: 'live-session' } }
|
||||
)
|
||||
|
||||
await store.getState().shutdownWorktreeTerminals(wt, {
|
||||
keepIdentifiers: true,
|
||||
shutdownReason: 'auto-hibernate-completed-agent',
|
||||
sleepingPaneKeys: ['tab-1:live'],
|
||||
expectedRuntimePtyIds: ['pty-1']
|
||||
})
|
||||
|
||||
expect(store.getState().agentStatusByPaneKey['tab-1:live']).toBeUndefined()
|
||||
expect(store.getState().retainedAgentsByPaneKey['tab-1:live']).toBeUndefined()
|
||||
expect(store.getState().retentionSuppressedPaneKeys['tab-1:live']).toBe(true)
|
||||
})
|
||||
|
||||
it('does not commit sleep state when exact runtime stop fails', async () => {
|
||||
const store = createTestStore()
|
||||
const wt = 'repo1::/path/wt1'
|
||||
@@ -3359,6 +3493,203 @@ describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => {
|
||||
expect(state.sleepingAgentSessionsByPaneKey['tab-1:retained']).toBeUndefined()
|
||||
})
|
||||
|
||||
it('retains only clean slept completions during automatic hibernation', async () => {
|
||||
const store = createTestStore()
|
||||
const wt = 'repo1::/path/wt1'
|
||||
const otherWt = 'repo1::/path/wt2'
|
||||
|
||||
seedStore(store, {
|
||||
worktreesByRepo: {
|
||||
repo1: [
|
||||
makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' }),
|
||||
makeWorktree({ id: otherWt, repoId: 'repo1', path: '/path/wt2' })
|
||||
]
|
||||
},
|
||||
tabsByWorktree: {
|
||||
[wt]: [makeTab({ id: 'tab-1', worktreeId: wt, title: 'Codex' })],
|
||||
[otherWt]: [makeTab({ id: 'tab-2', worktreeId: otherWt, title: 'Codex' })]
|
||||
},
|
||||
ptyIdsByTabId: { 'tab-1': ['pty-1'], 'tab-2': ['pty-2'] }
|
||||
})
|
||||
|
||||
store.getState().setAgentStatus(
|
||||
'tab-1:live',
|
||||
{
|
||||
state: 'working',
|
||||
prompt: 'new retained prompt',
|
||||
agentType: 'codex'
|
||||
},
|
||||
'Codex',
|
||||
{ updatedAt: 1800, stateStartedAt: 1800 },
|
||||
{ tabId: 'tab-1', worktreeId: wt },
|
||||
{ providerSession: { key: 'session_id', id: 'live-session' } }
|
||||
)
|
||||
store.getState().setAgentStatus(
|
||||
'tab-1:live',
|
||||
{
|
||||
state: 'done',
|
||||
prompt: 'new retained prompt',
|
||||
agentType: 'codex',
|
||||
lastAssistantMessage: 'new final message',
|
||||
interrupted: false
|
||||
},
|
||||
'Codex',
|
||||
{ updatedAt: 2000, stateStartedAt: 2000 },
|
||||
{ tabId: 'tab-1', worktreeId: wt },
|
||||
{ providerSession: { key: 'session_id', id: 'live-session' } }
|
||||
)
|
||||
store.getState().retainAgents([
|
||||
{
|
||||
entry: {
|
||||
paneKey: 'tab-1:live',
|
||||
state: 'done',
|
||||
stateStartedAt: 1000,
|
||||
updatedAt: 1000,
|
||||
stateHistory: [],
|
||||
prompt: 'stale same-pane prompt',
|
||||
agentType: 'codex',
|
||||
providerSession: { key: 'session_id', id: 'old-session' }
|
||||
},
|
||||
worktreeId: wt,
|
||||
tab: makeTab({ id: 'tab-1', worktreeId: wt, title: 'Old Codex' }),
|
||||
agentType: 'codex',
|
||||
startedAt: 1000
|
||||
},
|
||||
{
|
||||
entry: {
|
||||
paneKey: 'tab-1:retained',
|
||||
state: 'done',
|
||||
stateStartedAt: 1500,
|
||||
updatedAt: 1500,
|
||||
stateHistory: [],
|
||||
prompt: 'unslept retained prompt',
|
||||
agentType: 'codex'
|
||||
},
|
||||
worktreeId: wt,
|
||||
tab: makeTab({ id: 'tab-1', worktreeId: wt, title: 'Codex' }),
|
||||
agentType: 'codex',
|
||||
startedAt: 1500
|
||||
},
|
||||
{
|
||||
entry: {
|
||||
paneKey: 'tab-2:retained',
|
||||
state: 'done',
|
||||
stateStartedAt: 1600,
|
||||
updatedAt: 1600,
|
||||
stateHistory: [],
|
||||
prompt: 'other retained prompt',
|
||||
agentType: 'codex'
|
||||
},
|
||||
worktreeId: otherWt,
|
||||
tab: makeTab({ id: 'tab-2', worktreeId: otherWt, title: 'Codex' }),
|
||||
agentType: 'codex',
|
||||
startedAt: 1600
|
||||
}
|
||||
])
|
||||
store.getState().acknowledgeAgents(['tab-1:live', 'tab-1:retained', 'tab-2:retained'])
|
||||
const liveAck = store.getState().acknowledgedAgentsByPaneKey['tab-1:live']
|
||||
store.getState().setMigrationUnsupportedPty({
|
||||
ptyId: 'pty-legacy',
|
||||
worktreeId: wt,
|
||||
paneKey: 'tab-1:legacy',
|
||||
reason: 'legacy-numeric-pane-key',
|
||||
source: 'local',
|
||||
updatedAt: 1700
|
||||
})
|
||||
|
||||
await store.getState().shutdownWorktreeTerminals(wt, {
|
||||
keepIdentifiers: true,
|
||||
shutdownReason: 'auto-hibernate-completed-agent',
|
||||
sleepingPaneKeys: ['tab-1:live']
|
||||
})
|
||||
|
||||
const state = store.getState()
|
||||
expect(state.agentStatusByPaneKey['tab-1:live']).toBeUndefined()
|
||||
expect(state.retainedAgentsByPaneKey['tab-1:live']).toMatchObject({
|
||||
worktreeId: wt,
|
||||
startedAt: 1800,
|
||||
entry: {
|
||||
prompt: 'new retained prompt',
|
||||
lastAssistantMessage: 'new final message',
|
||||
providerSession: { key: 'session_id', id: 'live-session' }
|
||||
}
|
||||
})
|
||||
expect(state.sleepingAgentSessionsByPaneKey['tab-1:live']).toMatchObject({
|
||||
paneKey: 'tab-1:live',
|
||||
providerSession: { key: 'session_id', id: 'live-session' }
|
||||
})
|
||||
expect(state.retainedAgentsByPaneKey['tab-1:retained']).toBeUndefined()
|
||||
expect(state.retainedAgentsByPaneKey['tab-2:retained']).toBeDefined()
|
||||
expect(state.acknowledgedAgentsByPaneKey['tab-1:live']).toBe(liveAck)
|
||||
expect(state.acknowledgedAgentsByPaneKey['tab-1:retained']).toBeUndefined()
|
||||
expect(state.acknowledgedAgentsByPaneKey['tab-2:retained']).toBeGreaterThan(0)
|
||||
expect(state.migrationUnsupportedByPtyId['pty-legacy']).toBeUndefined()
|
||||
expect(state.retentionSuppressedPaneKeys['tab-1:live']).toBeUndefined()
|
||||
})
|
||||
|
||||
it('does not retain interrupted, non-done, or retained-only rows on automatic hibernation', async () => {
|
||||
const store = createTestStore()
|
||||
const wt = 'repo1::/path/wt1'
|
||||
|
||||
seedStore(store, {
|
||||
worktreesByRepo: {
|
||||
repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
|
||||
},
|
||||
tabsByWorktree: {
|
||||
[wt]: [makeTab({ id: 'tab-1', worktreeId: wt, title: 'Codex' })]
|
||||
},
|
||||
ptyIdsByTabId: { 'tab-1': ['pty-1'] }
|
||||
})
|
||||
|
||||
store.getState().setAgentStatus('tab-1:interrupted', {
|
||||
state: 'done',
|
||||
prompt: 'cancelled',
|
||||
agentType: 'codex',
|
||||
interrupted: true
|
||||
})
|
||||
store.getState().setAgentStatus('tab-1:working', {
|
||||
state: 'working',
|
||||
prompt: 'still working',
|
||||
agentType: 'codex'
|
||||
})
|
||||
store.getState().retainAgents([
|
||||
{
|
||||
entry: {
|
||||
paneKey: 'tab-1:retained-only',
|
||||
state: 'done',
|
||||
stateStartedAt: 1000,
|
||||
updatedAt: 1000,
|
||||
stateHistory: [],
|
||||
prompt: 'retained only',
|
||||
agentType: 'codex'
|
||||
},
|
||||
worktreeId: wt,
|
||||
tab: makeTab({ id: 'tab-1', worktreeId: wt, title: 'Codex' }),
|
||||
agentType: 'codex',
|
||||
startedAt: 1000
|
||||
}
|
||||
])
|
||||
store
|
||||
.getState()
|
||||
.acknowledgeAgents(['tab-1:interrupted', 'tab-1:working', 'tab-1:retained-only'])
|
||||
|
||||
await store.getState().shutdownWorktreeTerminals(wt, {
|
||||
keepIdentifiers: true,
|
||||
shutdownReason: 'auto-hibernate-completed-agent',
|
||||
sleepingPaneKeys: ['tab-1:interrupted', 'tab-1:working', 'tab-1:retained-only']
|
||||
})
|
||||
|
||||
const state = store.getState()
|
||||
expect(state.retainedAgentsByPaneKey['tab-1:interrupted']).toBeUndefined()
|
||||
expect(state.retainedAgentsByPaneKey['tab-1:working']).toBeUndefined()
|
||||
expect(state.retainedAgentsByPaneKey['tab-1:retained-only']).toBeUndefined()
|
||||
expect(state.acknowledgedAgentsByPaneKey['tab-1:interrupted']).toBeUndefined()
|
||||
expect(state.acknowledgedAgentsByPaneKey['tab-1:working']).toBeUndefined()
|
||||
expect(state.acknowledgedAgentsByPaneKey['tab-1:retained-only']).toBeUndefined()
|
||||
expect(state.retentionSuppressedPaneKeys['tab-1:interrupted']).toBe(true)
|
||||
expect(state.retentionSuppressedPaneKeys['tab-1:working']).toBe(true)
|
||||
})
|
||||
|
||||
it('does not preserve provider session metadata when a pane switches agent type', async () => {
|
||||
const store = createTestStore()
|
||||
const wt = 'repo1::/path/wt1'
|
||||
|
||||
@@ -53,7 +53,11 @@ import { sanitizeTerminalLayoutPaneTitles } from '@/lib/terminal-pane-title-sani
|
||||
import { focusTerminalTabSurface } from '@/lib/focus-terminal-tab-surface'
|
||||
import { getRuntimeEnvironmentIdForWorktree } from '@/lib/worktree-runtime-owner'
|
||||
import { getLocalProjectExecutionRuntimeContext } from '@/lib/local-preflight-context'
|
||||
import { collectSleepingAgentSessionRecordsForWorktree } from './agent-status'
|
||||
import {
|
||||
collectHibernatedCompletionEvidenceForWorktree,
|
||||
collectSleepingAgentSessionRecordsForWorktree,
|
||||
type AgentStatusWorktreeShutdownReason
|
||||
} from './agent-status'
|
||||
|
||||
function getNextTerminalOrdinal(tabs: TerminalTab[]): number {
|
||||
const usedOrdinals = new Set<number>()
|
||||
@@ -424,6 +428,7 @@ export type TerminalSlice = {
|
||||
worktreeId: string,
|
||||
opts?: {
|
||||
keepIdentifiers?: boolean
|
||||
shutdownReason?: AgentStatusWorktreeShutdownReason
|
||||
sleepingPaneKeys?: string[]
|
||||
expectedRuntimePtyIds?: string[]
|
||||
}
|
||||
@@ -1678,6 +1683,8 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
|
||||
shutdownWorktreeTerminals: async (worktreeId, opts) => {
|
||||
const keepIdentifiers = opts?.keepIdentifiers ?? false
|
||||
const shutdownReason: AgentStatusWorktreeShutdownReason =
|
||||
opts?.shutdownReason ?? (keepIdentifiers ? 'manual-sleep' : 'remove-worktree')
|
||||
const tabs = get().tabsByWorktree[worktreeId] ?? []
|
||||
const ptyIds = tabs.flatMap((tab) => get().ptyIdsByTabId[tab.id] ?? [])
|
||||
const expectedRuntimePtyIds = sortedUniquePtyIds(opts?.expectedRuntimePtyIds)
|
||||
@@ -1685,6 +1692,10 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
const sleepingAgentSessionRecords = keepIdentifiers
|
||||
? collectSleepingAgentSessionRecordsForWorktree(get(), worktreeId, opts?.sleepingPaneKeys)
|
||||
: {}
|
||||
const retainedCompletionEvidence =
|
||||
shutdownReason === 'auto-hibernate-completed-agent'
|
||||
? collectHibernatedCompletionEvidenceForWorktree(get(), worktreeId, opts?.sleepingPaneKeys)
|
||||
: []
|
||||
|
||||
// Why: the main process flushes any remaining batched PTY data before
|
||||
// sending the exit event (pty.ts onExit handler). Without this, that
|
||||
@@ -1955,12 +1966,13 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
get().clearSleepingAgentSessionsByWorktree(worktreeId)
|
||||
}
|
||||
|
||||
// Why: sleep/remove fold the whole worktree surface. The live PTY bindings
|
||||
// were cleared above and kill is about to run, so live rows are stale;
|
||||
// retained rows are folded too so a grey slept card does not keep a green
|
||||
// "done" row. Sweep by worktreeId because retained snapshots can outlive
|
||||
// their original tab.
|
||||
get().dropAgentStatusByWorktree(worktreeId)
|
||||
// Why: only automatic completed-agent hibernation keeps passive completion
|
||||
// evidence; manual sleep/remove still fold the entire worktree surface.
|
||||
get().dropAgentStatusByWorktree(worktreeId, {
|
||||
shutdownReason,
|
||||
sleepingPaneKeys: opts?.sleepingPaneKeys,
|
||||
retainedCompletionEvidence
|
||||
})
|
||||
|
||||
if (ptyIds.length === 0 && expectedRuntimePtyIds.length === 0) {
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user