Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,7 @@ describe('remote hook service installers', () => {
'SessionStart',
'UserPromptSubmit',
'Stop',
'StopCancelled',
'StopFailure',
'SessionEnd',
'PreToolUse',
Expand Down
185 changes: 185 additions & 0 deletions src/main/agent-hooks/server-grok-background-status.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { AgentHookServer, _internals } from './server'
import { buildBody, PANE } from './server.test-fixtures'

const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({
getCohortAtEmitMock: vi.fn(),
trackMock: vi.fn()
}))

vi.mock('../telemetry/client', () => ({ track: trackMock }))
vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock }))

beforeEach(() => {
_internals.resetCachesForTests()
trackMock.mockReset()
getCohortAtEmitMock.mockReset()
getCohortAtEmitMock.mockReturnValue({ nth_repo_added: 2 })
})

afterEach(() => vi.restoreAllMocks())

async function postGrokHook(
server: AgentHookServer,
payload: Record<string, unknown>
): Promise<void> {
const env = server.buildPtyEnv()
const response = await fetch(`http://127.0.0.1:${env.ORCA_AGENT_HOOK_PORT}/hook/grok`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Orca-Agent-Hook-Token': env.ORCA_AGENT_HOOK_TOKEN
},
body: JSON.stringify(buildBody(payload))
})
expect(response.status).toBe(204)
}

describe('Grok background status ownership', () => {
it('keeps the host-owned row working while finite background work remains', async () => {
const server = new AgentHookServer()
await server.start({ env: 'production' })
try {
await postGrokHook(server, {
hookEventName: 'user_prompt_submit',
sessionId: 'session-1',
promptId: 'prompt-1',
prompt: 'run a background task'
})
await postGrokHook(server, {
hookEventName: 'stop',
sessionId: 'session-1',
promptId: 'prompt-1',
reason: 'end_turn',
stopHookActive: false,
backgroundTasks: [{ id: 'task-1', type: 'shell', status: 'running' }]
})

expect(server.getStatusSnapshot()).toEqual([
expect.objectContaining({
paneKey: PANE,
state: 'working',
workingMode: 'monitoring',
agentType: 'grok'
})
])

await postGrokHook(server, {
hookEventName: 'user_prompt_submit',
sessionId: 'session-1',
promptId: 'task-completed-task-1',
prompt: 'the background task completed'
})
await postGrokHook(server, {
hookEventName: 'stop',
sessionId: 'session-1',
promptId: 'task-completed-task-1',
reason: 'end_turn',
stopHookActive: false,
backgroundTasks: []
})

expect(server.getStatusSnapshot()).toEqual([
expect.objectContaining({ paneKey: PANE, state: 'done', agentType: 'grok' })
])
} finally {
server.stop()
}
})

it('rejects a delayed remote cancellation from the turn replaced by a newer prompt', () => {
const server = new AgentHookServer()
server.ingestRemote(
{
paneKey: PANE,
tabId: 'tab-1',
worktreeId: 'wt-1',
source: 'grok',
hookEventName: 'UserPromptSubmit',
providerPromptId: 'prompt-new',
providerSession: { key: 'session_id', id: 'session-1' },
payload: { state: 'working', prompt: 'new turn', agentType: 'grok' }
},
'conn-1'
)
server.ingestRemote(
{
paneKey: PANE,
tabId: 'tab-1',
worktreeId: 'wt-1',
source: 'grok',
hookEventName: 'StopCancelled',
providerPromptId: 'prompt-old',
providerSession: { key: 'session_id', id: 'session-1' },
payload: {
state: 'done',
prompt: 'old turn',
agentType: 'grok',
interrupted: true
}
},
'conn-1'
)

expect(server._getStateForTests().lastStatusByPaneKey.get(PANE)).toMatchObject({
providerPromptId: 'prompt-new',
payload: { state: 'working', prompt: 'new turn' }
})
})

it('retains the Grok turn fence across status hydration', async () => {
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-grok-status-'))
const firstServer = new AgentHookServer()
const restoredServer = new AgentHookServer()
try {
await firstServer.start({ env: 'production', userDataPath })
firstServer.ingestRemote(
{
paneKey: PANE,
tabId: 'tab-1',
worktreeId: 'wt-1',
source: 'grok',
hookEventName: 'UserPromptSubmit',
providerPromptId: 'prompt-new',
providerSession: { key: 'session_id', id: 'session-1' },
payload: { state: 'working', prompt: 'new turn', agentType: 'grok' }
},
'conn-1'
)
firstServer.flushStatusPersistSync()
firstServer.stop()

await restoredServer.start({ env: 'production', userDataPath })
restoredServer.ingestRemote(
{
paneKey: PANE,
tabId: 'tab-1',
worktreeId: 'wt-1',
source: 'grok',
hookEventName: 'StopCancelled',
providerPromptId: 'prompt-old',
providerSession: { key: 'session_id', id: 'session-1' },
payload: {
state: 'done',
prompt: 'old turn',
agentType: 'grok',
interrupted: true
}
},
'conn-1'
)

expect(restoredServer._getStateForTests().lastStatusByPaneKey.get(PANE)).toMatchObject({
providerPromptId: 'prompt-new',
payload: { state: 'working', prompt: 'new turn' }
})
} finally {
firstServer.stop()
restoredServer.stop()
rmSync(userDataPath, { recursive: true, force: true })
}
})
})
25 changes: 25 additions & 0 deletions src/main/agent-hooks/server/server-grok-status-rules.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event'
import { isGrokEvent } from '../../../shared/agent-hook-listener/provider-event-names'
import type { EnrichedAgentHookEventPayload } from './server-types'

