Skip to content

Commit 1e733f1

Browse files
committed
fix: refresh agent permissions and distinguish historical denials
1 parent a6b6c5f commit 1e733f1

14 files changed

Lines changed: 228 additions & 31 deletions

File tree

‎docs/AI_PERMISSIONS.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,5 @@ A policy denial records the tool result and pauses the agent through the existin
4141
Each denied call retains a visible notice with its connection, required action, and decision source when recorded. For connection access denials, Review permissions always edits the blocked connection, including when its denied decision is inherited from system defaults. It never changes global defaults from chat. Conversation restrictions and saved confirmation rules retain their own recovery controls. Save and Back to chat share one dialog footer row. Saving never executes the blocked action. Retry request starts a new agent turn with the original tool arguments, fresh permissions, and normal confirmation; it does not replay earlier successful work automatically or bypass the application gate.
4242

4343
History loads persisted tool-call statuses and correlated results rather than assuming every call succeeded. Denials and failures remain visible after reopening. Interrupted or missing outcomes are shown as unavailable; legacy records whose permission source was never recorded retain a generic permission notice.
44+
45+
Each agent turn receives a backend-resolved snapshot of current effective actions for its attached connections, including management access. This planning context does not replace live dispatch authorization. Historical denials do not establish current access after a permission change, and an explicit retry must not be reported as failed without a new tool result. System AI defaults are application policy, not operating-system or database privileges. Earlier blocked calls remain labeled as previous attempts, with raw diagnostics collapsed behind their structured notice.

