wsb-daemon 0.248.6265

wsb's daemon: the workbench, the GitHub mirror's schedule and peer continuity, for every workspace on the machine
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
use wsb::persist::global::models::{DBMessage, DBSession, MinimapEntry, SessionFilter, Stats};
use wsb::prelude::*;
use crate::web::machine_web::{place_filter, MachineWeb};
use axum::{
    extract::{Path, Query, State},
    http::StatusCode,
    response::sse::{Event, KeepAlive, Sse},
    Json,
};
use std::convert::Infallible;

#[derive(Deserialize)]
pub struct ListSessionsQuery {
    pub limit: Option<i64>,
    pub cursor: Option<String>,
    pub project: Option<String>,
    pub worktree: Option<String>,
    pub placed: Option<String>,
    pub machine: Option<String>,
    pub agent: Option<String>,
    pub date: Option<String>,
    pub date_from: Option<String>,
    pub date_to: Option<String>,
    pub active_since: Option<String>,
    pub min_messages: Option<i64>,
    pub max_messages: Option<i64>,
    pub min_user_messages: Option<i64>,
    pub include_one_shot: Option<String>,
    pub include_children: Option<String>,
}

#[derive(Serialize)]
pub struct SessionListResponse {
    pub sessions: Vec<DBSession>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
    pub total: usize,
}

pub async fn list_sessions(
    State(state): State<MachineWeb>,
    Query(params): Query<ListSessionsQuery>,
) -> Result<Json<SessionListResponse>, (StatusCode, Json<ErrorResponse>)> {
    let limit = params.limit.unwrap_or(200).min(500);
    let filter = SessionFilter {
        place: place_filter(params.project, params.worktree, params.placed)?,
        machine: params
            .machine
            .map(|m| m.split(',').map(|s| s.to_string()).collect()),
        agent: params
            .agent
            .map(|a| a.split(',').map(|s| s.to_string()).collect()),
        date: params.date,
        date_from: params.date_from,
        date_to: params.date_to,
        active_since: params.active_since,
        min_messages: params.min_messages,
        max_messages: params.max_messages,
        min_user_messages: params.min_user_messages,
        include_one_shot: params.include_one_shot.as_deref() == Some("true"),
        include_children: params.include_children.as_deref() == Some("true"),
    };

    let cursor = params.cursor.as_ref().and_then(|c| {
        let parts: Vec<&str> = c.splitn(2, '|').collect();
        if parts.len() == 2 {
            Some((parts[0].to_string(), parts[1].to_string()))
        } else {
            None
        }
    });

    let db = state.db.clone();

    let sessions = tokio::task::spawn_blocking(move || {
        db.list_sessions(&filter, limit + 1, cursor)
    })
    .await
    .unwrap_or_else(|e| Err(anyhow::anyhow!("join error: {}", e)))
    .map_err(|e| internal_error(&e.to_string()))?;

    let has_more = sessions.len() as i64 > limit;
    let sessions: Vec<_> = sessions.into_iter().take(limit as usize).collect();
    let total = sessions.len();

    let next_cursor = if has_more {
        sessions
            .last()
            .map(|s| format!("{}|{}", s.ended_at.as_deref().unwrap_or(""), s.id))
    } else {
        None
    };

    Ok(Json(SessionListResponse {
        sessions,
        next_cursor,
        total,
    }))
}

pub async fn get_session(
    State(state): State<MachineWeb>,
    Path(id): Path<String>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<ErrorResponse>)> {
    let db = state.db.clone();
    let id_check = id.clone();

    let session = tokio::task::spawn_blocking(move || db.get_session(&id_check))
        .await
        .unwrap_or_else(|e| Err(anyhow::anyhow!("join error: {}", e)))
        .map_err(|e| internal_error(&e.to_string()))?;

    match session {
        Some(s) => {
            let is_starred = tokio::task::spawn_blocking({
                let db = state.db.clone();
                move || db.is_starred(&id)
            })
            .await
            .unwrap_or_else(|e| Err(anyhow::anyhow!("join error: {}", e)))
            .unwrap_or(false);

            let mut val = serde_json::to_value(&s).unwrap();
            val.as_object_mut()
                .unwrap()
                .insert("is_starred".to_string(), serde_json::json!(is_starred));
            Ok(Json(val))
        }
        None => Err(not_found("session not found")),
    }
}

#[derive(Deserialize)]
pub struct MessagesQuery {
    pub limit: Option<i64>,
    pub from: Option<i64>,
    pub direction: Option<String>,
}

#[derive(Serialize)]
pub struct MessagesResponse {
    pub messages: Vec<DBMessage>,
    pub count: usize,
}

