diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCard.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCard.svelte
index 796f2a4d2a53..93de621f1dd0 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCard.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCard.svelte
@@ -14,12 +14,13 @@
-
-
+
+
+
-
+
{@render message()}
-
+
{#if detail}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte
index 9e50951e353d..9acdde9867cd 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte
@@ -2,44 +2,86 @@
import { Button, buttonVariants } from '@ggml-org/llama-ui/ui/button';
import * as ButtonGroup from '@ggml-org/llama-ui/ui/button-group';
import * as DropdownMenu from '@ggml-org/llama-ui/ui/dropdown-menu';
+ import { Input } from '@ggml-org/llama-ui/ui/input';
import { cn } from '@ggml-org/llama-ui/utils';
import { ChevronDown, ShieldQuestion } from '@lucide/svelte';
import { ChatMessageActionCard } from '#lib/components/app/index.ts';
import { TOOL_SERVER_LABELS } from '#lib/constants/index.ts';
import { ToolPermissionDecision, ToolSource } from '#lib/enums/index.ts';
import { toolsStore } from '#lib/stores/index.ts';
+ import type { PermissionAnswer, PermissionRequest } from '#lib/types/index.ts';
interface Props {
- toolName: string;
- serverLabel: string;
- /**
- * The shell command the call would run, shown in full: the trace row may
- * show the model's own description of it, which is not what gets executed.
- */
- command?: string;
- onDecision: (decision: ToolPermissionDecision) => void;
+ request: PermissionRequest;
+ onDecision: (decision: ToolPermissionDecision, answer?: PermissionAnswer) => void;
}
- let { command, onDecision, serverLabel, toolName }: Props = $props();
+ let { onDecision, request }: Props = $props();
+
+ // the proposed patterns, editable before a choice that remembers them
+ // svelte-ignore state_referenced_locally
+ let patterns = $state([...request.patterns]);
+
+ const isShell = $derived(request.command !== undefined);
+ const folderName = $derived(
+ request.cwd
+ ?.replace(/[\\/]+$/, '')
+ .split(/[\\/]/)
+ .pop() || request.cwd
+ );
+ const providerName = $derived.by(() => {
+ if (request.serverLabel) return request.serverLabel;
+
+ const source = toolsStore.getToolSource(request.toolName);
+
+ if (source === ToolSource.SERVER) return TOOL_SERVER_LABELS[ToolSource.SERVER];
+
+ if (source === ToolSource.CUSTOM) return TOOL_SERVER_LABELS[ToolSource.CUSTOM];
+
+ return 'MCP Tools';
+ });
+
+ function decide(decision: ToolPermissionDecision) {
+ onDecision(decision, isShell ? { patterns } : undefined);
+ }
{#snippet message()}
- Allow use of {toolName} {#if serverLabel}
- from {serverLabel} {/if}?
+ Allow use of {request.toolName} {#if request.serverLabel}
+ from {request.serverLabel} {/if}?
+
+ {#if isShell && patterns.length > 0}
+
+
+ Remembered as {patterns.length > 1 ? 'these patterns' : 'this pattern'} when you allow it for
+ this chat or always:
+
+
+ {#each patterns as _, index (index)}
+
+ {/each}
+
+ {/if}
{/snippet}
{#snippet detail()}
- {#if command}
+
+ {#if request.command !== undefined}
{command}
+ class="mb-3 max-h-40 overflow-auto rounded-md bg-(--surface-code) px-3 py-2 font-mono text-caption whitespace-pre-wrap break-words">{request.command}
{/if}
{/snippet}
{#snippet actions()}
- onDecision(ToolPermissionDecision.ONCE)} size="sm" variant="outline">
+ decide(ToolPermissionDecision.ONCE)} size="sm" variant="outline">
Allow once
@@ -57,31 +99,34 @@
- onDecision(ToolPermissionDecision.ALWAYS)}>
- Always allow {toolName}
- tool
+ decide(ToolPermissionDecision.SESSION)}>
+ Allow for this chat
- {#if serverLabel}
- onDecision(ToolPermissionDecision.ALWAYS_SERVER)}>
- Always allow all tools from {serverLabel}
+ {#if request.cwd}
+ decide(ToolPermissionDecision.ALWAYS_HERE)}>
+ Always allow in {folderName}
- {:else}
- {@const source = toolsStore.getToolSource(toolName)}
- {@const providerName =
- source === ToolSource.SERVER
- ? TOOL_SERVER_LABELS[ToolSource.SERVER]
- : source === ToolSource.CUSTOM
- ? TOOL_SERVER_LABELS[ToolSource.CUSTOM]
- : 'MCP Tools'}
- onDecision(ToolPermissionDecision.ALWAYS_SERVER)}>
- Approve all tools from {providerName}
+ {/if}
+
+ decide(ToolPermissionDecision.ALWAYS)}>
+ {#if isShell}
+ Always allow everywhere
+ {:else}
+ Always allow {request.toolName}
+ tool
+ {/if}
+
+
+ {#if !isShell}
+ decide(ToolPermissionDecision.ALWAYS_SERVER)}>
+ Always allow all tools from {providerName}
{/if}
- onDecision(ToolPermissionDecision.DENY)} size="sm" variant="destructive">
+ decide(ToolPermissionDecision.DENY)} size="sm" variant="destructive">
Deny
{/snippet}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte
index 988cb11d9afa..e52fbc995c02 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte
@@ -1,7 +1,6 @@
+
+
+
+
Permission rules
+
+
+ Added when you allow a command or a tool in its prompt for good, everywhere or in one folder.
+ Deny wins over ask, and ask over allow. Rules spare prompts; what tools may do is still set by
+ llama-server.
+
+
+
+ {#if rules.length === 0}
+ No rules yet
+ {:else}
+
+ {#each rules as rule (rule.id)}
+
+
+ {EFFECT_LABELS[rule.effect]}
+
+
+
+
+ {rule.pattern ?? toolName(rule)}
+
+
+
+ {rule.pattern ? `${toolName(rule)} · ` : ''}{rule.cwd ?? 'Everywhere'}
+
+
+
+ permissionsStore.removeRule(rule.id)}
+ size="icon-sm"
+ variant="ghost"
+ >
+
+
+
+ {/each}
+
+ {/if}
+
diff --git a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatToolsTab.svelte b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatToolsTab.svelte
index 5efae6c31b37..442b4e33b308 100644
--- a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatToolsTab.svelte
+++ b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatToolsTab.svelte
@@ -3,7 +3,7 @@
import * as Collapsible from '@ggml-org/llama-ui/ui/collapsible';
import * as Select from '@ggml-org/llama-ui/ui/select';
import { ChevronDown, ChevronRight } from '@lucide/svelte';
- import { TruncatedText } from '#lib/components/app/index.ts';
+ import { SettingsChatPermissionRules, TruncatedText } from '#lib/components/app/index.ts';
import {
ICON_CLASS_DEFAULT,
SETTINGS_KEYS,
@@ -229,3 +229,5 @@
{/each}
{/if}
+
+
diff --git a/ui/apps/chat/src/lib/components/app/settings/index.ts b/ui/apps/chat/src/lib/components/app/settings/index.ts
index 184a34fc7f51..bb56fc5baac6 100644
--- a/ui/apps/chat/src/lib/components/app/settings/index.ts
+++ b/ui/apps/chat/src/lib/components/app/settings/index.ts
@@ -91,3 +91,8 @@ export { default as SettingsChatFields } from './SettingsChat/SettingsChatFields
* server favicons and permission management controls.
*/
export { default as SettingsChatToolsTab } from './SettingsChat/SettingsChatToolsTab.svelte';
+
+/**
+ * **SettingsChatPermissionRules** - The kept permission rules, with a way to remove each
+ */
+export { default as SettingsChatPermissionRules } from './SettingsChat/SettingsChatPermissionRules.svelte';
diff --git a/ui/apps/chat/src/lib/constants/settings-keys.constants.ts b/ui/apps/chat/src/lib/constants/settings-keys.constants.ts
index 375b935b0a5a..cf18451e8958 100644
--- a/ui/apps/chat/src/lib/constants/settings-keys.constants.ts
+++ b/ui/apps/chat/src/lib/constants/settings-keys.constants.ts
@@ -45,6 +45,7 @@ export const SETTINGS_KEYS = {
// Display
PASTE_LONG_TEXT_TO_FILE_LEN: 'pasteLongTextToFileLen',
PDF_AS_IMAGE: 'pdfAsImage',
+ PERMISSION_MODE: 'permissionMode',
// Performance
PRE_ENCODE_CONVERSATION: 'preEncodeConversation',
PRESENCE_PENALTY: 'presence_penalty',
diff --git a/ui/apps/chat/src/lib/constants/settings.constants.ts b/ui/apps/chat/src/lib/constants/settings.constants.ts
index 4fcd7f307c84..4ff10e312182 100644
--- a/ui/apps/chat/src/lib/constants/settings.constants.ts
+++ b/ui/apps/chat/src/lib/constants/settings.constants.ts
@@ -11,6 +11,8 @@ import { VOICE_MICROPHONE_AUTO } from '@ggml-org/llama-voice';
import AudioLines from '@lucide/svelte/icons/audio-lines';
import Code from '@lucide/svelte/icons/code';
import Database from '@lucide/svelte/icons/database';
+import Eye from '@lucide/svelte/icons/eye';
+import FilePen from '@lucide/svelte/icons/file-pen';
import Funnel from '@lucide/svelte/icons/funnel';
import ListRestart from '@lucide/svelte/icons/list-restart';
import Mic from '@lucide/svelte/icons/mic';
@@ -18,10 +20,12 @@ import Monitor from '@lucide/svelte/icons/monitor';
import Moon from '@lucide/svelte/icons/moon';
import PencilRuler from '@lucide/svelte/icons/pencil-ruler';
import Puzzle from '@lucide/svelte/icons/puzzle';
+import ShieldQuestion from '@lucide/svelte/icons/shield-question-mark';
import SlidersVertical from '@lucide/svelte/icons/sliders-vertical';
import Sun from '@lucide/svelte/icons/sun';
import TextCursorInput from '@lucide/svelte/icons/text-cursor-input';
-import { SyncableParameterType, VoiceInputMode } from '#lib/enums/index.ts';
+import Zap from '@lucide/svelte/icons/zap';
+import { PermissionMode, SyncableParameterType, VoiceInputMode } from '#lib/enums/index.ts';
import { SettingsFieldType } from '#lib/enums/settings.enums.ts';
import { ColorMode } from '#lib/enums/ui.enums.ts';
import type {
@@ -542,6 +546,19 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [
label: 'Agentic turns',
type: SettingsFieldType.INPUT
},
+ {
+ defaultValue: PermissionMode.ASK,
+ help: 'What happens to a tool call that no permission rule decides. Ask shows a prompt. Accept edits also writes and edits files inside the working folder without asking. Read-only refuses tools that change files or run commands, except read-only shell commands. Auto-approve runs everything no rule denies. Commands that could destroy the system are refused in every mode.',
+ key: SETTINGS_KEYS.PERMISSION_MODE,
+ label: 'Permission mode',
+ options: [
+ { icon: ShieldQuestion, label: 'Ask', value: PermissionMode.ASK },
+ { icon: FilePen, label: 'Accept edits', value: PermissionMode.ACCEPT_EDITS },
+ { icon: Eye, label: 'Read-only', value: PermissionMode.READ_ONLY },
+ { icon: Zap, label: 'Auto-approve', value: PermissionMode.AUTO }
+ ],
+ type: SettingsFieldType.SELECT
+ },
{
defaultValue: DEFAULT_MCP_CONFIG.requestTimeoutSeconds,
extension: 'mcp',
diff --git a/ui/apps/chat/src/lib/constants/storage.constants.ts b/ui/apps/chat/src/lib/constants/storage.constants.ts
index fa8d6a09dfb9..17a860a3aca9 100644
--- a/ui/apps/chat/src/lib/constants/storage.constants.ts
+++ b/ui/apps/chat/src/lib/constants/storage.constants.ts
@@ -14,7 +14,9 @@ export const STORAGE_APP_NAME_DEPRECATED = 'LlamaCppWebui';
/** @deprecated Deprecated IndexedDB name — will be removed after all users have migrated */
export const DB_APP_NAME_DEPRECATED = 'LlamacppWebui';
+/** @deprecated Tools allowed for good, before permission rules; read once to migrate them */
export const ALWAYS_ALLOWED_TOOLS_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.alwaysAllowedTools`;
+export const PERMISSION_RULES_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.permissionRules`;
export const CONFIG_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.config`;
export const DISABLED_TOOLS_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.disabledTools`;
diff --git a/ui/apps/chat/src/lib/enums/index.ts b/ui/apps/chat/src/lib/enums/index.ts
index 8ac0994c3b12..4a54bbc90420 100644
--- a/ui/apps/chat/src/lib/enums/index.ts
+++ b/ui/apps/chat/src/lib/enums/index.ts
@@ -124,6 +124,8 @@ export {
ToolResponseField
} from './tools.enums';
+export { PermissionEffect, PermissionMode } from './permissions.enums';
+
export { SplashOrientation } from './splash.enums';
export { ChatFormVoiceState, VoiceInputMode, VoiceMode, VoiceModelRole } from './voice.enums';
diff --git a/ui/apps/chat/src/lib/enums/permissions.enums.ts b/ui/apps/chat/src/lib/enums/permissions.enums.ts
new file mode 100644
index 000000000000..844282d5efc1
--- /dev/null
+++ b/ui/apps/chat/src/lib/enums/permissions.enums.ts
@@ -0,0 +1,18 @@
+/** What a permission rule does with a tool call it matches. */
+export enum PermissionEffect {
+ ALLOW = 'allow',
+ ASK = 'ask',
+ DENY = 'deny'
+}
+
+/** How tool calls that no rule decides are handled. */
+export enum PermissionMode {
+ /** Also run file writes and edits inside the working folder without asking. */
+ ACCEPT_EDITS = 'accept_edits',
+ /** Ask for every call no rule decides. */
+ ASK = 'ask',
+ /** Run every call no rule denies, except the commands no mode may run. */
+ AUTO = 'auto',
+ /** Refuse tools that can change files or run commands. */
+ READ_ONLY = 'read_only'
+}
diff --git a/ui/apps/chat/src/lib/enums/tools.enums.ts b/ui/apps/chat/src/lib/enums/tools.enums.ts
index d46d7af83407..99bbe29f165a 100644
--- a/ui/apps/chat/src/lib/enums/tools.enums.ts
+++ b/ui/apps/chat/src/lib/enums/tools.enums.ts
@@ -13,10 +13,16 @@ export enum ServerToolType {
}
export enum ToolPermissionDecision {
+ /** Always, everywhere. */
ALWAYS = 'always',
+ /** Always, in the conversation's working folder. */
+ ALWAYS_HERE = 'always_here',
+ /** Every tool of the same server, always. */
ALWAYS_SERVER = 'always_server',
DENY = 'deny',
- ONCE = 'once'
+ ONCE = 'once',
+ /** For the rest of this conversation, until the app reloads. */
+ SESSION = 'session'
}
export enum ToolResponseField {
diff --git a/ui/apps/chat/src/lib/stores/agentic/gates.svelte.ts b/ui/apps/chat/src/lib/stores/agentic/gates.svelte.ts
index 217f9205bbb4..14e107c31dee 100644
--- a/ui/apps/chat/src/lib/stores/agentic/gates.svelte.ts
+++ b/ui/apps/chat/src/lib/stores/agentic/gates.svelte.ts
@@ -7,13 +7,15 @@
* resolvePermission/resolveContinue. Owned by agenticStore, no host coupling.
*/
-import { ToolPermissionDecision } from '#lib/enums/index.ts';
+import { PermissionEffect, ToolPermissionDecision } from '#lib/enums/index.ts';
// direct imports between stores, not via the barrel, to avoid circular deps
import { permissionsStore } from '#lib/stores/permissions.svelte.ts';
import { toolsStore } from '#lib/stores/tools.svelte.ts';
import type {
DatabaseMessageExtra,
- PendingPermissionRequest,
+ PermissionAnswer,
+ PermissionRequest,
+ PermissionRule,
SteeringMessage
} from '#lib/types/index.ts';
import { SvelteMap } from 'svelte/reactivity';
@@ -25,9 +27,12 @@ export class AgenticGates {
private pendingContinueRequests = new SvelteMap
();
/** Dedicated reactive state for pending permission requests (ensures immediate UI updates) */
- private pendingPermissions = new SvelteMap();
+ private pendingPermissions = new SvelteMap();
/** Resolve functions for pending permission Promises; nothing derives from this map */
- private permissionResolvers = new SvelteMap void>();
+ private permissionResolvers = new SvelteMap<
+ string,
+ (decision: ToolPermissionDecision, answer?: PermissionAnswer) => void
+ >();
/** Reactive: queued steering messages to inject between turns */
private steeringMessages = new SvelteMap();
@@ -68,7 +73,7 @@ export class AgenticGates {
return this.pendingContinueRequests.get(conversationId) ?? false;
}
- getPendingPermissionRequest(conversationId: string): PendingPermissionRequest | null {
+ getPendingPermissionRequest(conversationId: string): PermissionRequest | null {
return this.pendingPermissions.get(conversationId) ?? null;
}
@@ -128,20 +133,17 @@ export class AgenticGates {
});
}
+ /**
+ * Ask the user about a tool call, and keep what they chose to remember:
+ * for this conversation, in its working folder, everywhere, or every tool
+ * of the same server. A stopped run counts as a denial.
+ */
async requestPermission(
conversationId: string,
- toolName: string,
- serverLabel: string,
- toolCallId: string,
+ request: PermissionRequest,
signal?: AbortSignal
): Promise {
- const permissionKey = toolsStore.getPermissionKey(toolName);
-
- if (permissionKey && permissionsStore.hasTool(permissionKey)) {
- return ToolPermissionDecision.ONCE;
- }
-
- this.pendingPermissions.set(conversationId, { serverLabel, toolCallId, toolName });
+ this.pendingPermissions.set(conversationId, request);
return new Promise((resolve) => {
if (signal?.aborted) {
@@ -151,24 +153,9 @@ export class AgenticGates {
return;
}
- this.permissionResolvers.set(conversationId, (decision) => {
+ this.permissionResolvers.set(conversationId, (decision, answer) => {
this.pendingPermissions.set(conversationId, null);
-
- if (decision === ToolPermissionDecision.ALWAYS && permissionKey) {
- permissionsStore.allowTool(permissionKey);
- } else if (decision === ToolPermissionDecision.ALWAYS_SERVER) {
- const serverToolKeys = toolsStore.allTools
- .filter((t) =>
- t.serverName
- ? t.serverName === serverLabel
- : toolsStore.getToolServerLabel(t.definition.function.name) === serverLabel
- )
- .map((t) => toolsStore.getPermissionKey(t.definition.function.name)!)
- .filter((k): k is string => k !== null);
-
- permissionsStore.allowTools(serverToolKeys);
- }
-
+ this.remember(conversationId, request, decision, answer);
resolve(decision);
});
@@ -197,12 +184,59 @@ export class AgenticGates {
}
}
- resolvePermission(conversationId: string, decision: ToolPermissionDecision): void {
+ resolvePermission(
+ conversationId: string,
+ decision: ToolPermissionDecision,
+ answer?: PermissionAnswer
+ ): void {
const resolver = this.permissionResolvers.get(conversationId);
if (resolver) {
this.permissionResolvers.delete(conversationId);
- resolver(decision);
+ resolver(decision, answer);
+ }
+ }
+
+ private remember(
+ conversationId: string,
+ request: PermissionRequest,
+ decision: ToolPermissionDecision,
+ answer?: PermissionAnswer
+ ): void {
+ if (decision === ToolPermissionDecision.ALWAYS_SERVER) {
+ const serverToolKeys = toolsStore.allTools
+ .filter((t) =>
+ t.serverName
+ ? t.serverName === request.serverLabel
+ : toolsStore.getToolServerLabel(t.definition.function.name) === request.serverLabel
+ )
+ .map((t) => toolsStore.getPermissionKey(t.definition.function.name))
+ .filter((k): k is string => k !== null);
+
+ permissionsStore.allowTools(serverToolKeys);
+
+ return;
+ }
+
+ const patterns = (answer?.patterns ?? request.patterns)
+ .map((pattern) => pattern.trim())
+ .filter(Boolean);
+ // a shell command is remembered by its patterns, any other tool as a whole
+ const rules: Omit[] =
+ request.command !== undefined && patterns.length > 0
+ ? patterns.map((pattern) => ({
+ effect: PermissionEffect.ALLOW,
+ pattern,
+ tool: request.toolKey
+ }))
+ : [{ effect: PermissionEffect.ALLOW, tool: request.toolKey }];
+
+ if (decision === ToolPermissionDecision.SESSION) {
+ permissionsStore.addSessionRules(conversationId, rules);
+ } else if (decision === ToolPermissionDecision.ALWAYS_HERE && request.cwd) {
+ permissionsStore.addRules(rules.map((rule) => ({ ...rule, cwd: request.cwd })));
+ } else if (decision === ToolPermissionDecision.ALWAYS) {
+ permissionsStore.addRules(rules);
}
}
}
diff --git a/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts b/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts
index d42ec246f4b6..573239edb92f 100644
--- a/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts
+++ b/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts
@@ -22,7 +22,12 @@ import {
type ToolContext,
type ToolResult
} from '@ggml-org/llama-harness';
-import { DEFAULT_AGENTIC_CONFIG, NEWLINE, TOOL_DENIED_RESULT } from '#lib/constants/index.ts';
+import {
+ DEFAULT_AGENTIC_CONFIG,
+ NEWLINE,
+ SETTINGS_KEYS,
+ TOOL_DENIED_RESULT
+} from '#lib/constants/index.ts';
import {
AUDIO_MIME_TO_EXTENSION,
DATA_URI_BASE64_REGEX,
@@ -32,7 +37,13 @@ import {
MCP_ATTACHMENT_NAME_PREFIX,
MIME_TYPE_PREFIXES
} from '#lib/constants/index.ts';
-import { BuiltInTool, ToolPermissionDecision, ToolSource } from '#lib/enums/index.ts';
+import {
+ BuiltInTool,
+ PermissionEffect,
+ PermissionMode,
+ ToolPermissionDecision,
+ ToolSource
+} from '#lib/enums/index.ts';
import {
AttachmentType,
ContentPartType,
@@ -52,6 +63,7 @@ import { ToolsService } from '#lib/services/tools.service.ts';
import { AgenticGates } from '#lib/stores/agentic/gates.svelte.ts';
import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts';
import { modelsStore } from '#lib/stores/models/index.svelte.ts';
+import { permissionsStore } from '#lib/stores/permissions.svelte.ts';
import { settingsStore } from '#lib/stores/settings/index.svelte.ts';
import { toolsStore } from '#lib/stores/tools.svelte.ts';
import type {
@@ -59,7 +71,6 @@ import type {
AgenticFlowOptions,
AgenticMessage,
AgenticToolPolicy,
- PendingPermissionRequest,
SteeringMessage
} from '#lib/types/agentic.js';
import type { ApiChatMessageData } from '#lib/types/api.js';
@@ -74,6 +85,8 @@ import type {
AgenticFlowParams,
AgenticFlowResult,
AgenticSession,
+ PermissionAnswer,
+ PermissionRequest,
SettingsConfigType,
ToolExecutionResult
} from '#lib/types/index.ts';
@@ -255,7 +268,7 @@ class AgenticStore {
return this.gates.getPendingContinueRequest(conversationId);
}
- getPendingPermissionRequest(conversationId: string): PendingPermissionRequest | null {
+ getPendingPermissionRequest(conversationId: string): PermissionRequest | null {
return this.gates.getPendingPermissionRequest(conversationId);
}
@@ -333,8 +346,12 @@ class AgenticStore {
this.gates.resolveContinue(conversationId, shouldContinue);
}
- resolvePermission(conversationId: string, decision: ToolPermissionDecision): void {
- this.gates.resolvePermission(conversationId, decision);
+ resolvePermission(
+ conversationId: string,
+ decision: ToolPermissionDecision,
+ answer?: PermissionAnswer
+ ): void {
+ this.gates.resolvePermission(conversationId, decision, answer);
}
async runAgenticFlow(params: AgenticFlowParams): Promise {
@@ -415,8 +432,9 @@ class AgenticStore {
}
/**
- * The permission gate as the harness's authorize: the user's answer, or
- * the end of the run when it is stopped while the prompt is open.
+ * The permission gate as the harness's authorize: the rules and the mode
+ * decide first, and the user is asked about what they leave open. A run
+ * stopped while the prompt is open ends.
*/
private async authorizeTool(
conversationId: string,
@@ -424,11 +442,50 @@ class AgenticStore {
signal?: AbortSignal
): Promise {
const toolName = toolCall.function.name;
- const permission = await this.gates.requestPermission(
+ const toolKey = toolsStore.getPermissionKey(toolName) ?? toolName;
+ const isServerTool = toolsStore.getToolSource(toolName) === ToolSource.SERVER;
+ const args = this.parseToolArguments(toolCall.function.arguments);
+ const command =
+ isServerTool &&
+ toolName === BuiltInTool.SERVER_EXEC_SHELL_COMMAND &&
+ typeof args.command === 'string'
+ ? args.command
+ : undefined;
+ const editsFiles =
+ isServerTool &&
+ (toolName === BuiltInTool.SERVER_WRITE_FILE || toolName === BuiltInTool.SERVER_EDIT_FILE);
+ const cwd = conversationsStore.activeConversation?.cwd ?? undefined;
+ const verdict = permissionsStore.check(
+ {
+ command,
+ cwd,
+ editsFiles,
+ mode: permissionMode(settingsStore.config[SETTINGS_KEYS.PERMISSION_MODE]),
+ path: typeof args.path === 'string' ? args.path : undefined,
+ toolKey,
+ toolName,
+ writes: toolsStore.canWrite(toolName)
+ },
+ conversationId
+ );
+
+ if (verdict.effect === PermissionEffect.ALLOW) return { type: 'allow' };
+
+ if (verdict.effect === PermissionEffect.DENY) {
+ return { reason: verdict.reason ?? TOOL_DENIED_RESULT, type: 'deny' };
+ }
+
+ const decision = await this.gates.requestPermission(
conversationId,
- toolName,
- toolsStore.getToolServerLabel(toolName),
- toolCall.id,
+ {
+ command,
+ cwd,
+ patterns: verdict.pending?.map((part) => part.pattern) ?? [],
+ serverLabel: toolsStore.getToolServerLabel(toolName),
+ toolCallId: toolCall.id,
+ toolKey,
+ toolName
+ },
signal
);
@@ -437,7 +494,7 @@ class AgenticStore {
throwIfAborted(signal);
- return permission === ToolPermissionDecision.DENY
+ return decision === ToolPermissionDecision.DENY
? { reason: TOOL_DENIED_RESULT, type: 'deny' }
: { type: 'allow' };
}
@@ -1007,7 +1064,16 @@ class AgenticStore {
for (const provider of toolsStore.providers) await provider.prepare?.();
- return toolsStore.getEnabledToolsForLLM(disabledTools, disabledToolCategories);
+ const cwd = conversationsStore.activeConversation?.cwd ?? undefined;
+
+ // a tool that rules refuse outright here is not offered at all
+ return toolsStore
+ .getEnabledToolsForLLM(disabledTools, disabledToolCategories)
+ .filter((tool) => {
+ const key = toolsStore.getPermissionKey(tool.function.name);
+
+ return !key || !permissionsStore.isToolDenied(key, cwd);
+ });
}
private updateSession(conversationId: string, update: Partial): void {
@@ -1018,3 +1084,9 @@ class AgenticStore {
}
export const agenticStore = new AgenticStore();
+
+function permissionMode(value: unknown): PermissionMode {
+ return Object.values(PermissionMode).includes(value as PermissionMode)
+ ? (value as PermissionMode)
+ : PermissionMode.ASK;
+}
diff --git a/ui/apps/chat/src/lib/stores/permissions.svelte.ts b/ui/apps/chat/src/lib/stores/permissions.svelte.ts
index c257b1ff4676..722950bff4d2 100644
--- a/ui/apps/chat/src/lib/stores/permissions.svelte.ts
+++ b/ui/apps/chat/src/lib/stores/permissions.svelte.ts
@@ -1,75 +1,162 @@
/**
- * permissionsStore - Allowed tool permissions
+ * permissionsStore - Permission rules for tool calls
*
- * Owns the set of tools the user has permanently allowed, persisted to
- * localStorage. The agentic loop's permission gates consult it to run a
- * tool without prompting.
+ * Owns the rules that decide which tool calls run without asking, which ask
+ * and which are refused: rules kept for good (persisted to localStorage,
+ * everywhere or limited to a working folder) and rules for one conversation
+ * (in memory until the app reloads). The agentic loop's permission gate
+ * asks it before every tool call.
*/
-import { ALWAYS_ALLOWED_TOOLS_LOCALSTORAGE_KEY } from '#lib/constants/index.ts';
+import {
+ ALWAYS_ALLOWED_TOOLS_LOCALSTORAGE_KEY,
+ PERMISSION_RULES_LOCALSTORAGE_KEY
+} from '#lib/constants/index.ts';
+import { PermissionEffect } from '#lib/enums/index.ts';
+import type { PermissionCheck, PermissionRule, PermissionVerdict } from '#lib/types/index.ts';
+import { evaluatePermission, isToolDenied } from '#lib/utils/permission-rules.ts';
import { browser } from '$app/env';
-import { SvelteSet } from 'svelte/reactivity';
+import { SvelteMap } from 'svelte/reactivity';
+
+type NewRule = Omit;
class PermissionsStore {
- private _tools = $state(new SvelteSet());
+ private _rules = $state([]);
+ private sessionRules = new SvelteMap();
- get tools(): ReadonlySet {
- return this._tools;
+ /** The rules kept for good, oldest first. */
+ get rules(): readonly PermissionRule[] {
+ return this._rules;
}
- allowTool(key: string): void {
- this._tools.add(key);
+ /** Keep rules for good. A rule equal to one already kept is not added twice. */
+ addRules(rules: NewRule[]): void {
+ const fresh = rules.filter((rule) => !this._rules.some((kept) => sameRule(kept, rule)));
+
+ if (fresh.length === 0) return;
+
+ this._rules = [...this._rules, ...fresh.map(createRule)];
this.persist();
}
+ /** Keep rules for one conversation, until the app reloads. */
+ addSessionRules(conversationId: string, rules: NewRule[]): void {
+ const kept = this.sessionRules.get(conversationId) ?? [];
+
+ this.sessionRules.set(conversationId, [
+ ...kept,
+ ...rules.filter((rule) => !kept.some((k) => sameRule(k, rule))).map(createRule)
+ ]);
+ }
+
+ /** Allow every call of a tool, everywhere. */
+ allowTool(key: string): void {
+ this.addRules([{ effect: PermissionEffect.ALLOW, tool: key }]);
+ }
+
allowTools(keys: string[]): void {
- for (const key of keys) this._tools.add(key);
- this.persist();
+ this.addRules(keys.map((tool) => ({ effect: PermissionEffect.ALLOW, tool })));
+ }
+
+ /** Decide a tool call from the kept rules and the conversation's own. */
+ check(check: PermissionCheck, conversationId: string): PermissionVerdict {
+ return evaluatePermission(check, [
+ ...this._rules,
+ ...(this.sessionRules.get(conversationId) ?? [])
+ ]);
}
+ clearSession(conversationId: string): void {
+ this.sessionRules.delete(conversationId);
+ }
+
+ /** Whether a tool is allowed everywhere, for every call. */
hasTool(key: string): boolean {
- return this._tools.has(key);
+ return this._rules.some((rule) => isToolWideAllow(rule, key));
}
/**
- * Load persisted permissions. Called by initStores() after migrations
- * have run.
+ * Load the kept rules, and turn the tools allowed for good before rules
+ * existed into rules. Called by initStores() after migrations have run.
*/
initialize(): void {
// browser-only init: skip on SSR to avoid localStorage side effects
if (!browser) return;
try {
- const stored = localStorage.getItem(ALWAYS_ALLOWED_TOOLS_LOCALSTORAGE_KEY);
+ const stored = localStorage.getItem(PERMISSION_RULES_LOCALSTORAGE_KEY);
if (stored) {
- for (const name of JSON.parse(stored) as string[]) {
- if (typeof name === 'string') this._tools.add(name);
- }
+ this._rules = (JSON.parse(stored) as PermissionRule[]).filter(isRule);
+ }
+
+ const legacy = localStorage.getItem(ALWAYS_ALLOWED_TOOLS_LOCALSTORAGE_KEY);
+
+ if (legacy) {
+ const keys = (JSON.parse(legacy) as unknown[]).filter(
+ (key): key is string => typeof key === 'string'
+ );
+
+ this.allowTools(keys);
+ this.persist();
+ localStorage.removeItem(ALWAYS_ALLOWED_TOOLS_LOCALSTORAGE_KEY);
}
} catch (err) {
console.error(
- `Failed to load permissions from localStorage ("${ALWAYS_ALLOWED_TOOLS_LOCALSTORAGE_KEY}"):`,
+ `Failed to load permission rules from localStorage ("${PERMISSION_RULES_LOCALSTORAGE_KEY}"):`,
err
);
}
}
+ /** Whether rules refuse a tool outright here, so it is not offered to the model. */
+ isToolDenied(key: string, cwd?: string): boolean {
+ return isToolDenied(key, this._rules, cwd);
+ }
+
+ removeRule(id: string): void {
+ this._rules = this._rules.filter((rule) => rule.id !== id);
+ this.persist();
+ }
+
+ /** Stop allowing every call of a tool everywhere. Narrower rules stay. */
revokeTool(key: string): void {
- this._tools.delete(key);
+ this._rules = this._rules.filter((rule) => !isToolWideAllow(rule, key));
this.persist();
}
private persist(): void {
try {
- localStorage.setItem(ALWAYS_ALLOWED_TOOLS_LOCALSTORAGE_KEY, JSON.stringify([...this._tools]));
+ localStorage.setItem(PERMISSION_RULES_LOCALSTORAGE_KEY, JSON.stringify(this._rules));
} catch (err) {
console.error(
- `Failed to persist to localStorage ("${ALWAYS_ALLOWED_TOOLS_LOCALSTORAGE_KEY}"):`,
+ `Failed to persist to localStorage ("${PERMISSION_RULES_LOCALSTORAGE_KEY}"):`,
err
);
}
}
}
+function createRule(rule: NewRule): PermissionRule {
+ return { ...rule, createdAt: Date.now(), id: crypto.randomUUID() };
+}
+
+function isToolWideAllow(rule: PermissionRule, key: string): boolean {
+ return rule.tool === key && rule.effect === PermissionEffect.ALLOW && !rule.pattern && !rule.cwd;
+}
+
+function isRule(value: unknown): value is PermissionRule {
+ const rule = value as PermissionRule;
+
+ return (
+ typeof rule?.id === 'string' &&
+ typeof rule.tool === 'string' &&
+ Object.values(PermissionEffect).includes(rule.effect)
+ );
+}
+
+function sameRule(a: NewRule, b: NewRule): boolean {
+ return a.tool === b.tool && a.effect === b.effect && a.pattern === b.pattern && a.cwd === b.cwd;
+}
+
export const permissionsStore = new PermissionsStore();
diff --git a/ui/apps/chat/src/lib/stores/tools.svelte.ts b/ui/apps/chat/src/lib/stores/tools.svelte.ts
index 6601b8bd8b07..ddc14494a7d7 100644
--- a/ui/apps/chat/src/lib/stores/tools.svelte.ts
+++ b/ui/apps/chat/src/lib/stores/tools.svelte.ts
@@ -58,6 +58,8 @@ class ToolsStore {
// server tools that resolve their paths against the working directory,
// as declared by the server in its `/tools` listing
private cwdAwareTools = $state(new SvelteSet());
+ /** llama-server tools that can change files or run commands, per `/tools` */
+ private writeTools = $state(new SvelteSet());
get allToolDefinitions(): OpenAIToolDefinition[] {
return this.allTools.map((t) => t.definition);
@@ -242,6 +244,18 @@ class ToolsStore {
return groups;
}
+ /**
+ * Whether a tool can change files or run commands: llama-server says so
+ * per tool, browser tools cannot, and MCP or custom tools are assumed to.
+ */
+ canWrite(toolName: string): boolean {
+ const source = this.getToolSource(toolName);
+
+ if (source === ToolSource.SERVER) return this.writeTools.has(toolName);
+
+ return source !== ToolSource.BROWSER;
+ }
+
/** Enable several tools or tool groups by key, in one write */
enableTools(keys: string[]): void {
for (const key of keys) this._disabledTools.delete(key);
@@ -265,6 +279,9 @@ class ToolsStore {
this.cwdAwareTools = new SvelteSet(
toolInfos.filter((info) => info.uses_cwd).map((info) => info.tool)
);
+ this.writeTools = new SvelteSet(
+ toolInfos.filter((info) => info.permissions?.write).map((info) => info.tool)
+ );
} catch (err) {
this._error = err instanceof Error ? err.message : String(err);
diff --git a/ui/apps/chat/src/lib/types/agentic.d.ts b/ui/apps/chat/src/lib/types/agentic.d.ts
index 709b8f40ecac..3709244ba388 100644
--- a/ui/apps/chat/src/lib/types/agentic.d.ts
+++ b/ui/apps/chat/src/lib/types/agentic.d.ts
@@ -15,6 +15,7 @@ import type {
DatabaseMessageExtraAudioFile,
DatabaseMessageExtraImageFile
} from './database';
+import type { PermissionRequest } from './permissions';
import type { MessageRole, ToolSource } from '#lib/enums/index.ts';
import { AgenticSectionType, ContinueIntentKind, ToolCallType } from '#lib/enums/index.ts';
@@ -67,16 +68,6 @@ export type AgenticChatCompletionRequest = Omit;
+}
+
+/** A permission prompt waiting for the user. */
+export interface PermissionRequest {
+ toolName: string;
+ toolKey: string;
+ serverLabel: string;
+ /** The call the prompt is for, so the trace shows it at that call. */
+ toolCallId: string;
+ command?: string;
+ /** Proposed patterns for the parts of a shell command that need approval. */
+ patterns: string[];
+ cwd?: string;
+}
+
+/** The user's answer to a permission prompt. */
+export interface PermissionAnswer {
+ /** Patterns to remember instead of the proposed ones, for the shell tool. */
+ patterns?: string[];
+}
diff --git a/ui/apps/chat/src/lib/utils/permission-rules.ts b/ui/apps/chat/src/lib/utils/permission-rules.ts
new file mode 100644
index 000000000000..869b2f2f6801
--- /dev/null
+++ b/ui/apps/chat/src/lib/utils/permission-rules.ts
@@ -0,0 +1,219 @@
+/**
+ * Permission rules: which tool calls run without asking, which ask, which
+ * are refused. Deny beats ask beats allow, whatever the order of the rules.
+ * A shell command runs without asking only when every command it chains is
+ * allowed; a deny or ask rule fires when any of them matches. These rules
+ * spare prompts; the boundary is still what llama-server lets its tools do.
+ */
+
+import {
+ matchesShellPattern,
+ proposeShellPattern,
+ shellWords,
+ splitShellCommand,
+ stripWrappers
+} from './shell-command.ts';
+import { PermissionEffect, PermissionMode } from '#lib/enums/index.ts';
+import type { PermissionCheck, PermissionRule, PermissionVerdict } from '#lib/types/index.ts';
+
+/** Commands that only read, run without asking in every mode. */
+const READ_ONLY_COMMANDS = new Set([
+ 'cat',
+ 'cd',
+ 'diff',
+ 'du',
+ 'echo',
+ 'file',
+ 'find',
+ 'grep',
+ 'head',
+ 'ls',
+ 'pwd',
+ 'rg',
+ 'stat',
+ 'tail',
+ 'tree',
+ 'wc',
+ 'which'
+]);
+const READ_ONLY_GIT = new Set(['blame', 'diff', 'log', 'ls-files', 'rev-parse', 'show', 'status']);
+// options that make `find` change files
+const FIND_WRITE_OPTIONS = new Set(['-delete', '-exec', '-execdir', '-fprint', '-ok', '-okdir']);
+// targets `rm -r` may never take
+const PROTECTED_TARGETS = new Set(['/', '/*', '~', '~/', '~/*', '$HOME', '$HOME/', '/.']);
+const FORK_BOMB = /:\s*\(\s*\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:/;
+const DISK_WRITE = /\bof=\/dev\/(sd|hd|nvme|disk|mmcblk)|>\s*\/dev\/(sd|hd|nvme|disk|mmcblk)/;
+const OUTPUT_REDIRECT = /(^|[^<>&\d])\d*>>?(?!&)\s*(?!\/dev\/null\b)\S/;
+
+export const PERMISSION_REASONS = {
+ BLOCKED: 'This command is blocked: it could destroy the system or its data.',
+ READ_ONLY: 'Read-only mode is on: tools that change files or run commands are refused.'
+} as const;
+
+/** Decide a tool call from the rules, the conversation's grants and the mode. */
+export function evaluatePermission(
+ check: PermissionCheck,
+ rules: readonly PermissionRule[]
+): PermissionVerdict {
+ const applicable = rules.filter((rule) => ruleApplies(rule, check));
+ const parts = check.command !== undefined ? splitShellCommand(check.command) : null;
+ const segments = parts?.segments ?? [];
+
+ if (check.command !== undefined && isBlockedCommand(check.command, segments)) {
+ return { effect: PermissionEffect.DENY, reason: PERMISSION_REASONS.BLOCKED };
+ }
+
+ const denied = applicable.find(
+ (rule) => rule.effect === PermissionEffect.DENY && ruleMatchesAny(rule, check, segments)
+ );
+
+ if (denied) return { effect: PermissionEffect.DENY, reason: denialReason(denied) };
+
+ const readOnlyShell = parts !== null && !parts.complex && segments.every(isReadOnlyCommand);
+
+ if (check.mode === PermissionMode.READ_ONLY && check.writes && !readOnlyShell) {
+ return { effect: PermissionEffect.DENY, reason: PERMISSION_REASONS.READ_ONLY };
+ }
+
+ const pending = () =>
+ segments
+ .filter((segment) => parts?.complex || !segmentAllowed(segment, applicable, check))
+ .map((segment) => ({ pattern: proposeShellPattern(segment), segment }));
+
+ if (
+ applicable.some(
+ (rule) => rule.effect === PermissionEffect.ASK && ruleMatchesAny(rule, check, segments)
+ )
+ ) {
+ return { effect: PermissionEffect.ASK, pending: parts ? pending() : undefined };
+ }
+
+ if (applicable.some((rule) => rule.effect === PermissionEffect.ALLOW && !rule.pattern)) {
+ return { effect: PermissionEffect.ALLOW };
+ }
+
+ if (parts && !parts.complex && segments.every((s) => segmentAllowed(s, applicable, check))) {
+ return { effect: PermissionEffect.ALLOW };
+ }
+
+ if (check.mode === PermissionMode.AUTO) return { effect: PermissionEffect.ALLOW };
+
+ if (
+ check.mode === PermissionMode.ACCEPT_EDITS &&
+ check.editsFiles &&
+ check.cwd &&
+ isPathInside(check.path, check.cwd)
+ ) {
+ return { effect: PermissionEffect.ALLOW };
+ }
+
+ return { effect: PermissionEffect.ASK, pending: parts ? pending() : undefined };
+}
+
+/** Whether rules refuse a tool outright here, so it should not be offered to the model at all. */
+export function isToolDenied(
+ toolKey: string,
+ rules: readonly PermissionRule[],
+ cwd?: string
+): boolean {
+ return rules.some(
+ (rule) =>
+ rule.effect === PermissionEffect.DENY &&
+ !rule.pattern &&
+ rule.tool === toolKey &&
+ cwdApplies(rule, cwd)
+ );
+}
+
+/** Whether `path` lies inside the folder `cwd`, or is relative to it. */
+export function isPathInside(path: string | undefined, cwd: string): boolean {
+ if (!path) return false;
+
+ const parts = path.split(/[\\/]+/);
+
+ if (parts.includes('..')) return false;
+
+ if (!path.startsWith('/') && !path.startsWith('~') && !/^[A-Za-z]:/.test(path)) return true;
+
+ return isFolderInside(path, cwd);
+}
+
+function isFolderInside(folder: string, root: string): boolean {
+ const trim = (p: string) => p.replace(/[\\/]+$/, '') || '/';
+ const f = trim(folder);
+ const r = trim(root);
+
+ return f === r || f.startsWith(r === '/' ? '/' : `${r}/`);
+}
+
+function cwdApplies(rule: PermissionRule, cwd: string | undefined): boolean {
+ return !rule.cwd || (!!cwd && isFolderInside(cwd, rule.cwd));
+}
+
+function ruleApplies(rule: PermissionRule, check: PermissionCheck): boolean {
+ return rule.tool === check.toolKey && cwdApplies(rule, check.cwd);
+}
+
+function ruleMatchesAny(rule: PermissionRule, check: PermissionCheck, segments: string[]): boolean {
+ if (!rule.pattern) return true;
+
+ if (check.command === undefined) return false;
+
+ return segments.some((segment) => matchesShellPattern(segment, rule.pattern!));
+}
+
+function segmentAllowed(
+ segment: string,
+ rules: readonly PermissionRule[],
+ check: PermissionCheck
+): boolean {
+ if (isReadOnlyCommand(segment)) return true;
+
+ return rules.some(
+ (rule) =>
+ rule.effect === PermissionEffect.ALLOW &&
+ !!rule.pattern &&
+ check.command !== undefined &&
+ matchesShellPattern(segment, rule.pattern)
+ );
+}
+
+function isReadOnlyCommand(segment: string): boolean {
+ if (OUTPUT_REDIRECT.test(segment)) return false;
+
+ const words = shellWords(stripWrappers(segment));
+ const [program, sub] = words;
+
+ if (!program) return false;
+
+ if (program === 'git') return !!sub && READ_ONLY_GIT.has(sub);
+
+ if (program === 'find') return !words.some((word) => FIND_WRITE_OPTIONS.has(word));
+
+ return READ_ONLY_COMMANDS.has(program);
+}
+
+function isBlockedCommand(command: string, segments: string[]): boolean {
+ if (FORK_BOMB.test(command) || DISK_WRITE.test(command)) return true;
+
+ return segments.some((segment) => {
+ const words = shellWords(stripWrappers(segment));
+ const program = words[0]?.replace(/^.*\//, '');
+
+ if (program === 'mkfs' || program?.startsWith('mkfs.')) return true;
+
+ if (program !== 'rm') return false;
+
+ const recursive = words.some(
+ (word) => word === '--recursive' || /^-[a-zA-Z]*[rR][a-zA-Z]*$/.test(word)
+ );
+
+ return recursive && words.some((word) => PROTECTED_TARGETS.has(word));
+ });
+}
+
+function denialReason(rule: PermissionRule): string {
+ return rule.pattern
+ ? `Denied by the permission rule "${rule.pattern}".`
+ : 'Denied by a permission rule for this tool.';
+}
diff --git a/ui/apps/chat/src/lib/utils/shell-command.ts b/ui/apps/chat/src/lib/utils/shell-command.ts
new file mode 100644
index 000000000000..4c1c38cb55f7
--- /dev/null
+++ b/ui/apps/chat/src/lib/utils/shell-command.ts
@@ -0,0 +1,251 @@
+/**
+ * Shell command parsing for permission rules: splits a command into the
+ * simple commands it runs, so a rule can allow `npm test` without allowing
+ * `npm test && rm -rf build`. It is a matcher for prompts, not a sandbox:
+ * anything it cannot read with confidence is reported as complex and always
+ * asks.
+ */
+
+import type { ShellCommandParts } from '#lib/types/index.ts';
+
+// operators that chain commands; longest first so `&&` wins over `&`
+const CHAIN_OPERATORS = ['&&', '||', '|&', ';', '|', '&', '\n'];
+// wrappers that run the command after them unchanged
+const WRAPPERS = new Set(['command', 'nice', 'nohup', 'time', 'timeout']);
+// commands whose second word picks the action, so a rule keeps it: `git log *`
+const SUBCOMMAND_TOOLS = new Set([
+ 'bun',
+ 'cargo',
+ 'docker',
+ 'gh',
+ 'git',
+ 'go',
+ 'kubectl',
+ 'make',
+ 'npm',
+ 'npx',
+ 'pip',
+ 'pnpm',
+ 'podman',
+ 'python',
+ 'uv',
+ 'yarn'
+]);
+// package managers whose `run` takes the script as a third word: `npm run test *`
+const RUN_SCRIPT_TOOLS = new Set(['bun', 'npm', 'pnpm', 'yarn']);
+const MAX_COMMAND_LENGTH = 10_000;
+
+/**
+ * Split a command line into its simple commands. Quotes and backslashes are
+ * honoured; `$(…)`, backticks, process substitution and unbalanced quotes
+ * mark the result as complex.
+ */
+export function splitShellCommand(command: string): ShellCommandParts {
+ const segments: string[] = [];
+
+ let complex = command.length > MAX_COMMAND_LENGTH;
+ let current = '';
+ let quote: '"' | "'" | null = null;
+ let i = 0;
+
+ const flush = () => {
+ const segment = normalizeSegment(current);
+
+ if (segment) segments.push(segment);
+
+ current = '';
+ };
+
+ while (i < command.length) {
+ const ch = command[i];
+
+ if (quote) {
+ if (ch === '\\' && quote === '"' && i + 1 < command.length) {
+ current += ch + command[i + 1];
+ i += 2;
+
+ continue;
+ }
+
+ if (ch === '$' && quote === '"' && command[i + 1] === '(') complex = true;
+
+ if (ch === '`' && quote === '"') complex = true;
+
+ if (ch === quote) quote = null;
+
+ current += ch;
+ i++;
+
+ continue;
+ }
+
+ if (ch === '\\' && i + 1 < command.length) {
+ // a backslash before a newline continues the line
+ if (command[i + 1] !== '\n') current += ch + command[i + 1];
+
+ i += 2;
+
+ continue;
+ }
+
+ if (ch === "'" || ch === '"') {
+ quote = ch;
+ current += ch;
+ i++;
+
+ continue;
+ }
+
+ if (ch === '`' || (ch === '$' && command[i + 1] === '(')) complex = true;
+
+ if ((ch === '<' || ch === '>') && command[i + 1] === '(') complex = true;
+
+ if ((ch === '(' || ch === ')' || ch === '{' || ch === '}') && current.trim() === '')
+ complex = true;
+
+ const operator = CHAIN_OPERATORS.find((op) => command.startsWith(op, i));
+ // `2>&1` and `>&` are redirections, not the `&` operator
+ const isRedirectAmpersand = operator === '&' && /[<>]$/.test(current);
+
+ if (operator && !isRedirectAmpersand) {
+ flush();
+ i += operator.length;
+
+ continue;
+ }
+
+ current += ch;
+ i++;
+ }
+
+ if (quote) complex = true;
+
+ flush();
+
+ return { complex: complex || segments.length === 0, segments };
+}
+
+/**
+ * The words of a simple command, quotes removed. Good enough to match rules
+ * and propose prefixes; not a full shell word expansion.
+ */
+export function shellWords(segment: string): string[] {
+ const words: string[] = [];
+
+ let word = '';
+ let quote: '"' | "'" | null = null;
+ let hasWord = false;
+
+ for (let i = 0; i < segment.length; i++) {
+ const ch = segment[i];
+
+ if (quote) {
+ if (ch === quote) quote = null;
+ else if (ch === '\\' && quote === '"' && i + 1 < segment.length) word += segment[++i];
+ else word += ch;
+
+ continue;
+ }
+
+ if (ch === "'" || ch === '"') {
+ quote = ch;
+ hasWord = true;
+ } else if (ch === '\\' && i + 1 < segment.length) {
+ word += segment[++i];
+ hasWord = true;
+ } else if (/\s/.test(ch)) {
+ if (hasWord) words.push(word);
+
+ word = '';
+ hasWord = false;
+ } else {
+ word += ch;
+ hasWord = true;
+ }
+ }
+
+ if (hasWord) words.push(word);
+
+ return words;
+}
+
+/**
+ * The command a segment runs once harmless wrappers are taken off:
+ * `timeout 30 npm test` is matched as `npm test`.
+ */
+export function stripWrappers(segment: string): string {
+ let words = shellWords(segment);
+
+ while (words.length > 1 && WRAPPERS.has(words[0])) {
+ const wrapper = words[0];
+
+ words = words.slice(1);
+
+ // options of the wrapper, and the duration of `timeout`
+ while (words.length > 1 && words[0].startsWith('-')) {
+ const option = words[0];
+
+ words = words.slice(1);
+
+ if (wrapper === 'nice' && option === '-n' && words.length > 1) words = words.slice(1);
+ }
+
+ if (wrapper === 'timeout' && words.length > 1 && /^\d+(\.\d+)?[smhd]?$/.test(words[0])) {
+ words = words.slice(1);
+ }
+ }
+
+ return words.join(' ');
+}
+
+/**
+ * The prefix a rule should keep for a command: the program and, for tools
+ * with subcommands, the subcommand (`git log *`, `npm run test *`).
+ */
+export function proposeShellPattern(segment: string): string {
+ const words = shellWords(stripWrappers(segment));
+
+ if (words.length === 0) return '';
+
+ const isPlainWord = (word: string | undefined) =>
+ !!word && /^[\w:@.-]+$/.test(word) && !word.startsWith('-') && !word.includes('/');
+ const kept = [words[0]];
+
+ if (SUBCOMMAND_TOOLS.has(words[0]) && isPlainWord(words[1])) {
+ kept.push(words[1]);
+
+ if (RUN_SCRIPT_TOOLS.has(words[0]) && words[1] === 'run' && isPlainWord(words[2])) {
+ kept.push(words[2]);
+ }
+ }
+
+ return kept.length === words.length ? kept.join(' ') : `${kept.join(' ')} *`;
+}
+
+/**
+ * Whether a simple command matches a rule pattern. `*` matches any text; a
+ * trailing ` *` also matches the bare command, so `git log *` matches
+ * `git log`. The whole command must match.
+ */
+export function matchesShellPattern(segment: string, pattern: string): boolean {
+ const command = stripWrappers(segment);
+ const normalized = normalizeSegment(pattern);
+
+ if (!normalized) return false;
+
+ const optionalTail = normalized.endsWith(' *');
+ const body = optionalTail ? normalized.slice(0, -2) : normalized;
+
+ let source = body
+ .split('*')
+ .map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&'))
+ .join('.*');
+
+ if (optionalTail) source += '(?: .*)?';
+
+ return new RegExp(`^${source}$`, 's').test(command);
+}
+
+function normalizeSegment(segment: string): string {
+ return segment.replace(/\s+/g, ' ').trim();
+}
diff --git a/ui/apps/chat/tests/client/permission-request-command.svelte.test.ts b/ui/apps/chat/tests/client/permission-request-command.svelte.test.ts
index b804a991b7bb..2b00af4a3241 100644
--- a/ui/apps/chat/tests/client/permission-request-command.svelte.test.ts
+++ b/ui/apps/chat/tests/client/permission-request-command.svelte.test.ts
@@ -39,10 +39,15 @@ function shellCall(): DatabaseMessage {
describe('approving a shell command', () => {
it('shows the command in the permission card', async () => {
const { container } = render(ChatMessageActionCardPermissionRequest, {
- command: COMMAND,
onDecision: () => {},
- serverLabel: 'Server Tools',
- toolName: BuiltInTool.SERVER_EXEC_SHELL_COMMAND
+ request: {
+ command: COMMAND,
+ patterns: [],
+ serverLabel: 'Server Tools',
+ toolCallId: 'c1',
+ toolKey: `server:${BuiltInTool.SERVER_EXEC_SHELL_COMMAND}`,
+ toolName: BuiltInTool.SERVER_EXEC_SHELL_COMMAND
+ }
});
await tick();
diff --git a/ui/apps/chat/tests/stories/chat/messages/ChatMessageActionCard.stories.svelte b/ui/apps/chat/tests/stories/chat/messages/ChatMessageActionCard.stories.svelte
index c56efb31ff3c..07f4b4213bdf 100644
--- a/ui/apps/chat/tests/stories/chat/messages/ChatMessageActionCard.stories.svelte
+++ b/ui/apps/chat/tests/stories/chat/messages/ChatMessageActionCard.stories.svelte
@@ -22,16 +22,28 @@
-
+
diff --git a/ui/apps/chat/tests/unit/agentic-flow.test.ts b/ui/apps/chat/tests/unit/agentic-flow.test.ts
index 0a146fae161e..e989c12d4b2d 100644
--- a/ui/apps/chat/tests/unit/agentic-flow.test.ts
+++ b/ui/apps/chat/tests/unit/agentic-flow.test.ts
@@ -7,7 +7,13 @@ vi.mock('#lib/services/database.service.ts', () => ({
DatabaseService: {}
}));
-import { BuiltInTool, MessageRole, ToolPermissionDecision, ToolSource } from '#lib/enums/index.ts';
+import {
+ BuiltInTool,
+ MessageRole,
+ PermissionEffect,
+ ToolPermissionDecision,
+ ToolSource
+} from '#lib/enums/index.ts';
import type { Extension, ToolProvider } from '#lib/extensions/index.ts';
import { extensions } from '#lib/extensions/index.ts';
import { ChatService } from '#lib/services/chat.service.ts';
@@ -149,7 +155,7 @@ beforeEach(() => {
vi.spyOn(toolsStore, 'fetchServerTools').mockResolvedValue();
vi.spyOn(toolsStore, 'getToolServerLabel').mockReturnValue('Browser');
vi.spyOn(toolsStore, 'getPermissionKey').mockReturnValue('tool-key');
- vi.spyOn(permissionsStore, 'hasTool').mockReturnValue(true);
+ vi.spyOn(permissionsStore, 'check').mockReturnValue({ effect: PermissionEffect.ALLOW });
});
afterEach(async () => {
@@ -237,7 +243,7 @@ describe('agentic flow', () => {
it('waits for permission and tells the model when it is denied', async () => {
mockTools(ToolSource.BROWSER, BuiltInTool.BROWSER_GET_DATETIME);
- vi.mocked(permissionsStore.hasTool).mockReturnValue(false);
+ vi.mocked(permissionsStore.check).mockReturnValue({ effect: PermissionEffect.ASK });
const requests = mockTurns(
(options) => options.onToolCallChunk?.(toolCalls(BuiltInTool.BROWSER_GET_DATETIME)),
@@ -247,9 +253,11 @@ describe('agentic flow', () => {
const flow = runFlow(callbacks);
await vi.waitFor(() =>
- expect(agenticStore.getPendingPermissionRequest(CONV_ID)).toEqual({
+ expect(agenticStore.getPendingPermissionRequest(CONV_ID)).toMatchObject({
+ patterns: [],
serverLabel: 'Browser',
toolCallId: 'call_0',
+ toolKey: 'tool-key',
toolName: BuiltInTool.BROWSER_GET_DATETIME
})
);
diff --git a/ui/apps/chat/tests/unit/permission-rules.test.ts b/ui/apps/chat/tests/unit/permission-rules.test.ts
new file mode 100644
index 000000000000..75cdb85b6990
--- /dev/null
+++ b/ui/apps/chat/tests/unit/permission-rules.test.ts
@@ -0,0 +1,229 @@
+import { PermissionEffect, PermissionMode } from '#lib/enums/index.ts';
+import type { PermissionCheck, PermissionRule } from '#lib/types/index.ts';
+import {
+ evaluatePermission,
+ isPathInside,
+ isToolDenied,
+ PERMISSION_REASONS
+} from '#lib/utils/permission-rules.ts';
+import {
+ matchesShellPattern,
+ proposeShellPattern,
+ splitShellCommand,
+ stripWrappers
+} from '#lib/utils/shell-command.ts';
+import { describe, expect, it } from 'vitest';
+
+const SHELL = 'server:exec_shell_command';
+const WRITE = 'server:write_file';
+
+function shell(command: string, extra: Partial = {}): PermissionCheck {
+ return {
+ command,
+ editsFiles: false,
+ mode: PermissionMode.ASK,
+ toolKey: SHELL,
+ toolName: 'exec_shell_command',
+ writes: true,
+ ...extra
+ };
+}
+
+function rule(effect: PermissionEffect, extra: Partial = {}): PermissionRule {
+ return { createdAt: 0, effect, id: Math.random().toString(36), tool: SHELL, ...extra };
+}
+
+describe('splitShellCommand', () => {
+ it('splits chained commands and keeps quoted operators', () => {
+ expect(splitShellCommand('git status && npm test | tee out; echo "a && b"')).toEqual({
+ complex: false,
+ segments: ['git status', 'npm test', 'tee out', 'echo "a && b"']
+ });
+ });
+
+ it('treats 2>&1 as a redirection, not a background operator', () => {
+ expect(splitShellCommand('npm test 2>&1').segments).toEqual(['npm test 2>&1']);
+ });
+
+ it('marks substitution, subshells and open quotes as complex', () => {
+ expect(splitShellCommand('echo $(whoami)').complex).toBe(true);
+ expect(splitShellCommand('echo `id`').complex).toBe(true);
+ expect(splitShellCommand('(cd x && rm y)').complex).toBe(true);
+ expect(splitShellCommand('echo "open').complex).toBe(true);
+ expect(splitShellCommand("echo '$(not substituted)'").complex).toBe(false);
+ });
+});
+
+describe('shell patterns', () => {
+ it('strips harmless wrappers', () => {
+ expect(stripWrappers('timeout 30 nice -n 5 npm test')).toBe('npm test');
+ });
+
+ it('proposes a prefix up to the subcommand', () => {
+ expect(proposeShellPattern('git log --oneline -5')).toBe('git log *');
+ expect(proposeShellPattern('npm run test -- --watch')).toBe('npm run test *');
+ expect(proposeShellPattern('ls -la src')).toBe('ls *');
+ expect(proposeShellPattern('make')).toBe('make');
+ });
+
+ it('matches a trailing " *" with or without arguments, and the whole command only', () => {
+ expect(matchesShellPattern('git log', 'git log *')).toBe(true);
+ expect(matchesShellPattern('git log --oneline', 'git log *')).toBe(true);
+ expect(matchesShellPattern('git logs', 'git log *')).toBe(false);
+ expect(matchesShellPattern('npm test', 'npm test')).toBe(true);
+ expect(matchesShellPattern('npm test --watch', 'npm test')).toBe(false);
+ expect(matchesShellPattern('docker run -it x', 'docker * x')).toBe(true);
+ });
+});
+
+describe('evaluatePermission', () => {
+ it('asks for an unknown command and proposes a pattern', () => {
+ expect(evaluatePermission(shell('npm run build'), [])).toEqual({
+ effect: PermissionEffect.ASK,
+ pending: [{ pattern: 'npm run build', segment: 'npm run build' }]
+ });
+ });
+
+ it('allows read-only commands without a rule', () => {
+ expect(evaluatePermission(shell('ls -la && git status'), []).effect).toBe(
+ PermissionEffect.ALLOW
+ );
+ expect(evaluatePermission(shell('ls > files.txt'), []).effect).toBe(PermissionEffect.ASK);
+ expect(evaluatePermission(shell('find . -delete'), []).effect).toBe(PermissionEffect.ASK);
+ });
+
+ it('allows a chain only when every command is allowed', () => {
+ const rules = [rule(PermissionEffect.ALLOW, { pattern: 'npm test *' })];
+
+ expect(evaluatePermission(shell('npm test && git status'), rules).effect).toBe(
+ PermissionEffect.ALLOW
+ );
+ expect(evaluatePermission(shell('npm test && rm -rf build'), rules)).toEqual({
+ effect: PermissionEffect.ASK,
+ pending: [{ pattern: 'rm *', segment: 'rm -rf build' }]
+ });
+ });
+
+ it('never allows a complex command by pattern', () => {
+ const rules = [rule(PermissionEffect.ALLOW, { pattern: 'echo *' })];
+
+ expect(evaluatePermission(shell('echo $(cat ~/.ssh/id_rsa)'), rules).effect).toBe(
+ PermissionEffect.ASK
+ );
+ });
+
+ it('lets deny beat allow, and fires on any part of a chain', () => {
+ const rules = [
+ rule(PermissionEffect.ALLOW),
+ rule(PermissionEffect.DENY, { pattern: 'git push *' })
+ ];
+
+ expect(evaluatePermission(shell('git add . && git push origin main'), rules)).toEqual({
+ effect: PermissionEffect.DENY,
+ reason: 'Denied by the permission rule "git push *".'
+ });
+ });
+
+ it('limits a rule to its folder and the folders inside it', () => {
+ const rules = [rule(PermissionEffect.ALLOW, { cwd: '/work/app', pattern: 'npm test *' })];
+
+ expect(evaluatePermission(shell('npm test', { cwd: '/work/app/pkg' }), rules).effect).toBe(
+ PermissionEffect.ALLOW
+ );
+ expect(evaluatePermission(shell('npm test', { cwd: '/work/other' }), rules).effect).toBe(
+ PermissionEffect.ASK
+ );
+ expect(evaluatePermission(shell('npm test', { cwd: '/work/application' }), rules).effect).toBe(
+ PermissionEffect.ASK
+ );
+ });
+
+ it('blocks destructive commands in every mode, even with an allow-all rule', () => {
+ const rules = [rule(PermissionEffect.ALLOW)];
+
+ for (const command of [
+ 'rm -rf /',
+ 'sudo true; rm -fr ~',
+ ':(){ :|:& };:',
+ 'mkfs.ext4 /dev/sda1'
+ ]) {
+ expect(evaluatePermission(shell(command, { mode: PermissionMode.AUTO }), rules)).toEqual({
+ effect: PermissionEffect.DENY,
+ reason: PERMISSION_REASONS.BLOCKED
+ });
+ }
+
+ expect(evaluatePermission(shell('rm -rf ./build'), rules).effect).toBe(PermissionEffect.ALLOW);
+ });
+
+ it('refuses writing tools in read-only mode but still runs read-only commands', () => {
+ const readOnly = { mode: PermissionMode.READ_ONLY };
+
+ expect(evaluatePermission(shell('npm install', readOnly), [])).toEqual({
+ effect: PermissionEffect.DENY,
+ reason: PERMISSION_REASONS.READ_ONLY
+ });
+ expect(evaluatePermission(shell('git diff', readOnly), []).effect).toBe(PermissionEffect.ALLOW);
+ });
+
+ it('runs file edits inside the folder in accept-edits mode', () => {
+ const edit = (path: string): PermissionCheck => ({
+ cwd: '/work/app',
+ editsFiles: true,
+ mode: PermissionMode.ACCEPT_EDITS,
+ path,
+ toolKey: WRITE,
+ toolName: 'write_file',
+ writes: true
+ });
+
+ expect(evaluatePermission(edit('src/a.ts'), []).effect).toBe(PermissionEffect.ALLOW);
+ expect(evaluatePermission(edit('/work/app/b.ts'), []).effect).toBe(PermissionEffect.ALLOW);
+ expect(evaluatePermission(edit('../secrets'), []).effect).toBe(PermissionEffect.ASK);
+ expect(evaluatePermission(edit('/etc/hosts'), []).effect).toBe(PermissionEffect.ASK);
+ });
+
+ it('allows everything but denials and blocked commands in auto mode', () => {
+ const auto = { mode: PermissionMode.AUTO };
+ const rules = [rule(PermissionEffect.ASK, { pattern: 'git push *' })];
+
+ expect(evaluatePermission(shell('npm install', auto), rules).effect).toBe(
+ PermissionEffect.ALLOW
+ );
+ expect(evaluatePermission(shell('git push', auto), rules).effect).toBe(PermissionEffect.ASK);
+ });
+
+ it('applies tool rules without a pattern to any tool', () => {
+ const check: PermissionCheck = {
+ editsFiles: false,
+ mode: PermissionMode.ASK,
+ toolKey: 'mcp:github:create_issue',
+ toolName: 'create_issue',
+ writes: true
+ };
+
+ expect(evaluatePermission(check, []).effect).toBe(PermissionEffect.ASK);
+ expect(
+ evaluatePermission(check, [rule(PermissionEffect.ALLOW, { tool: 'mcp:github:create_issue' })])
+ .effect
+ ).toBe(PermissionEffect.ALLOW);
+ });
+});
+
+describe('helpers', () => {
+ it('tells which tools rules refuse outright', () => {
+ const rules = [
+ rule(PermissionEffect.DENY, { tool: WRITE }),
+ rule(PermissionEffect.DENY, { pattern: 'rm *' })
+ ];
+
+ expect(isToolDenied(WRITE, rules)).toBe(true);
+ expect(isToolDenied(SHELL, rules)).toBe(false);
+ });
+
+ it('keeps paths with .. out of a folder', () => {
+ expect(isPathInside('a/../../b', '/w')).toBe(false);
+ expect(isPathInside('/w/x', '/w')).toBe(true);
+ expect(isPathInside(undefined, '/w')).toBe(false);
+ });
+});
diff --git a/ui/apps/chat/tests/unit/permissions-store.test.ts b/ui/apps/chat/tests/unit/permissions-store.test.ts
new file mode 100644
index 000000000000..682404adf990
--- /dev/null
+++ b/ui/apps/chat/tests/unit/permissions-store.test.ts
@@ -0,0 +1,185 @@
+import {
+ ALWAYS_ALLOWED_TOOLS_LOCALSTORAGE_KEY,
+ PERMISSION_RULES_LOCALSTORAGE_KEY
+} from '#lib/constants/index.ts';
+import { PermissionEffect, PermissionMode, ToolPermissionDecision } from '#lib/enums/index.ts';
+import { AgenticGates } from '#lib/stores/agentic/gates.svelte.ts';
+import { permissionsStore } from '#lib/stores/permissions.svelte.ts';
+import type { PermissionCheck, PermissionRequest } from '#lib/types/index.ts';
+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+// node env unit project has no DOM, install a minimal localStorage backed by a Map
+beforeAll(() => {
+ const store = new Map();
+ const polyfill: Storage = {
+ clear: () => store.clear(),
+ getItem: (k) => (store.has(k) ? store.get(k)! : null),
+ key: (i) => Array.from(store.keys())[i] ?? null,
+ get length() {
+ return store.size;
+ },
+ removeItem: (k) => {
+ store.delete(k);
+ },
+ setItem: (k, v) => {
+ store.set(k, String(v));
+ }
+ };
+
+ (globalThis as unknown as { localStorage: Storage }).localStorage = polyfill;
+});
+
+const SHELL = 'server:exec_shell_command';
+const CONV = 'conv-1';
+
+function shell(command: string, cwd?: string): PermissionCheck {
+ return {
+ command,
+ cwd,
+ editsFiles: false,
+ mode: PermissionMode.ASK,
+ toolKey: SHELL,
+ toolName: 'exec_shell_command',
+ writes: true
+ };
+}
+
+function request(extra: Partial = {}): PermissionRequest {
+ return {
+ command: 'npm run test -- --run',
+ cwd: '/work/app',
+ patterns: ['npm run test *'],
+ serverLabel: '',
+ toolCallId: 'call-1',
+ toolKey: SHELL,
+ toolName: 'exec_shell_command',
+ ...extra
+ };
+}
+
+// the store is a singleton: empty it between tests
+function reset() {
+ for (const rule of [...permissionsStore.rules]) permissionsStore.removeRule(rule.id);
+
+ permissionsStore.clearSession(CONV);
+ localStorage.clear();
+}
+
+beforeEach(reset);
+
+describe('permissionsStore', () => {
+ it('turns tools allowed before rules existed into rules, once', async () => {
+ // initialize() reads localStorage only in the browser: load a copy of the store that thinks it is in one
+ vi.resetModules();
+ vi.doMock('$app/env', () => ({ browser: true }));
+
+ const { permissionsStore: store } = await import('#lib/stores/permissions.svelte.ts');
+
+ localStorage.setItem(
+ ALWAYS_ALLOWED_TOOLS_LOCALSTORAGE_KEY,
+ JSON.stringify(['server:read_file'])
+ );
+ store.initialize();
+
+ expect(store.hasTool('server:read_file')).toBe(true);
+ expect(localStorage.getItem(ALWAYS_ALLOWED_TOOLS_LOCALSTORAGE_KEY)).toBeNull();
+ expect(JSON.parse(localStorage.getItem(PERMISSION_RULES_LOCALSTORAGE_KEY)!)).toHaveLength(1);
+
+ vi.doUnmock('$app/env');
+ });
+
+ it('does not keep the same rule twice, and revokes only tool-wide allows', () => {
+ permissionsStore.allowTool(SHELL);
+ permissionsStore.allowTool(SHELL);
+ permissionsStore.addRules([
+ { effect: PermissionEffect.ALLOW, pattern: 'npm test *', tool: SHELL }
+ ]);
+
+ expect(permissionsStore.rules).toHaveLength(2);
+
+ permissionsStore.revokeTool(SHELL);
+
+ expect(permissionsStore.rules.map((rule) => rule.pattern)).toEqual(['npm test *']);
+ });
+
+ it('keeps rules for one conversation apart from the others', () => {
+ permissionsStore.addSessionRules(CONV, [
+ { effect: PermissionEffect.ALLOW, pattern: 'npm test *', tool: SHELL }
+ ]);
+
+ expect(permissionsStore.check(shell('npm test'), CONV).effect).toBe(PermissionEffect.ALLOW);
+ expect(permissionsStore.check(shell('npm test'), 'other').effect).toBe(PermissionEffect.ASK);
+ expect(permissionsStore.rules).toHaveLength(0);
+ });
+});
+
+describe('AgenticGates.requestPermission', () => {
+ it('remembers the edited patterns in the folder when allowed there for good', async () => {
+ const gates = new AgenticGates();
+ const answer = gates.requestPermission(CONV, request());
+
+ expect(gates.getPendingPermissionRequest(CONV)).toMatchObject({ toolKey: SHELL });
+
+ gates.resolvePermission(CONV, ToolPermissionDecision.ALWAYS_HERE, {
+ patterns: ['npm run test *', ' ']
+ });
+
+ expect(await answer).toBe(ToolPermissionDecision.ALWAYS_HERE);
+ expect(permissionsStore.rules).toMatchObject([
+ { cwd: '/work/app', effect: PermissionEffect.ALLOW, pattern: 'npm run test *', tool: SHELL }
+ ]);
+ expect(permissionsStore.check(shell('npm run test', '/work/app/pkg'), CONV).effect).toBe(
+ PermissionEffect.ALLOW
+ );
+ expect(permissionsStore.check(shell('npm run test', '/elsewhere'), CONV).effect).toBe(
+ PermissionEffect.ASK
+ );
+ });
+
+ it('remembers a tool for this conversation only', async () => {
+ const gates = new AgenticGates();
+ const answer = gates.requestPermission(
+ CONV,
+ request({ command: undefined, patterns: [], toolKey: 'mcp:github:create_issue' })
+ );
+
+ gates.resolvePermission(CONV, ToolPermissionDecision.SESSION);
+ await answer;
+
+ const check: PermissionCheck = {
+ editsFiles: false,
+ mode: PermissionMode.ASK,
+ toolKey: 'mcp:github:create_issue',
+ toolName: 'create_issue',
+ writes: true
+ };
+
+ expect(permissionsStore.check(check, CONV).effect).toBe(PermissionEffect.ALLOW);
+ expect(permissionsStore.rules).toHaveLength(0);
+ });
+
+ it('remembers nothing for a one-off answer or a denial', async () => {
+ const gates = new AgenticGates();
+
+ for (const decision of [ToolPermissionDecision.ONCE, ToolPermissionDecision.DENY]) {
+ const answer = gates.requestPermission(CONV, request());
+
+ gates.resolvePermission(CONV, decision);
+ await answer;
+ }
+
+ expect(permissionsStore.rules).toHaveLength(0);
+ expect(permissionsStore.check(shell('npm run test'), CONV).effect).toBe(PermissionEffect.ASK);
+ });
+
+ it('denies when the run is stopped while the prompt is open', async () => {
+ const gates = new AgenticGates();
+ const controller = new AbortController();
+ const answer = gates.requestPermission(CONV, request(), controller.signal);
+
+ controller.abort();
+
+ expect(await answer).toBe(ToolPermissionDecision.DENY);
+ expect(gates.getPendingPermissionRequest(CONV)).toBeNull();
+ });
+});