omniterm 0.1.9

Web-based tmux terminal manager — one browser tab to watch and drive your AI coding agents
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use std::sync::Arc;

use axum::{
    extract::{
        ws::{Message, WebSocket},
        Path, State, WebSocketUpgrade,
    },
    response::IntoResponse,
};
use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;
use tracing::{error, info};

use crate::acp::chat_persistence;
use crate::acp::permission::PermissionRequestEvent;
use crate::acp::AcpClient;
use crate::api::agents::load_agent;
use crate::AppState;

pub async fn ws_acp_handler(
    ws: WebSocketUpgrade,
    Path(session_id): Path<String>,
    State(state): State<AppState>,
) -> impl IntoResponse {
    info!("ACP WS upgrade request: session_id={}", session_id);
    ws.on_upgrade(move |socket| handle_acp_ws(socket, session_id, state))
}

#[derive(Debug, Deserialize)]
#[serde(tag = "type")]
enum AcpClientMessage {
    #[serde(rename = "prompt")]
    Prompt { text: String },
    #[serde(rename = "cancel")]
    Cancel,
    #[serde(rename = "load_session")]
    LoadSession,
    #[serde(rename = "permission_response")]
    PermissionResponse { id: String, option_id: String },
    #[serde(rename = "set_config_option")]
    SetConfigOption { config_id: String, value: String },
}

#[derive(Debug, Serialize)]
#[serde(tag = "type")]
enum AcpServerMessage<'a> {
    #[serde(rename = "error")]
    Error {
        #[serde(skip_serializing_if = "Option::is_none")]
        code: Option<&'a str>,
        message: &'a str,
    },
    #[serde(rename = "session_update")]
    SessionUpdate { data: serde_json::Value },
    #[serde(rename = "prompt_done")]
    PromptDone { stop_reason: &'a str },
    #[serde(rename = "prompt_error")]
    PromptError { message: &'a str },
    #[serde(rename = "replay_start")]
    ReplayStart,
    #[serde(rename = "replay_end")]
    ReplayEnd,
    #[serde(rename = "process_alive")]
    ProcessAlive { alive: bool },
    #[serde(rename = "permission_request")]
    PermissionRequest {
        id: &'a str,
        request: &'a serde_json::Value,
    },
}

fn extract_text_from_notification(data: &serde_json::Value) -> Option<String> {
    let update = data.get("update")?;
    let obj = update.as_object()?;

    let chunk = if let Some(c) = obj.get("AgentMessageChunk") {
        c
    } else if obj.get("sessionUpdate").and_then(|v| v.as_str())
        == Some("agent_message_chunk")
    {
        update
    } else {
        return None;
    };

    let content = chunk.get("content")?;
    if let Some(text_obj) = content.get("Text").or_else(|| content.get("text")) {
        if let Some(t) = text_obj.get("text").and_then(|v| v.as_str()) {
            return Some(t.to_string());
        }
    }
    if let Some(t) = content.get("text").and_then(|v| v.as_str()) {
        return Some(t.to_string());
    }
    if let Some(t) = chunk.get("text").and_then(|v| v.as_str()) {
        return Some(t.to_string());
    }
    None
}

async fn spawn_notify_task(
    mut rx: tokio::sync::broadcast::Receiver<agent_client_protocol::schema::v1::SessionNotification>,
    notify_tx: tokio::sync::mpsc::Sender<Message>,
    buf: Arc<Mutex<String>>,
) {
    tokio::spawn(async move {
        loop {
            match rx.recv().await {
                Ok(notification) => {
                    let data = serde_json::to_value(&notification).unwrap_or_default();
                    if let Some(text) = extract_text_from_notification(&data) {
                        buf.lock().await.push_str(&text);
                    }
                    let msg = serde_json::to_string(&AcpServerMessage::SessionUpdate { data })
                        .unwrap_or_default();
                    if notify_tx.send(Message::Text(msg.into())).await.is_err() {
                        break;
                    }
                }
                Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
                Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
                    tracing::warn!("ACP WS subscriber lagged by {} messages", n);
                }
            }
        }
    });
}

async fn spawn_permission_task(
    mut rx: tokio::sync::broadcast::Receiver<PermissionRequestEvent>,
    notify_tx: tokio::sync::mpsc::Sender<Message>,
) {
    tokio::spawn(async move {
        loop {
            match rx.recv().await {
                Ok(event) => {
                    let msg = serde_json::to_string(&AcpServerMessage::PermissionRequest {
                        id: &event.id,
                        request: &event.request,
                    })
                    .unwrap_or_default();
                    if notify_tx.send(Message::Text(msg.into())).await.is_err() {
                        break;
                    }
                }
                Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
            }
        }
    });
}

