diff --git a/mobile/src/i18n/en-runtime-required.json b/mobile/src/i18n/en-runtime-required.json index 0e32408735c..2f845dbf111 100644 --- a/mobile/src/i18n/en-runtime-required.json +++ b/mobile/src/i18n/en-runtime-required.json @@ -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", diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index 8f37176bb25..75815ef8817 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -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": { diff --git a/mobile/src/platform/external-links/external-link.ts b/mobile/src/platform/external-links/external-link.ts index 28da3de6bf4..35f36d8d7da 100644 --- a/mobile/src/platform/external-links/external-link.ts +++ b/mobile/src/platform/external-links/external-link.ts @@ -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) => { diff --git a/mobile/src/platform/external-links/external-link.web.ts b/mobile/src/platform/external-links/external-link.web.ts index 71852a8f773..9443971dc19 100644 --- a/mobile/src/platform/external-links/external-link.web.ts +++ b/mobile/src/platform/external-links/external-link.web.ts @@ -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) { diff --git a/mobile/src/session/native-chat/input/prompts/MobileNativeChatPermission.tsx b/mobile/src/session/native-chat/input/prompts/MobileNativeChatPermission.tsx index fc29f6b2187..eb695646552 100644 --- a/mobile/src/session/native-chat/input/prompts/MobileNativeChatPermission.tsx +++ b/mobile/src/session/native-chat/input/prompts/MobileNativeChatPermission.tsx @@ -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 => { if (submittingRef.current) { return @@ -58,7 +78,7 @@ function MobileNativeChatPermissionImpl({ numberOfLines={2} ellipsizeMode="tail" > - {permission.title} + {title} {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 ( [ 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} > - - {option.label} + + {optionLabel(option)} ) @@ -165,6 +203,8 @@ function MobileNativeChatPermissionContext({ ) : null} + ) : isUrlApprovalSubject(permission.subject) ? ( + ) : 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 } })) diff --git a/mobile/src/session/native-chat/input/prompts/MobileNativeChatUrlRequest.tsx b/mobile/src/session/native-chat/input/prompts/MobileNativeChatUrlRequest.tsx new file mode 100644 index 00000000000..83c57b57b5c --- /dev/null +++ b/mobile/src/session/native-chat/input/prompts/MobileNativeChatUrlRequest.tsx @@ -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 ( + + + {target.host} + + + {target.href} + + + ) +} + +/** 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 ( + + + {body.description + ? t('chat.urlRequest.finishedWith', 'Sign-in finished · {{message}}', { + message: body.description + }) + : t('chat.urlRequest.finished', 'Sign-in finished')} + + + ) + } + const target = readApprovalUrl(subject.url) + return ( + + + {t('chat.urlRequest.title', 'Sign-in requested')} + + {body.description ? ( + + {body.description} + + ) : null} + {target ? ( + + {target.host} + + ) : null} + + + {t('chat.urlRequest.opened', 'Opened the sign-in page in your browser.')} + + {target ? ( + openUrlRequestPage(target.href)} + style={({ pressed }) => [styles.again, pressed && styles.pressed]} + > + + {t('chat.urlRequest.openAgain', 'Open again')} + + + ) : null} + + + ) +} + +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 + } +})) diff --git a/mobile/src/session/native-chat/input/prompts/mobile-structured-agent-prompts.ts b/mobile/src/session/native-chat/input/prompts/mobile-structured-agent-prompts.ts index 373dde71b57..28c8f494046 100644 --- a/mobile/src/session/native-chat/input/prompts/mobile-structured-agent-prompts.ts +++ b/mobile/src/session/native-chat/input/prompts/mobile-structured-agent-prompts.ts @@ -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 diff --git a/mobile/src/session/native-chat/transcript/messages/MobileNativeChatResolutionReceipt.tsx b/mobile/src/session/native-chat/transcript/messages/MobileNativeChatResolutionReceipt.tsx index 93952356464..e120c0da95e 100644 --- a/mobile/src/session/native-chat/transcript/messages/MobileNativeChatResolutionReceipt.tsx +++ b/mobile/src/session/native-chat/transcript/messages/MobileNativeChatResolutionReceipt.tsx @@ -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 + } const { resolution } = body const device = nativeChatReceiptDevice(resolution, { current: t('chat.receipt.thisPhone', 'this phone'), diff --git a/src/main/acp/acp-dialects/acp-dialect.ts b/src/main/acp/acp-dialects/acp-dialect.ts index 66169883785..1ecd510aecd 100644 --- a/src/main/acp/acp-dialects/acp-dialect.ts +++ b/src/main/acp/acp-dialects/acp-dialect.ts @@ -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?( diff --git a/src/main/acp/acp-dialects/grok-dialect.ts b/src/main/acp/acp-dialects/grok-dialect.ts index f74a272875c..e77ca0118c9 100644 --- a/src/main/acp/acp-dialects/grok-dialect.ts +++ b/src/main/acp/acp-dialects/grok-dialect.ts @@ -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, diff --git a/src/main/acp/acp-dialects/grok-requests.ts b/src/main/acp/acp-dialects/grok-requests.ts index 8a406b1d5ad..8f064e56daf 100644 --- a/src/main/acp/acp-dialects/grok-requests.ts +++ b/src/main/acp/acp-dialects/grok-requests.ts @@ -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 } diff --git a/src/main/acp/requests/acp-structured-prompts.ts b/src/main/acp/requests/acp-structured-prompts.ts index 5398873189e..6a107725f56 100644 --- a/src/main/acp/requests/acp-structured-prompts.ts +++ b/src/main/acp/requests/acp-structured-prompts.ts @@ -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}`) diff --git a/src/main/acp/requests/acp-timeline-requests.ts b/src/main/acp/requests/acp-timeline-requests.ts index ffbd6a4d6f3..143558ad6d5 100644 --- a/src/main/acp/requests/acp-timeline-requests.ts +++ b/src/main/acp/requests/acp-timeline-requests.ts @@ -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)) { diff --git a/src/main/acp/requests/acp-url-elicitation.ts b/src/main/acp/requests/acp-url-elicitation.ts new file mode 100644 index 00000000000..3969efda86c --- /dev/null +++ b/src/main/acp/requests/acp-url-elicitation.ts @@ -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 + +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({ 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 } + } + ] + } +} diff --git a/src/main/acp/session/acp-structured-acquire.ts b/src/main/acp/session/acp-structured-acquire.ts index 03632db169f..c54280ac1d5 100644 --- a/src/main/acp/session/acp-structured-acquire.ts +++ b/src/main/acp/session/acp-structured-acquire.ts @@ -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) => { diff --git a/src/main/acp/session/acp-structured-url-elicitation.test.ts b/src/main/acp/session/acp-structured-url-elicitation.test.ts new file mode 100644 index 00000000000..870c695e62f --- /dev/null +++ b/src/main/acp/session/acp-structured-url-elicitation.test.ts @@ -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) => ({ + sessionId: PROVIDER_SESSION, + toolCallId: 'mcp-elicit-1', + serverName: 'linear', + message: 'Authorize access', + ...fields +}) + +async function promptingRig(): Promise { + 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>, + response: AgentSessionPromptResponse, + selectedOptionId: string +): Promise { + 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' } }) + }) +}) diff --git a/src/main/acp/timeline/acp-timeline-translator.ts b/src/main/acp/timeline/acp-timeline-translator.ts index f072b686ede..b31bf9fa748 100644 --- a/src/main/acp/timeline/acp-timeline-translator.ts +++ b/src/main/acp/timeline/acp-timeline-translator.ts @@ -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({ 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 { - 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. diff --git a/src/main/native-chat/agent-session-timeline/provider-timeline-assembler.ts b/src/main/native-chat/agent-session-timeline/provider-timeline-assembler.ts index eb964af80aa..12ee7625a69 100644 --- a/src/main/native-chat/agent-session-timeline/provider-timeline-assembler.ts +++ b/src/main/native-chat/agent-session-timeline/provider-timeline-assembler.ts @@ -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': diff --git a/src/main/native-chat/agent-session-timeline/provider-timeline-decision.ts b/src/main/native-chat/agent-session-timeline/provider-timeline-decision.ts index 3fdab9d0e4a..3efef0a5e58 100644 --- a/src/main/native-chat/agent-session-timeline/provider-timeline-decision.ts +++ b/src/main/native-chat/agent-session-timeline/provider-timeline-decision.ts @@ -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': diff --git a/src/main/native-chat/agent-session-timeline/provider-timeline-event.ts b/src/main/native-chat/agent-session-timeline/provider-timeline-event.ts index 6e4fc268f33..7f8b4a32a3f 100644 --- a/src/main/native-chat/agent-session-timeline/provider-timeline-event.ts +++ b/src/main/native-chat/agent-session-timeline/provider-timeline-event.ts @@ -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 } diff --git a/src/main/native-chat/agent-session-timeline/provider-timeline-item-decisions.ts b/src/main/native-chat/agent-session-timeline/provider-timeline-item-decisions.ts index d0710b25acb..4870d67dffc 100644 --- a/src/main/native-chat/agent-session-timeline/provider-timeline-item-decisions.ts +++ b/src/main/native-chat/agent-session-timeline/provider-timeline-item-decisions.ts @@ -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 +): 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, diff --git a/src/main/native-chat/agent-session-timeline/provider-timeline-writer-resolution.ts b/src/main/native-chat/agent-session-timeline/provider-timeline-writer-resolution.ts index 9351237ec92..fc44ecd917b 100644 --- a/src/main/native-chat/agent-session-timeline/provider-timeline-writer-resolution.ts +++ b/src/main/native-chat/agent-session-timeline/provider-timeline-writer-resolution.ts @@ -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() for (const request of resolution.keep) { diff --git a/src/renderer/src/components/native-chat/prompts/NativeChatApprovalCard.tsx b/src/renderer/src/components/native-chat/prompts/NativeChatApprovalCard.tsx index 8b5f706db02..e19fa256cc1 100644 --- a/src/renderer/src/components/native-chat/prompts/NativeChatApprovalCard.tsx +++ b/src/renderer/src/components/native-chat/prompts/NativeChatApprovalCard.tsx @@ -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({

- {approval.title} + {title}

{worker ? (

@@ -182,6 +201,8 @@ export function NativeChatApprovalCard({

) : null}
+ ) : url !== null ? ( + ) : approval.detail ? ( ) : null}
- {approval.options.map((opt, i) => ( - - ))} + {approval.options.map((opt, i) => { + const opensUrl = url !== null && opt.send === URL_APPROVAL_OPEN_OPTION_ID + return ( + + ) + })} {approval.options.length === 0 && onOpenTerminal ? ( + ) : null} +
+ + ) +} diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 8f2773a8cdf..bda3f54d8fb 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -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": { diff --git a/src/shared/agent-session/agent-session-approval-subject.ts b/src/shared/agent-session/agent-session-approval-subject.ts index 16396b98e7c..4251182b73c 100644 --- a/src/shared/agent-session/agent-session-approval-subject.ts +++ b/src/shared/agent-session/agent-session-approval-subject.ts @@ -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 = new Set(['plan']) +export const DRAWN_APPROVAL_SUBJECT_KINDS: ReadonlySet = 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) } diff --git a/src/shared/agent-session/journal/agent-session-journal-approval-subject-schema.ts b/src/shared/agent-session/journal/agent-session-journal-approval-subject-schema.ts new file mode 100644 index 00000000000..48524b25ecf --- /dev/null +++ b/src/shared/agent-session/journal/agent-session-journal-approval-subject-schema.ts @@ -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) diff --git a/src/shared/agent-session/journal/agent-session-journal-approval-subject.ts b/src/shared/agent-session/journal/agent-session-journal-approval-subject.ts index 55a7fc68b0d..aa6bc7f0ea9 100644 --- a/src/shared/agent-session/journal/agent-session-journal-approval-subject.ts +++ b/src/shared/agent-session/journal/agent-session-journal-approval-subject.ts @@ -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 diff --git a/src/shared/agent-session/journal/agent-session-journal-schemas.ts b/src/shared/agent-session/journal/agent-session-journal-schemas.ts index 3deb1e7fb67..4ee8a8f60ec 100644 --- a/src/shared/agent-session/journal/agent-session-journal-schemas.ts +++ b/src/shared/agent-session/journal/agent-session-journal-schemas.ts @@ -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), diff --git a/src/shared/agent-session/journal/agent-session-journal-types.ts b/src/shared/agent-session/journal/agent-session-journal-types.ts index b75d6e2a5b6..1a211a30bda 100644 --- a/src/shared/agent-session/journal/agent-session-journal-types.ts +++ b/src/shared/agent-session/journal/agent-session-journal-types.ts @@ -183,6 +183,7 @@ export type { AgentJournalApprovalMatchedAskRule, AgentJournalApprovalSubject, AgentJournalPlanApprovalSubject, + AgentJournalUrlApprovalSubject, AgentJournalUnknownApprovalSubject, AgentJournalUnknownKind } from './agent-session-journal-approval-subject' diff --git a/src/shared/plugins/languages/protected-copy-keys.json b/src/shared/plugins/languages/protected-copy-keys.json index 76da02e609f..cf1a6187862 100644 --- a/src/shared/plugins/languages/protected-copy-keys.json +++ b/src/shared/plugins/languages/protected-copy-keys.json @@ -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",