From 602d1a78d316915860f07f1858c2b35aca1151d8 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 2 Oct 2026 17:24:06 -0700 Subject: [PATCH 1/7] fix(quick-commands): save agent prompts whole, bounded by what a chat message carries Agent quick-command prompts were silently cut to 6,000 characters on save: the editor accepted a long paste, settings normalization trimmed it, and reopening showed the shortened copy. The 6,000 was a Windows launch speed threshold, not a limit on prompts. - Storage no longer trims. A save is refused, never trimmed, when a prompt's chat text block is over 256 KiB of JSON (measured on its real escaped size, the measure the chat send schema applies) or the list is too large for one paired reply. Host and desktop store both check before writing. - The editor shows the size against the limit and blocks Save past it, and stays open with the text when the host refuses the save. - terminal.quick-commands.long-prompts.v1: hosts withhold prompts over 6,000 characters from clients that do not advertise it (older clients reject a whole list holding one); editors keep an older host's 6,000 cap. - The phone editor no longer drops pasted text past 6,000 via maxLength. Launch delivery of long prompts is left to the launch-prompt series (#24257, #23962, #24080); this branch's earlier paste-after-ready delivery duplicated it and is removed. --- mobile/src/session/MobileSessionSheets.tsx | 2 + mobile/src/session/QuickCommandEditorForm.tsx | 38 +++- mobile/src/session/QuickCommandsSheet.test.ts | 5 + mobile/src/session/QuickCommandsSheet.tsx | 8 +- .../src/session/quick-command-draft.test.ts | 57 ++++++ mobile/src/session/quick-command-draft.ts | 31 ++- ...se-mobile-session-feedback-capabilities.ts | 6 + .../use-mobile-session-tab-reconciliation.ts | 9 +- mobile/src/terminal/quick-commands.ts | 12 +- src/cli/runtime/websocket-transport.test.ts | 4 +- ...ngs-update-terminal-quick-commands.test.ts | 130 ++++++++++++ .../applying-settings/settings-update.ts | 8 +- .../runtime/rpc/methods/client-ui.test.ts | 11 -- src/main/runtime/rpc/methods/client-ui.ts | 15 +- ...ick-command-long-prompt-capability.test.ts | 95 +++++++++ ...al-quick-command-long-prompt-capability.ts | 32 +++ src/main/runtime/rpc/ws-transport.ts | 2 +- .../components/settings/QuickCommandsPane.tsx | 11 +- .../tab-bar/TabBarQuickCommandsButton.tsx | 13 +- .../TerminalQuickCommandEditorDialog.tsx | 7 +- .../use-terminal-pane-startup-actions.ts | 5 +- .../TerminalQuickCommandContentSection.tsx | 86 +++++++- .../TerminalQuickCommandDialog.test.tsx | 185 +++++++++++++++++- .../TerminalQuickCommandDialog.tsx | 37 +++- src/renderer/src/i18n/locales/en.json | 6 +- src/renderer/src/i18n/locales/fr.json | 6 +- src/renderer/src/i18n/locales/ja.json | 6 +- src/renderer/src/i18n/locales/ko.json | 6 +- src/renderer/src/i18n/locales/zh.json | 6 +- ...al-quick-command-host-prompt-limit.test.ts | 45 +++++ ...erminal-quick-command-host-prompt-limit.ts | 19 ++ .../lib/terminal-quick-command-search.test.ts | 22 +++ .../src/lib/terminal-quick-command-search.ts | 19 +- .../settings-terminal-quick-commands.test.ts | 31 +++ src/renderer/src/store/slices/settings.ts | 3 + .../slices/terminal-quick-command-hosts.ts | 4 +- .../src/web/web-runtime-client.test.ts | 4 +- .../web-runtime-connection-frame-router.ts | 4 +- src/shared/protocol-version.ts | 7 +- .../remote-runtime-client-capabilities.ts | 2 + .../session-tabs-schemas-params.ts | 7 +- .../terminal-quick-command-params.ts | 6 +- .../terminal-quick-command-capabilities.ts | 13 ++ .../terminal-quick-command-prompt-limit.ts | 131 +++++++++++++ src/shared/terminal-quick-commands.test.ts | 4 +- src/shared/terminal-quick-commands.ts | 8 +- 46 files changed, 1071 insertions(+), 97 deletions(-) create mode 100644 mobile/src/session/quick-command-draft.test.ts create mode 100644 src/main/persistence/applying-settings/settings-update-terminal-quick-commands.test.ts create mode 100644 src/main/runtime/rpc/methods/terminal-quick-command-long-prompt-capability.test.ts create mode 100644 src/main/runtime/rpc/methods/terminal-quick-command-long-prompt-capability.ts create mode 100644 src/renderer/src/lib/terminal-quick-command-host-prompt-limit.test.ts create mode 100644 src/renderer/src/lib/terminal-quick-command-host-prompt-limit.ts create mode 100644 src/renderer/src/store/slices/settings-terminal-quick-commands.test.ts create mode 100644 src/shared/terminal-quick-command-capabilities.ts create mode 100644 src/shared/terminal-quick-command-prompt-limit.ts diff --git a/mobile/src/session/MobileSessionSheets.tsx b/mobile/src/session/MobileSessionSheets.tsx index c91ddff1c60a..015ff64b4a42 100644 --- a/mobile/src/session/MobileSessionSheets.tsx +++ b/mobile/src/session/MobileSessionSheets.tsx @@ -61,6 +61,7 @@ export function MobileSessionSheets({ controller }: { controller: MobileSessionC setShowDictationSetup, browserScreencastSupported, quickCommandsSupported, + quickCommandAgentPromptMaxLength, showToast, nativeChatTranscriptIsLocalReadable, nativeChatController, @@ -111,6 +112,7 @@ export function MobileSessionSheets({ controller }: { controller: MobileSessionC : getRepoIdFromMobileWorktreeId(worktreeId) || null } repoName={worktreeName || null} + agentPromptMaxLength={quickCommandAgentPromptMaxLength} onLaunch={launchQuickCommand} /> ) => void onOpenAgentPicker: () => void onCancel: () => void @@ -68,6 +72,7 @@ export function QuickCommandEditorForm({ error, repoId, repoName, + agentPromptMaxLength, onChange, onOpenAgentPicker, onCancel, @@ -76,7 +81,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 +142,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 ea8d6438bf49..92463d512aac 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] = @@ -120,6 +124,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 59a4102471ba..f5601e7c1cc2 100644 --- a/src/cli/runtime/websocket-transport.test.ts +++ b/src/cli/runtime/websocket-transport.test.ts @@ -32,6 +32,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', () => ({ @@ -85,7 +86,8 @@ describe('CLI remote WebSocket transport', () => { WORKTREE_GITHUB_PR_SUPPRESSION_RUNTIME_CAPABILITY, WORKTREE_VISIBILITY_DEFAULTS_RUNTIME_CAPABILITY, WORKTREE_VISIBILITY_SOURCE_DEFAULTS_RUNTIME_CAPABILITY, - AUTOMATION_OWNER_FENCING_RUNTIME_CAPABILITY + AUTOMATION_OWNER_FENCING_RUNTIME_CAPABILITY, + TERMINAL_QUICK_COMMAND_LONG_PROMPTS_RUNTIME_CAPABILITY ] }) ) 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..949c2c6bd79e --- /dev/null +++ b/src/main/persistence/applying-settings/settings-update-terminal-quick-commands.test.ts @@ -0,0 +1,130 @@ +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 { MAX_WS_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, { + terminalQuickCommands: [agentCommand('review', `${promptAtLimit('x')}x`)] + }) + ).toThrow(/"review" is 257 KB\. Quick command prompts can be up to 256 KB/) + 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(MAX_WS_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 97190a6f8907..368bf3e95afd 100644 --- a/src/main/persistence/applying-settings/settings-update.ts +++ b/src/main/persistence/applying-settings/settings-update.ts @@ -6,6 +6,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 { normalizeTerminalCursorStyleDefault } from '../../../shared/terminal-cursor-style-settings' import { normalizeDesktopTerminalScrollbackRows } from '../../../shared/terminal-scrollback-policy' @@ -105,9 +106,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 ('terminalCustomThemes' in updates) { sanitizedUpdates.terminalCustomThemes = normalizeTerminalCustomThemes( diff --git a/src/main/runtime/rpc/methods/client-ui.test.ts b/src/main/runtime/rpc/methods/client-ui.test.ts index e2cf1289636c..db3910aa4293 100644 --- a/src/main/runtime/rpc/methods/client-ui.test.ts +++ b/src/main/runtime/rpc/methods/client-ui.test.ts @@ -2,7 +2,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 6ed36a6fe83b..794b2bcc2a0b 100644 --- a/src/main/runtime/rpc/methods/client-ui.ts +++ b/src/main/runtime/rpc/methods/client-ui.ts @@ -11,6 +11,7 @@ import { FeatureInteractionIdParam, UiUpdate } from './client-ui-schemas' // the typecheck graph so drift fails the build instead of a paired client. import { TerminalQuickCommandsUpdate } from './terminal-quick-command-rpc-schema' +import { projectTerminalQuickCommandsForClient } from './terminal-quick-command-long-prompt-capability' export const CLIENT_UI_METHODS = [ defineMethod({ @@ -30,15 +31,21 @@ 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', 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 3ba8a17fe607..9332e6b0a496 100644 --- a/src/main/runtime/rpc/ws-transport.ts +++ b/src/main/runtime/rpc/ws-transport.ts @@ -6,7 +6,7 @@ import type { RpcTransport } from './transport' import { createStaticWebClientHandler } from './static-web-client-handler' import { RemoteRuntimeServerHeartbeat } from './remote-runtime-server-heartbeat' -const MAX_WS_MESSAGE_BYTES = 1024 * 1024 +export const MAX_WS_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 MAX_WS_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/TerminalQuickCommandContentSection.tsx b/src/renderer/src/components/terminal-quick-commands/TerminalQuickCommandContentSection.tsx index c56a77a4ca47..10213a97bbe4 100644 --- a/src/renderer/src/components/terminal-quick-commands/TerminalQuickCommandContentSection.tsx +++ b/src/renderer/src/components/terminal-quick-commands/TerminalQuickCommandContentSection.tsx @@ -1,10 +1,14 @@ -import type { Dispatch, MutableRefObject, SetStateAction } from 'react' +import { useId, type Dispatch, type MutableRefObject, type SetStateAction } from 'react' import type { TerminalQuickCommand } from '../../../../shared/terminal-quick-command-types' import type { TuiAgent } from '../../../../shared/tui-agent' import { isTerminalAgentQuickCommand, supportsTerminalAgentQuickCommand } from '../../../../shared/terminal-quick-commands' +import { + formatKilobytes, + type TerminalQuickCommandBodySize +} from '../../../../shared/terminal-quick-command-prompt-limit' import { Label } from '@/components/ui/label' import { Select, @@ -21,24 +25,62 @@ import type { TerminalQuickCommandDialogDraftMemory } from './terminal-quick-com import { TerminalQuickCommandAppendEnterSwitch } from './TerminalQuickCommandAppendEnterSwitch' const QUICK_COMMAND_AGENT_OPTIONS = getTerminalQuickCommandAgentOptions() +// Why: long pastes are the common way to hit the cap, so the count appears before Save disables. +const BODY_LENGTH_COUNTER_THRESHOLD = 0.8 type TerminalQuickCommandContentSectionProps = { draft: TerminalQuickCommand isAgentAction: boolean selectedAgent: TuiAgent + bodySize: TerminalQuickCommandBodySize draftMemoryRef: MutableRefObject 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({ 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 @@ -134,7 +176,13 @@ export function TerminalQuickCommandContentSection({ {/* Why: the textarea drops its own ring, so the frame carries the focus state. */} -
+
{commandFieldLabel} @@ -152,6 +200,8 @@ export function TerminalQuickCommandContentSection({