Skip to content
Merged
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
3 changes: 2 additions & 1 deletion crates/goose-server/src/openapi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use goose::config::ExtensionEntry;
use goose::conversation::Conversation;
use goose::dictation::download_manager::{DownloadProgress, DownloadStatus};
use goose::model::ModelConfig;
use goose::permission::permission_confirmation::PrincipalType;
use goose::permission::permission_confirmation::{Permission, PrincipalType};
use goose::providers::base::{ConfigKey, ModelInfo, ProviderMetadata, ProviderType};
use goose::session::{Session, SessionInsights, SessionType, SystemInfo};
use rmcp::model::{
Expand Down Expand Up @@ -498,6 +498,7 @@ derive_utoipa!(Icon as IconSchema);
ToolAnnotationsSchema,
ToolInfo,
PermissionLevel,
Permission,
PrincipalType,
ModelInfo,
ModelConfig,
Expand Down
12 changes: 3 additions & 9 deletions crates/goose-server/src/routes/action_required.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub struct ConfirmToolActionRequest {
id: String,
#[serde(default = "default_principal_type")]
principal_type: PrincipalType,
action: String,
action: Permission,
session_id: String,
}

Expand All @@ -37,19 +37,13 @@ pub async fn confirm_tool_action(
Json(request): Json<ConfirmToolActionRequest>,
) -> Result<Json<Value>, ErrorResponse> {
let agent = state.get_agent_for_route(request.session_id).await?;
let permission = match request.action.as_str() {
"always_allow" => Permission::AlwaysAllow,
"allow_once" => Permission::AllowOnce,
"deny" => Permission::DenyOnce,
_ => Permission::DenyOnce,
};

agent
.handle_confirmation(
request.id.clone(),
PermissionConfirmation {
principal_type: request.principal_type,
permission,
permission: request.action,
},
)
.await;
Expand Down Expand Up @@ -91,7 +85,7 @@ mod tests {
serde_json::to_string(&ConfirmToolActionRequest {
id: "test-id".to_string(),
principal_type: PrincipalType::Tool,
action: "allow_once".to_string(),
action: Permission::AllowOnce,
session_id: "test-session".to_string(),
})
.unwrap(),
Expand Down
3 changes: 2 additions & 1 deletion crates/goose/src/permission/permission_confirmation.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum Permission {
AlwaysAllow,
AllowOnce,
Expand Down
12 changes: 11 additions & 1 deletion ui/desktop/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -3555,7 +3555,7 @@
],
"properties": {
"action": {
"type": "string"
"$ref": "#/components/schemas/Permission"
},
"id": {
"type": "string"
Expand Down Expand Up @@ -5240,6 +5240,16 @@
}
}
},
"Permission": {
"type": "string",
"enum": [
"always_allow",
"allow_once",
"cancel",
"deny_once",
"always_deny"
]
},
"PermissionLevel": {
"type": "string",
"description": "Enum representing the possible permission levels for a tool.",
Expand Down
2 changes: 1 addition & 1 deletion ui/desktop/src/api/index.ts

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion ui/desktop/src/api/types.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ export type ConfigResponse = {
};

export type ConfirmToolActionRequest = {
action: string;
action: Permission;
id: string;
principalType?: PrincipalType;
sessionId: string;
Expand Down Expand Up @@ -662,6 +662,8 @@ export type ParseRecipeResponse = {
recipe: Recipe;
};

export type Permission = 'always_allow' | 'allow_once' | 'cancel' | 'deny_once' | 'always_deny';

/**
* Enum representing the possible permission levels for a tool.
*/
Expand Down
71 changes: 53 additions & 18 deletions ui/desktop/src/components/GooseMessage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import {
getToolConfirmationContent,
getElicitationContent,
getPendingToolConfirmationIds,
getAnyToolConfirmationData,
ToolConfirmationData,
NotificationEvent,
} from '../types/message';
import { Message } from '../api';
Expand All @@ -26,7 +28,7 @@ interface GooseMessageProps {
metadata?: string[];
toolCallNotifications: Map<string, NotificationEvent[]>;
append: (value: string) => void;
isStreaming?: boolean; // Whether this message is currently being streamed
isStreaming: boolean;
submitElicitationResponse?: (
elicitationId: string,
userData: Record<string, unknown>
Expand All @@ -39,7 +41,7 @@ export default function GooseMessage({
messages,
toolCallNotifications,
append,
isStreaming = false,
isStreaming,
submitElicitationResponse,
}: GooseMessageProps) {
const contentRef = useRef<HTMLDivElement | null>(null);
Expand Down Expand Up @@ -69,6 +71,18 @@ export default function GooseMessage({
const messageIndex = messages.findIndex((msg) => msg.id === message.id);
const toolConfirmationContent = getToolConfirmationContent(message);
const elicitationContent = getElicitationContent(message);

const findConfirmationForToolAcrossMessages = (
toolRequestId: string
): ToolConfirmationData | undefined => {
for (const msg of messages) {
const confirmationData = getAnyToolConfirmationData(msg);
if (confirmationData && confirmationData.id === toolRequestId) {
return confirmationData;
}
}
return undefined;
};
const toolCallChains = useMemo(() => identifyConsecutiveToolCalls(messages), [messages]);
const hideTimestamp = useMemo(
() => shouldHideTimestamp(messageIndex, toolCallChains),
Expand All @@ -77,6 +91,20 @@ export default function GooseMessage({
const hasToolConfirmation = toolConfirmationContent !== undefined;
const hasElicitation = elicitationContent !== undefined;

const toolConfirmationShownInline = useMemo(() => {
if (!toolConfirmationContent) return false;
const confirmationData = getAnyToolConfirmationData(message);
if (!confirmationData) return false;

for (const msg of messages) {
const requests = getToolRequests(msg);
if (requests.some((req) => req.id === confirmationData.id)) {
return true;
}
}
return false;
}, [toolConfirmationContent, message, messages]);

const toolResponsesMap = useMemo(() => {
const responseMap = new Map();

Expand Down Expand Up @@ -149,20 +177,28 @@ export default function GooseMessage({
<div className={cn(displayText && 'mt-2')}>
<div className="relative flex flex-col w-full">
<div className="flex flex-col gap-3">
{toolRequests.map((toolRequest) => (
<div className="goose-message-tool" key={toolRequest.id}>
<ToolCallWithResponse
sessionId={sessionId}
isCancelledMessage={false}
toolRequest={toolRequest}
toolResponse={toolResponsesMap.get(toolRequest.id)}
notifications={toolCallNotifications.get(toolRequest.id)}
isStreamingMessage={isStreaming}
isPendingApproval={pendingConfirmationIds.has(toolRequest.id)}
append={append}
/>
</div>
))}
{toolRequests.map((toolRequest) => {
const hasResponse = toolResponsesMap.has(toolRequest.id);
const isPending = pendingConfirmationIds.has(toolRequest.id);
const confirmationContent = findConfirmationForToolAcrossMessages(toolRequest.id);
const isApprovalClicked = confirmationContent && !isPending && hasResponse;
return (
<div className="goose-message-tool" key={toolRequest.id}>
<ToolCallWithResponse
sessionId={sessionId}
isCancelledMessage={false}
toolRequest={toolRequest}
toolResponse={toolResponsesMap.get(toolRequest.id)}
notifications={toolCallNotifications.get(toolRequest.id)}
isStreamingMessage={isStreaming}
isPendingApproval={isPending}
append={append}
confirmationContent={confirmationContent}
isApprovalClicked={isApprovalClicked}
/>
</div>
);
})}
</div>
<div className="text-xs text-text-muted transition-all duration-200 group-hover:-translate-y-4 group-hover:opacity-0 pt-1">
{!isStreaming && !hideTimestamp && timestamp}
Expand All @@ -171,10 +207,9 @@ export default function GooseMessage({
</div>
)}

{hasToolConfirmation && (
{hasToolConfirmation && !toolConfirmationShownInline && (
<ToolCallConfirmation
sessionId={sessionId}
isCancelledMessage={false}
isClicked={false}
actionRequiredContent={toolConfirmationContent}
/>
Expand Down
99 changes: 99 additions & 0 deletions ui/desktop/src/components/ToolApprovalButtons.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { useState, useEffect } from 'react';
import { Button } from './ui/button';
import { confirmToolAction, Permission } from '../api';

const globalApprovalState = new Map<
string,
{
decision: Permission | null;
isClicked: boolean;
}
>();

export interface ToolApprovalData {
id: string;
toolName: string;
prompt?: string;
sessionId: string;
isClicked?: boolean;
}

export default function ToolApprovalButtons({ data }: { data: ToolApprovalData }) {
const { id, toolName, prompt, sessionId, isClicked: initialIsClicked } = data;

const storedState = globalApprovalState.get(id);
const [decision, setDecision] = useState<Permission | null>(storedState?.decision ?? null);
const [isClicked, setIsClicked] = useState(storedState?.isClicked ?? initialIsClicked ?? false);

useEffect(() => {
const currentState = globalApprovalState.get(id);
if (currentState) {
setDecision(currentState.decision);
setIsClicked(currentState.isClicked);
}
}, [id]);

useEffect(() => {
globalApprovalState.set(id, { decision, isClicked });
}, [id, decision, isClicked]);

const handleAction = async (action: Permission) => {
setDecision(action);
setIsClicked(true);

try {
const response = await confirmToolAction({
body: {
sessionId,
id,
action,
principalType: 'Tool',
},
});
if (response.error) {
console.error('Failed to confirm tool action:', response.error);
}
} catch (err) {
console.error('Error confirming tool action:', err);
}
};

if (isClicked && decision) {
const statusMessages: Record<Permission, string> = {
allow_once: 'Allowed once',
always_allow: 'Always allowed',
always_deny: 'Denied',
deny_once: 'Denied once',
cancel: 'Cancelled',
};
return (
<p className="text-sm text-muted-foreground mt-2">
{toolName} - {statusMessages[decision]}
</p>
);
}

return (
<div className="flex items-center gap-2 mt-2">
<Button
className="rounded-full"
variant="secondary"
onClick={() => handleAction('allow_once')}
>
Allow Once
</Button>
{!prompt && (
<Button
className="rounded-full"
variant="secondary"
onClick={() => handleAction('always_allow')}
>
Always Allow
</Button>
)}
<Button className="rounded-full" variant="outline" onClick={() => handleAction('deny_once')}>
Deny
</Button>
</div>
);
}
Loading
Loading