pub async fn get_messages(
    State(state): State<MachineWeb>,
    Path(id): Path<String>,
    Query(params): Query<MessagesQuery>,
) -> Result<Json<MessagesResponse>, (StatusCode, Json<ErrorResponse>)> {
    let limit = params.limit.unwrap_or(100).min(1000);
    let desc = params.direction.as_deref() == Some("desc");
    let from = params.from.unwrap_or(if desc { i64::MAX } else { 0 });

    let db = state.db.clone();
    let id_clone = id.clone();

    let messages = tokio::task::spawn_blocking(move || {
        db.get_messages(&id_clone, limit, from, desc)
    })
    .await
    .unwrap_or_else(|e| Err(anyhow::anyhow!("join error: {}", e)))
    .map_err(|e| internal_error(&e.to_string()))?;

    let count = messages.len();
    Ok(Json(MessagesResponse { messages, count }))
}

pub async fn get_children(
    State(state): State<MachineWeb>,
    Path(id): Path<String>,
) -> Result<Json<Vec<DBSession>>, (StatusCode, Json<ErrorResponse>)> {
    let db = state.db.clone();

    let children = tokio::task::spawn_blocking(move || db.get_children(&id))
        .await
        .unwrap_or_else(|e| Err(anyhow::anyhow!("join error: {}", e)))
        .map_err(|e| internal_error(&e.to_string()))?;

    Ok(Json(children))
}

#[derive(Deserialize)]
pub struct MinimapQuery {
    pub from: Option<i64>,
    pub max: Option<i64>,
}

#[derive(Serialize)]
pub struct MinimapResponse {
    pub entries: Vec<MinimapEntry>,
    pub count: usize,
}

pub async fn get_minimap(
    State(state): State<MachineWeb>,
    Path(id): Path<String>,
    Query(params): Query<MinimapQuery>,
) -> Result<Json<MinimapResponse>, (StatusCode, Json<ErrorResponse>)> {
    let db = state.db.clone();

    let entries = tokio::task::spawn_blocking(move || {
        db.get_minimap(&id, params.from.unwrap_or(0), params.max)
    })
    .await
    .unwrap_or_else(|e| Err(anyhow::anyhow!("join error: {}", e)))
    .map_err(|e| internal_error(&e.to_string()))?;

    let count = entries.len();
    Ok(Json(MinimapResponse { entries, count }))
}

#[derive(Deserialize)]
pub struct SessionSearchQuery {
    pub q: String,
}

pub async fn search_session(
    State(state): State<MachineWeb>,
    Path(id): Path<String>,
    Query(params): Query<SessionSearchQuery>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<ErrorResponse>)> {
    let db = state.db.clone();
    let id_clone = id.clone();
    let q = params.q.clone();

    let ordinals =
        tokio::task::spawn_blocking(move || db.search_session(&id_clone, &q))
            .await
            .unwrap_or_else(|e| Err(anyhow::anyhow!("join error: {}", e)))
            .map_err(|e| internal_error(&e.to_string()))?;

    Ok(Json(serde_json::json!({ "ordinals": ordinals })))
}

pub async fn watch_session(
    State(state): State<MachineWeb>,
    Path(id): Path<String>,
) -> Sse<impl futures::Stream<Item = Result<Event, Infallible>>> {
    let stream = async_stream::stream! {
        let mut last_count: i64 = 0;
        let mut last_mtime: i64 = 0;
        let mut heartbeat_counter: u32 = 0;
        let db = state.db.clone();
        let id_clone = id.clone();

        if let Ok(Some((count, mtime))) = tokio::task::spawn_blocking(move || {
            db.get_session_version(&id_clone)
        }).await.unwrap_or_else(|e| Err(anyhow::anyhow!("join error: {}", e))) {
            last_count = count;
            last_mtime = mtime;
        }

        loop {
            tokio::time::sleep(std::time::Duration::from_millis(1500)).await;
            heartbeat_counter += 1;

            let db = state.db.clone();
            let id_clone = id.clone();

            match tokio::task::spawn_blocking(move || {
                db.get_session_version(&id_clone)
            }).await {
                Ok(Ok(Some((count, mtime)))) => {
                    if count != last_count || mtime != last_mtime {
                        last_count = count;
                        last_mtime = mtime;
                        yield Ok(Event::default()
                            .event("session_updated")
                            .data(id.clone()));
                    }
                }
                Ok(Ok(None)) => {
                    break;
                }
                _ => {}
            }

            if heartbeat_counter >= 20 {
                heartbeat_counter = 0;
                yield Ok(Event::default()
                    .event("heartbeat")
                    .data(chrono::Utc::now().to_rfc3339()));
            }
        }
    };

    Sse::new(stream).keep_alive(KeepAlive::default())
}

