diff --git a/cli/src/claude/claudeRemote.ts b/cli/src/claude/claudeRemote.ts index 52510a5d..0014de92 100644 --- a/cli/src/claude/claudeRemote.ts +++ b/cli/src/claude/claudeRemote.ts @@ -624,6 +624,14 @@ export async function claudeRemote(opts: { ); logger.debugLargeJson(`[claudeRemote] Message ${message.type}`, message); + // Autonomous rounds (background tasks, scheduled follow-ups) stream + // assistant messages after the previous result flipped thinking off; + // the SDK never re-fires its own thinking signal for them. Re-bump + // here so the hub renders the round as working, not waiting. + if (message.type === 'assistant') { + updateThinking(true); + } + if (message.type === 'user' && (message as SDKUserMessage).isReplay === true) { const uuid = (message as SDKUserMessage).uuid; if (uuid && pushedUuids.delete(uuid)) { diff --git a/hub/src/store/getLiveToolWork.test.ts b/hub/src/store/getLiveToolWork.test.ts new file mode 100644 index 00000000..e3361282 --- /dev/null +++ b/hub/src/store/getLiveToolWork.test.ts @@ -0,0 +1,229 @@ +import { describe, expect, it } from 'bun:test' +import { AGENT_MESSAGE_PAYLOAD_TYPE } from '@hapi/protocol' +import { getToolCallId } from '@hapi/protocol/messages' +import { Store } from './index' + +function makeStore(): Store { + return new Store(':memory:') +} + +function makeSession(store: Store, tag: string) { + return store.sessions.getOrCreateSession(tag, { path: `/tmp/${tag}` }, null, 'default') +} + +type ToolCallFields = { + name?: string + input?: unknown + status?: string + nativeTitle?: string + nativeKind?: string + nativeName?: string + nativeArgs?: unknown + progress?: unknown +} + +function toolCallContent(callId: string, fields: ToolCallFields = {}): unknown { + return { + role: 'agent', + content: { + type: AGENT_MESSAGE_PAYLOAD_TYPE, + data: { + type: 'tool-call', + callId, + name: fields.name ?? 'Read', + ...(fields.input !== undefined ? { input: fields.input } : {}), + ...(fields.status !== undefined ? { status: fields.status } : {}), + ...(fields.nativeTitle !== undefined ? { nativeTitle: fields.nativeTitle } : {}), + ...(fields.nativeKind !== undefined ? { nativeKind: fields.nativeKind } : {}), + ...(fields.nativeName !== undefined ? { nativeName: fields.nativeName } : {}), + ...(fields.nativeArgs !== undefined ? { nativeArgs: fields.nativeArgs } : {}), + ...(fields.progress !== undefined ? { progress: fields.progress } : {}) + } + } + } +} + +function agentMessageContent(text: string): unknown { + return { + role: 'agent', + content: { + type: AGENT_MESSAGE_PAYLOAD_TYPE, + data: { type: 'message', message: text } + } + } +} + +function toolCallResultContent(callId: string, output: unknown): unknown { + return { + role: 'agent', + content: { + type: AGENT_MESSAGE_PAYLOAD_TYPE, + data: { type: 'tool-call-result', callId, output } + } + } +} + +function claudeAssistantContent(blocks: unknown[], extra: Record = {}): unknown { + return { + role: 'agent', + content: { + type: 'output', + data: { + type: 'assistant', + message: { role: 'assistant', content: blocks }, + ...extra + } + } + } +} + +function claudeUserContent(blocks: unknown[], extra: Record = {}): unknown { + return { + role: 'agent', + content: { + type: 'output', + data: { + type: 'user', + message: { role: 'user', content: blocks }, + ...extra + } + } + } +} + +describe('getLiveToolWork', () => { + it('reports open ACP tool calls until their result lands', () => { + const store = makeStore() + const session = makeSession(store, 'live-work-acp-open') + + // Empty session: nothing to wait on. + expect(store.messages.getLiveToolWork(session.id)).toBe(false) + + store.messages.upsertToolCallMessage(session.id, toolCallContent('call-1', { status: 'in_progress' }), 'call-1') + expect(store.messages.getLiveToolWork(session.id)).toBe(true) + + // Agent chatter between the call and now does not settle it. + store.messages.addMessage(session.id, agentMessageContent('still working')) + expect(store.messages.getLiveToolWork(session.id)).toBe(true) + + store.messages.addMessage(session.id, toolCallResultContent('call-1', 'done')) + expect(store.messages.getLiveToolWork(session.id)).toBe(false) + store.close() + }) + + it('closes every call at a human turn for ACP sessions', () => { + const store = makeStore() + const session = makeSession(store, 'live-work-acp-user-turn') + + store.messages.upsertToolCallMessage(session.id, toolCallContent('call-1', { status: 'in_progress' }), 'call-1') + store.messages.addMessage(session.id, { role: 'user', content: { type: 'text', text: 'new prompt' } }) + + expect(store.messages.getLiveToolWork(session.id)).toBe(false) + store.close() + }) + + it('treats a terminal-status ACP call as settled even without a result row', () => { + const store = makeStore() + const session = makeSession(store, 'live-work-acp-terminal') + + store.messages.upsertToolCallMessage(session.id, toolCallContent('call-1', { status: 'completed' }), 'call-1') + expect(store.messages.getLiveToolWork(session.id)).toBe(false) + store.close() + }) + + it('reports open claude tool_use pairs until the matching tool_result lands', () => { + const store = makeStore() + const session = makeSession(store, 'live-work-claude-open') + + store.messages.addMessage(session.id, claudeAssistantContent([ + { type: 'text', text: 'let me check' } + ])) + expect(store.messages.getLiveToolWork(session.id)).toBe(false) + + store.messages.addMessage(session.id, claudeAssistantContent([ + { type: 'tool_use', id: 'tu-1', name: 'Bash', input: { command: 'sleep 60' } } + ])) + expect(store.messages.getLiveToolWork(session.id)).toBe(true) + + // A tool-result carrier continues the turn but settles the call. + store.messages.addMessage(session.id, claudeUserContent([ + { type: 'tool_result', tool_use_id: 'tu-1', content: 'ran' } + ])) + expect(store.messages.getLiveToolWork(session.id)).toBe(false) + + // A second open call re-opens the work; an unrelated result walks past. + store.messages.addMessage(session.id, claudeAssistantContent([ + { type: 'tool_use', id: 'tu-2', name: 'Read', input: { path: '/a' } } + ])) + store.messages.addMessage(session.id, toolCallResultContent('other-flavor', 'unrelated')) + expect(store.messages.getLiveToolWork(session.id)).toBe(true) + + store.messages.addMessage(session.id, claudeUserContent([ + { type: 'tool_result', tool_use_id: 'tu-2', content: 'read' } + ])) + expect(store.messages.getLiveToolWork(session.id)).toBe(false) + store.close() + }) + + it('closes claude tool_use at a human turn or a prompt-shaped user row', () => { + const store = makeStore() + const sessionHuman = makeSession(store, 'live-work-claude-human-row') + store.messages.addMessage(sessionHuman.id, claudeAssistantContent([ + { type: 'tool_use', id: 'tu-1', name: 'Bash', input: {} } + ])) + store.messages.addMessage(sessionHuman.id, { role: 'user', content: { type: 'text', text: 'stop' } }) + expect(store.messages.getLiveToolWork(sessionHuman.id)).toBe(false) + + const sessionPrompt = makeSession(store, 'live-work-claude-prompt-row') + store.messages.addMessage(sessionPrompt.id, claudeAssistantContent([ + { type: 'tool_use', id: 'tu-1', name: 'Bash', input: {} } + ])) + // A claude user passthrough row with no tool_result is a human prompt. + store.messages.addMessage(sessionPrompt.id, claudeUserContent([ + { type: 'text', text: 'do something else' } + ])) + expect(store.messages.getLiveToolWork(sessionPrompt.id)).toBe(false) + store.close() + }) + + it('stops at a claude turn-end result row, with newer open calls still detected', () => { + const store = makeStore() + const session = makeSession(store, 'live-work-claude-result') + + const claudeResult = (isError = false): unknown => ({ + role: 'agent', + content: { + type: 'output', + data: { type: 'result', subtype: isError ? 'error_during_execution' : 'success', is_error: isError, result: 'done', uuid: 'r1' } + } + }) + + // Finished turn: open-looking call below the turn's result row is closed. + store.messages.addMessage(session.id, claudeAssistantContent([ + { type: 'tool_use', id: 'tu-dead', name: 'Bash', input: {} } + ])) + // No tool_result ever landed (interrupted turn) — the result row still + // proves the turn ended. + store.messages.addMessage(session.id, claudeResult(true)) + expect(store.messages.getLiveToolWork(session.id)).toBe(false) + + // A newer round opens work again, regardless of the older result row. + store.messages.addMessage(session.id, claudeAssistantContent([ + { type: 'tool_use', id: 'tu-live', name: 'Bash', input: {} } + ])) + expect(store.messages.getLiveToolWork(session.id)).toBe(true) + store.close() + }) + + it('ignores hidden claude passthrough rows (sidechain/meta)', () => { + const store = makeStore() + const session = makeSession(store, 'live-work-claude-hidden') + + store.messages.addMessage(session.id, claudeAssistantContent( + [{ type: 'tool_use', id: 'tu-side', name: 'Task', input: {} }], + { isSidechain: true } + )) + expect(store.messages.getLiveToolWork(session.id)).toBe(false) + store.close() + }) +}) diff --git a/hub/src/store/messageStore.ts b/hub/src/store/messageStore.ts index bbfdd60b..563103a8 100644 --- a/hub/src/store/messageStore.ts +++ b/hub/src/store/messageStore.ts @@ -8,6 +8,7 @@ import type { StoredMessage } from './types' import { addMessage, upsertToolCallMessage, + getLiveToolWork, syncNativeQueuedMessage, addImportedMessage, cancelQueuedMessage, @@ -81,6 +82,12 @@ export class MessageStore { return upsertToolCallMessage(this.db, sessionId, content, callId, localId, createdAt) } + /** Whether the session tail still holds unsettled tool work (see + * getLiveToolWork in messages.ts for the liveness contract). */ + getLiveToolWork(sessionId: string): boolean { + return getLiveToolWork(this.db, sessionId) + } + syncNativeQueuedMessage(sessionId: string, localId: string, text: string): StoredMessage { return syncNativeQueuedMessage(this.db, sessionId, localId, text) } diff --git a/hub/src/store/messages.ts b/hub/src/store/messages.ts index f2c041df..0993b00c 100644 --- a/hub/src/store/messages.ts +++ b/hub/src/store/messages.ts @@ -506,6 +506,155 @@ function findLiveToolCallRow(db: Database, sessionId: string, callId: string): D return full } +/** The `data` record of a Claude-SDK passthrough row + * (`{ role: 'agent', content: { type: 'output', data } }`), or null. */ +function claudeOutputData(value: unknown): Record | null { + const record = unwrapRoleWrappedRecordEnvelope(value) + if (record?.role !== 'agent' || !isRecord(record.content)) return null + if (record.content.type !== 'output') return null + return isRecord(record.content.data) ? record.content.data : null +} + +/** Claude passthrough rows the chat never renders (meta / compact summaries / + * subagent sidechains). Their tool traffic has no settlement contract in the + * main thread, so the liveness sweep must ignore them on both sides. */ +function isHiddenClaudeOutput(data: Record): boolean { + return data.isMeta === true || data.isCompactSummary === true || data.isSidechain === true +} + +/** The `message.content` block array of a Claude passthrough row, or null. */ +function claudeMessageBlocks(data: Record): unknown[] | null { + const message = isRecord(data.message) ? data.message : null + return Array.isArray(message?.content) ? message.content : null +} + +/** Collect `tool_result` tool_use_ids from a Claude user passthrough row. + * Returns whether the row carried any tool_result at all — a user row + * without one is a human prompt, which starts a new turn. */ +function collectClaudeToolResultIds(data: Record, into: Set): boolean { + const blocks = claudeMessageBlocks(data) + if (!blocks) return false + let found = false + for (const block of blocks) { + if (!isRecord(block) || block.type !== 'tool_result') continue + if (typeof block.tool_use_id === 'string' && block.tool_use_id.length > 0) { + into.add(block.tool_use_id) + found = true + } + } + return found +} + +/** Whether a Claude assistant passthrough row holds a `tool_use` block whose + * result has not settled yet (work the agent is still waiting on). */ +function claudeAssistantHasOpenToolUse(data: Record, settledToolUseIds: Set): boolean { + const blocks = claudeMessageBlocks(data) + if (!blocks) return false + for (const block of blocks) { + if (!isRecord(block) || block.type !== 'tool_use') continue + if (typeof block.id === 'string' && block.id.length > 0 && !settledToolUseIds.has(block.id)) { + return true + } + } + return false +} + +/** Whether a stored ACP `tool-call` row already reports a terminal status. + * Flavors that settle a call through its status (instead of a separate + * `tool-call-result` row) must not read as open work. */ +function isTerminalToolCallRow(value: unknown): boolean { + const record = unwrapRoleWrappedRecordEnvelope(value) + if (!record || !isRecord(record.content) || record.content.type !== AGENT_MESSAGE_PAYLOAD_TYPE) return false + const data = isRecord(record.content.data) ? record.content.data : null + if (!data || data.type !== 'tool-call') return false + return toolCallStatusRank(data.status) === TOOL_CALL_STATUS_RANK.completed +} + +/** Whether the session tail still holds tool work that started but never + * settled — the transcript-derived "the agent is demonstrably working" + * signal for the hub's work-scoped liveness sweep. + * + * Scans the same bounded tail window as `findLiveToolCallRow` and shares its + * liveness contract (which the toolCallRowCache also keys on): a settled + * call is closed by a later result row, and every live call of the session + * is closed by a later human turn. Walking newest-first: + * + * - ACP flavors: an unsettled, non-terminal `tool-call` row means open work. + * - Claude passthrough: an assistant `tool_use` block with no later user + * `tool_result` for its id means open work. Tool-result carriers do NOT + * close the turn (the agent loop continues through them); a user row with + * no tool_result is a human prompt and does. + * + * Anything older than the window reads as no work — the same err-closed + * bias the upsert scan uses for ancient rows. */ +export function getLiveToolWork(db: Database, sessionId: string): boolean { + const rows = prepareCached(db, ` + SELECT id, content FROM messages + WHERE session_id = ? + ORDER BY seq DESC + LIMIT ? + `).all(sessionId, TOOL_CALL_UPSERT_LOOKBACK) as Array> + + const settledAcpCallIds = new Set() + const settledClaudeToolUseIds = new Set() + for (const row of rows) { + const decoded = decodeMessageContent(row.content) + // A human turn (web prompt, native user row) starts a new round and + // closes every tool call older than it — stop, nothing is open. + if (isUserMessageRow(decoded)) return false + + const claudeData = claudeOutputData(decoded) + if (claudeData !== null) { + if (isHiddenClaudeOutput(claudeData)) continue + if (claudeData.type === 'user') { + if (!collectClaudeToolResultIds(claudeData, settledClaudeToolUseIds)) return false + continue + } + if (claudeData.type === 'result') { + // Turn-end marker: everything newer was walked already, so the + // calls of this finished turn are settled. Idle sessions end + // here, which keeps the sweep's every-tick scan to one row. + return false + } + if (claudeData.type === 'assistant' + && claudeAssistantHasOpenToolUse(claudeData, settledClaudeToolUseIds)) { + return true + } + continue + } + + const resultCallId = toolCallResultCallId(decoded) + if (resultCallId !== null) { + settledAcpCallIds.add(resultCallId) + continue + } + const callId = getToolCallId(decoded) + if (callId !== null && !settledAcpCallIds.has(callId) && !isTerminalToolCallRow(decoded)) { + return true + } + } + return false +} + +/** Merge an incoming tool-call snapshot into a known live row. Shared by the + * cache-hit path and the tail-scan path so both produce identical rows. */ +function mergeIntoToolCallRow(db: Database, existing: DbMessageRow, content: unknown): UpsertToolCallResult { + const storedContent = decodeMessageContent(existing.content) + const mergedContent = truncateOversizedMessageContent(mergeToolCallContent(storedContent, content)) + // A re-emitted tick that changes nothing must not rewrite the row: + // only observable content changes touch the database. + if (isDeepStrictEqual(mergedContent, storedContent)) { + return { message: toStoredMessage(existing), updated: true } + } + const encoded = encodeMessageContent(mergedContent) + // Same in-place content swap as the queued-message edit path + // (syncNativeQueuedMessage): no new seq, no content_revision bump. + prepareCached(db, 'UPDATE messages SET content = ? WHERE id = ?').run(encoded, existing.id) + const row = prepareCached(db, 'SELECT * FROM messages WHERE id = ?').get(existing.id) as DbMessageRow | undefined + if (!row) throw new Error('Failed to update tool-call message') + return { message: toStoredMessage(row), updated: true } +} + /** Store one ACP `tool-call` agent message, updating the call's existing row * in place when the same callId is still live in the session tail. * diff --git a/hub/src/sync/sessionCache.derivedWork.test.ts b/hub/src/sync/sessionCache.derivedWork.test.ts new file mode 100644 index 00000000..f86daec1 --- /dev/null +++ b/hub/src/sync/sessionCache.derivedWork.test.ts @@ -0,0 +1,157 @@ +import { describe, expect, it } from 'bun:test' +import { toSessionSummary } from '@hapi/protocol' +import type { SyncEvent, SessionPatch } from '@hapi/protocol/types' +import { Store } from '../store' +import type { EventPublisher } from './eventPublisher' +import { SessionCache } from './sessionCache' + +function createPublisher(events: SyncEvent[]): EventPublisher { + return { + emit: (event: SyncEvent) => { + events.push(event) + } + } as unknown as EventPublisher +} + +function derivedWorkPatches(events: SyncEvent[], sessionId: string): Array { + return events + .filter((event): event is Extract => + event.type === 'session-updated' && event.sessionId === sessionId) + .map((event) => (event.data as SessionPatch | undefined)?.derivedToolWork) + .filter((value) => value !== undefined) +} + +const baseTime = 1_780_000_000_000 + +describe('derived tool work flag', () => { + it('noteDerivedWork broadcasts only on change and surfaces in the summary', () => { + const store = new Store(':memory:') + const events: SyncEvent[] = [] + const cache = new SessionCache(store, createPublisher(events)) + const session = cache.getOrCreateSession( + 'derived-work-broadcast', + { path: '/tmp/project', host: 'localhost', flavor: 'claude' }, + null, + 'default' + ) + + expect(session.derivedToolWork ?? false).toBe(false) + expect(toSessionSummary(cache.getSession(session.id)!).derivedToolWork).toBe(false) + + cache.noteDerivedWork(session.id, true) + expect(cache.getSession(session.id)?.derivedToolWork).toBe(true) + expect(toSessionSummary(cache.getSession(session.id)!).derivedToolWork).toBe(true) + expect(derivedWorkPatches(events, session.id)).toEqual([true]) + + // Repeat call with the same value stays quiet (the sweep ticks every 5s). + events.length = 0 + cache.noteDerivedWork(session.id, true) + expect(events).toEqual([]) + + cache.noteDerivedWork(session.id, false) + expect(cache.getSession(session.id)?.derivedToolWork).toBe(false) + expect(derivedWorkPatches(events, session.id)).toEqual([false]) + + // Unknown sessions are a no-op, not a broadcast. + events.length = 0 + cache.noteDerivedWork('never-seen', true) + expect(events).toEqual([]) + store.close() + }) + + it('survives a cache refresh (transient, never persisted)', () => { + const store = new Store(':memory:') + const events: SyncEvent[] = [] + const cache = new SessionCache(store, createPublisher(events)) + const session = cache.getOrCreateSession( + 'derived-work-refresh', + { path: '/tmp/project', host: 'localhost', flavor: 'claude' }, + null, + 'default' + ) + + cache.noteDerivedWork(session.id, true) + cache.refreshSession(session.id) + expect(cache.getSession(session.id)?.derivedToolWork).toBe(true) + store.close() + }) + + it('handleSessionEnd clears the derived flag alongside background tasks', () => { + const originalDateNow = Date.now + Date.now = () => baseTime + try { + const store = new Store(':memory:') + const events: SyncEvent[] = [] + const cache = new SessionCache(store, createPublisher(events)) + const session = cache.getOrCreateSession( + 'derived-work-end', + { path: '/tmp/project', host: 'localhost', flavor: 'claude' }, + null, + 'default' + ) + + cache.handleSessionAlive({ sid: session.id, time: baseTime, thinking: false }) + cache.setBackgroundTasks(session.id, [{ id: 'b1', type: 'local_bash', description: 'run' }]) + cache.noteDerivedWork(session.id, true) + events.length = 0 + + cache.handleSessionEnd({ sid: session.id, time: baseTime + 1_000 }) + + const ended = cache.getSession(session.id)! + expect(ended.active).toBe(false) + expect(ended.backgroundTaskCount).toBe(0) + expect(ended.backgroundTasks).toEqual([]) + expect(ended.derivedToolWork).toBe(false) + expect(derivedWorkPatches(events, session.id)).toEqual([false]) + store.close() + } finally { + Date.now = originalDateNow + } + }) + + it('expireInactive resets stale background task counts like handleSessionEnd', () => { + const originalDateNow = Date.now + Date.now = () => baseTime + try { + const store = new Store(':memory:') + const events: SyncEvent[] = [] + const cache = new SessionCache(store, createPublisher(events)) + const session = cache.getOrCreateSession( + 'derived-work-expire', + { path: '/tmp/project', host: 'localhost', flavor: 'claude' }, + null, + 'default' + ) + + cache.handleSessionAlive({ sid: session.id, time: baseTime, thinking: false }) + // The runner died mid-background-work: counts were declared, the + // keepalive went silent, and no session-end ever arrived. + cache.setBackgroundTasks(session.id, [ + { id: 'b1', type: 'local_bash', description: 'long job' } + ]) + cache.noteDerivedWork(session.id, true) + events.length = 0 + + const expired = cache.expireInactive(baseTime + 30_001) + expect(expired).toEqual([session.id]) + + const after = cache.getSession(session.id)! + expect(after.active).toBe(false) + expect(after.backgroundTaskCount).toBe(0) + expect(after.backgroundTasks).toEqual([]) + expect(after.derivedToolWork).toBe(false) + + const patches = events + .filter((event): event is Extract => + event.type === 'session-updated' && event.sessionId === session.id) + .map((event) => event.data as SessionPatch) + expect(patches).toHaveLength(1) + expect(patches[0]!.backgroundTaskCount).toBe(0) + expect(patches[0]!.backgroundTasks).toEqual([]) + expect(patches[0]!.derivedToolWork).toBe(false) + store.close() + } finally { + Date.now = originalDateNow + } + }) +}) diff --git a/hub/src/sync/sessionCache.ts b/hub/src/sync/sessionCache.ts index 6725b081..4a43ae4b 100644 --- a/hub/src/sync/sessionCache.ts +++ b/hub/src/sync/sessionCache.ts @@ -317,6 +317,8 @@ export class SessionCache { activeTurnStartedAt: existing?.activeTurnStartedAt ?? null, backgroundTaskCount: existing?.backgroundTaskCount ?? 0, backgroundTasks: existing?.backgroundTasks ?? [], + // Transient derived flag: survive a cache refresh, never persist. + derivedToolWork: existing?.derivedToolWork ?? false, todos, teamState, todosUpdatedAt: stored.todosUpdatedAt ?? 0, @@ -454,6 +456,7 @@ export class SessionCache { if (patch.collaborationMode !== undefined) session.collaborationMode = patch.collaborationMode if (patch.backgroundTaskCount !== undefined) session.backgroundTaskCount = patch.backgroundTaskCount if (patch.backgroundTasks !== undefined) session.backgroundTasks = patch.backgroundTasks + if (patch.derivedToolWork !== undefined) session.derivedToolWork = patch.derivedToolWork if (patch.todos !== undefined) { session.todos = patch.todos.value session.todosUpdatedAt = patch.todos.version @@ -721,6 +724,30 @@ export class SessionCache { }) } + /** + * Record the transcript-derived "open tool work" flag (work-scoped + * liveness). Mirrors setBackgroundTasks: a transient in-memory Session + * flag plus a session-updated broadcast, and a no-op when nothing + * changed so the sweep's every-tick calls stay quiet. + * + * Set by the SyncEngine's derived-work sweep for connected sessions + * whose `thinking` is false and no background task is declared, yet + * whose tail holds a tool call that never settled — the autonomous + * round case. Cleared on session end / expiry alongside the other + * transient work state. + */ + noteDerivedWork(sessionId: string, open: boolean): void { + const session = this.sessions.get(sessionId) + if (!session) return + if ((session.derivedToolWork ?? false) === open) return + session.derivedToolWork = open + this.publisher.emit({ + type: 'session-updated', + sessionId, + data: { derivedToolWork: open } satisfies SessionPatch + }) + } + refreshLastUserMessageAt(sessionId: string): void { const stored = this.store.sessions.getSession(sessionId) if (stored?.lastUserMessageAt === undefined) return @@ -975,12 +1002,20 @@ export class SessionCache { this.recordTurn(session, wasThinking, t, 'agent', 'session_end') session.backgroundTaskCount = 0 session.backgroundTasks = [] + session.derivedToolWork = false this.pendingThinkingUntilBySessionId.delete(session.id) this.publisher.emit({ type: 'session-updated', sessionId: session.id, - data: { active: false, thinking: false, activeTurnStartedAt: null, backgroundTaskCount: 0, backgroundTasks: [] } satisfies SessionPatch + data: { + active: false, + thinking: false, + activeTurnStartedAt: null, + backgroundTaskCount: 0, + backgroundTasks: [], + derivedToolWork: false + } satisfies SessionPatch }) } @@ -1002,6 +1037,14 @@ export class SessionCache { session.active = false this.store.sessions.setSessionActive(session.id, false, now, session.namespace) session.thinking = false + // The keepalive died, not the tasks: reset the transient work + // state like handleSessionEnd does, or a session that expired + // mid-background-work keeps its stale backgroundTaskCount (and + // derived flag) forever — the row would render "waiting" for + // hours after the process was gone. + session.backgroundTaskCount = 0 + session.backgroundTasks = [] + session.derivedToolWork = false // The last keepalive is the last time the agent was known to be working. this.recordTurn(session, wasThinking, session.activeAt, 'agent', 'expired') this.pendingThinkingUntilBySessionId.delete(session.id) @@ -1009,7 +1052,12 @@ export class SessionCache { this.publisher.emit({ type: 'session-updated', sessionId: session.id, - data: { active: false } satisfies SessionPatch + data: { + active: false, + backgroundTaskCount: 0, + backgroundTasks: [], + derivedToolWork: false + } satisfies SessionPatch }) } diff --git a/hub/src/sync/syncEngine.derivedWork.test.ts b/hub/src/sync/syncEngine.derivedWork.test.ts new file mode 100644 index 00000000..2e13ca79 --- /dev/null +++ b/hub/src/sync/syncEngine.derivedWork.test.ts @@ -0,0 +1,147 @@ +import { describe, expect, it } from 'bun:test' +import { AGENT_MESSAGE_PAYLOAD_TYPE } from '@hapi/protocol' +import type { SyncEvent, SessionPatch } from '@hapi/protocol/types' +import { Store } from '../store' +import { RpcRegistry } from '../socket/rpcRegistry' +import { SyncEngine } from './syncEngine' + +function createEngine(store: Store): { engine: SyncEngine; events: SyncEvent[] } { + const events: SyncEvent[] = [] + const engine = new SyncEngine(store, {} as never, new RpcRegistry(), { broadcast() {} } as never) + engine.subscribe((event) => { events.push(event) }) + return { engine, events } +} + +function acpToolCall(callId: string): unknown { + return { + role: 'agent', + content: { + type: AGENT_MESSAGE_PAYLOAD_TYPE, + data: { type: 'tool-call', callId, name: 'Bash', input: {}, status: 'in_progress' } + } + } +} + +function acpToolCallResult(callId: string): unknown { + return { + role: 'agent', + content: { + type: AGENT_MESSAGE_PAYLOAD_TYPE, + data: { type: 'tool-call-result', callId, output: 'done' } + } + } +} + +function derivedWorkPatches(events: SyncEvent[], sessionId: string): Array { + return events + .filter((event): event is Extract => + event.type === 'session-updated' && event.sessionId === sessionId) + .map((event) => (event.data as SessionPatch | undefined)?.derivedToolWork) + .filter((value) => value !== undefined) +} + +function tick(engine: SyncEngine): void { + ;(engine as unknown as { expireInactive(): void }).expireInactive() +} + +describe('sync engine derived tool work sweep', () => { + it('derives open tool work for a connected non-thinking session and clears it when the call settles', () => { + const store = new Store(':memory:') + const { engine, events } = createEngine(store) + try { + const session = engine.getOrCreateSession( + 'engine-derived-sweep', + { path: '/tmp/project', host: 'localhost', flavor: 'gemini' }, + null, + 'default' + ) + engine.handleSessionAlive({ sid: session.id, time: Date.now(), thinking: false }) + + // Autonomous round: the result already flipped thinking off, but a + // tool call never settled. + store.messages.upsertToolCallMessage(session.id, acpToolCall('call-1'), 'call-1') + tick(engine) + + expect(engine.getSession(session.id)?.derivedToolWork).toBe(true) + expect(derivedWorkPatches(events, session.id)).toEqual([true]) + + store.messages.addMessage(session.id, acpToolCallResult('call-1')) + tick(engine) + + expect(engine.getSession(session.id)?.derivedToolWork).toBe(false) + expect(derivedWorkPatches(events, session.id)).toEqual([true, false]) + } finally { + engine.stop() + store.close() + } + }) + + it('skips thinking sessions and clears a stale flag once the session turns ineligible', () => { + const store = new Store(':memory:') + const { engine } = createEngine(store) + try { + const session = engine.getOrCreateSession( + 'engine-derived-thinking', + { path: '/tmp/project', host: 'localhost', flavor: 'gemini' }, + null, + 'default' + ) + engine.handleSessionAlive({ sid: session.id, time: Date.now(), thinking: false }) + store.messages.upsertToolCallMessage(session.id, acpToolCall('call-1'), 'call-1') + tick(engine) + expect(engine.getSession(session.id)?.derivedToolWork).toBe(true) + + // A foreground turn starts: thinking carries the spinner itself, so + // the derived flag must not linger. + engine.handleSessionAlive({ sid: session.id, time: Date.now(), thinking: true }) + tick(engine) + expect(engine.getSession(session.id)?.derivedToolWork ?? false).toBe(false) + + // And a thinking session with open work never derives the flag. + store.messages.upsertToolCallMessage(session.id, acpToolCall('call-2'), 'call-2') + tick(engine) + expect(engine.getSession(session.id)?.derivedToolWork ?? false).toBe(false) + } finally { + engine.stop() + store.close() + } + }) + + it('skips sessions that already render work: background tasks or a running attached job', () => { + const store = new Store(':memory:') + const { engine } = createEngine(store) + try { + const withTasks = engine.getOrCreateSession( + 'engine-derived-tasks', + { path: '/tmp/project', host: 'localhost', flavor: 'claude' }, + null, + 'default' + ) + engine.handleSessionAlive({ sid: withTasks.id, time: Date.now(), thinking: false }) + store.messages.upsertToolCallMessage(withTasks.id, acpToolCall('call-t'), 'call-t') + ;(engine as unknown as { + sessionCache: { setBackgroundTasks(id: string, tasks: unknown[]): void } + }).sessionCache.setBackgroundTasks(withTasks.id, [ + { id: 'b1', type: 'local_bash', description: 'long job' } + ]) + + const withJob = engine.getOrCreateSession( + 'engine-derived-job', + { path: '/tmp/project', host: 'localhost', flavor: 'claude' }, + null, + 'default' + ) + engine.handleSessionAlive({ sid: withJob.id, time: Date.now(), thinking: false }) + store.messages.upsertToolCallMessage(withJob.id, acpToolCall('call-j'), 'call-j') + engine.upsertSessionJob(withJob.id, 'import', { label: 'beets import', status: 'running' }) + + tick(engine) + + expect(engine.getSession(withTasks.id)?.derivedToolWork ?? false).toBe(false) + expect(engine.getSession(withJob.id)?.derivedToolWork ?? false).toBe(false) + } finally { + engine.stop() + store.close() + } + }) +}) diff --git a/hub/src/sync/syncEngine.ts b/hub/src/sync/syncEngine.ts index cf5b3f98..131c09ec 100644 --- a/hub/src/sync/syncEngine.ts +++ b/hub/src/sync/syncEngine.ts @@ -1867,6 +1867,49 @@ export class SyncEngine { for (const session of this.sessionCache.getSessions()) if (this.openCodeRewindPending(session.id)) held.add(session.id) this.messageService.releaseMatureScheduledMessages(Date.now(), held) void this.reconcileOpenCodeClears() + this.reconcileDerivedToolWork() + } + + /** + * Work-scoped liveness sweep, piggybacked on the 5s inactivity tick. + * + * `thinking` is turn-scoped: the CLI flips it false at the SDK result + * even while autonomous rounds (background tasks, scheduled follow-ups) + * keep streaming tool calls. For connected sessions that claim neither + * thinking nor background tasks nor an attached job, derive "open tool + * work" straight from the transcript tail and broadcast it as + * `derivedToolWork`, so the session row shows work instead of a stale + * "waiting". Sessions inside the queued-prompt thinking grace are left + * alone — their spinner is already accounted for. When a session stops + * being eligible while the flag is still set, clear it so the derived + * signal never outlives the state it vouched for. + */ + private reconcileDerivedToolWork(): void { + const now = Date.now() + const candidates: Session[] = [] + for (const session of this.sessionCache.getSessions()) { + if (this.isDerivedToolWorkCandidate(session)) { + candidates.push(session) + } else if (session.derivedToolWork === true) { + this.sessionCache.noteDerivedWork(session.id, false) + } + } + if (candidates.length === 0) return + // One batched primary-job read: a session with a running attached + // job already renders work; the sweep must not double-report. + const primaryJobs = this.getPrimaryAttachedJobsBySessionIds(candidates.map((session) => session.id)) + for (const session of candidates) { + if ((primaryJobs.get(session.id) ?? null) !== null) continue + this.sessionCache.noteDerivedWork(session.id, this.store.messages.getLiveToolWork(session.id)) + } + } + + /** Eligibility for the derived-work sweep: connected, no thinking flag, + * and no declared background tasks. */ + private isDerivedToolWorkCandidate(session: Session): boolean { + if (!session.active || session.thinking) return false + if ((session.backgroundTaskCount ?? 0) > 0) return false + return true } private async reconcileOpenCodeClears(): Promise { diff --git a/shared/src/schemas.ts b/shared/src/schemas.ts index 6eebeb45..7e17b448 100644 --- a/shared/src/schemas.ts +++ b/shared/src/schemas.ts @@ -487,6 +487,11 @@ export const SessionSchema = z.object({ activeTurnStartedAt: z.number().nullable().optional(), backgroundTaskCount: z.number().optional(), backgroundTasks: z.array(BackgroundTaskSchema).optional(), + // Hub-derived "open tool work exists in the transcript tail" signal + // (work-scoped liveness). Transient — never persisted, recomputed by the + // hub's inactivity tick; covers autonomous rounds the CLI's turn-scoped + // `thinking` flag misses. + derivedToolWork: z.boolean().optional(), todos: TodosSchema.optional(), teamState: TeamStateSchema.optional(), // Watermarks for structured SSE patches (PR #897). Dual EventSource @@ -641,6 +646,10 @@ export const SessionPatchSchema = z.object({ copilotAgentMode: CopilotAgentModeSchema.optional(), backgroundTaskCount: z.number().optional(), backgroundTasks: z.array(BackgroundTaskSchema).optional(), + // Hub-derived open-tool-work signal (see SessionSchema). Emitted by the + // hub's derived-work sweep so list rows can render a working state for + // autonomous rounds that carry no `thinking` flag. + derivedToolWork: z.boolean().optional(), // tiann/hapi#893 (scratchlist v2). Bumped whenever any entry on the // session_scratchlist table mutates. Web client uses the change as a // trigger to refetch the entries query - the timestamp itself is the diff --git a/shared/src/sessionSummary.ts b/shared/src/sessionSummary.ts index 37d82340..d6a3f288 100644 --- a/shared/src/sessionSummary.ts +++ b/shared/src/sessionSummary.ts @@ -117,6 +117,14 @@ export type SessionSummary = { * `pendingRequestsCount`. */ pendingRequests: PendingRequest[] backgroundTaskCount: number + /** + * Hub-derived "open tool work exists in the transcript tail" (work-scoped + * liveness). True when the hub's sweep found a tool call that started but + * never settled — the autonomous-round case where `thinking` is false and + * no background task is declared, yet the agent is demonstrably working. + * Optional because older hubs never send it. + */ + derivedToolWork?: boolean futureScheduledMessageCount: number /** Epoch ms of the soonest uninvoked future scheduled message, or null. */ nextScheduledAt: number | null @@ -306,6 +314,7 @@ export function toSessionSummary( pendingRequestKinds: computePendingRequestKinds(session.agentState), pendingRequests: computePendingRequests(session.agentState, session.updatedAt), backgroundTaskCount: session.backgroundTaskCount ?? 0, + derivedToolWork: session.derivedToolWork === true, futureScheduledMessageCount: 0, nextScheduledAt: null, attachedJob, diff --git a/web/src/components/SessionRowSummary.test.tsx b/web/src/components/SessionRowSummary.test.tsx index f8bc9a3a..9069c68a 100644 --- a/web/src/components/SessionRowSummary.test.tsx +++ b/web/src/components/SessionRowSummary.test.tsx @@ -275,6 +275,50 @@ describe('SessionRowSummary background status', () => { expect(container.querySelector('[data-testid="session-presence"]')).toHaveAttribute('data-presence', 'waiting') }) + it('shows a working spinner for hub-derived open tool work (autonomous rounds)', () => { + // thinking=false and no declared background tasks is exactly the + // autonomous-round shape the hub sweep covers: the transcript still + // holds an unsettled tool call, so the row must render working, not + // waiting. + const { container } = render( + + + + ) + + const badge = container.querySelector('[data-testid="session-presence"]') + expect(badge).toHaveAttribute('data-presence', 'working') + // The low-rate ticker drives the working pulse now; the static badge + // class is the visible contract (animate-pulse no longer exists). + expect(badge).toHaveClass('bg-[var(--app-badge-success-text)]') + expect(screen.getByTestId('session-activity')).toBeInTheDocument() + // Not the background-only dot: this is foreground-style work. + expect(screen.queryByTestId('session-background')).toBeNull() + + // Without the derived flag the same shape stays waiting. + cleanup() + const idle = render( + + + + ).container + expect(idle.querySelector('[data-testid="session-presence"]')).toHaveAttribute('data-presence', 'waiting') + expect(idle.querySelector('[data-testid="session-presence"]')).not.toHaveClass('animate-pulse') + expect(idle.querySelector('[data-testid="session-activity"]')).toBeNull() + }) + it('shows and clears the unread dot in standard session rows', () => { const session = makeSummary({ id: 'standard-unread', backgroundTaskCount: 0, contentRevision: 5 }) const view = render() diff --git a/web/src/components/SessionRowSummary.tsx b/web/src/components/SessionRowSummary.tsx index 4d8eb51e..67c99f30 100644 --- a/web/src/components/SessionRowSummary.tsx +++ b/web/src/components/SessionRowSummary.tsx @@ -189,9 +189,13 @@ export function SessionRowSummary(props: { // Presence represents foreground work and connection state on the agent // icon. Connected sessions with only background work are waiting from the // foreground's perspective; the title-side blue dot owns that state. + // Derived tool work (hub transcript sweep) and an attached job both + // represent work that outlives the `thinking` flag, so they render + // working too. + const derivedWork = s.derivedToolWork === true const isRunning = s.active && s.thinking const isBackgroundOnly = s.active && !s.thinking && (s.backgroundTaskCount ?? 0) > 0 - const presence: 'working' | 'waiting' | 'stopped' = isRunning || attachedJob + const presence: 'working' | 'waiting' | 'stopped' = isRunning || attachedJob || derivedWork ? 'working' : s.active ? 'waiting' @@ -210,8 +214,10 @@ export function SessionRowSummary(props: { // the spinner rather than hiding real work behind the request symbol. // Background-only work gets a static title dot so the spinner remains a // stable "foreground turn running" signal. An attached job keeps its own - // running spinner because it outlives the agent and is independently visible. - const hasForegroundWork = Boolean(attachedJob) || isRunning + // running spinner because it outlives the agent and is independently + // visible; hub-derived open tool work (autonomous rounds) spins for the + // same reason — the transcript proves the agent is mid-call. + const hasForegroundWork = Boolean(attachedJob) || derivedWork || isRunning // At-rest unread styling applies to background-only work too: its title dot // is static, unlike the foreground spinner that carries unread by color. const emphasizeUnread = isUnread && !hasForegroundWork diff --git a/web/src/hooks/useSSE.ts b/web/src/hooks/useSSE.ts index 8dd9d894..890f1b16 100644 --- a/web/src/hooks/useSSE.ts +++ b/web/src/hooks/useSSE.ts @@ -156,6 +156,7 @@ export function isRenderIrrelevantPatch(current: SessionSummary, next: SessionSu && current.updatedAt === next.updatedAt && current.lastUserMessageAt === next.lastUserMessageAt && current.backgroundTaskCount === next.backgroundTaskCount + && current.derivedToolWork === next.derivedToolWork && current.attachedJob?.key === next.attachedJob?.key && current.attachedJob?.label === next.attachedJob?.label && current.attachedJob?.status === next.attachedJob?.status @@ -553,6 +554,9 @@ export function useSSE(options: { backgroundTaskCount: Object.prototype.hasOwnProperty.call(patch, 'backgroundTaskCount') ? patch.backgroundTaskCount ?? 0 : current.backgroundTaskCount, + derivedToolWork: Object.prototype.hasOwnProperty.call(patch, 'derivedToolWork') + ? patch.derivedToolWork === true + : current.derivedToolWork === true, attachedJob: current.attachedJob ?? null, attachedJobUpdatedAt: current.attachedJobUpdatedAt ?? 0, model: Object.prototype.hasOwnProperty.call(patch, 'model') ? patch.model ?? null : current.model, diff --git a/web/src/lib/sessionPatch.ts b/web/src/lib/sessionPatch.ts index e0712a91..78c9ea92 100644 --- a/web/src/lib/sessionPatch.ts +++ b/web/src/lib/sessionPatch.ts @@ -88,6 +88,7 @@ export function applySessionDetailPatch(session: Session, patch: SessionPatch): if (patch.copilotAgentMode !== undefined) assign('copilotAgentMode', patch.copilotAgentMode) if (patch.backgroundTaskCount !== undefined) assign('backgroundTaskCount', patch.backgroundTaskCount) if (patch.backgroundTasks !== undefined) assign('backgroundTasks', patch.backgroundTasks) + if (patch.derivedToolWork !== undefined) assign('derivedToolWork', patch.derivedToolWork) // Version gates: dual SSE can deliver duplicates out of order. // Only mark changed when a strictly newer version lands — // otherwise keep previous object identity (no redundant render).