‎src-tauri/src/ai_permissions/denial.rs‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,16 @@ pub(crate) struct AccessDenial {
1818

1919
impl AccessDenial {
2020
pub fn permission(action: Permission, id: &str, source: &str) -> Self {
21+
let source_label = match source {
22+
"system" => "SQLKit system AI defaults",
23+
"connection" => "this connection's AI permissions",
24+
"conversation" => "this conversation's source restrictions",
25+
_ => "SQLKit AI permissions",
26+
};
2127
Self {
2228
kind: "permission".into(),
2329
source: source.into(),
24-
message: format!(
25-
"{action:?} access denied for connection '{id}' by {source} permissions"
26-
),
30+
message: format!("{action:?} access denied for connection '{id}' by {source_label}"),
2731
connection_id: Some(id.into()),
2832
source_id: None,
2933
action: Some(action),

‎src-tauri/src/ai_permissions/invocation.rs‎

Lines changed: 86 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,45 @@ pub async fn get_ai_context(
258258
schemas.push(format!("-- Source: {alias}\n{schema}"));
259259
}
260260
}
261-
Ok(json!({"readableConnectionIds": readable, "schema": schemas.join("\n")}))
261+
let policy = load_permission_policy(&app)?;
262+
let session = access.current("")?;
263+
let effective_permissions =
264+
connection_permission_context(&policy, &access.connections, &session.restrictions);
265+
Ok(
266+
json!({"readableConnectionIds": readable, "schema": schemas.join("\n"), "effectivePermissions": effective_permissions}),
267+
)
268+
}
269+
270+
fn connection_permission_context(
271+
policy: &AiPolicy,
272+
connections: &std::collections::HashMap<String, Value>,
273+
restrictions: &std::collections::HashMap<String, super::PermissionRules>,
274+
) -> std::collections::HashMap<String, super::PermissionRules> {
275+
connections
276+
.iter()
277+
.filter_map(|(alias, config)| {
278+
let id = config["connectionId"].as_str()?;
279+
let restriction = restrictions.get(id)?;
280+
let effective = policy.effective_permissions(id);
281+
let allowed = |action| {
282+
effective.get(action) == Some(true)
283+
&& restriction.get(action) != Some(false)
284+
&& (action != super::chain::Permission::Manage
285+
|| restriction.manage == Some(true))
286+
};
287+
use super::chain::Permission::{Create, Delete, Manage, Read, Update};
288+
Some((
289+
alias.clone(),
290+
super::PermissionRules::explicit(
291+
allowed(Read),
292+
allowed(Create),
293+
allowed(Update),
294+
allowed(Delete),
295+
allowed(Manage),
296+
),
297+
))
298+
})
299+
.collect()
262300
}
263301

264302
#[cfg(test)]
@@ -294,6 +332,53 @@ mod tests {
294332
..Default::default()
295333
}
296334
}
335+
336+
#[test]
337+
fn persisted_connection_grant_refreshes_retry_context_and_still_requires_ddl_approval() {
338+
let dir = tempfile::tempdir().unwrap();
339+
let mut config = crate::mcp_bridge::McpConfig::default();
340+
config.policy.permission_defaults =
341+
Some(PermissionRules::explicit(true, true, true, true, false));
342+
config.save(dir.path()).unwrap();
343+
let target = json!({"connectionId":"42"});
344+
let connections = HashMap::from([
345+
("example".into(), target.clone()),
346+
("outside".into(), json!({"connectionId":"99"})),
347+
]);
348+
let mut ddl = cap();
349+
ddl.name = "sqlkit__execute_ddl";
350+
ddl.required_permission = "manage";
351+
ddl.risk_level = RiskLevel::Destructive;
352+
let args = json!({"sql":"CREATE TABLE example(id INT)"});
353+
assert!(evaluate(config.policy.clone(), &ddl, &args, &target, Some(session())).is_err());
354+
config.policy.connection_permissions.insert(
355+
"42".into(),
356+
PermissionRules::explicit(true, true, true, true, true),
357+
);
358+
config.save(dir.path()).unwrap();
359+
let current = super::super::read_permission_config(dir.path())
360+
.unwrap()
361+
.policy;
362+
assert_eq!(
363+
current.permission_defaults.as_ref().unwrap().manage,
364+
Some(false)
365+
);
366+
let decision = evaluate(current.clone(), &ddl, &args, &target, Some(session())).unwrap();
367+
assert!(decision.confirmation);
368+
let context =
369+
connection_permission_context(&current, &connections, &session().restrictions);
370+
assert_eq!(context["example"].manage, Some(true));
371+
assert!(!context.contains_key("outside"));
372+
let mut restricted = session();
373+
restricted.restrictions.get_mut("42").unwrap().manage = Some(false);
374+
assert_eq!(
375+
connection_permission_context(&current, &connections, &restricted.restrictions)
376+
["example"]
377+
.manage,
378+
Some(false)
379+
);
380+
assert!(evaluate(current, &ddl, &args, &target, Some(restricted)).is_err());
381+
}
297382
fn session() -> SessionAccess {
298383
SessionAccess {
299384
restrictions: HashMap::from([(

‎src/__tests__/agentOutcomes.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,12 +45,20 @@ describe('tool outcome notices', () => {
4545
expect(notice.text()).toContain('connection’s AI permissions')
4646
expect(wrapper.get('.tool-verb-label').text()).toBe('Blocked')
4747
expect(notice.element.closest('details')).toBeNull()
48+
expect(wrapper.get('.activity-item-details').attributes('open')).toBeUndefined()
49+
expect(wrapper.find('.result-preview-denied').exists()).toBe(false)
4850
await notice.findAll('button')[0].trigger('click')
4951
expect(wrapper.emitted('reviewPermissions')?.[0]).toEqual([call])
5052
await notice.findAll('button')[1].trigger('click')
5153
expect(wrapper.emitted('retryToolCall')?.[0]).toEqual([call])
5254
})
5355

56+
it('labels an earlier denial as history after the user sends a new request', async () => {
57+
const wrapper = render()
58+
await wrapper.setProps({ historical: true })
59+
expect(wrapper.get('[role="alert"]').text()).toContain('Previous attempt blocked')
60+
})
61+
5462
it('distinguishes user rejection without offering to change permissions', () => {
5563
const wrapper = render({ ...call, denial: { ...call.denial!, kind: 'user' } })
5664
expect(wrapper.get('[role="alert"]').text()).toContain('Rejected by you — action not executed')
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import type { ChatSession } from '@/types/chat'
2+
import { computed, reactive, ref } from 'vue'
3+
import { useChatAgent } from '@/composables/useChatAgent'
4+
import { agentApi } from '@/datasources/agentApi'
5+
6+
jest.mock('@/common', () => jest.requireActual('@/common/agentPrompt'))
7+
jest.mock('@/datasources/agentApi', () => ({ agentApi: { getAvailableTools: jest.fn(), getAiContext: jest.fn(), runAgentLoop: jest.fn() } }))
8+
jest.mock('@/store/connectionStore', () => ({ useConnectionStore: () => ({ getConnectionById: () => undefined }) }))
9+
jest.mock('@/store/entitlementStore', () => ({ useEntitlementStore: () => ({ isLocalUltimate: false }) }))
10+
jest.mock('@/store/appStore', () => ({ useAppStore: () => ({
11+
llmSettings: { chat: {} },
12+
getFeatureModelConfig: async () => ({ provider: { name: 'synthetic', apiKey: 'synthetic', apiCompatibility: 'openai-compatible' }, model: { label: 'synthetic' } }),
13+
}) }))
14+
jest.mock('@/store/dataStudioStore', () => ({ useDataStudioStore: () => ({ clearSessionError: jest.fn(), insertPreparingPlaceholder: jest.fn(), setSessionProgress: jest.fn(), getSessionError: () => undefined }) }))
15+
16+
describe('agent retry uses current backend permissions', () => {
17+
it.each([true, false])('uses current Manage=%s instead of the previous frontend snapshot', async (manage) => {
18+
const session = reactive<ChatSession>({ id: 'chat', messages: [], status: 'blocked', maxIterations: 3 })
19+
jest.mocked(agentApi.getAvailableTools).mockResolvedValue({ tools: [], metadata: {} })
20+
jest.mocked(agentApi.getAiContext).mockResolvedValue({
21+
readableConnectionIds: ['42'],
22+
schema: '',
23+
effectivePermissions: { example: { read: true, create: true, update: true, delete: true, manage } },
24+
})
25+
jest.mocked(agentApi.runAgentLoop).mockClear()
26+
jest.mocked(agentApi.runAgentLoop).mockResolvedValue(undefined)
27+
const agent = useChatAgent({
28+
feature: 'dataStudio',
29+
autoMode: ref(true),
30+
sessionStore: {
31+
sessions: ref([session]),
32+
activeSession: computed(() => session),
33+
activeSessionId: ref('chat'),
34+
addMessage: jest.fn(),
35+
updateStreamingContent: jest.fn(),
36+
updateStreamingThinking: jest.fn(),
37+
setMessageStatus: jest.fn(),
38+
setMessageToolCalls: jest.fn(),
39+
removeOrphanedStreamingMessages: jest.fn(),
40+
updateToolCallStatus: jest.fn(),
41+
setSessionStatus: (_id, status) => { session.status = status },
42+
setSessionSchema: jest.fn(),
43+
clearSession: jest.fn(),
44+
getOrCreateSession: async () => 'chat',
45+
reloadSessionMessages: jest.fn(),
46+
},
47+
})
48+
await agent.sendMessage({ content: 'retry', context: { connections: { example: {
49+
connectionId: '42',
50+
dbType: 'POSTGRESQL',
51+
permissions: { read: true, create: false, update: false, delete: false, manage: !manage },
52+
} } } })
53+
expect(agentApi.runAgentLoop).toHaveBeenCalledTimes(1)
54+
const settings = jest.mocked(agentApi.runAgentLoop).mock.calls[0][2] as Record<string, unknown>
55+
expect(settings.systemPrompt).toContain(manage ? 'allowed actions: read, create, update, delete, manage; denied actions: none' : 'allowed actions: read, create, update, delete; denied actions: manage')
56+
expect(settings.systemPrompt).toContain('Never claim a new attempt failed without a new tool result from this turn')
57+
})
58+
})

‎src/__tests__/aiPermissions.test.ts‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,16 @@ import { invoke } from '@tauri-apps/api/core'
33
import { openUrl } from '@tauri-apps/plugin-opener'
44
import { flushPromises, mount } from '@vue/test-utils'
55
import { defineComponent, reactive } from 'vue'
6-
import { AI_ACTIONS, aiPreset, resolveAiPermissions } from '@/common/aiPermissions'
6+
import { AI_ACTIONS, aiPreset, getAiPolicy, resolveAiPermissions } from '@/common/aiPermissions'
77
import ConnectionPermissionEditor from '@/components/ai-permissions/ConnectionPermissionEditor.vue'
88
import DefaultPermissionEditor from '@/components/ai-permissions/DefaultPermissionEditor.vue'
9+
import ToolPermissionReview from '@/components/ai-permissions/ToolPermissionReview.vue'
910
import SourcePermissionModal from '@/views/data-studio/components/modify-source-modal.vue'
1011

1112
jest.mock('@tauri-apps/api/core', () => ({ invoke: jest.fn() }))
1213
jest.mock('@/common', () => ({ ...jest.requireActual('@/common/aiPermissions'), UPGRADE_URL: 'https://example.test/upgrade' }))
1314
const mockEntitlement = reactive({ isLocalUltimate: true })
14-
jest.mock('@/store', () => ({ useEntitlementStore: () => mockEntitlement }))
15+
jest.mock('@/store', () => ({ useEntitlementStore: () => mockEntitlement, useConnectionStore: () => ({ getConnectionById: (id: string) => ({ id, name: 'Development database' }) }) }))
1516
jest.mock('@tauri-apps/plugin-opener', () => ({ openUrl: jest.fn() }))
1617
jest.mock('@/components/upgrade', () => ({ ProBadge: { template: '<span>Ultimate</span>' } }))
1718
jest.mock('vue-i18n', () => ({ useI18n: () => ({ t: (key: string) => key }) }))
@@ -68,6 +69,26 @@ const openEditor = async (id?: string) => {
6869
}
6970

7071
describe('aI permission chain', () => {
72+
it('persists Full access from the real recovery editor without changing the denying defaults', async () => {
73+
let saved = { permission_defaults: aiPreset('data'), connection_permissions: {} as Record<string, Record<string, boolean>> }
74+
mockEntitlement.isLocalUltimate = true
75+
mockInvoke.mockImplementation(async (command, args) => {
76+
if (command === 'save_ai_permissions') {
77+
const update = args as { connectionId: string, permissions: Record<string, boolean> }
78+
saved = { ...saved, connection_permissions: { ...saved.connection_permissions, [update.connectionId]: update.permissions } }
79+
}
80+
return saved
81+
})
82+
const wrapper = mount(ToolPermissionReview, { props: { open: true, denial: { kind: 'permission', source: 'system', connectionId: 'dev', action: 'manage', message: 'Manage denied' }, toolName: 'ddl', sessionId: 'session' } })
83+
await flushPromises()
84+
await wrapper.get('input[value="full"]').setValue()
85+
await wrapper.findAll('button').find(button => button.text() === 'dataStudio.modifySource.saveChanges')!.trigger('click')
86+
await flushPromises()
87+
const reloaded = await getAiPolicy()
88+
expect(reloaded.permission_defaults.manage).toBe(false)
89+
expect(reloaded.connection_permissions.dev).toEqual(aiPreset('full'))
90+
expect(resolveAiPermissions(reloaded.permission_defaults, reloaded.connection_permissions.dev).manage).toBe(true)
91+
})
7192
beforeEach(() => {
7293
mockEntitlement.isLocalUltimate = true
7394
mockStore.updateSessionSourcePermissions.mockReset()

‎src/common/agentPrompt.test.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { assembleSystemPrompt, buildAgentModeInstructions } from './agentPrompt'
1+
import { assembleSystemPrompt, buildAgentModeInstructions, buildAgentPermissionInstructions } from './agentPrompt'
22

33
describe('assembleSystemPrompt', () => {
44
it('joins layers in developer, global, connections, sidebar order', () => {
@@ -35,6 +35,15 @@ describe('assembleSystemPrompt', () => {
3535
})
3636

3737
describe('agent mode contract', () => {
38+
it('refreshes manage access after a connection grant instead of replaying a historical default denial', () => {
39+
const denied = buildAgentPermissionInstructions([{ connectionId: 'example', permissions: { read: true, manage: false } }]).join('\n')
40+
const granted = buildAgentPermissionInstructions([{ connectionId: 'example', permissions: { read: true, manage: true } }]).join('\n')
41+
expect(denied).toContain('denied actions: manage')
42+
expect(granted).toContain('allowed actions: read, manage; denied actions: none')
43+
expect(granted).toContain('Never claim a new attempt failed without a new tool result from this turn')
44+
expect(granted).toContain('submit a fresh tool call')
45+
expect(granted).toContain('not operating-system or database privileges')
46+
})
3847
it.each([false, true])('keeps reads automatic and all deletes and DDL subject to application approval (auto=%s)', (auto) => {
3948
const prompt = buildAgentModeInstructions(auto).join('\n')
4049
expect(prompt).toContain('read-only queries and metadata reads execute automatically in both modes')

‎src/common/agentPrompt.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import type { AiPermissions } from './aiPermissions'
2+
13
export type ConnectionPrompt = {
24
alias: string
35
prompt: string
@@ -21,6 +23,21 @@ export const buildAgentModeInstructions = (auto: boolean): string[] => [
2123
'Approval does not grant a denied permission. If an action is blocked or rejected, do not retry it or use another tool to bypass the decision. Wait for an explicit user request to retry.',
2224
]
2325

26+
export const buildAgentPermissionInstructions = (sources: Array<{ connectionId: string, permissions?: AiPermissions }>): string[] => [
27+
'## Current SQLKit AI permissions',
28+
'This snapshot is refreshed for this request and resolves connection decisions, system AI defaults, and conversation restrictions. System AI defaults are application settings, not operating-system or database privileges. An explicit connection decision takes priority over a system default.',
29+
...sources.map(({ connectionId, permissions }) => {
30+
if (!permissions)
31+
return `- ${connectionId}: permissions unavailable; the application must check access.`
32+
const actions = Object.entries(permissions)
33+
const allowed = actions.filter(([, value]) => value).map(([action]) => action).join(', ') || 'none'
34+
const denied = actions.filter(([, value]) => !value).map(([action]) => action).join(', ') || 'none'
35+
return `- ${connectionId}: allowed actions: ${allowed}; denied actions: ${denied}.`
36+
}),
37+
'Permission failures in earlier tool results are historical. They do not prove current denial after settings change. Never claim a new attempt failed without a new tool result from this turn.',
38+
'When the user explicitly asks to retry and current permissions allow the action, submit a fresh tool call and let the application recheck access and request any required approval. Do not repeat an earlier denial as the result of a new attempt.',
39+
]
40+
2441
const isNonEmpty = (value: string | undefined | null): value is string => Boolean(value?.trim())
2542

2643
export const assembleSystemPrompt = (layers: SystemPromptLayers): string => {

‎src/components/agent-message-bubble.vue‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const props = defineProps<{
1212
message: any
1313
iterationIndex?: number
1414
canRetry?: boolean
15+
historical?: boolean
1516
}>()
1617
const emit = defineEmits<{
1718
reviewPermissions: [toolCall: AgentToolCall]
@@ -34,7 +35,7 @@ const connectionLabel = (call: AgentToolCall) => {
3435
}
3536
const outcomeTitle = (call: AgentToolCall) => {
3637
const key = call.status === 'denied'
37-
? call.denial?.kind === 'user' ? 'rejectedNotice' : call.denial?.kind === 'unavailable' ? 'unavailableNotice' : 'blockedNotice'
38+
? call.denial?.kind === 'user' ? 'rejectedNotice' : call.denial?.kind === 'unavailable' ? 'unavailableNotice' : props.historical ? 'historicalBlockedNotice' : 'blockedNotice'
3839
: call.status === 'interrupted' ? 'interruptedNotice' : 'toolError'
3940
return t(`dataStudio.agent.message.${key}`)
4041
}
@@ -404,7 +405,7 @@ function toolVerb(toolName: string, tc: AgentToolCall): string {
404405
<template v-for="tc in message.toolCalls" :key="tc.id">
405406
<details
406407
class="activity-item-details"
407-
:open="tc.status === 'error' || tc.status === 'denied' || tc.status === 'executing'"
408+
:open="tc.status === 'error' || tc.status === 'executing'"
408409
>
409410
<summary class="activity-item">
410411
<span class="activity-icon" :class="toolIcon(tc.toolName)" />
@@ -439,7 +440,7 @@ function toolVerb(toolName: string, tc: AgentToolCall): string {
439440
<span
440441
v-if="
441442
toolResultText(tc)
442-
&& (tc.status === 'done' || tc.status === 'error' || tc.status === 'denied' || tc.status === 'executing')
443+
&& (tc.status === 'done' || tc.status === 'error' || tc.status === 'executing')
443444
"
444445
class="result-preview"
445446
:class="`result-preview-${resultStatus(tc)}`"

0 commit comments

Comments
 (0)