lopi-ui 0.22.0

TUI dashboard and web API for lopi
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
//! Route handlers for the lopi web API.
//!
//! Separated from `web/mod.rs` to keep that file within the 500-line budget.
//! All functions are imported into `mod.rs` via `use handlers::*`.

use super::types::{CreateTaskRequest, CreateTaskResponse, MAX_GOAL_LENGTH};
use super::AppState;
use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::{IntoResponse, Json},
};
use lopi_core::{
    PermissionMode, PermissionModeError, Priority, ReportChannel, ReportChannelError, Task, TaskId,
};
use lopi_memory::CheckpointInput;
use lopi_spec::SpecSurface;
use serde::Deserialize;
use serde_json::{json, Value};

pub(super) async fn health() -> impl IntoResponse {
    Json(json!({ "status": "ok", "service": "lopi" }))
}

pub(super) async fn get_stats(State(s): State<AppState>) -> impl IntoResponse {
    // Lifecycle counts come from the durable store, not `pool.stats()`: those
    // in-memory counters are per-pool, so in multi-repo mode the primary pool
    // misses every task dispatched to an extra repo (Verify-1 F3/F4 — "N live"
    // read 1 while 2 ran, `succeeded` 3 against 7). The DB is shared across all
    // pools. `uptime_secs` stays sourced from the pool — it is a server-lifetime
    // clock, not a per-task tally.
    let counts = s.store.status_counts().await.unwrap_or_else(|e| {
        tracing::warn!("status_counts query failed: {e}");
        Default::default()
    });
    let uptime_secs = s.pool.stats().uptime_secs;
    let (total_tokens_today, total_cost_usd_today) =
        s.store.daily_token_totals().await.unwrap_or_else(|e| {
            tracing::warn!("daily_token_totals query failed: {e}");
            (0, 0.0)
        });
    Json(json!({
        "running": counts.running, "queued": counts.queued,
        "succeeded": counts.succeeded, "failed": counts.failed,
        "uptime_secs": uptime_secs,
        "total_tokens_today": total_tokens_today,
        "total_cost_usd_today": total_cost_usd_today,
    }))
}

pub(super) async fn list_tasks(State(s): State<AppState>) -> Json<Value> {
    let rows = s.store.load_history(100).await.unwrap_or_default();
    let costs = s.store.task_costs().await.unwrap_or_default();
    let body: Vec<_> = rows
        .into_iter()
        .map(|t| {
            let cost = costs.get(&t.id).copied().unwrap_or(0.0);
            json!({
                "id": t.id, "goal": t.goal, "status": t.status,
                "created_at": t.created_at, "completed_at": t.completed_at,
                "client_ref": t.client_ref, "cost": cost,
            })
        })
        .collect();
    Json(json!({ "tasks": body }))
}

pub(super) async fn get_task(
    Path(id): Path<String>,
    State(s): State<AppState>,
) -> impl IntoResponse {
    let rows = s.store.load_history(500).await.unwrap_or_default();
    match find_by_id_prefix(rows, &id, |t| t.id.as_str()) {
        PrefixMatch::Unique(t) => {
            let cost = s
                .store
                .task_costs()
                .await
                .unwrap_or_default()
                .get(&t.id)
                .copied()
                .unwrap_or(0.0);
            (
                StatusCode::OK,
                Json(json!({
                    "id": t.id, "goal": t.goal, "status": t.status,
                    "created_at": t.created_at, "completed_at": t.completed_at,
                    "client_ref": t.client_ref, "cost": cost,
                })),
            )
                .into_response()
        }
        PrefixMatch::NotFound => (
            StatusCode::NOT_FOUND,
            Json(json!({ "error": "task not found" })),
        )
            .into_response(),
        PrefixMatch::Ambiguous => ambiguous_prefix_response(),
    }
}

/// Outcome of a lookup by a full id or a possibly-partial prefix.
enum PrefixMatch<T> {
    /// No entity's id starts with the given prefix.
    NotFound,
    /// Exactly one match — the unambiguous case.
    Unique(T),
    /// More than one entity's id starts with the given prefix. The caller
    /// must not silently act on an arbitrary one of them (`Iterator::find`'s
    /// usual first-match behavior) — surface this to the client instead.
    Ambiguous,
}