#[derive(Deserialize)]
pub struct RenameRequest {
    pub display_name: Option<String>,
}

pub async fn rename_session(
    State(state): State<MachineWeb>,
    Path(id): Path<String>,
    Json(body): Json<RenameRequest>,
) -> Result<Json<DBSession>, (StatusCode, Json<ErrorResponse>)> {
    let db = state.db.clone();
    let db_get = state.db.clone();
    let id_get = id.clone();

    tokio::task::spawn_blocking(move || {
        db.rename_session(&id, body.display_name.as_deref())
    })
    .await
    .unwrap_or_else(|e| Err(anyhow::anyhow!("join error: {}", e)))
    .map_err(|e| internal_error(&e.to_string()))?;

    let session = tokio::task::spawn_blocking(move || db_get.get_session(&id_get))
        .await
        .unwrap_or_else(|e| Err(anyhow::anyhow!("join error: {}", e)))
        .map_err(|e| internal_error(&e.to_string()))?;

    match session {
        Some(s) => Ok(Json(s)),
        None => Err(not_found("session not found")),
    }
}

pub async fn delete_session(
    State(state): State<MachineWeb>,
    Path(id): Path<String>,
) -> Result<StatusCode, (StatusCode, Json<ErrorResponse>)> {
    let db = state.db.clone();

    let deleted = tokio::task::spawn_blocking(move || db.soft_delete_session(&id))
        .await
        .unwrap_or_else(|e| Err(anyhow::anyhow!("join error: {}", e)))
        .map_err(|e| internal_error(&e.to_string()))?;

    if deleted {
        Ok(StatusCode::NO_CONTENT)
    } else {
        Err(not_found("session not found"))
    }
}

pub async fn restore_session(
    State(state): State<MachineWeb>,
    Path(id): Path<String>,
) -> Result<StatusCode, (StatusCode, Json<ErrorResponse>)> {
    let db = state.db.clone();

    let restored = tokio::task::spawn_blocking(move || db.restore_session(&id))
        .await
        .unwrap_or_else(|e| Err(anyhow::anyhow!("join error: {}", e)))
        .map_err(|e| internal_error(&e.to_string()))?;

    if restored {
        Ok(StatusCode::NO_CONTENT)
    } else {
        Err(not_found("session not found or not in trash"))
    }
}

pub async fn permanent_delete(
    State(state): State<MachineWeb>,
    Path(id): Path<String>,
) -> Result<StatusCode, (StatusCode, Json<ErrorResponse>)> {
    let db = state.db.clone();

    let deleted = tokio::task::spawn_blocking(move || db.permanent_delete(&id))
        .await
        .unwrap_or_else(|e| Err(anyhow::anyhow!("join error: {}", e)))
        .map_err(|e| internal_error(&e.to_string()))?;

    if deleted {
        Ok(StatusCode::NO_CONTENT)
    } else {
        Err((
            StatusCode::CONFLICT,
            Json(ErrorResponse {
                error: "session not found or not in trash".to_string(),
            }),
        ))
    }
}

#[derive(Deserialize)]
pub struct OneShot {
    pub include_one_shot: Option<String>,
}

/// How many sessions ran in each project and worktree, and outside `$PRJ`.
pub async fn list_places(
    State(state): State<MachineWeb>,
    Query(params): Query<OneShot>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<ErrorResponse>)> {
    let include = params.include_one_shot.as_deref() == Some("true");
    let db = state.db.clone();

    let places = tokio::task::spawn_blocking(move || db.list_places(include))
        .await
        .unwrap_or_else(|e| Err(anyhow::anyhow!("join error: {}", e)))
        .map_err(|e| internal_error(&e.to_string()))?;

    Ok(Json(serde_json::json!(places)))
}

#[derive(Deserialize)]
pub struct StatsQuery {
    pub include_one_shot: Option<String>,
    pub project: Option<String>,
    pub worktree: Option<String>,
    pub placed: Option<String>,
}

pub async fn list_machines(
    State(state): State<MachineWeb>,
    Query(params): Query<OneShot>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<ErrorResponse>)> {
    let include = params.include_one_shot.as_deref() == Some("true");
    let db = state.db.clone();

    let machines = tokio::task::spawn_blocking(move || db.list_machines(include))
        .await
        .unwrap_or_else(|e| Err(anyhow::anyhow!("join error: {}", e)))
        .map_err(|e| internal_error(&e.to_string()))?;

    Ok(Json(serde_json::json!({ "machines": machines })))
}

