Skip to content

Commit 27aaf06

Browse files
committed
fix: preserve blocked agent outcomes and restore permission recovery
1 parent 24f4bfe commit 27aaf06

37 files changed

Lines changed: 1233 additions & 114 deletions

‎.impeccable/config.json‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
{
2+
"detector": {
3+
"ignoreRules": [],
4+
"ignoreFiles": [],
5+
"ignoreValues": [
6+
{
7+
"rule": "side-tab",
8+
"value": "*",
9+
"files": [
10+
"src/components/agent-message-bubble.vue"
11+
],
12+
"createdAt": "2026-10-27T07:14:06.715Z",
13+
"reason": "Agent review: this neutral border marks semantic Markdown blockquotes, not decorative card accents."
14+
},
15+
{
16+
"rule": "bounce-easing",
17+
"value": "typing-bounce",
18+
"files": [
19+
"src/components/agent-message-bubble.vue"
20+
],
21+
"createdAt": "2026-10-27T07:14:06.764Z",
22+
"reason": "Agent review: the existing typing dots pulse from scale 0 to 1 with ease-in-out; there is no bounce, overshoot, or elastic easing."
23+
}
24+
]
25+
}
26+
}

‎DESIGN.md‎

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

332332
### AI permission controls
333333

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. A short description below the option group reflects the selected access level. 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.
334+
Per-connection permission editing uses the existing local Ultimate gate and inline upgrade prompt; Community connection edits preserve saved permission decisions. Connection dialogs group the agent prompt with a collapsed AI permissions section shared by Data Studio and external MCP, separate from SSL and SSH tunnel blocks. Default to system inheritance, show effective allowed actions, and offer visible radio choices for access levels, including Custom. A short description below the option group reflects the selected access level. Custom reveals per-action switches whose labels show Use default (decision) for inherited actions and the explicit decision otherwise. 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 actions, and preserve shared RadioGroup, Switch, 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.
335+
336+
Data Studio tool outcomes remain visible outside collapsible result details. Policy blocks use a local destructive notice naming the connection, required action, and recorded permission source; user rejection uses warning feedback and explicit rejection copy. Neither uses a success verb. A blocked conversation shows a paused status near the composer. Review permissions reuses existing permission controls, and Retry request starts a fresh checked turn. Keep these notices and outcomes when restoring history; an unknown or interrupted outcome must not appear successful.

