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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
151 changes: 151 additions & 0 deletions src/main/auto-sleep-monitor.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import { describe, it, expect, vi } from 'vitest'

vi.mock('./debug', () => ({
log: () => {}
}))
vi.mock('./perf-log', () => ({
perfLog: () => {}
}))

import { Store } from './store'
import { AutoSleepMonitor } from './auto-sleep-monitor'
import { initialState, type AppState } from '../shared/state'
import type { PanesFSM } from './panes-fsm'

const WT = '/wt/a'
const TAB = 'chat-1'
const AGENT_TOOL_USE = 'toolu_agent'
const MINUTE = 60_000
const LAST_ACTIVE = 1_000_000

function makeStore(): Store {
const state: AppState = {
...initialState,
settings: { ...initialState.settings, autoSleepMinutes: 10 },
terminals: {
...initialState.terminals,
panes: {
[WT]: {
type: 'leaf',
id: 'p1',
tabs: [{ id: TAB, type: 'json-claude', label: 'Chat' }],
activeTabId: TAB
}
},
statuses: { [TAB]: 'waiting' },
lastActive: { [WT]: LAST_ACTIVE }
}
}
const store = new Store(state)
store.dispatch({
type: 'jsonClaude/sessionStarted',
payload: { sessionId: TAB, worktreePath: WT }
})
store.dispatch({
type: 'jsonClaude/sessionStateChanged',
payload: { sessionId: TAB, state: 'running' }
})
store.dispatch({
type: 'jsonClaude/backgroundAgentLaunched',
payload: {
sessionId: TAB,
toolUseId: AGENT_TOOL_USE,
agentId: 'a123',
description: 'long job',
taskType: 'local_agent',
timestamp: LAST_ACTIVE
}
})
return store
}

function makeMonitor(store: Store) {
const sleepJsonClaudeTab = vi.fn()
const monitor = new AutoSleepMonitor(store, { sleepJsonClaudeTab } as unknown as PanesFSM)
return { monitor, sleepJsonClaudeTab }
}

describe('AutoSleepMonitor', () => {
it('does not sleep an idle tab with a running background agent', () => {
const store = makeStore()
const { monitor, sleepJsonClaudeTab } = makeMonitor(store)
monitor.sweep(LAST_ACTIVE + 30 * MINUTE)
expect(sleepJsonClaudeTab).not.toHaveBeenCalled()
})

it('sleeps the tab once the agent settles and it has been idle past the threshold', () => {
const store = makeStore()
const { monitor, sleepJsonClaudeTab } = makeMonitor(store)
store.dispatch({
type: 'jsonClaude/backgroundAgentSettled',
payload: {
sessionId: TAB,
toolUseId: AGENT_TOOL_USE,
agentId: 'a123',
status: 'completed',
timestamp: LAST_ACTIVE + MINUTE
}
})
// Under the threshold: still awake.
monitor.sweep(LAST_ACTIVE + 5 * MINUTE)
expect(sleepJsonClaudeTab).not.toHaveBeenCalled()
monitor.sweep(LAST_ACTIVE + 30 * MINUTE)
expect(sleepJsonClaudeTab).toHaveBeenCalledWith(WT, TAB)
})

it('does not sleep while a resumed agent is running again', () => {
const store = makeStore()
const { monitor, sleepJsonClaudeTab } = makeMonitor(store)
store.dispatch({
type: 'jsonClaude/backgroundAgentSettled',
payload: {
sessionId: TAB,
toolUseId: AGENT_TOOL_USE,
agentId: 'a123',
status: 'completed',
timestamp: LAST_ACTIVE + MINUTE
}
})
// SendMessage resume: same task id, the SendMessage call's tool_use id.
store.dispatch({
type: 'jsonClaude/backgroundAgentLaunched',
payload: {
sessionId: TAB,
toolUseId: 'toolu_sendmessage',
agentId: 'a123',
description: 'long job',
taskType: 'local_agent',
timestamp: LAST_ACTIVE + 2 * MINUTE
}
})
monitor.sweep(LAST_ACTIVE + 30 * MINUTE)
expect(sleepJsonClaudeTab).not.toHaveBeenCalled()
})

it('does not sleep while a background Bash task is running', () => {
const store = makeStore()
const { monitor, sleepJsonClaudeTab } = makeMonitor(store)
store.dispatch({
type: 'jsonClaude/backgroundAgentSettled',
payload: {
sessionId: TAB,
toolUseId: AGENT_TOOL_USE,
status: 'completed',
timestamp: LAST_ACTIVE + MINUTE
}
})
store.dispatch({
type: 'jsonClaude/backgroundAgentLaunched',
payload: {
sessionId: TAB,
toolUseId: 'toolu_bash',
agentId: 'bvn3zclfg',
description: 'sleep 600',
taskType: 'local_bash',
timestamp: LAST_ACTIVE + 2 * MINUTE
}
})
monitor.sweep(LAST_ACTIVE + 30 * MINUTE)
expect(sleepJsonClaudeTab).not.toHaveBeenCalled()
})
})
31 changes: 29 additions & 2 deletions src/main/auto-sleep-monitor.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Store } from './store'
import type { PanesFSM } from './panes-fsm'
import { getLeaves } from '../shared/state/terminals'
import { hasRunningBackgroundTask } from '../shared/state/json-claude'
import { log } from './debug'