pub async fn list_agents(
    State(state): State<MachineWeb>,
    Query(params): Query<OneShot>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<ErrorResponse>)> {
    let include = params.include_one_shot.as_deref() == Some("true");
    let db = state.db.clone();

    let agents = tokio::task::spawn_blocking(move || db.list_agents(include))
        .await
        .unwrap_or_else(|e| Err(anyhow::anyhow!("join error: {}", e)))
        .map_err(|e| internal_error(&e.to_string()))?;

    Ok(Json(serde_json::json!({ "agents": agents })))
}

pub async fn get_stats(
    State(state): State<MachineWeb>,
    Query(params): Query<StatsQuery>,
) -> Result<Json<Stats>, (StatusCode, Json<ErrorResponse>)> {
    let include = params.include_one_shot.as_deref() == Some("true");
    let place = place_filter(params.project, params.worktree, params.placed)?;
    let db = state.db.clone();

    let stats = tokio::task::spawn_blocking(move || db.get_stats(include, &place))
        .await
        .unwrap_or_else(|e| Err(anyhow::anyhow!("join error: {}", e)))
        .map_err(|e| internal_error(&e.to_string()))?;

    Ok(Json(stats))
}

#[derive(Serialize, Debug)]
pub struct ErrorResponse {
    pub error: String,
}

fn internal_error(msg: &str) -> (StatusCode, Json<ErrorResponse>) {
    (
        StatusCode::INTERNAL_SERVER_ERROR,
        Json(ErrorResponse {
            error: msg.to_string(),
        }),
    )
}

#[derive(Deserialize)]
pub struct CompactQuery {
    pub token_mode: Option<String>,
}

pub async fn get_compact_text(
    State(state): State<MachineWeb>,
    Path(id): Path<String>,
    Query(params): Query<CompactQuery>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<ErrorResponse>)> {
    let token_mode = params.token_mode.as_deref() == Some("true");
    let db = state.db.clone();
    let id_clone = id.clone();

    let messages = tokio::task::spawn_blocking(move || {
        db.get_messages(&id_clone, i64::MAX, 0, false)
    })
    .await
    .unwrap_or_else(|e| Err(anyhow::anyhow!("join error: {}", e)))
    .map_err(|e| internal_error(&e.to_string()))?;

    let text = messages
        .iter()
        .filter(|m| !m.content.trim().is_empty())
        .map(|m| {
            let role = match m.role.as_str() {
                "user" => "USER:",
                "assistant" => "ASSIST:",
                other => other,
            };
            format!("{}\n{}", role, m.content.trim())
        })
        .collect::<Vec<_>>()
        .join("\n\n");

    let compacted = wsb::compact::compact_text(&text, token_mode);

    Ok(Json(serde_json::json!({
        "text": compacted,
    })))
}

pub async fn export_session(
    State(state): State<MachineWeb>,
    Path(id): Path<String>,
) -> Result<axum::response::Response, (StatusCode, Json<ErrorResponse>)> {
    let db = state.db.clone();
    let id_for_messages = id.clone();
    let id_for_body = id.clone();

    let (session, messages) = tokio::task::spawn_blocking(move || {
        let session = db.get_session(&id_for_messages)?;
        let msgs = db
            .get_messages(&id_for_messages, i64::MAX, 0, false)?;
        anyhow::Ok((session, msgs))
    })
    .await
    .unwrap_or_else(|e| Err(anyhow::anyhow!("join error: {}", e)))
    .map_err(|e| internal_error(&e.to_string()))?;

    let session = session.ok_or_else(|| not_found("Session not found"))?;

    let title = session
        .display_name
        .clone()
        .or_else(|| {
            session.project.clone().map(|project| match &session.worktree {
                Some(worktree) => format!("{project}/{worktree}"),
                None => project,
            })
        })
        .unwrap_or_else(|| id_for_body.clone());
    let title = title.as_str();

    let mut body = format!("# {}\n\n", title);
    for m in &messages {
        let role = match m.role.as_str() {
            "user" => "User",
            "assistant" => "Assistant",
            other => other,
        };
        body.push_str(&format!("## {}\n\n{}\n\n", role, m.content));
    }

    let filename = format!(
        "{}-{}.md",
        title.replace(' ', "-"),
        &id_for_body[..8.min(id_for_body.len())]
    );

    Ok(axum::response::IntoResponse::into_response((
        [
            ("content-type", "text/markdown; charset=utf-8"),
            (
                "content-disposition",
                format!("attachment; filename=\"{}\"", filename).as_str(),
            ),
        ],
        body,
    )))
}

fn not_found(msg: &str) -> (StatusCode, Json<ErrorResponse>) {
    (
        StatusCode::NOT_FOUND,
        Json(ErrorResponse {
            error: msg.to_string(),
        }),
    )
}