forgetop-server 1.1.4

Local dashboard server and embedded web UI for forgetop. Internal crate: no API stability guarantees, use the `forgetop` binary instead.
Documentation
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
//! Embedded HTTP server for the forgetop web dashboard.
//!
//! It's a thin frontend over the **same** `SectionService` / health services the TUI uses —
//! no logic fork. Wave 1 is a read-only JSON API + a placeholder page, bound to `127.0.0.1`
//! and gated by a per-session token so no other local process or web page can reach it.

use std::net::Ipv4Addr;
use std::sync::Arc;

use axum::extract::{Query, Request, State};
use axum::http::{header, StatusCode, Uri};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Json, Response};
use axum::routing::{get, post};
use axum::Router;
use forgetop_core::provider::{ItemRef, PrDecoration};
use forgetop_core::secret::SecretStore;
use forgetop_core::service::{ConfigService, ConnectionHealthService, SectionService};
use rust_embed::RustEmbed;
use serde::Deserialize;

use crate::actions::ActionError;

mod actions;
mod connections;
mod dto;

/// The built dashboard SPA, baked into the binary at compile time (see `build.rs`).
#[derive(RustEmbed)]
#[folder = "web/dist"]
struct Assets;

/// Default dashboard port. `0` lets the OS pick a free one.
pub const DEFAULT_PORT: u16 = 8177;

/// The services the dashboard reads from and writes through — the same ones the TUI is given,
/// so connections added here show up in the TUI (and vice versa).
#[derive(Clone)]
pub struct Deps {
    pub sections: Arc<SectionService>,
    pub health: Arc<ConnectionHealthService>,
    pub config: Arc<ConfigService>,
    pub secrets: Arc<dyn SecretStore>,
}

/// A bound, running server: where it lives and the token needed to reach it.
pub struct Server {
    pub port: u16,
    pub token: String,
    /// `http://127.0.0.1:<port>/?t=<token>` — the URL to open in a browser.
    pub url: String,
}

/// Decorated PR fields, cached per `(connection, repository, id, updated_at)`.
///
/// `updated_at` is part of the key on purpose: it is the provider's own statement that the PR
/// changed, so a stale entry can never outlive the change that invalidates it.
#[derive(Default)]
struct DecorationCache {
    entries: std::sync::Mutex<std::collections::HashMap<String, PrDecoration>>,
}

impl DecorationCache {
    /// Bounded so a long-running dashboard can't grow it without limit. On overflow the whole
    /// map is dropped rather than evicted one by one — decoration is cheap to refetch.
    const MAX: usize = 500;

    fn key(conn: &str, item: &ItemRef, updated_at: Option<&str>) -> String {
        format!("{conn}\u{1}{}\u{1}{}\u{1}{}", item.repo.as_deref().unwrap_or(""), item.id, updated_at.unwrap_or(""))
    }

    fn get(&self, key: &str) -> Option<PrDecoration> {
        self.entries.lock().unwrap().get(key).cloned()
    }

    fn put(&self, key: String, value: PrDecoration) {
        let mut entries = self.entries.lock().unwrap();
        if entries.len() >= Self::MAX {
            entries.clear();
        }
        entries.insert(key, value);
    }
}

#[derive(Clone)]
struct AppState {
    deps: Deps,
    token: Arc<str>,
    decorations: Arc<DecorationCache>,
}

async fn bind(deps: Deps, port: u16) -> std::io::Result<(tokio::net::TcpListener, Server, AppState)> {
    let token = uuid::Uuid::new_v4().to_string();
    let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, port)).await?;
    let bound = listener.local_addr()?.port();
    let url = format!("http://127.0.0.1:{bound}/?t={token}");
    let state = AppState { deps, token: Arc::from(token.as_str()), decorations: Arc::new(DecorationCache::default()) };
    Ok((listener, Server { port: bound, token, url }, state))
}

/// Bind + serve in the background, returning the URL (with token) for the caller to open.
/// **Best-effort:** an `Err` just means "no dashboard" — the TUI should carry on regardless.
pub async fn spawn(deps: Deps, port: u16) -> std::io::Result<Server> {
    let (listener, server, state) = bind(deps, port).await?;
    tokio::spawn(async move {
        let _ = axum::serve(listener, router(state)).await;
    });
    Ok(server)
}

