diff --git a/mobile/src/session/MobileSessionSheets.tsx b/mobile/src/session/MobileSessionSheets.tsx index fc979a79229a..b053cf4216e2 100644 --- a/mobile/src/session/MobileSessionSheets.tsx +++ b/mobile/src/session/MobileSessionSheets.tsx @@ -62,6 +62,7 @@ export function MobileSessionSheets({ controller }: { controller: MobileSessionC setShowDictationSetup, browserScreencastSupported, quickCommandsSupported, + quickCommandAgentPromptMaxLength, showToast, nativeChatTranscriptIsLocalReadable, nativeChatController, @@ -113,6 +114,7 @@ export function MobileSessionSheets({ controller }: { controller: MobileSessionC : getRepoIdFromMobileWorktreeId(worktreeId) || null } repoName={worktreeName || null} + agentPromptMaxLength={quickCommandAgentPromptMaxLength} onLaunch={launchQuickCommand} /> ) => void onOpenAgentPicker: () => void onCancel: () => void @@ -68,6 +71,7 @@ export function QuickCommandEditorForm({ error, repoId, repoName, + agentPromptMaxLength, onChange, onOpenAgentPicker, onCancel, @@ -76,7 +80,13 @@ export function QuickCommandEditorForm({ const hasRepoScope = repoId !== null const [advancedOpen, setAdvancedOpen] = useState(draft.scope.type === 'repo') const isAgent = draft.action === 'agent-prompt' - const canSave = isQuickCommandDraftValid(draft) && !saving + const canSave = isQuickCommandDraftValid(draft, agentPromptMaxLength) && !saving + const promptTooLong = isQuickCommandDraftPromptTooLong(draft, agentPromptMaxLength) + const promptSize = getTerminalQuickCommandBodySize( + 'agent-prompt', + draft.prompt, + agentPromptMaxLength + ) return ( @@ -131,11 +141,24 @@ export function QuickCommandEditorForm({ autoCapitalize="none" autoCorrect={false} multiline - maxLength={ - isAgent ? MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH : MAX_QUICK_COMMAND_TERMINAL_TEXT_LENGTH - } + // Why: maxLength drops the tail of a paste silently, so prompts show a refusal instead. + maxLength={isAgent ? undefined : MAX_QUICK_COMMAND_TERMINAL_TEXT_LENGTH} /> - {isAgent ? ( + {promptTooLong ? ( + + {/* Why static text in the alert: a live count would re-announce on every keystroke. */} + + {promptSize.olderHostCap + ? 'Too long for this host. Update Orca on the host to save longer prompts.' + : 'Too long to save.'} + + + {promptSize.unit === 'bytes' + ? `${formatKilobytes(promptSize.used)} / ${formatKilobytes(promptSize.max)}` + : `${promptSize.used.toLocaleString()} / ${promptSize.max.toLocaleString()} characters`} + + + ) : isAgent ? ( Supports skills, file paths, and built-in commands. ) : null} diff --git a/mobile/src/session/QuickCommandsSheet.test.ts b/mobile/src/session/QuickCommandsSheet.test.ts index 2ce520a4eaf0..bc76b2ac2448 100644 --- a/mobile/src/session/QuickCommandsSheet.test.ts +++ b/mobile/src/session/QuickCommandsSheet.test.ts @@ -87,6 +87,7 @@ describe('QuickCommandsSheet', () => { client: {} as RpcClient, repoId: 'repo-1', repoName: 'Repo', + agentPromptMaxLength: null, onLaunch }) ) @@ -109,6 +110,7 @@ describe('QuickCommandsSheet', () => { client: {} as RpcClient, repoId: 'repo-1', repoName: 'Repo', + agentPromptMaxLength: null, onLaunch: () => true }) ) @@ -146,6 +148,7 @@ describe('QuickCommandsSheet', () => { client: {} as RpcClient, repoId: 'repo-1', repoName: 'Repo', + agentPromptMaxLength: null, onLaunch: () => true }) ) @@ -172,6 +175,7 @@ describe('QuickCommandsSheet', () => { client: {} as RpcClient, repoId: null, repoName: 'Folder workspace', + agentPromptMaxLength: null, onLaunch: () => true }) ) @@ -195,6 +199,7 @@ describe('QuickCommandsSheet', () => { client: {} as RpcClient, repoId: 'repo-1', repoName: 'Repo', + agentPromptMaxLength: null, onLaunch: () => true }) ) diff --git a/mobile/src/session/QuickCommandsSheet.tsx b/mobile/src/session/QuickCommandsSheet.tsx index e828676f67b6..7b516b25d231 100644 --- a/mobile/src/session/QuickCommandsSheet.tsx +++ b/mobile/src/session/QuickCommandsSheet.tsx @@ -26,6 +26,8 @@ type Props = { client: RpcClient | null repoId: string | null repoName: string | null + /** The host's agent-prompt cap. */ + agentPromptMaxLength: number | null onLaunch: (command: TerminalQuickCommand) => boolean } @@ -37,6 +39,7 @@ export function QuickCommandsSheet({ client, repoId, repoName, + agentPromptMaxLength, onLaunch }: Props) { const { commands, loading, ready, error, persist } = useQuickCommands({ @@ -59,7 +62,7 @@ export function QuickCommandsSheet({ } } - // Why: prompt bodies can total ~240 KB. Lowercase them once per settings + // Why: prompt bodies can total megabytes. Lowercase them once per settings // update instead of allocating the same search text on every keystroke. const searchableCommands = useMemo(() => { return commands @@ -123,7 +126,7 @@ export function QuickCommandsSheet({ if (!draft || savingRef.current) { return } - const built = draftToQuickCommand(draft) + const built = draftToQuickCommand(draft, agentPromptMaxLength) if (!built) { return } @@ -204,6 +207,7 @@ export function QuickCommandsSheet({ error={error} repoId={repoId} repoName={repoName} + agentPromptMaxLength={agentPromptMaxLength} onChange={(patch) => setDraft((current) => (current ? { ...current, ...patch } : current)) } diff --git a/mobile/src/session/quick-command-draft.test.ts b/mobile/src/session/quick-command-draft.test.ts new file mode 100644 index 000000000000..ae67a21bb306 --- /dev/null +++ b/mobile/src/session/quick-command-draft.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from 'vitest' +import { + LEGACY_MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH, + MAX_QUICK_COMMAND_AGENT_PROMPT_MESSAGE_BYTES +} from '../../../src/shared/terminal-quick-command-prompt-limit' +import { terminalQuickCommandAgentPromptMaxLength } from '../terminal/quick-commands' +import { TERMINAL_QUICK_COMMAND_LONG_PROMPTS_RUNTIME_CAPABILITY } from '../../../src/shared/terminal-quick-command-capabilities' +import { + createEmptyQuickCommandDraft, + draftToQuickCommand, + isQuickCommandDraftPromptTooLong, + type QuickCommandDraft +} from './quick-command-draft' + +function agentDraft(prompt: string): QuickCommandDraft { + return { + ...createEmptyQuickCommandDraft({ type: 'global' }), + label: 'Review', + action: 'agent-prompt', + agent: 'claude', + prompt + } +} + +describe('quick command drafts', () => { + it('saves a long prompt whole on a host that stores long prompts', () => { + const prompt = 'x'.repeat(100_000) + + expect(draftToQuickCommand(agentDraft(prompt))).toMatchObject({ prompt }) + // Past what a chat message carries, measured on the prompt's real size. + expect( + draftToQuickCommand(agentDraft('x'.repeat(MAX_QUICK_COMMAND_AGENT_PROMPT_MESSAGE_BYTES))) + ).toBeNull() + }) + + it('reads the host cap from its capabilities', () => { + expect(terminalQuickCommandAgentPromptMaxLength(['terminal.quick-commands.v1'])).toBe( + LEGACY_MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH + ) + expect( + terminalQuickCommandAgentPromptMaxLength([ + TERMINAL_QUICK_COMMAND_LONG_PROMPTS_RUNTIME_CAPABILITY + ]) + ).toBeNull() + // Unknown capabilities must not block a save; an older host refuses visibly itself. + expect(terminalQuickCommandAgentPromptMaxLength(undefined)).toBeNull() + }) + + it('refuses rather than trims a prompt over an older host cap', () => { + const draft = agentDraft('x'.repeat(LEGACY_MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH + 1)) + + expect( + isQuickCommandDraftPromptTooLong(draft, LEGACY_MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH) + ).toBe(true) + expect(draftToQuickCommand(draft, LEGACY_MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH)).toBeNull() + }) +}) diff --git a/mobile/src/session/quick-command-draft.ts b/mobile/src/session/quick-command-draft.ts index c1bf3fb5e35e..2100f9539629 100644 --- a/mobile/src/session/quick-command-draft.ts +++ b/mobile/src/session/quick-command-draft.ts @@ -5,8 +5,8 @@ import type { } from '../../../src/shared/terminal-quick-command-types' import type { TuiAgent } from '../../../src/shared/tui-agent' import { + getTerminalQuickCommandBodySize, isAgentQuickCommand, - MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH, MAX_QUICK_COMMAND_LABEL_LENGTH, MAX_QUICK_COMMAND_TERMINAL_TEXT_LENGTH, supportsTerminalAgentQuickCommand @@ -68,7 +68,22 @@ export function quickCommandToDraft(command: TerminalQuickCommand): QuickCommand } } -export function isQuickCommandDraftValid(draft: QuickCommandDraft): boolean { +/** Whether the draft's prompt is over its limit; `agentPromptMaxLength` is an older host's cap. */ +export function isQuickCommandDraftPromptTooLong( + draft: QuickCommandDraft, + agentPromptMaxLength: number | null +): boolean { + if (draft.action !== 'agent-prompt') { + return false + } + const size = getTerminalQuickCommandBodySize('agent-prompt', draft.prompt, agentPromptMaxLength) + return size.used > size.max +} + +export function isQuickCommandDraftValid( + draft: QuickCommandDraft, + agentPromptMaxLength: number | null = null +): boolean { if (!draft.label.trim()) { return false } @@ -76,7 +91,8 @@ export function isQuickCommandDraftValid(draft: QuickCommandDraft): boolean { return Boolean( draft.agent && supportsTerminalAgentQuickCommand(draft.agent) && - draft.prompt.trim().length > 0 + draft.prompt.trim().length > 0 && + !isQuickCommandDraftPromptTooLong(draft, agentPromptMaxLength) ) } return draft.command.trim().length > 0 @@ -85,8 +101,11 @@ export function isQuickCommandDraftValid(draft: QuickCommandDraft): boolean { // Build the persisted command from a draft. Returns null when incomplete so the // caller can keep the editor open. The server re-normalizes, but we trim/cap // here so optimistic local state matches what will be saved. -export function draftToQuickCommand(draft: QuickCommandDraft): TerminalQuickCommand | null { - if (!isQuickCommandDraftValid(draft)) { +export function draftToQuickCommand( + draft: QuickCommandDraft, + agentPromptMaxLength: number | null = null +): TerminalQuickCommand | null { + if (!isQuickCommandDraftValid(draft, agentPromptMaxLength)) { return null } // Why: timestamps alone collide when desktop and mobile add commands in the @@ -101,7 +120,7 @@ export function draftToQuickCommand(draft: QuickCommandDraft): TerminalQuickComm label, action: 'agent-prompt', agent: draft.agent, - prompt: draft.prompt.trimEnd().slice(0, MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH), + prompt: draft.prompt.trimEnd(), scope: draft.scope } } diff --git a/mobile/src/session/use-mobile-session-feedback-capabilities.ts b/mobile/src/session/use-mobile-session-feedback-capabilities.ts index ad0fb7813634..7caebcb05430 100644 --- a/mobile/src/session/use-mobile-session-feedback-capabilities.ts +++ b/mobile/src/session/use-mobile-session-feedback-capabilities.ts @@ -33,6 +33,10 @@ export function useMobileSessionFeedbackCapabilities(scope: MobileSessionTermina null ) const [quickCommandsSupported, setQuickCommandsSupported] = useState(null) + // Why: an older host's character cap; null until a host says it has one. + const [quickCommandAgentPromptMaxLength, setQuickCommandAgentPromptMaxLength] = useState< + number | null + >(null) // Structured-session features are negotiated with the same host capability probe as // the other session surfaces; consumers never maintain a second status cache. const [agentSessionHostSupport, setAgentSessionHostSupport] = @@ -131,6 +135,8 @@ export function useMobileSessionFeedbackCapabilities(scope: MobileSessionTermina setAgentSessionHistorySupported, quickCommandsSupported, setQuickCommandsSupported, + quickCommandAgentPromptMaxLength, + setQuickCommandAgentPromptMaxLength, agentSessionHostSupport, setAgentSessionHostSupport, browserScreencastSupportedRef, diff --git a/mobile/src/session/use-mobile-session-tab-reconciliation.ts b/mobile/src/session/use-mobile-session-tab-reconciliation.ts index 9f9af59833d1..5007ac579dd1 100644 --- a/mobile/src/session/use-mobile-session-tab-reconciliation.ts +++ b/mobile/src/session/use-mobile-session-tab-reconciliation.ts @@ -1,6 +1,9 @@ import { useEffect, useRef, useCallback, useMemo, useState } from 'react' import { startRuntimeCapabilityProbe } from '../transport/runtime-capability-probe' -import { supportsMobileQuickCommands } from '../terminal/quick-commands' +import { + supportsMobileQuickCommands, + terminalQuickCommandAgentPromptMaxLength +} from '../terminal/quick-commands' import { MOBILE_AI_VAULT_CAPABILITY } from '../agent-history/agent-history-capability' import { TERMINAL_QUERY_REPLY_INPUT_RUNTIME_CAPABILITY } from '../../../src/shared/protocol-version' import { structuredAgentSessionHostSupport } from './mobile-structured-agent-session-host-support' @@ -34,6 +37,7 @@ export function useMobileSessionTabReconciliation(scope: MobileSessionMarkdownAc setAgentSessionHistorySupported, setAgentSessionHostSupport, setQuickCommandsSupported, + setQuickCommandAgentPromptMaxLength, nativeChatStream, fetchTerminals, applySessionTabs, @@ -152,6 +156,7 @@ export function useMobileSessionTabReconciliation(scope: MobileSessionMarkdownAc setAgentSessionHistorySupported(null) setAgentSessionHostSupport(null) setQuickCommandsSupported(null) + setQuickCommandAgentPromptMaxLength(null) setShowQuickCommands(false) hostQueryReplyInputSupportedRef.current = false return @@ -162,6 +167,7 @@ export function useMobileSessionTabReconciliation(scope: MobileSessionMarkdownAc setAgentSessionHistorySupported(null) setAgentSessionHostSupport(null) setQuickCommandsSupported(null) + setQuickCommandAgentPromptMaxLength(null) setShowQuickCommands(false) hostQueryReplyInputSupportedRef.current = false // Why: the probe retries — a relay→direct cutover or request timeout rejects @@ -171,6 +177,7 @@ export function useMobileSessionTabReconciliation(scope: MobileSessionMarkdownAc setAgentSessionHistorySupported(capabilities.includes(MOBILE_AI_VAULT_CAPABILITY)) setAgentSessionHostSupport(structuredAgentSessionHostSupport(capabilities)) setQuickCommandsSupported(supportsMobileQuickCommands(capabilities)) + setQuickCommandAgentPromptMaxLength(terminalQuickCommandAgentPromptMaxLength(capabilities)) // Why: hosts without this capability strip inputKind from terminal.send, // so a forwarded xterm reply would become floor-stealing shell input. hostQueryReplyInputSupportedRef.current = capabilities.includes( diff --git a/mobile/src/terminal/quick-commands.ts b/mobile/src/terminal/quick-commands.ts index 625d2702bc77..4f48e093a4bc 100644 --- a/mobile/src/terminal/quick-commands.ts +++ b/mobile/src/terminal/quick-commands.ts @@ -6,7 +6,6 @@ import { getTerminalQuickCommandBody, isTerminalAgentQuickCommand, MAX_QUICK_COMMANDS, - MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH, MAX_QUICK_COMMAND_LABEL_LENGTH, MAX_QUICK_COMMAND_TERMINAL_TEXT_LENGTH, parseNormalizedTerminalQuickCommands, @@ -14,6 +13,11 @@ import { terminalQuickCommandMatchesRepo, type TerminalQuickCommandMutation } from '../../../src/shared/terminal-quick-commands' +import { + getTerminalQuickCommandBodySize, + formatKilobytes, + terminalQuickCommandAgentPromptMaxLength +} from '../../../src/shared/terminal-quick-command-prompt-limit' import { TERMINAL_QUICK_COMMANDS_RUNTIME_CAPABILITY } from '../../../src/shared/protocol-version' import { MOBILE_TUI_AGENT_LABELS } from '../tasks/mobile-tui-agents' @@ -25,11 +29,13 @@ export { getTerminalQuickCommandBody, terminalQuickCommandMatchesRepo as quickCommandMatchesRepo, supportsTerminalAgentQuickCommand, + getTerminalQuickCommandBodySize, + formatKilobytes, MAX_QUICK_COMMANDS, - MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH, MAX_QUICK_COMMAND_LABEL_LENGTH, MAX_QUICK_COMMAND_TERMINAL_TEXT_LENGTH, parseNormalizedTerminalQuickCommands, + terminalQuickCommandAgentPromptMaxLength, applyTerminalQuickCommandMutation, type TerminalQuickCommandMutation } @@ -102,7 +108,7 @@ export function getQuickCommandDisplayPreview(command: TerminalQuickCommand): st if (preview.length <= MAX_QUICK_COMMAND_DISPLAY_PREVIEW_LENGTH) { return preview } - // Why: one-line rows should not send up to 6 KB each through native text + // Why: one-line rows should not send whole prompts through native text // layout; full command bodies remain available to search, edit, and launch. return `${preview.slice(0, MAX_QUICK_COMMAND_DISPLAY_PREVIEW_LENGTH - 1)}…` } diff --git a/src/cli/runtime/websocket-transport.test.ts b/src/cli/runtime/websocket-transport.test.ts index 5c814f91fc63..1171f9b0bf8d 100644 --- a/src/cli/runtime/websocket-transport.test.ts +++ b/src/cli/runtime/websocket-transport.test.ts @@ -33,6 +33,7 @@ import { WORKTREE_VISIBILITY_DEFAULTS_RUNTIME_CAPABILITY, WORKTREE_VISIBILITY_SOURCE_DEFAULTS_RUNTIME_CAPABILITY } from '../../shared/protocol-version' +import { TERMINAL_QUICK_COMMAND_LONG_PROMPTS_RUNTIME_CAPABILITY } from '../../shared/terminal-quick-command-capabilities' import { AGENT_SESSION_BACKGROUND_TASK_CHILD_VIEWS_CAPABILITY } from '../../shared/agent-session-background-task-child-views-capability' vi.mock('./launch', () => ({ @@ -87,7 +88,8 @@ describe('CLI remote WebSocket transport', () => { WORKTREE_VISIBILITY_DEFAULTS_RUNTIME_CAPABILITY, WORKTREE_VISIBILITY_SOURCE_DEFAULTS_RUNTIME_CAPABILITY, AUTOMATION_OWNER_FENCING_RUNTIME_CAPABILITY, - REPO_SEARCH_QUALIFIED_REFS_RUNTIME_CAPABILITY + REPO_SEARCH_QUALIFIED_REFS_RUNTIME_CAPABILITY, + TERMINAL_QUICK_COMMAND_LONG_PROMPTS_RUNTIME_CAPABILITY ] }) ) diff --git a/src/main/ipc/desktop-renderer-runtime-capabilities.ts b/src/main/ipc/desktop-renderer-runtime-capabilities.ts index d44fda04208a..6b749abf2868 100644 --- a/src/main/ipc/desktop-renderer-runtime-capabilities.ts +++ b/src/main/ipc/desktop-renderer-runtime-capabilities.ts @@ -20,6 +20,7 @@ import { AGENT_LAUNCH_TAB_CLOSED_CLIENT_CAPABILITY } from '../../shared/agent-launch-runtime-capability' import { AGENT_SESSION_BACKGROUND_TASK_CHILD_VIEWS_CAPABILITY } from '../../shared/agent-session-background-task-child-views-capability' +import { TERMINAL_QUICK_COMMAND_LONG_PROMPTS_RUNTIME_CAPABILITY } from '../../shared/terminal-quick-command-capabilities' /** * What the desktop renderer advertises when it calls its own main process over `runtime:call`. @@ -58,5 +59,7 @@ export const DESKTOP_RENDERER_RUNTIME_CLIENT_CAPABILITIES: readonly RuntimeCapab AGENT_LAUNCH_PROMPT_UNCONFIRMED_RUNTIME_CAPABILITY, // A launch whose tab the user closed is answered as exactly that, which the desktop stays silent // on, rather than as unknown, which it would report as a failure. - AGENT_LAUNCH_TAB_CLOSED_CLIENT_CAPABILITY + AGENT_LAUNCH_TAB_CLOSED_CLIENT_CAPABILITY, + // Same build as its host, so it reads every quick-command prompt the host stores. + TERMINAL_QUICK_COMMAND_LONG_PROMPTS_RUNTIME_CAPABILITY ] as const diff --git a/src/main/persistence/applying-settings/settings-update-terminal-quick-commands.test.ts b/src/main/persistence/applying-settings/settings-update-terminal-quick-commands.test.ts new file mode 100644 index 000000000000..f6f16a37bc69 --- /dev/null +++ b/src/main/persistence/applying-settings/settings-update-terminal-quick-commands.test.ts @@ -0,0 +1,133 @@ +import { describe, expect, it, vi } from 'vitest' +import type { PersistedState } from '../../../shared/persisted-state-types' +import type { TerminalQuickCommand } from '../../../shared/terminal-quick-command-types' +import { MAX_QUICK_COMMANDS } from '../../../shared/terminal-quick-commands' +import { + getTerminalQuickCommandPromptMessageBytes, + MAX_QUICK_COMMAND_AGENT_PROMPT_MESSAGE_BYTES, + MAX_TERMINAL_QUICK_COMMANDS_SERIALIZED_BYTES +} from '../../../shared/terminal-quick-command-prompt-limit' +import { REMOTE_RPC_MAX_CONTENT_BYTES } from '../../../shared/remote-rpc-content-budget' +import { WEBSOCKET_TRANSPORT_MAX_MESSAGE_BYTES } from '../../runtime/rpc/ws-transport' +import { updateSettings, type SettingsMutationOperations } from './settings-update' +import { + CreateAgentSessionParams, + MAX_PROMPT_BYTES as CREATE_MAX_PROMPT_BYTES +} from '../../../shared/rpc-contract/agent-session-params' +import { MAX_PROMPT_BYTES as STRUCTURED_MAX_PROMPT_BYTES } from '../../../shared/rpc-contract/structured-agent-session-params' + +function makeOperations(): SettingsMutationOperations { + return { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the fields updateSettings reads for this setting. + state: { settings: { terminalQuickCommands: [] }, repos: [] } as unknown as PersistedState, + bumpLocalWorktreeScanGeneration: vi.fn(), + removeRetainedBlob: vi.fn(), + scheduleSave: vi.fn(), + notifySettingsChanged: vi.fn() + } +} + +// The largest prompt of one repeated character the message bound admits. +function promptAtLimit(character: string): string { + const overhead = getTerminalQuickCommandPromptMessageBytes('') + const perCharacter = getTerminalQuickCommandPromptMessageBytes(character) - overhead + return character.repeat( + Math.floor((MAX_QUICK_COMMAND_AGENT_PROMPT_MESSAGE_BYTES - overhead) / perCharacter) + ) +} + +function agentCommand(id: string, prompt: string): TerminalQuickCommand { + return { + id, + label: id, + action: 'agent-prompt', + agent: 'claude', + prompt, + scope: { type: 'global' } + } +} + +// Local saves and paired saves both reach the store here, so this is the one place the bound holds. +describe('updateSettings terminalQuickCommands', () => { + it('stores a prompt at the limit whole', () => { + const prompt = promptAtLimit('x') + const saved = updateSettings(makeOperations(), { + terminalQuickCommands: [agentCommand('review', prompt)] + }) + + expect(saved.terminalQuickCommands?.[0]).toMatchObject({ prompt }) + }) + + it('refuses a prompt over the limit rather than trimming it', () => { + const operations = makeOperations() + + expect(() => + updateSettings(operations, { + opencodeSessionCookie: '', + httpProxyUrl: '', + terminalQuickCommands: [agentCommand('review', `${promptAtLimit('x')}x`)] + }) + ).toThrow(/"review" is 257 KB\. Quick command prompts can be up to 256 KB/) + expect(operations.removeRetainedBlob).not.toHaveBeenCalled() + expect(operations.scheduleSave).not.toHaveBeenCalled() + }) + + it('refuses a list too large for one paired reply', () => { + // Forty prompts at the limit total about 10 MB of JSON. + const commands = Array.from({ length: MAX_QUICK_COMMANDS }, (_, index) => + agentCommand(`c${index}`, promptAtLimit('界')) + ) + + expect(() => updateSettings(makeOperations(), { terminalQuickCommands: commands })).toThrow( + /Shorten or remove a prompt/ + ) + }) +}) + +describe('the quick-command storage bound against every prompt limit on the run path', () => { + // The worst character for each limit: a C0 control escapes to 6 bytes of JSON, CJK is 3 of UTF-8. + const worstForJson = promptAtLimit('\u0001') + const worstForUtf8 = promptAtLimit('界') + + it('measures the prompt the way a chat message measures its blocks', () => { + expect(MAX_QUICK_COMMAND_AGENT_PROMPT_MESSAGE_BYTES).toBe(STRUCTURED_MAX_PROMPT_BYTES) + expect(getTerminalQuickCommandPromptMessageBytes(worstForJson)).toBe( + Buffer.byteLength(JSON.stringify([{ type: 'text', text: worstForJson }]), 'utf8') + ) + }) + + it('fits a structured chat message, which caps the JSON of its blocks', () => { + const blocks = [{ type: 'text', text: worstForJson }] + expect(Buffer.byteLength(JSON.stringify(blocks), 'utf8')).toBeLessThanOrEqual( + STRUCTURED_MAX_PROMPT_BYTES + ) + }) + + it('fits a paired create, which caps the prompt in UTF-8 bytes', () => { + expect(Buffer.byteLength(worstForUtf8, 'utf8')).toBeLessThanOrEqual(CREATE_MAX_PROMPT_BYTES) + expect( + CreateAgentSessionParams.safeParse({ + clientOperationId: `${Date.now()}-0123456789abcdef0123456789abcdef`, + worktree: 'id:worktree-1', + agent: 'claude', + prompt: worstForUtf8 + }).success + ).toBe(true) + }) +}) + +describe('the quick-command storage bound against the paired transports', () => { + it('fits a saved list in one reply', () => { + expect(MAX_TERMINAL_QUICK_COMMANDS_SERIALIZED_BYTES + 64 * 1024).toBeLessThanOrEqual( + REMOTE_RPC_MAX_CONTENT_BYTES + ) + }) + + it('fits one saved command in an inbound frame at the worst JSON escape', () => { + // Legacy E2EE frames are base64 of nonce + MAC + plaintext. + const inboundPlaintextBytes = Math.floor(WEBSOCKET_TRANSPORT_MAX_MESSAGE_BYTES / 4) * 3 - 40 + const worstCasePromptBytes = MAX_QUICK_COMMAND_AGENT_PROMPT_MESSAGE_BYTES + const envelopeReserveBytes = 16 * 1024 + expect(worstCasePromptBytes + envelopeReserveBytes).toBeLessThanOrEqual(inboundPlaintextBytes) + }) +}) diff --git a/src/main/persistence/applying-settings/settings-update.ts b/src/main/persistence/applying-settings/settings-update.ts index 01e5e4f31959..22fb36d8f8ec 100644 --- a/src/main/persistence/applying-settings/settings-update.ts +++ b/src/main/persistence/applying-settings/settings-update.ts @@ -7,6 +7,7 @@ import { normalizeTuiAgentEnvRecord } from '../../../shared/tui-agent-launch-defaults' import { normalizeTerminalQuickCommands } from '../../../shared/terminal-quick-commands' +import { assertTerminalQuickCommandsStorable } from '../../../shared/terminal-quick-command-prompt-limit' import { normalizeTerminalCustomThemes } from '../../../shared/terminal-custom-themes' import { normalizeTerminalDefaultShell } from '../../../shared/terminal-default-shell' import { normalizeTerminalCursorStyleDefault } from '../../../shared/terminal-cursor-style-settings' @@ -64,12 +65,6 @@ export function updateSettings( // Loaded defaults are ambiguous; synchronize the legacy switch only on an explicit write. sanitizedUpdates.terminalLinkActionPopoverEnabled = linkBehavior === 'actions' } - if ('opencodeSessionCookie' in updates && !updates.opencodeSessionCookie) { - operations.removeRetainedBlob(PROTECTED_SECRET_SLOT.opencodeSessionCookie) - } - if ('httpProxyUrl' in updates && !updates.httpProxyUrl) { - operations.removeRetainedBlob(PROTECTED_SECRET_SLOT.httpProxyUrl) - } // Why: coerce to boolean here (not the IPC edge) so every write path is covered and a truthy non-bool can't persist as "tray-minimize on". if ('minimizeToTrayOnClose' in updates) { sanitizedUpdates.minimizeToTrayOnClose = updates.minimizeToTrayOnClose === true @@ -114,9 +109,10 @@ export function updateSettings( sanitizedUpdates.agentYoloDefaultsMigrated = true } if ('terminalQuickCommands' in updates) { - sanitizedUpdates.terminalQuickCommands = normalizeTerminalQuickCommands( - updates.terminalQuickCommands - ) + const terminalQuickCommands = normalizeTerminalQuickCommands(updates.terminalQuickCommands) + // Every local and paired save lands here, so this is where an unstorable list is refused. + assertTerminalQuickCommandsStorable(terminalQuickCommands) + sanitizedUpdates.terminalQuickCommands = terminalQuickCommands } if ('terminalDefaultShell' in updates) { sanitizedUpdates.terminalDefaultShell = normalizeTerminalDefaultShell( @@ -274,6 +270,12 @@ export function updateSettings( }), ...(mergedTelemetry !== undefined ? { telemetry: mergedTelemetry } : {}) } + if ('opencodeSessionCookie' in updates && !updates.opencodeSessionCookie) { + operations.removeRetainedBlob(PROTECTED_SECRET_SLOT.opencodeSessionCookie) + } + if ('httpProxyUrl' in updates && !updates.httpProxyUrl) { + operations.removeRetainedBlob(PROTECTED_SECRET_SLOT.httpProxyUrl) + } if ( !Object.is( previousSettings.localWindowsRuntimeDefault, diff --git a/src/main/runtime/rpc/methods/client-ui.test.ts b/src/main/runtime/rpc/methods/client-ui.test.ts index 0894fb7d7de5..871997c38333 100644 --- a/src/main/runtime/rpc/methods/client-ui.test.ts +++ b/src/main/runtime/rpc/methods/client-ui.test.ts @@ -3,7 +3,6 @@ import { describe, expect, it, vi } from 'vitest' import { getDefaultUIState } from '../../../../shared/constants' import { omitPairingLocalUiFields } from '../../../../shared/pairing-local-ui-fields' import { - MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH, MAX_QUICK_COMMAND_ID_LENGTH, MAX_QUICK_COMMAND_LABEL_LENGTH, MAX_QUICK_COMMAND_REPO_ID_LENGTH, @@ -318,16 +317,6 @@ describe('client UI RPC methods', () => { scope: { type: 'repo', repoId: 'x'.repeat(MAX_QUICK_COMMAND_REPO_ID_LENGTH + 1) } } }, - { - type: 'upsert', - command: { - id: 'oversized-prompt', - label: 'Oversized prompt', - action: 'agent-prompt', - agent: 'codex', - prompt: 'x'.repeat(MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH + 1) - } - }, { type: 'upsert', command: { id: 'default-pwd', label: 'Removed', command: 'pwd' } } ]) { const response = await dispatcher.dispatch( diff --git a/src/main/runtime/rpc/methods/client-ui.ts b/src/main/runtime/rpc/methods/client-ui.ts index 23a7eb3e0678..ffc8311817f0 100644 --- a/src/main/runtime/rpc/methods/client-ui.ts +++ b/src/main/runtime/rpc/methods/client-ui.ts @@ -19,6 +19,7 @@ import { FeatureInteractionIdParam, UiUpdate } from './client-ui-schemas' import { TerminalQuickCommandsUpdate } from '../../../../shared/rpc-contract/terminal-quick-command-params' import { AgentLaunchSettingsMutation } from '../../../../shared/rpc-contract/agent-launch-settings-params' +import { projectTerminalQuickCommandsForClient } from './terminal-quick-command-long-prompt-capability' export const CLIENT_UI_METHODS = [ defineMethod({ @@ -89,16 +90,22 @@ export const CLIENT_UI_METHODS = [ params: null, // Why: command bodies can total ~240 KB, so keep unrelated settings reads // from carrying them over every paired/relay connection. - handler: (_params, { runtime }) => ({ - terminalQuickCommands: runtime.getClientTerminalQuickCommands() + handler: (_params, ctx) => ({ + terminalQuickCommands: projectTerminalQuickCommandsForClient( + ctx.runtime.getClientTerminalQuickCommands(), + ctx + ) }) }), defineMethod({ name: 'settings.updateTerminalQuickCommands', permission: 'settings-write', params: TerminalQuickCommandsUpdate, - handler: (params, { runtime }) => ({ - terminalQuickCommands: runtime.updateClientTerminalQuickCommands(params.mutation) + handler: (params, ctx) => ({ + terminalQuickCommands: projectTerminalQuickCommandsForClient( + ctx.runtime.updateClientTerminalQuickCommands(params.mutation), + ctx + ) }) }), defineMethod({ diff --git a/src/main/runtime/rpc/methods/terminal-quick-command-long-prompt-capability.test.ts b/src/main/runtime/rpc/methods/terminal-quick-command-long-prompt-capability.test.ts new file mode 100644 index 000000000000..a56de07d4202 --- /dev/null +++ b/src/main/runtime/rpc/methods/terminal-quick-command-long-prompt-capability.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, it, vi } from 'vitest' +import { LEGACY_MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH } from '../../../../shared/terminal-quick-command-prompt-limit' +import type { TerminalQuickCommand } from '../../../../shared/terminal-quick-command-types' +import { TERMINAL_QUICK_COMMAND_LONG_PROMPTS_RUNTIME_CAPABILITY } from '../../../../shared/terminal-quick-command-capabilities' +import type { OrcaRuntimeService } from '../../orca-runtime' +import type { RpcRequest } from '../core' +import { RpcDispatcher } from '../dispatcher' +import { CLIENT_UI_METHODS } from './client-ui' + +function makeRequest(method: string, params?: unknown): RpcRequest { + return { id: 'req-1', authToken: 'tok', method, params } +} + +describe('quick-command prompts longer than older clients accept', () => { + const shortCommand: TerminalQuickCommand = { + id: 'status', + label: 'Status', + action: 'terminal-command', + command: 'git status', + appendEnter: true, + scope: { type: 'global' } + } + const longCommand: TerminalQuickCommand = { + id: 'review', + label: 'Review', + action: 'agent-prompt', + agent: 'claude', + prompt: 'x'.repeat(LEGACY_MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH + 1), + scope: { type: 'global' } + } + + function makeDispatcher(): { + dispatcher: RpcDispatcher + update: ReturnType + } { + const update = vi.fn(() => [shortCommand, longCommand]) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: these handlers call only the quick-command methods stubbed here. + const runtime = { + getRuntimeId: () => 'test-runtime', + getClientTerminalQuickCommands: vi.fn(() => [shortCommand, longCommand]), + updateClientTerminalQuickCommands: update + } as unknown as OrcaRuntimeService + return { dispatcher: new RpcDispatcher({ runtime, methods: CLIENT_UI_METHODS }), update } + } + + it('stores a long prompt instead of refusing it', async () => { + const { dispatcher, update } = makeDispatcher() + const response = await dispatcher.dispatch( + makeRequest('settings.updateTerminalQuickCommands', { + mutation: { type: 'upsert', command: longCommand } + }) + ) + + expect(response).toMatchObject({ ok: true }) + expect(update).toHaveBeenCalledWith({ type: 'upsert', command: longCommand }) + }) + + it('withholds long prompts from a client that cannot read them', async () => { + const { dispatcher } = makeDispatcher() + const olderClient = { clientKind: 'mobile' as const, clientCapabilities: [] } + + for (const request of [ + makeRequest('settings.getTerminalQuickCommands'), + makeRequest('settings.updateTerminalQuickCommands', { + mutation: { type: 'delete', id: 'other' } + }) + ]) { + const response = await dispatcher.dispatch(request, olderClient) + expect(response).toMatchObject({ + ok: true, + result: { terminalQuickCommands: [shortCommand] } + }) + } + }) + + it('publishes long prompts to clients that advertise support and to in-process callers', async () => { + const { dispatcher } = makeDispatcher() + for (const options of [ + { + clientKind: 'mobile' as const, + clientCapabilities: [TERMINAL_QUICK_COMMAND_LONG_PROMPTS_RUNTIME_CAPABILITY] + }, + undefined + ]) { + const response = await dispatcher.dispatch( + makeRequest('settings.getTerminalQuickCommands'), + options + ) + expect(response).toMatchObject({ + ok: true, + result: { terminalQuickCommands: [shortCommand, longCommand] } + }) + } + }) +}) diff --git a/src/main/runtime/rpc/methods/terminal-quick-command-long-prompt-capability.ts b/src/main/runtime/rpc/methods/terminal-quick-command-long-prompt-capability.ts new file mode 100644 index 000000000000..12fd07bab78b --- /dev/null +++ b/src/main/runtime/rpc/methods/terminal-quick-command-long-prompt-capability.ts @@ -0,0 +1,32 @@ +// Transitional: remove once no supported release lacks TERMINAL_QUICK_COMMAND_LONG_PROMPTS_RUNTIME_CAPABILITY. +// +// A client from before long prompts rejects the whole quick-command list if one prompt is longer +// than its old cap, so the host leaves those commands out of what it publishes to that client. +// Omitting beats trimming: a trimmed copy would run the wrong prompt, and saving it would +// overwrite the stored one. + +import type { TerminalQuickCommand } from '../../../../shared/terminal-quick-command-types' +import { isLegacyReadableTerminalQuickCommand } from '../../../../shared/terminal-quick-command-prompt-limit' +import { TERMINAL_QUICK_COMMAND_LONG_PROMPTS_RUNTIME_CAPABILITY } from '../../../../shared/terminal-quick-command-capabilities' +import type { RpcContext } from '../core' + +type QuickCommandReader = Pick + +function readsLongPrompts(ctx: QuickCommandReader): boolean { + // An in-process caller is this build; only a negotiated client can predate long prompts. + return ( + ctx.clientKind === undefined || + ctx.clientCapabilities?.includes(TERMINAL_QUICK_COMMAND_LONG_PROMPTS_RUNTIME_CAPABILITY) === + true + ) +} + +export function projectTerminalQuickCommandsForClient( + commands: TerminalQuickCommand[], + ctx: QuickCommandReader +): TerminalQuickCommand[] { + if (readsLongPrompts(ctx) || commands.every(isLegacyReadableTerminalQuickCommand)) { + return commands + } + return commands.filter(isLegacyReadableTerminalQuickCommand) +} diff --git a/src/main/runtime/rpc/ws-transport.ts b/src/main/runtime/rpc/ws-transport.ts index 06d943faddfd..bd496e3eeacb 100644 --- a/src/main/runtime/rpc/ws-transport.ts +++ b/src/main/runtime/rpc/ws-transport.ts @@ -15,7 +15,7 @@ import { } from './node-websocket-lifecycle' import { RemoteRuntimeServerHeartbeat } from './remote-runtime-server-heartbeat' -const WEBSOCKET_TRANSPORT_MAX_MESSAGE_BYTES = 1024 * 1024 +export const WEBSOCKET_TRANSPORT_MAX_MESSAGE_BYTES = 1024 * 1024 // Why: one desktop remote-host client can hold many concurrent streams, so keep the cap high enough that stale streams don't starve control RPCs. const WEBSOCKET_TRANSPORT_MAX_CONNECTIONS = 128 // Why: bound pre-upgrade descriptor use above the WS cap so raw sockets can't grow without bound. diff --git a/src/renderer/src/components/settings/QuickCommandsPane.tsx b/src/renderer/src/components/settings/QuickCommandsPane.tsx index 2305a0342277..198b4e26d450 100644 --- a/src/renderer/src/components/settings/QuickCommandsPane.tsx +++ b/src/renderer/src/components/settings/QuickCommandsPane.tsx @@ -8,6 +8,7 @@ import { } from '@/components/terminal-quick-commands/TerminalQuickCommandDialog' import { searchTerminalQuickCommands } from '@/lib/terminal-quick-command-search' import { useAppStore } from '../../store' +import { getTerminalQuickCommandHostPromptMaxLength } from '@/lib/terminal-quick-command-host-prompt-limit' import { Button } from '../ui/button' import { useConfirmationDialog } from '@/components/confirmation-dialog-context' import { getSettingOwnershipSummary } from './setting-ownership' @@ -238,7 +239,7 @@ export function QuickCommandsPane({ setScopeSelection(null) } - const saveCommand = (next: TerminalQuickCommand): void => { + const saveCommand = async (next: TerminalQuickCommand): Promise => { if ( !editor || !isQuickCommandEditorHostCurrent( @@ -249,10 +250,10 @@ export function QuickCommandsPane({ ) ) { setEditor(null) - return + return false } useAppStore.getState().recordFeatureInteraction('quick-commands') - void useAppStore.getState().upsertTerminalQuickCommand(editor.hostId, next) + return await useAppStore.getState().upsertTerminalQuickCommand(editor.hostId, next) } const removeCommand = async (command: TerminalQuickCommand): Promise => { @@ -396,6 +397,10 @@ export function QuickCommandsPane({ command={editor.command} repos={hostRepos} defaultAdvancedOpen + agentPromptMaxLength={getTerminalQuickCommandHostPromptMaxLength( + { runtimeStatusByEnvironmentId: runtimeStatuses }, + editor.hostId + )} onOpenChange={(open) => !open && setEditor(null)} onSave={saveCommand} /> diff --git a/src/renderer/src/components/tab-bar/TabBarQuickCommandsButton.tsx b/src/renderer/src/components/tab-bar/TabBarQuickCommandsButton.tsx index ae831a418f92..62b6a0c28ffe 100644 --- a/src/renderer/src/components/tab-bar/TabBarQuickCommandsButton.tsx +++ b/src/renderer/src/components/tab-bar/TabBarQuickCommandsButton.tsx @@ -1,6 +1,7 @@ import { useMemo, useState } from 'react' import { Play } from 'lucide-react' import { useAppStore } from '@/store' +import { getTerminalQuickCommandHostPromptMaxLength } from '@/lib/terminal-quick-command-host-prompt-limit' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { createTerminalQuickCommandDraft, @@ -118,11 +119,8 @@ export function TabBarQuickCommandsButton({ }) } - const handleSaveCommand = (next: TerminalQuickCommand): void => { - if (editor) { - void useAppStore.getState().upsertTerminalQuickCommand(editor.hostId, next) - } - } + const handleSaveCommand = async (next: TerminalQuickCommand): Promise => + editor ? await useAppStore.getState().upsertTerminalQuickCommand(editor.hostId, next) : false const handleDeleteCommand = async (entry: HostedTerminalQuickCommand): Promise => { const { command } = entry @@ -156,6 +154,9 @@ export function TabBarQuickCommandsButton({ historyId: entry.key }) } + const editorPromptMaxLength = useAppStore((state) => + editor ? getTerminalQuickCommandHostPromptMaxLength(state, editor.hostId) : undefined + ) const editorRepos = editor?.hostId.startsWith('runtime:') ? repos.filter((repo) => getRepoExecutionHostId(repo) === editor.hostId) : repos @@ -204,6 +205,7 @@ export function TabBarQuickCommandsButton({ mode={editor?.mode ?? 'add'} command={editor?.command ?? createTerminalQuickCommandDraft({ type: 'repo', repoId })} repos={editorRepos} + agentPromptMaxLength={editorPromptMaxLength} onOpenChange={(open) => !open && setEditor(null)} onSave={handleSaveCommand} /> @@ -233,6 +235,7 @@ export function TabBarQuickCommandsButton({ mode={editor?.mode ?? 'add'} command={editor?.command ?? createTerminalQuickCommandDraft({ type: 'repo', repoId })} repos={editorRepos} + agentPromptMaxLength={editorPromptMaxLength} onOpenChange={(open) => !open && setEditor(null)} onSave={handleSaveCommand} /> diff --git a/src/renderer/src/components/terminal-pane/TerminalQuickCommandEditorDialog.tsx b/src/renderer/src/components/terminal-pane/TerminalQuickCommandEditorDialog.tsx index 007160e112ac..1281fa24547e 100644 --- a/src/renderer/src/components/terminal-pane/TerminalQuickCommandEditorDialog.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalQuickCommandEditorDialog.tsx @@ -1,4 +1,5 @@ import { useAppStore } from '../../store' +import { getTerminalQuickCommandHostPromptMaxLength } from '@/lib/terminal-quick-command-host-prompt-limit' import { getRepoExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' import type { TerminalQuickCommand } from '../../../../shared/terminal-quick-command-types' import { TerminalQuickCommandDialog } from '@/components/terminal-quick-commands/TerminalQuickCommandDialog' @@ -12,9 +13,12 @@ export function TerminalQuickCommandEditorDialog({ command: TerminalQuickCommand hostId: ExecutionHostId onOpenChange: (open: boolean) => void - onSave: (command: TerminalQuickCommand) => void + onSave: (command: TerminalQuickCommand) => Promise }): React.JSX.Element { const repos = useAppStore((store) => store.repos) + const agentPromptMaxLength = useAppStore((store) => + getTerminalQuickCommandHostPromptMaxLength(store, hostId) + ) const hostRepos = hostId.startsWith('runtime:') ? repos.filter((repo) => getRepoExecutionHostId(repo) === hostId) : repos @@ -25,6 +29,7 @@ export function TerminalQuickCommandEditorDialog({ mode="add" command={command} repos={hostRepos} + agentPromptMaxLength={agentPromptMaxLength} onOpenChange={onOpenChange} onSave={onSave} /> diff --git a/src/renderer/src/components/terminal-pane/use-terminal-pane-startup-actions.ts b/src/renderer/src/components/terminal-pane/use-terminal-pane-startup-actions.ts index deff696c93fb..b1e577b24146 100644 --- a/src/renderer/src/components/terminal-pane/use-terminal-pane-startup-actions.ts +++ b/src/renderer/src/components/terminal-pane/use-terminal-pane-startup-actions.ts @@ -149,9 +149,8 @@ export function useTerminalPaneStartupActions(controller: TerminalPaneStoreContr [] ) const saveQuickCommand = useCallback( - (command: TerminalQuickCommand): void => { - void useAppStore.getState().upsertTerminalQuickCommand(quickCommandEditorHostId, command) - }, + (command: TerminalQuickCommand): Promise => + useAppStore.getState().upsertTerminalQuickCommand(quickCommandEditorHostId, command), [quickCommandEditorHostId] ) useEffect(() => { diff --git a/src/renderer/src/components/terminal-quick-commands/TerminalQuickCommandAdvancedSection.tsx b/src/renderer/src/components/terminal-quick-commands/TerminalQuickCommandAdvancedSection.tsx index 1ad49ee76a0e..88bce02a30e9 100644 --- a/src/renderer/src/components/terminal-quick-commands/TerminalQuickCommandAdvancedSection.tsx +++ b/src/renderer/src/components/terminal-quick-commands/TerminalQuickCommandAdvancedSection.tsx @@ -9,6 +9,7 @@ import { translate } from '@/i18n/i18n' import { TerminalQuickCommandScopeField } from './TerminalQuickCommandScopeField' type TerminalQuickCommandAdvancedSectionProps = { + disabled: boolean repos: readonly Pick[] advancedOpen: boolean selectedScope: ReturnType @@ -43,6 +44,7 @@ function getScopeSummaryLabel({ } export function TerminalQuickCommandAdvancedSection({ + disabled, repos, advancedOpen, selectedScope, @@ -98,6 +100,7 @@ export function TerminalQuickCommandAdvancedSection({ )} > setDraft: Dispatch> toggleAppendEnter: () => void } +function getBodyLengthLabel(bodySize: TerminalQuickCommandBodySize): string { + if (bodySize.unit === 'bytes') { + return translate( + 'auto.components.terminal.quick.commands.TerminalQuickCommandDialog.size_count', + '{{value0}} / {{value1}}', + { value0: formatKilobytes(bodySize.used), value1: formatKilobytes(bodySize.max) } + ) + } + return translate( + 'auto.components.terminal.quick.commands.TerminalQuickCommandDialog.length_count', + '{{value0}} / {{value1}} characters', + { value0: bodySize.used.toLocaleString(), value1: bodySize.max.toLocaleString() } + ) +} + +function getBodyRefusalLabel(belowCurrentPromptCap: boolean): string { + return belowCurrentPromptCap + ? translate( + 'auto.components.terminal.quick.commands.TerminalQuickCommandDialog.prompt_over_host_limit', + 'Too long for this host. Update Orca on the host to save longer prompts.' + ) + : translate( + 'auto.components.terminal.quick.commands.TerminalQuickCommandDialog.length_over_limit', + 'Too long to save.' + ) +} + export function TerminalQuickCommandContentSection({ + disabled, draft, isAgentAction, selectedAgent, + bodySize, draftMemoryRef, setDraft, toggleAppendEnter }: TerminalQuickCommandContentSectionProps): React.JSX.Element { + const bodyTooLong = bodySize.used > bodySize.max + const showBodyLength = bodySize.used >= bodySize.max * BODY_LENGTH_COUNTER_THRESHOLD + const lengthId = useId() + const refusalId = useId() + const describedBy = + [showBodyLength ? lengthId : null, bodyTooLong ? refusalId : null].filter(Boolean).join(' ') || + undefined const commandText = isTerminalAgentQuickCommand(draft) ? draft.prompt : draft.command // Why: the frame header is a plain span, so the textarea carries the accessible name itself. const commandFieldLabel = isAgentAction @@ -79,7 +123,7 @@ export function TerminalQuickCommandContentSection({