Skip to content

Commit 3ffa404

Browse files
committed
fix: restore consistent AI permission controls and gate per-connection editing
- access levels use the shared radio pattern with a short scope description inside each option; Custom edits the same values as the presets instead of forming a separate layer - connection-level custom actions expose Use default (Allow/Deny); system defaults use switches for binary actions - MCP service settings and shared AI defaults live in separate cards - per-connection permission editing requires the local Ultimate entitlement: inline upgrade prompt, draft stripped on save, and save_ai_permissions enforced in Rust with a cleanup carve-out that only clears decisions of connections that no longer exist
1 parent eb7042a commit 3ffa404

12 files changed

Lines changed: 518 additions & 159 deletions

File tree

‎DESIGN.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -331,4 +331,4 @@ Check each affected surface. Documentation-only changes need source, link, and i
331331

332332
### AI permission controls
333333

334-
Connection dialogs expose a collapsed AI permissions section shared by Data Studio and external MCP. Default to system inheritance, show effective allowed actions, and reveal per-action Inherit / Allow / Deny under Customize. The system settings page edits action defaults, without a separate connection allowlist or MCP exposure switch. Preserve shared Select, Label, Button, neutral surfaces, localized English/Chinese copy, keyboard focus, and loading/error/retry states. See [AI permissions](docs/AI_PERMISSIONS.md) for enforcement and migration behavior.
334+
Per-connection permission editing uses the existing local Ultimate gate and inline upgrade prompt; Community connection edits preserve saved permission decisions. Connection dialogs expose a collapsed AI permissions section shared by Data Studio and external MCP. Default to system inheritance, show effective allowed actions, and offer visible radio choices for access levels, including Custom. Each option contains a short description of its scope. Custom reveals per-action Use default / Allow / Deny controls; each inherited option names its current decision. Presets and custom editing change the same permission values and do not form separate policy layers. The system settings page edits action defaults, without a separate connection allowlist or MCP exposure switch. Separate shared AI defaults from MCP service settings using the existing settings cards. Use switches for binary system defaults, and preserve shared RadioGroup, Select, Label, Button, neutral surfaces, localized English/Chinese copy, keyboard focus, and loading/error/retry states. See [AI permissions](docs/AI_PERMISSIONS.md) for enforcement and migration behavior.

‎docs/AI_PERMISSIONS.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,11 @@ Agent executors are bound to a conversation and its connection/source identities
2323
Preparation rejects denied calls before displaying confirmation. A queued call whose confirmation requirements become stricter returns to the existing approval flow. Permission denials are terminal and do not trigger transport retries; approval never bypasses a later denial. Rechecks occur at dispatch and do not cancel operations already dispatched or erase context already sent to a model.
2424