/// Find the row in `rows` whose `id_of` value starts with `prefix`,
/// distinguishing a unique match from an ambiguous one.
fn find_by_id_prefix<T>(rows: Vec<T>, prefix: &str, id_of: impl Fn(&T) -> &str) -> PrefixMatch<T> {
    let mut matches = rows.into_iter().filter(|t| id_of(t).starts_with(prefix));
    let Some(first) = matches.next() else {
        return PrefixMatch::NotFound;
    };
    if matches.next().is_some() {
        return PrefixMatch::Ambiguous;
    }
    PrefixMatch::Unique(first)
}

/// `409` response for an id prefix that matches more than one task.
fn ambiguous_prefix_response() -> axum::response::Response {
    (
        StatusCode::CONFLICT,
        Json(json!({ "error": "id prefix matches more than one task" })),
    )
        .into_response()
}

/// Body for `POST /api/agents/:id/checkpoint`. All fields optional — only
/// `state` is required because every checkpoint must carry a phase label.
#[derive(Debug, Deserialize)]
pub(super) struct CheckpointBody {
    /// Required. Lowercase phase: planning / implementing / testing /
    /// scoring / done / errored.
    pub state: String,
    /// Optional attempt number (defaults to 0 — the runner usually sets it).
    #[serde(default)]
    pub attempt: u8,
    pub last_plan: Option<String>,
    pub last_score: Option<String>,
    pub repo_path: Option<String>,
    pub context_hash: Option<String>,
}

/// P1.3 — durable checkpoint on demand. Persists an `agent_checkpoints`
/// row keyed by `task_id` so `lopi resume --agent-id` can recover.
pub(super) async fn checkpoint_agent(
    Path(id): Path<String>,
    State(s): State<AppState>,
    Json(body): Json<CheckpointBody>,
) -> impl IntoResponse {
    let Ok(uuid) = id.parse::<uuid::Uuid>() else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({"error": "agent id must be a uuid"})),
        )
            .into_response();
    };
    let mut input = CheckpointInput::new(TaskId(uuid), body.attempt, body.state);
    input.last_plan = body.last_plan;
    input.last_score = body.last_score;
    input.repo_path = body.repo_path;
    input.context_hash = body.context_hash;
    match s.store.save_checkpoint(&input).await {
        Ok(checkpoint_id) => (
            StatusCode::CREATED,
            Json(json!({ "checkpoint_id": checkpoint_id, "task_id": id })),
        )
            .into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({ "error": format!("{e:#}") })),
        )
            .into_response(),
    }
}

pub(super) async fn cancel_task(
    Path(id): Path<String>,
    State(s): State<AppState>,
) -> impl IntoResponse {
    let rows = s.store.load_history(500).await.unwrap_or_default();
    let t = match find_by_id_prefix(rows, &id, |t| t.id.as_str()) {
        PrefixMatch::Unique(t) => t,
        PrefixMatch::NotFound => {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({"error": "task not found"})),
            )
                .into_response();
        }
        PrefixMatch::Ambiguous => return ambiguous_prefix_response(),
    };
    let Ok(uuid) = t.id.parse::<uuid::Uuid>() else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({"error": "invalid id"})),
        )
            .into_response();
    };
    let task_id = TaskId(uuid);
    // First cancel any running execution, then permanently delete the task
    // and its dependent rows. Otherwise the snapshot endpoint would resurrect
    // the closed session on the next dashboard reload.
    let cancelled = s.pool.cancel(&task_id).await;
    let deleted = match s.store.delete_task(&task_id).await {
        Ok(removed) => removed,
        Err(e) => {
            tracing::warn!(error = %e, task_id = %t.id, "delete_task failed");
            false
        }
    };
    (
        StatusCode::OK,
        Json(json!({
            "id": t.id,
            "cancelled": cancelled,
            "deleted": deleted,
        })),
    )
        .into_response()
}

/// Phase 11 — approve a paused plan; the agent proceeds to implementation.
pub(super) async fn approve_plan(
    Path(id): Path<String>,
    State(s): State<AppState>,
) -> impl IntoResponse {
    decide_plan(&s, &id, lopi_core::PlanDecision::Approve).await
}

/// Phase 11 — reject a paused plan; the agent abandons the task.
pub(super) async fn reject_plan(
    Path(id): Path<String>,
    State(s): State<AppState>,
) -> impl IntoResponse {
    decide_plan(&s, &id, lopi_core::PlanDecision::Reject).await
}