/// Bind + serve until the process exits (headless `--dashboard`). Calls `on_ready` with the
/// URL once bound so the caller can open the browser.
pub async fn serve_blocking(deps: Deps, port: u16, on_ready: impl FnOnce(&str)) -> std::io::Result<()> {
    let (listener, server, state) = bind(deps, port).await?;
    on_ready(&server.url);
    axum::serve(listener, router(state)).await
}

fn router(state: AppState) -> Router {
    // The API carries your data and can act on your behalf, so it's token-gated. The static
    // SPA (HTML/JS/CSS) is just code — not secret — so it's served openly; the browser gets
    // the token from the `/?t=` URL and replays it on every API call.
    let api = Router::new()
        .route("/api/health", get(health))
        .route("/api/pull-requests", get(pull_requests))
        .route("/api/work-items", get(work_items))
        .route("/api/pipelines", get(pipelines))
        .route("/api/notifications", get(notifications))
        .route("/api/launchpad", get(launchpad))
        .route("/api/pr/detail", get(pr_detail))
        .route("/api/pr/decoration", get(pr_decoration))
        .route("/api/pr/commit-changes", get(pr_commit_changes))
        .route("/api/pr/vote", post(pr_vote))
        .route("/api/pr/merge", post(pr_merge))
        .route("/api/pr/revert", post(pr_revert))
        .route("/api/pr/comment", post(pr_comment))
        .route("/api/pr/reply", post(pr_reply))
        .route("/api/pr/review", post(pr_review))
        .route("/api/wi/detail", get(wi_detail))
        .route("/api/wi/states", get(wi_states))
        .route("/api/wi/state", post(wi_state))
        .route("/api/wi/comment", post(wi_comment))
        .route("/api/wi/assignees", get(wi_assignees))
        .route("/api/wi/assignee", post(wi_assignee))
        .route("/api/wi/update", post(wi_update))
        .route("/api/pipeline/detail", get(pipeline_detail))
        .route("/api/pipeline/logs", get(pipeline_logs))
        .route("/api/pipeline/approval", post(pipeline_approval))
        .route("/api/pipeline/trigger", post(pipeline_trigger))
        .route("/api/pipeline/cancel", post(pipeline_cancel))
        .route("/api/notification/read", post(notification_read))
        .route("/api/providers", get(providers))
        .route("/api/connections", get(list_connections).post(save_connection))
        .route("/api/connections/delete", post(delete_connection))
        .route("/api/connections/test", post(test_connection))
        .route("/api/connections/repositories", get(connection_repositories))
        .route("/api/connections/scope", post(set_connection_scope))
        .layer(middleware::from_fn_with_state(state.clone(), auth))
        .with_state(state);

    Router::new().merge(api).fallback(static_asset)
}

/// Serves an embedded SPA asset by path, falling back to `index.html` for unknown routes so
/// client-side routing works on refresh/deep-link.
async fn static_asset(uri: Uri) -> Response {
    let path = uri.path().trim_start_matches('/');
    let path = if path.is_empty() { "index.html" } else { path };
    serve(path)
        .or_else(|| serve("index.html"))
        .unwrap_or_else(|| (StatusCode::NOT_FOUND, "not found").into_response())
}

fn serve(path: &str) -> Option<Response> {
    let file = Assets::get(path)?;
    let mime = mime_guess::from_path(path).first_or_octet_stream();
    Some(([(header::CONTENT_TYPE, mime.as_ref().to_string())], file.data).into_response())
}

/// Session-token gate. The browser opens `/?t=<token>`; other calls may send it as the
/// `x-forgetop-token` header. Combined with localhost-only binding, this keeps the
/// (action-capable) API off-limits to other local processes and web pages.
async fn auth(State(state): State<AppState>, req: Request, next: Next) -> Response {
    if token_from(&req).as_deref() == Some(&state.token) {
        next.run(req).await
    } else {
        (StatusCode::UNAUTHORIZED, "unauthorized").into_response()
    }
}

fn token_from(req: &Request) -> Option<String> {
    if let Some(header) = req.headers().get("x-forgetop-token").and_then(|v| v.to_str().ok()) {
        return Some(header.to_string());
    }
    req.uri()
        .query()
        .and_then(|q| q.split('&').find_map(|pair| pair.strip_prefix("t=").map(str::to_string)))
}

