1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
//! ACP agent message processing for WindowState.
//!
//! Contains:
//! - `process_agent_messages_tick`: drain agent message queue, update AI inspector,
//! auto-context feeding, snapshot refresh, and bounded skill-failure recovery.
//!
//! Private stateless helpers (sensitive-key detection, command redaction, tool-name
//! extraction) live in the sibling `agent_message_helpers` module.
//!
//! Per-tick helper methods (recovery retry, auto-context, snapshot refresh) live in
//! the sibling `agent_tick_helpers` module.
//!
//! Config update application is in `agent_config.rs`.
//! Screenshot capture is in `agent_screenshot.rs`.
use crate::ai_inspector::chat::{
ChatMessage, extract_inline_config_update, extract_inline_tool_function_name,
};
use crate::app::window_state::WindowState;
use crate::app::window_state::agent_message_helpers::is_terminal_screenshot_permission_tool;
use par_term_acp::AgentMessage;
impl WindowState {
/// Process incoming ACP agent messages for this render tick and refresh
/// the AI Inspector snapshot when needed.
///
/// Called once per frame from `submit_gpu_frame()`. Handles the full agent message
/// dispatch loop, deferred config updates, inline tool-markup fallback,
/// bounded skill-failure recovery, auto-context feeding, and snapshot refresh.
pub(crate) fn process_agent_messages_tick(&mut self) {
let mut saw_prompt_complete_this_tick = false;
// Process agent messages
let msg_count_before = self.overlay_ui.ai_inspector.chat.messages.len();
// Config update requests are deferred until message processing completes.
type ConfigUpdateEntry = (
std::collections::HashMap<String, serde_json::Value>,
tokio::sync::oneshot::Sender<Result<(), String>>,
);
let mut pending_config_updates: Vec<ConfigUpdateEntry> = Vec::new();
let messages = self.agent_state.drain_messages();
for msg in messages {
match msg {
AgentMessage::StatusChanged(status) => {
// Flush any pending agent text on status change.
self.overlay_ui.ai_inspector.chat.flush_agent_message();
self.overlay_ui.ai_inspector.agent_status = status;
self.focus_state.needs_redraw = true;
}
AgentMessage::SessionUpdate(update) => {
match &update {
par_term_acp::SessionUpdate::ToolCall(info) => {
let title_l = info.title.to_ascii_lowercase();
if title_l.contains("skill")
|| title_l.contains("todo")
|| title_l.contains("enterplanmode")
{
self.agent_state.agent_skill_failure_detected = true;
}
}
par_term_acp::SessionUpdate::ToolCallUpdate(info) => {
if let Some(status) = &info.status {
let status_l = status.to_ascii_lowercase();
if status_l.contains("fail") || status_l.contains("error") {
self.agent_state.agent_skill_failure_detected = true;
}
}
}
par_term_acp::SessionUpdate::CurrentModeUpdate { mode_id } => {
if mode_id.eq_ignore_ascii_case("plan") {
self.agent_state.agent_skill_failure_detected = true;
self.overlay_ui.ai_inspector.chat.add_system_message(
"Agent switched to plan mode during an executable task. Requesting default mode and retry guidance."
.to_string(),
);
if let Some(agent) = &self.agent_state.agent {
let agent = agent.clone();
self.runtime.spawn(async move {
let agent = agent.lock().await;
if let Err(e) = agent.set_mode("default").await {
log::error!(
"ACP: failed to auto-reset mode from plan to default: {e}"
);
}
});
}
}
}
_ => {}
}
self.overlay_ui.ai_inspector.chat.handle_update(update);
self.focus_state.needs_redraw = true;
}
AgentMessage::PermissionRequest {
request_id,
tool_call,
options,
} => {
log::info!(
"ACP: permission request id={request_id} options={}",
options.len()
);
let description = tool_call
.get("title")
.and_then(|t| t.as_str())
.unwrap_or("Permission requested")
.to_string();
if is_terminal_screenshot_permission_tool(&tool_call)
&& !self
.config
.ai_inspector
.ai_inspector_agent_screenshot_access
{
let deny_option_id = options
.iter()
.find(|o| {
matches!(
o.kind.as_deref(),
Some("deny")
| Some("reject")
| Some("cancel")
| Some("disallow")
) || o.name.to_lowercase().contains("deny")
|| o.name.to_lowercase().contains("reject")
|| o.name.to_lowercase().contains("cancel")
})
.or_else(|| options.first())
.map(|o| o.option_id.clone());
if let Some(client) = &self.agent_state.agent_client {
let client = client.clone();
self.runtime.spawn(async move {
use par_term_acp::{PermissionOutcome, RequestPermissionResponse};
let outcome = RequestPermissionResponse {
outcome: PermissionOutcome {
outcome: "selected".to_string(),
option_id: deny_option_id,
},
};
let response_json =
serde_json::to_value(&outcome).unwrap_or_default();
if let Err(e) =
client.respond(request_id, Some(response_json), None).await
{
log::error!(
"ACP: failed to auto-deny screenshot permission: {e}"
);
}
});
} else {
log::error!(
"ACP: cannot auto-deny screenshot permission id={request_id} \
— agent_client is None!"
);
}
self.overlay_ui.ai_inspector.chat.add_system_message(format!(
"Blocked screenshot request (`{description}`) because \"Allow Agent Screenshots\" is disabled in Settings > Assistant > Permissions."
));
self.focus_state.needs_redraw = true;
continue;
}
self.overlay_ui
.ai_inspector
.chat
.messages
.push(ChatMessage::Permission {
request_id,
description,
options: options
.iter()
.map(|o| (o.option_id.clone(), o.name.clone()))
.collect(),
resolved: false,
});
self.focus_state.needs_redraw = true;
}
AgentMessage::PromptStarted => {
self.agent_state.agent_skill_failure_detected = false;
self.overlay_ui.ai_inspector.chat.mark_oldest_pending_sent();
// Remove the corresponding handle (first in queue).
if !self.agent_state.pending_send_handles.is_empty() {
self.agent_state.pending_send_handles.pop_front();
}
self.focus_state.needs_redraw = true;
}
AgentMessage::PromptComplete => {
saw_prompt_complete_this_tick = true;
self.overlay_ui.ai_inspector.chat.flush_agent_message();
self.focus_state.needs_redraw = true;
}
AgentMessage::ConfigUpdate { updates, reply } => {
pending_config_updates.push((updates, reply));
}
AgentMessage::ClientReady(client) => {
log::info!("ACP: agent_client ready");
self.agent_state.agent_client = Some(client);
}
AgentMessage::AutoApproved(description) => {
self.overlay_ui
.ai_inspector
.chat
.add_auto_approved(description);
self.focus_state.needs_redraw = true;
}
}
}
// Process deferred config updates now that message processing completes.
for (updates, reply) in pending_config_updates {
let result = self.apply_agent_config_updates(&updates);
if result.is_ok() {
self.render_loop.config_changed_by_agent = true;
}
let _ = reply.send(result);
self.focus_state.needs_redraw = true;
}
// Track recoverable local backend tool failures during the current
// prompt (for example failed `Skill`/`Write` calls).
if !self.agent_state.agent_skill_failure_detected {
let mut seen_user_boundary = false;
for msg in self.overlay_ui.ai_inspector.chat.messages.iter().rev() {
if matches!(msg, ChatMessage::User { .. }) {
seen_user_boundary = true;
break;
}
if let ChatMessage::ToolCall { title, status, .. } = msg {
let title_l = title.to_ascii_lowercase();
let status_l = status.to_ascii_lowercase();
let is_failed = status_l.contains("fail") || status_l.contains("error");
let is_recoverable_tool = title_l.contains("skill")
|| title_l == "write"
|| title_l.starts_with("write ")
|| title_l.contains(" write ");
if is_failed && is_recoverable_tool {
self.agent_state.agent_skill_failure_detected = true;
break;
}
}
}
// If there is no user message yet, ignore stale history.
if !seen_user_boundary {
self.agent_state.agent_skill_failure_detected = false;
}
}
// Compatibility fallback: some local ACP backends emit literal
// `<function=...>` tool markup in chat instead of structured tool calls.
// Parse inline `config_update` payloads from newly added agent messages
// and apply them so config changes still work.
let inline_updates: Vec<(usize, std::collections::HashMap<String, serde_json::Value>)> =
self.overlay_ui
.ai_inspector
.chat
.messages
.iter()
.enumerate()
.skip(msg_count_before)
.filter_map(|(idx, msg)| match msg {
ChatMessage::Agent(text) => {
extract_inline_config_update(text).map(|updates| (idx, updates))
}
_ => None,
})
.collect();
for (idx, updates) in inline_updates {
match self.apply_agent_config_updates(&updates) {
Ok(()) => {
self.render_loop.config_changed_by_agent = true;
if let Some(ChatMessage::Agent(text)) =
self.overlay_ui.ai_inspector.chat.messages.get_mut(idx)
{
*text = "Applied config update request.".to_string();
}
self.overlay_ui.ai_inspector.chat.add_system_message(
"Applied inline config_update fallback from agent output.".to_string(),
);
}
Err(e) => {
self.overlay_ui
.ai_inspector
.chat
.add_system_message(format!("Inline config_update fallback failed: {e}"));
}
}
self.focus_state.needs_redraw = true;
}
// Detect other inline XML-style tool markup (we only auto-apply
// `config_update`). Treat these as recoverable local backend tool
// failures so we can issue a one-shot retry with stricter guidance.
for msg in self
.overlay_ui
.ai_inspector
.chat
.messages
.iter()
.skip(msg_count_before)
{
if let ChatMessage::Agent(text) = msg
&& let Some(function_name) = extract_inline_tool_function_name(text)
&& function_name != "mcp__par-term-config__config_update"
{
self.agent_state.agent_skill_failure_detected = true;
self.overlay_ui.ai_inspector.chat.add_system_message(format!(
"Agent emitted inline tool markup (`{function_name}`) instead of a structured ACP tool call."
));
self.focus_state.needs_redraw = true;
break;
}
}
let last_user_text = self
.overlay_ui
.ai_inspector
.chat
.messages
.iter()
.rev()
.find_map(|msg| {
if let ChatMessage::User { text, .. } = msg {
Some(text.clone())
} else {
None
}
});
let shader_activation_incomplete = if saw_prompt_complete_this_tick {
if let Some(user_text) = last_user_text.as_deref() {
if crate::ai_inspector::shader_context::is_shader_activation_request(user_text) {
let mut saw_user_boundary = false;
let mut saw_config_update_for_prompt = false;
for msg in self.overlay_ui.ai_inspector.chat.messages.iter().rev() {
match msg {
ChatMessage::User { .. } => {
saw_user_boundary = true;
break;
}
ChatMessage::ToolCall { title, .. } => {
let title_l = title.to_ascii_lowercase();
if title_l.contains("config_update") {
saw_config_update_for_prompt = true;
break;
}
}
_ => {}
}
}
saw_user_boundary && !saw_config_update_for_prompt
} else {
false
}
} else {
false
}
} else {
false
};
// Delegate recovery/retry to agent_tick_helpers.
self.attempt_skill_failure_recovery(
saw_prompt_complete_this_tick,
shader_activation_incomplete,
&last_user_text,
);
// Delegate auto-context + command suggestion execution to agent_tick_helpers.
self.feed_auto_context(msg_count_before);
// Delegate snapshot refresh to agent_tick_helpers.
self.refresh_inspector_snapshot();
}
}