fix(native-chat): run /goal pause, resume and clear in Codex chats (#38250)

* fix(native-chat): run Codex /goal pause|resume|clear and /usage from chat

Codex app-server has no slash parser, so a chat's /goal pause set the goal's text to "pause" and /usage reached the model as prose. /goal pause|resume|clear now change the current goal through the host, and /usage opens the Codex usage section in Settings for the chat's host.

* fix(codex): say a chat has no goal when /goal pause or resume finds none

Codex rejects a status change without a goal in words naming the thread id; read the goal after that rejection and show Orca's copy instead.

* fix(native-chat): address review on Codex /goal controls and /usage

Look goal words up without inherited properties, keep text after a picked /usage, let Send run what Enter runs on a held host, name Codex when there is no goal (clear included), and drop the shared /goal hint that phones and goal-less hosts would show for words they send as text.

* fix(native-chat): keep the draft after a picked /usage and hold goal-mode Send

Picking /usage opens Settings and leaves the text typed after the command; Enter on the row no longer sends /usage to the agent. Goal mode submits its draft as an objective, so a held host keeps Send held there, and an enabled Send is not labelled with the hold.

* test(native-chat): build the picker state instead of casting it

* fix(native-chat): honor Stop before naming a missing goal, and own any Codex /usage row

A canceled pause or resume no longer reads the goal to word a refusal, and an agent-reported /usage row gives way to Orca's, as /resume already does.

* revert(native-chat): leave /usage for its own change

Brennan wants /usage to show the status bar's Codex usage panel for the chat's account, in a separate PR; this PR keeps the /goal controls and the held-chat Send fix.
This commit is contained in:
Brennan Benson
2026-11-04 18:49:32 -08:00
committed by GitHub
parent 4152c19541
commit cb456bfc2b
17 changed files with 237 additions and 44 deletions
@@ -100,6 +100,41 @@ describe('codex thread goal requests', () => {
])
})
it('says there is no goal when Codex refuses a status change for a thread without one', async () => {
const request = vi.fn(async (method: unknown) => {
if (method === 'thread/goal/set') {
throw new CodexAppServerRequestError(
'thread/goal/set',
-32600,
`cannot update goal for thread ${THREAD}: no goal exists`
)
}
return { goal: null }
})
await expect(
changeCodexThreadGoal(session(request), { kind: 'status', status: 'paused' }, false, 5_000)
).resolves.toEqual({
ok: false,
rejected:
'Codex has no goal to change in this chat. Set one with /goal followed by the objective.'
})
expect(request.mock.calls.map(([method]) => method)).toEqual([
'thread/goal/set',
'thread/goal/get'
])
})
it('says there is no goal when Codex reports a clear removed nothing', async () => {
const request = vi.fn(async () => ({ cleared: false }))
await expect(
changeCodexThreadGoal(session(request), { kind: 'clear' }, false, 5_000)
).resolves.toEqual({
ok: false,
rejected:
'Codex has no goal to change in this chat. Set one with /goal followed by the objective.'
})
})
it('awaits a revoked clear and never activates the replacement', async () => {
const clear = Promise.withResolvers<unknown>()
const authority = new AbortController()
@@ -38,6 +38,32 @@ export function codexThreadGoalRequests(
]
}
/** After Codex refuses a status change, whether it had no goal to change; unknown counts as a goal. */
async function codexThreadGoalMissing(
session: Pick<CodexSession, 'connection' | 'threadId'>,
timeoutMs: number | undefined
): Promise<boolean> {
try {
const read = await session.connection.request(
'thread/goal/get',
{ threadId: session.threadId },
{ timeoutMs }
)
return typeof read === 'object' && read !== null && 'goal' in read && read.goal === null
} catch {
return false
}
}
function readCodexClearedFlag(response: unknown): boolean | undefined {
return typeof response === 'object' &&
response !== null &&
'cleared' in response &&
typeof response.cleared === 'boolean'
? response.cleared
: undefined
}
export async function changeCodexThreadGoal(
session: Pick<CodexSession, 'connection' | 'threadId'>,
change: AgentSessionThreadGoalChange,
@@ -49,11 +75,26 @@ export async function changeCodexThreadGoal(
try {
for (const request of codexThreadGoalRequests(session.threadId, change, replacesGoal)) {
throwIfSignalAborted(signal)
await session.connection.request(request.method, request.params, { timeoutMs })
const response = await session.connection.request(request.method, request.params, {
timeoutMs
})
// A clear on its own reports whether a goal existed; Codex says nothing else when none did.
if (change.kind === 'clear' && readCodexClearedFlag(response) === false) {
return { ok: false, rejected: AGENT_SESSION_GOAL_CONTROL_COPY.noGoal }
}
cleared ||= request.method === 'thread/goal/clear'
}
} catch (error) {
if (isCodexAppServerRequestError(error)) {
// Codex words a missing goal with internal ids; say it in the user's terms instead.
if (change.kind === 'status') {
throwIfSignalAborted(signal)
const missing = await codexThreadGoalMissing(session, timeoutMs)
throwIfSignalAborted(signal)
if (missing) {
return { ok: false, rejected: AGENT_SESSION_GOAL_CONTROL_COPY.noGoal }
}
}
return {
ok: false,
rejected: cleared
@@ -294,7 +294,9 @@ export const NativeChatComposerPane = forwardRef<ComposerHandle, C.NativeChatCom
structuredTransport,
editSession,
isWorking,
canStop: hasPty && onStop !== undefined
canStop: hasPty && onStop !== undefined,
orcaCommand: !pending && !launchPrompt && resume.matchesDraft(draft),
goalMode: goalMode.active
})
const { send, chooseEditItem, fieldOverrides, dispatchPickerCommand } =
@@ -18,7 +18,8 @@ const WORDS = new Map<string, () => string>([
[
COPY.stopUnconfirmed,
() => translate('components.native-chat.goalControl.stopUnconfirmed', COPY.stopUnconfirmed)
]
],
[COPY.noGoal, () => translate('components.native-chat.goalControl.noGoal', COPY.noGoal)]
])
export function agentSessionGoalControlWords(text: string): string {
@@ -276,7 +276,7 @@ it('captures projected identity once for real typed-goal dispatch and Goal mode'
expect(expected).not.toContain('\n')
expect(expected).toContain('message it with orca orchestration send --to')
expect(expected.match(/@Same name \(2\)/g)).toHaveLength(1)
const setObjective = vi.fn(async () => true)
const setObjective = vi.fn(async (_objective: string) => true)
const structured = transport()
structured.threadGoal = { setObjective }
structured.dispatchCommand = (text) =>
@@ -284,7 +284,7 @@ it('captures projected identity once for real typed-goal dispatch and Goal mode'
snapshot: [],
invokeAction: async () => true,
setOption: async () => true,
setThreadGoalObjective: setObjective
changeThreadGoal: (change) => setObjective(change.kind === 'set' ? change.objective : '')
})
structured.capturePresentation = () => {
updateNativeChatComposerDraft(
@@ -420,7 +420,7 @@ it('keeps an actual composing return through command acceptance, composition set
snapshot: [],
invokeAction: async () => true,
setOption: async () => true,
setThreadGoalObjective: () => reply.promise
changeThreadGoal: () => reply.promise
}),
optionsSurface: {
getSnapshot: () => [],
@@ -0,0 +1,48 @@
import { describe, expect, it } from 'vitest'
import { nativeChatComposerSendState } from './native-chat-composer-send-state'
import type { NativeChatStructuredComposerTransport } from './native-chat-composer-types'
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: send state reads only these fields.
const heldHost = {
sendBlockedReason: 'Waiting for permission mode',
threadGoal: { setObjective: async () => true }
} as unknown as NativeChatStructuredComposerTransport
function sendState(draft: string, orcaCommand = false, goalMode = false) {
return nativeChatComposerSendState({
draft,
messageDelivery: true,
imageAttachments: [],
pastedTextSaving: false,
disabled: false,
structuredTransport: heldHost,
editSession: undefined,
isWorking: false,
canStop: false,
orcaCommand,
goalMode
})
}
function sendDisabled(draft: string, orcaCommand = false, goalMode = false): boolean {
return sendState(draft, orcaCommand, goalMode).sendButtonDisabled
}
describe('Send on a held chat host', () => {
it('stays pressable for what Enter still runs and held for anything that starts a turn', () => {
expect(sendDisabled('/goal pause')).toBe(false)
expect(sendDisabled('/goal clear')).toBe(false)
expect(sendDisabled('/model')).toBe(false)
expect(sendDisabled('/resume', true)).toBe(false)
expect(sendDisabled('/goal resume')).toBe(true)
expect(sendDisabled('/goal ship it')).toBe(true)
expect(sendDisabled('/compact')).toBe(true)
expect(sendDisabled('hello')).toBe(true)
// Goal mode sends the draft as an objective, even one spelled like a command.
expect(sendDisabled('/goal pause', false, true)).toBe(true)
expect(sendDisabled('/resume', true, true)).toBe(false)
// An enabled button is not labelled with the hold.
expect(sendState('/goal pause').sendBlockedReason).toBeNull()
expect(sendState('hello').sendBlockedReason).toBe('Waiting for permission mode')
})
})
@@ -2,6 +2,10 @@ import type { NativeChatFollowUpBehavior } from '../../../../shared/native-chat/
import type { NativeChatComposerImageAttachment } from './NativeChatComposerField'
import type { NativeChatStructuredComposerTransport } from './native-chat-composer-types'
import { nativeChatImageSendBlock } from './native-chat-image-reattach'
import {
isStructuredAgentSessionHostCommand,
structuredAgentSessionCommandChangesConversation
} from '../../../../shared/agent-session/view/structured-agent-session-composer'
export type NativeChatComposerSendState = {
/** Why Send is disabled, when the user can do something about it. */
@@ -26,26 +30,41 @@ export function nativeChatComposerSendState(input: {
editSession: { canSave: boolean } | undefined
isWorking: boolean
canStop: boolean
/** The draft is an Orca command such as /resume, which runs without the agent. */
orcaCommand?: boolean
/** Goal mode submits the draft as an objective, which starts work. */
goalMode?: boolean
}): NativeChatComposerSendState {
const { structuredTransport: transport } = input
const imageBlock = nativeChatImageSendBlock(input.imageAttachments)
const sendHeld =
input.pastedTextSaving ||
input.disabled ||
transport?.sendOut === true ||
imageBlock.holdsSend ||
transport?.sendBlockedReason !== undefined
const localHold =
input.pastedTextSaving || input.disabled || transport?.sendOut === true || imageBlock.holdsSend
const hostHold = transport?.sendBlockedReason !== undefined
const sendHeld = localHold || hostHold
// Like Enter, a held host still takes commands that start no turn.
const runsWhileHostHolds =
input.orcaCommand === true ||
(transport !== undefined &&
input.goalMode !== true &&
input.imageAttachments.length === 0 &&
isStructuredAgentSessionHostCommand(input.draft, transport.threadGoal !== undefined) &&
!structuredAgentSessionCommandChangesConversation(input.draft))
const draftHeld = localHold || (hostHold && !runsWhileHostHolds)
const hasDraft = input.draft.trim() !== '' || input.imageAttachments.length > 0
// Like Enter, a typed draft sends while the agent works; only an empty one offers Stop.
const sendButtonDisabled = input.editSession
? sendHeld || !input.editSession.canSave
: input.isWorking && !hasDraft
? !input.canStop
: sendHeld || !hasDraft
: draftHeld || !hasDraft
// The send's own resolver, so the hint withdraws wherever Cmd/Ctrl+Enter would send no differently.
const followUp = transport?.sendFollowUp
return {
sendBlockedReason: imageBlock.reason ?? transport?.sendBlockedReason ?? null,
// The host's reason labels Send only while it holds this draft.
sendBlockedReason:
imageBlock.reason ??
(hostHold && !runsWhileHostHolds ? transport?.sendBlockedReason : null) ??
null,
sendHeld,
hasDraft,
sendButtonDisabled,
@@ -254,7 +254,7 @@ describe('mid-turn send keys on a host that queues', () => {
function operationTransport(overrides: Partial<NativeChatStructuredComposerTransport> = {}) {
const send = vi.fn(() => true)
const setObjective = vi.fn(async () => true)
const setObjective = vi.fn(async (_objective: string) => true)
const invokeAction = vi.fn(async () => true)
const runConversationCommand = vi.fn(async () => ({ accepted: true, error: null }))
const transport: NativeChatStructuredComposerTransport = {
@@ -267,7 +267,7 @@ function operationTransport(overrides: Partial<NativeChatStructuredComposerTrans
setOption: async () => true,
conversationCommands: ['compact', 'clear'],
runConversationCommand,
setThreadGoalObjective: setObjective
changeThreadGoal: (change) => setObjective(change.kind === 'set' ? change.objective : '')
}),
sendFollowUp: { action: 'queue', offersChoice: true },
threadGoal: { setObjective },
@@ -97,7 +97,7 @@ describe('complete handback acceptance', () => {
snapshot: [],
invokeAction: async () => true,
setOption: async () => true,
setThreadGoalObjective: () => goal.promise
changeThreadGoal: () => goal.promise
}),
optionsSurface: {
getSnapshot: () => [],
@@ -9,6 +9,7 @@ import type {
import type { NativeChatStructuredViewProps } from './native-chat-view-types'
import type { useStructuredAgentSession } from './use-structured-agent-session'
import type { AgentType } from '../../../../shared/agent-status/contracts/agent-status-types'
import type { AgentSessionThreadGoalChange } from '../../../../shared/agent-session/agent-session-thread-goal-wire'
import { translate } from '@/i18n/i18n'
import { structuredAgentLabel } from '@/lib/agent-session/launch/structured-agent-session-launch-label'
@@ -58,10 +59,13 @@ export function useNativeChatStructuredComposerTransport(args: {
)
return useMemo((): NativeChatStructuredComposerTransport => {
const threadGoal = controller.threadGoal
const setThreadGoalObjective = threadGoal?.hostChanges
? (objective: string) =>
sendBlockedReason === null
? threadGoal.change({ kind: 'set', objective })
// A held host takes no turn; pausing or clearing a goal starts none.
const changeThreadGoal = threadGoal?.hostChanges
? (change: AgentSessionThreadGoalChange) =>
sendBlockedReason === null ||
change.kind === 'clear' ||
(change.kind === 'status' && change.status === 'paused')
? threadGoal.change(change)
: Promise.resolve(false)
: null
return {
@@ -97,9 +101,15 @@ export function useNativeChatStructuredComposerTransport(args: {
conversationCommands: controller.conversationCommands,
compactInstructions: controller.compactInstructions,
runConversationCommand: controller.runConversationCommand,
...(setThreadGoalObjective ? { setThreadGoalObjective } : {})
...(changeThreadGoal ? { changeThreadGoal } : {})
}).then(localizeStructuredComposerOutcome),
...(setThreadGoalObjective ? { threadGoal: { setObjective: setThreadGoalObjective } } : {}),
...(changeThreadGoal
? {
threadGoal: {
setObjective: (objective: string) => changeThreadGoal({ kind: 'set', objective })
}
}
: {}),
sendOut: controller.sendOut || starting,
sendFollowUp: controller.sendFollowUp,
...(sendBlockedReason !== null ? { sendBlockedReason } : {}),
@@ -146,7 +146,9 @@ export function useStructuredAgentSessionMutate(args: {
const message = result.refusal.message
if (
fingerprintMethod === 'agentSession.threadGoal' &&
(message === GOAL_COPY.settingsRejected || message === GOAL_COPY.settingsUnconfirmed)
(message === GOAL_COPY.settingsRejected ||
message === GOAL_COPY.settingsUnconfirmed ||
message === GOAL_COPY.noGoal)
) {
outcome.notice = agentSessionGoalControlWords(message)
}
+2 -1
View File
@@ -1642,7 +1642,8 @@
"pauseUnconfirmed": "Codex stopped running, but its goal pause was not confirmed. Check the goal before continuing.",
"settingsRejected": "Codex could not apply the selected model and effort. This goal change was not sent. Check the selection and try again.",
"settingsUnconfirmed": "Codex did not confirm the selected model and effort. This goal change was not sent. Check the chat and try again.",
"stopUnconfirmed": "Codex could not confirm Stop. Check the chat before continuing."
"stopUnconfirmed": "Codex could not confirm Stop. Check the chat before continuing.",
"noGoal": "Codex has no goal to change in this chat. Set one with /goal followed by the objective."
},
"notices": {
"compaction": "Context compacted",
+2 -1
View File
@@ -20460,7 +20460,8 @@
"settingsRejected": "Codex could not apply the selected model and effort. This goal change was not sent. Check the selection and try again.",
"settingsUnconfirmed": "Codex did not confirm the selected model and effort. This goal change was not sent. Check the chat and try again.",
"pauseUnconfirmed": "Codex stopped running, but its goal pause was not confirmed. Check the goal before continuing.",
"stopUnconfirmed": "Codex could not confirm Stop. Check the chat before continuing."
"stopUnconfirmed": "Codex could not confirm Stop. Check the chat before continuing.",
"noGoal": "Codex has no goal to change in this chat. Set one with /goal followed by the objective."
},
"slashCommandDescriptions": {
"clearConversation": "Clear the conversation",
@@ -5,5 +5,6 @@ export const AGENT_SESSION_GOAL_CONTROL_COPY = {
'Codex did not confirm the selected model and effort. This goal change was not sent. Check the chat and try again.',
pauseUnconfirmed:
'Codex stopped running, but its goal pause was not confirmed. Check the goal before continuing.',
stopUnconfirmed: 'Codex could not confirm Stop. Check the chat before continuing.'
stopUnconfirmed: 'Codex could not confirm Stop. Check the chat before continuing.',
noGoal: 'Codex has no goal to change in this chat. Set one with /goal followed by the objective.'
} as const
@@ -80,34 +80,52 @@ describe('agent-implemented commands pass through to the agent', () => {
const PASSED_THROUGH = { handled: false, accepted: false, error: null }
it('sets the goal through the host where the host can, instead of sending prose', async () => {
const setThreadGoalObjective = vi.fn(async () => true)
const changeThreadGoal = vi.fn(async () => true)
expect(
await dispatchStructuredAgentSessionComposerCommand('/goal ship the fix ', {
...controller,
agent: 'codex',
setThreadGoalObjective
changeThreadGoal
})
).toEqual({ handled: true, accepted: true, error: null })
expect(setThreadGoalObjective).toHaveBeenCalledWith('ship the fix')
expect(changeThreadGoal).toHaveBeenCalledWith({ kind: 'set', objective: 'ship the fix' })
// A refused goal keeps the draft; the session error surface explains why.
setThreadGoalObjective.mockResolvedValueOnce(false)
changeThreadGoal.mockResolvedValueOnce(false)
expect(
await dispatchStructuredAgentSessionComposerCommand('/goal ship the fix', {
...controller,
agent: 'codex',
setThreadGoalObjective
changeThreadGoal
})
).toEqual({ handled: true, accepted: false, error: null })
})
it('pauses, resumes or clears the current goal; any other word is the objective', async () => {
const changeThreadGoal = vi.fn(async () => true)
const goalHost = { ...controller, agent: 'codex' as const, changeThreadGoal }
for (const text of ['/goal pause', '/goal Resume', '/goal clear', '/goal constructor']) {
expect(await dispatchStructuredAgentSessionComposerCommand(text, goalHost)).toEqual({
handled: true,
accepted: true,
error: null
})
}
expect(changeThreadGoal.mock.calls).toEqual([
[{ kind: 'status', status: 'paused' }],
[{ kind: 'status', status: 'active' }],
[{ kind: 'clear' }],
[{ kind: 'set', objective: 'constructor' }]
])
})
it('asks for an objective when a goal-capable host gets a bare /goal', async () => {
const setThreadGoalObjective = vi.fn(async () => true)
const changeThreadGoal = vi.fn(async () => true)
expect(
await dispatchStructuredAgentSessionComposerCommand('/goal', {
...controller,
agent: 'codex',
setThreadGoalObjective
changeThreadGoal
})
).toEqual({
handled: true,
@@ -115,7 +133,7 @@ describe('agent-implemented commands pass through to the agent', () => {
error: 'Describe the goal after /goal.',
errorCode: 'goalObjectiveMissing'
})
expect(setThreadGoalObjective).not.toHaveBeenCalled()
expect(changeThreadGoal).not.toHaveBeenCalled()
})
it('leaves provider text independent of the optional inventory', async () => {
@@ -9,6 +9,7 @@ import {
type SlashCommandSuggestion
} from '../../native-chat/input/native-chat-slash-commands'
import type { AgentSessionConversationCommand } from '../agent-session-conversation-command'
import type { AgentSessionThreadGoalChange } from '../agent-session-thread-goal-wire'
import type { AgentSessionSlashCommand } from '../agent-session-wire'
import {
structuredComposerFailure,
@@ -54,7 +55,7 @@ export type StructuredAgentSessionComposerOptions = {
instructions?: string
) => Promise<Omit<StructuredAgentSessionCommandOutcome, 'handled'>>
/** Without host goal support, /goal remains agent-handled text. */
setThreadGoalObjective?: (objective: string) => Promise<boolean>
changeThreadGoal?: (change: AgentSessionThreadGoalChange) => Promise<boolean>
}
/** Visible condition holding a refusal: agent/prompt/background work, an in-flight send or a Retry card. */
@@ -188,14 +189,25 @@ export function isStructuredAgentSessionGoalCommand(text: string): boolean {
return commandParts(text)?.name === 'goal'
}
/** `/clear`, `/compact` and `/goal …` change the conversation; option and picker commands do not. */
const GOAL_CONTROLS: ReadonlyMap<string, AgentSessionThreadGoalChange> = new Map([
['pause', { kind: 'status', status: 'paused' }],
['resume', { kind: 'status', status: 'active' }],
['clear', { kind: 'clear' }]
])
/** `/goal pause|resume|clear` controls the current goal; any other text is a new objective. */
export function structuredAgentSessionGoalChange(argument: string): AgentSessionThreadGoalChange {
return GOAL_CONTROLS.get(argument.toLowerCase()) ?? { kind: 'set', objective: argument }
}
/** `/clear`, `/compact` and goal changes that start work change the conversation; pausing or clearing a goal does not. */
export function structuredAgentSessionCommandChangesConversation(text: string): boolean {
const command = commandParts(text)
return (
command?.name === 'clear' ||
command?.name === 'compact' ||
(command?.name === 'goal' && command.argument !== '')
)
if (command?.name === 'goal') {
const change = command.argument ? structuredAgentSessionGoalChange(command.argument) : null
return change?.kind === 'set' || (change?.kind === 'status' && change.status === 'active')
}
return command?.name === 'clear' || command?.name === 'compact'
}
/** `/goal` with nothing after it: an entrance to goal mode, not an objective. */
@@ -223,7 +235,7 @@ export async function dispatchStructuredAgentSessionComposerCommand(
controller: StructuredAgentSessionComposerOptions
): Promise<StructuredAgentSessionCommandOutcome> {
const command = commandParts(text)
if (command?.name === 'goal' && controller.setThreadGoalObjective) {
if (command?.name === 'goal' && controller.changeThreadGoal) {
if (!command.argument) {
return {
handled: true,
@@ -234,7 +246,9 @@ export async function dispatchStructuredAgentSessionComposerCommand(
// A refusal reaches the user through the session's own error surface.
return {
handled: true,
accepted: await controller.setThreadGoalObjective(command.argument),
accepted: await controller.changeThreadGoal(
structuredAgentSessionGoalChange(command.argument)
),
error: null
}
}