async fn health(State(s): State<AppState>) -> Json<Vec<dto::HealthRow>> {
    Json(dto::health(&s.deps.health).await)
}
async fn pull_requests(State(s): State<AppState>, Query(q): Query<PrListQuery>) -> Json<Vec<dto::PrRow>> {
    Json(dto::pull_requests(&s.deps.sections, dto::PrView::parse(q.view.as_deref())).await)
}
async fn work_items(State(s): State<AppState>) -> Json<Vec<dto::WiRow>> {
    Json(dto::work_items(&s.deps.sections).await)
}
async fn pipelines(State(s): State<AppState>) -> Json<Vec<dto::PipeRow>> {
    Json(dto::pipelines(&s.deps.sections).await)
}
async fn notifications(State(s): State<AppState>) -> Json<Vec<dto::NotifRow>> {
    Json(dto::notifications(&s.deps.sections).await)
}
async fn launchpad(State(s): State<AppState>) -> Json<dto::LaunchpadResponse> {
    Json(dto::launchpad(&s.deps.sections).await)
}

/// Query params identifying an item within a connection (`?conn=…&id=…&repo=…`).
///
/// `repo` is a **query parameter**, never a path segment: an `owner/repo` always contains a
/// slash. It is optional, so every link written before connections spanned an account still
/// resolves (a single-repository connection needs no address).
#[derive(Deserialize)]
struct ItemQuery {
    conn: String,
    id: String,
    #[serde(default)]
    repo: Option<String>,
}

impl ItemQuery {
    fn item(self) -> (String, ItemRef) {
        (self.conn, ItemRef::maybe(self.repo, self.id))
    }
}

/// Query params identifying a single commit's diff within a PR (`?conn=…&id=…&sha=…`).
#[derive(Deserialize)]
struct CommitQuery {
    conn: String,
    id: String,
    sha: String,
    #[serde(default)]
    repo: Option<String>,
}

/// Query params for the PR list: which view to show (`?view=all|merged|review_requested`).
#[derive(Deserialize)]
struct PrListQuery {
    #[serde(default)]
    view: Option<String>,
}

/// Query params identifying a pipeline run within a connection (`?conn=…&run_id=…`).
#[derive(Deserialize)]
struct RunQuery {
    conn: String,
    run_id: String,
    #[serde(default)]
    repo: Option<String>,
}

/// Query params for pipeline logs: a run, optionally scoped to a single job (`&job=…`).
#[derive(Deserialize)]
struct PipelineLogsQuery {
    conn: String,
    run_id: String,
    #[serde(default)]
    repo: Option<String>,
    #[serde(default)]
    job: Option<String>,
}

/// Turns an action outcome into a response: `{ok:true}`, 404 (no such connection/capability),
/// or 502 (the provider call failed).
fn action_response(operation: &'static str, result: Result<(), ActionError>) -> Response {
    match result {
        Ok(()) => Json(serde_json::json!({ "ok": true })).into_response(),
        Err(ActionError::NotFound) => (StatusCode::NOT_FOUND, "connection or capability not found").into_response(),
        Err(ActionError::Failed(msg)) => {
            forgetop_core::diag::log(operation, "provider action failed");
            (StatusCode::BAD_GATEWAY, msg).into_response()
        }
    }
}

async fn pr_commit_changes(State(s): State<AppState>, Query(q): Query<CommitQuery>) -> Response {
    match dto::pr_commit_changes(&s.deps.sections, &q.conn, &ItemRef::maybe(q.repo, q.id), &q.sha).await {
        Some(changes) => Json(changes).into_response(),
        None => (StatusCode::NOT_FOUND, "pull request not found").into_response(),
    }
}

async fn pr_detail(State(s): State<AppState>, Query(q): Query<ItemQuery>) -> Response {
    let (conn, item) = q.item();
    match dto::pr_detail(&s.deps.sections, &conn, &item).await {
        Some(detail) => Json(detail).into_response(),
        None => (StatusCode::NOT_FOUND, "pull request not found").into_response(),
    }
}

/// Query params for one PR's decoration. `updated_at` is the provider's own last-changed stamp
/// from the list row, and is what makes the cache entry safe to reuse.
#[derive(Deserialize)]
struct DecorationQuery {
    conn: String,
    id: String,
    #[serde(default)]
    repo: Option<String>,
    #[serde(default)]
    updated_at: Option<String>,
}

