feat(native-chat): show agent sign-in requests as a card in chat (#42219)

ACP agents can ask the user to open a sign-in page with URL-mode
elicitation (elicitation/create mode "url", then elicitation/complete).
Orca now advertises URL elicitation to ACP chats and shows the request as a
"Sign-in requested" card with the link's host, Open sign-in page and
Decline. Open replies accept once the system browser opens the page; the
card collapses to "Sign-in finished" when the agent sends completion.

Grok forwards its MCP servers' elicitations through its own
x.ai/mcp/elicit extension, which Orca refused before. URL requests now use
the same card and form requests use the existing question card.
This commit is contained in:
Kelvin Amoaba
2026-11-15 22:19:14 +00:00
committed by GitHub
parent 15cbd7154c
commit bf05c9b2ae
33 changed files with 1025 additions and 56 deletions
+1 -2
View File
@@ -77,8 +77,7 @@
"moreCount_one": "{{count}} more",
"moreCount_other": "{{count}} more",
"queuedCount_one": "{{count}} queued message",
"queuedCount_other": "{{count}} queued messages",
"foldNeedsAttention": "{{more}}, a message needs attention"
"queuedCount_other": "{{count}} queued messages"
},
"subagentGroup": {
"ran_one": "Ran {{count}} subagent",
+9
View File
@@ -3489,6 +3489,15 @@
"outcomeUnknownReturned": "Orca couldn't confirm whether the conversation went back to this message. Your message is back in the composer, and Orca checks the conversation before your next message is sent.",
"timeout": "The chat didn't update after going back to this message. Reopen it to see the latest.",
"pending": "Wait for the conversation to go back to the earlier message."
},
"urlRequest": {
"title": "Sign-in requested",
"open": "Open sign-in page",
"decline": "Decline",
"opened": "Opened the sign-in page in your browser.",
"openAgain": "Open again",
"finished": "Sign-in finished",
"finishedWith": "Sign-in finished · {{message}}"
}
},
"sourceControl": {
@@ -1,6 +1,11 @@
import { Linking } from 'react-native'
// Catch both synchronous Linking validation and rejected open promises; either can fail a tap, and neither may escape its handler. The page sibling forwards through native.
/** Linking takes any URL here; only the page's shell bridge refuses some. */
export function canOpenExternalLink(_url: string): boolean {
return true
}
export function openExternalLink(url: string): void {
try {
void Linking.openURL(url).catch((error: unknown) => {
@@ -10,6 +10,11 @@ export function publishExternalLinkOpener(opener: ExternalLinkOpener): void {
post = opener
}
/** False for a URL the shell would refuse, such as one past the bridge's length limit. */
export function canOpenExternalLink(url: string): boolean {
return readBridgeExternalLinkUrl(url) !== null
}
export function openExternalLink(url: string): void {
// Validate before posting: the shell drops refused frames without a reply, which would otherwise look like successful navigation.
if (readBridgeExternalLinkUrl(url) === null) {
@@ -11,9 +11,18 @@ import { useMobileColorScheme } from '../../../../theme/use-mobile-color-scheme'
import { useMobileTranslation } from '../../../../i18n/use-mobile-translation'
import {
isNewerApprovalSubject,
isPlanApprovalSubject
isPlanApprovalSubject,
isUrlApprovalSubject,
URL_APPROVAL_DECLINE_OPTION_ID,
URL_APPROVAL_OPEN_OPTION_ID
} from '../../../../../../src/shared/agent-session/agent-session-approval-subject'
import type { MobileChatPermission } from './mobile-native-chat-permission'
import {
canOpenUrlRequestPage,
MobileNativeChatUrlTarget,
openUrlRequestPage
} from './MobileNativeChatUrlRequest'
import { structuredApprovalOptionId } from './mobile-structured-agent-prompts'
function MobileNativeChatPermissionImpl({
permission,
@@ -36,6 +45,17 @@ function MobileNativeChatPermissionImpl({
const submittingRef = useRef(false)
// Unknown newer-host subjects allow only cancellation; preserve their detail for the reader.
const newerSubject = isNewerApprovalSubject(permission.subject)
// A page to open: its option opens it, and the back-out stays quiet.
const url = isUrlApprovalSubject(permission.subject) ? permission.subject.url : null
const title = url === null ? permission.title : t('chat.urlRequest.title', 'Sign-in requested')
const optionLabel = (option: MobileChatPermission['options'][number]): string =>
url === null
? option.label
: structuredApprovalOptionId(option.send) === URL_APPROVAL_OPEN_OPTION_ID
? t('chat.urlRequest.open', 'Open sign-in page')
: structuredApprovalOptionId(option.send) === URL_APPROVAL_DECLINE_OPTION_ID
? t('chat.urlRequest.decline', 'Decline')
: option.label
const respond = async (send: string): Promise<void> => {
if (submittingRef.current) {
return
@@ -58,7 +78,7 @@ function MobileNativeChatPermissionImpl({
numberOfLines={2}
ellipsizeMode="tail"
>
{permission.title}
{title}
</Text>
<MobileNativeChatCardHeaderAction
prompt={permission.prompt}
@@ -71,21 +91,39 @@ function MobileNativeChatPermissionImpl({
<View testID="native-chat-approval-actions" style={styles.options}>
{permission.options.map((option, index) => {
const isPrimary = index === 0 && !permission.neutralOptions
const opensUrl =
url !== null && structuredApprovalOptionId(option.send) === URL_APPROVAL_OPEN_OPTION_ID
const unopenable = opensUrl && !canOpenUrlRequestPage(url)
return (
<Pressable
key={`${option.send}:${option.label}`}
style={({ pressed }) => [
styles.option,
isPrimary ? styles.optionPrimary : styles.optionSecondary,
isPrimary
? styles.optionPrimary
: url === null
? styles.optionSecondary
: styles.optionQuiet,
pressed && !submitting && styles.optionPressed,
newerSubject && styles.disabled
(newerSubject || unopenable) && styles.disabled
]}
hitSlop={6}
onPress={() => respond(option.send)}
disabled={submitting || newerSubject}
onPress={() => {
if (opensUrl && !submittingRef.current) {
openUrlRequestPage(url)
}
void respond(option.send)
}}
disabled={submitting || newerSubject || unopenable}
>
<Text style={[styles.optionText, isPrimary && styles.optionTextPrimary]}>
{option.label}
<Text
style={[
styles.optionText,
isPrimary && styles.optionTextPrimary,
!isPrimary && url !== null && styles.optionTextQuiet
]}
>
{optionLabel(option)}
</Text>
</Pressable>
)
@@ -165,6 +203,8 @@ function MobileNativeChatPermissionContext({
</Text>
) : null}
</View>
) : isUrlApprovalSubject(permission.subject) ? (
<MobileNativeChatUrlTarget url={permission.subject.url} />
) : permission.detail ? (
<MobileNativeChatPermissionDetail detail={permission.detail} />
) : null}
@@ -274,6 +314,9 @@ const styles = themedStyleSheet(() => ({
borderWidth: StyleSheet.hairlineWidth,
borderColor: colors.borderSubtle
},
optionQuiet: {
backgroundColor: 'transparent'
},
optionPressed: {
opacity: 0.7
},
@@ -287,5 +330,8 @@ const styles = themedStyleSheet(() => ({
},
optionTextPrimary: {
color: colors.onAccent
},
optionTextQuiet: {
color: colors.textSecondary
}
}))
@@ -0,0 +1,173 @@
import { Pressable, StyleSheet, Text, View } from 'react-native'
import { readApprovalUrl } from '../../../../../../src/shared/agent-session/agent-session-approval-subject'
import type {
AgentJournalApprovalItem,
AgentJournalUrlApprovalSubject
} from '../../../../../../src/shared/agent-session/journal/agent-session-journal-types'
import {
canOpenExternalLink,
openExternalLink
} from '../../../../platform/external-links/external-link'
import { colors, radii, spacing, typography } from '../../../../theme/mobile-theme'
import { themedStyleSheet } from '../../../../theme/themed-styles'
import { useMobileColorScheme } from '../../../../theme/use-mobile-color-scheme'
import { useMobileTranslation } from '../../../../i18n/use-mobile-translation'
import { scaledType } from '../../transcript/messages/mobile-native-chat-message-styles'
/** Whether this device can open the page; when it can't, Open must not tell the agent it did. */
export function canOpenUrlRequestPage(url: string): boolean {
const target = readApprovalUrl(url)
return target !== null && canOpenExternalLink(target.href)
}
/** Opens only in the system browser, outside anything Orca or an agent can read. */
export function openUrlRequestPage(url: string): void {
const target = readApprovalUrl(url)
if (target) {
openExternalLink(target.href)
}
}
/** Where the page goes: its host to judge it by, then the whole link. */
export function MobileNativeChatUrlTarget({ url }: { url: string }): React.JSX.Element | null {
useMobileColorScheme()
const target = readApprovalUrl(url)
if (!target) {
return null
}
return (
<View testID="native-chat-url-target" style={styles.target}>
<Text style={styles.host} numberOfLines={1}>
{target.host}
</Text>
<Text selectable style={styles.href}>
{target.href}
</Text>
</View>
)
}
/** An opened URL request in the transcript: waiting on the agent, or finished. */
export function MobileNativeChatUrlRequestReceipt({
body,
subject,
finished,
fontScale
}: {
body: AgentJournalApprovalItem
subject: AgentJournalUrlApprovalSubject
finished: boolean
fontScale: number
}): React.JSX.Element {
useMobileColorScheme()
const t = useMobileTranslation()
const meta = [styles.meta, scaledType(typography.metaSize, fontScale, 5)]
if (finished) {
return (
<View testID="native-chat-url-finished" style={[styles.card, styles.finished]}>
<Text style={meta} numberOfLines={1}>
{body.description
? t('chat.urlRequest.finishedWith', 'Sign-in finished · {{message}}', {
message: body.description
})
: t('chat.urlRequest.finished', 'Sign-in finished')}
</Text>
</View>
)
}
const target = readApprovalUrl(subject.url)
return (
<View testID="native-chat-url-opened" style={styles.card}>
<Text style={[styles.title, scaledType(typography.bodySize, fontScale, 6)]}>
{t('chat.urlRequest.title', 'Sign-in requested')}
</Text>
{body.description ? (
<Text style={[styles.description, scaledType(typography.bodySize, fontScale, 6)]}>
{body.description}
</Text>
) : null}
{target ? (
<Text style={[meta, styles.mono]} numberOfLines={1}>
{target.host}
</Text>
) : null}
<View style={styles.row}>
<Text style={meta}>
{t('chat.urlRequest.opened', 'Opened the sign-in page in your browser.')}
</Text>
{target ? (
<Pressable
accessibilityRole="button"
hitSlop={8}
onPress={() => openUrlRequestPage(target.href)}
style={({ pressed }) => [styles.again, pressed && styles.pressed]}
>
<Text style={[meta, styles.againText]}>
{t('chat.urlRequest.openAgain', 'Open again')}
</Text>
</Pressable>
) : null}
</View>
</View>
)
}
const styles = themedStyleSheet(() => ({
target: {
gap: spacing.xs
},
host: {
color: colors.textPrimary,
fontFamily: typography.monoFamily,
fontSize: typography.metaSize,
lineHeight: typography.metaSize + 5
},
href: {
color: colors.textSecondary,
fontFamily: typography.monoFamily,
fontSize: typography.metaSize - 1,
lineHeight: typography.metaSize + 4
},
card: {
gap: spacing.xs,
padding: spacing.md,
borderRadius: radii.surface,
borderWidth: StyleSheet.hairlineWidth,
borderColor: colors.borderSubtle,
backgroundColor: colors.bgPanel
},
finished: {
paddingVertical: spacing.sm
},
title: {
color: colors.textPrimary,
fontWeight: '600'
},
description: {
color: colors.textSecondary
},
meta: {
color: colors.textMuted
},
mono: {
fontFamily: typography.monoFamily
},
row: {
flexDirection: 'row',
flexWrap: 'wrap',
alignItems: 'center',
gap: spacing.sm
},
again: {
paddingHorizontal: spacing.sm,
paddingVertical: spacing.xs,
borderRadius: radii.control
},
againText: {
color: colors.textPrimary,
fontWeight: '600'
},
pressed: {
opacity: 0.7
}
}))
@@ -194,6 +194,12 @@ export function projectStructuredQuestion(
}
}
/** The journal option an approval card's response token names; null for a terminal reply. */
export function structuredApprovalOptionId(response: string): string | null {
const token = decodePromptToken(response)
return token?.kind === 'approval' ? token.optionId : null
}
export function structuredApprovalResponseTarget(
response: string,
currentPrompt: StructuredApprovalItem | null
@@ -16,6 +16,8 @@ import { scaledType } from './mobile-native-chat-message-styles'
import { MobileNativeChatMessageTime } from './MobileNativeChatMessageTime'
import { themedStyleSheet } from '../../../../theme/themed-styles'
import { useMobileColorScheme } from '../../../../theme/use-mobile-color-scheme'
import { urlApprovalProgress } from '../../../../../../src/shared/agent-session/agent-session-approval-subject'
import { MobileNativeChatUrlRequestReceipt } from '../../input/prompts/MobileNativeChatUrlRequest'
export function MobileNativeChatResolutionReceipt({
body,
@@ -41,6 +43,10 @@ export function MobileNativeChatResolutionReceipt({
/>
) : null
}
const urlProgress = body.kind === 'approval' ? urlApprovalProgress(body) : null
if (body.kind === 'approval' && urlProgress) {
return <MobileNativeChatUrlRequestReceipt body={body} {...urlProgress} fontScale={fontScale} />
}
const { resolution } = body
const device = nativeChatReceiptDevice(resolution, {
current: t('chat.receipt.thisPhone', 'this phone'),
+4
View File
@@ -35,6 +35,8 @@ export type AcpAdvertisedEfforts = {
export type AcpRequestPresentation = {
body: ProviderTimelineRequestBody
reply(response: AgentSessionPromptResponse | null): unknown
/** A URL request the agent may later report finished with `elicitation/complete`. */
elicitationId?: string
}
export type AcpRequestSettlement = { reply: unknown; plan?: string }
@@ -168,6 +170,8 @@ export type AcpDialect = {
sessionlessRequests?: readonly string[]
/** Claimed permission requests are never auto-approved. */
request?(method: string, params: unknown): AcpRequestPresentation | undefined
/** The agent's own notification that a URL request it raised finished, carrying `elicitationId`. */
elicitationComplete?(method: string): boolean
settleRequest?(method: string, params: unknown): AcpRequestSettlement | undefined
promptErrorDetail?(error: AcpAgentError): string | undefined
promptFailure?(
@@ -244,6 +244,7 @@ export const GROK_ACP_DIALECT: AcpDialect = {
return parsed.success ? parsed.data['x.ai/tool'].name : undefined
},
request: grokRequest,
elicitationComplete: (method) => method.replace(/^_/, '') === 'x.ai/mcp/elicit_complete',
settleRequest: grokSettleRequest,
toolBackgroundTasks: grokToolBackgroundTasks,
toolSubagents: grokToolSubagents,
@@ -4,6 +4,8 @@ import {
legacyAgentSessionQuestionAnswers
} from '../../../shared/agent-session/agent-session-question-answer'
import { AcpRpcError } from '../transport/acp-errors'
import { acpFormElicitationPresentation } from '../requests/acp-form-elicitation'
import { acpUrlElicitationPresentation } from '../requests/acp-url-elicitation'
import {
pendingAcpResolution,
type AcpRequestPresentation,
@@ -101,6 +103,32 @@ function questionRequest(params: unknown): AcpRequestPresentation {
}
}
const mcpElicitSchema = z.looseObject({ serverName: z.string(), message: z.string() })
const formReplySchema = z.object({ action: z.string(), content: z.unknown().optional() })
/** An MCP server's `elicitation/create` that Grok forwards: a URL to open, or a form to fill. */
function mcpElicitRequest(params: unknown): AcpRequestPresentation {
const parsed = mcpElicitSchema.safeParse(params)
if (!parsed.success) {
throw new AcpRpcError(-32602, 'Invalid MCP elicitation request')
}
const { serverName, message } = parsed.data
// Name the server, since the request is its, not Grok's.
const named = { ...parsed.data, message: serverName ? `${serverName}: ${message}` : message }
if (parsed.data.mode === 'url') {
return acpUrlElicitationPresentation(named, (action) => ({ outcome: action }))
}
const form = acpFormElicitationPresentation(named)
return {
...form,
// Grok reads the same answer under `outcome` rather than ACP's `action`.
reply: (response) => {
const { action, content } = formReplySchema.parse(form.reply(response))
return { outcome: action, ...(content === undefined ? {} : { content }) }
}
}
}
const PLAN_SHOWN_FEEDBACK =
'Orca showed your plan to the user. Stop here and wait for their feedback or a request to implement it in a later turn.'
@@ -129,5 +157,8 @@ export function grokRequest(method: string, params: unknown): AcpRequestPresenta
if (['_x.ai/ask_user_question', 'x.ai/ask_user_question'].includes(method)) {
return questionRequest(params)
}
if (['_x.ai/mcp/elicit', 'x.ai/mcp/elicit'].includes(method)) {
return mcpElicitRequest(params)
}
return undefined
}
@@ -117,7 +117,12 @@ export class AcpStructuredPrompts {
}
entry.settle(reply)
// Release the timeline's hold; withdrawal keeps the committed answer.
this.lane()?.apply([{ type: 'request.withdrawn', request: entry.key }])
const lane = this.lane()
lane?.apply([
{ type: 'request.withdrawn', request: entry.key },
// A URL request's completion that arrived before the answer was saved applies now.
...lane.translator.elicitations.answered(entry.key)
])
if (entry.permission && entry.signal.aborted) {
// Protocol cancellation already replied while the permission answer was being saved.
throw new Error(`the agent stopped waiting for the answer to ${input.itemId}`)
@@ -8,6 +8,7 @@ import {
import type { AcpToolTimeline } from '../timeline/acp-tool-timeline'
import { AcpRpcError } from '../transport/acp-errors'
import { ACP_FORM_ELICITATION_METHOD, acpFormElicitationPresentation } from './acp-form-elicitation'
import { acpUrlElicitationPresentation, isAcpUrlElicitation } from './acp-url-elicitation'
import { readAcpPermissionRequest } from '../protocol/acp-permission-requests'
import { isAgentJournalPromptIntent } from '../../../shared/agent-session/journal/agent-session-journal-types'
@@ -107,7 +108,11 @@ export function translateAcpRequest(
const presentation =
options.dialect.request?.(method, params) ??
(method === 'session/request_permission' ? acpPermissionPresentation(params) : undefined) ??
(method === ACP_FORM_ELICITATION_METHOD ? acpFormElicitationPresentation(params) : undefined)
(method === ACP_FORM_ELICITATION_METHOD
? isAcpUrlElicitation(params)
? acpUrlElicitationPresentation(params)
: acpFormElicitationPresentation(params)
: undefined)
if (!presentation) {
// OpenCode 1.x repeats completed writes through unadvertised client methods; omit their rows.
if (UNADVERTISED_CLIENT_METHOD.test(method)) {
@@ -0,0 +1,155 @@
import { z } from 'zod'
import { BoundedMap } from '../../../shared/collections/bounded-map'
import type { AgentJournalUrlApprovalSubject } from '../../../shared/agent-session/journal/agent-session-journal-types'
import type { ProviderTimelineEvent } from '../../native-chat/agent-session-timeline/provider-timeline-event'
import {
isUrlApprovalSubject,
readApprovalUrl,
URL_APPROVAL_DECLINE_OPTION_ID,
URL_APPROVAL_OPEN_OPTION_ID
} from '../../../shared/agent-session/agent-session-approval-subject'
import {
pendingAcpResolution,
type AcpDialect,
type AcpRequestPresentation
} from '../acp-dialects/acp-dialect'
import { AcpRpcError } from '../transport/acp-errors'
import type { ClientCapabilities } from '../generated/acp-protocol.generated'
// Longer than any sign-in link; a URL the card cannot show whole is refused.
const MAX_URL_LENGTH = 8 * 1024
const urlSchema = z.object({
mode: z.literal('url'),
message: z.string(),
elicitationId: z.string().min(1),
url: z.string().max(MAX_URL_LENGTH)
})
const completeSchema = z.object({ elicitationId: z.string().min(1) })
export function isAcpUrlElicitation(params: unknown): boolean {
return z.object({ mode: z.literal('url') }).safeParse(params).success
}
type AcpChatCapabilities = Pick<ClientCapabilities, 'elicitation' | '_meta'>
export function withAcpUrlElicitation(capabilities?: AcpChatCapabilities): AcpChatCapabilities {
return { ...capabilities, elicitation: { ...capabilities?.elicitation, url: {} } }
}
type UrlRequestAction = 'accept' | 'decline' | 'cancel'
/** A page the agent asks the person to open, such as an MCP server's sign-in. Only http(s) is shown.
* `answer` writes the action in the agent's reply shape; ACP's is `{ action }`. */
export function acpUrlElicitationPresentation(
params: unknown,
answer: (action: UrlRequestAction) => unknown = (action) => ({ action })
): AcpRequestPresentation & { elicitationId: string } {
const parsed = urlSchema.safeParse(params)
const url = parsed.success ? readApprovalUrl(parsed.data.url) : null
if (!parsed.success || !url) {
throw new AcpRpcError(-32602, 'Unsupported ACP elicitation URL')
}
const { message, elicitationId } = parsed.data
return {
elicitationId,
body: {
kind: 'approval',
title: 'Sign-in requested',
...(message.trim() ? { description: message } : {}),
subject: { kind: 'url', url: url.href },
// Another agent must not consent to a person's sign-in.
personOnly: true,
detail: null,
options: [
{ id: URL_APPROVAL_OPEN_OPTION_ID, label: 'Open sign-in page' },
{ id: URL_APPROVAL_DECLINE_OPTION_ID, label: 'Decline' }
],
resolution: pendingAcpResolution
},
// `accept` means the person opened the page, not that the work there finished.
reply: (response) => {
if (response === null) {
return answer('cancel')
}
if (response.kind === 'option' && response.optionId === URL_APPROVAL_OPEN_OPTION_ID) {
return answer('accept')
}
if (response.kind === 'option' && response.optionId === URL_APPROVAL_DECLINE_OPTION_ID) {
return answer('decline')
}
throw new AcpRpcError(-32602, 'URL request answer must open or decline')
}
}
}
type TrackedUrlRequest = {
request: string
subject: AgentJournalUrlApprovalSubject
answered: boolean
completedAt?: number
}
/** URL requests by elicitation ID, until the agent reports them finished and the person has answered. */
export class AcpUrlElicitations {
private readonly open = new BoundedMap<string, TrackedUrlRequest>({ maxEntries: 64 })
track<
T extends { events: readonly ProviderTimelineEvent[]; presentation?: AcpRequestPresentation }
>(translated: T): T {
const elicitationId = translated.presentation?.elicitationId
const opened = translated.events.find((event) => event.type === 'request.open')
if (
elicitationId &&
opened?.type === 'request.open' &&
opened.body.kind === 'approval' &&
isUrlApprovalSubject(opened.body.subject)
) {
this.open.set(elicitationId, {
request: opened.request,
subject: opened.body.subject,
answered: false
})
}
return translated
}
/** ACP's completion, or the agent's own name for it. */
completes(method: string, dialect: AcpDialect): boolean {
return method === 'elicitation/complete' || dialect.elicitationComplete?.(method) === true
}
/** Unknown and already-finished IDs are ignored, as the protocol requires. */
complete(params: unknown, at: number): ProviderTimelineEvent[] {
const parsed = completeSchema.safeParse(params)
const entry = parsed.success ? this.open.get(parsed.data.elicitationId) : undefined
if (!parsed.success || !entry || entry.completedAt !== undefined) {
return []
}
entry.completedAt = at
// Before the answer is saved the card is still pending; `answered` writes it then.
return entry.answered ? this.finish(parsed.data.elicitationId, entry) : []
}
/** The person's answer to `request` is saved; a completion that came first now applies. */
answered(request: string): ProviderTimelineEvent[] {
for (const [elicitationId, entry] of this.open.entries()) {
if (entry.request === request) {
entry.answered = true
return entry.completedAt === undefined ? [] : this.finish(elicitationId, entry)
}
}
return []
}
private finish(elicitationId: string, entry: TrackedUrlRequest): ProviderTimelineEvent[] {
this.open.delete(elicitationId)
return [
{
type: 'request.subject',
request: entry.request,
subject: { ...entry.subject, completedAt: entry.completedAt }
}
]
}
}
@@ -21,6 +21,7 @@ import { prepareAcpStructuredLaunch } from '../launch/acp-structured-launch-prep
import { AcpStructuredOptions } from '../options/acp-structured-options'
import { acpLaunchPermissionModes } from '../launch/acp-launch-permission-modes'
import { AcpStructuredPrompts } from '../requests/acp-structured-prompts'
import { withAcpUrlElicitation } from '../requests/acp-url-elicitation'
import { AcpLoadHistory } from '../history/acp-history-replay'
import { asReattachHistory } from '../history/acp-reattach-history'
import { routeAcpSessionEvent } from '../timeline/acp-session-event-routing'
@@ -101,7 +102,8 @@ export async function acquireAcpStructuredSession(input: {
},
{
clientInfo: { name: 'orca', version: '1' },
clientCapabilities: spec.dialect.clientCapabilities,
// Only a chat can show a URL request's card, so other connections never advertise it.
clientCapabilities: withAcpUrlElicitation(spec.dialect.clientCapabilities),
retryBusyPrompts: spec.agent === 'omp',
...(spec.signIn ? { signIn: spec.signIn } : {}),
onPermission: (request, context) => {
@@ -0,0 +1,202 @@
import { afterEach, describe, expect, it } from 'vitest'
import { parseAgentJournalItemKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key'
import type { AgentSessionPromptResponse } from '../../../shared/agent-session/agent-session-question-answer'
import {
closeProviderTimelineRigs,
SESSION
} from '../../native-chat/agent-session-timeline/provider-timeline-assembler-test-support'
import {
openAcpAdapterRig,
PROVIDER_SESSION,
sendHello,
waitFor,
type AcpAdapterRig
} from './testing/acp-structured-adapter.test-support'
afterEach(async () => {
await closeProviderTimelineRigs()
})
const URL = 'https://linear.app/oauth?x=1'
const signIn = (url: string) => ({
sessionId: PROVIDER_SESSION,
mode: 'url',
elicitationId: 'linear-oauth-1',
url,
message: 'Authorize access to the Linear MCP server.'
})
// What Grok sends when an MCP server it runs asks for a URL or a form.
const grokElicit = (fields: Record<string, unknown>) => ({
sessionId: PROVIDER_SESSION,
toolCallId: 'mcp-elicit-1',
serverName: 'linear',
message: 'Authorize access',
...fields
})
async function promptingRig(): Promise<AcpAdapterRig> {
const rig = await openAcpAdapterRig()
await rig.acquire()
await sendHello(rig, 'send-1')
await rig.frame('session/prompt')
return rig
}
async function promptRow(rig: AcpAdapterRig, kind: 'approval' | 'question') {
return waitFor(async () => {
const row = (await rig.rig.rows()).find((item) => item.body.kind === kind)
expect(row).toBeDefined()
return row!
})
}
/** Answer as the host does: save the resolution, then reply to the agent. */
async function answer(
rig: AcpAdapterRig,
row: Awaited<ReturnType<typeof promptRow>>,
response: AgentSessionPromptResponse,
selectedOptionId: string
): Promise<void> {
const body = row.body
if (body.kind !== 'approval' && body.kind !== 'question') {
throw new Error('expected a prompt row')
}
await rig.adapter.answerPrompt({
sessionId: SESSION,
itemId: row.itemId,
kind: body.kind,
response,
fence: 1,
commit: async () => {
await rig.rig.journal.appendItem(
parseAgentJournalItemKey(row.itemId)!,
{
...body,
resolution: {
state: 'resolved',
selectedOptionId,
resolvedBy: 'desktop-renderer',
resolvedAt: 5_000
}
},
{ fence: 1, turnScope: row.turnScope! }
)
}
})
}
const open: AgentSessionPromptResponse = { kind: 'option', optionId: 'open' }
describe('ACP URL elicitation', () => {
it('opens a card, accepts once the person opens the page, and marks it finished on complete', async () => {
const rig = await promptingRig()
expect((await rig.frame('initialize')).params).toMatchObject({
clientCapabilities: { elicitation: { url: {} } }
})
const { agent } = rig.child()
const reply = agent.request(9, 'elicitation/create', signIn(URL))
const row = await promptRow(rig, 'approval')
expect(row.body).toMatchObject({
kind: 'approval',
description: 'Authorize access to the Linear MCP server.',
subject: { kind: 'url', url: URL },
personOnly: true,
options: [{ id: 'open' }, { id: 'decline' }],
resolution: { state: 'pending' }
})
await answer(rig, row, open, 'open')
expect((await reply).result).toEqual({ action: 'accept' })
agent.notify('elicitation/complete', { elicitationId: 'unknown-id' })
agent.notify('elicitation/complete', { elicitationId: 'linear-oauth-1' })
await waitFor(async () => {
expect((await rig.rig.row(row.itemId))?.body).toMatchObject({
subject: { kind: 'url', url: URL, completedAt: 5_000 },
resolution: { state: 'resolved', selectedOptionId: 'open' }
})
})
})
it('marks it finished when the agent completes it before the answer is saved', async () => {
const rig = await promptingRig()
const { agent } = rig.child()
const reply = agent.request(9, 'elicitation/create', signIn(URL))
const row = await promptRow(rig, 'approval')
agent.notify('elicitation/complete', { elicitationId: 'linear-oauth-1' })
await rig.settle()
await answer(rig, row, open, 'open')
expect((await reply).result).toEqual({ action: 'accept' })
await waitFor(async () => {
expect((await rig.rig.row(row.itemId))?.body).toMatchObject({
subject: { kind: 'url', url: URL, completedAt: 5_000 },
resolution: { state: 'resolved', selectedOptionId: 'open' }
})
})
})
it('refuses a URL that is not http(s) without showing a card', async () => {
const rig = await promptingRig()
const reply = await rig
.child()
.agent.request(9, 'elicitation/create', signIn('javascript:alert(1)'))
expect(reply.error).toMatchObject({ code: -32602 })
await rig.settle()
expect((await rig.rig.rows()).some((item) => item.body.kind === 'approval')).toBe(false)
})
})
describe("Grok's forwarded MCP elicitation", () => {
it('shows a URL request on the sign-in card, answers in Grok’s shape, and finishes on its complete', async () => {
const rig = await promptingRig()
const { agent } = rig.child()
const reply = agent.request(
9,
'_x.ai/mcp/elicit',
grokElicit({ mode: 'url', url: URL, elicitationId: 'el-1' })
)
const row = await promptRow(rig, 'approval')
expect(row.body).toMatchObject({
description: 'linear: Authorize access',
subject: { kind: 'url', url: URL }
})
await answer(rig, row, open, 'open')
expect((await reply).result).toEqual({ outcome: 'accept' })
agent.notify('_x.ai/mcp/elicit_complete', {
sessionId: PROVIDER_SESSION,
elicitationId: 'el-1',
serverName: 'linear'
})
await waitFor(async () => {
expect((await rig.rig.row(row.itemId))?.body).toMatchObject({
subject: { kind: 'url', completedAt: 5_000 }
})
})
})
it('asks a form request on the question card and returns its content under outcome', async () => {
const rig = await promptingRig()
const reply = rig.child().agent.request(
9,
'_x.ai/mcp/elicit',
grokElicit({
mode: 'form',
message: 'Which team?',
requestedSchema: {
type: 'object',
properties: { team: { type: 'string', enum: ['Core', 'Mobile'] } },
required: ['team']
}
})
)
const row = await promptRow(rig, 'question')
expect(row.body).toMatchObject({ question: 'linear: Which team?' })
await answer(
rig,
row,
{ kind: 'answers', answers: [{ questionId: 'q1', optionIds: ['o2'] }] },
'o2'
)
expect((await reply).result).toEqual({ outcome: 'accept', content: { team: 'Mobile' } })
})
})
@@ -16,6 +16,7 @@ import type { AcpAgentError } from '../transport/acp-errors'
import { acpTurnEndEvents, AcpPromptTurns } from './acp-prompt-turns'
import { translateAcpRequest } from '../requests/acp-timeline-requests'
import { AcpUrlElicitations } from '../requests/acp-url-elicitation'
import { ACP_SUBSTANTIVE_UPDATES, acpSessionUpdate } from './acp-session-update'
import { AcpSubagents } from './acp-subagents'
import { AcpChildSessions } from './acp-child-sessions'
@@ -45,6 +46,7 @@ export class AcpTimelineTranslator {
readonly children: AcpChildSessions
private readonly ownership: AcpTimelineOwnership
private readonly started = new BoundedMap<string, true>({ maxEntries: 128 })
readonly elicitations = new AcpUrlElicitations()
private readonly failures: AcpTurnFailures
private loading = false
private readonly context = new AcpContextTimeline()
@@ -163,6 +165,9 @@ export class AcpTimelineTranslator {
if (this.ownership.disposed) {
return []
}
if (this.elicitations.completes(method, this.dialect)) {
return this.elicitations.complete(params, at)
}
const extension = this.dialect.notification?.(method, params, at)
const open = this.prompts.current?.opened ? this.prompts.current.turn : this.activeTurn
const child = this.children.notification(method, params, extension, this.loading, open, at)
@@ -268,11 +273,13 @@ export class AcpTimelineTranslator {
params: unknown,
id: string | number
): ReturnType<typeof translateAcpRequest> {
return translateAcpRequest(method, params, id, {
sessionId: this.options.sessionId,
dialect: this.dialect,
tools: this.ownership.tools
})
return this.elicitations.track(
translateAcpRequest(method, params, id, {
sessionId: this.options.sessionId,
dialect: this.dialect,
tools: this.ownership.tools
})
)
}
// Write failure reasons before ending the turn so their rows join it.
@@ -192,6 +192,7 @@ export function createProviderTimelineAssembler(
case 'item.close':
case 'request.open':
case 'request.withdrawn':
case 'request.subject':
case 'context.usage':
case 'provider.frame':
case 'session.ended':
@@ -10,6 +10,7 @@ import {
decideFrame,
decideItem,
decideRequest,
decideRequestSubject,
decideWithdrawal
} from './provider-timeline-item-decisions'
import type { ProviderTimelineTurnRef } from './provider-timeline-rows'
@@ -96,6 +97,8 @@ export function decideProviderTimelineEvent(
return decideRequest(input, event)
case 'request.withdrawn':
return decideWithdrawal(input, event)
case 'request.subject':
return decideRequestSubject(input, event)
case 'context.usage':
return decideContextUsage(input, event)
case 'provider.frame':
@@ -6,6 +6,7 @@
import type { AgentSessionContextUsage } from '../../../shared/agent-session/agent-session-context-usage'
import type {
AgentJournalApprovalItem,
AgentJournalApprovalSubject,
AgentJournalItemBody,
AgentJournalProducerLinkage,
AgentJournalQuestionItem
@@ -95,6 +96,8 @@ export type ProviderTimelineEvent =
Joined)
/** Withdraw only unanswered requests. */
| { type: 'request.withdrawn'; request: string }
/** Replace an answered approval's subject, keeping the answer; unanswered requests stay as they are. */
| { type: 'request.subject'; request: string; subject: AgentJournalApprovalSubject }
/** Use the named turn, otherwise open turn, otherwise last turn. */
| ({ type: 'context.usage'; usage: AgentSessionContextUsage } & Joined)
| { type: 'activity'; text: string | null }
@@ -120,6 +120,23 @@ export function decideRequest(
}
}
/** The writer revises the newest incarnation only once it is answered. */
export function decideRequestSubject(
input: ProviderTimelineDecisionInput,
event: Extract<ProviderTimelineDecidedEvent, { type: 'request.subject' }>
): ProviderTimelineDecision {
return {
settle: {
what: 'request-subject',
resolution: {
kind: 'request-subject',
request: providerTimelineRequest(input.context, event.request),
subject: event.subject
}
}
}
}
/** The writer withdraws the newest incarnation only while it is still pending. */
export function decideWithdrawal(
input: ProviderTimelineDecisionInput,
@@ -3,6 +3,7 @@
import { agentJournalItemKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key'
import {
AGENT_JOURNAL_THREAD_SCOPE,
type AgentJournalApprovalSubject,
type AgentJournalItemBody
} from '../../../shared/agent-session/journal/agent-session-journal-types'
import type { AgentJournalItemIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity'
@@ -61,6 +62,11 @@ export type ProviderTimelineSettlementResolution =
keep: readonly ProviderTimelineRequest[]
}
| { kind: 'request-withdrawn'; request: ProviderTimelineRequest }
| {
kind: 'request-subject'
request: ProviderTimelineRequest
subject: AgentJournalApprovalSubject
}
/** Lifecycle writers own lifecycle fields; preserve the rest of each turn row. */
| {
kind: 'turn-revisions'
@@ -205,6 +211,22 @@ export function resolveProviderTimelineSettlement(
]
: []
}
if (resolution.kind === 'request-subject') {
const { held } = providerTimelineRequestRows(resolution.request, view.itemBody)
const item = held ? view.item(held.itemId) : null
// A revision while pending would make the person's answer stale.
if (!held || item?.body.kind !== 'approval' || item.body.resolution.state === 'pending') {
return []
}
return [
{
kind: 'item',
identity: held.identity,
body: { ...item.body, subject: resolution.subject },
turnScope: item.turnScope ?? AGENT_JOURNAL_THREAD_SCOPE
}
]
}
const { ending } = resolution
const keep = new Set<string>()
for (const request of resolution.keep) {
@@ -9,12 +9,17 @@ import { NativeChatMarkdown } from '../markdown/NativeChatMarkdown'
import { approvalBlockedPathToShow } from '../../../../../shared/agent-session/agent-session-approval-blocked-path'
import {
isNewerApprovalSubject,
isPlanApprovalSubject
isPlanApprovalSubject,
isUrlApprovalSubject,
readApprovalUrl,
URL_APPROVAL_DECLINE_OPTION_ID,
URL_APPROVAL_OPEN_OPTION_ID
} from '../../../../../shared/agent-session/agent-session-approval-subject'
import { NativeChatCodeBlock } from '../markdown/code/NativeChatCodeBlock'
import type { ChatApproval } from '../../../../../shared/native-chat/input/native-chat-interactive-prompt'
import { NativeChatPromptCollapseToggle } from './NativeChatPromptCollapse'
import { useNativeChatPromptCardFocus } from './use-native-chat-prompt-card-focus'
import { NativeChatUrlTarget, openUrlRequestPage } from './NativeChatUrlRequest'
export type NativeChatApprovalCardProps = {
approval: ChatApproval
@@ -59,6 +64,20 @@ export function NativeChatApprovalCard({
const neededPath = approvalBlockedPathToShow(approval)
// A newer Orca's subject: its detail is shown, and only the card's cancel answers.
const newerSubject = isNewerApprovalSubject(approval.subject)
// A page to open: its option opens it, and the back-out stays quiet.
const url = isUrlApprovalSubject(approval.subject) ? approval.subject.url : null
const title =
url === null
? approval.title
: t('components.native-chat.urlRequest.title', 'Sign-in requested')
const optionLabel = (option: ChatApproval['options'][number]): string =>
url === null
? option.label
: option.send === URL_APPROVAL_OPEN_OPTION_ID
? t('components.native-chat.urlRequest.open', 'Open sign-in page')
: option.send === URL_APPROVAL_DECLINE_OPTION_ID
? t('components.native-chat.urlRequest.decline', 'Decline')
: option.label
const stacked = placement === 'stacked'
const hasContext = Boolean(
countdown ||
@@ -85,7 +104,7 @@ export function NativeChatApprovalCard({
data-native-chat-prompt-card-focus={shouldFocus || undefined}
data-native-chat-approval-card="true"
role="group"
aria-label={approval.title}
aria-label={title}
tabIndex={-1}
onKeyDown={(event) => {
if (event.key === 'Escape' && !event.nativeEvent.isComposing && escape) {
@@ -100,7 +119,7 @@ export function NativeChatApprovalCard({
<ShieldQuestion className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
<div className="min-w-0 flex-1">
<p className="line-clamp-2 break-words text-sm font-semibold text-foreground">
{approval.title}
{title}
</p>
{worker ? (
<p className="mt-0.5 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">
@@ -182,6 +201,8 @@ export function NativeChatApprovalCard({
</p>
) : null}
</div>
) : url !== null ? (
<NativeChatUrlTarget url={url} />
) : approval.detail ? (
<NativeChatApprovalDetail
detail={approval.detail}
@@ -199,29 +220,41 @@ export function NativeChatApprovalCard({
</div>
) : null}
<div data-native-chat-approval-actions="true" className="flex shrink-0 flex-wrap gap-2">
{approval.options.map((opt, i) => (
<button
key={`${opt.label}-${i}`}
type="button"
disabled={newerSubject || isSubmitting}
onClick={() => onChoose(opt.send)}
className={cn(
'rounded-md px-4 py-1.5 text-sm font-semibold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50',
i === 0 && !approval.neutralOptions
? 'bg-primary text-primary-foreground hover:bg-primary/90'
: 'border border-border bg-background text-foreground hover:bg-accent hover:text-accent-foreground'
)}
>
{isSubmitting && opt.send === submittingOption ? (
<span className="inline-flex items-center gap-1.5">
<Loader2 className="size-3.5 animate-spin" aria-hidden />
{opt.label}
</span>
) : (
opt.label
)}
</button>
))}
{approval.options.map((opt, i) => {
const opensUrl = url !== null && opt.send === URL_APPROVAL_OPEN_OPTION_ID
return (
<button
key={`${opt.label}-${i}`}
type="button"
disabled={
newerSubject || isSubmitting || (opensUrl && readApprovalUrl(url) === null)
}
onClick={() => {
if (opensUrl) {
openUrlRequestPage(url)
}
onChoose(opt.send)
}}
className={cn(
'rounded-md px-4 py-1.5 text-sm font-semibold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50',
i === 0 && !approval.neutralOptions
? 'bg-primary text-primary-foreground hover:bg-primary/90'
: url !== null
? 'text-muted-foreground hover:bg-accent hover:text-accent-foreground'
: 'border border-border bg-background text-foreground hover:bg-accent hover:text-accent-foreground'
)}
>
{isSubmitting && opt.send === submittingOption ? (
<span className="inline-flex items-center gap-1.5">
<Loader2 className="size-3.5 animate-spin" aria-hidden />
{optionLabel(opt)}
</span>
) : (
optionLabel(opt)
)}
</button>
)
})}
{approval.options.length === 0 && onOpenTerminal ? (
<button
type="button"
@@ -2,6 +2,8 @@ import { NativeChatQuestionText } from './NativeChatQuestionText'
import { useTranslate } from '@/i18n/use-translate'
import { NativeChatMessageTimestamp } from '../messages/rows/NativeChatMessageTimestamp'
import { NativeChatAwaitingInputRow } from './NativeChatAwaitingInputRow'
import { NativeChatUrlRequestReceipt } from './NativeChatUrlRequest'
import { urlApprovalProgress } from '../../../../../shared/agent-session/agent-session-approval-subject'
import {
NATIVE_CHAT_RECEIPT_COPY,
nativeChatReceiptAnswerHeading,
@@ -37,6 +39,10 @@ export function NativeChatResolutionReceipt({
/>
) : null
}
const urlProgress = body.kind === 'approval' ? urlApprovalProgress(body) : null
if (body.kind === 'approval' && urlProgress) {
return <NativeChatUrlRequestReceipt body={body} {...urlProgress} />
}
const { resolution } = body
const device = nativeChatReceiptDevice(resolution, {
current: t('components.native-chat.receipt.thisComputer', 'this computer'),
@@ -0,0 +1,63 @@
import { defineFixture } from '../../../component-fixtures/component-fixture'
import type { AgentJournalApprovalItem } from '../../../../../shared/agent-session/journal/agent-session-journal-types'
import { chatApprovalFromJournal } from '../../../../../shared/native-chat/input/native-chat-interactive-prompt'
import { NativeChatApprovalCard } from './NativeChatApprovalCard'
import { NativeChatResolutionReceipt } from './NativeChatResolutionReceipt'
const url = 'https://linear.app/oauth/authorize?client_id=orca-mcp&response_type=code&state=4f2a9c'
const request: AgentJournalApprovalItem = {
kind: 'approval',
title: 'Sign-in requested',
description: 'Authorize access to the Linear MCP server.',
subject: { kind: 'url', url },
personOnly: true,
detail: null,
options: [
{ id: 'open', label: 'Open sign-in page' },
{ id: 'decline', label: 'Decline' }
],
resolution: { state: 'pending', selectedOptionId: null, resolvedBy: null, resolvedAt: null }
}
const opened: AgentJournalApprovalItem = {
...request,
resolution: {
state: 'resolved',
selectedOptionId: 'open',
resolvedBy: 'desktop-renderer',
resolvedAt: 1_700_000_000_000
}
}
export const open = defineFixture({
width: 720,
render: () => (
<NativeChatApprovalCard approval={chatApprovalFromJournal(request)} onChoose={() => {}} />
)
})
export const narrowOpen = defineFixture({ ...open, width: 360 })
export const waiting = defineFixture({
width: 720,
render: () => <NativeChatResolutionReceipt body={opened} />
})
export const finished = defineFixture({
width: 720,
render: () => (
<NativeChatResolutionReceipt
body={{ ...opened, subject: { kind: 'url', url, completedAt: 1_700_000_060_000 } }}
/>
)
})
export const declined = defineFixture({
width: 720,
render: () => (
<NativeChatResolutionReceipt
body={{ ...opened, resolution: { ...opened.resolution, selectedOptionId: 'decline' } }}
/>
)
})
@@ -0,0 +1,89 @@
import { useTranslate } from '@/i18n/use-translate'
import { Button } from '@/components/ui/button'
import { openAppHttpLink } from '@/lib/browser/navigation/app-http-link-open'
import { readApprovalUrl } from '../../../../../shared/agent-session/agent-session-approval-subject'
import type {
AgentJournalApprovalItem,
AgentJournalUrlApprovalSubject
} from '../../../../../shared/agent-session/journal/agent-session-journal-types'
/** Opens only in the system browser, outside anything Orca or an agent can read. */
export function openUrlRequestPage(url: string): void {
const target = readApprovalUrl(url)
if (target) {
openAppHttpLink(target.href, { destination: 'system' })
}
}
/** Where the page goes: its host to judge it by, then the whole link. */
export function NativeChatUrlTarget({ url }: { url: string }): React.JSX.Element | null {
const target = readApprovalUrl(url)
if (!target) {
return null
}
return (
<div data-native-chat-url-target="true" className="min-w-0 space-y-0.5 font-mono">
<p className="truncate text-xs text-foreground">{target.host}</p>
<p className="break-all text-2xs text-muted-foreground">{target.href}</p>
</div>
)
}
/** An opened URL request in the transcript: waiting on the agent, or finished. */
export function NativeChatUrlRequestReceipt({
body,
subject,
finished
}: {
body: AgentJournalApprovalItem
subject: AgentJournalUrlApprovalSubject
finished: boolean
}): React.JSX.Element {
const t = useTranslate()
if (finished) {
return (
<div
data-native-chat-receipt="url-finished"
className="truncate rounded-lg border border-input bg-card px-3 py-2 text-xs text-muted-foreground"
>
{body.description
? t('components.native-chat.urlRequest.finishedWith', 'Sign-in finished · {{message}}', {
message: body.description
})
: t('components.native-chat.urlRequest.finished', 'Sign-in finished')}
</div>
)
}
const target = readApprovalUrl(subject.url)
return (
<div
data-native-chat-receipt="url-opened"
className="space-y-1 rounded-lg border border-input bg-card px-4 py-3"
>
<p className="text-sm font-semibold text-foreground">
{t('components.native-chat.urlRequest.title', 'Sign-in requested')}
</p>
{body.description ? (
<p className="whitespace-pre-wrap break-words text-sm text-muted-foreground">
{body.description}
</p>
) : null}
{target ? (
<p className="truncate font-mono text-xs text-muted-foreground">{target.host}</p>
) : null}
<div className="flex flex-wrap items-center gap-2 pt-1">
<span className="text-xs text-muted-foreground">
{t(
'components.native-chat.urlRequest.opened',
'Opened the sign-in page in your browser.'
)}
</span>
{target ? (
<Button variant="ghost" size="xs" onClick={() => openUrlRequestPage(target.href)}>
{t('components.native-chat.urlRequest.openAgain', 'Open again')}
</Button>
) : null}
</div>
</div>
)
}
+9
View File
@@ -21646,6 +21646,15 @@
"questionNotSentDetail": "Your question is still in this chat. Send /btw again to retry.",
"questionUnconfirmed": "{{agent}} couldn't confirm the side chat got your question",
"questionUnconfirmedDetail": "Check the side chat before asking again. Your question is still in this chat."
},
"urlRequest": {
"title": "Sign-in requested",
"open": "Open sign-in page",
"decline": "Decline",
"opened": "Opened the sign-in page in your browser.",
"openAgain": "Open again",
"finished": "Sign-in finished",
"finishedWith": "Sign-in finished · {{message}}"
}
},
"tab": {
@@ -1,13 +1,19 @@
// Preserve unknown newer-host subjects and show detail, but permit only Cancel because this build cannot display what approval means. Claude denies and continues; Codex ends the turn.
import type {
AgentJournalApprovalItem,
AgentJournalApprovalSubject,
AgentJournalItemBody,
AgentJournalPlanApprovalSubject
AgentJournalPlanApprovalSubject,
AgentJournalUrlApprovalSubject
} from './journal/agent-session-journal-types'
/** Schema-independent readers share this supported-kind set; a test keeps it aligned with the schema. */
export const DRAWN_APPROVAL_SUBJECT_KINDS: ReadonlySet<string> = new Set(['plan'])
export const DRAWN_APPROVAL_SUBJECT_KINDS: ReadonlySet<string> = new Set(['plan', 'url'])
/** The options a URL approval offers. Choosing `open` means the person opened the page. */
export const URL_APPROVAL_OPEN_OPTION_ID = 'open'
export const URL_APPROVAL_DECLINE_OPTION_ID = 'decline'
export function isPlanApprovalSubject(
subject: AgentJournalApprovalSubject | undefined
@@ -15,6 +21,37 @@ export function isPlanApprovalSubject(
return subject?.kind === 'plan'
}
export function isUrlApprovalSubject(
subject: AgentJournalApprovalSubject | undefined
): subject is AgentJournalUrlApprovalSubject {
return subject?.kind === 'url'
}
/** The http(s) URL to open and the host to show for it; null for anything else, which is never opened. */
export function readApprovalUrl(url: string): { href: string; host: string } | null {
let parsed: URL
try {
parsed = new URL(url)
} catch {
return null
}
// `host` is the punycode form, so a look-alike domain shows as what it really is.
return (parsed.protocol === 'https:' || parsed.protocol === 'http:') && parsed.host
? { href: parsed.href, host: parsed.host }
: null
}
/** Where a URL approval stands once answered: the page was opened, and maybe finished. */
export function urlApprovalProgress(
body: AgentJournalApprovalItem
): { subject: AgentJournalUrlApprovalSubject; finished: boolean } | null {
return isUrlApprovalSubject(body.subject) &&
body.resolution.state === 'resolved' &&
body.resolution.selectedOptionId === URL_APPROVAL_OPEN_OPTION_ID
? { subject: body.subject, finished: body.subject.completedAt !== undefined }
: null
}
export function isNewerApprovalSubject(subject: { kind: string } | undefined): boolean {
return subject !== undefined && !DRAWN_APPROVAL_SUBJECT_KINDS.has(subject.kind)
}
@@ -0,0 +1,15 @@
import * as z from 'zod'
import { knownTags, openDiscriminatedUnion } from './agent-session-journal-open-union'
const KnownApprovalSubject = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('plan'), text: z.string().min(1), filePath: z.string().optional() }),
z.object({
kind: z.literal('url'),
url: z.string().min(1),
completedAt: z.number().finite().optional()
})
])
export const AGENT_JOURNAL_APPROVAL_SUBJECT_KINDS = knownTags(KnownApprovalSubject)
/** Open like blocks; a subject this build cannot draw is never approvable here
* (agent-session-approval-subject.ts). */
export const AgentJournalApprovalSubjectSchema = openDiscriminatedUnion(KnownApprovalSubject)
@@ -1,4 +1,4 @@
/** What an approval prompt asks about, beyond its tool call: the ask rule that forced it, or a plan. */
/** What an approval prompt asks about, beyond its tool call: the ask rule that forced it, a plan, or a page to open. */
export type AgentJournalApprovalMatchedAskRule = {
source: string
toolName: string
@@ -11,6 +11,14 @@ export type AgentJournalPlanApprovalSubject = {
filePath?: string
}
/** A page the agent asks the person to open outside Orca, such as an MCP server's sign-in. Only
* http(s) URLs are written. `completedAt` is set once the agent reports the page's work finished. */
export type AgentJournalUrlApprovalSubject = {
kind: 'url'
url: string
completedAt?: number
}
declare const agentJournalUnknownKind: unique symbol
/** A kind tag this build does not know. Branded, so it never stands in for a known tag. */
export type AgentJournalUnknownKind = string & { readonly [agentJournalUnknownKind]: true }
@@ -22,4 +30,5 @@ export type AgentJournalUnknownApprovalSubject = { readonly kind: AgentJournalUn
/** Open, as the journal schema reads it: narrow with `isPlanApprovalSubject` before reading it. */
export type AgentJournalApprovalSubject =
| AgentJournalPlanApprovalSubject
| AgentJournalUrlApprovalSubject
| AgentJournalUnknownApprovalSubject
@@ -11,6 +11,7 @@ import { AgentJournalThreadGoalStateSchema } from './agent-session-journal-threa
import { AgentSessionFailureFactSchema } from '../failures/agent-session-failure-fact-schema'
import { knownTags, openDiscriminatedUnion } from './agent-session-journal-open-union'
import { SubagentEntry } from './agent-session-journal-subagent-schema'
import { AgentJournalApprovalSubjectSchema } from './agent-session-journal-approval-subject-schema'
import type {
AgentJournalItemBody,
AgentJournalMessageItem,
@@ -158,14 +159,6 @@ const ApprovalMatchedAskRule = z.object({
ruleContent: z.string().optional()
})
const KnownApprovalSubject = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('plan'), text: z.string().min(1), filePath: z.string().optional() })
])
export const AGENT_JOURNAL_APPROVAL_SUBJECT_KINDS = knownTags(KnownApprovalSubject)
/** Open like blocks; a subject this build cannot draw is never approvable here
* (agent-session-approval-subject.ts). */
const ApprovalSubject = openDiscriminatedUnion(KnownApprovalSubject)
const MessageBody = z.object({
kind: z.literal('message'),
role: z.string().min(1),
@@ -228,7 +221,7 @@ const KnownItemBody = z.discriminatedUnion('kind', [
decisionReason: z.string().optional(),
blockedPath: z.string().optional(),
matchedAskRule: ApprovalMatchedAskRule.optional(),
subject: ApprovalSubject.optional(),
subject: AgentJournalApprovalSubjectSchema.optional(),
personOnly: z.literal(true).optional(),
detail: z.string().nullable(),
options: z.array(PromptOption),
@@ -183,6 +183,7 @@ export type {
AgentJournalApprovalMatchedAskRule,
AgentJournalApprovalSubject,
AgentJournalPlanApprovalSubject,
AgentJournalUrlApprovalSubject,
AgentJournalUnknownApprovalSubject,
AgentJournalUnknownKind
} from './agent-session-journal-approval-subject'
@@ -728,6 +728,13 @@
"components.native-chat.prompt.collapse",
"components.native-chat.prompt.expand",
"components.native-chat.question.openTerminal",
"components.native-chat.urlRequest.decline",
"components.native-chat.urlRequest.finished",
"components.native-chat.urlRequest.finishedWith",
"components.native-chat.urlRequest.open",
"components.native-chat.urlRequest.openAgain",
"components.native-chat.urlRequest.opened",
"components.native-chat.urlRequest.title",
"components.native-chat.wrapLines",
"components.newWorkspace.directSetup.askRunDefaultTabs",
"components.newWorkspace.directSetup.askRunSetup",