const SWEEP_INTERVAL_MS = 60_000
Expand All @@ -14,6 +15,9 @@ export class AutoSleepMonitor {
private store: Store
private panesFSM: PanesFSM
private timer: NodeJS.Timeout | null = null
/** Tabs already logged as kept awake by background work, so the skip
* is logged once per stretch rather than every minute. */
private keptAwake = new Set<string>()

constructor(store: Store, panesFSM: PanesFSM) {
this.store = store
Expand All @@ -32,12 +36,12 @@ export class AutoSleepMonitor {
}
}

private sweep(): void {
/** @internal exposed for tests. */
sweep(now: number = Date.now()): void {
const state = this.store.getSnapshot().state
const minutes = state.settings.autoSleepMinutes
if (!Number.isFinite(minutes) || minutes <= 0) return
const thresholdMs = minutes * 60_000
const now = Date.now()
for (const [wtPath, tree] of Object.entries(state.terminals.panes)) {
const lastActive = state.terminals.lastActive[wtPath]
if (typeof lastActive !== 'number') continue
Expand All @@ -52,6 +56,29 @@ export class AutoSleepMonitor {
// mid-spawn would race the JsonClaudeManager's create().
const session = state.jsonClaude.sessions[tab.id]
if (session?.state === 'connecting') continue
// A turn can end with a detached Agent or run_in_background
// Bash still going; the tab reads 'waiting' but killing the
// process would kill that work too. Bash counts because Claude
// Code reports it through the same task_started/notification
// pair (see json-claude-manager.ts).
//
// No upper bound, deliberately: a backgrounded dev server or
// `tail -f` never settles, so its tab stays awake until the
// process exits. Killing the user's server would be worse than
// not sleeping. The cost is that a dropped task_notification
// (a Claude Code bug or protocol change) pins the tab too —
// hence the log line, so that's diagnosable from debug.log.
if (session && hasRunningBackgroundTask(session)) {
if (!this.keptAwake.has(tab.id)) {
this.keptAwake.add(tab.id)
log(
'auto-sleep',
`skip tab=${tab.id} wt=${wtPath}: running background task`
)
}
continue
}
this.keptAwake.delete(tab.id)
log(
'auto-sleep',
`sleep tab=${tab.id} wt=${wtPath} idleMs=${now - lastActive}`
Expand Down
34 changes: 34 additions & 0 deletions src/main/json-claude-manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -817,6 +817,40 @@ describe('JsonClaudeManager', () => {
expect(results[results.length - 1]?.content).toBe('Exact stdout: alpha')
})

// Recorded from Claude Code 2.1.327: a SendMessage resume re-runs the
// same task_id under the SendMessage call's tool_use_id.
it('a SendMessage resume re-runs and re-settles the original Agent card', () => {
const { store, feed } = setup()
const SEND_ID = 'toolu_sendmessage'
feed(started)
feed({
type: 'system',
subtype: 'task_notification',
task_id: TASK_ID,
tool_use_id: TOOL_USE_ID,
status: 'completed',
summary: 'hi'
})
feed({ ...started, tool_use_id: SEND_ID, prompt: 'now sleep 25' })
expect(Object.keys(agents(store) ?? {})).toEqual([TOOL_USE_ID])
expect(agents(store)?.[TOOL_USE_ID]?.status).toBe('running')
feed({
type: 'system',
subtype: 'task_notification',
task_id: TASK_ID,
tool_use_id: SEND_ID,
status: 'completed',
summary: 'done'
})
expect(agents(store)?.[TOOL_USE_ID]?.status).toBe('completed')
const entries =
store.getSnapshot().state.jsonClaude.sessions['sess-bg']?.entries ?? []
const results = entries
.flatMap((e) => e.blocks ?? [])
.filter((b) => b.type === 'tool_result' && b.toolUseId === TOOL_USE_ID)
expect(results[results.length - 1]?.content).toBe('done')
})

it('ignores a task event with no tool_use_id', () => {
const { store, feed } = setup()
feed({ type: 'system', subtype: 'task_started', task_id: TASK_ID })
Expand Down
51 changes: 47 additions & 4 deletions src/main/json-claude-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import type {
JsonClaudePermissionMode,
JsonClaudeSessionState
} from '../shared/state/json-claude'
import { parseUserTurn } from '../shared/state/json-claude'
import { parseUserTurn, resolveBackgroundAgentKey } from '../shared/state/json-claude'
import { writeResultImage } from './json-claude-attachments'
import type { ClaudeLaunchSettings } from './claude-launch'
import { log } from './debug'
Expand Down Expand Up @@ -1625,9 +1625,27 @@ export class JsonClaudeManager implements ChatProvider {
// actual work streams inline on this same stdout carrying
// parent_tool_use_id, so nesting already works — only the card's
// running/settled status needs wiring.
//
// What Claude Code 2.1.x actually emits (probed against the bundled
// binary):
// - Background Bash gets the same pair, with task_type 'local_bash'
// and tool_use_id = the Bash call, so it lands in backgroundAgents
// too. Bash launched by a sub-agent carries owned_by_subagent.
// - A SendMessage resume of a finished agent emits a fresh
// task_started with the SAME task_id but tool_use_id = the
// SendMessage call; its task_notification does likewise. The
// reducer maps it back to the Agent call by task_id. The resumed
// agent's inline activity still carries the original Agent id as
// parent_tool_use_id.
// - task_updated / task_progress / background_tasks_changed also
// arrive; the pair above is enough, so they're ignored.
if (type === 'system' && subtype === 'task_started') {
const toolUseId = parsed['tool_use_id']
const agentId = parsed['task_id']
log(
'json-claude',
`task_started sessionId=${instance.sessionId} tool_use_id=${String(toolUseId)} task_id=${String(agentId)} task_type=${String(parsed['task_type'])}`
)
if (typeof toolUseId !== 'string' || typeof agentId !== 'string') return
this.store.dispatch({
type: 'jsonClaude/backgroundAgentLaunched',
Expand All @@ -1639,14 +1657,33 @@ export class JsonClaudeManager implements ChatProvider {
typeof parsed['description'] === 'string'
? (parsed['description'] as string)
: '',
...(typeof parsed['task_type'] === 'string'
? { taskType: parsed['task_type'] as string }
: {}),
timestamp: Date.now()
}
})
return
}
if (type === 'system' && subtype === 'task_notification') {
const toolUseId = parsed['tool_use_id']
if (typeof toolUseId !== 'string') return
const rawToolUseId = parsed['tool_use_id']
const agentId =
typeof parsed['task_id'] === 'string' ? (parsed['task_id'] as string) : undefined
log(
'json-claude',
`task_notification sessionId=${instance.sessionId} tool_use_id=${String(rawToolUseId)} task_id=${String(agentId)} status=${String(parsed['status'])}`
)
if (typeof rawToolUseId !== 'string') return
// A resume's notification names the SendMessage call; its report
// belongs on the Agent card, which is what the user is watching.
// Resolved here because toolResultAttached below needs the Agent
// id. The backgroundAgentSettled reducer resolves again so the
// event stays correct for any other dispatcher (tests, replay);
// after this pass that second resolve is a no-op, not dead code.
const session = this.store.getSnapshot().state.jsonClaude.sessions[instance.sessionId]
const toolUseId = session
? resolveBackgroundAgentKey(session, rawToolUseId, agentId)
: rawToolUseId
const failed = parsed['status'] !== 'completed'
const rawUsage = parsed['usage'] as Record<string, unknown> | undefined
const num = (v: unknown): number | undefined =>
Expand All @@ -1663,6 +1700,7 @@ export class JsonClaudeManager implements ChatProvider {
payload: {
sessionId: instance.sessionId,
toolUseId,
...(agentId ? { agentId } : {}),
status: failed ? 'failed' : 'completed',
timestamp: Date.now(),
...(usage ? { usage } : {})
Expand Down Expand Up @@ -2203,7 +2241,12 @@ export class JsonClaudeManager implements ChatProvider {
): void {
this.store.dispatch({
type: 'jsonClaude/sessionStateChanged',
payload: { sessionId, state, ...extra }
payload: {
sessionId,
state,
...extra,
...(state === 'exited' ? { timestamp: Date.now() } : {})
}
})
}

Expand Down
Loading
Loading