/// Deliver a plan decision to a paused runner, resolving `id` (full UUID or a
/// prefix) to a task and signalling the pool.
async fn decide_plan(
    s: &AppState,
    id: &str,
    decision: lopi_core::PlanDecision,
) -> axum::response::Response {
    let task_id = match resolve_task_id(s, id).await {
        PrefixMatch::Unique(task_id) => task_id,
        PrefixMatch::NotFound => {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({"error": "task not found"})),
            )
                .into_response();
        }
        PrefixMatch::Ambiguous => return ambiguous_prefix_response(),
    };
    if s.pool.decide_plan(&task_id, decision).await {
        (
            StatusCode::OK,
            Json(json!({"task_id": task_id.0.to_string(), "decision": decision})),
        )
            .into_response()
    } else {
        (
            StatusCode::CONFLICT,
            Json(json!({"error": "task is not awaiting plan approval"})),
        )
            .into_response()
    }
}

/// Resolve a task id from a full UUID or a unique prefix (history fallback).
async fn resolve_task_id(s: &AppState, id: &str) -> PrefixMatch<TaskId> {
    if let Ok(uuid) = id.parse::<uuid::Uuid>() {
        return PrefixMatch::Unique(TaskId(uuid));
    }
    let rows = s.store.load_history(500).await.unwrap_or_default();
    match find_by_id_prefix(rows, id, |t| t.id.as_str()) {
        PrefixMatch::Unique(t) => match t.id.parse::<uuid::Uuid>() {
            Ok(uuid) => PrefixMatch::Unique(TaskId(uuid)),
            Err(_) => PrefixMatch::NotFound,
        },
        PrefixMatch::NotFound => PrefixMatch::NotFound,
        PrefixMatch::Ambiguous => PrefixMatch::Ambiguous,
    }
}

