Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 79 additions & 2 deletions crates/agents/src/engine/codex_protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ pub fn codex_approval_options() -> Vec<AgentPermissionOption> {
AgentPermissionOption {
id: "acceptForSession".to_string(),
label: "Allow for session".to_string(),
kind: AgentPermissionOptionKind::AllowAlways,
kind: AgentPermissionOptionKind::AllowOnce,
description: None,
},
AgentPermissionOption {
Expand All @@ -87,6 +87,42 @@ pub fn codex_approval_options() -> Vec<AgentPermissionOption> {
]
}

fn command_approval_options(params: &Value) -> Vec<AgentPermissionOption> {
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<EngineModelInfo> {
vec![
EngineModelInfo {
Expand Down Expand Up @@ -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))
}
Expand Down Expand Up @@ -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::<usize>()
.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 {
Expand Down Expand Up @@ -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"]));
Expand Down
14 changes: 7 additions & 7 deletions crates/agents/src/permissions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand Down Expand Up @@ -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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
});
});

Expand All @@ -171,6 +170,35 @@ describe('PermissionRequestCard', () => {
});
});

it('将命令前缀原样展示并仅提交所选规则', async () => {
const user = userEvent.setup();
const onRespond = vi.fn();
render(
<PermissionRequestCard
request={fileEditRequest({
options: [
{ id: 'accept', label: '允许一次', kind: 'allow_once' },
{
id: 'allow-prefix-1',
label: '记住命令前缀',
description: '["git","status"]',
kind: 'allow_once',
},
],
})}
onRespond={onRespond}
/>
);
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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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',
Expand All @@ -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 (
<section className="permission-request-card conv-entry-item w-full rounded-lg border border-border bg-[var(--conv-surface-card)] px-4 py-3.5 text-sm">
Expand Down Expand Up @@ -121,7 +113,7 @@ export function PermissionRequestCard({
>
{t('permissionRequestCard.reject')}
</Button>
{primaryAllow ? (
{defaultAllow ? (
<div
className="permission-request-allow-group inline-flex items-stretch"
role="group"
Expand All @@ -132,9 +124,11 @@ export function PermissionRequestCard({
size="sm"
disabled={responding}
className="rounded-r-none"
onClick={() => respondWithScope('once')}
onClick={() => respondWithOption(defaultAllow)}
>
{t('permissionRequestCard.allow')}
{primaryAllow
? t('permissionRequestCard.allow')
: defaultAllow.label}
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
Expand All @@ -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 (
<DropdownMenuItem
key={scope}
disabled={responding || !option}
className="px-2.5 py-2"
onSelect={() => respondWithScope(scope)}
>
{label}
</DropdownMenuItem>
);
})}
{allowOptions.map((option) => (
<DropdownMenuItem
key={option.id}
disabled={responding}
className="px-2.5 py-2"
onSelect={() => respondWithOption(option)}
>
<span className="break-all">
{option === primaryAllow
? t('permissionRequestCard.allowOnce')
: option.id === 'acceptForSession'
? t('permissionRequestCard.allowSession')
: option.label}
{option.description && (
<small className="block">
{option.description}
</small>
)}
</span>
</DropdownMenuItem>
))}
{primaryAllow && (
<DropdownMenuItem
disabled={responding}
onSelect={() => respondWithOption(primaryAllow, true)}
>
{t('permissionRequestCard.allowAlways')}
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
Expand Down
Loading
Loading