‎docs/AI_PERMISSIONS.md‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,16 @@ The host-hook API is introduced by [data-studio-agent #35](https://github.com/ge
2828

2929
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; a short description below the option group updates with the selected access level. Custom is an access choice that reveals individual actions; it edits the same values as the presets. Choosing Custom alone does not change permissions.
3030

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.
31+
Connection dialogs group the agent prompt with the AI permissions section, separate from the SSL and SSH tunnel blocks. They default to system inheritance. Custom actions use switches: inherited actions show Use default (with the current decision), explicit actions show their decision with the connection source, and toggling sets an explicit decision. 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.
3232

3333
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.
34+
35+
## Blocked actions and conversation history
36+
37+
Ask and Auto both run permitted reads automatically. Ask requests approval for ordinary data writes; Auto runs them automatically. Both modes request approval for permitted deletes and structure/administration changes unless a saved confirmation rule applies. The application displays the approval card when the agent submits a tool call; model instructions do not replace that gate. Approval does not grant an action denied by the connection chain or conversation restrictions.
38+
39+
A policy denial records the tool result and pauses the agent through the existing runtime cancellation boundary. The host persists the conversation as blocked and reports that state after the run has settled. Already dispatched work is not undone. Other unresolved calls show an unavailable outcome instead of success. Explicit user rejection remains distinct from a policy block.
40+
41+
Each denied call retains a visible notice with its connection, required action, and decision source when recorded. Review permissions opens the existing system, connection, source, or confirmation-rule control. 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.
42+
43+
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.

‎src-tauri/src/agent/events.rs‎

Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
use std::sync::Mutex;
2+
3+
use data_studio_agent::traits::{CancelMap, EventEmitter};
4+
use serde_json::Value;
5+
6+
use crate::ai_permissions::AccessDenial;
7+
8+
pub(crate) struct AgentRunEmitter<E> {
9+
pub inner: E,
10+
pub cancel_map: CancelMap,
11+
pub blocked: Mutex<Option<Value>>,
12+
}
13+
14+
impl<E: EventEmitter> EventEmitter for AgentRunEmitter<E> {
15+
fn emit(&self, event: &str, mut payload: Value) {
16+
if event == "agent-loop-tool-result" && payload["denied"] == true {
17+
let denial = AccessDenial::from_message(
18+
payload["envelope"]["summary"]
19+
.as_str()
20+
.unwrap_or("Access denied"),
21+
);
22+
payload["envelope"]["summary"] = Value::String(denial.message.clone());
23+
payload["denial"] = serde_json::to_value(&denial).unwrap();
24+
if denial.kind != "user" {
25+
let mut blocked = self
26+
.blocked
27+
.lock()
28+
.unwrap_or_else(|error| error.into_inner());
29+
if blocked.is_none() {
30+
*blocked = Some(payload.clone());
31+
if let Some(session) = payload["session_id"].as_str() {
32+
// Use the runtime's cancellation boundary after it records the denied result.
33+
let _ = data_studio_agent::loop_runner::cancel_agent_loop(
34+
session,
35+
&self.cancel_map,
36+
);
37+
}
38+
}
39+
}
40+
}
41+
let blocked = self
42+
.blocked
43+
.lock()
44+
.unwrap_or_else(|error| error.into_inner())
45+
.is_some();
46+
if blocked
47+
&& (event == "agent-loop-done"
48+
|| event == "agent-loop-iteration"
49+
|| (event == "agent-loop-error" && payload["error"] == "cancelled"))
50+
{
51+
return;
52+
}
53+
self.inner.emit(event, payload);
54+
}
55+
}
56+
57+
#[cfg(test)]
58+
mod tests {
59+
use super::*;
60+
use serde_json::json;
61+
use std::{collections::HashMap, sync::Arc};
62+
63+
#[derive(Default)]
64+
struct Events(Mutex<Vec<(String, Value)>>);
65+
impl EventEmitter for Events {
66+
fn emit(&self, event: &str, payload: Value) {
67+
self.0.lock().unwrap().push((event.into(), payload));
68+
}
69+
}
70+
71+
#[test]
72+
fn permission_denial_cancels_further_work_without_hiding_the_result() {
73+
let (tx, mut rx) = tokio::sync::oneshot::channel();
74+
let emitter = AgentRunEmitter {
75+
inner: Events::default(),
76+
cancel_map: Arc::new(Mutex::new(HashMap::from([("chat".into(), tx)]))),
77+
blocked: Mutex::new(None),
78+
};
79+
let denial = AccessDenial::permission(
80+
crate::ai_permissions::Permission::Manage,
81+
"db",
82+
"connection",
83+
);
84+
emitter.emit("agent-loop-tool-result", json!({"session_id":"chat","tool_call_id":"call","denied":true,"envelope":{"summary":denial.encode()}}));
85+
assert_eq!(rx.try_recv(), Ok(()));
86+
emitter.emit("agent-loop-error", json!({"error":"cancelled"}));
87+
emitter.emit("agent-loop-iteration", json!({}));
88+
let events = emitter.inner.0.lock().unwrap();
89+
assert_eq!(events.len(), 1);
90+
assert_eq!(events[0].1["denial"]["source"], "connection");
91+
assert_eq!(events[0].1["envelope"]["summary"], denial.message);
92+
assert!(emitter.blocked.lock().unwrap().is_some());
93+
}
94+
95+
#[test]
96+
fn user_rejection_does_not_become_a_permission_block() {
97+
let emitter = AgentRunEmitter {
98+
inner: Events::default(),
99+
cancel_map: Arc::new(Mutex::new(HashMap::new())),
100+
blocked: Mutex::new(None),
101+
};
102+
emitter.emit(
103+
"agent-loop-tool-result",
104+
json!({"denied":true,"envelope":{"summary":"Tool call was not approved"}}),
105+
);
106+
assert!(emitter.blocked.lock().unwrap().is_none());
107+
assert_eq!(
108+
emitter.inner.0.lock().unwrap()[0].1["denial"]["kind"],
109+
"user"
110+
);
111+
}
112+
113+
#[tokio::test]
114+
async fn denied_preflight_persists_result_and_stops_before_another_model_turn() {
115+
use async_trait::async_trait;
116+
use data_studio_agent::{
117+
storage::{db::AgentDb, session_store::SqliteSessionStore},
118+
tool_executor::{ToolCallPreparation, ToolEnvelope, ToolExecutor},
119+
};
120+
use std::sync::atomic::{AtomicUsize, Ordering};
121+
122+
struct Deny;
123+
#[async_trait]
124+
impl ToolExecutor for Deny {
125+
fn prepare(
126+
&self,
127+
_: &str,
128+
_: &Value,
129+
_: &Value,
130+
_: &HashMap<String, Value>,
131+
) -> Result<ToolCallPreparation, String> {
132+
Err(AccessDenial::permission(
133+
crate::ai_permissions::Permission::Manage,
134+
"db",
135+
"system",
136+
)
137+
.encode())
138+
}
139+
async fn execute(&self, _: &str, _: &Value, _: &Value) -> Result<ToolEnvelope, String> {
140+
panic!("a blocked action must not execute")
141+
}
142+
}
143+
144+
let requests = Arc::new(AtomicUsize::new(0));
145+
let count = requests.clone();
146+
let response = format!(
147+
"data: {}\n\ndata: {}\n\ndata: [DONE]\n\n",
148+
json!({"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call","type":"function","function":{"name":"sqlkit__execute_ddl","arguments":"{\"connection_id\":\"db\",\"sql\":\"CREATE TABLE example(id INT)\"}"}}]}}]}),
149+
json!({"choices":[{"delta":{},"finish_reason":"tool_calls"}]})
150+
);
151+
let router = axum::Router::new().route(
152+
"/v1/chat/completions",
153+
axum::routing::post(move || {
154+
count.fetch_add(1, Ordering::SeqCst);
155+
let response = response.clone();
156+
async move { ([("content-type", "text/event-stream")], response) }
157+
}),
158+
);
159+
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
160+
let address = listener.local_addr().unwrap();
161+
let server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
162+
let db = AgentDb(Arc::new(Mutex::new(
163+
rusqlite::Connection::open_in_memory().unwrap(),
164+
)));
165+
data_studio_agent::storage::db::migrate(&db).unwrap();
166+
db.0.lock().unwrap().execute("INSERT INTO agent_sessions (id,title,created_at,updated_at) VALUES ('chat','Chat',0,0)", []).unwrap();
167+
let cancel_map = Arc::new(Mutex::new(HashMap::new()));
168+
let emitter = AgentRunEmitter {
169+
inner: Events::default(),
170+
cancel_map: cancel_map.clone(),
171+
blocked: Mutex::new(None),
172+
};
173+
let settings = json!({"baseUrl":format!("http://{address}"),"model":"gpt-4o-mini","apiKey":"synthetic","proxyMode":"none","tools":[{"type":"function","function":{"name":"sqlkit__execute_ddl","parameters":{"type":"object"}}}],"maxIterations":3});
174+
let result = tokio::time::timeout(
175+
std::time::Duration::from_secs(10),
176+
data_studio_agent::loop_runner::run_agent_loop(
177+
"chat",
178+
"Create example",
179+
&settings,
180+
&SqliteSessionStore::new(db.clone()),
181+
&emitter,
182+
&Deny,
183+
HashMap::from([("db".into(), json!({"connectionId":"db"}))]),
184+
Value::Null,
185+
&Arc::new(Mutex::new(HashMap::new())),
186+
&cancel_map,
187+
&|_| false,
188+
&|_, _| false,
189+
),
190+
)
191+
.await
192+
.unwrap();
193+
server.abort();
194+
assert_eq!(result.unwrap_err(), "cancelled");
195+
assert_eq!(requests.load(Ordering::SeqCst), 1);
196+
assert!(emitter.blocked.lock().unwrap().is_some());
197+
let conn = db.0.lock().unwrap();
198+
let status: String = conn
199+
.query_row(
200+
"SELECT status FROM agent_tool_calls WHERE id='call'",
201+
[],
202+
|row| row.get(0),
203+
)
204+
.unwrap();
205+
assert_eq!(status, "denied");
206+
let result_count: i64 = conn
207+
.query_row(
208+
"SELECT COUNT(*) FROM agent_messages WHERE role='tool'",
209+
[],
210+
|row| row.get(0),
211+
)
212+
.unwrap();
213+
assert_eq!(result_count, 1);
214+
}
215+
}

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// App-specific agent modules — shared logic is in data-studio-agent-lib.
2+
pub(crate) mod events;
23
pub mod executor;
34
pub mod query_history;
45
pub mod session_store;

0 commit comments

Comments
 (0)