/// Why [`apply_loop_fields`] rejected a `CreateTaskRequest` — every variant
/// maps to a 422, never a silent drop or coercion of the offending field.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub(super) enum ApplyLoopFieldsError {
    /// `req.report` named an unknown or currently-unreachable channel.
    #[error(transparent)]
    Report(#[from] ReportChannelError),
    /// `req.permission_mode` named anything other than the four headless-safe
    /// modes [`PermissionMode`] exposes.
    #[error(transparent)]
    PermissionMode(#[from] PermissionModeError),
}

/// Apply the loop/verifier/report/override fields exposed on
/// [`CreateTaskRequest`] onto a freshly constructed `Task`. Kept separate
/// from [`create_task`] so the field-mapping contract is unit-testable
/// without an HTTP round-trip.
///
/// # Errors
/// Returns [`ApplyLoopFieldsError::Report`] when `req.report` names an
/// unknown or currently-unreachable channel (e.g. `"whatsapp"`) — reuses
/// [`ReportChannel::parse`], the same validator `Task`/`ScheduleEntry`
/// already use, rather than a second report-channel parser. Returns
/// [`ApplyLoopFieldsError::PermissionMode`] when `req.permission_mode` names
/// anything other than the four headless-safe modes, reusing
/// [`PermissionMode::parse`] the same way.
pub(super) fn apply_loop_fields(
    task: &mut Task,
    req: &CreateTaskRequest,
) -> Result<(), ApplyLoopFieldsError> {
    if let Some(report) = &req.report {
        ReportChannel::parse(report)?;
        task.report = Some(report.clone());
    }
    if let Some(mode) = &req.permission_mode {
        task.permission_mode = PermissionMode::parse(mode)?;
    }
    if let Some(v) = req.verifier_required {
        task.verifier_required = v;
    }
    if let Some(m) = &req.verifier_model {
        task.verifier_model = Some(m.clone());
    }
    if let Some(e) = &req.verifier_effort {
        task.verifier_effort = Some(e.clone());
    }
    if let Some(n) = req.max_iterations {
        task.max_iterations = Some(n);
    }
    if let Some(m) = &req.model {
        task.model = Some(m.clone());
    }
    if let Some(e) = &req.effort {
        task.effort = Some(e.clone());
    }
    if let Some(d) = req.deliverable {
        task.deliverable = Some(d);
    }
    if let Some(g) = &req.gate {
        task.gate = Some(g.clone());
    }
    if let Some(u) = &req.until {
        task.until = Some(u.clone());
    }
    if let Some(f) = req.on_fail {
        task.on_fail = Some(f);
    }
    if let Some(a) = &req.acceptance {
        task.acceptance = Some(a.clone());
    }
    if let Some(fo) = req.verifier_fail_open {
        task.verifier_fail_open = fo;
    }
    if let Some(b) = req.budget_tokens {
        task.budget_tokens = b;
    }
    if let Some(bo) = &req.budget_override {
        task.budget_override = Some(bo.clone());
    }
    Ok(())
}

/// Validate a submitted goal at the API boundary, per `.claude/rules/security.md`
/// ("max goal length, character set constraints"). Rejects:
/// - empty or whitespace-only goals (Ops-2 bug #5 — `{"goal":""}` spawned a real
///   agent),
/// - goals longer than [`MAX_GOAL_LENGTH`] characters,
/// - goals carrying C0/C1 control characters other than the ordinary
///   `\n` / `\r` / `\t` whitespace — NUL and ANSI escape sequences have no place
///   in a natural-language goal and are a log-poisoning / injection vector.
///
/// Pure and separate from [`create_task`] so the boundary contract is
/// table-testable without an HTTP round-trip. Returns the human-readable
/// rejection reason on failure.
pub(super) fn validate_goal(goal: &str) -> Result<(), String> {
    if goal.trim().is_empty() {
        return Err("goal must not be empty".to_string());
    }
    if goal.chars().count() > MAX_GOAL_LENGTH {
        return Err(format!("goal too long (max {MAX_GOAL_LENGTH} chars)"));
    }
    super::types::reject_control_chars(goal)
}

pub(super) async fn create_task(
    State(s): State<AppState>,
    Json(req): Json<CreateTaskRequest>,
) -> impl IntoResponse {
    if let Err(reason) = validate_goal(&req.goal) {
        return (
            StatusCode::UNPROCESSABLE_ENTITY,
            Json(json!({ "error": reason })),
        )
            .into_response();
    }

    let mut task = Task::new(req.goal.clone());
    if let Err(e) = apply_loop_fields(&mut task, &req) {
        return (
            StatusCode::UNPROCESSABLE_ENTITY,
            Json(json!({"error": e.to_string()})),
        )
            .into_response();
    }
    task.priority = match req.priority.as_deref() {
        Some("low") => Priority::Low,
        Some("high") => Priority::High,
        Some("critical") => Priority::Critical,
        _ => Priority::Normal,
    };
    if let Some(repo) = req.repo {
        task.repo_path = Some(std::path::PathBuf::from(repo));
    }
    if let Some(dirs) = req.allowed_dirs {
        task.allowed_dirs = dirs;
    }
    if let Some(dirs) = req.forbidden_dirs {
        task.forbidden_dirs = dirs;
    }
    if let Some(c) = req.constraints {
        task.constraints = c;
    }
    if let Some(r) = req.max_retries {
        task.max_retries = r;
    }
    task.require_plan_approval = req.require_plan_approval.unwrap_or(false);
    task.client_ref = req.client_ref.clone();

    let task_id = task.id.0.to_string();
    let client_ref = task.client_ref.clone();
    let duplicate_of = s.pool.submit(task).await.map(|id| id.0.to_string());
    let resp = CreateTaskResponse {
        id: task_id,
        goal: req.goal,
        queued: duplicate_of.is_none(),
        duplicate_of,
        client_ref,
    };
    (StatusCode::CREATED, Json(resp)).into_response()
}

/// `GET /api/spec` — returns the cached or freshly-extracted spec surface.
pub(super) async fn get_spec(State(s): State<AppState>) -> impl IntoResponse {
    let surface = match SpecSurface::load(&s.repo_path) {
        Ok(Some(cached)) => cached,
        _ => match SpecSurface::extract(&s.repo_path) {
            Ok(live) => live,
            Err(e) => {
                tracing::warn!("spec extract failed: {e}");
                return (StatusCode::INTERNAL_SERVER_ERROR, "spec extraction failed")
                    .into_response();
            }
        },
    };
    Json(serde_json::json!({
        "count": surface.len(),
        "rust_files_scanned": surface.rust_files_scanned,
        "python_files_scanned": surface.python_files_scanned,
        "extracted_at": surface.extracted_at,
        "items": surface.items,
    }))
    .into_response()
}