async fn handle_acp_ws(socket: WebSocket, session_id: String, state: AppState) {
    let (mut ws_tx, mut ws_rx) = socket.split();
    let (notify_tx, mut notify_rx) = tokio::sync::mpsc::channel::<Message>(64);
    let assistant_buf: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));

    let mut client: Option<Arc<AcpClient>> = match state.acp_supervisor.get(&session_id).await {
        Some(c) => {
            info!("ACP WS connected: session_id={} (supervisor hit)", session_id);
            let rx = c.session_update_subscribe();
            spawn_notify_task(rx, notify_tx.clone(), assistant_buf.clone()).await;
            let perm_rx = c.permission_subscribe();
            spawn_permission_task(perm_rx, notify_tx.clone()).await;
            if let Some(notif) = c.initial_config_notification() {
                let data = serde_json::to_value(&notif).unwrap_or_default();
                let msg =
                    serde_json::to_string(&AcpServerMessage::SessionUpdate { data })
                        .unwrap_or_default();
                let _ = notify_tx.send(Message::Text(msg.into())).await;
            }
            if let Some(notif) = c.initial_commands_notification() {
                let data = serde_json::to_value(&notif).unwrap_or_default();
                let msg =
                    serde_json::to_string(&AcpServerMessage::SessionUpdate { data })
                        .unwrap_or_default();
                let _ = notify_tx.send(Message::Text(msg.into())).await;
            }
            Some(c)
        }
        None => {
            info!("ACP WS: session_id={} not in supervisor, keeping alive for restore", session_id);
            let msg = serde_json::to_string(&AcpServerMessage::Error {
                code: Some("session_not_found"),
                message: "ACP session not found",
            })
            .unwrap();
            let _ = ws_tx.send(Message::Text(msg.into())).await;
            None
        }
    };

    // 订阅进程存活事件,向本连接转发对应会话的 process_alive 帧(事件驱动,
    // 替代前端对 acp_process_alive 的轮询)。
    let mut proc_rx = state.acp_supervisor.process_event_subscribe();
    // 连接建立即发一帧初始存活状态,作初始同步(broadcast 无历史,防止错过连接前事件)。
    let _ = notify_tx
        .send(
            Message::Text(
                serde_json::to_string(&AcpServerMessage::ProcessAlive { alive: client.is_some() })
                    .unwrap_or_default()
                    .into(),
            ),
        )
        .await;

    let db = state.db.clone();
    let sid = session_id.clone();

    loop {
        tokio::select! {
            msg = ws_rx.next() => {
                match msg {
                    Some(Ok(Message::Text(text))) => {
                        match serde_json::from_str::<AcpClientMessage>(&text) {
                            Ok(AcpClientMessage::Prompt { text: prompt_text }) => {
                                let Some(ref c) = client else {
                                    let msg = serde_json::to_string(&AcpServerMessage::Error {
                                        code: Some("session_not_found"),
                                        message: "no active ACP session",
                                    }).unwrap_or_default();
                                    let _ = ws_tx.send(Message::Text(msg.into())).await;
                                    continue;
                                };

                                let _ = chat_persistence::insert_message(
                                    &db, &sid, "user", &prompt_text,
                                ).await;

                                let c = c.clone();
                                // 标记 prompt 进行中(活跃度守卫据此判断 agent 在工作中)
                                c.mark_prompt_active();
                                let tx = notify_tx.clone();
                                let db2 = db.clone();
                                let sid2 = sid.clone();
                                let buf2 = assistant_buf.clone();
                                tokio::spawn(async move {
                                    match c.send_prompt(&prompt_text).await {
                                        Ok(resp) => {
                                            c.mark_prompt_idle();
                                            tokio::task::yield_now().await;
                                            let assistant_text = buf2.lock().await.drain(..).collect::<String>();
                                            if !assistant_text.is_empty() {
                                                let _ = chat_persistence::insert_message(
                                                    &db2, &sid2, "assistant", &assistant_text,
                                                ).await;
                                            }
                                            let reason = format!("{:?}", resp.stop_reason);
                                            let msg = serde_json::to_string(
                                                &AcpServerMessage::PromptDone { stop_reason: &reason },
                                            ).unwrap_or_default();
                                            let _ = tx.send(Message::Text(msg.into())).await;
                                        }
                                        Err(e) => {
                                            c.mark_prompt_idle();
                                            buf2.lock().await.clear();
                                            let err_msg = format!("{}", e);
                                            let msg = serde_json::to_string(
                                                &AcpServerMessage::PromptError { message: &err_msg },
                                            ).unwrap_or_default();
                                            let _ = tx.send(Message::Text(msg.into())).await;
                                        }
                                    }
                                });
                            }
                            Ok(AcpClientMessage::Cancel) => {
                                if let Some(ref c) = client {
                                    // 取消也视为 prompt 结束
                                    c.mark_prompt_idle();
                                    if let Err(e) = c.cancel() {
                                        error!("ACP cancel failed: {}", e);
                                    }
                                }
                            }
                            Ok(AcpClientMessage::LoadSession) => {
                                let row: Option<(String, String, String)> = sqlx::query_as(
                                    "SELECT agent_id, acp_session_id, workspace_path FROM sessions WHERE id = ? AND runtime_kind = 'acp'",
                                )
                                .bind(&sid)
                                .fetch_optional(&db)
                                .await
                                .ok()
                                .flatten();

                                let Some((agent_id, acp_sid, ws_path)) = row else {
                                    let msg = serde_json::to_string(&AcpServerMessage::Error {
                                        code: None,
                                        message: "session row not found or not ACP",
                                    }).unwrap_or_default();
                                    let _ = ws_tx.send(Message::Text(msg.into())).await;
                                    continue;
                                };

                                let Some(agent) = load_agent(&db, &agent_id).await else {
                                    let msg = serde_json::to_string(&AcpServerMessage::Error {
                                        code: None,
                                        message: "agent config not found",
                                    }).unwrap_or_default();
                                    let _ = ws_tx.send(Message::Text(msg.into())).await;
                                    continue;
                                };

                                let cwd = std::path::PathBuf::from(&ws_path);
                                match AcpClient::spawn_and_load(agent, cwd.clone(), acp_sid.clone()).await {
                                    Ok(new_client) => {
                                        let new_client = Arc::new(new_client);

                                        if !new_client.supports_load_session() {
                                            let msg = serde_json::to_string(&AcpServerMessage::Error {
                                                code: Some("load_not_supported"),
                                                message: "agent does not support session/load",
                                            }).unwrap_or_default();
                                            let _ = ws_tx.send(Message::Text(msg.into())).await;
                                            let c = Arc::try_unwrap(new_client).ok();
                                            if let Some(c) = c { c.disconnect().await; }
                                            continue;
                                        }

                                        // 覆盖前先回收可能残留的旧 client,避免旧进程泄漏
                                        if let Some(old) = state.acp_supervisor.dispose(&sid).await {
                                            if let Some(c) = Arc::try_unwrap(old).ok() {
                                                c.disconnect().await;
                                            }
                                        }
                                        state.acp_supervisor.insert(sid.clone(), new_client.clone()).await;

                                        let rx = new_client.session_update_subscribe();
                                        spawn_notify_task(rx, notify_tx.clone(), assistant_buf.clone()).await;
                                        let perm_rx = new_client.permission_subscribe();
                                        spawn_permission_task(perm_rx, notify_tx.clone()).await;
                                        client = Some(new_client.clone());

                                        let replay_msg = serde_json::to_string(&AcpServerMessage::ReplayStart).unwrap_or_default();
                                        let _ = ws_tx.send(Message::Text(replay_msg.into())).await;

                                        let tx = notify_tx.clone();
                                        tokio::spawn(async move {
                                            let result = new_client.load_session(&acp_sid, cwd).await;
                                            let msg = match result {
                                                Ok(()) => serde_json::to_string(&AcpServerMessage::ReplayEnd).unwrap_or_default(),
                                                Err(e) => serde_json::to_string(&AcpServerMessage::Error {
                                                    code: Some("load_failed"),
                                                    message: &format!("session/load failed: {}", e),
                                                }).unwrap_or_default(),
                                            };
                                            let _ = tx.send(Message::Text(msg.into())).await;
                                        });
                                    }
                                    Err(e) => {
                                        let err_msg = format!("failed to spawn agent: {}", e);
                                        let msg = serde_json::to_string(&AcpServerMessage::Error {
                                            code: Some("spawn_failed"),
                                            message: &err_msg,
                                        }).unwrap_or_default();
                                        let _ = ws_tx.send(Message::Text(msg.into())).await;
                                    }
                                }
                            }
                            Ok(AcpClientMessage::PermissionResponse { id, option_id }) => {
                                if let Some(ref c) = client {
                                    c.resolve_permission(&id, &option_id).await;
                                }
                            }
                            Ok(AcpClientMessage::SetConfigOption { config_id, value }) => {
                                if let Some(ref c) = client {
                                    if let Err(e) = c.set_config_option(&config_id, &value).await {
                                        error!("set_config_option failed: {}", e);
                                    }
                                }
                            }
                            Err(e) => {
                                let err_msg = format!("invalid message: {}", e);
                                let msg = serde_json::to_string(&AcpServerMessage::Error {
                                    code: None,
                                    message: &err_msg,
                                })
                                .unwrap_or_default();
                                if ws_tx.send(Message::Text(msg.into())).await.is_err() {
                                    break;
                                }
                            }
                        }
                    }
                    Some(Ok(Message::Close(_))) | None => break,
                    _ => {}
                }
            }
            msg = notify_rx.recv() => {
                match msg {
                    Some(ws_msg) => {
                        if ws_tx.send(ws_msg).await.is_err() {
                            break;
                        }
                    }
                    None => break,
                }
            }
            msg = proc_rx.recv() => {
                match msg {
                    Ok(evt) => {
                        if evt.session_id == session_id {
                            let frame = serde_json::to_string(&AcpServerMessage::ProcessAlive {
                                alive: evt.alive,
                            })
                            .unwrap_or_default();
                            if notify_tx.send(Message::Text(frame.into())).await.is_err() {
                                break;
                            }
                        }
                    }
                    // Lagged / Closed:忽略,等待下一次事件(参照现有 notify task 处理风格)
                    Err(_) => {}
                }
            }
        }
    }
}