Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
1 change: 1 addition & 0 deletions src/main/grok/grok-hook-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export const GROK_EVENTS = [
{ eventName: 'SessionStart', definition: { hooks: [{ type: 'command', command: '' }] } },
{ eventName: 'UserPromptSubmit', definition: { hooks: [{ type: 'command', command: '' }] } },
{ eventName: 'Stop', definition: { hooks: [{ type: 'command', command: '' }] } },
{ eventName: 'StopCancelled', definition: { hooks: [{ type: 'command', command: '' }] } },
{ eventName: 'StopFailure', definition: { hooks: [{ type: 'command', command: '' }] } },
{ eventName: 'SessionEnd', definition: { hooks: [{ type: 'command', command: '' }] } },
{
Expand Down
4 changes: 3 additions & 1 deletion src/main/grok/hook-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,7 @@ describe('GrokHookService', () => {
'SessionEnd',
'SessionStart',
'Stop',
'StopCancelled',
'StopFailure',
'UserPromptSubmit'
].sort()
Expand All @@ -262,7 +263,8 @@ describe('GrokHookService', () => {
// Why: Grok matchers are real regexes; bare `*` does not match-all.
expect(config.hooks.PostToolUseFailure[0].matcher).toBe('.*')
expect(config.hooks.PostToolUse[0].matcher).toBe('.*')
// Why: StopFailure must not carry a tool matcher — lifecycle-only event.
// Why: cancellation/failure are lifecycle-only events and must not inherit a tool matcher.
expect(config.hooks.StopCancelled[0].matcher).toBeUndefined()
expect(config.hooks.StopFailure[0].matcher).toBeUndefined()
expect(config.hooks.Notification[0].matcher).toBeUndefined()
// Why: assert the shipped helper still matches what install wrote (regression
Expand Down
1 change: 1 addition & 0 deletions src/main/grok/windows-hook-launcher-chain.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ const GROK_EVENT_NAMES = [
'SessionStart',
'UserPromptSubmit',
'Stop',
'StopCancelled',
'StopFailure',
'SessionEnd',
'PreToolUse',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { describe, expect, it, vi } from 'vitest'
import { createAgentCompletionCoordinator } from './agent-completion-coordinator'
import { useAgentCompletionCoordinatorLifecycle } from './agent-completion-coordinator-test-harness'

describe('agent completion coordinator Grok announceability', () => {
useAgentCompletionCoordinatorLifecycle()

// Pins notification-controller.ts ordinary hook dispatch metadata; dropping the accepted snapshot or completionIdentity must redden.
it('dispatches an explicit accepted Stop with its immutable snapshot and dedupe identity', () => {
const dispatchCompletion = vi.fn()
const coordinator = createAgentCompletionCoordinator({
paneKey: 'tab-1:leaf-1',
getPtyId: () => 'pty-1',
getSettings: () => null,
inspectProcess: vi.fn(),
dispatchCompletion,
isLive: () => true
})
const acceptedStop = {
state: 'done' as const,
prompt: 'finish the request',
agentType: 'grok',
completionOutcome: 'succeeded' as const,
announceCompletion: true,
lastAssistantMessage: 'Final answer.',
stateStartedAt: 2_000
}

coordinator.observeHookStatus(acceptedStop)
coordinator.observeHookStatus({
state: 'working',
prompt: 'later work',
agentType: 'grok',
stateStartedAt: 3_000
})

expect(dispatchCompletion).toHaveBeenCalledTimes(1)
expect(dispatchCompletion).toHaveBeenCalledWith('grok', {
source: 'hook',
quietedHookDone: false,
agentStatus: acceptedStop,
completionIdentity: {
source: 'hook',
identity: 'done:grok:2000',
agentIdentity: 'grok'
}
})
})

// Pins hook-observer.ts suppressNotification dispatch and notification-controller.ts identity commit; returning before that commit must redden on remount.
it('records a silent Stop identity so the same observation cannot revive later', () => {
const dispatchCompletion = vi.fn()
const dispatchHookLifecycle = vi.fn()
const options = {
paneKey: 'tab-1:leaf-1',
statusLane: 'hook' as const,
getPtyId: () => 'pty-1',
getSettings: () => null,
inspectProcess: vi.fn(),
dispatchCompletion,
dispatchHookLifecycle,
isLive: () => true
}
const first = createAgentCompletionCoordinator(options)
first.observeHookStatus({
state: 'working',
prompt: 'start background work',
agentType: 'grok',
stateStartedAt: 1_000
})
first.observeHookStatus({
state: 'done',
prompt: 'start background work',
agentType: 'grok',
completionOutcome: 'succeeded',
announceCompletion: false,
stateStartedAt: 2_000
})

expect(dispatchCompletion).not.toHaveBeenCalled()
expect(dispatchHookLifecycle).toHaveBeenLastCalledWith(
expect.objectContaining({ state: 'done', announceCompletion: false })
)
first.dispose()

const remounted = createAgentCompletionCoordinator(options)
remounted.observeHookStatus({
state: 'done',
prompt: 'start background work',
agentType: 'grok',
completionOutcome: 'succeeded',
announceCompletion: true,
stateStartedAt: 2_000
})

expect(dispatchCompletion).not.toHaveBeenCalled()
})
})
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { ParsedAgentStatusPayload } from '../../../../shared/agent-status-types'
import type { GlobalSettings } from '../../../../shared/global-settings-types'
import type { RecognizedAgentProcess } from '../../../../shared/agent-process-recognition'
import type { LastCompletionIdentity } from './agent-completion-identity-store'
import type { RuntimeTerminalProcessInspection } from '@/runtime/runtime-terminal-inspection'

export type AgentCompletionStatusSnapshot = ParsedAgentStatusPayload & {
Expand All @@ -14,6 +15,7 @@ export type AgentCompletionDispatchMeta = {
quietedHookDone: boolean
terminalIdleConfirmed?: boolean
agentStatus?: AgentCompletionStatusSnapshot
completionIdentity?: LastCompletionIdentity
}

export type AgentAttentionDispatchMeta = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,16 @@ export function createAgentCompletionHookObserver({
state.lastCompletionIdentity = identity
? { source: 'hook', identity, agentIdentity: hookCompletionAgentIdentity(payload) }
: null
if (payload.announceCompletion === false) {
dispatchCompletion('hook', payload.agentType ?? options.paneKey, {
agentStatus: payload,
...(state.lastCompletionIdentity
? { completionIdentity: state.lastCompletionIdentity }
: {}),
suppressNotification: true
})
return
}
if (doneShouldUseQuietWindow(payload)) {
scheduleHookDoneCompletion(payload.agentType ?? options.paneKey, payload)
return
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/** Derivation of a completion's identity from a hook payload: the stable key that decides
* whether a `done` has already been announced. Pure — no coordinator state, which is why it
* lives outside the controller closure. */
import type { AgentCompletionStatusSnapshot } from './agent-completion-coordinator-types'

export function isFiniteTurnCompletedAt(value: number | undefined): value is number {
return typeof value === 'number' && Number.isFinite(value)
}

export function completionIdentityFor(
state: string,
agentType: string | undefined,
timestamp: number
): string {
return [state, agentType ?? '', String(Math.trunc(timestamp))].join(':')
}

export function hookCompletionIdentity(payload: AgentCompletionStatusSnapshot): string | null {
// Why: `stateStartedAt` is pinned while the reported state does not change. A Claude pane held at `working` by background inventory would otherwise give every turn in the run the same identity.
const timestamp = isFiniteTurnCompletedAt(payload.turnCompletedAt)
? payload.turnCompletedAt
: payload.stateStartedAt
if (typeof timestamp !== 'number' || !Number.isFinite(timestamp)) {
return null
}
return completionIdentityFor(payload.state, payload.agentType, timestamp)
}

export function hookCompletionAgentIdentity(payload: AgentCompletionStatusSnapshot): string | null {
return payload.agentType?.trim().toLowerCase() || null
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type {
AgentCompletionCoordinatorOptions,
AgentCompletionDispatchMeta,
AgentCompletionStatusSnapshot
} from './agent-completion-coordinator-types'
import type { RecognizedAgentProcess } from '../../../../shared/agent-process-recognition'
Expand All @@ -8,6 +9,11 @@ import type {
LastCompletionIdentity
} from './agent-completion-identity-store'
import { isPiCompatibleAgentType } from '../../../../shared/pi-agent-kind'
import {
completionIdentityFor,
hookCompletionAgentIdentity,
hookCompletionIdentity
} from './agent-completion-identity-derivation'

type CompletionSource = 'hook' | 'title' | 'process-exit'

Expand Down Expand Up @@ -50,10 +56,6 @@ export function createAgentCompletionNotificationController({
processState,
identityScope
}: CompletionControllerOptions) {
function isFiniteTurnCompletedAt(value: number | undefined): value is number {
return typeof value === 'number' && Number.isFinite(value)
}

function completionToken(source: CompletionSource): string {
if (state.workingStatusObserved) {
return `turn:${state.currentTurn}`
Expand All @@ -64,30 +66,10 @@ export function createAgentCompletionNotificationController({
return `${source}:${state.currentTurn}:${processState.processSession}`
}

function completionIdentityFor(
state: string,
agentType: string | undefined,
timestamp: number
): string {
return [state, agentType ?? '', String(Math.trunc(timestamp))].join(':')
}

function hookCompletionIdentity(payload: AgentCompletionStatusSnapshot): string | null {
// Why: `stateStartedAt` is pinned while the reported state does not change. A Claude pane held at `working` by background inventory would otherwise give every turn in the run the same identity.
const timestamp = isFiniteTurnCompletedAt(payload.turnCompletedAt)
? payload.turnCompletedAt
: payload.stateStartedAt
if (typeof timestamp !== 'number' || !Number.isFinite(timestamp)) {
return null
}
return completionIdentityFor(payload.state, payload.agentType, timestamp)
}

function hookCompletionAgentIdentity(payload: AgentCompletionStatusSnapshot): string | null {
return payload.agentType?.trim().toLowerCase() || null
}

function doneShouldUseQuietWindow(payload: AgentCompletionStatusSnapshot): boolean {
if (payload.announceCompletion !== undefined) {
return false
}
// Why: Pi/OMP emit milestone 'done' while still working, so route it through the quiet window so later work can cancel it.
return (
state.workingStatusObserved || isPiCompatibleAgentType(hookCompletionAgentIdentity(payload))
Expand Down Expand Up @@ -153,6 +135,8 @@ export function createAgentCompletionNotificationController({
completionIdentity?: LastCompletionIdentity | null
/** Announce only. The pane is still genuinely `working` (Claude background inventory), so the synthetic `done` must not run pane lifecycle. */
notifyWithoutLifecycle?: boolean
/** Commit lifecycle and dedupe identity without producing user attention. */
suppressNotification?: boolean
} = {}
): boolean {
if (source !== 'hook' && state.pendingHookDoneTimer !== null) {
Expand Down Expand Up @@ -199,21 +183,32 @@ export function createAgentCompletionNotificationController({
) {
options.dispatchHookLifecycle?.(optionsOverride.agentStatus)
}
if (optionsOverride.quietedHookDone === true || source === 'process-exit') {
// Why: confirmed process death is independent completion evidence; keep its provenance so stale hook rows can't veto it later.
options.dispatchCompletion(title, {
if (optionsOverride.suppressNotification === true) {
return true
}
if (
optionsOverride.quietedHookDone === true ||
source === 'process-exit' ||
(source === 'hook' &&
optionsOverride.agentStatus !== undefined &&
(optionsOverride.notifyWithoutLifecycle === true ||
optionsOverride.agentStatus.announceCompletion !== undefined))
) {
// Why: a hook's accepted snapshot and identity must survive later status mutations before notification delivery.
const dispatchMeta: AgentCompletionDispatchMeta = {
source,
quietedHookDone: optionsOverride.quietedHookDone === true,
...(optionsOverride.terminalIdleConfirmed === true ? { terminalIdleConfirmed: true } : {}),
...(optionsOverride.agentStatus ? { agentStatus: optionsOverride.agentStatus } : {})
})
} else if (optionsOverride.notifyWithoutLifecycle === true && optionsOverride.agentStatus) {
// Why: the pane is still `working`; the synthetic done must carry its own snapshot or the notification would read the pinned working row.
options.dispatchCompletion(title, {
source,
quietedHookDone: false,
agentStatus: optionsOverride.agentStatus
})
}
if (
source === 'hook' &&
optionsOverride.agentStatus?.announceCompletion !== undefined &&
optionsOverride.completionIdentity
) {
dispatchMeta.completionIdentity = optionsOverride.completionIdentity
}
options.dispatchCompletion(title, dispatchMeta)
} else {
options.dispatchCompletion(title)
}
Expand Down
Loading
Loading