2525
The host-hook API is introduced by [data-studio-agent #35](https://github.com/geek-fun/data-studio-agent/pull/35). Merge that runtime implementation before merging its consumers. Keep the exact compatible revision until a release containing these hooks exists; after the runtime is merged and released, update both the manifest and lockfile to that release. Older release tags do not provide this API.
26+
27+
## Permission controls
28+
29+
Settings separate MCP service controls from the AI defaults shared by Data Studio and external MCP clients. Access levels use the existing settings radio pattern, with a short description inside each option. Custom is an access choice that reveals individual actions; it edits the same values as the presets. Choosing Custom alone does not change permissions.
30+
31+
Connection dialogs default to system inheritance. Each custom action offers Use default (with the current decision), Allow, or Deny, alongside its effective decision and source. Within the connection section, saved custom combinations show their action controls automatically. Choosing a preset sets explicit decisions for every action; choosing Use system default clears them.
32+
33+
Editing AI permission defaults and per-connection decisions requires the existing local Ultimate entitlement, including eligible version-locked releases. Community users see the existing upgrade prompt in connection dialogs. Ordinary connection edits preserve saved decisions. Permission cleanup after deletion remains available only when the connection no longer exists; it cannot reset the permissions of a saved connection.

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

Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,13 +67,61 @@ pub fn get_ai_permissions(app: AppHandle) -> Result<AiPolicy, String> {
6767
load_permission_policy(&app)
6868
}
6969

70+
fn authorize_permission_change(
71+
access: Result<(), String>,
72+
defaults: &Option<PermissionRules>,
73+
connection_id: Option<&str>,
74+
permissions: &Option<PermissionRules>,
75+
saved_connections: impl FnOnce() -> Result<Option<Value>, String>,
76+
) -> Result<(), String> {
77+
if access.is_ok()
78+
|| defaults.is_some()
79+
|| permissions
80+
.as_ref()
81+
.is_some_and(|rules| *rules != PermissionRules::default())
82+
{
83+
return access;
84+
}
85+
let Some(id) = connection_id else {
86+
return access;
87+
};
88+
match saved_connections()? {
89+
None => Ok(()),
90+
Some(Value::Array(connections))
91+
if connections
92+
.iter()
93+
.all(|connection| match connection.get("id") {
94+
Some(Value::String(saved)) => saved != id,
95+
Some(Value::Number(saved)) => saved.to_string() != id,
96+
_ => false,
97+
}) =>
98+
{
99+
Ok(())
100+
}
101+
_ => access,
102+
}
103+
}
104+
70105
#[tauri::command]
71106
pub fn save_ai_permissions(
72107
defaults: Option<PermissionRules>,
73108
connection_id: Option<String>,
74109
permissions: Option<PermissionRules>,
75110
app: AppHandle,
76111
) -> Result<AiPolicy, String> {
112+
authorize_permission_change(
113+
crate::entitlement::ensure_local_ultimate(
114+
&app.state::<crate::entitlement::EntitlementState>(),
115+
"AI permissions",
116+
),
117+
&defaults,
118+
connection_id.as_deref(),
119+
&permissions,
120+
|| {
121+
let store = app.store(".store.dat").map_err(|e| e.to_string())?;
122+
Ok(store.get("connections"))
123+
},
124+
)?;
77125
let _guard = AI_POLICY_LOCK.lock().map_err(|e| e.to_string())?;
78126
let mut policy = load_permission_policy_inner(&app)?;
79127
if let Some(defaults) = defaults {
@@ -93,3 +141,111 @@ pub fn save_ai_permissions(
93141
config.save(&dir)?;
94142
Ok(policy)
95143
}
144+
145+
#[cfg(test)]
146+
mod entitlement_tests {
147+
use super::*;
148+
use serde_json::json;
149+
150+
fn denied() -> Result<(), String> {
151+
Err(crate::entitlement::entitlement_required_error(
152+
"AI permissions",
153+
))
154+
}
155+
156+
#[test]
157+
fn ultimate_can_edit_defaults_and_connection_decisions_without_cleanup_lookup() {
158+
assert!(authorize_permission_change(
159+
Ok(()),
160+
&Some(PermissionRules::default()),
161+
Some("saved"),
162+
&Some(PermissionRules::explicit(true, false, false, false, false)),
163+
|| panic!("editing must not use the cleanup path"),
164+
)
165+
.is_ok());
166+
}
167+
168+
#[test]
169+
fn community_cannot_edit_defaults_or_explicit_connection_decisions() {
170+
assert!(authorize_permission_change(
171+
denied(),
172+
&Some(PermissionRules::default()),
173+
None,
174+
&None,
175+
|| panic!("denied defaults must not inspect storage"),
176+
)
177+
.is_err());
178+
assert!(authorize_permission_change(
179+
denied(),
180+
&None,
181+
Some("saved"),
182+
&Some(PermissionRules::explicit(false, false, false, false, false)),
183+
|| panic!("explicit denials are permission edits, not cleanup"),
184+
)
185+
.is_err());
186+
assert!(authorize_permission_change(
187+
denied(),
188+
&None,
189+
Some("new"),
190+
&Some(PermissionRules::explicit(true, false, false, false, false)),
191+
|| panic!("new connection permissions also require Ultimate"),
192+
)
193+
.is_err());
194+
}
195+
196+
#[test]
197+
fn community_cannot_reset_a_saved_connections_permissions() {
198+
for (id, connections) in [
199+
("saved", json!([{"id":"saved"}])),
200+
("42", json!([{"id":42}])),
201+
] {
202+
let error = authorize_permission_change(
203+
denied(),
204+
&None,
205+
Some(id),
206+
&Some(PermissionRules::default()),
207+
|| Ok(Some(connections)),
208+
)
209+
.unwrap_err();
210+
assert!(error.contains("ENTITLEMENT_REQUIRED"));
211+
}
212+
}
213+
214+
#[test]
215+
fn community_can_only_cleanup_decisions_for_deleted_connections() {
216+
assert!(authorize_permission_change(
217+
denied(),
218+
&None,
219+
Some("deleted"),
220+
&Some(PermissionRules::default()),
221+
|| Ok(Some(json!([{"id":"retained"}]))),
222+
)
223+
.is_ok());
224+
assert!(
225+
authorize_permission_change(denied(), &None, Some("last-deleted"), &None, || Ok(None),)
226+
.is_ok()
227+
);
228+
}
229+
230+
#[test]
231+
fn unreadable_or_malformed_connections_do_not_authorize_cleanup() {
232+
for connections in [
233+
json!({}),
234+
json!([{"name":"missing-id"}]),
235+
json!([{"id":null}]),
236+
] {
237+
assert!(
238+
authorize_permission_change(denied(), &None, Some("saved"), &None, || Ok(Some(
239+
connections
240+
)),)
241+
.is_err()
242+
);
243+
}
244+
assert!(
245+
authorize_permission_change(denied(), &None, Some("saved"), &None, || Err(
246+
"Storage unavailable".into()
247+
),)
248+
.is_err()
249+
);
250+
}
251+
}

‎src/__tests__/aiPermissions.test.ts‎

Lines changed: 100 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,29 @@
11
/** @jest-environment jsdom */
22
import { invoke } from '@tauri-apps/api/core'
3+
import { openUrl } from '@tauri-apps/plugin-opener'
34
import { flushPromises, mount } from '@vue/test-utils'
4-
import { defineComponent } from 'vue'
5+
import { defineComponent, reactive } from 'vue'
56
import { AI_ACTIONS, aiPreset, resolveAiPermissions } from '@/common/aiPermissions'
67
import ConnectionPermissionEditor from '@/components/ai-permissions/ConnectionPermissionEditor.vue'
78
import DefaultPermissionEditor from '@/components/ai-permissions/DefaultPermissionEditor.vue'
89
import SourcePermissionModal from '@/views/data-studio/components/modify-source-modal.vue'
910

1011
jest.mock('@tauri-apps/api/core', () => ({ invoke: jest.fn() }))
11-
jest.mock('@/common', () => jest.requireActual('@/common/aiPermissions'))
12+
jest.mock('@/common', () => ({ ...jest.requireActual('@/common/aiPermissions'), UPGRADE_URL: 'https://example.test/upgrade' }))
13+
const mockEntitlement = reactive({ isLocalUltimate: true })
14+
jest.mock('@/store', () => ({ useEntitlementStore: () => mockEntitlement }))
15+
jest.mock('@tauri-apps/plugin-opener', () => ({ openUrl: jest.fn() }))
16+
jest.mock('@/components/upgrade', () => ({ ProBadge: { template: '<span>Ultimate</span>' } }))
1217
jest.mock('vue-i18n', () => ({ useI18n: () => ({ t: (key: string) => key }) }))
1318
jest.mock('@/components/ui/button', () => ({ Button: { template: '<button><slot /></button>' } }))
1419
jest.mock('@/components/ui/label', () => ({ Label: { template: '<label><slot /></label>' } }))
20+
jest.mock('@/components/ui/radio-group', () => ({
21+
RadioGroup: { props: ['modelValue', 'disabled'], emits: ['update:modelValue'], template: '<fieldset :data-value="modelValue" :disabled="disabled" @change="$emit(\'update:modelValue\', $event.target.value)"><slot /></fieldset>' },
22+
RadioGroupItem: { props: ['value'], template: '<input type="radio" :value="value">' },
23+
}))
24+
jest.mock('@/components/ui/switch', () => ({
25+
Switch: { props: ['checked', 'disabled'], emits: ['update:checked'], template: '<input type="checkbox" :checked="checked" :disabled="disabled" @change="$emit(\'update:checked\', $event.target.checked)">' },
26+
}))
1527
jest.mock('@/components/ui/select', () => ({
1628
Select: { props: ['modelValue'], emits: ['update:modelValue'], template: '<select :value="modelValue" @change="$emit(\'update:modelValue\', $event.target.value)"><slot /></select>' },
1729
SelectTrigger: { template: '<span />' },
@@ -57,32 +69,73 @@ const openEditor = async (id?: string) => {
5769

5870
describe('aI permission chain', () => {
5971
beforeEach(() => {
72+
mockEntitlement.isLocalUltimate = true
6073
mockStore.updateSessionSourcePermissions.mockReset()
6174
mockStore.detachSourceFromSession.mockReset()
6275
mockInvoke.mockReset()
6376
mockInvoke.mockResolvedValue(policy)
6477
})
6578

79+
it('gates Community users without loading permissions or blocking ordinary connection saves', async () => {
80+
mockEntitlement.isLocalUltimate = false
81+
const wrapper = mount(ConnectionPermissionEditor, { props: { connectionId: 'dev' } })
82+
await flushPromises()
83+
expect(mockInvoke).not.toHaveBeenCalled()
84+
expect(wrapper.find('details').exists()).toBe(false)
85+
expect(wrapper.text()).toContain('aiPermissions.ultimateOnly')
86+
expect((wrapper.vm as unknown as { ready: boolean }).ready).toBe(true)
87+
await wrapper.get('button').trigger('click')
88+
expect(openUrl).toHaveBeenCalledWith('https://example.test/upgrade')
89+
mockEntitlement.isLocalUltimate = true
90+
await flushPromises()
91+
expect(mockInvoke).toHaveBeenCalledWith('get_ai_permissions')
92+
expect(wrapper.find('details').exists()).toBe(true)
93+
})
94+
95+
it('discards an in-flight permission load when Ultimate access is lost', async () => {
96+
let finishLoad!: (value: typeof policy) => void
97+
mockInvoke.mockImplementationOnce(() => new Promise((resolve) => {
98+
finishLoad = resolve
99+
}))
100+
const wrapper = mount(ConnectionPermissionEditor, { props: { connectionId: 'dev' } })
101+
mockEntitlement.isLocalUltimate = false
102+
await flushPromises()
103+
finishLoad(policy)
104+
await flushPromises()
105+
expect(wrapper.emitted('update:modelValue')).toBeUndefined()
106+
expect(wrapper.find('details').exists()).toBe(false)
107+
expect((wrapper.vm as unknown as { ready: boolean }).ready).toBe(true)
108+
})
109+
66110
it('resolves each action with explicit false distinct from inheritance', () => {
67111
expect(resolveAiPermissions(aiPreset('full'), { update: false })).toEqual({ read: true, create: true, update: false, delete: true, manage: true })
68112
expect(resolveAiPermissions({}, { read: true })).toEqual(aiPreset('read'))
69113
expect(aiPreset('inherit')).toEqual({})
70114
expect(AI_ACTIONS.every(action => aiPreset('none')[action] === false)).toBe(true)
71115
})
72116

117+
it('describes every access level inside its own selectable container', async () => {
118+
const wrapper = mount(DefaultPermissionEditor)
119+
await flushPromises()
120+
;['none', 'read', 'data', 'full', 'custom'].forEach((value) => {
121+
const option = wrapper.get(`label[for="ai-default-preset-${value}"]`)
122+
expect(option.text()).toContain(`aiPermissions.${value}Help`)
123+
expect(option.get('input').attributes('aria-describedby')).toBe(`ai-default-preset-${value}-description`)
124+
})
125+
})
126+
73127
it('loads saved decisions and displays effective access from the whole chain', async () => {
74128
const wrapper = await openEditor('dev')
75129
expect(wrapper.vm.rules).toEqual({ update: true, delete: false })
76130
expect(wrapper.text()).toContain('aiPermissions.effective: aiPermissions.read, aiPermissions.update')
77-
await wrapper.get('button').trigger('click')
131+
expect(wrapper.findAll('select')).toHaveLength(5)
78132
expect(wrapper.text()).toContain('aiPermissions.fromConnection')
79133
expect(wrapper.text()).toContain('aiPermissions.fromSystem')
80134
})
81135

82136
it('supports inherit, explicit allow and explicit deny independently', async () => {
83137
const wrapper = await openEditor('dev')
84-
await wrapper.get('button').trigger('click')
85-
const actionSelect = () => wrapper.findAll('select')[3]
138+
const actionSelect = () => wrapper.findAll('select')[2]
86139
await actionSelect().setValue('deny')
87140
expect(wrapper.vm.rules).toEqual({ update: false, delete: false })
88141
await actionSelect().setValue('inherit')
@@ -93,20 +146,55 @@ describe('aI permission chain', () => {
93146

94147
it('keeps custom decisions when opening the custom preset', async () => {
95148
const wrapper = await openEditor('dev')
96-
await wrapper.get('select').setValue('custom')
149+
await wrapper.get('input[value="custom"]').setValue()
97150
expect(wrapper.vm.rules).toEqual({ update: true, delete: false })
98-
expect(wrapper.findAll('select')).toHaveLength(6)
151+
expect(wrapper.findAll('select')).toHaveLength(5)
99152
})
100153

101154
it('new connections inherit and presets preserve explicit decisions', async () => {
102155
const wrapper = await openEditor()
103156
expect(wrapper.vm.rules).toEqual({})
104-
await wrapper.get('select').setValue('none')
157+
await wrapper.get('input[value="none"]').setValue()
105158
expect(wrapper.vm.rules).toEqual(aiPreset('none'))
106-
await wrapper.get('select').setValue('inherit')
159+
await wrapper.get('input[value="inherit"]').setValue()
107160
expect(wrapper.vm.rules).toEqual({})
108161
})
109162

163+
it('offers Custom from inherited access without changing stored decisions', async () => {
164+
const wrapper = await openEditor()
165+
await wrapper.get('input[value="custom"]').setValue()
166+
expect(wrapper.vm.rules).toEqual({})
167+
expect(wrapper.findAll('select')).toHaveLength(5)
168+
await wrapper.findAll('select')[1].setValue('allow')
169+
expect(wrapper.vm.rules).toEqual({ create: true })
170+
await wrapper.get('input[value="inherit"]').setValue()
171+
expect(wrapper.vm.rules).toEqual({})
172+
expect(wrapper.findAll('select')).toHaveLength(0)
173+
})
174+
175+
it('shows custom defaults on load and keeps action editing open when values match a preset', async () => {
176+
mockInvoke.mockResolvedValueOnce({ permission_defaults: { ...aiPreset('read'), create: true }, connection_permissions: {} })
177+
const wrapper = mount(DefaultPermissionEditor)
178+
await flushPromises()
179+
expect(wrapper.findAll('input[type="checkbox"]')).toHaveLength(5)
180+
await wrapper.get('#ai-default-create').setValue(false)
181+
expect(wrapper.get('[data-value]').attributes('data-value')).toBe('custom')
182+
expect(wrapper.findAll('input[type="checkbox"]')).toHaveLength(5)
183+
await wrapper.get('button').trigger('click')
184+
await flushPromises()
185+
expect(mockInvoke).toHaveBeenLastCalledWith('save_ai_permissions', { defaults: aiPreset('read') })
186+
})
187+
188+
it('entering Custom does not change default permissions or introduce a separate policy', async () => {
189+
const wrapper = mount(DefaultPermissionEditor)
190+
await flushPromises()
191+
await wrapper.get('input[value="custom"]').setValue()
192+
expect(wrapper.findAll('input[type="checkbox"]')).toHaveLength(5)
193+
await wrapper.get('button').trigger('click')
194+
await flushPromises()
195+
expect(mockInvoke).toHaveBeenLastCalledWith('save_ai_permissions', { defaults: aiPreset('read') })
196+
})
197+
110198
it('blocks readiness after load failure and recovers through Retry', async () => {
111199
mockInvoke.mockRejectedValueOnce(new Error('Unavailable'))
112200
const wrapper = await openEditor('dev')
@@ -121,11 +209,11 @@ describe('aI permission chain', () => {
121209
it('retries failed default saves without discarding the edited permissions', async () => {
122210
const wrapper = mount(DefaultPermissionEditor)
123211
await flushPromises()
124-
await wrapper.get('select').setValue('full')
212+
await wrapper.get('input[value="full"]').setValue()
125213
mockInvoke.mockRejectedValueOnce(new Error('Temporarily unavailable'))
126214
await wrapper.findAll('button').find(button => button.text() === 'aiPermissions.save')!.trigger('click')
127215
await flushPromises()
128-
expect(wrapper.get('select').element.value).toBe('full')
216+
expect(wrapper.get('[data-value]').attributes('data-value')).toBe('full')
129217
await wrapper.findAll('button').find(button => button.text() === 'aiPermissions.retry')!.trigger('click')
130218
await flushPromises()
131219
expect(mockInvoke).toHaveBeenLastCalledWith('save_ai_permissions', { defaults: aiPreset('full') })
@@ -162,7 +250,7 @@ describe('aI permission chain', () => {
162250
it('saves system defaults without overwriting connection decisions', async () => {
163251
const wrapper = mount(DefaultPermissionEditor)
164252
await flushPromises()
165-
await wrapper.get('select').setValue('none')
253+
await wrapper.get('input[value="none"]').setValue()
166254
await wrapper.findAll('button').find(button => button.text() === 'aiPermissions.save')!.trigger('click')
167255
await flushPromises()
168256
expect(mockInvoke).toHaveBeenLastCalledWith('save_ai_permissions', { defaults: aiPreset('none') })

0 commit comments

Comments
 (0)