diff --git a/crates/agents/src/engine/codex_protocol.rs b/crates/agents/src/engine/codex_protocol.rs index 0f4b300d2..a7f93fdc4 100644 --- a/crates/agents/src/engine/codex_protocol.rs +++ b/crates/agents/src/engine/codex_protocol.rs @@ -75,7 +75,7 @@ pub fn codex_approval_options() -> Vec { AgentPermissionOption { id: "acceptForSession".to_string(), label: "Allow for session".to_string(), - kind: AgentPermissionOptionKind::AllowAlways, + kind: AgentPermissionOptionKind::AllowOnce, description: None, }, AgentPermissionOption { @@ -87,6 +87,42 @@ pub fn codex_approval_options() -> Vec { ] } +fn command_approval_options(params: &Value) -> Vec { + let Some(decisions) = params.get("availableDecisions").and_then(Value::as_array) else { + return codex_approval_options(); + }; + let defaults = codex_approval_options(); + decisions + .iter() + .enumerate() + .filter_map(|(index, value)| { + if let Some(id) = value.as_str() { + if id == "cancel" { + return Some(AgentPermissionOption { + id: id.into(), + label: "取消".into(), + kind: AgentPermissionOptionKind::RejectOnce, + description: None, + }); + } + return defaults.iter().find(|option| option.id == id).cloned(); + } + let prefix = value + .pointer("/acceptWithExecpolicyAmendment/execpolicy_amendment")? + .as_array()?; + if prefix.is_empty() || !prefix.iter().all(Value::is_string) { + return None; + } + Some(AgentPermissionOption { + id: format!("allow-prefix-{index}"), + label: "记住命令前缀".into(), + description: Some(json!(prefix).to_string()), + kind: AgentPermissionOptionKind::AllowOnce, + }) + }) + .collect() +} + pub fn default_codex_models() -> Vec { vec![ EngineModelInfo { @@ -357,7 +393,11 @@ pub fn parse_codex_server_request( tool_name, input: params.clone(), decision_reason, - options: codex_approval_options(), + options: if default_tool == "commandExecution" { + command_approval_options(params) + } else { + codex_approval_options() + }, }; Some((permission_id, record, event)) } @@ -459,6 +499,27 @@ pub fn build_codex_server_request_result( return (result, "accept".to_string()); } + if let Some(index) = decision + .option_id + .as_deref() + .and_then(|id| id.strip_prefix("allow-prefix-")) + { + if !decision.interrupt + && decision.approved + && pending.method == "item/commandExecution/requestApproval" + && let Some(advertised) = index + .parse::() + .ok() + .and_then(|i| pending.params.get("availableDecisions")?.get(i)) + && advertised + .pointer("/acceptWithExecpolicyAmendment/execpolicy_amendment") + .and_then(Value::as_array) + .is_some_and(|p| !p.is_empty() && p.iter().all(Value::is_string)) + { + return (json!({ "decision": advertised }), "accept".into()); + } + return (json!({ "decision": "cancel" }), "cancel".into()); + } let codex_decision = if decision.interrupt { "cancel" } else { @@ -1337,6 +1398,22 @@ mod tests { } } + #[test] + fn command_rule_round_trip_uses_the_offered_prefix() { + let mut request = pending("item/commandExecution/requestApproval"); + let rule = + json!({"acceptWithExecpolicyAmendment": {"execpolicy_amendment": ["git", "status"]}}); + request.params = json!({"availableDecisions": ["accept", rule, "cancel"]}); + let options = command_approval_options(&request.params); + let ids: Vec<_> = options.iter().map(|option| option.id.as_str()).collect(); + assert_eq!(ids, ["accept", "allow-prefix-1", "cancel"]); + let result = + |id| build_codex_server_request_result(&request, &decision(Some(id), true, false)).0; + assert_eq!(result("allow-prefix-1"), json!({"decision": rule})); + assert_eq!(result("allow-prefix-0"), json!({"decision": "cancel"})); + assert_eq!(result("allow-prefix-2"), json!({"decision": "cancel"})); + } + #[test] fn mcp_tool_approval_elicitation_becomes_a_permission_card() { let params = approval_params(json!(["session", "always"])); diff --git a/crates/agents/src/permissions.rs b/crates/agents/src/permissions.rs index a22e5a9d5..71d2fcb53 100644 --- a/crates/agents/src/permissions.rs +++ b/crates/agents/src/permissions.rs @@ -111,17 +111,16 @@ impl AgentPermissionResponse { } } - /// "始终允许" / ACP `allow_always` both mean: answer this request and YOLO the rest. + /// 只有显式选择连接级全部允许时,才改变连接的审批模式。 pub fn should_persist_auto_approve(&self, options: &[AgentPermissionOption]) -> bool { match self { Self::Selected { option_id, persist, .. } => { *persist - || options.iter().any(|option| { - option.id == *option_id - && option.kind == AgentPermissionOptionKind::AllowAlways - }) + && options + .iter() + .any(|option| option.id == *option_id && option.kind.is_allow()) } Self::Cancelled => false, } @@ -378,13 +377,14 @@ mod tests { } #[test] - fn persist_flag_or_allow_always_option_upgrades_the_connection() { + fn explicit_persist_flag_upgrades_the_connection() { let options = vec![ option("allow-once", AgentPermissionOptionKind::AllowOnce), option("allow-always", AgentPermissionOptionKind::AllowAlways), ]; assert!( - AgentPermissionResponse::selected("allow-always").should_persist_auto_approve(&options) + !AgentPermissionResponse::selected("allow-always") + .should_persist_auto_approve(&options) ); assert!( AgentPermissionResponse::selected_persist("allow-once") diff --git a/frontend/src/components/NormalizedConversation/conversation/PermissionRequestCard.test.tsx b/frontend/src/components/NormalizedConversation/conversation/PermissionRequestCard.test.tsx index db0e48783..1363d934e 100644 --- a/frontend/src/components/NormalizedConversation/conversation/PermissionRequestCard.test.tsx +++ b/frontend/src/components/NormalizedConversation/conversation/PermissionRequestCard.test.tsx @@ -142,12 +142,11 @@ describe('PermissionRequestCard', () => { expect( screen.getByRole('menuitem', { name: '总是允许全部' }) ).toBeInTheDocument(); - await user.click(screen.getByRole('menuitem', { name: '本次会话中允许' })); + await user.click(screen.getByRole('menuitem', { name: /允许类似命令/ })); expect(onRespond).toHaveBeenCalledWith('perm-1', { kind: 'selected', option_id: 'allow-similar', - persist: true, }); }); @@ -171,6 +170,35 @@ describe('PermissionRequestCard', () => { }); }); + it('将命令前缀原样展示并仅提交所选规则', async () => { + const user = userEvent.setup(); + const onRespond = vi.fn(); + render( + + ); + await user.click(screen.getByRole('button', { name: '展开允许选项' })); + await user.click( + screen.getByRole('menuitem', { name: /记住命令前缀.*git.*status/ }) + ); + expect(onRespond).toHaveBeenCalledWith('perm-1', { + kind: 'selected', + option_id: 'allow-prefix-1', + }); + }); + it('uses the agent-provided reject option for the reject action', () => { const onRespond = vi.fn(); render( diff --git a/frontend/src/components/NormalizedConversation/conversation/PermissionRequestCard.tsx b/frontend/src/components/NormalizedConversation/conversation/PermissionRequestCard.tsx index 26af9e2d5..4c4fa3648 100644 --- a/frontend/src/components/NormalizedConversation/conversation/PermissionRequestCard.tsx +++ b/frontend/src/components/NormalizedConversation/conversation/PermissionRequestCard.tsx @@ -22,10 +22,7 @@ import { DropdownMenuTrigger, } from '@/components/ui/dropdown-menu'; import { cn } from '@/lib/utils'; -import { - resolvePermissionAllowOption, - type PermissionAllowScope, -} from './permissionRequestPresentation'; +import { isAllowOption } from './permissionRequestPresentation'; /** * Inline, answerable permission request (Dimo style — docked at the bottom of @@ -57,18 +54,16 @@ export function PermissionRequestCard({ ); const permissionType = permissionTypeFor(detail.kind); const PermissionTypeIcon = permissionType.icon; - const primaryAllow = resolvePermissionAllowOption(options, 'once'); + const allowOptions = options.filter(isAllowOption); + const primaryAllow = allowOptions.find( + (option) => + option.kind === 'allow_once' && + !['acceptForSession', 'acceptAlways'].includes(option.id) && + !option.id.startsWith('allow-prefix-') + ); const rejectOption = options.find((option) => option.kind === 'reject_once') ?? options.find((option) => option.kind === 'reject_always'); - const allowScopes: Array<{ - scope: PermissionAllowScope; - label: string; - }> = [ - { scope: 'once', label: t('permissionRequestCard.allowOnce') }, - { scope: 'session', label: t('permissionRequestCard.allowSession') }, - { scope: 'always', label: t('permissionRequestCard.allowAlways') }, - ]; const respondWithOption = (option: AgentPermissionOption, persist = false) => onRespond(request.permission_id, { kind: 'selected', @@ -78,10 +73,7 @@ export function PermissionRequestCard({ ? { expected_revision: request.revision } : {}), }); - const respondWithScope = (scope: PermissionAllowScope) => { - const option = resolvePermissionAllowOption(options, scope); - if (option) respondWithOption(option, scope !== 'once'); - }; + const defaultAllow = primaryAllow ?? allowOptions[0]; return (
@@ -121,7 +113,7 @@ export function PermissionRequestCard({ > {t('permissionRequestCard.reject')} - {primaryAllow ? ( + {defaultAllow ? (
respondWithScope('once')} + onClick={() => respondWithOption(defaultAllow)} > - {t('permissionRequestCard.allow')} + {primaryAllow + ? t('permissionRequestCard.allow') + : defaultAllow.label} @@ -153,22 +147,35 @@ export function PermissionRequestCard({ side="top" className="w-[min(280px,calc(100vw-24px))] p-1.5" > - {allowScopes.map(({ scope, label }) => { - const option = resolvePermissionAllowOption( - options, - scope - ); - return ( - respondWithScope(scope)} - > - {label} - - ); - })} + {allowOptions.map((option) => ( + respondWithOption(option)} + > + + {option === primaryAllow + ? t('permissionRequestCard.allowOnce') + : option.id === 'acceptForSession' + ? t('permissionRequestCard.allowSession') + : option.label} + {option.description && ( + + {option.description} + + )} + + + ))} + {primaryAllow && ( + respondWithOption(primaryAllow, true)} + > + {t('permissionRequestCard.allowAlways')} + + )}
diff --git a/frontend/src/components/NormalizedConversation/useTimelineScrollController.ts b/frontend/src/components/NormalizedConversation/useTimelineScrollController.ts index 79325bed5..d0a3523fe 100644 --- a/frontend/src/components/NormalizedConversation/useTimelineScrollController.ts +++ b/frontend/src/components/NormalizedConversation/useTimelineScrollController.ts @@ -132,7 +132,13 @@ export function useTimelineScrollController({ index: number | null; }>({ sessionId: null, index: null }); const previousPrependEpochRef = useRef(0); + const readingAnchorRef = useRef<{ + key: string | number | bigint; + offset: number; + } | null>(null); const previousTotalSizeRef = useRef(0); + const cancelAnchorRestoreRef = useRef<(() => void) | null>(null); + useLayoutEffect(() => () => cancelAnchorRestoreRef.current?.(), [sessionId]); const pendingJumpTimelineIndexRef = useRef<{ index: number; align: 'start' | 'center' | 'end' | 'auto'; @@ -296,7 +302,22 @@ export function useTimelineScrollController({ ); const hasEarlierTimeline = hasHiddenEarlierItems || hasEarlier; + const captureReadingAnchor = useCallback(() => { + const container = containerRef.current; + const list = virtualListRef.current; + if (!container || !list) return; + const marginDelta = + measureScrollMargin(list, container) - + rowVirtualizer.options.scrollMargin; + const top = container.scrollTop - marginDelta; + const row = rowVirtualizer.getVirtualItems().find((item) => item.end > top); + readingAnchorRef.current = row + ? { key: row.key, offset: top - row.start } + : null; + }, [rowVirtualizer]); const loadEarlierTimeline = useCallback(() => { + cancelAnchorRestoreRef.current?.(); + captureReadingAnchor(); if (hasHiddenEarlierItems) { setVisibleTailSession((current) => { const baseCount = current.sessionId === sessionId ? current.count : 24; @@ -325,6 +346,7 @@ export function useTimelineScrollController({ }); void loadOlder(); }, [ + captureReadingAnchor, hasHiddenEarlierItems, loadOlder, sessionId, @@ -550,6 +572,13 @@ export function useTimelineScrollController({ const scrollHeight = container.scrollHeight; lastScrollTopRef.current = scrollTop; lastScrollHeightRef.current = scrollHeight; + if ( + readingAnchorRef.current && + event.nativeEvent.isTrusted && + programmaticScrollDepthRef.current === 0 + ) { + captureReadingAnchor(); + } const intent = conversationFollowIntent({ trustedUserScroll: event.nativeEvent.isTrusted && @@ -586,6 +615,7 @@ export function useTimelineScrollController({ updateActiveIndex(); }, [ + captureReadingAnchor, detachFromBottom, hasEarlierTimeline, loadEarlierTimeline, @@ -817,21 +847,81 @@ export function useTimelineScrollController({ const prepended = combinedPrependEpoch > previousPrependEpochRef.current; const container = containerRef.current; if (container) { - const nextTop = scrollTopAfterPrepend({ - followTail: followTailRef.current, - sessionChanged, - prepended, - previousTotalSize: previousTotalSizeRef.current, - nextTotalSize: totalSize, - scrollTop: container.scrollTop, - }); + const anchor = readingAnchorRef.current; + const row = + prepended && !sessionChanged && !followTailRef.current && anchor + ? rowVirtualizer.measurementsCache.find( + (item) => item.key === anchor.key + ) + : undefined; + const list = virtualListRef.current; + const nextTop = + row && anchor && list + ? row.start + + anchor.offset + + measureScrollMargin(list, container) - + rowVirtualizer.options.scrollMargin + : scrollTopAfterPrepend({ + followTail: followTailRef.current, + sessionChanged, + prepended, + previousTotalSize: previousTotalSizeRef.current, + nextTotalSize: totalSize, + scrollTop: container.scrollTop, + }); if (nextTop !== container.scrollTop) { runProgrammaticScroll(() => { container.scrollTop = nextTop; }); } + if (row && anchor && list) { + cancelAnchorRestoreRef.current?.(); + let frame = 0; + let stableFrames = 0; + const cancel = () => { + cancelAnimationFrame(frame); + container.removeEventListener('wheel', cancel, true); + container.removeEventListener('pointerdown', cancel, true); + window.removeEventListener('keydown', cancel, true); + cancelAnchorRestoreRef.current = null; + }; + const settle = () => { + const current = rowVirtualizer.measurementsCache.find( + (item) => item.key === anchor.key + ); + if (!current || followTailRef.current) return cancel(); + const top = + current.start + + anchor.offset + + measureScrollMargin(list, container) - + rowVirtualizer.options.scrollMargin; + const target = Math.max( + 0, + Math.min(top, container.scrollHeight - container.clientHeight) + ); + if (Math.abs(container.scrollTop - target) > 1) { + stableFrames = 0; + runProgrammaticScroll(() => { + container.scrollTop = target; + }); + } else if (++stableFrames >= 3) { + return cancel(); + } + frame = requestAnimationFrame(settle); + }; + container.addEventListener('wheel', cancel, { + capture: true, + passive: true, + }); + container.addEventListener('pointerdown', cancel, true); + window.addEventListener('keydown', cancel, true); + cancelAnchorRestoreRef.current = cancel; + frame = requestAnimationFrame(settle); + } } previousPrependEpochRef.current = combinedPrependEpoch; + if (prepended || sessionChanged || followTailRef.current) + readingAnchorRef.current = null; previousTotalSizeRef.current = totalSize; sessionPinRef.current = sessionId; const currentExpandableRevision = getExpandableRevision(); diff --git a/frontend/src/components/logs/VirtualizedList.test.ts b/frontend/src/components/logs/VirtualizedList.test.ts index 120982735..9292acc17 100644 --- a/frontend/src/components/logs/VirtualizedList.test.ts +++ b/frontend/src/components/logs/VirtualizedList.test.ts @@ -396,7 +396,7 @@ describe('conversation bottom distance', () => { windowHeight: 800, followTail: false, }) - ).toBe(2000); + ).toBeNull(); expect( scrollTopToRevealVirtualWindow({ scrollTop: 0, diff --git a/frontend/src/components/logs/VirtualizedList.tsx b/frontend/src/components/logs/VirtualizedList.tsx index 241fd07d9..09b5ca792 100644 --- a/frontend/src/components/logs/VirtualizedList.tsx +++ b/frontend/src/components/logs/VirtualizedList.tsx @@ -166,7 +166,8 @@ export function scrollTopToRevealVirtualWindow(input: { windowHeight: number; followTail: boolean; }): number | null { - if (input.viewportHeight <= 0 || input.windowHeight <= 1) return null; + if (!input.followTail || input.viewportHeight <= 0 || input.windowHeight <= 1) + return null; const visualTop = Math.max(0, input.windowStart ?? input.scrollMargin); const visualBottom = visualTop + input.windowHeight; const viewTop = input.scrollTop; @@ -175,8 +176,8 @@ export function scrollTopToRevealVirtualWindow(input: { const maxScroll = Math.max(0, input.scrollHeight - input.viewportHeight); let next: number | null = null; if (!intersects) { - next = input.followTail ? maxScroll : Math.min(visualTop, maxScroll); - } else if (input.followTail && visualBottom > viewBottom + 1) { + next = maxScroll; + } else if (visualBottom > viewBottom + 1) { next = Math.min( Math.max(0, visualBottom - input.viewportHeight), maxScroll