async fn pr_decoration(State(s): State<AppState>, Query(q): Query<DecorationQuery>) -> Response {
    let item = ItemRef::maybe(q.repo, q.id);
    let key = DecorationCache::key(&q.conn, &item, q.updated_at.as_deref());
    if let Some(hit) = s.decorations.get(&key) {
        return Json(hit).into_response();
    }
    match dto::pr_decoration(&s.deps.sections, &q.conn, &item).await {
        Some(decoration) => {
            s.decorations.put(key, decoration.clone());
            Json(decoration).into_response()
        }
        None => (StatusCode::NOT_FOUND, "pull request not found").into_response(),
    }
}

async fn pr_vote(State(s): State<AppState>, Json(req): Json<actions::PrVoteReq>) -> Response {
    action_response("dashboard.pr_vote", actions::pr_vote(&s.deps.sections, req).await)
}
async fn pr_merge(State(s): State<AppState>, Json(req): Json<actions::PrMergeReq>) -> Response {
    action_response("dashboard.pr_merge", actions::pr_merge(&s.deps.sections, req).await)
}
async fn pr_revert(State(s): State<AppState>, Json(req): Json<actions::PrRevertReq>) -> Response {
    action_response("dashboard.pr_revert", actions::pr_revert(&s.deps.sections, req).await)
}
async fn pr_comment(State(s): State<AppState>, Json(req): Json<actions::PrCommentReq>) -> Response {
    action_response("dashboard.pr_comment", actions::pr_comment(&s.deps.sections, req).await)
}
async fn pr_reply(State(s): State<AppState>, Json(req): Json<actions::PrReplyReq>) -> Response {
    action_response("dashboard.pr_reply", actions::pr_reply(&s.deps.sections, req).await)
}
async fn pr_review(State(s): State<AppState>, Json(req): Json<actions::PrReviewReq>) -> Response {
    action_response("dashboard.pr_review", actions::pr_review(&s.deps.sections, req).await)
}

async fn wi_detail(State(s): State<AppState>, Query(q): Query<ItemQuery>) -> Response {
    let (conn, item) = q.item();
    match dto::wi_detail(&s.deps.sections, &conn, &item).await {
        Some(detail) => Json(detail).into_response(),
        None => (StatusCode::NOT_FOUND, "work item not found").into_response(),
    }
}
async fn wi_states(State(s): State<AppState>, Query(q): Query<ItemQuery>) -> Response {
    let (conn, item) = q.item();
    match actions::wi_states(&s.deps.sections, &conn, &item).await {
        Some(states) => Json(states).into_response(),
        None => (StatusCode::NOT_FOUND, "work item connection not found").into_response(),
    }
}
async fn wi_state(State(s): State<AppState>, Json(req): Json<actions::WiStateReq>) -> Response {
    action_response("dashboard.wi_state", actions::wi_set_state(&s.deps.sections, req).await)
}
async fn wi_comment(State(s): State<AppState>, Json(req): Json<actions::WiCommentReq>) -> Response {
    action_response("dashboard.wi_comment", actions::wi_comment(&s.deps.sections, req).await)
}
async fn wi_assignees(State(s): State<AppState>, Query(q): Query<ItemQuery>) -> Response {
    let (conn, item) = q.item();
    match actions::wi_assignees(&s.deps.sections, &conn, &item).await {
        Some(users) => Json(users).into_response(),
        None => (StatusCode::NOT_FOUND, "work item connection not found").into_response(),
    }
}
async fn wi_assignee(State(s): State<AppState>, Json(req): Json<actions::WiAssigneeReq>) -> Response {
    action_response("dashboard.wi_assignee", actions::wi_set_assignee(&s.deps.sections, req).await)
}
async fn wi_update(State(s): State<AppState>, Json(req): Json<actions::WiUpdateReq>) -> Response {
    action_response("dashboard.wi_update", actions::wi_update(&s.deps.sections, req).await)
}

