OXYGENHUB
# c30444e35f2e oxygenhub / crates / hub / src / web / proposals.rs
80.0 KiB · Rust · last changed Drafts stream into the editor as the assistant writes them 19 days ago source blame history raw
de505df5 Andy McCall ↶ 1
//! Proposal pages (hub spec §7): list, new, detail with conversation,
2
//! changes and files, comments anchored to atoms, reviews, landing.
3
4
use super::history::{render_files, FileRows};
5
use super::settings::{csrf, require};
6
use super::{filters, lookup, lookup_role, Error, Page, RepoShell, Shell};
7
use crate::auth::{Access, Role, Viewer};
8
use crate::db::{self, accounts, proposals as pdb};
9
use crate::render::{self, diff};
10
use crate::repos::proposals::{self as pl, Projection, Source};
11
use crate::repos::view::{self, ChangeView, ConflictView};
12
use crate::repos::RepoName;
13
use crate::Shared;
14
use askama::Template;
15
use axum::extract::{Form, Path, Query, State};
16
use axum::response::{IntoResponse, Redirect, Response};
17
use hub_api::{Approval, ProposalSource, ProposalState};
18
use oxy_core::hash::ChangeHash;
19
use serde::Deserialize;
20
use std::collections::{BTreeMap, HashMap};
21
22
// ------------------------------------------------------------------ list
23
24
#[derive(Template)]
25
#[template(path = "proposals.html")]
26
pub struct ProposalsPage {
27
    shell: Shell,
28
    repo: RepoShell,
29
    rows: Vec<pdb::ProposalRow>,
30
    filter: String,
31
    counts: (usize, usize, usize),
32
    bookmarks: Vec<String>,
1ac84c62 Andy McCall ↶ 33
    q: String,
34
    sort: String,
35
    pager: super::Pager,
36
    labels: std::collections::HashMap<i64, Vec<db::issues::Label>>,
de505df5 Andy McCall ↶ 37
}
38
1ac84c62 Andy McCall ↶ 39
impl ProposalsPage {
40
    fn labels_of(&self, id: &i64) -> &[db::issues::Label] {
41
        self.labels.get(id).map(Vec::as_slice).unwrap_or(&[])
42
    }
43
}
44
de505df5 Andy McCall ↶ 45
#[derive(Deserialize)]
46
pub struct ListQuery {
47
    state: Option<String>,
1ac84c62 Andy McCall ↶ 48
    q: Option<String>,
49
    sort: Option<String>,
50
    page: Option<usize>,
de505df5 Andy McCall ↶ 51
}
52
1ac84c62 Andy McCall ↶ 53
/// The list's sort orders.
54
pub const SORTS: &[(&str, &str)] = &[("updated", "recently updated"), ("newest", "newest"), ("oldest", "oldest")];
55
de505df5 Andy McCall ↶ 56
pub async fn list(
57
    State(app): State<Shared>,
58
    viewer: Viewer,
59
    Path((owner, name)): Path<(String, String)>,
60
    Query(q): Query<ListQuery>,
61
) -> Result<Page<ProposalsPage>, Error> {
62
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposals"), &viewer);
63
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
64
    let all = pdb::list(&app.db, row.id, &[]).await.map_err(|e| Error::from_db(shell.clone(), e))?;
65
    let counts = (
66
        all.iter().filter(|p| p.is_open()).count(),
67
        all.iter().filter(|p| p.state == "landed").count(),
68
        all.iter().filter(|p| p.state == "closed").count(),
69
    );
70
    let filter = q.state.unwrap_or_else(|| "open".into());
1ac84c62 Andy McCall ↶ 71
    let mut labels: std::collections::HashMap<i64, Vec<db::issues::Label>> = std::collections::HashMap::new();
72
    for (id, l) in db::issues::labels_by_proposal(&app.db, row.id).await.map_err(|e| Error::from_db(shell.clone(), e))? {
73
        labels.entry(id).or_default().push(l);
74
    }
75
    // `author:bob label:ui target:main words…`
76
    let qtext = q.q.clone().unwrap_or_default();
77
    let (mut authors, mut wanted, mut targets, mut words) = (vec![], vec![], vec![], vec![]);
78
    for tok in qtext.split_whitespace() {
79
        match tok.split_once(':') {
80
            Some(("author", v)) => authors.push(v.to_lowercase()),
81
            Some(("label", v)) => wanted.push(v.to_lowercase()),
82
            Some(("target", v)) => targets.push(v.to_string()),
83
            _ => words.push(tok.to_lowercase()),
84
        }
85
    }
86
    let mut rows: Vec<pdb::ProposalRow> = all
de505df5 Andy McCall ↶ 87
        .into_iter()
88
        .filter(|p| match filter.as_str() {
89
            "open" => p.is_open(),
90
            "landed" => p.state == "landed",
91
            "closed" => p.state == "closed",
92
            _ => true,
93
        })
1ac84c62 Andy McCall ↶ 94
        .filter(|p| authors.is_empty() || authors.contains(&p.author.to_lowercase()))
95
        .filter(|p| targets.is_empty() || targets.contains(&p.target))
96
        .filter(|p| wanted.iter().all(|w| labels.get(&p.id).is_some_and(|ls| ls.iter().any(|l| l.name.to_lowercase() == *w))))
97
        .filter(|p| words.iter().all(|w| p.title.to_lowercase().contains(w) || p.body.to_lowercase().contains(w)))
de505df5 Andy McCall ↶ 98
        .collect();
1ac84c62 Andy McCall ↶ 99
    let sort = q.sort.filter(|s| SORTS.iter().any(|(k, _)| k == s)).unwrap_or_else(|| "updated".into());
100
    match sort.as_str() {
101
        "newest" => rows.sort_by_key(|p| std::cmp::Reverse(p.number)),
102
        "oldest" => rows.sort_by_key(|p| p.number),
103
        _ => rows.sort_by_key(|p| std::cmp::Reverse(p.updated_ms)),
104
    }
105
    let pager = super::Pager::new(rows.len(), q.page, &[("state", &filter), ("q", &qtext), ("sort", &sort)]);
106
    let rows = pager.slice(rows);
de505df5 Andy McCall ↶ 107
    let bookmarks = app
108
        .repos
109
        .read(&repo, |r, _| Ok(r.bookmarks()?.into_iter().map(|b| b.name).collect::<Vec<_>>()))
110
        .await
111
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
1ac84c62 Andy McCall ↶ 112
    Ok(Page(ProposalsPage {
113
        shell,
114
        repo: RepoShell::new(&app, &row, "proposals").with_role(role),
115
        rows,
116
        filter,
117
        counts,
118
        bookmarks,
119
        q: qtext,
120
        sort,
121
        pager,
122
        labels,
123
    }))
de505df5 Andy McCall ↶ 124
}
125
126
// ------------------------------------------------------------------- new
127
128
#[derive(Template)]
129
#[template(path = "proposal_new.html")]
130
pub struct NewProposalPage {
131
    shell: Shell,
132
    repo: RepoShell,
133
    bookmarks: Vec<String>,
134
    source: String,
135
    target: String,
136
    error: Option<String>,
137
    /// Preview: the changes the proposal would add.
138
    preview: Vec<ChangeView>,
139
    conflicted: bool,
7d2eb590 Andy McCall ↶ 140
    /// What the form holds so far (after a failed open, or a draft).
141
    title: String,
142
    body: String,
143
    /// AI assistants that may draft the description (hub spec §13.4).
144
    assistants: Vec<String>,
de505df5 Andy McCall ↶ 145
}
146
147
#[derive(Deserialize)]
148
pub struct NewQuery {
149
    source: Option<String>,
150
    target: Option<String>,
151
}
152
153
/// `owner/name:bookmark` for a fork, else a bookmark of this repository.
0b20f1ec Andy McCall ↶ 154
/// A proposal's source: a bookmark of this repository by name (which may
155
/// hold `/`, as `feature/16-hud` does), or `owner/name:bookmark` of a fork;
156
/// `owner/name:bookmark` naming this repository is its own bookmark.
de505df5 Andy McCall ↶ 157
fn parse_source(app: &Shared, repo: &RepoName, source: &str) -> Option<(Option<RepoName>, String)> {
0b20f1ec Andy McCall ↶ 158
    let plain = |b: &str| !b.is_empty() && !b.chars().any(|c| c.is_control() || c == ':');
de505df5 Andy McCall ↶ 159
    if let Some((slug, bookmark)) = source.split_once(':') {
160
        let fork = RepoName::parse(slug)?;
0b20f1ec Andy McCall ↶ 161
        if !plain(bookmark) {
de505df5 Andy McCall ↶ 162
            return None;
0b20f1ec Andy McCall ↶ 163
        }
164
        if fork == *repo {
165
            return Some((None, bookmark.to_string()));
de505df5 Andy McCall ↶ 166
        }
0b20f1ec Andy McCall ↶ 167
        if !app.repos.exists(&fork) {
168
            return None;
169
        }
de505df5 Andy McCall ↶ 170
        return Some((Some(fork), bookmark.to_string()));
171
    }
0b20f1ec Andy McCall ↶ 172
    plain(source).then(|| (None, source.to_string()))
de505df5 Andy McCall ↶ 173
}
174
175
async fn preview_for(
176
    app: &Shared,
177
    repo: &RepoName,
178
    target: &str,
179
    source: &str,
180
) -> Result<(Vec<ChangeView>, bool), crate::repos::RepoError> {
181
    let Some((fork, bookmark)) = parse_source(app, repo, source) else { return Ok((vec![], false)) };
182
    let target = target.to_string();
183
    let fork_dir = fork.as_ref().map(|f| app.repos.dir(f));
184
    app.repos
185
        .read(repo, move |r, cache| {
186
            let projection = match &fork_dir {
187
                Some(dir) => {
188
                    let fork_repo = oxy_core::repo::Repo::open(dir)?;
189
                    let heads = fork_repo.bookmarks()?.into_iter().find(|b| b.name == bookmark).map(|b| b.heads).unwrap_or_default();
190
                    pl::project(r, cache, &target, Source::Fork { fork: &fork_repo, heads })?
191
                }
192
                None => {
193
                    let heads = r.bookmarks()?.into_iter().find(|b| b.name == bookmark).map(|b| b.heads).unwrap_or_default();
194
                    pl::project(r, cache, &target, Source::Bookmark(heads))?
195
                }
196
            };
197
            Ok((projection.changes, projection.conflicted))
198
        })
199
        .await
200
}
201
202
pub async fn new_form(
203
    State(app): State<Shared>,
204
    viewer: Viewer,
205
    Path((owner, name)): Path<(String, String)>,
206
    Query(q): Query<NewQuery>,
207
) -> Result<Page<NewProposalPage>, Error> {
208
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposals/new"), &viewer);
209
    require(&viewer, &shell)?;
210
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
211
    let bookmarks = app
212
        .repos
213
        .read(&repo, |r, _| Ok(r.bookmarks()?.into_iter().map(|b| b.name).collect::<Vec<_>>()))
214
        .await
215
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
216
    let target = q.target.unwrap_or_else(|| row.default_bookmark.clone());
217
    let source = q.source.unwrap_or_default();
218
    let (preview, conflicted) =
219
        if source.is_empty() { (vec![], false) } else { preview_for(&app, &repo, &target, &source).await.unwrap_or((vec![], false)) };
7d2eb590 Andy McCall ↶ 220
    let assistants = if preview.is_empty() { vec![] } else { assistant_names(&app, &row).await };
de505df5 Andy McCall ↶ 221
    Ok(Page(NewProposalPage {
222
        shell,
223
        repo: RepoShell::new(&app, &row, "proposals").with_role(role),
224
        bookmarks,
225
        source,
226
        target,
227
        error: None,
228
        preview,
229
        conflicted,
7d2eb590 Andy McCall ↶ 230
        title: String::new(),
231
        body: String::new(),
232
        assistants,
de505df5 Andy McCall ↶ 233
    }))
234
}
235
236
#[derive(Deserialize)]
237
pub struct NewForm {
238
    #[serde(rename = "_csrf")]
239
    csrf_token: String,
240
    title: String,
241
    #[serde(default)]
242
    body: String,
243
    target: String,
244
    source: String,
245
    #[serde(default)]
246
    draft: Option<String>,
7d2eb590 Andy McCall ↶ 247
    /// For `/proposals/new/draft`: which assistant writes the description.
248
    #[serde(default)]
249
    assistant: String,
de505df5 Andy McCall ↶ 250
}
251
b64e2537 Andy McCall ↶ 252
/// Open a proposal from a form or the API: validate, create, index, notify.
253
#[allow(clippy::too_many_arguments)]
254
pub async fn open_proposal(
255
    app: &Shared,
256
    repo: &RepoName,
257
    row: &db::repos::RepoRow,
258
    me: &accounts::Account,
259
    title: &str,
260
    body: &str,
261
    target: &str,
262
    source: &str,
263
    draft: bool,
264
) -> Result<pdb::ProposalRow, String> {
265
    if title.trim().is_empty() {
266
        return Err("Give the proposal a title.".into());
de505df5 Andy McCall ↶ 267
    }
b64e2537 Andy McCall ↶ 268
    let bookmarks =
269
        app.repos.read(repo, |r, _| Ok(r.bookmarks()?.into_iter().map(|b| b.name).collect::<Vec<_>>())).await.map_err(|e| e.to_string())?;
270
    if !bookmarks.iter().any(|b| b == target) {
271
        return Err("Pick a target bookmark of this repository.".into());
de505df5 Andy McCall ↶ 272
    }
b64e2537 Andy McCall ↶ 273
    let Some((fork, bookmark)) = parse_source(app, repo, source.trim()) else {
274
        return Err("The source is a bookmark of this repository, or owner/name:bookmark of a fork.".into());
de505df5 Andy McCall ↶ 275
    };
0b20f1ec Andy McCall ↶ 276
    if fork.is_none() && !bookmarks.contains(&bookmark) {
277
        return Err(format!("There is no bookmark {bookmark} in this repository."));
278
    }
b64e2537 Andy McCall ↶ 279
    if fork.is_none() && bookmark == target {
280
        return Err("The source and the target are the same bookmark.".into());
de505df5 Andy McCall ↶ 281
    }
b64e2537 Andy McCall ↶ 282
    let (preview, _) = preview_for(app, repo, target, source.trim()).await.map_err(|e| e.to_string())?;
de505df5 Andy McCall ↶ 283
    if preview.is_empty() {
b64e2537 Andy McCall ↶ 284
        return Err("The source adds nothing to the target.".into());
de505df5 Andy McCall ↶ 285
    }
286
    let source_repo_id = match &fork {
b64e2537 Andy McCall ↶ 287
        Some(fk) => db::repos::get(&app.db, &fk.owner, &fk.name).await.map_err(|e| e.to_string())?.map(|r| r.id),
de505df5 Andy McCall ↶ 288
        None => None,
289
    };
290
    let created = pdb::create(
291
        &app.db,
292
        pdb::NewProposal {
293
            repo_id: row.id,
b64e2537 Andy McCall ↶ 294
            title: title.trim(),
295
            body: body.trim(),
296
            author_id: Some(me.id),
297
            author: &me.username,
298
            draft,
299
            target,
de505df5 Andy McCall ↶ 300
            source_kind: if fork.is_some() { "fork" } else { "bookmark" },
301
            source_repo_id,
302
            source_bookmark: &bookmark,
303
            source_changes: "",
304
        },
305
    )
306
    .await
b64e2537 Andy McCall ↶ 307
    .map_err(|e| e.to_string())?;
308
    pdb::add_event(&app.db, created.id, &me.username, "opened", "").await.ok();
309
    accounts::audit(&app.db, Some(me), "proposal.opened", &format!("{}#{}", row.slug(), created.number), title).await.ok();
18e381ea Andy McCall ↶ 310
    db::notify::index(&app.db, "proposal", row.id, created.id, created.number, &created.title, &created.body).await.ok();
b64e2537 Andy McCall ↶ 311
    let url = format!("/{}/proposal/{}", row.slug(), created.number);
18e381ea Andy McCall ↶ 312
    crate::notify::deliver(
b64e2537 Andy McCall ↶ 313
        app,
18e381ea Andy McCall ↶ 314
        crate::notify::Event {
315
            kind: "proposal.opened",
b64e2537 Andy McCall ↶ 316
            title: format!("{}#{}: {}", row.slug(), created.number, created.title),
317
            url,
318
            actor: me,
18e381ea Andy McCall ↶ 319
            repo_id: row.id,
320
            thread: Some(("proposal", created.id)),
b64e2537 Andy McCall ↶ 321
            mention_text: body,
18e381ea Andy McCall ↶ 322
            direct: vec![],
323
        },
324
    )
325
    .await;
b64e2537 Andy McCall ↶ 326
    crate::hooks::emit(
327
        app,
328
        row,
329
        "proposal.opened",
330
        &me.username,
331
        serde_json::json!({ "number": created.number, "title": created.title, "target": target, "source": source }),
332
    )
333
    .await;
334
    Ok(created)
335
}
336
337
pub async fn create(
338
    State(app): State<Shared>,
339
    viewer: Viewer,
340
    Path((owner, name)): Path<(String, String)>,
341
    Form(f): Form<NewForm>,
342
) -> Result<Response, Error> {
343
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposals/new"), &viewer);
344
    let me = require(&viewer, &shell)?;
345
    csrf(&viewer, &f.csrf_token, &shell)?;
346
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d0fbea2e Andy McCall ↶ 347
    super::writable(&row, &shell)?;
b64e2537 Andy McCall ↶ 348
    match open_proposal(&app, &repo, &row, &me.account, &f.title, &f.body, &f.target, &f.source, f.draft.is_some()).await {
349
        Ok(created) => Ok(Redirect::to(&format!("/{owner}/{name}/proposal/{}", created.number)).into_response()),
350
        Err(msg) => {
351
            let bookmarks =
352
                app.repos.read(&repo, |r, _| Ok(r.bookmarks()?.into_iter().map(|b| b.name).collect::<Vec<_>>())).await.unwrap_or_default();
353
            Ok(Page(NewProposalPage {
354
                shell,
355
                repo: RepoShell::new(&app, &row, "proposals").with_role(role),
356
                bookmarks,
357
                source: f.source.clone(),
358
                target: f.target.clone(),
359
                error: Some(msg),
360
                preview: vec![],
361
                conflicted: false,
7d2eb590 Andy McCall ↶ 362
                title: f.title.clone(),
363
                body: f.body.clone(),
364
                assistants: vec![],
b64e2537 Andy McCall ↶ 365
            })
366
            .into_response())
367
        }
368
    }
de505df5 Andy McCall ↶ 369
}
370
371
// ---------------------------------------------------------------- detail
372
373
/// A comment placed on a diff row, or general.
374
pub struct CommentView {
375
    pub row: pdb::CommentRow,
376
    pub body_html: String,
377
    pub line: Option<usize>,
378
}
379
a1b98695 Andy McCall ↶ 380
/// One entry of a proposal's conversation, in time order: what kind it
381
/// is and its index in `comments`, `reviews` or `events`.
382
pub struct Entry {
383
    pub kind: &'static str,
384
    pub index: usize,
385
}
386
de505df5 Andy McCall ↶ 387
pub struct ReviewView {
388
    pub row: pdb::ReviewRow,
389
    pub body_html: String,
390
    pub sealed: bool,
391
}
392
393
/// Everything the detail page and the API need, computed once under the lock.
394
pub struct Loaded {
395
    pub row: pdb::ProposalRow,
396
    pub changes: Vec<ChangeView>,
397
    pub hashes: Vec<ChangeHash>,
398
    pub heads: Vec<ChangeHash>,
3f02e5ea Andy McCall ↶ 399
    pub target_heads: Vec<ChangeHash>,
de505df5 Andy McCall ↶ 400
    pub state: String,
401
    pub target_state: String,
402
    pub conflicted: bool,
403
    pub conflicts: Vec<ConflictView>,
404
    pub files: Vec<FileRows>,
9df855f2 Andy McCall ↶ 405
    /// The per-file hunks and bases behind `files`, to render again with other options.
406
    pub diffs: Vec<oxy_core::repo::FileDiff>,
407
    pub bases: std::collections::BTreeMap<String, Vec<u8>>,
de505df5 Andy McCall ↶ 408
    /// Atom per (path, new line number) of the projected state.
409
    pub atoms: HashMap<(String, usize), (String, u32)>,
410
    pub sealing_keys: Vec<String>,
411
    pub touched: Vec<String>,
412
    pub owners: Vec<String>,
413
    pub landed_already: bool,
ac713df7 Andy McCall ↶ 414
    /// Whether its source has any changes at all (#141): an open proposal
415
    /// whose source has changes, none of them missing from the target, was
416
    /// landed by some other route.
417
    pub source_has_changes: bool,
de505df5 Andy McCall ↶ 418
}
419
420
/// Compute the projection and everything derived from it.
421
pub async fn load(app: &Shared, repo: &RepoName, row: pdb::ProposalRow) -> Result<Loaded, crate::repos::RepoError> {
422
    let fork_dir = match (row.source_kind.as_str(), row.source_repo_id) {
423
        ("fork", Some(id)) => {
424
            db::repos::get_by_id(&app.db, id).await.ok().flatten().and_then(|r| RepoName::new(&r.owner, &r.name)).map(|n| app.repos.dir(&n))
425
        }
426
        _ => None,
427
    };
428
    let r2 = row.clone();
429
    let loaded = app
430
        .repos
431
        .read(repo, move |r, cache| {
432
            let source = match (r2.source_kind.as_str(), &fork_dir) {
433
                ("changes", _) => Source::Changes(r2.source_changes().iter().filter_map(|h| ChangeHash::from_hex(h)).collect()),
434
                ("fork", Some(dir)) => {
435
                    let fork_repo = oxy_core::repo::Repo::open(dir)?;
436
                    let heads =
437
                        fork_repo.bookmarks()?.into_iter().find(|b| b.name == r2.source_bookmark).map(|b| b.heads).unwrap_or_default();
438
                    // Bring the fork's changes over now, so the projection below can read them.
439
                    let fork_state = fork_repo.load_state(&heads)?;
440
                    let missing: Vec<ChangeHash> = fork_state.changes().map(|(h, _)| *h).filter(|h| !r.store().has(h)).collect();
441
                    if !missing.is_empty() {
442
                        r.import_bundle(&fork_repo.bundle_for(&missing)?, r.current_policy()?.is_some())?;
443
                    }
444
                    Source::Changes(heads)
445
                }
446
                _ => {
447
                    let heads = r.bookmarks()?.into_iter().find(|b| b.name == r2.source_bookmark).map(|b| b.heads).unwrap_or_default();
448
                    Source::Bookmark(heads)
449
                }
450
            };
ac713df7 Andy McCall ↶ 451
            let source_has_changes = match &source {
452
                Source::Changes(h) | Source::Bookmark(h) | Source::Fork { heads: h, .. } => !h.is_empty(),
453
            };
de505df5 Andy McCall ↶ 454
            let p: Projection = pl::project(r, cache, &r2.target, source)?;
455
            let target_loaded = cache.load(r, &p.target_heads)?;
456
            let files = render_files(&p.files, &p.bases);
457
            let mut atoms = HashMap::new();
458
            for f in &files {
459
                for l in &f.lines {
460
                    if let Some(n) = l.new_no {
461
                        if let Some((h, i)) = pl::atom_at(&p.loaded, &f.path, n as usize) {
462
                            atoms.insert((f.path.clone(), n as usize), (h.to_hex(), i));
463
                        }
464
                    }
465
                }
466
            }
467
            let touched: Vec<String> = p.files.iter().map(|f| f.path.clone()).collect();
468
            let owners = pl::owners_for(&target_loaded, &touched);
469
            let sealing = pl::sealing_keys(r, &p.hashes)?.into_iter().map(|k| k.to_hex()).collect();
470
            let landed_already = !p.hashes.is_empty() && p.hashes.iter().all(|h| target_loaded.state.contains(h));
0b20f1ec Andy McCall ↶ 471
            // A landed proposal's changes are in its target now: it shows
472
            // the ones it landed, as recorded when it landed.
473
            let (changes, hashes) = if r2.state == "landed" && p.hashes.is_empty() {
474
                let hashes: Vec<ChangeHash> = r2.projected_changes().iter().filter_map(|h| ChangeHash::from_hex(h)).collect();
475
                let labels = HashMap::new();
476
                let changes = hashes
477
                    .iter()
478
                    .filter_map(|h| Some(view::change_view_pub(r, h, &r.store().get_change_meta(h).ok()?, false, &labels)))
479
                    .collect();
480
                (changes, hashes)
481
            } else {
482
                (p.changes, p.hashes)
483
            };
de505df5 Andy McCall ↶ 484
            Ok(Loaded {
485
                row: r2,
0b20f1ec Andy McCall ↶ 486
                changes,
487
                hashes,
de505df5 Andy McCall ↶ 488
                heads: p.heads,
3f02e5ea Andy McCall ↶ 489
                target_heads: p.target_heads.clone(),
de505df5 Andy McCall ↶ 490
                state: p.state.to_hex(),
491
                target_state: p.target_state.to_hex(),
492
                conflicted: p.conflicted,
493
                conflicts: p.conflicts,
494
                files,
9df855f2 Andy McCall ↶ 495
                diffs: p.files.clone(),
496
                bases: p.bases.clone(),
de505df5 Andy McCall ↶ 497
                atoms,
498
                sealing_keys: sealing,
499
                touched,
500
                owners,
501
                landed_already,
ac713df7 Andy McCall ↶ 502
                source_has_changes,
de505df5 Andy McCall ↶ 503
            })
504
        })
505
        .await?;
ac713df7 Andy McCall ↶ 506
    // Landed by another route (#141): `oxy proposal land` from a client (a
507
    // repository with a trust policy needs it), or the work merged and
508
    // pushed by hand. Everything it proposes is in its target, so it is
509
    // landed, not open with nothing to land.
510
    let mut loaded = loaded;
511
    if loaded.row.is_open()
512
        && loaded.source_has_changes
513
        && loaded.hashes.is_empty()
514
        && pdb::set_landed(&app.db, loaded.row.id, &loaded.target_state, "", "push").await.is_ok()
515
    {
516
        loaded.row.state = "landed".into();
517
        loaded.row.landed_via = "push".into();
518
        loaded.row.landed_state = loaded.target_state.clone();
519
        return Ok(loaded);
520
    }
0b20f1ec Andy McCall ↶ 521
    // Remember the projection for the list, the API and other proposals'
522
    // stacking checks, while the proposal is open: a landed one keeps what
523
    // it landed.
524
    if !loaded.row.is_open() {
525
        return Ok(loaded);
526
    }
de505df5 Andy McCall ↶ 527
    let heads_csv = loaded.heads.iter().map(|h| h.to_hex()).collect::<Vec<_>>().join(",");
528
    let changes_csv = loaded.hashes.iter().map(|h| h.to_hex()).collect::<Vec<_>>().join(",");
529
    pdb::set_projection(&app.db, loaded.row.id, &loaded.state, &heads_csv, &loaded.target_state, &changes_csv, loaded.conflicted)
530
        .await
531
        .ok();
532
    Ok(loaded)
ac713df7 Andy McCall ↶ 533
}
534
535
/// After a push moved `bookmark`: open proposals into it whose work it now
536
/// holds are marked landed, by the pusher (#141).
537
pub async fn settle_after_push(app: &Shared, row: &db::repos::RepoRow, bookmark: &str, actor: &str) {
538
    let Some(repo) = RepoName::new(&row.owner, &row.name) else { return };
539
    let Ok(open) = pdb::list(&app.db, row.id, &["open", "draft"]).await else { return };
540
    for p in open.into_iter().filter(|p| p.target == bookmark) {
541
        let id = p.id;
d943160d Andy McCall ↶ 542
        let number = p.number;
ac713df7 Andy McCall ↶ 543
        if let Ok(l) = load(app, &repo, p).await {
544
            if l.row.state == "landed" && l.row.landed_by.is_empty() {
545
                pdb::set_landed(&app.db, id, &l.target_state, actor, "push").await.ok();
d943160d Andy McCall ↶ 546
            } else if l.row.is_open() && !l.hashes.is_empty() && crate::flow::enabled(app, row) {
547
                // The target moved, so the proposal's projected state is
548
                // new and its checks would be for an older one (#134): run
549
                // the pipeline on it, once.
5d90e0e0 Andy McCall 550
                let ran: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM flow_runs WHERE repo_id = $1 AND state = $2")
d943160d Andy McCall ↶ 551
                    .bind(row.id)
552
                    .bind(&l.state)
553
                    .fetch_one(&app.db)
554
                    .await
555
                    .unwrap_or(1);
556
                if ran == 0 {
557
                    let label = format!("proposal/{number}");
558
                    match crate::flow::start_run_scoped(app, row, &label, &l.state, &l.heads, actor, "proposal", None).await {
559
                        Ok(Some(n)) => tracing::info!("proposal {number}: its target moved; run #{n} checks its new projected state"),
560
                        Ok(None) => {}
561
                        Err(e) => tracing::warn!("proposal {number}: a run of its new projected state did not start: {e}"),
562
                    }
563
                }
ac713df7 Andy McCall ↶ 564
            }
565
        }
566
    }
de505df5 Andy McCall ↶ 567
}
568
569
/// Reviews, approvals and blockers.
570
pub struct Verdict {
571
    pub reviews: Vec<ReviewView>,
572
    pub approvals: Vec<Approval>,
573
    pub blockers: Vec<String>,
574
    pub depends_on: Vec<i64>,
575
    pub requirements: pdb::Requirements,
576
}
577
578
pub async fn verdict(app: &Shared, loaded: &Loaded, repo_id: i64) -> Result<Verdict, sqlx::Error> {
579
    let rows = pdb::reviews(&app.db, loaded.row.id).await?;
580
    let links = accounts::identity_accounts(&app.db).await?;
581
    let sealed_accounts: Vec<String> = links.iter().filter(|(k, _)| loaded.sealing_keys.contains(k)).map(|(_, u)| u.clone()).collect();
582
    // Latest verdict per reviewer.
583
    let mut latest: BTreeMap<String, &pdb::ReviewRow> = BTreeMap::new();
7d2eb590 Andy McCall ↶ 584
    for r in rows.iter().filter(|r| r.via.is_empty()) {
585
        // An assistant's answer is never the person's own verdict.
de505df5 Andy McCall ↶ 586
        latest.insert(r.author.clone(), r);
587
    }
588
    let mut approvals = Vec::new();
589
    for (who, r) in &latest {
590
        if r.verdict == "approve" {
591
            let sealed = sealed_accounts.contains(who);
592
            let key = links.iter().find(|(k, u)| u == who && loaded.sealing_keys.contains(k)).map(|(k, _)| k.clone());
593
            approvals.push(Approval { account: who.clone(), sealed, key });
594
        }
595
    }
596
    let reviews = rows
597
        .iter()
598
        .map(|r| ReviewView {
599
            row: r.clone(),
600
            body_html: render::markdown::render(&r.body, "/", "/"),
601
            sealed: r.verdict == "approve" && sealed_accounts.contains(&r.author),
602
        })
603
        .collect();
604
    let requirements = pdb::requirements(&app.db, repo_id).await?;
605
    let mut blockers = Vec::new();
0b20f1ec Andy McCall ↶ 606
    // Only an open proposal can be held back.
607
    if !loaded.row.is_open() {
608
        return Ok(Verdict { reviews, approvals, blockers, depends_on: vec![], requirements });
609
    }
de505df5 Andy McCall ↶ 610
    if loaded.row.state == "draft" {
611
        blockers.push("the proposal is a draft".into());
612
    }
613
    if loaded.hashes.is_empty() {
614
        blockers.push("the proposal adds no changes".into());
615
    }
616
    let sealed_count = approvals.iter().filter(|a| a.sealed).count() as i64;
617
    if sealed_count < requirements.required_approvals {
618
        blockers.push(format!("{sealed_count} of {} required sealed approvals", requirements.required_approvals));
619
    }
620
    if requirements.require_owners {
621
        let missing: Vec<&String> = loaded.owners.iter().filter(|o| !approvals.iter().any(|a| a.sealed && &a.account == *o)).collect();
622
        if !missing.is_empty() {
623
            blockers.push(format!("code owners still to approve: {}", missing.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")));
624
        }
625
    }
626
    if loaded.conflicted && !requirements.allow_conflicts {
627
        blockers.push("landing would carry conflicts, which this repository refuses".into());
628
    }
b64e2537 Andy McCall ↶ 629
    let required = db::hooks::required_checks(&app.db, repo_id).await?;
630
    if !required.is_empty() {
631
        let checks = db::hooks::checks_for_state(&app.db, repo_id, &loaded.state).await?;
632
        let missing: Vec<String> =
633
            required.iter().filter(|n| !checks.iter().any(|c| &c.name == *n && c.status == "passed")).cloned().collect();
634
        if !missing.is_empty() {
635
            blockers.push(format!("required checks not passed on the projected state: {}", missing.join(", ")));
636
        }
637
    }
de505df5 Andy McCall ↶ 638
    let requesting: Vec<&String> = latest.iter().filter(|(_, r)| r.verdict == "changes").map(|(who, _)| who).collect();
639
    if !requesting.is_empty() {
640
        blockers.push(format!("changes requested by {}", requesting.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")));
641
    }
642
    // Stacking: another open, earlier proposal whose changes this one includes.
643
    let mut depends_on = Vec::new();
644
    for other in pdb::list(&app.db, repo_id, &["open", "draft"]).await? {
645
        if other.id == loaded.row.id || other.number > loaded.row.number {
646
            continue;
647
        }
648
        let theirs = other.projected_changes();
649
        if !theirs.is_empty() && theirs.iter().all(|h| loaded.hashes.iter().any(|m| m.to_hex() == *h)) {
650
            depends_on.push(other.number);
651
        }
652
    }
653
    if !depends_on.is_empty() {
654
        blockers.push(format!("depends on {}", depends_on.iter().map(|n| format!("#{n}")).collect::<Vec<_>>().join(", ")));
655
    }
656
    Ok(Verdict { reviews, approvals, blockers, depends_on, requirements })
657
}
658
659
#[derive(Template)]
660
#[template(path = "proposal.html")]
661
pub struct ProposalPage {
662
    shell: Shell,
663
    repo: RepoShell,
664
    p: pdb::ProposalRow,
b5a0a69b Andy McCall ↶ 665
    /// Live topics (oxygenhub#205): the proposal's and its repository's
666
    /// (checks arrive on the latter).
667
    live_topic: String,
668
    repo_topic: String,
669
    /// Assistants answering now: shown as pending until they do.
670
    pending: Vec<String>,
38833ed7 Andy McCall ↶ 671
    /// Issues it closes, from its description and its changes.
672
    closes: Vec<super::chain::Link>,
a1b98695 Andy McCall ↶ 673
    /// Projects the viewer may add it to.
674
    project_choices: Option<Vec<db::projects::Project>>,
675
    /// Comments (not anchored to a line), reviews and events, oldest first.
676
    timeline: Vec<Entry>,
677
    /// The viewer may set labels (triage or above).
678
    can_triage: bool,
de505df5 Andy McCall ↶ 679
    body_html: String,
680
    tab: String,
681
    changes: Vec<ChangeView>,
682
    files: Vec<FileRows>,
9df855f2 Andy McCall ↶ 683
    diffs: Vec<oxy_core::repo::FileDiff>,
684
    bases: std::collections::BTreeMap<String, Vec<u8>>,
685
    /// Whitespace-only changes are hidden (`?w=1`).
686
    ignore_ws: bool,
de505df5 Andy McCall ↶ 687
    conflicts: Vec<ConflictView>,
688
    conflicted: bool,
689
    comments: Vec<CommentView>,
690
    /// Anchored comments by (path, current line).
691
    placed: HashMap<(String, usize), Vec<usize>>,
692
    outdated: Vec<usize>,
693
    reviews: Vec<ReviewView>,
694
    approvals: Vec<Approval>,
695
    blockers: Vec<String>,
696
    depends_on: Vec<i64>,
697
    events: Vec<pdb::EventRow>,
698
    owners: Vec<String>,
699
    requirements: pdb::Requirements,
700
    landed_already: bool,
701
    can_edit: bool,
4f37afcc Andy McCall ↶ 702
    /// The landed proposal's source bookmark, when it is this repository's,
703
    /// still there, and the viewer may delete it (oxygenhub#86).
704
    deletable_source: Option<String>,
de505df5 Andy McCall ↶ 705
    can_land: bool,
706
    hub_can_land: bool,
707
    notice: Option<String>,
708
    error: Option<String>,
709
    heads: Vec<String>,
710
    state_hash: String,
711
    source_label: String,
712
    api_url: String,
18e381ea Andy McCall ↶ 713
    labels: Vec<db::issues::Label>,
714
    all_labels: Vec<db::issues::Label>,
b64e2537 Andy McCall ↶ 715
    checks: Vec<db::hooks::Check>,
716
    required_checks: Vec<String>,
e1ec9fbf Andy McCall ↶ 717
    /// Projects this proposal is on that the viewer may see, with the column.
718
    projects: Vec<(db::projects::Project, String)>,
cc1cd197 Andy McCall ↶ 719
    /// Asked to review and not yet reviewing.
720
    requested: Vec<String>,
8e96499f Andy McCall ↶ 721
    /// Who can be asked to review, for the sidebar's menu (oxygenhub#84).
722
    reviewable: Vec<String>,
cc1cd197 Andy McCall ↶ 723
    /// The viewer may ask for reviews (the author, or a writer).
724
    can_request: bool,
7d2eb590 Andy McCall ↶ 725
    /// AI assistants the viewer may ask, by name (hub spec §13.4).
726
    assistants: Vec<String>,
727
    /// A description an assistant just drafted, for the editor.
728
    draft: Option<String>,
de505df5 Andy McCall ↶ 729
}
730
731
#[derive(Deserialize)]
732
pub struct DetailQuery {
733
    tab: Option<String>,
a1b98695 Andy McCall ↶ 734
    /// What an action said, after it redirected here.
9df855f2 Andy McCall ↶ 735
    #[serde(default)]
a1b98695 Andy McCall ↶ 736
    notice: Option<String>,
737
    #[serde(default)]
738
    error: Option<String>,
739
    #[serde(default)]
9df855f2 Andy McCall ↶ 740
    w: Option<String>,
b5a0a69b Andy McCall ↶ 741
    /// Only this part of the page (live pages, oxygenhub#205).
742
    #[serde(default)]
743
    fragment: Option<String>,
de505df5 Andy McCall ↶ 744
}
745
746
/// The page assembler every action ends in; its arguments are the route
747
/// plus what to say, and a struct would only rename them.
748
#[allow(clippy::too_many_arguments)]
749
async fn detail(
750
    app: &Shared,
751
    shell: Shell,
752
    viewer: &Viewer,
753
    owner: &str,
754
    name: &str,
755
    number: i64,
756
    tab: String,
757
    notice: Option<String>,
758
    error: Option<String>,
759
) -> Result<Page<ProposalPage>, Error> {
760
    let (repo, row, role) = lookup(app, &shell, viewer, owner, name).await?;
761
    let p = pdb::get(&app.db, row.id, number)
762
        .await
763
        .map_err(|e| Error::from_db(shell.clone(), e))?
764
        .ok_or_else(|| Error::not_found(shell.clone()))?;
b5a0a69b Andy McCall ↶ 765
    let p_id = p.id;
de505df5 Andy McCall ↶ 766
    let loaded = load(app, &repo, p).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
767
    // A proposal whose changes all reached the target landed by another route.
768
    if loaded.landed_already && loaded.row.is_open() {
769
        pdb::set_state(&app.db, loaded.row.id, "landed", &loaded.target_state).await.ok();
770
        pdb::add_event(&app.db, loaded.row.id, "", "landed", "every change reached the target").await.ok();
771
    }
772
    let p = pdb::get(&app.db, row.id, number).await.map_err(|e| Error::from_db(shell.clone(), e))?.unwrap_or(loaded.row.clone());
773
    let v = verdict(app, &loaded, row.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
774
    let comment_rows = pdb::comments(&app.db, loaded.row.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
775
    let events = pdb::events(&app.db, loaded.row.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
776
    // Place anchored comments at their atom's current line.
777
    let mut by_atom: HashMap<(String, String, u32), usize> = HashMap::new();
778
    for ((path, line), (h, i)) in &loaded.atoms {
779
        by_atom.insert((path.clone(), h.clone(), *i), *line);
780
    }
781
    let mut comments = Vec::new();
782
    let mut placed: HashMap<(String, usize), Vec<usize>> = HashMap::new();
783
    let mut outdated = Vec::new();
784
    for (idx, c) in comment_rows.into_iter().enumerate() {
785
        let line = if c.anchor_change.is_empty() {
786
            None
787
        } else {
788
            by_atom.get(&(c.path.clone(), c.anchor_change.clone(), c.anchor_index as u32)).copied()
789
        };
790
        if !c.anchor_change.is_empty() {
791
            match line {
792
                Some(l) => placed.entry((c.path.clone(), l)).or_default().push(idx),
793
                None => outdated.push(idx),
794
            }
795
        }
796
        comments.push(CommentView { body_html: render::markdown::render(&c.body, "/", "/"), row: c, line });
797
    }
798
    let mut changes = loaded.changes.clone();
799
    super::attribute(app, &mut changes.iter_mut().collect::<Vec<_>>()).await;
800
    let me = viewer.account();
801
    let can_edit = me.is_some_and(|a| Some(a.id) == p.author_id || role >= Role::Maintain);
4f37afcc Andy McCall ↶ 802
    let deletable_source =
803
        if p.state == "landed" && p.source_kind == "bookmark" && role >= Role::Write && p.source_bookmark != row.default_bookmark {
804
            let b = p.source_bookmark.clone();
805
            app.repos
806
                .read(&repo, move |r, _| Ok(r.view()?.bookmarks.contains_key(&b)))
807
                .await
808
                .unwrap_or(false)
809
                .then(|| p.source_bookmark.clone())
810
        } else {
811
            None
812
        };
de505df5 Andy McCall ↶ 813
    let can_land = role >= Role::Write && p.is_open() && v.blockers.is_empty();
cc1cd197 Andy McCall ↶ 814
    let can_request = p.is_open() && me.is_some_and(|a| Some(a.id) == p.author_id || role >= Role::Write);
8e96499f Andy McCall ↶ 815
    let requested = pdb::review_requests(&app.db, p.id).await.unwrap_or_default();
816
    let mut reviewable: Vec<String> = if can_request {
817
        accounts::assignable(&app.db, row.id, &row.owner).await.unwrap_or_default().into_iter().filter(|u| *u != p.author).collect()
818
    } else {
819
        Vec::new()
820
    };
821
    for r in &requested {
822
        if !reviewable.iter().any(|x| x.eq_ignore_ascii_case(r)) {
823
            reviewable.push(r.clone());
824
        }
825
    }
7d2eb590 Andy McCall ↶ 826
    let assistants: Vec<String> = if (can_request || can_edit) && p.is_open() { assistant_names(app, &row).await } else { Vec::new() };
14530604 Andy McCall ↶ 827
    let delegated = match viewer.account() {
828
        Some(a) => super::edit::delegated_identity(app, a.id).await.is_some(),
829
        None => false,
830
    };
831
    let hub_can_land = delegated || app.repos.read(&repo, |r, _| Ok(r.current_policy()?.is_none())).await.unwrap_or(false);
de505df5 Andy McCall ↶ 832
    let source_label = match p.source_kind.as_str() {
833
        "fork" => format!(
834
            "fork {}",
835
            db::repos::get_by_id(&app.db, p.source_repo_id.unwrap_or(0))
836
                .await
837
                .ok()
838
                .flatten()
839
                .map(|r| format!("{}:{}", r.slug(), p.source_bookmark))
840
                .unwrap_or_default()
841
        ),
842
        "changes" => format!("{} changes", p.source_changes().len()),
843
        _ => p.source_bookmark.clone(),
844
    };
e1ec9fbf Andy McCall ↶ 845
    let projects = super::projects::placements_for(app, viewer, &row, p.number).await;
38833ed7 Andy McCall ↶ 846
    let texts: Vec<String> = std::iter::once(p.body.clone()).chain(changes.iter().map(|c| format!("{}\n{}", c.title, c.body))).collect();
847
    let closes = super::chain::issues_closed_by(app, &row, &texts.iter().map(String::as_str).collect::<Vec<_>>()).await;
a1b98695 Andy McCall ↶ 848
    let project_choices = super::projects::project_choices(app, viewer, &row, &projects).await;
849
    let mut dated: Vec<(i64, Entry)> = Vec::new();
850
    for (index, c) in comments.iter().enumerate() {
851
        if c.row.anchor_change.is_empty() {
852
            dated.push((c.row.created_ms, Entry { kind: "comment", index }));
853
        }
854
    }
855
    for (index, r) in v.reviews.iter().enumerate() {
856
        dated.push((r.row.created_ms, Entry { kind: "review", index }));
857
    }
858
    for (index, e) in events.iter().enumerate() {
859
        dated.push((e.at_ms, Entry { kind: "event", index }));
860
    }
861
    dated.sort_by_key(|(at, _)| *at);
862
    let timeline: Vec<Entry> = dated.into_iter().map(|(_, e)| e).collect();
b5a0a69b Andy McCall ↶ 863
    let pending = app.assistant_gate.lock().unwrap_or_else(|e| e.into_inner()).answering(p_id);
de505df5 Andy McCall ↶ 864
    Ok(Page(ProposalPage {
b5a0a69b Andy McCall ↶ 865
        live_topic: crate::events::topic::proposal(row.id, number),
866
        repo_topic: crate::events::topic::repo(row.id),
867
        pending,
a1b98695 Andy McCall ↶ 868
        can_triage: role >= Role::Triage,
869
        timeline,
38833ed7 Andy McCall ↶ 870
        closes,
a1b98695 Andy McCall ↶ 871
        project_choices,
e1ec9fbf Andy McCall ↶ 872
        projects,
de505df5 Andy McCall ↶ 873
        shell,
ffb67a81 Andy McCall 874
        repo: RepoShell::new(app, &row, "proposals").with_role(role).with_sky(app, &row).await,
c79a1111 Andy McCall ↶ 875
        body_html: super::issues::markdown(app, &row, &row.default_bookmark, &p.body).await,
de505df5 Andy McCall ↶ 876
        p,
877
        tab,
878
        changes,
879
        files: loaded.files,
9df855f2 Andy McCall ↶ 880
        diffs: loaded.diffs,
881
        bases: loaded.bases,
882
        ignore_ws: false,
de505df5 Andy McCall ↶ 883
        conflicts: loaded.conflicts,
884
        conflicted: loaded.conflicted,
885
        comments,
886
        placed,
887
        outdated,
888
        reviews: v.reviews,
889
        approvals: v.approvals,
890
        blockers: v.blockers,
891
        depends_on: v.depends_on,
892
        events,
893
        owners: loaded.owners,
894
        requirements: v.requirements,
895
        landed_already: loaded.landed_already,
896
        can_edit,
4f37afcc Andy McCall ↶ 897
        deletable_source,
de505df5 Andy McCall ↶ 898
        can_land,
899
        hub_can_land,
900
        notice,
901
        error,
902
        heads: loaded.heads.iter().map(|h| h.to_hex()).collect(),
b64e2537 Andy McCall ↶ 903
        state_hash: loaded.state.clone(),
de505df5 Andy McCall ↶ 904
        source_label,
905
        api_url: format!("{}/api/v1/repos/{owner}/{name}/proposals/{number}", app.config.base_url()),
18e381ea Andy McCall ↶ 906
        labels: db::issues::proposal_labels(&app.db, loaded.row.id).await.unwrap_or_default(),
907
        all_labels: db::issues::labels(&app.db, row.id).await.unwrap_or_default(),
b64e2537 Andy McCall ↶ 908
        checks: db::hooks::checks_for_state(&app.db, row.id, &loaded.state).await.unwrap_or_default(),
909
        required_checks: db::hooks::required_checks(&app.db, row.id).await.unwrap_or_default(),
8e96499f Andy McCall ↶ 910
        requested,
911
        reviewable,
7d2eb590 Andy McCall ↶ 912
        assistants,
913
        draft: None,
cc1cd197 Andy McCall ↶ 914
        can_request,
de505df5 Andy McCall ↶ 915
    }))
916
}
917
a1b98695 Andy McCall ↶ 918
/// Back to the proposal after an action, with what to say: a redirect, so
919
/// reloading the page (the checks script does) never repeats the action.
920
fn back(owner: &str, name: &str, number: i64, tab: &str, notice: Option<String>, error: Option<String>) -> Response {
921
    let mut url = format!("/{owner}/{name}/proposal/{number}?tab={tab}");
922
    if let Some(n) = notice {
923
        url.push_str(&format!("&notice={}", super::settings::urlencode(&n)));
924
    }
925
    if let Some(e) = error {
926
        url.push_str(&format!("&error={}", super::settings::urlencode(&e)));
927
    }
928
    Redirect::to(&url).into_response()
929
}
930
de505df5 Andy McCall ↶ 931
pub async fn show(
932
    State(app): State<Shared>,
933
    viewer: Viewer,
934
    Path((owner, name, number)): Path<(String, String, i64)>,
935
    Query(q): Query<DetailQuery>,
b5a0a69b Andy McCall ↶ 936
) -> Result<Response, Error> {
de505df5 Andy McCall ↶ 937
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
a1b98695 Andy McCall ↶ 938
    let mut page =
939
        detail(&app, shell, &viewer, &owner, &name, number, q.tab.unwrap_or_else(|| "conversation".into()), q.notice, q.error).await?;
9df855f2 Andy McCall ↶ 940
    if q.w.as_deref() == Some("1") {
941
        // Hide whitespace-only changes: the same hunks, rendered again.
942
        page.0.files =
943
            super::history::render_files_with(&page.0.diffs, &page.0.bases, crate::render::diff::Options { ignore_whitespace: true });
944
        page.0.ignore_ws = true;
b5a0a69b Andy McCall ↶ 945
    }
946
    // A live page asks for one part again (oxygenhub#205): rendered by the
947
    // same route, so the same access, and cut from the whole.
948
    if let Some(name) = q.fragment.as_deref() {
949
        let html = page.0.render().map_err(|e| Error::bad(page.0.shell.clone(), e.to_string()))?;
950
        return Ok(match super::fragment(&html, name) {
951
            Some(part) => ([(axum::http::header::CACHE_CONTROL, "no-store")], axum::response::Html(part)).into_response(),
952
            None => (axum::http::StatusCode::NOT_FOUND, "no such fragment").into_response(),
953
        });
9df855f2 Andy McCall ↶ 954
    }
b5a0a69b Andy McCall ↶ 955
    Ok(page.into_response())
de505df5 Andy McCall ↶ 956
}
957
958
// ---------------------------------------------------------------- actions
959
960
#[derive(Deserialize)]
961
pub struct CommentForm {
962
    #[serde(rename = "_csrf")]
963
    csrf_token: String,
964
    body: String,
965
    #[serde(default)]
966
    path: String,
967
    #[serde(default)]
968
    line: Option<usize>,
969
}
970
971
pub async fn comment(
972
    State(app): State<Shared>,
973
    viewer: Viewer,
974
    Path((owner, name, number)): Path<(String, String, i64)>,
975
    Form(f): Form<CommentForm>,
a1b98695 Andy McCall ↶ 976
) -> Result<Response, Error> {
de505df5 Andy McCall ↶ 977
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
978
    let me = require(&viewer, &shell)?;
979
    csrf(&viewer, &f.csrf_token, &shell)?;
980
    let (repo, row, _) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d0fbea2e Andy McCall ↶ 981
    super::writable(&row, &shell)?;
de505df5 Andy McCall ↶ 982
    let p = pdb::get(&app.db, row.id, number)
983
        .await
984
        .map_err(|e| Error::from_db(shell.clone(), e))?
985
        .ok_or_else(|| Error::not_found(shell.clone()))?;
986
    if f.body.trim().is_empty() {
a1b98695 Andy McCall ↶ 987
        return Ok(back(&owner, &name, number, "conversation", None, Some("An empty comment says nothing.".into())));
de505df5 Andy McCall ↶ 988
    }
989
    let anchor = match (f.path.trim(), f.line) {
990
        ("", _) | (_, None) => None,
991
        (path, Some(line)) => {
992
            let loaded = load(&app, &repo, p.clone()).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
993
            loaded.atoms.get(&(path.to_string(), line)).cloned()
994
        }
995
    };
996
    let tab = if anchor.is_some() { "files" } else { "conversation" };
997
    pdb::add_comment(
998
        &app.db,
999
        p.id,
1000
        Some(me.account.id),
1001
        &me.account.username,
1002
        f.body.trim(),
1003
        f.path.trim(),
1004
        anchor.as_ref().map(|(h, i)| (h.as_str(), *i as i64)),
1005
    )
1006
    .await
1007
    .map_err(|e| Error::from_db(shell.clone(), e))?;
b5a0a69b Andy McCall ↶ 1008
    app.events.live.publish(&crate::events::topic::proposal(row.id, number), "comment");
a1b98695 Andy McCall ↶ 1009
    Ok(back(&owner, &name, number, tab, None, None))
de505df5 Andy McCall ↶ 1010
}
1011
1012
#[derive(Deserialize)]
1013
pub struct ReviewForm {
1014
    #[serde(rename = "_csrf")]
1015
    csrf_token: String,
1016
    verdict: String,
1017
    #[serde(default)]
1018
    body: String,
1019
}
1020
1021
pub async fn review(
1022
    State(app): State<Shared>,
1023
    viewer: Viewer,
1024
    Path((owner, name, number)): Path<(String, String, i64)>,
1025
    Form(f): Form<ReviewForm>,
a1b98695 Andy McCall ↶ 1026
) -> Result<Response, Error> {
de505df5 Andy McCall ↶ 1027
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1028
    let me = require(&viewer, &shell)?;
1029
    csrf(&viewer, &f.csrf_token, &shell)?;
1030
    let (_, row, _) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d0fbea2e Andy McCall ↶ 1031
    super::writable(&row, &shell)?;
de505df5 Andy McCall ↶ 1032
    let p = pdb::get(&app.db, row.id, number)
1033
        .await
1034
        .map_err(|e| Error::from_db(shell.clone(), e))?
1035
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1036
    if !matches!(f.verdict.as_str(), "comment" | "changes" | "approve") {
1037
        return Err(Error::bad(shell, "a review is comment, changes or approve"));
1038
    }
1039
    if f.verdict == "approve" && Some(me.account.id) == p.author_id {
a1b98695 Andy McCall ↶ 1040
        return Ok(back(&owner, &name, number, "conversation", None, Some("You cannot approve your own proposal.".into())));
de505df5 Andy McCall ↶ 1041
    }
1042
    pdb::add_review(&app.db, p.id, me.account.id, &me.account.username, &f.verdict, f.body.trim())
1043
        .await
1044
        .map_err(|e| Error::from_db(shell.clone(), e))?;
1045
    pdb::add_event(&app.db, p.id, &me.account.username, &format!("review.{}", f.verdict), "").await.ok();
cc1cd197 Andy McCall ↶ 1046
    reviewed(&app, &row, &p, &me.account, &f.verdict).await;
b64e2537 Andy McCall ↶ 1047
    crate::hooks::emit(&app, &row, "review", &me.account.username, serde_json::json!({ "number": number, "verdict": f.verdict })).await;
de505df5 Andy McCall ↶ 1048
    let notice = if f.verdict == "approve" {
1049
        Some(format!(
1050
            "Approval recorded. It counts once you seal the changes: oxy seal --proposal {}/{owner}/{name}/proposal/{number}",
1051
            app.config.base_url()
1052
        ))
1053
    } else {
1054
        None
1055
    };
a1b98695 Andy McCall ↶ 1056
    Ok(back(&owner, &name, number, "conversation", notice, None))
de505df5 Andy McCall ↶ 1057
}
1058
1059
#[derive(Deserialize)]
1060
pub struct EditForm {
1061
    #[serde(rename = "_csrf")]
1062
    csrf_token: String,
1063
    title: String,
1064
    #[serde(default)]
1065
    body: String,
1066
    target: String,
1067
}
1068
1069
pub async fn edit(
1070
    State(app): State<Shared>,
1071
    viewer: Viewer,
1072
    Path((owner, name, number)): Path<(String, String, i64)>,
1073
    Form(f): Form<EditForm>,
a1b98695 Andy McCall ↶ 1074
) -> Result<Response, Error> {
de505df5 Andy McCall ↶ 1075
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1076
    let me = require(&viewer, &shell)?;
1077
    csrf(&viewer, &f.csrf_token, &shell)?;
1078
    let (_, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1079
    let p = pdb::get(&app.db, row.id, number)
1080
        .await
1081
        .map_err(|e| Error::from_db(shell.clone(), e))?
1082
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1083
    if Some(me.account.id) != p.author_id && role < Role::Maintain {
1084
        return Err(Error::not_found(shell));
1085
    }
1086
    let target = if crate::repos::names::valid_segment(f.target.trim()) { f.target.trim() } else { &p.target };
1087
    pdb::edit(&app.db, p.id, f.title.trim(), f.body.trim(), target).await.map_err(|e| Error::from_db(shell.clone(), e))?;
1088
    pdb::add_event(&app.db, p.id, &me.account.username, "edited", "").await.ok();
a1b98695 Andy McCall ↶ 1089
    Ok(back(&owner, &name, number, "conversation", Some("Saved.".into()), None))
de505df5 Andy McCall ↶ 1090
}
1091
1092
#[derive(Deserialize)]
1093
pub struct StateForm {
1094
    #[serde(rename = "_csrf")]
1095
    csrf_token: String,
1096
    action: String,
1097
}
1098
1099
pub async fn state(
1100
    State(app): State<Shared>,
1101
    viewer: Viewer,
1102
    Path((owner, name, number)): Path<(String, String, i64)>,
1103
    Form(f): Form<StateForm>,
a1b98695 Andy McCall ↶ 1104
) -> Result<Response, Error> {
de505df5 Andy McCall ↶ 1105
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1106
    let me = require(&viewer, &shell)?;
1107
    csrf(&viewer, &f.csrf_token, &shell)?;
1108
    let (_, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1109
    let p = pdb::get(&app.db, row.id, number)
1110
        .await
1111
        .map_err(|e| Error::from_db(shell.clone(), e))?
1112
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1113
    if Some(me.account.id) != p.author_id && role < Role::Triage {
1114
        return Err(Error::not_found(shell));
1115
    }
1116
    let new_state = match (f.action.as_str(), p.state.as_str()) {
1117
        ("close", "open" | "draft") => "closed",
1118
        ("reopen", "closed") => "open",
1119
        ("ready", "draft") => "open",
1120
        ("draft", "open") => "draft",
1121
        _ => return Err(Error::bad(shell, "that transition is not possible")),
1122
    };
1123
    pdb::set_state(&app.db, p.id, new_state, "").await.map_err(|e| Error::from_db(shell.clone(), e))?;
1124
    pdb::add_event(&app.db, p.id, &me.account.username, new_state, "").await.ok();
b64e2537 Andy McCall ↶ 1125
    crate::hooks::emit(&app, &row, &format!("proposal.{new_state}"), &me.account.username, serde_json::json!({ "number": number })).await;
a1b98695 Andy McCall ↶ 1126
    Ok(back(&owner, &name, number, "conversation", None, None))
de505df5 Andy McCall ↶ 1127
}
1128
1129
pub async fn resolve_comment(
1130
    State(app): State<Shared>,
1131
    viewer: Viewer,
1132
    Path((owner, name, number, id)): Path<(String, String, i64, i64)>,
1133
    Form(f): Form<super::session::CsrfForm>,
a1b98695 Andy McCall ↶ 1134
) -> Result<Response, Error> {
de505df5 Andy McCall ↶ 1135
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1136
    require(&viewer, &shell)?;
1137
    csrf(&viewer, &f.csrf, &shell)?;
1138
    let (_, row, _) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1139
    let p = pdb::get(&app.db, row.id, number)
1140
        .await
1141
        .map_err(|e| Error::from_db(shell.clone(), e))?
1142
        .ok_or_else(|| Error::not_found(shell.clone()))?;
5d90e0e0 Andy McCall 1143
    let current: Option<bool> = sqlx::query_scalar("SELECT resolved FROM proposal_comments WHERE id = $1 AND proposal_id = $2")
de505df5 Andy McCall ↶ 1144
        .bind(id)
1145
        .bind(p.id)
1146
        .fetch_optional(&app.db)
1147
        .await
1148
        .map_err(|e| Error::from_db(shell.clone(), e))?;
1149
    if let Some(r) = current {
1150
        pdb::set_comment_resolved(&app.db, id, !r).await.map_err(|e| Error::from_db(shell.clone(), e))?;
1151
    }
a1b98695 Andy McCall ↶ 1152
    Ok(back(&owner, &name, number, "files", None, None))
de505df5 Andy McCall ↶ 1153
}
1154
1155
/// Land from the hub: only when the repository has no trust policy (the
1156
/// hub never signs a reference update the policy would have to admit).
1157
pub async fn land(
1158
    State(app): State<Shared>,
1159
    viewer: Viewer,
1160
    Path((owner, name, number)): Path<(String, String, i64)>,
1161
    Form(f): Form<super::session::CsrfForm>,
a1b98695 Andy McCall ↶ 1162
) -> Result<Response, Error> {
de505df5 Andy McCall ↶ 1163
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1164
    let me = require(&viewer, &shell)?;
1165
    csrf(&viewer, &f.csrf, &shell)?;
1166
    let (repo, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
f4d6ef41 Andy McCall ↶ 1167
    match land_as(&app, &repo, &row, &me.account, number, "web", false).await {
a1b98695 Andy McCall ↶ 1168
        Ok(_) => Ok(back(&owner, &name, number, "conversation", Some("Landed.".into()), None)),
1f1eb06a Andy McCall ↶ 1169
        Err(Landing::NotFound) => Err(Error::not_found(shell)),
a1b98695 Andy McCall ↶ 1170
        Err(Landing::Refused(m)) => Ok(back(&owner, &name, number, "conversation", None, Some(m))),
1f1eb06a Andy McCall ↶ 1171
    }
1172
}
1173
1174
/// Why a proposal did not land.
1175
pub enum Landing {
1176
    NotFound,
1177
    Refused(String),
1178
}
1179
1180
/// Land proposal `number` as `me` (hub spec §8.4), who has write access:
1181
/// refused while it is not open or has blockers. Moves the target bookmark
1182
/// (attested by the hub key on `me`'s behalf when they delegated to it),
0b20f1ec Andy McCall ↶ 1183
/// then records, announces and audits the landing, saying how it was done
f4d6ef41 Andy McCall ↶ 1184
/// (`via`: `web`, or `api (token NAME)`). `as_hub` signs with the hub's own
1185
/// key rather than `me`'s delegation (Diffusion's auto-land). Returns the
1186
/// new state.
1f1eb06a Andy McCall ↶ 1187
pub async fn land_as(
1188
    app: &Shared,
1189
    repo: &RepoName,
1190
    row: &db::repos::RepoRow,
1191
    me: &accounts::Account,
1192
    number: i64,
0b20f1ec Andy McCall ↶ 1193
    via: &str,
f4d6ef41 Andy McCall ↶ 1194
    as_hub: bool,
1f1eb06a Andy McCall ↶ 1195
) -> Result<String, Landing> {
1196
    let (owner, name) = (row.owner.clone(), row.name.clone());
1197
    let refused = |e: String| Landing::Refused(e);
1198
    let p = pdb::get(&app.db, row.id, number).await.map_err(|e| refused(e.to_string()))?.ok_or(Landing::NotFound)?;
1199
    let loaded = load(app, repo, p.clone()).await.map_err(|e| refused(e.to_string()))?;
1200
    let v = verdict(app, &loaded, row.id).await.map_err(|e| refused(e.to_string()))?;
1201
    if !p.is_open() {
1202
        return Err(refused(format!("Cannot land: the proposal is {}", p.state)));
1203
    }
1204
    if !v.blockers.is_empty() {
1205
        return Err(refused(format!("Cannot land: {}", v.blockers.join("; "))));
de505df5 Andy McCall ↶ 1206
    }
1207
    let target = p.target.clone();
1208
    let heads = loaded.heads.clone();
14530604 Andy McCall ↶ 1209
    // With a delegation the landing is attested by the hub key on the
1210
    // user's behalf, which a policy accepts when it lets the user update
1211
    // the target (spec §14.5); without one, only a policy-free repository
1212
    // can be landed here.
f4d6ef41 Andy McCall ↶ 1213
    let signer = if as_hub { super::edit::hub_signer(app) } else { super::edit::signer_for(app, me.id).await };
1214
    let result = match signer {
1f1eb06a Andy McCall ↶ 1215
        Ok(signer) => crate::repos::edits::move_bookmark(&app.repos, repo, target.clone(), heads.clone(), signer).await.map(|_| pl::state_ref(&heads).to_hex()),
14530604 Andy McCall ↶ 1216
        Err(why) => {
1217
            app.repos
1f1eb06a Andy McCall ↶ 1218
                .write(repo, move |r, _| {
14530604 Andy McCall ↶ 1219
                    if r.current_policy()?.is_some() {
1220
                        return Err(crate::repos::RepoError::Oxy(oxy_core::repo::RepoError::Msg(format!(
1221
                            "this repository has a trust policy, so the landing must be signed by a key it authorises. Land from a client with oxy proposal land, or delegate to the hub. {why}"
1222
                        ))));
1223
                    }
1224
                    r.bookmark_set(&target, &heads)?;
1225
                    Ok(pl::state_ref(&heads).to_hex())
1226
                })
1227
                .await
1228
        }
1229
    };
1f1eb06a Andy McCall ↶ 1230
    let state = result.map_err(|e| refused(e.to_string()))?;
0b20f1ec Andy McCall ↶ 1231
    pdb::set_landed(&app.db, p.id, &state, &me.username, via).await.map_err(|e| refused(e.to_string()))?;
1232
    let how = if v.approvals.is_empty() { format!("{via}, with no approval") } else { via.to_string() };
1233
    pdb::add_event(&app.db, p.id, &me.username, "landed", &how).await.ok();
1f1eb06a Andy McCall ↶ 1234
    crate::hooks::emit(
1235
        app,
1236
        row,
1237
        "proposal.landed",
1238
        &me.username,
1239
        serde_json::json!({ "number": number, "target": p.target, "state": state }),
1240
    )
1241
    .await;
1242
    crate::notify::deliver(
1243
        app,
1244
        crate::notify::Event {
1245
            kind: "proposal.landed",
1246
            title: format!("{owner}/{name}#{number}: {} landed", p.title),
1247
            url: format!("/{owner}/{name}/proposal/{number}"),
1248
            actor: me,
1249
            repo_id: row.id,
1250
            thread: Some(("proposal", p.id)),
1251
            mention_text: "",
1252
            direct: p.author_id.into_iter().collect(),
1253
        },
1254
    )
1255
    .await;
1256
    if p.target == row.default_bookmark {
1257
        let messages: Vec<(String, String)> = loaded.changes.iter().map(|c| (c.hash.clone(), format!("{}\n{}", c.title, c.body))).collect();
1258
        super::issues::close_from_messages(app, row, &messages).await;
de505df5 Andy McCall ↶ 1259
    }
0b20f1ec Andy McCall ↶ 1260
    accounts::audit(&app.db, Some(me), "proposal.landed", &format!("{owner}/{name}#{number}"), &how).await.ok();
1f1eb06a Andy McCall ↶ 1261
    db::repos::record_push(
1262
        &app.db,
1263
        row.id,
1264
        Some((me.id, me.username.as_str())),
1265
        &[db::repos::PushOutcome {
1266
            reference: p.target.clone(),
1267
            ok: true,
0b20f1ec Andy McCall ↶ 1268
            reason: format!("landed #{number} ({how})"),
1f1eb06a Andy McCall ↶ 1269
            old_state: loaded.target_state.clone(),
1270
            new_state: state.clone(),
1271
            heads: loaded.heads.len() as i64,
1272
            changes: loaded.hashes.len() as i64,
1273
        }],
1274
    )
1275
    .await
1276
    .ok();
d943160d Andy McCall ↶ 1277
    // The target moved: its other open proposals are checked again (#134).
1278
    settle_after_push(app, row, &p.target, &me.username).await;
acc85ac0 Andy McCall ↶ 1279
    // A landing on the default bookmark closes the issues its changes (and
1280
    // its description) say they close, as a push there would.
1281
    if p.target == row.default_bookmark {
1282
        let body = (format!("proposal #{number}"), p.body.clone());
1283
        crate::web::issues::close_from_arrived(app, row, loaded.target_heads.clone(), loaded.heads.clone(), Some(body)).await;
1284
    }
757195ad Andy McCall ↶ 1285
    // Diffusion (#150): a landing moves the target as a push would, so the
1286
    // pin index follows it, and the consumers of a moved default bookmark
1287
    // are bumped.
1288
    let heads = loaded.heads.clone();
1289
    let moved = vec![(p.target.clone(), state.clone(), heads.clone())];
1290
    crate::diffusion::after_push(app, row, &moved).await;
1291
    if p.target == row.default_bookmark {
1292
        let (app, row) = (app.clone(), row.clone());
1293
        tokio::spawn(async move { crate::diffusion::propagate(&app, &row, heads, false).await });
1294
    }
1f1eb06a Andy McCall ↶ 1295
    Ok(state)
de505df5 Andy McCall ↶ 1296
}
1297
18e381ea Andy McCall ↶ 1298
#[derive(Deserialize)]
1299
pub struct LabelsForm {
1300
    #[serde(rename = "_csrf")]
1301
    csrf_token: String,
1302
    #[serde(default)]
1303
    label: Vec<i64>,
1304
}
1305
1306
pub async fn set_labels(
1307
    State(app): State<Shared>,
1308
    viewer: Viewer,
1309
    Path((owner, name, number)): Path<(String, String, i64)>,
1310
    axum_extra::extract::Form(f): axum_extra::extract::Form<LabelsForm>,
a1b98695 Andy McCall ↶ 1311
) -> Result<Response, Error> {
18e381ea Andy McCall ↶ 1312
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1313
    require(&viewer, &shell)?;
1314
    csrf(&viewer, &f.csrf_token, &shell)?;
1315
    let (_, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1316
    if role < Role::Triage {
1317
        return Err(Error::not_found(shell));
1318
    }
1319
    let p = pdb::get(&app.db, row.id, number)
1320
        .await
1321
        .map_err(|e| Error::from_db(shell.clone(), e))?
1322
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1323
    for l in db::issues::labels(&app.db, row.id).await.map_err(|e| Error::from_db(shell.clone(), e))? {
1324
        db::issues::set_proposal_label(&app.db, p.id, l.id, f.label.contains(&l.id)).await.map_err(|e| Error::from_db(shell.clone(), e))?;
1325
    }
a1b98695 Andy McCall ↶ 1326
    Ok(back(&owner, &name, number, "conversation", None, None))
18e381ea Andy McCall ↶ 1327
}
1328
b64e2537 Andy McCall ↶ 1329
/// `GET /{owner}/{name}/proposal/{number}/events`: server-sent events for
1330
/// checks on the projected state (hub spec §13.1).
1331
pub async fn events(
1332
    State(app): State<Shared>,
1333
    viewer: Viewer,
1334
    Path((owner, name, number)): Path<(String, String, i64)>,
1335
) -> Result<axum::response::Sse<impl futures::Stream<Item = Result<axum::response::sse::Event, std::convert::Infallible>>>, Error> {
1336
    use futures::StreamExt;
1337
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1338
    let (_, row, _) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1339
    let rx = app.events.proposals.subscribe();
1340
    let repo_id = row.id;
1341
    let stream = tokio_stream::wrappers::BroadcastStream::new(rx).filter_map(move |item| async move {
1342
        match item {
1343
            Ok((id, ev)) if id == repo_id => {
1344
                Some(Ok(axum::response::sse::Event::default().event(ev.kind.clone()).data(serde_json::to_string(&ev).unwrap_or_default())))
1345
            }
1346
            _ => None,
1347
        }
1348
    });
c92a9949 Andy McCall ↶ 1349
    Ok(axum::response::Sse::new(futures::StreamExt::take_until(stream, crate::shutdown::stopping()))
1350
        .keep_alive(axum::response::sse::KeepAlive::default()))
b64e2537 Andy McCall ↶ 1351
}
1352
de505df5 Andy McCall ↶ 1353
// -------------------------------------------------------------------- API
1354
1355
pub async fn to_api(app: &Shared, owner: &str, name: &str, loaded: &Loaded, v: &Verdict, source_url: Option<String>) -> hub_api::Proposal {
1356
    let p = &loaded.row;
1357
    hub_api::Proposal {
1358
        number: p.number,
1359
        title: p.title.clone(),
1360
        body: p.body.clone(),
1361
        author: p.author.clone(),
1362
        state: ProposalState::parse(&p.state).unwrap_or(ProposalState::Open),
1363
        target: p.target.clone(),
1364
        source: match p.source_kind.as_str() {
1365
            "fork" => {
1366
                let (o, n) = source_url
1367
                    .as_deref()
1368
                    .and_then(|u| u.rsplit_once('/'))
1369
                    .and_then(|(b, n)| b.rsplit_once('/').map(|(_, o)| (o.to_string(), n.to_string())))
1370
                    .unwrap_or_default();
1371
                ProposalSource::Fork { owner: o, name: n, bookmark: p.source_bookmark.clone() }
1372
            }
1373
            "changes" => ProposalSource::Changes { hashes: p.source_changes() },
1374
            _ => ProposalSource::Bookmark { bookmark: p.source_bookmark.clone() },
1375
        },
1376
        changes: loaded
1377
            .changes
1378
            .iter()
1379
            .map(|c| hub_api::ChangeSummary {
1380
                hash: c.hash.clone(),
1381
                message: if c.body.is_empty() { c.title.clone() } else { format!("{}\n\n{}", c.title, c.body) },
1382
                author: hub_api::Author {
1383
                    name: c.author.name.clone(),
1384
                    email: c.author.email.clone(),
1385
                    key: c.author.key.clone(),
1386
                    account: c.author.account.clone(),
760a7dd3 Andy McCall ↶ 1387
                    note: hub_api::Author::note_for(&c.author.key, &c.author.account),
de505df5 Andy McCall ↶ 1388
                },
1389
                when_ms: c.when_ms,
1390
                deps: c.deps.clone(),
1391
                head: c.head,
8933faff Andy McCall ↶ 1392
                via: c.via.as_ref().map(|v| hub_api::Via {
1393
                    name: v.name.clone(),
1394
                    key: v.key.clone(),
1395
                    scope: v.scope.clone(),
1396
                    expires_ms: v.expires_ms,
1397
                    revoked: v.revoked,
1398
                }),
de505df5 Andy McCall ↶ 1399
                signature: match &c.signature {
1400
                    view::SigView::Unsigned => hub_api::Signature::Unsigned,
1401
                    view::SigView::Valid { key, sealed, revoked, .. } => {
1402
                        hub_api::Signature::Valid { key: key.clone(), sealed: *sealed, revoked: *revoked }
1403
                    }
1404
                    view::SigView::Invalid(why) => hub_api::Signature::Invalid { reason: why.clone() },
1405
                },
1406
            })
1407
            .collect(),
1408
        projected_heads: loaded.heads.iter().map(|h| h.to_hex()).collect(),
1409
        projected_state: Some(loaded.state.clone()),
1410
        conflicted: loaded.conflicted,
1411
        approvals: v.approvals.clone(),
1412
        landable: p.is_open() && v.blockers.is_empty(),
1413
        blockers: v.blockers.clone(),
1414
        created_ms: p.created_ms,
1415
        updated_ms: p.updated_ms,
1416
        url: format!("{}/{owner}/{name}/proposal/{}", app.config.base_url(), p.number),
1417
        repository_url: format!("{}/{owner}/{name}", app.config.base_url()),
1418
        source_url,
0b20f1ec Andy McCall ↶ 1419
        landed: (p.state == "landed" && p.landed_ms > 0).then(|| hub_api::Landed {
1420
            by: p.landed_by.clone(),
1421
            via: p.landed_via.clone(),
1422
            when_ms: p.landed_ms,
1423
        }),
cc1cd197 Andy McCall ↶ 1424
        requested_reviewers: pdb::review_requests(&app.db, p.id).await.unwrap_or_default(),
2291f8cc Andy McCall ↶ 1425
        labels: db::issues::proposal_labels(&app.db, p.id)
1426
            .await
1427
            .unwrap_or_default()
1428
            .into_iter()
1429
            .map(|l| hub_api::Label { name: l.name, colour: l.colour, description: l.description })
1430
            .collect(),
de505df5 Andy McCall ↶ 1431
    }
1432
}
1433
1434
/// The line comment form's placement key, for templates.
1435
pub fn key(path: &str, line: impl filters::Num) -> (String, usize) {
1436
    (path.to_string(), line.as_u64() as usize)
1437
}
1438
1439
#[allow(dead_code)]
1440
fn _unused(_: &diff::Line, _: &ConflictView, _: &Role) {}
cc1cd197 Andy McCall ↶ 1441
1442
// ------------------------------------------------------- review requests
1443
1444
/// Ask accounts to review a proposal (hub plan 0.4): each must exist, be
1445
/// someone other than the author, and be able to read the repository. Each
1446
/// newly asked is told, and the proposal records it. The usernames newly
1447
/// asked, or why none could be.
1448
pub async fn request_reviewers(
1449
    app: &Shared,
1450
    row: &db::repos::RepoRow,
1451
    p: &pdb::ProposalRow,
1452
    by: &accounts::Account,
1453
    names: &[String],
1454
) -> Result<Vec<String>, String> {
1455
    let mut found = Vec::new();
1456
    for name in names.iter().map(|n| n.trim().trim_start_matches('@')).filter(|n| !n.is_empty()) {
1457
        let Some(a) = accounts::account_by_name(&app.db, name).await.ok().flatten() else {
1458
            return Err(format!("There is no account {name}."));
1459
        };
1460
        if Some(a.id) == p.author_id {
1461
            return Err(format!("{name} wrote this proposal, and cannot review it."));
1462
        }
1463
        let role = crate::auth::roles::role_for(&app.db, Some(&a), row).await.ok().flatten();
1464
        if !crate::auth::roles::allows(role, crate::auth::Access::Read) {
1465
            return Err(format!("{name} cannot read this repository."));
1466
        }
1467
        found.push(a);
1468
    }
1469
    let mut asked = Vec::new();
1470
    for a in found {
1471
        if !pdb::request_review(&app.db, p.id, a.id, &by.username).await.map_err(|e| e.to_string())? {
1472
            continue;
1473
        }
1474
        pdb::add_event(&app.db, p.id, &by.username, "review requested", &a.username).await.ok();
1475
        crate::notify::deliver(
1476
            app,
1477
            crate::notify::Event {
1478
                kind: "proposal.review_requested",
1479
                title: format!("{}/{}#{}: {} (review requested from {})", row.owner, row.name, p.number, p.title, a.username),
1480
                url: format!("/{}/{}/proposal/{}", row.owner, row.name, p.number),
1481
                actor: by,
1482
                repo_id: row.id,
1483
                thread: None,
1484
                mention_text: "",
1485
                direct: vec![a.id],
1486
            },
1487
        )
1488
        .await;
1489
        asked.push(a.username);
1490
    }
1491
    Ok(asked)
1492
}
1493
1494
/// After a review: it answers the reviewer's request, if there was one, and
1495
/// the proposal's author is told.
1496
pub async fn reviewed(app: &Shared, row: &db::repos::RepoRow, p: &pdb::ProposalRow, by: &accounts::Account, verdict: &str) {
1497
    pdb::unrequest_review(&app.db, p.id, by.id).await.ok();
1498
    let what = match verdict {
1499
        "approve" => "approved",
1500
        "changes" => "changes requested",
1501
        _ => "reviewed",
1502
    };
1503
    crate::notify::deliver(
1504
        app,
1505
        crate::notify::Event {
1506
            kind: "proposal.review",
1507
            title: format!("{}/{}#{}: {} ({what} by {})", row.owner, row.name, p.number, p.title, by.username),
1508
            url: format!("/{}/{}/proposal/{}", row.owner, row.name, p.number),
1509
            actor: by,
1510
            repo_id: row.id,
1511
            thread: Some(("proposal", p.id)),
1512
            mention_text: "",
1513
            direct: p.author_id.into_iter().collect(),
1514
        },
1515
    )
1516
    .await;
1517
}
1518
1519
#[derive(Deserialize)]
1520
pub struct ReviewersForm {
1521
    #[serde(rename = "_csrf")]
1522
    csrf_token: String,
8e96499f Andy McCall ↶ 1523
    /// `add`, `remove`, or `set` (the menu: exactly these are asked).
cc1cd197 Andy McCall ↶ 1524
    action: String,
8e96499f Andy McCall ↶ 1525
    #[serde(default)]
1526
    username: Vec<String>,
cc1cd197 Andy McCall ↶ 1527
}
1528
1529
/// `POST /{owner}/{name}/proposal/{number}/reviewers`: the author or a
1530
/// writer asks someone to review, or withdraws the request.
1531
pub async fn reviewers(
1532
    State(app): State<Shared>,
1533
    viewer: Viewer,
1534
    Path((owner, name, number)): Path<(String, String, i64)>,
8e96499f Andy McCall ↶ 1535
    axum_extra::extract::Form(f): axum_extra::extract::Form<ReviewersForm>,
cc1cd197 Andy McCall ↶ 1536
) -> Result<Response, Error> {
1537
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1538
    let me = require(&viewer, &shell)?;
1539
    csrf(&viewer, &f.csrf_token, &shell)?;
1540
    let (_, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1541
    let p = pdb::get(&app.db, row.id, number)
1542
        .await
1543
        .map_err(|e| Error::from_db(shell.clone(), e))?
1544
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1545
    if Some(me.account.id) != p.author_id && role < Role::Write {
1546
        return Err(Error::not_found(shell));
1547
    }
8e96499f Andy McCall ↶ 1548
    let names: Vec<String> = f.username.iter().map(|n| n.trim().trim_start_matches('@').to_string()).filter(|n| !n.is_empty()).collect();
1549
    let current = pdb::review_requests(&app.db, p.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
1550
    // Withdrawn: those named (remove), or those the menu left out (set).
1551
    let withdraw: Vec<String> = match f.action.as_str() {
1552
        "remove" => names.clone(),
1553
        "set" => current.iter().filter(|c| !names.iter().any(|n| n.eq_ignore_ascii_case(c))).cloned().collect(),
1554
        _ => Vec::new(),
1555
    };
1556
    for who in &withdraw {
1557
        if let Some(a) = accounts::account_by_name(&app.db, who).await.ok().flatten() {
cc1cd197 Andy McCall ↶ 1558
            if pdb::unrequest_review(&app.db, p.id, a.id).await.map_err(|e| Error::from_db(shell.clone(), e))? {
1559
                pdb::add_event(&app.db, p.id, &me.account.username, "review request withdrawn", &a.username).await.ok();
1560
            }
1561
        }
8e96499f Andy McCall ↶ 1562
    }
1563
    let ask: Vec<String> = match f.action.as_str() {
1564
        "add" => names,
1565
        "set" => names.into_iter().filter(|n| !current.iter().any(|c| c.eq_ignore_ascii_case(n))).collect(),
1566
        _ => return Ok(back(&owner, &name, number, "conversation", None, None)),
1567
    };
1568
    if ask.is_empty() {
cc1cd197 Andy McCall ↶ 1569
        return Ok(back(&owner, &name, number, "conversation", None, None));
1570
    }
8e96499f Andy McCall ↶ 1571
    match request_reviewers(&app, &row, &p, &me.account, &ask).await {
cc1cd197 Andy McCall ↶ 1572
        Ok(asked) if asked.is_empty() => Ok(back(&owner, &name, number, "conversation", Some("Already asked.".into()), None)),
1573
        Ok(asked) => Ok(back(&owner, &name, number, "conversation", Some(format!("Asked {} to review.", asked.join(", "))), None)),
1574
        Err(e) => Ok(back(&owner, &name, number, "conversation", None, Some(e))),
7d2eb590 Andy McCall ↶ 1575
    }
1576
}
1577
1578
#[derive(Deserialize)]
1579
pub struct AssistantForm {
1580
    #[serde(rename = "_csrf")]
1581
    csrf_token: String,
1582
    assistant: String,
ffb67a81 Andy McCall 1583
    /// `summary` asks for a summary comment (oxygenhub#190); otherwise a review.
1584
    #[serde(default)]
1585
    task: String,
7d2eb590 Andy McCall ↶ 1586
}
1587
1588
/// `POST /{owner}/{name}/proposal/{number}/assistant`: the author or a
1589
/// writer asks an AI assistant to review (hub spec §13.4). The answer
1590
/// comes later as a review via the assistant.
1591
pub async fn assistant(
1592
    State(app): State<Shared>,
1593
    viewer: Viewer,
1594
    Path((owner, name, number)): Path<(String, String, i64)>,
1595
    Form(f): Form<AssistantForm>,
1596
) -> Result<Response, Error> {
1597
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1598
    let me = require(&viewer, &shell)?;
1599
    csrf(&viewer, &f.csrf_token, &shell)?;
1600
    let (_, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d0fbea2e Andy McCall ↶ 1601
    super::writable(&row, &shell)?;
7d2eb590 Andy McCall ↶ 1602
    let p = pdb::get(&app.db, row.id, number)
1603
        .await
1604
        .map_err(|e| Error::from_db(shell.clone(), e))?
1605
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1606
    if Some(me.account.id) != p.author_id && role < Role::Write {
1607
        return Err(Error::not_found(shell));
1608
    }
1609
    if !p.is_open() {
1610
        return Ok(back(&owner, &name, number, "conversation", None, Some("The proposal is not open.".into())));
1611
    }
1612
    let Some(a) = crate::assistants::enabled_for_repo(&app.db, &row)
1613
        .await
1614
        .map_err(|e| Error::from_db(shell.clone(), e))?
1615
        .into_iter()
1616
        .find(|a| a.name.eq_ignore_ascii_case(f.assistant.trim()))
1617
    else {
1618
        return Ok(back(&owner, &name, number, "conversation", None, Some(format!("No assistant called {} here.", f.assistant.trim()))));
1619
    };
1620
    let who = a.name.clone();
ffb67a81 Andy McCall 1621
    let summary = f.task == "summary";
1622
    let asked = if summary {
1623
        crate::assistants::request_summary(&app, &row, &p, &me.account, a).await
1624
    } else {
1625
        crate::assistants::request_review(&app, &row, &p, &me.account, a).await
1626
    };
1627
    match asked {
7d2eb590 Andy McCall ↶ 1628
        Ok(()) => Ok(back(
1629
            &owner,
1630
            &name,
1631
            number,
1632
            "conversation",
ffb67a81 Andy McCall 1633
            Some(if summary {
1634
                format!("Asked {who} for a summary; its comment appears here when it comes.")
1635
            } else {
1636
                format!("Asked {who} to review; its answer appears here when it comes.")
1637
            }),
7d2eb590 Andy McCall ↶ 1638
            None,
1639
        )),
1640
        Err(e) => Ok(back(&owner, &name, number, "conversation", None, Some(format!("Not asked: {e}.")))),
1641
    }
1642
}
1643
1644
/// The assistants a repository may use, by name.
1645
async fn assistant_names(app: &Shared, row: &db::repos::RepoRow) -> Vec<String> {
1646
    crate::assistants::enabled_for_repo(&app.db, row).await.unwrap_or_default().into_iter().map(|a| a.name).collect()
1647
}
1648
1649
/// The changes and the file diffs a proposal from `source` into `target`
1650
/// would carry.
1651
async fn preview_diff(
1652
    app: &Shared,
1653
    repo: &RepoName,
1654
    target: &str,
1655
    source: &str,
1656
) -> Result<(Vec<ChangeView>, Vec<oxy_core::repo::FileDiff>), crate::repos::RepoError> {
1657
    let Some((fork, bookmark)) = parse_source(app, repo, source) else { return Ok((vec![], vec![])) };
1658
    let target = target.to_string();
1659
    let fork_dir = fork.as_ref().map(|f| app.repos.dir(f));
1660
    app.repos
1661
        .read(repo, move |r, cache| {
1662
            let projection = match &fork_dir {
1663
                Some(dir) => {
1664
                    let fork_repo = oxy_core::repo::Repo::open(dir)?;
1665
                    let heads = fork_repo.bookmarks()?.into_iter().find(|b| b.name == bookmark).map(|b| b.heads).unwrap_or_default();
1666
                    pl::project(r, cache, &target, Source::Fork { fork: &fork_repo, heads })?
1667
                }
1668
                None => {
1669
                    let heads = r.bookmarks()?.into_iter().find(|b| b.name == bookmark).map(|b| b.heads).unwrap_or_default();
1670
                    pl::project(r, cache, &target, Source::Bookmark(heads))?
1671
                }
1672
            };
1673
            Ok((projection.changes, projection.files))
1674
        })
1675
        .await
1676
}
1677
1678
/// `POST /{owner}/{name}/proposals/new/draft`: an assistant drafts the
1679
/// description from the changes the proposal would add; the form comes
1680
/// back with the draft to edit (hub spec §13.4).
1681
pub async fn new_draft(
1682
    State(app): State<Shared>,
1683
    viewer: Viewer,
1684
    Path((owner, name)): Path<(String, String)>,
1685
    Form(f): Form<NewForm>,
1686
) -> Result<Page<NewProposalPage>, Error> {
1687
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposals/new"), &viewer);
1688
    let me = require(&viewer, &shell)?;
1689
    csrf(&viewer, &f.csrf_token, &shell)?;
1690
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d0fbea2e Andy McCall ↶ 1691
    super::writable(&row, &shell)?;
7d2eb590 Andy McCall ↶ 1692
    let bookmarks =
1693
        app.repos.read(&repo, |r, _| Ok(r.bookmarks()?.into_iter().map(|b| b.name).collect::<Vec<_>>())).await.unwrap_or_default();
1694
    let (preview, conflicted) = preview_for(&app, &repo, &f.target, &f.source).await.unwrap_or((vec![], false));
1695
    let assistants = if preview.is_empty() { vec![] } else { assistant_names(&app, &row).await };
1696
    let mut page = NewProposalPage {
1697
        shell,
1698
        repo: RepoShell::new(&app, &row, "proposals").with_role(role),
1699
        bookmarks,
1700
        source: f.source.clone(),
1701
        target: f.target.clone(),
1702
        error: None,
1703
        preview,
1704
        conflicted,
1705
        title: f.title.clone(),
1706
        body: f.body.clone(),
1707
        assistants,
1708
    };
1709
    let assistant = crate::assistants::enabled_for_repo(&app.db, &row)
1710
        .await
1711
        .unwrap_or_default()
1712
        .into_iter()
1713
        .find(|a| a.name.eq_ignore_ascii_case(f.assistant.trim()));
1714
    let Some(a) = assistant else {
1715
        page.error = Some(format!("No assistant called {} here.", f.assistant.trim()));
1716
        return Ok(Page(page));
1717
    };
1718
    if page.preview.is_empty() {
1719
        page.error = Some("Nothing to describe: the source adds nothing to the target.".into());
1720
        return Ok(Page(page));
1721
    }
1722
    let (changes, diffs) = match preview_diff(&app, &repo, &f.target, &f.source).await {
1723
        Ok(x) => x,
1724
        Err(e) => {
1725
            page.error = Some(e.to_string());
1726
            return Ok(Page(page));
1727
        }
1728
    };
1729
    let d = crate::assistants::Draft { slot: -row.id, title: &f.title, target: &f.target, changes: &changes, diffs: &diffs };
1730
    match crate::assistants::draft_description(&app, &row, &me.account, &a, d).await {
1731
        Ok(text) => page.body = text,
1732
        Err(why) => page.error = Some(format!("{} did not answer: {why}.", a.name)),
1733
    }
1734
    Ok(Page(page))
1735
}
1736
1737
#[derive(Deserialize)]
1738
pub struct DraftForm {
1739
    #[serde(rename = "_csrf")]
1740
    csrf_token: String,
1741
    assistant: String,
1742
    #[serde(default)]
1743
    title: String,
1744
}
1745
1746
/// `POST /{owner}/{name}/proposal/{number}/draft`: an assistant drafts the
1747
/// description of an open proposal from its changes; the editor opens
1748
/// with the draft, nothing is saved (hub spec §13.4).
1749
pub async fn draft(
1750
    State(app): State<Shared>,
1751
    viewer: Viewer,
1752
    Path((owner, name, number)): Path<(String, String, i64)>,
1753
    Form(f): Form<DraftForm>,
1754
) -> Result<Response, Error> {
1755
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1756
    let me = require(&viewer, &shell)?;
1757
    csrf(&viewer, &f.csrf_token, &shell)?;
1758
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d0fbea2e Andy McCall ↶ 1759
    super::writable(&row, &shell)?;
7d2eb590 Andy McCall ↶ 1760
    let p = pdb::get(&app.db, row.id, number)
1761
        .await
1762
        .map_err(|e| Error::from_db(shell.clone(), e))?
1763
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1764
    if Some(me.account.id) != p.author_id && role < Role::Maintain {
1765
        return Err(Error::not_found(shell));
1766
    }
1767
    let Some(a) = crate::assistants::enabled_for_repo(&app.db, &row)
1768
        .await
1769
        .map_err(|e| Error::from_db(shell.clone(), e))?
1770
        .into_iter()
1771
        .find(|a| a.name.eq_ignore_ascii_case(f.assistant.trim()))
1772
    else {
1773
        return Ok(back(&owner, &name, number, "conversation", None, Some(format!("No assistant called {} here.", f.assistant.trim()))));
1774
    };
1775
    let loaded = crate::web::proposals::load(&app, &repo, p.clone()).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
1776
    let title = if f.title.trim().is_empty() { p.title.clone() } else { f.title.clone() };
1777
    let d = crate::assistants::Draft { slot: p.id, title: &title, target: &p.target, changes: &loaded.changes, diffs: &loaded.diffs };
1778
    let draft = crate::assistants::draft_description(&app, &row, &me.account, &a, d).await;
1779
    match draft {
1780
        Ok(text) => {
1781
            let mut page = detail(&app, shell, &viewer, &owner, &name, number, "conversation".into(), None, None).await?;
1782
            page.0.draft = Some(text);
1783
            Ok(page.into_response())
1784
        }
1785
        Err(why) => Ok(back(&owner, &name, number, "conversation", None, Some(format!("{} did not answer: {why}.", a.name)))),
cc1cd197 Andy McCall ↶ 1786
    }
1787
}
119fd17d Andy McCall ↶ 1788
1789
/// A draft being written, as server-sent events for the page: `part` with
1790
/// each piece of text, then `done` with the whole draft or `error` with
1791
/// why there is none (each a JSON string). The response starts at once, so
1792
/// a draft that takes minutes is not cut off by a proxy waiting for it
1793
/// (oxygenhub#248).
1794
type DraftEvents = axum::response::Sse<
1795
    axum::response::sse::KeepAliveStream<
1796
        tokio_stream::wrappers::ReceiverStream<Result<axum::response::sse::Event, std::convert::Infallible>>,
1797
    >,
1798
>;
1799
1800
fn draft_events(rx: tokio::sync::mpsc::Receiver<Result<axum::response::sse::Event, std::convert::Infallible>>) -> DraftEvents {
1801
    axum::response::Sse::new(tokio_stream::wrappers::ReceiverStream::new(rx))
1802
        .keep_alive(axum::response::sse::KeepAlive::new().interval(std::time::Duration::from_secs(15)))
1803
}
1804
1805
fn draft_event(kind: &str, text: &str) -> Result<axum::response::sse::Event, std::convert::Infallible> {
1806
    Ok(axum::response::sse::Event::default().event(kind).data(serde_json::to_string(text).unwrap_or_default()))
1807
}
1808
1809
/// Only an error, for a draft that cannot start.
1810
fn draft_refused(why: String) -> DraftEvents {
1811
    let (tx, rx) = tokio::sync::mpsc::channel(1);
1812
    let _ = tx.try_send(draft_event("error", &why));
1813
    draft_events(rx)
1814
}
1815
1816
/// What a draft is written from, owned so a task of its own can have it.
1817
struct DraftJob {
1818
    row: db::repos::RepoRow,
1819
    by: accounts::Account,
1820
    a: crate::assistants::Assistant,
1821
    slot: i64,
1822
    title: String,
1823
    target: String,
1824
    changes: Vec<ChangeView>,
1825
    diffs: Vec<oxy_core::repo::FileDiff>,
1826
}
1827
1828
/// Write the draft in a task of its own, its parts to the page.
1829
fn draft_in_background(app: Shared, job: DraftJob) -> DraftEvents {
1830
    let (tx, rx) = tokio::sync::mpsc::channel(64);
1831
    tokio::spawn(async move {
1832
        let DraftJob { row, by, a, slot, title, target, changes, diffs } = job;
1833
        let d = crate::assistants::Draft { slot, title: &title, target: &target, changes: &changes, diffs: &diffs };
1834
        let parts = tx.clone();
1835
        let result = crate::assistants::draft_description_streaming(&app, &row, &by, &a, d, move |p: &str| {
1836
            // A page that went away stops nothing: the draft finishes.
1837
            let _ = parts.try_send(draft_event("part", p));
1838
        })
1839
        .await;
1840
        let last = match result {
1841
            Ok(text) => draft_event("done", text.trim()),
1842
            Err(why) => draft_event("error", &format!("{} did not answer: {why}.", a.name)),
1843
        };
1844
        let _ = tx.send(last).await;
1845
    });
1846
    draft_events(rx)
1847
}
1848
1849
/// `POST /{owner}/{name}/proposal/{number}/draft/stream`: [`draft`], with
1850
/// the draft streamed to the page as it is written.
1851
pub async fn draft_stream(
1852
    State(app): State<Shared>,
1853
    viewer: Viewer,
1854
    Path((owner, name, number)): Path<(String, String, i64)>,
1855
    Form(f): Form<DraftForm>,
1856
) -> Result<DraftEvents, Error> {
1857
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposal/{number}"), &viewer);
1858
    let me = require(&viewer, &shell)?;
1859
    csrf(&viewer, &f.csrf_token, &shell)?;
1860
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1861
    super::writable(&row, &shell)?;
1862
    let p = pdb::get(&app.db, row.id, number)
1863
        .await
1864
        .map_err(|e| Error::from_db(shell.clone(), e))?
1865
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1866
    if Some(me.account.id) != p.author_id && role < Role::Maintain {
1867
        return Err(Error::not_found(shell));
1868
    }
1869
    let Some(a) = crate::assistants::enabled_for_repo(&app.db, &row)
1870
        .await
1871
        .map_err(|e| Error::from_db(shell.clone(), e))?
1872
        .into_iter()
1873
        .find(|a| a.name.eq_ignore_ascii_case(f.assistant.trim()))
1874
    else {
1875
        return Ok(draft_refused(format!("No assistant called {} here.", f.assistant.trim())));
1876
    };
1877
    let loaded = load(&app, &repo, p.clone()).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
1878
    let title = if f.title.trim().is_empty() { p.title.clone() } else { f.title.clone() };
1879
    let job = DraftJob {
1880
        row,
1881
        by: me.account.clone(),
1882
        a,
1883
        slot: p.id,
1884
        title,
1885
        target: p.target.clone(),
1886
        changes: loaded.changes,
1887
        diffs: loaded.diffs,
1888
    };
1889
    Ok(draft_in_background(app.clone(), job))
1890
}
1891
1892
/// `POST /{owner}/{name}/proposals/new/draft/stream`: [`new_draft`], with
1893
/// the draft streamed to the page as it is written.
1894
pub async fn new_draft_stream(
1895
    State(app): State<Shared>,
1896
    viewer: Viewer,
1897
    Path((owner, name)): Path<(String, String)>,
1898
    Form(f): Form<NewForm>,
1899
) -> Result<DraftEvents, Error> {
1900
    let shell = Shell::new(&app, &format!("/{owner}/{name}/proposals/new"), &viewer);
1901
    let me = require(&viewer, &shell)?;
1902
    csrf(&viewer, &f.csrf_token, &shell)?;
1903
    let (repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1904
    super::writable(&row, &shell)?;
1905
    let Some(a) = crate::assistants::enabled_for_repo(&app.db, &row)
1906
        .await
1907
        .unwrap_or_default()
1908
        .into_iter()
1909
        .find(|a| a.name.eq_ignore_ascii_case(f.assistant.trim()))
1910
    else {
1911
        return Ok(draft_refused(format!("No assistant called {} here.", f.assistant.trim())));
1912
    };
1913
    let (changes, diffs) = match preview_diff(&app, &repo, &f.target, &f.source).await {
1914
        Ok(x) => x,
1915
        Err(e) => return Ok(draft_refused(e.to_string())),
1916
    };
1917
    if changes.is_empty() {
1918
        return Ok(draft_refused("Nothing to describe: the source adds nothing to the target.".into()));
1919
    }
1920
    let job = DraftJob { slot: -row.id, row, by: me.account.clone(), a, title: f.title.clone(), target: f.target.clone(), changes, diffs };
1921
    Ok(draft_in_background(app.clone(), job))
1922
}