mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 02:47:34 +00:00
Make chat wait check the chat's work state instead of reading its history every second (#41129)
* fix(cli): chat wait checks the chat's work state instead of reading its history every second
`orca chat wait` and `orca chat send --wait` polled `agentSession.history` once a second only to
learn whether the chat was still working. Each poll made the host build a transcript page, scan
every retained item twice for the running turn, and send the newest reply's full text, all
ignored by the waiter.
The host now answers `agentSession.workState` with just the facts a wait decides from (working,
a waiting question or approval, queued ids, the next queued send, the fence), and the journal's
running turn comes from its existing per-row turn index instead of a scan. The CLI polls that
read and falls back to history pages on hosts without it. The final transcript read is unchanged.
* test(cli): type the chat wait host test without assertions
* docs(cli): say what a work-state check skips, not that it does no history work
* test(cli): pin the chat wait's exact final reply and its single history read
* docs(cli): name the scan a work-state check skips
* ci: typecheck the chat wait host test with the cross-process test project
(cherry picked from commit 9a10464bec)
This commit is contained in:
@@ -39,7 +39,8 @@
|
||||
],
|
||||
"exclude": [
|
||||
"../src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts",
|
||||
"../src/main/runtime/rpc/methods/orchestration/orchestration-check-ambiguous-caller.test.ts"
|
||||
"../src/main/runtime/rpc/methods/orchestration/orchestration-check-ambiguous-caller.test.ts",
|
||||
"../src/main/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts"
|
||||
],
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
"../src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab-main-surface.test.ts",
|
||||
"../src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts",
|
||||
"../src/main/runtime/rpc/methods/orchestration/orchestration-check-ambiguous-caller.test.ts",
|
||||
"../src/main/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts",
|
||||
"../src/renderer/src/components/task-page/linear/task-page-linear-detail-query.test.tsx",
|
||||
"../src/renderer/src/runtime/observed-provider-accounts.test.tsx",
|
||||
"../src/renderer/src/components/status-bar/ClaudeSwitcherMenu.observation.test.tsx",
|
||||
|
||||
@@ -20,7 +20,8 @@ const contracts = [
|
||||
'config/scripts/static-analysis/oxlint-contracts/app-store-performance-plugin.test.mjs',
|
||||
'config/scripts/static-analysis/oxlint-contracts/quadratic-buffer-concat-plugin.test.mjs',
|
||||
'src/main/claude-usage/scanner-incremental-append.test.ts',
|
||||
'src/main/claude-usage/store-checkpoint-persistence.test.ts'
|
||||
'src/main/claude-usage/store-checkpoint-persistence.test.ts',
|
||||
'src/main/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts'
|
||||
]
|
||||
for (const contract of contracts) {
|
||||
if (!existsSync(resolve(contract))) {
|
||||
|
||||
+49
-11
@@ -2,6 +2,7 @@ import type {
|
||||
AgentSessionHistoryPage,
|
||||
AgentSessionHistoryResult
|
||||
} from '../shared/agent-session/agent-session-wire'
|
||||
import type { AgentSessionWorkState } from '../shared/agent-session/agent-session-work-state'
|
||||
import { AGENT_SESSION_HISTORY_MAX_LIMIT } from '../shared/agent-session/agent-session-wire'
|
||||
import {
|
||||
AGENT_SESSION_UNATTACHED_REFUSAL_CODE,
|
||||
@@ -56,8 +57,45 @@ export async function readTranscript(
|
||||
return { ...response, result: { session, entries, cursor: page.window.newest, truncated } }
|
||||
}
|
||||
|
||||
export function requireWorkingFlag(page: AgentSessionHistoryPage): void {
|
||||
if (page.working === undefined) {
|
||||
/** Older hosts' history pages may omit `working`. */
|
||||
export type ChatWorkState = Omit<AgentSessionWorkState, 'working'> & { working?: boolean }
|
||||
|
||||
/** One command's reads of the facts a send or wait decides from. Hosts without
|
||||
* `agentSession.workState` answer from a history page for the rest of the command. */
|
||||
export function chatWorkStateReader(
|
||||
client: RuntimeClient,
|
||||
session: string
|
||||
): () => Promise<ChatWorkState> {
|
||||
let historyOnly = false
|
||||
return async () => {
|
||||
if (!historyOnly) {
|
||||
try {
|
||||
const response = await client.call<AgentSessionWorkState>('agentSession.workState', {
|
||||
sessionId: session
|
||||
})
|
||||
return response.result
|
||||
} catch (error) {
|
||||
if (!(error instanceof RuntimeClientError && error.code === 'method_not_found')) {
|
||||
throw explainChatRefusal(error, session, 'read')
|
||||
}
|
||||
historyOnly = true
|
||||
}
|
||||
}
|
||||
const { page } = (await readHistory(client, session, 1)).result
|
||||
return {
|
||||
...(page.working !== undefined ? { working: page.working } : {}),
|
||||
actionablePrompt: (page.actionablePromptIds?.length ?? 0) > 0,
|
||||
...(page.queuedMessages !== undefined
|
||||
? { queuedMessageIds: (page.queuedMessages ?? []).map((m) => m.messageId) }
|
||||
: {}),
|
||||
nextQueuedMessageId: page.nextQueuedMessageId ?? null,
|
||||
...(page.fence !== undefined ? { fence: page.fence } : {})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function requireWorkingFlag(state: { working?: boolean }): void {
|
||||
if (state.working === undefined) {
|
||||
throw new RuntimeClientError(
|
||||
'incompatible_runtime',
|
||||
'This Orca host does not report when a chat is working, so it cannot wait. Update Orca on the host.'
|
||||
@@ -67,26 +105,26 @@ export function requireWorkingFlag(page: AgentSessionHistoryPage): void {
|
||||
|
||||
// Settled means no running turn or unanswered send, or a question/approval waiting for the user.
|
||||
export async function waitForChat(
|
||||
client: RuntimeClient,
|
||||
session: string,
|
||||
readWorkState: () => Promise<ChatWorkState>,
|
||||
timeoutMs: number | undefined,
|
||||
queuedMessageId?: string
|
||||
): Promise<ChatSettled> {
|
||||
const deadline = timeoutMs === undefined ? Infinity : Date.now() + timeoutMs
|
||||
for (;;) {
|
||||
const { page } = (await readHistory(client, session, 1)).result
|
||||
requireWorkingFlag(page)
|
||||
if ((page.actionablePromptIds?.length ?? 0) > 0) {
|
||||
const state = await readWorkState()
|
||||
requireWorkingFlag(state)
|
||||
if (state.actionablePrompt) {
|
||||
return 'blocked'
|
||||
}
|
||||
// Between turns the host names its next automatic send while working is briefly false.
|
||||
const sendsNext = structuredAgentSessionQueueSendsNext(
|
||||
page.nextQueuedMessageId,
|
||||
page.working === true
|
||||
state.nextQueuedMessageId,
|
||||
state.working === true
|
||||
)
|
||||
if (!page.working && !sendsNext) {
|
||||
if (!state.working && !sendsNext) {
|
||||
// Still queued with nothing running or about to send: stopped, failed or held across a reopen.
|
||||
const held = page.queuedMessages?.some((m) => m.messageId === queuedMessageId) === true
|
||||
const held =
|
||||
queuedMessageId !== undefined && state.queuedMessageIds?.includes(queuedMessageId) === true
|
||||
return held ? 'held' : 'done'
|
||||
}
|
||||
if (Date.now() >= deadline) {
|
||||
|
||||
@@ -35,6 +35,10 @@ function historyPage(
|
||||
})
|
||||
}
|
||||
|
||||
function workState(fields: Record<string, unknown>) {
|
||||
return ok({ working: false, actionablePrompt: false, ...fields })
|
||||
}
|
||||
|
||||
function item(body: unknown) {
|
||||
return { itemId: 'i', revision: 1, sequence: 1, observedAt: 1, body }
|
||||
}
|
||||
@@ -90,7 +94,7 @@ afterEach(() => {
|
||||
describe('chat send', () => {
|
||||
it('sends a host-valid message fenced to the chat it read, queued while the agent works', async () => {
|
||||
const client = fakeClient([
|
||||
historyPage([], 7),
|
||||
workState({ fence: 7 }),
|
||||
ok({
|
||||
ok: true,
|
||||
replayed: false,
|
||||
@@ -122,7 +126,7 @@ describe('chat send', () => {
|
||||
|
||||
it('reports a host refusal as an error instead of a sent message', async () => {
|
||||
const client = fakeClient([
|
||||
historyPage([], 2),
|
||||
workState({ fence: 2 }),
|
||||
ok({
|
||||
ok: false,
|
||||
refusal: { code: 'agent_session_fence_mismatch', message: 'The chat restarted.' }
|
||||
@@ -136,7 +140,7 @@ describe('chat send', () => {
|
||||
it('with --wait, waits for its queued message to run and returns that turn', async () => {
|
||||
vi.useFakeTimers()
|
||||
const client = fakeClient([
|
||||
historyPage([], 7, { working: true }),
|
||||
workState({ fence: 7, working: true }),
|
||||
ok({
|
||||
ok: true,
|
||||
replayed: false,
|
||||
@@ -148,13 +152,9 @@ describe('chat send', () => {
|
||||
}
|
||||
}),
|
||||
// The earlier turn ended, but the queued message has not been handed to the agent yet.
|
||||
historyPage([], 7, {
|
||||
working: false,
|
||||
queuedMessages: [{ messageId: 'q-1' }],
|
||||
nextQueuedMessageId: 'q-1'
|
||||
}),
|
||||
historyPage([], 7, { working: true, queuedMessages: [] }),
|
||||
historyPage([], 7, { working: false, queuedMessages: [], actionablePromptIds: [] }),
|
||||
workState({ fence: 7, queuedMessageIds: ['q-1'], nextQueuedMessageId: 'q-1' }),
|
||||
workState({ fence: 7, working: true, queuedMessageIds: [] }),
|
||||
workState({ fence: 7, queuedMessageIds: [] }),
|
||||
historyPage([
|
||||
item({ kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Earlier' }] }),
|
||||
item({ kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'Old reply' }] }),
|
||||
|
||||
@@ -17,9 +17,9 @@ import { AGENT_STATUS_STATES } from '../../shared/agent-status/contracts/agent-s
|
||||
import { readInjectedAgentSessionId } from '../../shared/agent-session/lifecycle/agent-session-caller-env'
|
||||
import {
|
||||
DEFAULT_READ_LIMIT,
|
||||
chatWorkStateReader,
|
||||
explainChatRefusal,
|
||||
formatSettled,
|
||||
readHistory,
|
||||
readSettledTurn,
|
||||
readTranscript,
|
||||
requireWorkingFlag,
|
||||
@@ -122,7 +122,7 @@ export const CHAT_HANDLERS: Record<string, CommandHandler> = {
|
||||
'chat wait': async ({ flags, client, json }) => {
|
||||
const session = readSession(flags, client)
|
||||
const timeoutMs = getOptionalPositiveIntegerFlag(flags, 'timeout-ms')
|
||||
const settled = await waitForChat(client, session, timeoutMs)
|
||||
const settled = await waitForChat(chatWorkStateReader(client, session), timeoutMs)
|
||||
printResult(await readSettledTurn(client, session, settled), json, formatSettled)
|
||||
},
|
||||
'chat send': async ({ flags, client, cwd, json }) => {
|
||||
@@ -146,11 +146,12 @@ export const CHAT_HANDLERS: Record<string, CommandHandler> = {
|
||||
AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY
|
||||
) === true
|
||||
// The send is fenced to the session's current runtime, so a restarted chat refuses it.
|
||||
const { page } = (await readHistory(client, session, 1)).result
|
||||
const readWorkState = chatWorkStateReader(client, session)
|
||||
const state = await readWorkState()
|
||||
if (wait) {
|
||||
requireWorkingFlag(page)
|
||||
requireWorkingFlag(state)
|
||||
}
|
||||
const { fence } = page
|
||||
const { fence } = state
|
||||
if (fence === undefined) {
|
||||
throw new RuntimeClientError(
|
||||
'agent_session_not_running',
|
||||
@@ -188,7 +189,7 @@ export const CHAT_HANDLERS: Record<string, CommandHandler> = {
|
||||
return
|
||||
}
|
||||
const queuedId = 'queued' in value ? value.queued.messageId : undefined
|
||||
const settled = await waitForChat(client, session, timeoutMs, queuedId)
|
||||
const settled = await waitForChat(readWorkState, timeoutMs, queuedId)
|
||||
const turn = await readSettledTurn(client, session, settled)
|
||||
printResult({ ...turn, result: { ...sent, ...turn.result } }, json, formatSettled)
|
||||
}
|
||||
|
||||
@@ -50,6 +50,13 @@ export class JournalNewestTurn {
|
||||
return this.root?.latest.item ?? null
|
||||
}
|
||||
|
||||
/** The newest turn or clear, when it is a turn still running. */
|
||||
running(): { item: AgentJournalRenderItem; turnId: string } | null {
|
||||
const item = this.read()
|
||||
const turn = item ? readAgentJournalTurn(item.body) : null
|
||||
return item && turn?.state === 'running' ? { item, turnId: turn.turnId } : null
|
||||
}
|
||||
|
||||
/** Releasing Resume marks must be written after this position. */
|
||||
failure(): number {
|
||||
const winner = this.root?.winner
|
||||
|
||||
@@ -15,7 +15,6 @@ import type {
|
||||
import { agentJournalItemKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import type { AgentSessionContextUsage } from '../../../shared/agent-session/agent-session-context-usage'
|
||||
import { latestStructuredAgentContextFacts } from '../../../shared/agent-session/structured-agent-session-context-usage'
|
||||
import { runningStructuredAgentSessionTurnItemBySequence } from '../../../shared/agent-session/view/structured-agent-session-live-turn'
|
||||
import { readAgentJournalTurn } from '../../../shared/agent-session/lifecycle/agent-session-turn-record'
|
||||
import { journalWroteBeforeOpen } from './replay/journal-cursor'
|
||||
import type { JournalHostDatabase } from './database/journal-host-database'
|
||||
@@ -230,9 +229,8 @@ export class AgentSessionJournal {
|
||||
hasRecordedItem = (itemId: string): boolean =>
|
||||
this.state.items.has(itemId) || this.state.tombstones.has(itemId)
|
||||
|
||||
/** Read the journal's running turn without allocating a snapshot; host projection decides current work. */
|
||||
runningTurn = (): { item: journal.AgentJournalRenderItem; turnId: string } | null =>
|
||||
runningStructuredAgentSessionTurnItemBySequence(this.state.items.values())
|
||||
/** Read from the per-row turn index so hot readers never rescan history; host projection decides current work. */
|
||||
runningTurn = () => journalInputOrder(this.state).newestTurn.running()
|
||||
|
||||
newestTurn = (): journal.AgentJournalTurnLifecycle | null =>
|
||||
readAgentJournalTurn(journalInputOrder(this.state).newestTurn.read()?.body)
|
||||
|
||||
@@ -62,7 +62,8 @@ export class StructuredAgentSessionHost {
|
||||
private readonly lifetime: HostTypes.StructuredAgentSessionConversationLifetime
|
||||
private readonly conversationDelivery: conversation.StructuredAgentSessionConversationDelivery
|
||||
private readonly eventRecovery: StructuredAgentSessionEventRecovery
|
||||
private readonly backgroundTasks: BackgroundTasks
|
||||
/** History and work-state reads, which open a chat at rest without starting its agent. */
|
||||
readonly backgroundTasks: BackgroundTasks
|
||||
readonly restartResume: StructuredAgentSessionRestartResume
|
||||
|
||||
readonly usageLimitContinue: ReturnType<typeof usageLimit.start>
|
||||
|
||||
+28
@@ -6,6 +6,9 @@ import type {
|
||||
AgentSessionHistoryRequest,
|
||||
AgentSessionHistoryResult
|
||||
} from '../../../../../shared/agent-session/agent-session-wire'
|
||||
import type { AgentSessionWorkState } from '../../../../../shared/agent-session/agent-session-work-state'
|
||||
import { AgentSessionRefusalError } from '../../../../../shared/agent-session/failures/agent-session-wire-refusals'
|
||||
import { AGENT_SESSION_NOT_ATTACHED } from '../../operations/structured-agent-session-mutation-refusals'
|
||||
import type { AgentSessionBackgroundTaskState } from '../../../../../shared/agent-session/agent-session-background-task-wire'
|
||||
import type { AgentChildWorkView } from '../../../../../shared/agent-status/child-work/agent-status-child-work-view'
|
||||
import { structuredChildWorkLegacyTasks } from '../../../../../shared/agent-session/structured-agent-session-child-work-legacy'
|
||||
@@ -85,6 +88,31 @@ export class StructuredAgentSessionBackgroundTaskChannel {
|
||||
}
|
||||
}
|
||||
|
||||
/** What a waiter decides from, from the sources history pages state, without building a page. */
|
||||
async workState(sessionId: string): Promise<AgentSessionWorkState> {
|
||||
await this.conversation(sessionId)
|
||||
const work = hostStructuredAgentSessionCurrentWork(
|
||||
{ store: this.deps.store, sessions: this.sessions },
|
||||
sessionId
|
||||
)
|
||||
if (!work) {
|
||||
throw new AgentSessionRefusalError(AGENT_SESSION_NOT_ATTACHED)
|
||||
}
|
||||
const queue = this.subscribers.readQueuePublication(sessionId)
|
||||
const fence = this.deps.store.getConversation(sessionId)?.currentFence
|
||||
return {
|
||||
working: work.working(),
|
||||
actionablePrompt: work.hasActionablePrompt(),
|
||||
...(queue !== undefined
|
||||
? {
|
||||
queuedMessageIds: (queue.queuedMessages ?? []).map((card) => card.messageId),
|
||||
nextQueuedMessageId: queue.nextQueuedMessageId
|
||||
}
|
||||
: {}),
|
||||
...(fence !== undefined ? { fence } : {})
|
||||
}
|
||||
}
|
||||
|
||||
async currentRequests(request: AgentSessionCurrentRequestsRead) {
|
||||
await this.conversation(request.sessionId)
|
||||
const work = hostStructuredAgentSessionCurrentWork(
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
// `orca chat send --wait` through the real host: each check while the turn runs reads only work
|
||||
// state, never a history page, a running-turn scan or the turn's text.
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { RpcResponse } from '../rpc/core'
|
||||
import type * as HistoryPage from '../../native-chat/agent-session-wire/publication/history/agent-session-history-page'
|
||||
import type * as LiveTurn from '../../../shared/agent-session/view/structured-agent-session-live-turn'
|
||||
import { AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY } from '../../../shared/agent-session/agent-session-runtime-capabilities'
|
||||
import { RuntimeClient, RuntimeClientError } from '../../../cli/runtime-client'
|
||||
import { CHAT_HANDLERS } from '../../../cli/handlers/chat'
|
||||
import {
|
||||
openStructuredCodexRpcHarness,
|
||||
SESSION,
|
||||
THREAD,
|
||||
TURN,
|
||||
type StructuredCodexRpcHarness
|
||||
} from '../rpc/methods/structured-sessions/structured-codex-session-rpc-test-harness'
|
||||
|
||||
const work = vi.hoisted(() => ({ historyPages: 0, turnScans: 0 }))
|
||||
|
||||
vi.mock(
|
||||
'../../native-chat/agent-session-wire/publication/history/agent-session-history-page',
|
||||
async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof HistoryPage>()
|
||||
return {
|
||||
...actual,
|
||||
readAgentSessionHistory: (...args: Parameters<typeof actual.readAgentSessionHistory>) => {
|
||||
work.historyPages += 1
|
||||
return actual.readAgentSessionHistory(...args)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
vi.mock(
|
||||
'../../../shared/agent-session/view/structured-agent-session-live-turn',
|
||||
async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof LiveTurn>()
|
||||
return {
|
||||
...actual,
|
||||
runningStructuredAgentSessionTurnItemBySequence: (
|
||||
...args: Parameters<typeof actual.runningStructuredAgentSessionTurnItemBySequence>
|
||||
) => {
|
||||
work.turnScans += 1
|
||||
return actual.runningStructuredAgentSessionTurnItemBySequence(...args)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
const NEWEST_MARKER = 'newest-row-marker'
|
||||
|
||||
let harness: StructuredCodexRpcHarness | undefined
|
||||
|
||||
afterEach(async () => {
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
await harness?.dispose()
|
||||
harness = undefined
|
||||
})
|
||||
|
||||
/** The CLI's own client, answered by the host's dispatcher in the local CLI's caller context. */
|
||||
function cliClient(open: StructuredCodexRpcHarness) {
|
||||
const client = new RuntimeClient('/tmp/orca-chat-wait-test', 60_000, null, null)
|
||||
const replies: { method: string; json: string }[] = []
|
||||
vi.spyOn(client, 'getCliStatus').mockResolvedValue({
|
||||
id: 'status',
|
||||
ok: true,
|
||||
result: {
|
||||
app: { running: true, pid: 1 },
|
||||
runtime: {
|
||||
state: 'ready',
|
||||
reachable: true,
|
||||
runtimeId: 'runtime-1',
|
||||
capabilities: [AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY]
|
||||
},
|
||||
graph: { state: 'ready' }
|
||||
},
|
||||
_meta: { runtimeId: 'runtime-1' }
|
||||
})
|
||||
vi.spyOn(client, 'call').mockImplementation(async (method: string, params?: unknown) => {
|
||||
const response: RpcResponse = await open.call(method, params)
|
||||
replies.push({ method, json: JSON.stringify(response) })
|
||||
if (!response.ok) {
|
||||
throw new RuntimeClientError(response.error.code, response.error.message)
|
||||
}
|
||||
return response
|
||||
})
|
||||
return { client, replies }
|
||||
}
|
||||
|
||||
function agentMessage(id: string, text: string): void {
|
||||
harness!.codex.notify('item/completed', {
|
||||
threadId: THREAD,
|
||||
turnId: TURN,
|
||||
item: { type: 'agentMessage', id, text }
|
||||
})
|
||||
}
|
||||
|
||||
/** A running turn holding `rows` earlier replies and one newest reply of `newestBytes`. */
|
||||
async function seedRunningTurn(rows: number, newestBytes: number): Promise<void> {
|
||||
harness!.codex.notify('turn/started', { threadId: THREAD, turn: { id: TURN } })
|
||||
for (let index = 0; index < rows; index += 1) {
|
||||
agentMessage(`older-${index}`, `Older reply ${index}.`)
|
||||
}
|
||||
agentMessage('newest', `${NEWEST_MARKER} ${'x'.repeat(newestBytes)}`)
|
||||
await vi.waitFor(async () => {
|
||||
const page = await harness!.call('agentSession.history', {
|
||||
sessionId: SESSION,
|
||||
direction: 'tail',
|
||||
limit: 1
|
||||
})
|
||||
expect(JSON.stringify(page)).toContain(NEWEST_MARKER)
|
||||
})
|
||||
}
|
||||
|
||||
/** Lets the command's next checks run until it prints, then surfaces its result or failure. */
|
||||
async function settle(command: Promise<void>, logs: string[]): Promise<void> {
|
||||
for (let second = 0; second < 10 && logs.length === 0; second += 1) {
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
}
|
||||
await command
|
||||
}
|
||||
|
||||
/** Runs `chat send --wait`, completes the turn after two checks, and returns what each check cost. */
|
||||
async function sendAndWait(rows: number, newestBytes: number) {
|
||||
harness = await openStructuredCodexRpcHarness([], {}, { localCli: true })
|
||||
await harness.ok('agentSession.create', harness.createIntentParams())
|
||||
const { client, replies } = cliClient(harness)
|
||||
const flags = new Map<string, string | boolean>([
|
||||
['session', SESSION],
|
||||
['text', 'Run the tests'],
|
||||
['wait', true]
|
||||
])
|
||||
const logs: string[] = []
|
||||
vi.spyOn(console, 'log').mockImplementation((line: string) => logs.push(line))
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
|
||||
const sending = CHAT_HANDLERS['chat send']!({ flags, client, cwd: '/tmp', json: true })
|
||||
await vi.waitFor(() =>
|
||||
expect(harness!.codex.live().calls.map((c) => c.method)).toContain('turn/start')
|
||||
)
|
||||
await seedRunningTurn(rows, newestBytes)
|
||||
const before = replies.length
|
||||
work.historyPages = 0
|
||||
work.turnScans = 0
|
||||
const checks = () => replies.slice(before).filter((r) => r.method === 'agentSession.workState')
|
||||
for (let second = 0; second < 5 && checks().length < 2; second += 1) {
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
}
|
||||
expect(checks()).toHaveLength(2)
|
||||
const during = { ...work, checks: checks().map((r) => r.json) }
|
||||
work.historyPages = 0
|
||||
harness.codex.notify('turn/completed', {
|
||||
threadId: THREAD,
|
||||
turn: { id: TURN, status: 'completed' }
|
||||
})
|
||||
await settle(sending, logs)
|
||||
const printed: { result: { entries: unknown[] } } = JSON.parse(logs.join('\n'))
|
||||
return { during, finalPages: work.historyPages, result: printed.result }
|
||||
}
|
||||
|
||||
describe('chat send --wait over the real host', () => {
|
||||
it.each([
|
||||
{ rows: 15, newestBytes: 64 * 1024 },
|
||||
{ rows: 150, newestBytes: 640 * 1024 }
|
||||
])(
|
||||
'checks a running turn without history pages, turn scans or its text ($rows rows, $newestBytes byte newest reply)',
|
||||
async ({ rows, newestBytes }) => {
|
||||
const { during, finalPages, result } = await sendAndWait(rows, newestBytes)
|
||||
expect(during.historyPages).toBe(0)
|
||||
expect(during.turnScans).toBe(0)
|
||||
for (const check of during.checks) {
|
||||
expect(check).not.toContain(NEWEST_MARKER)
|
||||
expect(JSON.parse(check).result).toEqual({
|
||||
working: true,
|
||||
actionablePrompt: false,
|
||||
queuedMessageIds: [],
|
||||
nextQueuedMessageId: null,
|
||||
fence: expect.any(Number)
|
||||
})
|
||||
}
|
||||
expect(finalPages).toBe(1)
|
||||
expect(result).toMatchObject({ delivery: 'submitted', settled: 'done', truncated: false })
|
||||
expect(result.entries).toEqual([
|
||||
...Array.from({ length: rows }, (_, index) => ({
|
||||
kind: 'message',
|
||||
role: 'assistant',
|
||||
text: `Older reply ${index}.`
|
||||
})),
|
||||
{ kind: 'message', role: 'assistant', text: `${NEWEST_MARKER} ${'x'.repeat(newestBytes)}` }
|
||||
])
|
||||
}
|
||||
)
|
||||
|
||||
it('reads history pages from a host without agentSession.workState, asking it only once', async () => {
|
||||
harness = await openStructuredCodexRpcHarness(
|
||||
[],
|
||||
{},
|
||||
{ localCli: true, omitMethods: ['agentSession.workState'] }
|
||||
)
|
||||
await harness.ok('agentSession.create', harness.createIntentParams())
|
||||
const { client, replies } = cliClient(harness)
|
||||
const logs: string[] = []
|
||||
vi.spyOn(console, 'log').mockImplementation((line: string) => logs.push(line))
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
|
||||
const sending = CHAT_HANDLERS['chat send']!({
|
||||
flags: new Map<string, string | boolean>([
|
||||
['session', SESSION],
|
||||
['text', 'Run the tests'],
|
||||
['wait', true]
|
||||
]),
|
||||
client,
|
||||
cwd: '/tmp',
|
||||
json: true
|
||||
})
|
||||
await vi.waitFor(() =>
|
||||
expect(harness!.codex.live().calls.map((c) => c.method)).toContain('turn/start')
|
||||
)
|
||||
await seedRunningTurn(1, 16)
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
harness.codex.notify('turn/completed', {
|
||||
threadId: THREAD,
|
||||
turn: { id: TURN, status: 'completed' }
|
||||
})
|
||||
await settle(sending, logs)
|
||||
expect(replies.filter((r) => r.method === 'agentSession.workState')).toHaveLength(1)
|
||||
expect(JSON.parse(logs.join('\n')).result).toMatchObject({
|
||||
delivery: 'submitted',
|
||||
settled: 'done',
|
||||
entries: [{ text: 'Older reply 0.' }, { text: `${NEWEST_MARKER} ${'x'.repeat(16)}` }]
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -45,6 +45,7 @@ import {
|
||||
CreateParams,
|
||||
CreateSupportParams,
|
||||
HistoryParams,
|
||||
WorkStateParams,
|
||||
RewindParams,
|
||||
SendParams,
|
||||
SleepWorkspaceParams,
|
||||
@@ -191,6 +192,16 @@ export const STRUCTURED_AGENT_SESSION_METHODS = [
|
||||
)
|
||||
}
|
||||
}),
|
||||
// Waiters poll this instead of history: no history page or running-turn scan, and no transcript in the reply.
|
||||
defineMethod({
|
||||
name: 'agentSession.workState',
|
||||
permission: 'workspace',
|
||||
params: WorkStateParams,
|
||||
handler: async (params, ctx) =>
|
||||
(await requireInstalledHost(ctx, params.sessionId)).backgroundTasks.workState(
|
||||
params.sessionId
|
||||
)
|
||||
}),
|
||||
STRUCTURED_AGENT_SESSION_SUBSCRIBE_METHOD,
|
||||
defineMethod({
|
||||
name: 'agentSession.unsubscribe',
|
||||
|
||||
+7
-3
@@ -181,11 +181,13 @@ export type StructuredCodexRpcHarness = {
|
||||
export async function openStructuredCodexRpcHarness(
|
||||
clientCapabilities: readonly RuntimeCapability[] = DEFAULT_CLIENT_CAPABILITIES,
|
||||
/** What the transport stamps, as a paired device's authenticated socket does. */
|
||||
transport: { clientId?: string; pairedDeviceId?: string } = {}
|
||||
transport: { clientId?: string; pairedDeviceId?: string } = {},
|
||||
/** The local CLI names no client kind; an older host lacks newer methods. */
|
||||
options: { localCli?: boolean; omitMethods?: readonly string[] } = {}
|
||||
): Promise<StructuredCodexRpcHarness> {
|
||||
const client = {
|
||||
clientId: 'device-a',
|
||||
clientKind: 'runtime' as const,
|
||||
...(options.localCli ? {} : { clientKind: 'runtime' as const }),
|
||||
clientCapabilities,
|
||||
...transport
|
||||
}
|
||||
@@ -247,7 +249,9 @@ export async function openStructuredCodexRpcHarness(
|
||||
}
|
||||
const dispatcher = new RpcDispatcher({
|
||||
runtime: runtime as unknown as OrcaRuntimeService,
|
||||
methods: STRUCTURED_AGENT_SESSION_METHODS
|
||||
methods: STRUCTURED_AGENT_SESSION_METHODS.filter(
|
||||
(method) => !options.omitMethods?.includes(method.name)
|
||||
)
|
||||
})
|
||||
const call: StructuredCodexRpcHarness['call'] = async (method, params) => {
|
||||
const replies: RpcResponse[] = []
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
/** `agentSession.workState`: the facts a waiter decides from, read without a history page. */
|
||||
export type AgentSessionWorkState = {
|
||||
working: boolean
|
||||
/** A question or approval is waiting for the user. */
|
||||
actionablePrompt: boolean
|
||||
/** Absent = the host makes no queue claim. */
|
||||
queuedMessageIds?: string[]
|
||||
/** With queuedMessageIds, the next unblocked send; null while held. */
|
||||
nextQueuedMessageId?: string | null
|
||||
/** The session's current runtime fence, as history pages state it. */
|
||||
fence?: number
|
||||
}
|
||||
+3
-1
@@ -665,7 +665,8 @@ import {
|
||||
SleepWorkspaceParams,
|
||||
SubscribeTurnCompletionsParams,
|
||||
ThreadGoalParams,
|
||||
UnsubscribeParams
|
||||
UnsubscribeParams,
|
||||
WorkStateParams
|
||||
} from './structured-agent-session-params'
|
||||
import { RespondToQuestionParams } from './structured-agent-session-question-params'
|
||||
import {
|
||||
@@ -873,6 +874,7 @@ export const RPC_PARAMS_BY_METHOD = {
|
||||
'agentSession.subscribeTurnCompletions': SubscribeTurnCompletionsParams,
|
||||
'agentSession.threadGoal': ThreadGoalParams,
|
||||
'agentSession.unsubscribe': UnsubscribeParams,
|
||||
'agentSession.workState': WorkStateParams,
|
||||
'agentSessionAttachment.read': AttachmentReadParams,
|
||||
'agentSessionAttachment.readTextChunk': AttachmentTextReadParams,
|
||||
'agentSessionAttachment.uploadAbort': AttachmentUploadIdParams,
|
||||
|
||||
@@ -335,6 +335,8 @@ export const HistoryParams = z
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const WorkStateParams = z.object({ sessionId: SessionId }).strict()
|
||||
|
||||
// Not strict: an older host ignores these params entirely, and this host must ignore a newer client's.
|
||||
export const SubscribeTurnCompletionsParams = z.object({ includePrompts: z.boolean().optional() })
|
||||
|
||||
|
||||
Reference in New Issue
Block a user