async fn pipeline_detail(State(s): State<AppState>, Query(q): Query<RunQuery>) -> Response {
    match dto::pipeline_detail(&s.deps.sections, &q.conn, &ItemRef::maybe(q.repo, q.run_id)).await {
        Some(detail) => Json(detail).into_response(),
        None => (StatusCode::NOT_FOUND, "pipeline run not found").into_response(),
    }
}
async fn pipeline_logs(State(s): State<AppState>, Query(q): Query<PipelineLogsQuery>) -> Response {
    match dto::pipeline_logs(&s.deps.sections, &q.conn, &ItemRef::maybe(q.repo, q.run_id), q.job.as_deref()).await {
        Some(text) => ([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text).into_response(),
        None => (StatusCode::NOT_FOUND, "logs not available").into_response(),
    }
}

async fn pipeline_approval(State(s): State<AppState>, Json(req): Json<actions::PipelineApprovalReq>) -> Response {
    action_response("dashboard.pipeline_approval", actions::pipeline_approval(&s.deps.sections, req).await)
}
async fn pipeline_trigger(State(s): State<AppState>, Json(req): Json<actions::PipelineTriggerReq>) -> Response {
    action_response("dashboard.pipeline_trigger", actions::pipeline_trigger(&s.deps.sections, req).await)
}
async fn pipeline_cancel(State(s): State<AppState>, Json(req): Json<actions::PipelineCancelReq>) -> Response {
    action_response("dashboard.pipeline_cancel", actions::pipeline_cancel(&s.deps.sections, req).await)
}

async fn notification_read(State(s): State<AppState>, Json(req): Json<actions::NotifReadReq>) -> Response {
    action_response("dashboard.notification_read", actions::notif_read(&s.deps.sections, req).await)
}

// ---- connection management ----

#[derive(Deserialize)]
struct IdReq {
    id: String,
}

async fn providers() -> Json<Vec<connections::ProviderInfo>> {
    Json(connections::providers())
}
async fn list_connections(State(s): State<AppState>) -> Json<Vec<connections::ConnectionRow>> {
    Json(connections::list(&s.deps.config, s.deps.secrets.as_ref()))
}
async fn save_connection(State(s): State<AppState>, Json(req): Json<connections::SaveConnectionReq>) -> Response {
    match connections::save(&s.deps.config, &s.deps.sections, req).await {
        Ok(id) => Json(serde_json::json!({ "ok": true, "id": id })).into_response(),
        Err(msg) => (StatusCode::BAD_GATEWAY, msg).into_response(),
    }
}
async fn delete_connection(State(s): State<AppState>, Json(req): Json<IdReq>) -> Response {
    match connections::remove(&s.deps.config, &req.id).await {
        Ok(()) => Json(serde_json::json!({ "ok": true })).into_response(),
        Err(msg) => (StatusCode::BAD_GATEWAY, msg).into_response(),
    }
}
async fn test_connection(State(s): State<AppState>, Json(req): Json<IdReq>) -> Response {
    match connections::test(&s.deps.health, &req.id).await {
        Some(healthy) => Json(serde_json::json!({ "healthy": healthy })).into_response(),
        None => (StatusCode::NOT_FOUND, "connection not found").into_response(),
    }
}

/// The repositories a connection could fetch from — the scope picker's candidate list. Only
/// this endpoint calls provider discovery, so discovery being wrong shows an empty picker; it
/// cannot stop an already-scoped connection fetching.
async fn connection_repositories(State(s): State<AppState>, Query(q): Query<IdQuery>) -> Response {
    match s.deps.sections.discover_repositories(&q.id).await {
        Ok(page) => Json(page).into_response(),
        Err(e) => (StatusCode::BAD_GATEWAY, e.to_string()).into_response(),
    }
}

#[derive(Deserialize)]
struct IdQuery {
    id: String,
}

#[derive(Deserialize)]
struct ScopeReq {
    id: String,
    /// The chosen repositories. An empty list is a real choice — fetch nothing — and is stored
    /// as such; it is not the same as never having chosen.
    scope: Vec<String>,
}

async fn set_connection_scope(State(s): State<AppState>, Json(req): Json<ScopeReq>) -> Response {
    match s.deps.config.set_repo_scope(&req.id, Some(req.scope)).await {
        Ok(()) => Json(serde_json::json!({ "ok": true })).into_response(),
        Err(e) => (StatusCode::BAD_GATEWAY, e.to_string()).into_response(),
    }
}