forked from 1jehuang/jcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbus.rs
More file actions
430 lines (385 loc) · 12.2 KB
/
bus.rs
File metadata and controls
430 lines (385 loc) · 12.2 KB
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
419
420
421
422
423
424
425
426
427
428
429
430
use crate::message::ToolCall;
use crate::side_panel::SidePanelSnapshot;
use crate::todo::TodoItem;
pub use jcode_background_types::{
BackgroundTaskProgress, BackgroundTaskProgressEvent, BackgroundTaskProgressKind,
BackgroundTaskProgressSource, BackgroundTaskStatus,
};
pub use jcode_batch_types::{BatchProgress, BatchSubcallProgress, BatchSubcallState};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
use tokio::sync::broadcast;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ToolStatus {
Running,
Completed,
Error,
}
impl ToolStatus {
pub fn as_str(&self) -> &'static str {
match self {
ToolStatus::Running => "running",
ToolStatus::Completed => "completed",
ToolStatus::Error => "error",
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ToolEvent {
pub session_id: String,
pub message_id: String,
pub tool_call_id: String,
pub tool_name: String,
pub status: ToolStatus,
pub title: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TodoEvent {
pub session_id: String,
pub todos: Vec<TodoItem>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ToolSummaryState {
pub status: String,
pub title: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ToolSummary {
pub id: String,
pub tool: String,
pub state: ToolSummaryState,
}
/// Status update from a subagent (used by Task tool)
#[derive(Clone, Debug)]
pub struct SubagentStatus {
pub session_id: String,
pub status: String, // e.g., "calling API", "running grep", "streaming"
pub model: Option<String>,
}
#[derive(Clone, Debug)]
pub struct ManualToolCompleted {
pub session_id: String,
pub tool_call: ToolCall,
pub output: String,
pub is_error: bool,
pub title: Option<String>,
pub duration_ms: u64,
}
/// Type of file operation for swarm awareness
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum FileOp {
Read,
Write,
Edit,
}
impl FileOp {
pub fn as_str(&self) -> &'static str {
match self {
FileOp::Read => "read",
FileOp::Write => "wrote",
FileOp::Edit => "edited",
}
}
pub fn is_modification(&self) -> bool {
matches!(self, FileOp::Write | FileOp::Edit)
}
}
/// File touch event for swarm coordination
#[derive(Clone, Debug)]
pub struct FileTouch {
pub session_id: String,
pub path: PathBuf,
pub op: FileOp,
/// Human-readable summary like "edited lines 45-60" or "read 200 lines"
pub summary: Option<String>,
/// Optional compact preview of what changed. Keep this short and already truncated.
pub detail: Option<String>,
}
/// Event sent when a background task completes
#[derive(Debug, Clone)]
pub struct BackgroundTaskCompleted {
pub task_id: String,
pub tool_name: String,
pub display_name: Option<String>,
pub session_id: String,
pub status: BackgroundTaskStatus,
pub exit_code: Option<i32>,
pub output_preview: String,
pub output_file: PathBuf,
pub duration_secs: f64,
pub notify: bool,
pub wake: bool,
}
#[derive(Clone, Debug)]
pub struct LoginCompleted {
pub provider: String,
pub success: bool,
pub message: String,
}
#[derive(Clone, Debug)]
pub struct InputShellCompleted {
pub session_id: String,
pub result: crate::message::InputShellResult,
}
#[derive(Clone, Debug)]
pub enum ClipboardPasteKind {
Smart,
ImageOnly,
ImageUrl { fallback_text: Option<String> },
}
#[derive(Clone, Debug)]
pub enum ClipboardPasteContent {
Text(String),
Image {
media_type: String,
base64_data: String,
},
Empty,
Error(String),
}
#[derive(Clone, Debug)]
pub struct ClipboardPasteCompleted {
pub session_id: String,
pub kind: ClipboardPasteKind,
pub content: ClipboardPasteContent,
}
#[derive(Clone, Debug)]
pub struct ModelRefreshCompleted {
pub session_id: String,
pub result: std::result::Result<crate::provider::ModelCatalogRefreshSummary, String>,
}
#[derive(Clone, Debug)]
pub struct GitStatusCompleted {
pub session_id: String,
pub result: std::result::Result<String, String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SidePanelUpdated {
pub session_id: String,
pub snapshot: SidePanelSnapshot,
}
#[derive(Clone, Debug)]
pub enum UpdateStatus {
Checking,
Available { current: String, latest: String },
Downloading { version: String },
Installed { version: String },
UpToDate,
Error(String),
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ClientMaintenanceAction {
Update,
Rebuild,
}
impl ClientMaintenanceAction {
pub fn noun(&self) -> &'static str {
match self {
Self::Update => "update",
Self::Rebuild => "rebuild",
}
}
pub fn title(&self) -> &'static str {
match self {
Self::Update => "Update",
Self::Rebuild => "Rebuild",
}
}
}
#[derive(Clone, Debug)]
pub enum SessionUpdateStatus {
Status {
session_id: String,
action: ClientMaintenanceAction,
message: String,
},
NoUpdate {
session_id: String,
current: String,
},
ReadyToReload {
session_id: String,
action: ClientMaintenanceAction,
version: String,
},
Error {
session_id: String,
action: ClientMaintenanceAction,
message: String,
},
}
#[derive(Clone, Debug)]
pub enum BusEvent {
ToolUpdated(ToolEvent),
TodoUpdated(TodoEvent),
SubagentStatus(SubagentStatus),
ManualToolCompleted(ManualToolCompleted),
BatchProgress(BatchProgress),
/// File was touched by an agent (for swarm conflict detection)
FileTouch(FileTouch),
/// Background task completed
BackgroundTaskCompleted(BackgroundTaskCompleted),
/// Background task reported progress
BackgroundTaskProgress(BackgroundTaskProgressEvent),
/// Usage report fetched from providers
UsageReport(Vec<crate::usage::ProviderUsage>),
/// Progressive usage report update while providers are still loading
UsageReportProgress(crate::usage::ProviderUsageProgress),
/// OAuth/login flow completed in the background
LoginCompleted(LoginCompleted),
/// Local `!cmd` shell command completed from the input line
InputShellCompleted(InputShellCompleted),
/// Clipboard paste/image URL work completed off the UI thread
ClipboardPasteCompleted(ClipboardPasteCompleted),
/// Local model catalog refresh completed off the UI thread
ModelRefreshCompleted(ModelRefreshCompleted),
/// Local git status command completed off the UI thread
GitStatusCompleted(GitStatusCompleted),
/// Update check status from background thread
UpdateStatus(UpdateStatus),
/// Interactive client update status for a specific session
SessionUpdateStatus(SessionUpdateStatus),
/// External dictation command completed with transcript text
DictationCompleted {
dictation_id: String,
session_id: Option<String>,
text: String,
mode: crate::protocol::TranscriptMode,
},
/// External dictation command failed
DictationFailed {
dictation_id: String,
session_id: Option<String>,
message: String,
},
/// Background compaction task finished (check_and_apply should be called)
CompactionFinished,
/// Provider's available models list may have changed
ModelsUpdated,
/// A background provider setup task selected a model for this session.
ProviderModelActivated {
session_id: String,
model: String,
message: String,
open_picker: bool,
},
/// Side panel pages were updated for a session
SidePanelUpdated(SidePanelUpdated),
/// Deferred Mermaid rendering completed and cached content may now be visible
MermaidRenderCompleted,
}
pub struct Bus {
sender: broadcast::Sender<BusEvent>,
}
const MODELS_UPDATED_DEBOUNCE: Duration = Duration::from_millis(750);
#[derive(Default)]
struct ModelsUpdatedPublishState {
last_published_at: Option<Instant>,
publish_pending: bool,
}
fn models_updated_publish_state() -> &'static Mutex<ModelsUpdatedPublishState> {
static STATE: OnceLock<Mutex<ModelsUpdatedPublishState>> = OnceLock::new();
STATE.get_or_init(|| Mutex::new(ModelsUpdatedPublishState::default()))
}
#[cfg(test)]
pub(crate) fn reset_models_updated_publish_state_for_tests() {
let mut state = models_updated_publish_state()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
*state = ModelsUpdatedPublishState::default();
}
impl Bus {
pub fn global() -> &'static Bus {
static INSTANCE: OnceLock<Bus> = OnceLock::new();
INSTANCE.get_or_init(|| {
let (sender, _) = broadcast::channel(256);
Bus { sender }
})
}
pub fn subscribe(&self) -> broadcast::Receiver<BusEvent> {
self.sender.subscribe()
}
pub fn publish(&self, event: BusEvent) {
let _ = self.sender.send(event);
}
pub fn publish_models_updated(&self) {
let delay = {
let now = Instant::now();
let mut state = models_updated_publish_state()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
match state.last_published_at {
None => {
state.last_published_at = Some(now);
None
}
Some(last) => {
let elapsed = now.saturating_duration_since(last);
if elapsed >= MODELS_UPDATED_DEBOUNCE {
state.last_published_at = Some(now);
None
} else if state.publish_pending {
return;
} else {
state.publish_pending = true;
Some(MODELS_UPDATED_DEBOUNCE - elapsed)
}
}
}
};
if let Some(delay) = delay {
let Ok(handle) = tokio::runtime::Handle::try_current() else {
let mut state = models_updated_publish_state()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
state.publish_pending = false;
state.last_published_at = Some(Instant::now());
drop(state);
self.publish(BusEvent::ModelsUpdated);
return;
};
handle.spawn(async move {
tokio::time::sleep(delay).await;
let mut state = models_updated_publish_state()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
state.publish_pending = false;
state.last_published_at = Some(Instant::now());
drop(state);
Bus::global().publish(BusEvent::ModelsUpdated);
});
return;
}
self.publish(BusEvent::ModelsUpdated);
}
}
#[cfg(test)]
mod tests {
use super::{Bus, BusEvent, reset_models_updated_publish_state_for_tests};
use tokio::time::{Duration, timeout};
#[tokio::test]
async fn models_updated_publishes_are_coalesced() {
let mut rx = Bus::global().subscribe();
while rx.try_recv().is_ok() {}
reset_models_updated_publish_state_for_tests();
Bus::global().publish_models_updated();
Bus::global().publish_models_updated();
Bus::global().publish_models_updated();
match timeout(Duration::from_secs(1), rx.recv()).await {
Ok(Ok(BusEvent::ModelsUpdated)) => {}
other => panic!("expected immediate ModelsUpdated event, got {other:?}"),
}
match timeout(Duration::from_secs(2), rx.recv()).await {
Ok(Ok(BusEvent::ModelsUpdated)) => {}
other => panic!("expected coalesced delayed ModelsUpdated event, got {other:?}"),
}
assert!(
timeout(Duration::from_millis(300), rx.recv())
.await
.is_err()
);
}
}