export function isStaleGrokTurnEnd(
previous: EnrichedAgentHookEventPayload | undefined,
incoming: AgentHookEventPayload
): boolean {
if (
previous?.source !== 'grok' ||
previous.payload.state === 'done' ||
incoming.source !== 'grok' ||
!isGrokEvent(incoming.hookEventName, 'stop', 'stop_failure', 'stop_cancelled') ||
!previous.providerPromptId ||
!incoming.providerPromptId
) {
return false
}
const differentSession = Boolean(
previous.providerSession?.id &&
incoming.providerSession?.id &&
previous.providerSession.id !== incoming.providerSession.id
)
return differentSession || previous.providerPromptId !== incoming.providerPromptId
}
7 changes: 6 additions & 1 deletion src/main/agent-hooks/server/server-ingest-remote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { isAgentHookSource, restoreShedStatusFields } from '../../../shared/agen
import {
MAX_PANE_KEY_LEN,
normalizeClaudePromptId,
normalizeGrokPromptId,
warnOnHookEnvOrVersionMismatch
} from '../../../shared/agent-hook-listener/listener-limits'
import {
Expand Down Expand Up @@ -104,7 +105,11 @@ export abstract class AgentHookServerIngestRemote extends AgentHookServerIngestS
: undefined
const source = isAgentHookSource(envelope.source) ? envelope.source : undefined
const providerPromptId =
source === 'claude' ? normalizeClaudePromptId(envelope.providerPromptId) : undefined
source === 'claude'
? normalizeClaudePromptId(envelope.providerPromptId)
: source === 'grok'
? normalizeGrokPromptId(envelope.providerPromptId)
: undefined
const compactTrigger =
source === 'claude' &&
(envelope.compactTrigger === 'manual' || envelope.compactTrigger === 'auto')
Expand Down
11 changes: 9 additions & 2 deletions src/main/agent-hooks/server/server-persistence-validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ import {
type ParsedAgentStatusPayload
} from '../../../shared/agent-status-types'
import { isAgentHookSource } from '../../../shared/agent-hook-relay'
import { normalizeClaudePromptId } from '../../../shared/agent-hook-listener/listener-limits'
import {
normalizeClaudePromptId,
normalizeGrokPromptId
} from '../../../shared/agent-hook-listener/listener-limits'
import { parsePaneKey } from '../../../shared/stable-pane-id'
import type { AgentHookAuthorityEvidence, EnrichedAgentHookEventPayload } from './server-types'
import { isValidPaneKey, isValidPiProviderSessionOnly } from './server-status-identity'
Expand Down Expand Up @@ -100,7 +103,11 @@ export function sanitizeHydratedEntry(
}
const source = isAgentHookSource(record.source) ? record.source : undefined
const providerPromptId =
source === 'claude' ? normalizeClaudePromptId(record.providerPromptId) : undefined
source === 'claude'
? normalizeClaudePromptId(record.providerPromptId)
: source === 'grok'
? normalizeGrokPromptId(record.providerPromptId)
: undefined
const compactTrigger =
source === 'claude' && (record.compactTrigger === 'manual' || record.compactTrigger === 'auto')
? record.compactTrigger
Expand Down
6 changes: 6 additions & 0 deletions src/main/agent-hooks/server/server-status-update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
invalidateClaudeChildOnlyBoundary,
shouldKeepClaudePermissionVisible
} from './server-claude-status-rules'
import { isStaleGrokTurnEnd } from './server-grok-status-rules'
import { isToolProgressWorkingAfterInterrupt } from './server-status-identity'
import { AgentHookServerStatusApplication } from './server-status-application'

Expand All @@ -42,6 +43,11 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusA
: undefined)
const terminalOwnedPayload =
terminalHandle === payload.terminalHandle ? payload : { ...payload, terminalHandle }
if (previous && isStaleGrokTurnEnd(previous, terminalOwnedPayload)) {
// Why: Grok turn-end hooks may arrive after the next prompt, including across relay restart.
this.commitStatusRowMutation(rowBefore, previous)
return previous
}
const connectionClearWatermark = terminalOwnedPayload.connectionId
? this.connectionTimestampWatermarkById.get(terminalOwnedPayload.connectionId)
: undefined
Expand Down
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
Loading