forge
Explore
Log in

Don't you dare go Hollow

Site-wide alignment audit

Browse files at this commit

63d7a81e3335bba01a4040cd6d98b432618455ceAhmet Kaan GümüşParent: d30dc31
  • ui
    • site-wide alignment audit
  • ci
    • parallel jobs with fail fast
Show full message
💄 ui: site-wide alignment audit; 👷 ci: parallel jobs with fail fast

- CI: test and build run in parallel; a failing job cancels the rest of the run.
  Releases and self-update require the whole run to succeed.
- Waterfall draws dependency connectors instead of "needs X" subtitles.
- Screenshot audit harness (scripts/audit) in headless Chromium, all routes,
  desktop and mobile, light and dark.
- Alignment fixes across repo, issues/PRs, CI, settings, admin, auth, profile,
  orgs, wiki and snippets; select text centring; heatmap empty vs 1-commit contrast.
- Profile repositories tab: rich rows, sort, DB-side paging, live search.
- Org pages get their own section sidebar; Settings shown to owners only.
- Styled 404 page; no em dashes in UI copy.

101 changed files +4837 -862

.forge/ci.tomlmodified+5 -2
@@ -1,7 +1,11 @@
11 # CI for forge itself. Format: docs/ci.md, parser: crates/forge-ci/src/config.rs.
22 #
33 # The workflow has no branch condition, so the build job also runs for pull requests.
4-# A tag push matching "v*" that passes every job publishes a release with the build job's binaries and SHA256SUMS.
4+# test and build have no `needs` between them, so they run in parallel when runner capacity allows
5+# (two runners, or one runner with concurrency = 2). The build job's artifacts are still only used
6+# once the whole run is green: a tag push matching "v*" publishes a release with the build job's
7+# binaries and SHA256SUMS, and self-update deploys dist/forge, only when every job in the run,
8+# including test, succeeded.
59
610 [on]
711 push = ["main"]
@@ -21,7 +25,6 @@ timeout_minutes = 120
2125
2226 [jobs.build]
2327 image = "docker.io/library/rust:1"
24-needs = ["test"]
2528 # Runner has a few GB RAM and 2 CPUs: rustc runs one crate at a time because a single forge-web compile needs several GB.
2629 env = { CARGO_BUILD_JOBS = "1", CARGO_INCREMENTAL = "0" }
2730 run = """
crates/forge-ci/src/config.rsmodified+11 -3
@@ -216,7 +216,7 @@ pub fn parse_config(text: &str) -> Result<CiConfig, ConfigError> {
216216 // serde_ignored marks `Option` wrappers with `?`; they are not part of the key path.
217217 let path = path.to_string().replace("?.", "");
218218 warnings.push(format!(
219- "unknown key `{path}` ignored \u{2014} this forge may be older than your ci.toml"
219+ "unknown key `{path}` ignored: this forge may be older than your ci.toml"
220220 ));
221221 })
222222 .map_err(|e| ConfigError::Toml(e.to_string()))?;
@@ -715,7 +715,11 @@ artifacts = ["target/release/forge"]
715715
716716 let cfg = parse_config(&job_toml("bogus = 1")).unwrap();
717717 assert_eq!(cfg.warnings.len(), 1);
718- assert!(cfg.warnings[0].contains("`jobs.build.bogus`"), "{:?}", cfg.warnings);
718+ assert!(
719+ cfg.warnings[0].contains("`jobs.build.bogus`"),
720+ "{:?}",
721+ cfg.warnings
722+ );
719723 assert_eq!(cfg.jobs.len(), 1);
720724
721725 let cfg = parse_config(&format!("{}\n[other]\nx = 1\n", job_toml(""))).unwrap();
@@ -1194,7 +1198,11 @@ artifacts = ["target/release/forge"]
11941198 fn release_unknown_keys_are_ignored_with_a_warning() {
11951199 let cfg = parse_config(&release_toml("bogus = 1")).unwrap();
11961200 assert_eq!(cfg.warnings.len(), 1);
1197- assert!(cfg.warnings[0].contains("`release.bogus`"), "{:?}", cfg.warnings);
1201+ assert!(
1202+ cfg.warnings[0].contains("`release.bogus`"),
1203+ "{:?}",
1204+ cfg.warnings
1205+ );
11981206 assert!(cfg.release.is_some());
11991207 }
12001208
crates/forge-core/src/store/ci.rsmodified+74 -1
@@ -712,7 +712,8 @@ impl Store {
712712 }
713713
714714 /// Finishes a job with a terminal state. Dependants are then unblocked or skipped, and the
715- /// run state is recomputed. Returns the run. `Conflict` if the job already finished.
715+ /// run state is recomputed. A `Failure` or `Error` fails the run fast: the run's queued and
716+ /// blocked jobs are cancelled and its running jobs get `cancel_requested`. Returns the run. `Conflict` if the job already finished.
716717 pub async fn finish_job(
717718 &self,
718719 job_id: &str,
@@ -747,6 +748,23 @@ impl Store {
747748 .await
748749 .map_err(db_err)?;
749750 propagate(&tx, &job.run_id, &now).await?;
751+ if matches!(state, JobState::Failure | JobState::Error) {
752+ // Fail fast: the run cannot succeed any more, so stop the sibling jobs now.
753+ tx.execute(
754+ "UPDATE ci_jobs SET state = 'cancelled', finished_at = ?2 \
755+ WHERE run_id = ?1 AND state IN ('queued', 'blocked')",
756+ (job.run_id.clone(), now.clone()),
757+ )
758+ .await
759+ .map_err(db_err)?;
760+ tx.execute(
761+ "UPDATE ci_jobs SET cancel_requested = 1 \
762+ WHERE run_id = ?1 AND state = 'running'",
763+ (job.run_id.clone(),),
764+ )
765+ .await
766+ .map_err(db_err)?;
767+ }
750768 recompute_run(&tx, &job.run_id, &now).await?;
751769 load_run(&tx, &job.run_id).await?.ok_or_else(missing_row)
752770 }
@@ -1697,6 +1715,61 @@ mod tests {
16971715 assert_eq!(done.state, RunState::Failure);
16981716 }
16991717
1718+ #[tokio::test]
1719+ async fn failure_fails_fast_cancelling_running_and_queued_siblings() {
1720+ let fx = fixture().await;
1721+ let run = create(
1722+ &fx.store,
1723+ &fx.repo.id,
1724+ &fx.tahinli.id,
1725+ &[
1726+ job("test", &[], &[]),
1727+ job("build", &[], &[]),
1728+ job("docs", &["build"], &[]),
1729+ ],
1730+ false,
1731+ )
1732+ .await;
1733+ let runner = bare_runner(&[]);
1734+ let first = fx.store.claim_job(&runner).await.unwrap().unwrap();
1735+ let second = fx.store.claim_job(&runner).await.unwrap().unwrap();
1736+ let (test, build) = if first.0.name == "test" {
1737+ (first, second)
1738+ } else {
1739+ (second, first)
1740+ };
1741+ let after = fx
1742+ .store
1743+ .finish_job(&test.0.id, JobState::Failure, Some(1), None)
1744+ .await
1745+ .unwrap();
1746+ assert_eq!(
1747+ after.state,
1748+ RunState::Running,
1749+ "build is still winding down"
1750+ );
1751+ let build_now = job_named(&fx.store, &run.id, "build").await;
1752+ assert!(build_now.cancel_requested);
1753+ assert!(fx.store.heartbeat(&build.0.id).await.unwrap());
1754+ assert!(
1755+ job_named(&fx.store, &run.id, "docs")
1756+ .await
1757+ .state
1758+ .is_terminal()
1759+ );
1760+
1761+ let done = fx
1762+ .store
1763+ .finish_job(&build.0.id, JobState::Cancelled, None, None)
1764+ .await
1765+ .unwrap();
1766+ assert_eq!(done.state, RunState::Failure);
1767+ assert_eq!(
1768+ job_named(&fx.store, &run.id, "build").await.state,
1769+ JobState::Cancelled
1770+ );
1771+ }
1772+
17001773 #[tokio::test]
17011774 async fn cancel_queued_and_running_jobs() {
17021775 let fx = fixture().await;
crates/forge-core/src/store/contributions.rsmodified+17 -3
@@ -70,7 +70,10 @@ mod tests {
7070 async fn counts_pushes_issues_pulls_and_comments_per_day() {
7171 let dir = tempfile::tempdir().unwrap();
7272 let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
73- let tahinli = store.create_user("tahinli", None, "x", false).await.unwrap();
73+ let tahinli = store
74+ .create_user("tahinli", None, "x", false)
75+ .await
76+ .unwrap();
7477 let bob = store.create_user("bob", None, "x", false).await.unwrap();
7578 let demo = store
7679 .create_repo(&tahinli.id, "demo", "", Visibility::Public, "main")
@@ -102,12 +105,23 @@ mod tests {
102105 .unwrap();
103106 let pull = store
104107 .create_pull(
105- &demo.id, &tahinli.id, "change", "", "main", &demo.id, "topic", OID, OID,
108+ &demo.id,
109+ &tahinli.id,
110+ "change",
111+ "",
112+ "main",
113+ &demo.id,
114+ "topic",
115+ OID,
116+ OID,
106117 )
107118 .await
108119 .unwrap();
109120 set_created_at(&store, "issues", &pull.issue.id, day2).await;
110- let comment = store.add_comment(&issue.id, &tahinli.id, "hi").await.unwrap();
121+ let comment = store
122+ .add_comment(&issue.id, &tahinli.id, "hi")
123+ .await
124+ .unwrap();
111125 set_created_at(&store, "comments", &comment.id, day2).await;
112126
113127 // Before `since`, and someone else's activity: left out.
crates/forge-core/src/store/issues.rsmodified+5 -1
@@ -1653,7 +1653,11 @@ mod tests {
16531653 #[tokio::test]
16541654 async fn usernames_by_ids_is_batched_and_skips_unknown() {
16551655 let fx = fixture().await;
1656- let ids = vec![fx.tahinli.id.clone(), fx.bob.id.clone(), "nobody".to_string()];
1656+ let ids = vec![
1657+ fx.tahinli.id.clone(),
1658+ fx.bob.id.clone(),
1659+ "nobody".to_string(),
1660+ ];
16571661 let map = fx.store.usernames_by_ids(&ids).await.unwrap();
16581662 assert_eq!(map.len(), 2);
16591663 assert_eq!(map[&fx.tahinli.id].0, "Tahinli");
crates/forge-core/src/store/labels.rsmodified+10 -2
@@ -1006,7 +1006,11 @@ mod tests {
10061006 .unwrap();
10071007
10081008 let err = s
1009- .set_issue_labels(&issue.id, &fx.tahinli.id, &[b.id.clone(), foreign.id.clone()])
1009+ .set_issue_labels(
1010+ &issue.id,
1011+ &fx.tahinli.id,
1012+ &[b.id.clone(), foreign.id.clone()],
1013+ )
10101014 .await;
10111015 assert!(matches!(err, Err(Error::Invalid(_))));
10121016 assert_eq!(names(&s.issue_labels(&issue.id).await.unwrap()), ["a"]);
@@ -1027,7 +1031,11 @@ mod tests {
10271031 .create_issue(&fx.repo.id, &fx.tahinli.id, "t", "")
10281032 .await
10291033 .unwrap();
1030- let input = ["bob".to_string(), "BOB".to_string(), " Tahinli ".to_string()];
1034+ let input = [
1035+ "bob".to_string(),
1036+ "BOB".to_string(),
1037+ " Tahinli ".to_string(),
1038+ ];
10311039 s.set_issue_assignees(&issue.id, &fx.tahinli.id, &input)
10321040 .await
10331041 .unwrap();
crates/forge-core/src/store/lfs.rsmodified+4 -1
@@ -60,7 +60,10 @@ mod tests {
6060
6161 async fn repo_fixture(dir: &tempfile::TempDir) -> (Store, String, String) {
6262 let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
63- let user = store.create_user("tahinli", None, "h", false).await.unwrap();
63+ let user = store
64+ .create_user("tahinli", None, "h", false)
65+ .await
66+ .unwrap();
6467 let repo = store
6568 .create_repo(&user.id, "demo", "", Visibility::Public, "main")
6669 .await
crates/forge-core/src/store/mod.rsmodified+16 -46
@@ -5,8 +5,8 @@ pub mod advisories;
55 pub mod audit;
66 pub mod backup_runs;
77 pub mod ci;
8-pub mod contributions;
98 pub mod commit_status;
9+pub mod contributions;
1010 pub mod discussions;
1111 pub mod edit_history_read;
1212 pub mod issues;
@@ -26,6 +26,7 @@ pub mod push_recent;
2626 pub mod reactions;
2727 pub mod releases;
2828 pub mod replication;
29+pub mod repo_listing;
2930 pub mod reviews;
3031 pub mod signatures;
3132 pub mod snapshot;
@@ -2412,7 +2413,8 @@ impl Store {
24122413 /// One page of public repos, optionally filtered by `query`. The query matches the repo name
24132414 /// or description, case-insensitively, as a plain substring: `%`, `_` and `\` are literal.
24142415 /// Each row carries the star count and the last activity time (the latest push, or the
2415- /// creation time). Returns the rows for `page` (1-based) and the total number of matches.
2416+ /// creation time). Returns the rows for `page` (1-based, clamped to the last page) and the
2417+ /// total number of matches.
24162418 pub async fn list_public_repos(
24172419 &self,
24182420 query: Option<&str>,
@@ -2420,10 +2422,6 @@ impl Store {
24202422 page: u64,
24212423 per_page: u64,
24222424 ) -> Result<(Vec<ListedRepo>, u64)> {
2423- const ACTIVITY: &str = "COALESCE((SELECT MAX(p.created_at) FROM push_events p \
2424- WHERE p.repo_id = r.id), r.created_at)";
2425- const STARS: &str = "(SELECT COUNT(*) FROM stars s WHERE s.repo_id = r.id)";
2426-
24272425 let mut clauses: Vec<&str> = vec!["r.visibility = 'public'"];
24282426 let mut params: Vec<Value> = Vec::new();
24292427 if let Some(q) = query.map(str::trim).filter(|q| !q.is_empty()) {
@@ -2434,46 +2432,15 @@ impl Store {
24342432 params.push(Value::Text(pattern.clone()));
24352433 params.push(Value::Text(pattern));
24362434 }
2437- let where_sql = clauses.join(" AND ");
2438- let order = match sort {
2439- RepoSort::RecentlyUpdated => format!("{ACTIVITY} DESC, r.name_folded ASC"),
2440- RepoSort::MostStars => format!("{STARS} DESC, r.name_folded ASC"),
2441- RepoSort::Name => "r.name_folded ASC".to_owned(),
2442- };
2443- let per_page = per_page.clamp(1, 100);
2444- let page = page.clamp(1, 100_000);
2445- let offset = i64::try_from((page - 1) * per_page).unwrap_or(i64::MAX);
2446-
2447- let conn = self.read_conn().await;
2448- let total = fetch_opt(
2449- &conn,
2450- &format!(
2451- "SELECT COUNT(*) FROM repos r JOIN users u ON u.id = r.owner_id WHERE {where_sql}"
2452- ),
2453- params.clone(),
2454- |row| col_int(row, 0),
2435+ self.page_of_repos(
2436+ "repos r JOIN users u ON u.id = r.owner_id",
2437+ &clauses.join(" AND "),
2438+ params,
2439+ sort,
2440+ page,
2441+ per_page,
24552442 )
2456- .await?
2457- .unwrap_or(0);
2458-
2459- let mut page_params = params;
2460- page_params.push(Value::Integer(i64::try_from(per_page).unwrap_or(100)));
2461- page_params.push(Value::Integer(offset));
2462- let rows = fetch_all(
2463- &conn,
2464- &format!(
2465- "SELECT {REPO_COLS}, {STARS} AS stars, {ACTIVITY} AS activity \
2466- FROM repos r JOIN users u ON u.id = r.owner_id \
2467- WHERE {where_sql} ORDER BY {order} LIMIT ? OFFSET ?"
2468- ),
2469- page_params,
2470- |row| {
2471- let stars = u64::try_from(col_int(row, 10)?).unwrap_or(0);
2472- Ok((map_repo(row)?, stars, col_text(row, 11)?))
2473- },
2474- )
2475- .await?;
2476- Ok((rows, u64::try_from(total).unwrap_or(0)))
2443+ .await
24772444 }
24782445 }
24792446
@@ -2484,7 +2451,10 @@ mod security_tests {
24842451 async fn store_with_user() -> (Store, User, tempfile::TempDir) {
24852452 let dir = tempfile::tempdir().unwrap();
24862453 let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
2487- let user = store.create_user("tahinli", None, "h", false).await.unwrap();
2454+ let user = store
2455+ .create_user("tahinli", None, "h", false)
2456+ .await
2457+ .unwrap();
24882458 (store, user, dir)
24892459 }
24902460
crates/forge-core/src/store/notifications.rsmodified+32 -11
@@ -531,9 +531,14 @@ mod tests {
531531 async fn subscribers_lists_only_subscribed() {
532532 let fx = fixture().await;
533533 let s = &fx.store;
534- s.subscribe(&fx.tahinli, &fx.issue_a, SubState::Subscribed, Reason::Assign)
535- .await
536- .unwrap();
534+ s.subscribe(
535+ &fx.tahinli,
536+ &fx.issue_a,
537+ SubState::Subscribed,
538+ Reason::Assign,
539+ )
540+ .await
541+ .unwrap();
537542 s.subscribe(&fx.bob, &fx.issue_a, SubState::Ignored, Reason::Subscribed)
538543 .await
539544 .unwrap();
@@ -568,7 +573,10 @@ mod tests {
568573 )
569574 .await
570575 .unwrap();
571- assert_eq!(reason_of(s, &fx.tahinli, &fx.issue_a).await, Reason::Mention);
576+ assert_eq!(
577+ reason_of(s, &fx.tahinli, &fx.issue_a).await,
578+ Reason::Mention
579+ );
572580 assert_eq!(s.unread_count(&fx.tahinli).await.unwrap(), 1);
573581
574582 s.mark_issue_read(&fx.tahinli, &fx.issue_a).await.unwrap();
@@ -583,7 +591,10 @@ mod tests {
583591 )
584592 .await
585593 .unwrap();
586- assert_eq!(reason_of(s, &fx.tahinli, &fx.issue_a).await, Reason::Comment);
594+ assert_eq!(
595+ reason_of(s, &fx.tahinli, &fx.issue_a).await,
596+ Reason::Comment
597+ );
587598 assert_eq!(s.unread_count(&fx.tahinli).await.unwrap(), 1);
588599
589600 // A stronger reason while unread still wins.
@@ -806,9 +817,14 @@ mod tests {
806817 s.set_watch(&fx.tahinli, &fx.repo, WatchLevel::Watching)
807818 .await
808819 .unwrap();
809- s.subscribe(&fx.tahinli, &fx.issue_a, SubState::Subscribed, Reason::Author)
810- .await
811- .unwrap();
820+ s.subscribe(
821+ &fx.tahinli,
822+ &fx.issue_a,
823+ SubState::Subscribed,
824+ Reason::Author,
825+ )
826+ .await
827+ .unwrap();
812828 s.upsert_notification(
813829 &fx.tahinli,
814830 &fx.repo,
@@ -859,9 +875,14 @@ mod tests {
859875 s.set_watch(&fx.tahinli, &fx.repo, WatchLevel::Watching)
860876 .await
861877 .unwrap();
862- s.subscribe(&fx.tahinli, &fx.issue_a, SubState::Subscribed, Reason::Author)
863- .await
864- .unwrap();
878+ s.subscribe(
879+ &fx.tahinli,
880+ &fx.issue_a,
881+ SubState::Subscribed,
882+ Reason::Author,
883+ )
884+ .await
885+ .unwrap();
865886 // Bob's inbox row whose last actor is Tahinli, and Tahinli's own inbox row.
866887 s.upsert_notification(
867888 &fx.bob,
crates/forge-core/src/store/pinned.rsmodified+4 -1
@@ -119,7 +119,10 @@ mod tests {
119119 async fn fixture() -> (Store, User, String, tempfile::TempDir) {
120120 let dir = tempfile::tempdir().unwrap();
121121 let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
122- let tahinli = store.create_user("tahinli", None, "h", false).await.unwrap();
122+ let tahinli = store
123+ .create_user("tahinli", None, "h", false)
124+ .await
125+ .unwrap();
123126 let repo = store
124127 .create_repo(&tahinli.id, "forge", "", Visibility::Public, "main")
125128 .await
crates/forge-core/src/store/push_recent.rsmodified+6 -2
@@ -8,7 +8,8 @@ use crate::model::Id;
88
99 /// The all-zero object ids that mark a ref deletion: SHA-1 (40 digits) and SHA-256 (64 digits).
1010 pub(super) const ZERO_OID_SHA1: &str = "0000000000000000000000000000000000000000";
11-pub(super) const ZERO_OID_SHA256: &str = "0000000000000000000000000000000000000000000000000000000000000000";
11+pub(super) const ZERO_OID_SHA256: &str =
12+ "0000000000000000000000000000000000000000000000000000000000000000";
1213
1314 impl Store {
1415 /// Branches `pusher_id` pushed to in any of `repo_ids` at or after `since` (an RFC 3339
@@ -99,7 +100,10 @@ mod tests {
99100 async fn store_with_repos() -> (tempfile::TempDir, Store, Id, Id, Id, Id) {
100101 let dir = tempfile::tempdir().unwrap();
101102 let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
102- let tahinli = store.create_user("tahinli", None, "x", false).await.unwrap();
103+ let tahinli = store
104+ .create_user("tahinli", None, "x", false)
105+ .await
106+ .unwrap();
103107 let bob = store.create_user("bob", None, "x", false).await.unwrap();
104108 let demo = store
105109 .create_repo(&tahinli.id, "demo", "", Visibility::Public, "main")
crates/forge-core/src/store/repo_listing.rsadded+409 -0
@@ -0,0 +1,409 @@
1+//! Paged repo listings filtered in SQL: the public listing (`/explore`) and the profile tabs (a
2+//! user's repos, a user's stars). Read access is decided in the query with the same rules as
3+//! `authz::authorize` for `Action::Read`, so no per-repo role lookup is needed.
4+
5+use turso::Value;
6+
7+use super::{
8+ ListedRepo, REPO_COLS, RepoSort, Store, col_int, col_text, fetch_all, fetch_opt, issues,
9+ map_repo,
10+};
11+use crate::error::Result;
12+use crate::model::User;
13+
14+/// Whose repos a profile tab lists.
15+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16+pub enum RepoScope<'a> {
17+ /// The repos owned by this user or organization id.
18+ OwnedBy(&'a str),
19+ /// The repos this user id has starred.
20+ StarredBy(&'a str),
21+}
22+
23+/// The last activity time of `r`: its latest push, or its creation time.
24+const ACTIVITY: &str = "COALESCE((SELECT MAX(p.created_at) FROM push_events p \
25+ WHERE p.repo_id = r.id), r.created_at)";
26+/// The star count of `r`.
27+const STARS: &str = "(SELECT COUNT(*) FROM stars s WHERE s.repo_id = r.id)";
28+
29+/// The SQL condition under which a signed-in, non-admin viewer may read repo `r`, taking the
30+/// viewer id four times (bind it as four `?` parameters). It mirrors `authorize` for Read:
31+/// public repos, the viewer's own repos, repos where the viewer is a collaborator, and repos of an
32+/// org where the viewer's org role (`Store::org_repo_role`) is some role: an org owner, a member
33+/// when the default repo role is not `none`, or a member of a team covering the repo.
34+const READABLE_BY_VIEWER: &str = "(r.visibility = 'public' OR r.owner_id = ? \
35+ OR EXISTS (SELECT 1 FROM collaborators c WHERE c.repo_id = r.id AND c.user_id = ?) \
36+ OR EXISTS (SELECT 1 FROM org_members m WHERE m.org_id = r.owner_id AND m.user_id = ? AND ( \
37+ m.role = 'owner' \
38+ OR EXISTS (SELECT 1 FROM org_settings os WHERE os.org_id = r.owner_id \
39+ AND os.default_repo_role <> 'none') \
40+ OR EXISTS (SELECT 1 FROM teams t JOIN team_members tm ON tm.team_id = t.id \
41+ WHERE t.org_id = r.owner_id AND tm.user_id = ? AND (t.all_repos = 1 \
42+ OR EXISTS (SELECT 1 FROM team_repos tr WHERE tr.team_id = t.id \
43+ AND tr.repo_id = r.id))))))";
44+
45+impl Store {
46+ /// One page of a profile tab: the repos in `scope` that `viewer` may read, optionally
47+ /// filtered by `query` (a case-insensitive substring of the name; `%`, `_` and `\` are
48+ /// literal), in `sort` order. Rows carry the star count and the last activity time. A page
49+ /// past the end is clamped to the last page. Returns the rows and the number of matches.
50+ pub async fn list_visible_repos(
51+ &self,
52+ scope: RepoScope<'_>,
53+ viewer: Option<&User>,
54+ query: Option<&str>,
55+ sort: RepoSort,
56+ page: u64,
57+ per_page: u64,
58+ ) -> Result<(Vec<ListedRepo>, u64)> {
59+ let (from_sql, mut clauses, mut params) = scoped(scope, viewer);
60+ if let Some(q) = query.map(str::trim).filter(|q| !q.is_empty()) {
61+ clauses.push("LOWER(r.name) LIKE ? ESCAPE '\\'");
62+ params.push(Value::Text(issues::like_pattern(&q.to_lowercase())));
63+ }
64+ self.page_of_repos(
65+ from_sql,
66+ &clauses.join(" AND "),
67+ params,
68+ sort,
69+ page,
70+ per_page,
71+ )
72+ .await
73+ }
74+
75+ /// How many repos in `scope` the viewer may read, with no name filter (the tab counts).
76+ pub async fn count_visible_repos(
77+ &self,
78+ scope: RepoScope<'_>,
79+ viewer: Option<&User>,
80+ ) -> Result<u64> {
81+ let (from_sql, clauses, params) = scoped(scope, viewer);
82+ let conn = self.read_conn().await;
83+ let n = fetch_opt(
84+ &conn,
85+ &format!(
86+ "SELECT COUNT(*) FROM {from_sql} WHERE {}",
87+ clauses.join(" AND ")
88+ ),
89+ params,
90+ |row| col_int(row, 0),
91+ )
92+ .await?
93+ .unwrap_or(0);
94+ Ok(u64::try_from(n).unwrap_or(0))
95+ }
96+
97+ /// One page of the repos `from_sql` (which joins `repos r` and its owner `users u`) yields
98+ /// under `where_sql`, in `sort` order, with the total match count. `page` is 1-based and is
99+ /// clamped to the last page; `per_page` to 1..=100.
100+ pub(super) async fn page_of_repos(
101+ &self,
102+ from_sql: &str,
103+ where_sql: &str,
104+ params: Vec<Value>,
105+ sort: RepoSort,
106+ page: u64,
107+ per_page: u64,
108+ ) -> Result<(Vec<ListedRepo>, u64)> {
109+ let order = match sort {
110+ RepoSort::RecentlyUpdated => format!("{ACTIVITY} DESC, r.name_folded ASC, r.id"),
111+ RepoSort::MostStars => format!("{STARS} DESC, r.name_folded ASC, r.id"),
112+ RepoSort::Name => "r.name_folded ASC, u.username_folded ASC, r.id".to_owned(),
113+ };
114+ let per_page = per_page.clamp(1, 100);
115+
116+ let conn = self.read_conn().await;
117+ let total = fetch_opt(
118+ &conn,
119+ &format!("SELECT COUNT(*) FROM {from_sql} WHERE {where_sql}"),
120+ params.clone(),
121+ |row| col_int(row, 0),
122+ )
123+ .await?
124+ .unwrap_or(0);
125+ let total = u64::try_from(total).unwrap_or(0);
126+ let pages = total.div_ceil(per_page).max(1);
127+ let page = page.clamp(1, pages);
128+ let offset = i64::try_from((page - 1) * per_page).unwrap_or(i64::MAX);
129+
130+ let mut page_params = params;
131+ page_params.push(Value::Integer(i64::try_from(per_page).unwrap_or(100)));
132+ page_params.push(Value::Integer(offset));
133+ let rows = fetch_all(
134+ &conn,
135+ &format!(
136+ "SELECT {REPO_COLS}, {STARS} AS stars, {ACTIVITY} AS activity \
137+ FROM {from_sql} WHERE {where_sql} ORDER BY {order} LIMIT ? OFFSET ?"
138+ ),
139+ page_params,
140+ |row| {
141+ let stars = u64::try_from(col_int(row, 10)?).unwrap_or(0);
142+ Ok((map_repo(row)?, stars, col_text(row, 11)?))
143+ },
144+ )
145+ .await?;
146+ Ok((rows, total))
147+ }
148+}
149+
150+/// The FROM clause, the WHERE clauses and their parameters for `scope` as seen by `viewer`.
151+fn scoped(
152+ scope: RepoScope<'_>,
153+ viewer: Option<&User>,
154+) -> (&'static str, Vec<&'static str>, Vec<Value>) {
155+ let (from_sql, scope_id) = match scope {
156+ RepoScope::OwnedBy(id) => ("repos r JOIN users u ON u.id = r.owner_id", id),
157+ RepoScope::StarredBy(id) => (
158+ "stars st JOIN repos r ON r.id = st.repo_id JOIN users u ON u.id = r.owner_id",
159+ id,
160+ ),
161+ };
162+ let mut clauses = vec![match scope {
163+ RepoScope::OwnedBy(_) => "r.owner_id = ?",
164+ RepoScope::StarredBy(_) => "st.user_id = ?",
165+ }];
166+ let mut params = vec![Value::Text(scope_id.to_owned())];
167+ match viewer {
168+ // Admins read everything.
169+ Some(user) if user.is_admin => {}
170+ Some(user) => {
171+ clauses.push(READABLE_BY_VIEWER);
172+ for _ in 0..4 {
173+ params.push(Value::Text(user.id.clone()));
174+ }
175+ }
176+ None => clauses.push("r.visibility = 'public'"),
177+ }
178+ (from_sql, clauses, params)
179+}
180+
181+#[cfg(test)]
182+mod tests {
183+ use super::*;
184+ use crate::model::{Role, Visibility};
185+ use crate::store::orgs::{DefaultRepoRole, OrgMemberRole, OrgSettings};
186+
187+ struct Fixture {
188+ store: Store,
189+ owner: User,
190+ _dir: tempfile::TempDir,
191+ }
192+
193+ async fn names(store: &Store, scope: RepoScope<'_>, viewer: Option<&User>) -> Vec<String> {
194+ let (rows, total) = store
195+ .list_visible_repos(scope, viewer, None, RepoSort::Name, 1, 100)
196+ .await
197+ .unwrap();
198+ assert_eq!(total, rows.len() as u64);
199+ assert_eq!(
200+ store.count_visible_repos(scope, viewer).await.unwrap(),
201+ total
202+ );
203+ rows.into_iter().map(|(repo, _, _)| repo.name).collect()
204+ }
205+
206+ /// Tahinli owns `open` (public), `closed` and `shared` (private).
207+ async fn fixture() -> Fixture {
208+ let dir = tempfile::tempdir().unwrap();
209+ let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
210+ let owner = store
211+ .create_user("tahinli", None, "h", false)
212+ .await
213+ .unwrap();
214+ for (name, vis) in [
215+ ("open", Visibility::Public),
216+ ("closed", Visibility::Private),
217+ ("shared", Visibility::Private),
218+ ] {
219+ store
220+ .create_repo(&owner.id, name, "", vis, "main")
221+ .await
222+ .unwrap();
223+ }
224+ Fixture {
225+ store,
226+ owner,
227+ _dir: dir,
228+ }
229+ }
230+
231+ async fn repo_id(store: &Store, owner: &str, name: &str) -> String {
232+ store
233+ .repo_by_owner_and_name(owner, name)
234+ .await
235+ .unwrap()
236+ .unwrap()
237+ .id
238+ }
239+
240+ #[tokio::test]
241+ async fn strangers_and_anonymous_viewers_never_see_private_repos() {
242+ let fx = fixture().await;
243+ let stranger = fx
244+ .store
245+ .create_user("mira", None, "h", false)
246+ .await
247+ .unwrap();
248+ let scope = RepoScope::OwnedBy(&fx.owner.id);
249+ assert_eq!(names(&fx.store, scope, None).await, ["open"]);
250+ assert_eq!(names(&fx.store, scope, Some(&stranger)).await, ["open"]);
251+ assert_eq!(
252+ names(&fx.store, scope, Some(&fx.owner)).await,
253+ ["closed", "open", "shared"]
254+ );
255+ }
256+
257+ #[tokio::test]
258+ async fn a_collaborator_sees_the_private_repo_they_work_on() {
259+ let fx = fixture().await;
260+ let carol = fx
261+ .store
262+ .create_user("carol", None, "h", false)
263+ .await
264+ .unwrap();
265+ let shared = repo_id(&fx.store, "tahinli", "shared").await;
266+ fx.store
267+ .set_collaborator(&shared, &carol.id, Role::Read)
268+ .await
269+ .unwrap();
270+ let scope = RepoScope::OwnedBy(&fx.owner.id);
271+ assert_eq!(
272+ names(&fx.store, scope, Some(&carol)).await,
273+ ["open", "shared"]
274+ );
275+ }
276+
277+ #[tokio::test]
278+ async fn an_admin_sees_everything() {
279+ let fx = fixture().await;
280+ let admin = fx.store.create_user("root", None, "h", true).await.unwrap();
281+ let scope = RepoScope::OwnedBy(&fx.owner.id);
282+ assert_eq!(
283+ names(&fx.store, scope, Some(&admin)).await,
284+ ["closed", "open", "shared"]
285+ );
286+ }
287+
288+ /// The org repos `viewer` sees are `expected`, and the SQL rule agrees with `authorize` on
289+ /// every org repo.
290+ async fn check_org(store: &Store, org_id: &str, viewer: User, expected: &[&str]) {
291+ let got = names(store, RepoScope::OwnedBy(org_id), Some(&viewer)).await;
292+ assert_eq!(got, expected, "viewer {}", viewer.username);
293+ for repo in store.list_repos_by_owner(org_id).await.unwrap() {
294+ let role = store.collaborator_role(&repo.id, &viewer.id).await.unwrap();
295+ let org_role = store
296+ .org_repo_role(org_id, &viewer.id, &repo.id)
297+ .await
298+ .unwrap();
299+ let allowed = crate::authz::authorize(
300+ Some(&viewer),
301+ &repo,
302+ role,
303+ org_role,
304+ crate::authz::Action::Read,
305+ )
306+ .is_ok();
307+ assert_eq!(allowed, got.contains(&repo.name), "{}", repo.name);
308+ }
309+ }
310+
311+ #[tokio::test]
312+ async fn org_roles_match_org_repo_role() {
313+ let fx = fixture().await;
314+ let org = fx.store.create_org("acme", &fx.owner.id).await.unwrap();
315+ let member = fx
316+ .store
317+ .create_user("mira", None, "h", false)
318+ .await
319+ .unwrap();
320+ let outsider = fx.store.create_user("zed", None, "h", false).await.unwrap();
321+ fx.store
322+ .add_org_member(&org.id, &member.id, OrgMemberRole::Member)
323+ .await
324+ .unwrap();
325+ for name in ["infra", "web"] {
326+ fx.store
327+ .create_repo(&org.id, name, "", Visibility::Private, "main")
328+ .await
329+ .unwrap();
330+ }
331+ let check = |viewer: &User, expected: &'static [&'static str]| {
332+ check_org(&fx.store, &org.id, viewer.clone(), expected)
333+ };
334+
335+ // The default repo role is read: every member sees every org repo.
336+ check(&member, &["infra", "web"]).await;
337+ check(&outsider, &[]).await;
338+ check(&fx.owner, &["infra", "web"]).await;
339+
340+ // With no default role, a plain member sees only what a team grants.
341+ fx.store
342+ .set_org_settings(
343+ &org.id,
344+ OrgSettings {
345+ default_repo_role: DefaultRepoRole::None,
346+ members_can_create_repos: true,
347+ },
348+ )
349+ .await
350+ .unwrap();
351+ check(&member, &[]).await;
352+ let team = fx
353+ .store
354+ .create_team(&org.id, "ops", "", Role::Read, false)
355+ .await
356+ .unwrap();
357+ fx.store
358+ .add_team_member(&team.id, &member.id)
359+ .await
360+ .unwrap();
361+ check(&member, &[]).await;
362+ let infra = repo_id(&fx.store, "acme", "infra").await;
363+ fx.store.add_team_repo(&team.id, &infra).await.unwrap();
364+ check(&member, &["infra"]).await;
365+ // An org owner sees every org repo whatever the default.
366+ check(&fx.owner, &["infra", "web"]).await;
367+ // A team membership alone, without org membership, grants nothing.
368+ fx.store.add_team_member(&team.id, &outsider.id).await.ok();
369+ check(&outsider, &[]).await;
370+ }
371+
372+ #[tokio::test]
373+ async fn stars_scope_filters_search_and_pages() {
374+ let fx = fixture().await;
375+ let fan = fx
376+ .store
377+ .create_user("mira", None, "h", false)
378+ .await
379+ .unwrap();
380+ for name in ["open", "closed"] {
381+ let id = repo_id(&fx.store, "tahinli", name).await;
382+ fx.store.star(&fan.id, &id).await.unwrap();
383+ }
384+ let scope = RepoScope::StarredBy(&fan.id);
385+ assert_eq!(names(&fx.store, scope, None).await, ["open"]);
386+ assert_eq!(
387+ names(&fx.store, scope, Some(&fx.owner)).await,
388+ ["closed", "open"]
389+ );
390+
391+ let owned = RepoScope::OwnedBy(&fx.owner.id);
392+ let (rows, total) = fx
393+ .store
394+ .list_visible_repos(owned, Some(&fx.owner), Some("SH%"), RepoSort::Name, 1, 10)
395+ .await
396+ .unwrap();
397+ assert_eq!(total, 0, "% is literal");
398+ assert!(rows.is_empty());
399+ let (rows, total) = fx
400+ .store
401+ .list_visible_repos(owned, Some(&fx.owner), Some("O"), RepoSort::Name, 9, 1)
402+ .await
403+ .unwrap();
404+ // "closed" and "open" match; page 9 of 2 is clamped to the last page.
405+ assert_eq!(total, 2);
406+ assert_eq!(rows.len(), 1);
407+ assert_eq!(rows[0].0.name, "open");
408+ }
409+}
crates/forge-core/src/store/signatures.rsmodified+4 -1
@@ -392,7 +392,10 @@ mod tests {
392392 let got = store.cached_signatures(&repo, &oids[..1]).await.unwrap();
393393 assert_eq!(got[&oids[0]].status, SigStatus::Unverified);
394394
395- store.invalidate_signatures_for_user(&tahinli).await.unwrap();
395+ store
396+ .invalidate_signatures_for_user(&tahinli)
397+ .await
398+ .unwrap();
396399 let got = store.cached_signatures(&repo, &oids).await.unwrap();
397400 // signer rows and unknown_key rows are gone; the bad row stays.
398401 assert_eq!(got.len(), 1);
crates/forge-core/src/store/webhooks.rsmodified+6 -1
@@ -1234,7 +1234,12 @@ mod tests {
12341234 assert_eq!(count(&store, "webhook_deliveries").await, 1);
12351235 }
12361236
1237- async fn hook_at(store: &Store, tahinli: &User, repo: &crate::model::Repo, url: &str) -> Webhook {
1237+ async fn hook_at(
1238+ store: &Store,
1239+ tahinli: &User,
1240+ repo: &crate::model::Repo,
1241+ url: &str,
1242+ ) -> Webhook {
12381243 store
12391244 .create_webhook(
12401245 &repo.id,
crates/forge-core/tests/stars_store.rsmodified+20 -5
@@ -18,7 +18,10 @@ async fn open_store(path: &Path) -> Store {
1818 async fn star_and_unstar_round_trip_with_count() {
1919 let dir = tempfile::tempdir().unwrap();
2020 let store = open_store(&db_path(&dir)).await;
21- let tahinli = store.create_user("tahinli", None, "h", false).await.unwrap();
21+ let tahinli = store
22+ .create_user("tahinli", None, "h", false)
23+ .await
24+ .unwrap();
2225 let bob = store.create_user("bob", None, "h", false).await.unwrap();
2326 let repo = store
2427 .create_repo(&tahinli.id, "proj", "", Visibility::Public, "main")
@@ -46,7 +49,10 @@ async fn star_and_unstar_round_trip_with_count() {
4649 async fn delete_repo_removes_its_stars() {
4750 let dir = tempfile::tempdir().unwrap();
4851 let store = open_store(&db_path(&dir)).await;
49- let tahinli = store.create_user("tahinli", None, "h", false).await.unwrap();
52+ let tahinli = store
53+ .create_user("tahinli", None, "h", false)
54+ .await
55+ .unwrap();
5056 let repo = store
5157 .create_repo(&tahinli.id, "proj", "", Visibility::Public, "main")
5258 .await
@@ -63,7 +69,10 @@ async fn delete_repo_removes_its_stars() {
6369 async fn public_listing_hides_private_repos_and_matches_literally() {
6470 let dir = tempfile::tempdir().unwrap();
6571 let store = open_store(&db_path(&dir)).await;
66- let tahinli = store.create_user("tahinli", None, "h", false).await.unwrap();
72+ let tahinli = store
73+ .create_user("tahinli", None, "h", false)
74+ .await
75+ .unwrap();
6776 store
6877 .create_repo(&tahinli.id, "tools", "", Visibility::Public, "main")
6978 .await
@@ -126,7 +135,10 @@ async fn public_listing_hides_private_repos_and_matches_literally() {
126135 async fn listing_sorts_by_stars_and_paginates() {
127136 let dir = tempfile::tempdir().unwrap();
128137 let store = open_store(&db_path(&dir)).await;
129- let tahinli = store.create_user("tahinli", None, "h", false).await.unwrap();
138+ let tahinli = store
139+ .create_user("tahinli", None, "h", false)
140+ .await
141+ .unwrap();
130142 let bob = store.create_user("bob", None, "h", false).await.unwrap();
131143 let quiet = store
132144 .create_repo(&tahinli.id, "aaa", "", Visibility::Public, "main")
@@ -163,7 +175,10 @@ async fn listing_sorts_by_stars_and_paginates() {
163175 async fn recently_updated_uses_latest_push_over_creation() {
164176 let dir = tempfile::tempdir().unwrap();
165177 let store = open_store(&db_path(&dir)).await;
166- let tahinli = store.create_user("tahinli", None, "h", false).await.unwrap();
178+ let tahinli = store
179+ .create_user("tahinli", None, "h", false)
180+ .await
181+ .unwrap();
167182 let older = store
168183 .create_repo(&tahinli.id, "older", "", Visibility::Public, "main")
169184 .await
crates/forge-core/tests/store_basic.rsmodified+36 -9
@@ -84,7 +84,10 @@ async fn duplicate_username_is_conflict_case_insensitive() {
8484 let dir = tempfile::tempdir().unwrap();
8585 let store = open_store(&db_path(&dir)).await;
8686
87- store.create_user("Tahinli", None, "h", false).await.unwrap();
87+ store
88+ .create_user("Tahinli", None, "h", false)
89+ .await
90+ .unwrap();
8891 let err = store
8992 .create_user("TAHINLI", None, "h", false)
9093 .await
@@ -100,7 +103,10 @@ async fn duplicate_username_is_conflict_case_insensitive() {
100103 async fn sessions_respect_expiry() {
101104 let dir = tempfile::tempdir().unwrap();
102105 let store = open_store(&db_path(&dir)).await;
103- let user = store.create_user("tahinli", None, "h", false).await.unwrap();
106+ let user = store
107+ .create_user("tahinli", None, "h", false)
108+ .await
109+ .unwrap();
104110
105111 let live = store
106112 .create_session(
@@ -179,7 +185,10 @@ async fn sessions_respect_expiry() {
179185 async fn ssh_key_exact_blob_lookup() {
180186 let dir = tempfile::tempdir().unwrap();
181187 let store = open_store(&db_path(&dir)).await;
182- let user = store.create_user("tahinli", None, "h", false).await.unwrap();
188+ let user = store
189+ .create_user("tahinli", None, "h", false)
190+ .await
191+ .unwrap();
183192
184193 let blob: Vec<u8> = vec![
185194 0, 0, 0, 11, b's', b's', b'h', b'-', b'e', b'd', b'2', b'5', b'5', b'1', b'9', 0, 0, 0, 32,
@@ -225,7 +234,10 @@ async fn ssh_key_exact_blob_lookup() {
225234 async fn access_token_create_lookup_and_expiry() {
226235 let dir = tempfile::tempdir().unwrap();
227236 let store = open_store(&db_path(&dir)).await;
228- let user = store.create_user("tahinli", None, "h", false).await.unwrap();
237+ let user = store
238+ .create_user("tahinli", None, "h", false)
239+ .await
240+ .unwrap();
229241 let scopes = vec!["repo:read".to_string(), "repo:write".to_string()];
230242
231243 let live = store
@@ -278,7 +290,10 @@ async fn access_token_create_lookup_and_expiry() {
278290 async fn repo_create_and_case_insensitive_lookup() {
279291 let dir = tempfile::tempdir().unwrap();
280292 let store = open_store(&db_path(&dir)).await;
281- let tahinli = store.create_user("Tahinli", None, "h", false).await.unwrap();
293+ let tahinli = store
294+ .create_user("Tahinli", None, "h", false)
295+ .await
296+ .unwrap();
282297
283298 let repo = store
284299 .create_repo(
@@ -342,7 +357,10 @@ async fn repo_create_and_case_insensitive_lookup() {
342357 .unwrap();
343358 assert_eq!(bobs.owner_name, "bob");
344359
345- assert_eq!(store.list_repos_by_owner(&tahinli.id).await.unwrap().len(), 1);
360+ assert_eq!(
361+ store.list_repos_by_owner(&tahinli.id).await.unwrap().len(),
362+ 1
363+ );
346364
347365 store.set_repo_archived(&repo.id, true).await.unwrap();
348366 assert!(store.repo_by_id(&repo.id).await.unwrap().unwrap().archived);
@@ -354,7 +372,10 @@ async fn repo_create_and_case_insensitive_lookup() {
354372 async fn collaborator_role_roundtrip() {
355373 let dir = tempfile::tempdir().unwrap();
356374 let store = open_store(&db_path(&dir)).await;
357- let tahinli = store.create_user("tahinli", None, "h", false).await.unwrap();
375+ let tahinli = store
376+ .create_user("tahinli", None, "h", false)
377+ .await
378+ .unwrap();
358379 let bob = store.create_user("bob", None, "h", false).await.unwrap();
359380 let repo = store
360381 .create_repo(&tahinli.id, "proj", "", Visibility::Private, "main")
@@ -382,7 +403,10 @@ async fn collaborator_role_roundtrip() {
382403 Some(Role::Maintain)
383404 );
384405 assert_eq!(
385- store.collaborator_role(&repo.id, &tahinli.id).await.unwrap(),
406+ store
407+ .collaborator_role(&repo.id, &tahinli.id)
408+ .await
409+ .unwrap(),
386410 None
387411 );
388412 }
@@ -392,7 +416,10 @@ async fn push_event_is_recorded() {
392416 let dir = tempfile::tempdir().unwrap();
393417 let path = db_path(&dir);
394418 let store = open_store(&path).await;
395- let tahinli = store.create_user("tahinli", None, "h", false).await.unwrap();
419+ let tahinli = store
420+ .create_user("tahinli", None, "h", false)
421+ .await
422+ .unwrap();
396423 let repo = store
397424 .create_repo(&tahinli.id, "proj", "", Visibility::Public, "main")
398425 .await
crates/forge-git/src/verify.rsmodified+2 -1
@@ -409,7 +409,8 @@ mod tests {
409409
410410 #[test]
411411 fn parses_ssh_sentences() {
412- let text = "Good \"git\" signature for tahinli@example.com with ED25519 key SHA256:abc+def\n";
412+ let text =
413+ "Good \"git\" signature for tahinli@example.com with ED25519 key SHA256:abc+def\n";
413414 let raw = parse_output(text, Some(SigKind::Ssh));
414415 assert!(raw.good);
415416 assert_eq!(raw.principal.as_deref(), Some("tahinli@example.com"));
crates/forge-web/assets/nav.jsmodified+22 -0
@@ -414,6 +414,28 @@
414414 load({ target: withoutHash(url), dest: url, init: GET_INIT, how: 'pop', keep: false, post: false, form: null });
415415 });
416416
417+ // Search as you type: a search field marked data-live-search refetches its GET form 250 ms after
418+ // the last keystroke and swaps the page in place, with no history entry and the field's focus and
419+ // caret kept. A newer request drops an older answer. The submit button stays as the no-JS path.
420+ var searchTimer = null;
421+ function liveSearch(input) {
422+ var el = input.isConnected ? input : document.querySelector('[data-live-search]');
423+ var form = el && el.form;
424+ var url = form ? pageUrl(form.getAttribute('action') || location.href) : null;
425+ if (!url) { return; }
426+ var dest = withoutHash(url);
427+ var q = new URLSearchParams(new FormData(form)).toString();
428+ dest.search = q ? '?' + q : '';
429+ if (dest.pathname + dest.search === shown) { return; }
430+ load({ target: dest, dest: dest, init: GET_INIT, how: 'query', keep: true, post: false, form: null });
431+ }
432+ document.addEventListener('input', function (e) {
433+ var input = e.target && e.target.closest ? e.target.closest('[data-live-search]') : null;
434+ if (!input || !input.form) { return; }
435+ clearTimeout(searchTimer);
436+ searchTimer = setTimeout(function () { searchTimer = null; liveSearch(input); }, 250);
437+ });
438+
417439 // Filter controls submit their form on change.
418440 document.addEventListener('change', function (e) {
419441 var c = e.target && e.target.closest ? e.target.closest('[data-autosubmit]') : null;
crates/forge-web/src/accent.rsmodified+1 -15
@@ -59,7 +59,7 @@ mod tests {
5959 use std::collections::HashSet;
6060
6161 use super::*;
62- use crate::accent_palette::{BASE_TOKEN_VARS, TOKEN_VARS, Tokens};
62+ use crate::accent_palette::{BASE_TOKEN_VARS, TOKEN_VARS};
6363
6464 /// WCAG relative luminance of a `#RRGGBB` colour.
6565 fn luminance(hex: &str) -> f64 {
@@ -219,18 +219,4 @@ mod tests {
219219 }
220220 }
221221 }
222-
223- #[test]
224- fn heatmap_steps_grow_in_lightness_towards_the_strong_end() {
225- fn steps(t: &Tokens) -> [f64; 5] {
226- [t.h0, t.h1, t.h2, t.h3, t.h4].map(luminance)
227- }
228- for p in PALETTES {
229- // Light theme: each step is darker than the one before. Dark theme: each is lighter.
230- let light = steps(&p.light);
231- assert!(light.windows(2).all(|w| w[0] > w[1]), "{} light", p.id);
232- let dark = steps(&p.dark);
233- assert!(dark.windows(2).all(|w| w[0] < w[1]), "{} dark", p.id);
234- }
235- }
236222 }
crates/forge-web/src/accent_palette.rsmodified+3 -87
@@ -16,11 +16,6 @@ pub struct Tokens {
1616 pub note: &'static str,
1717 pub hunk_bg: &'static str,
1818 pub hunk_text: &'static str,
19- pub h0: &'static str,
20- pub h1: &'static str,
21- pub h2: &'static str,
22- pub h3: &'static str,
23- pub h4: &'static str,
2419 }
2520
2621 /// One accent colour: its id (the stored value and the `data-accent` attribute), and the tokens
@@ -82,30 +77,11 @@ pub const TOKEN_VARS: &[TokenVar] = &[
8277 name: "--hunk-text",
8378 value: |t| t.hunk_text,
8479 },
85- TokenVar {
86- name: "--h0",
87- value: |t| t.h0,
88- },
89- TokenVar {
90- name: "--h1",
91- value: |t| t.h1,
92- },
93- TokenVar {
94- name: "--h2",
95- value: |t| t.h2,
96- },
97- TokenVar {
98- name: "--h3",
99- value: |t| t.h3,
100- },
101- TokenVar {
102- name: "--h4",
103- value: |t| t.h4,
104- },
10580 ];
10681
107-/// Every accent colour on offer, in the order the picker lists them. Heatmap steps run from
108-/// `h0` (nearly the background) to `h4` (strongest).
82+/// Every accent colour on offer, in the order the picker lists them. The heatmap levels are not
83+/// here: style/_heatmap.scss mixes them from `--accent`/`--accent-ink` and the base's surface,
84+/// so they follow every accent and base.
10985 pub const PALETTES: &[Palette] = &[
11086 // Sage: the original forge colour.
11187 Palette {
@@ -121,11 +97,6 @@ pub const PALETTES: &[Palette] = &[
12197 note: "#4A6750",
12298 hunk_bg: "#EDF1EB",
12399 hunk_text: "#3F5F46",
124- h0: "#E6ECE4",
125- h1: "#C6D9C8",
126- h2: "#9DBDA2",
127- h3: "#6F9676",
128- h4: "#3F5F46",
129100 },
130101 dark: Tokens {
131102 accent: "#9DBEA2",
@@ -138,11 +109,6 @@ pub const PALETTES: &[Palette] = &[
138109 note: "#B5D2B9",
139110 hunk_bg: "#1E2620",
140111 hunk_text: "#9DBEA2",
141- h0: "#1F2722",
142- h1: "#2D3D31",
143- h2: "#41604A",
144- h3: "#628A6C",
145- h4: "#9DBEA2",
146112 },
147113 },
148114 // Blue, clear and cool.
@@ -159,11 +125,6 @@ pub const PALETTES: &[Palette] = &[
159125 note: "#336180",
160126 hunk_bg: "#E9F1F7",
161127 hunk_text: "#2B5977",
162- h0: "#DFECF5",
163- h1: "#BED7EA",
164- h2: "#99BEDA",
165- h3: "#6692B1",
166- h4: "#2C5D7E",
167128 },
168129 dark: Tokens {
169130 accent: "#86B9DD",
@@ -176,11 +137,6 @@ pub const PALETTES: &[Palette] = &[
176137 note: "#9FCBEA",
177138 hunk_bg: "#1A252E",
178139 hunk_text: "#86B9DD",
179- h0: "#1B262F",
180- h1: "#243B4C",
181- h2: "#375C76",
182- h3: "#5685A5",
183- h4: "#88BBDF",
184140 },
185141 },
186142 // Violet with a soft, muted edge.
@@ -197,11 +153,6 @@ pub const PALETTES: &[Palette] = &[
197153 note: "#645482",
198154 hunk_bg: "#F0EEF7",
199155 hunk_text: "#5C4B79",
200- h0: "#ECE7F6",
201- h1: "#D7CEEA",
202- h2: "#BEB1DA",
203- h3: "#9382B2",
204- h4: "#5F4D7E",
205156 },
206157 dark: Tokens {
207158 accent: "#BBA9E0",
@@ -214,11 +165,6 @@ pub const PALETTES: &[Palette] = &[
214165 note: "#CBBCEB",
215166 hunk_bg: "#25212E",
216167 hunk_text: "#BBA9E0",
217- h0: "#26222F",
218- h1: "#3C334C",
219- h2: "#5D4F76",
220- h3: "#8674A6",
221- h4: "#BBA9E0",
222168 },
223169 },
224170 // Dusty pink, warm and quiet.
@@ -235,11 +181,6 @@ pub const PALETTES: &[Palette] = &[
235181 note: "#864958",
236182 hunk_bg: "#F7ECEE",
237183 hunk_text: "#7D4050",
238- h0: "#F8E4E8",
239- h1: "#EEC7CF",
240- h2: "#DFA7B3",
241- h3: "#B67785",
242- h4: "#814151",
243184 },
244185 dark: Tokens {
245186 accent: "#E79DAD",
@@ -252,11 +193,6 @@ pub const PALETTES: &[Palette] = &[
252193 note: "#F3B2C0",
253194 hunk_bg: "#2F1E22",
254195 hunk_text: "#E79DAD",
255- h0: "#301F23",
256- h1: "#4E2D35",
257- h2: "#794652",
258- h3: "#AA6978",
259- h4: "#E69CAC",
260196 },
261197 },
262198 // Clay brown, warmer and earthier than the warning amber.
@@ -273,11 +209,6 @@ pub const PALETTES: &[Palette] = &[
273209 note: "#7A5338",
274210 hunk_bg: "#F6EEE8",
275211 hunk_text: "#724B30",
276- h0: "#F4E7DF",
277- h1: "#E6CEBE",
278- h2: "#D4B199",
279- h3: "#AB8267",
280- h4: "#764D30",
281212 },
282213 dark: Tokens {
283214 accent: "#D8A98A",
@@ -290,11 +221,6 @@ pub const PALETTES: &[Palette] = &[
290221 note: "#E4BCA1",
291222 hunk_bg: "#2C211A",
292223 hunk_text: "#D8A98A",
293- h0: "#2D221B",
294- h1: "#483325",
295- h2: "#704F39",
296- h3: "#9E7458",
297- h4: "#D8A989",
298224 },
299225 },
300226 // Blue-grey graphite, nearly neutral.
@@ -311,11 +237,6 @@ pub const PALETTES: &[Palette] = &[
311237 note: "#505E6C",
312238 hunk_bg: "#EAF0F7",
313239 hunk_text: "#485563",
314- h0: "#E6EAEF",
315- h1: "#CCD4DD",
316- h2: "#AFBAC7",
317- h3: "#808E9C",
318- h4: "#4C5A69",
319240 },
320241 dark: Tokens {
321242 accent: "#A4B4C4",
@@ -328,11 +249,6 @@ pub const PALETTES: &[Palette] = &[
328249 note: "#B8C6D5",
329250 hunk_bg: "#212428",
330251 hunk_text: "#A4B4C4",
331- h0: "#222529",
332- h1: "#323941",
333- h2: "#4E5965",
334- h3: "#728090",
335- h4: "#A6B6C7",
336252 },
337253 },
338254 ];
crates/forge-web/src/auth.rsmodified+4 -1
@@ -415,7 +415,10 @@ mod tests {
415415 let dir = tempfile::tempdir().unwrap();
416416 let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
417417 let key = [7u8; 32];
418- let tahinli = store.create_user("tahinli", None, "h", false).await.unwrap();
418+ let tahinli = store
419+ .create_user("tahinli", None, "h", false)
420+ .await
421+ .unwrap();
419422 let org = store.create_org("acme", &tahinli.id).await.unwrap();
420423 let shared = forge_core::totp::new_secret();
421424 let sealed = forge_core::secret::seal(&key, &shared).unwrap();
crates/forge-web/src/boot.rsmodified+1 -0
@@ -136,6 +136,7 @@ pub async fn serve(config: Config) -> forge_core::Result<()> {
136136 .cookies()
137137 .layer(crate::pages::settings_profile::avatar_body_limit())
138138 .layer(crate::pages::repo_ctx::RepoMovedLayer)
139+ .layer(crate::pages::not_found_page::NotFoundLayer)
139140 .layer(TowerLayer::new(crate::compression::ResponseCompression))
140141 .compression(Compression::off())
141142 .build();
crates/forge-web/src/ci/api_tests.rsmodified+74 -0
@@ -634,6 +634,80 @@ async fn finish_skips_dependants_on_failure() {
634634 assert_eq!(again.status, 401);
635635 }
636636
637+/// Parallel `test` and `build` on a deploy-branch push: `build` finishes green first, then `test`
638+/// fails. Neither finish leaves the run in a state that self-update deploys.
639+#[tokio::test]
640+async fn build_green_before_test_fails_never_qualifies_for_self_update() {
641+ let env = bare_with_self_update().await;
642+ let (_, secret) = runner(&env, &[]).await;
643+ let run = make_run(
644+ &env,
645+ "push",
646+ None,
647+ COMMIT,
648+ &[job("build", spec(&[], &[])), job("test", spec(&[], &[]))],
649+ )
650+ .await;
651+ let cfg = forge_core::config::SelfUpdateConfig {
652+ enabled: true,
653+ repo: format!("{OWNER}/{REPO}"),
654+ ..Default::default()
655+ };
656+ let full_name = format!("{OWNER}/{REPO}");
657+ let qualifies = |run: &CiRun| {
658+ crate::self_update::should_deploy(&cfg, &full_name, run, Some(run.id.as_str()))
659+ };
660+
661+ // Both jobs are claimable at once: no `needs` between them.
662+ let first = claim_job(&env.router, &secret).await;
663+ let second = claim_job(&env.router, &secret).await;
664+ let (build, test) = if first["job_name"] == "build" {
665+ (first, second)
666+ } else {
667+ (second, first)
668+ };
669+ assert_eq!(build["job_name"], "build");
670+ assert_eq!(test["job_name"], "test");
671+ let finish = |assignment: &Value, outcome: &'static str| {
672+ let job_id = assignment["job_id"].as_str().unwrap().to_owned();
673+ let token = assignment["job_token"].as_str().unwrap().to_owned();
674+ let router = env.router.clone();
675+ async move {
676+ send(
677+ &router,
678+ "POST",
679+ &format!("/api/v1/ci/jobs/{job_id}/finish"),
680+ &[bearer(&token)],
681+ finish_body(outcome),
682+ )
683+ .await
684+ }
685+ };
686+
687+ let sent = finish(&build, "success").await;
688+ assert_eq!(sent.status, 200, "{}", sent.json());
689+ assert_eq!(sent.json()["state"], "running", "test is still running");
690+ let after_build = env.store.run_by_id(&run.id).await.unwrap().unwrap();
691+ assert!(
692+ !qualifies(&after_build),
693+ "a green build alone never deploys"
694+ );
695+
696+ let sent = finish(&test, "failure").await;
697+ assert_eq!(sent.status, 200, "{}", sent.json());
698+ assert_eq!(sent.json()["state"], "failure");
699+ let after_test = env.store.run_by_id(&run.id).await.unwrap().unwrap();
700+ assert!(
701+ !qualifies(&after_test),
702+ "a run with a failed job never deploys"
703+ );
704+
705+ // Control: the same run shape with both jobs green does qualify.
706+ let mut green = after_test.clone();
707+ green.state = forge_core::ci::RunState::Success;
708+ assert!(qualifies(&green));
709+}
710+
637711 // ---------------------------------------------------------------------------------------------
638712 // Git read with a job token
639713 // ---------------------------------------------------------------------------------------------
crates/forge-web/src/ci/release.rsmodified+65 -3
@@ -616,6 +616,61 @@ title = "forge {tag}"
616616 assert!(release_named(&fx, "v1.0").await.is_none());
617617 }
618618
619+ /// Parallel jobs: `build` finishes green while `docs` still runs, then `docs` fails. The
620+ /// release hook runs after each finish, as `finish_job` does, and never publishes.
621+ #[tokio::test]
622+ async fn build_green_first_then_other_job_fails_creates_no_release() {
623+ let fx = fixture().await;
624+ push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await;
625+ let run = run_of(&fx, 1).await;
626+ let build = job_of(&fx, &run, "build").await;
627+ let docs = job_of(&fx, &run, "docs").await;
628+ add_artifact(&fx, &build, "dist_forge-linux-x86_64", b"binary").await;
629+
630+ let after_build = fx
631+ .state
632+ .store
633+ .finish_job(&build.id, JobState::Success, Some(0), None)
634+ .await
635+ .expect("finish build");
636+ assert_eq!(after_build.state, RunState::Running, "docs is still queued");
637+ on_run_finished(&fx.state, &after_build).await;
638+ assert!(release_named(&fx, "v1.0").await.is_none());
639+
640+ let after_docs = fx
641+ .state
642+ .store
643+ .finish_job(&docs.id, JobState::Failure, Some(1), None)
644+ .await
645+ .expect("finish docs");
646+ assert_eq!(after_docs.state, RunState::Failure);
647+ on_run_finished(&fx.state, &after_docs).await;
648+ assert!(release_named(&fx, "v1.0").await.is_none());
649+ }
650+
651+ /// Fail fast: `docs` fails while `build` has not finished. `build` is cancelled at once (the
652+ /// running-job path is covered in the store tests), the run fails, and no release is created.
653+ #[tokio::test]
654+ async fn failing_job_cancels_build_and_creates_no_release() {
655+ let fx = fixture().await;
656+ push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await;
657+ let run = run_of(&fx, 1).await;
658+ let build = job_of(&fx, &run, "build").await;
659+ let docs = job_of(&fx, &run, "docs").await;
660+ add_artifact(&fx, &build, "dist_forge-linux-x86_64", b"binary").await;
661+
662+ let after_docs = fx
663+ .state
664+ .store
665+ .finish_job(&docs.id, JobState::Failure, Some(1), None)
666+ .await
667+ .expect("finish docs");
668+ assert_eq!(after_docs.state, RunState::Failure);
669+ assert_eq!(job_of(&fx, &run, "build").await.state, JobState::Cancelled);
670+ on_run_finished(&fx.state, &after_docs).await;
671+ assert!(release_named(&fx, "v1.0").await.is_none());
672+ }
673+
619674 #[tokio::test]
620675 async fn branch_push_run_creates_no_release() {
621676 let fx = fixture().await;
@@ -665,9 +720,16 @@ title = "forge {tag}"
665720 commit_message(&fx.work, "feat: one");
666721 let oid = commit_message(&fx.work, "fix: two");
667722 land(&fx, &oid, "refs/tags/v1.1");
668- after_ref_update(&fx.state, &fx.repo, &fx.owner.id, "refs/tags/v1.1", ZERO, &oid)
669- .await
670- .expect("post update");
723+ after_ref_update(
724+ &fx.state,
725+ &fx.repo,
726+ &fx.owner.id,
727+ "refs/tags/v1.1",
728+ ZERO,
729+ &oid,
730+ )
731+ .await
732+ .expect("post update");
671733 finish_all(&fx, &run_of(&fx, 2).await.id, None).await;
672734 on_run_finished(&fx.state, &run_of(&fx, 2).await).await;
673735
crates/forge-web/src/ci/schedule.rsmodified+1 -1
@@ -721,7 +721,7 @@ run = "make"
721721 .expect("job log");
722722 assert!(
723723 log.starts_with(
724- "[forge] warning: unknown key `future` ignored \u{2014} this forge may be older than your ci.toml\n"
724+ "[forge] warning: unknown key `future` ignored: this forge may be older than your ci.toml\n"
725725 ),
726726 "log was {log:?}"
727727 );
crates/forge-web/src/compression.rsmodified+8 -2
@@ -230,13 +230,19 @@ mod tests {
230230 async fn git_smart_http_is_never_compressed() {
231231 let router = router();
232232 assert_eq!(encoding(&router, "/tahinli/demo.git/info/refs").await, None);
233- assert_eq!(encoding(&router, "/tahinli/demo/git-upload-pack").await, None);
233+ assert_eq!(
234+ encoding(&router, "/tahinli/demo/git-upload-pack").await,
235+ None
236+ );
234237 }
235238
236239 #[tokio::test]
237240 async fn raw_and_binary_are_not_compressed() {
238241 let router = router();
239- assert_eq!(encoding(&router, "/tahinli/demo/raw/main/a.txt").await, None);
242+ assert_eq!(
243+ encoding(&router, "/tahinli/demo/raw/main/a.txt").await,
244+ None
245+ );
240246 assert_eq!(encoding(&router, "/tahinli/demo/blob.bin").await, None);
241247 }
242248
crates/forge-web/src/git_auth.rsmodified+4 -1
@@ -142,7 +142,10 @@ mod tests {
142142
143143 #[test]
144144 fn rejects_missing_colon() {
145- assert_eq!(parse_basic_auth(&headers_with(&basic("tahinlitoken"))), None);
145+ assert_eq!(
146+ parse_basic_auth(&headers_with(&basic("tahinlitoken"))),
147+ None
148+ );
146149 }
147150
148151 #[test]
crates/forge-web/src/i18n/admin.rsmodified+2 -0
@@ -605,6 +605,7 @@ pub fn healthcheck_host(lang: Lang, host: Option<&str>) -> String {
605605 /// "every 6 hours".
606606 pub fn every_hours(lang: Lang, hours: u64) -> String {
607607 match lang {
608+ Lang::En if hours == 1 => "every hour".to_owned(),
608609 Lang::En => format!("every {hours} hours"),
609610 Lang::Tr => format!("her {hours} saatte bir"),
610611 }
@@ -613,6 +614,7 @@ pub fn every_hours(lang: Lang, hours: u64) -> String {
613614 /// "every 7 days".
614615 pub fn every_days(lang: Lang, days: u64) -> String {
615616 match lang {
617+ Lang::En if days == 1 => "every day".to_owned(),
616618 Lang::En => format!("every {days} days"),
617619 Lang::Tr => format!("her {days} günde bir"),
618620 }
crates/forge-web/src/i18n/code.rsmodified+5 -1
@@ -400,7 +400,11 @@ pub fn lfs_missing(lang: Lang, size: &str) -> String {
400400 /// The note for a binary file, with its size in bytes.
401401 pub fn binary_note(lang: Lang, bytes: impl std::fmt::Display) -> String {
402402 match lang {
403- Lang::En => format!("Binary file, {bytes} bytes"),
403+ Lang::En => {
404+ let bytes = bytes.to_string();
405+ let unit = if bytes == "1" { "byte" } else { "bytes" };
406+ format!("Binary file, {bytes} {unit}")
407+ }
404408 Lang::Tr => format!("İkili dosya, {bytes} bayt"),
405409 }
406410 }
crates/forge-web/src/i18n/community.rsmodified+7 -3
@@ -406,7 +406,7 @@ pub fn page_too_large(lang: Lang, max: usize) -> String {
406406 }
407407 }
408408
409-/// `2 file(s) · updated 3 days ago` / `2 dosya · 3 gün önce güncellendi`.
409+/// `2 files · updated 3 days ago` / `2 dosya · 3 gün önce güncellendi`.
410410 /// `updated 3 days ago` / `3 gün önce güncellendi`.
411411 pub fn updated_on(lang: Lang, updated: &str) -> String {
412412 match lang {
@@ -417,7 +417,10 @@ pub fn updated_on(lang: Lang, updated: &str) -> String {
417417
418418 pub fn files_updated(lang: Lang, count: u64, updated: &str) -> String {
419419 match lang {
420- Lang::En => format!("{count} file(s) · updated {updated}"),
420+ Lang::En => format!(
421+ "{count} {} · updated {updated}",
422+ if count == 1 { "file" } else { "files" }
423+ ),
421424 Lang::Tr => format!("{count} dosya · {updated} güncellendi"),
422425 }
423426 }
@@ -570,6 +573,7 @@ mod tests {
570573 assert_eq!(comments_count(Lang::En, 3), "3 comments");
571574 assert_eq!(comments_count(Lang::Tr, 3), "3 yorum");
572575 assert_eq!(page_number(Lang::Tr, 2), "Sayfa 2");
573- assert_eq!(files_updated(Lang::En, 2, "now"), "2 file(s) · updated now");
576+ assert_eq!(files_updated(Lang::En, 2, "now"), "2 files · updated now");
577+ assert_eq!(files_updated(Lang::En, 1, "now"), "1 file · updated now");
574578 }
575579 }
crates/forge-web/src/i18n/misc.rsmodified+4 -4
@@ -634,11 +634,11 @@ pub fn date_text(lang: Lang, year: i64, month: i64, day: i64) -> String {
634634 format!("{day} {} {year}", month_abbrev(lang, month))
635635 }
636636
637-/// `16 Oct 2025 to 16 Oct 2026` in English; Turkish joins the two dates with a dash.
637+/// `16 Oct 2025 to 16 Oct 2026` in English; Turkish uses `ile ... arası`.
638638 pub fn date_range(lang: Lang, from: &str, to: &str) -> String {
639639 match lang {
640640 Lang::En => format!("{from} to {to}"),
641- Lang::Tr => format!("{from} – {to}"),
641+ Lang::Tr => format!("{from} ile {to} arası"),
642642 }
643643 }
644644
@@ -646,13 +646,13 @@ pub fn date_range(lang: Lang, from: &str, to: &str) -> String {
646646 /// streak (which counts today when `today > 0`).
647647 pub fn heatmap_motivation(lang: Lang, today: u64, streak: u64) -> String {
648648 match (lang, today > 0, streak > 0) {
649- (Lang::En, true, _) => format!("Nice \u{2014} that's a {streak}-day streak."),
649+ (Lang::En, true, _) => format!("Nice, that's a {streak}-day streak!"),
650650 (Lang::En, false, true) => format!(
651651 "Keep it going: one commit today makes it a {}-day streak.",
652652 streak + 1
653653 ),
654654 (Lang::En, false, false) => "Start a new streak today.".to_owned(),
655- (Lang::Tr, true, _) => format!("Harika \u{2014} {streak} günlük bir seri!"),
655+ (Lang::Tr, true, _) => format!("Harika, {streak} günlük seri!"),
656656 (Lang::Tr, false, true) => format!(
657657 "Devam edin: bugün bir katkı, seriyi {} güne çıkarır.",
658658 streak + 1
crates/forge-web/src/i18n/orgs.rsmodified+30 -22
@@ -106,7 +106,6 @@ pub enum K {
106106 NoPublicReposMatch,
107107 // Profile.
108108 LocalTime,
109- AllMembers,
110109 NoMembers,
111110 NoVisibleRepos,
112111 NoVisibleStarred,
@@ -339,8 +338,6 @@ pub fn t(lang: Lang, key: K) -> &'static str {
339338 (NoPublicReposMatch, Tr) => "Aramayla eşleşen herkese açık depo yok.",
340339 (LocalTime, En) => "Local time: ",
341340 (LocalTime, Tr) => "Yerel saat: ",
342- (AllMembers, En) => "All members",
343- (AllMembers, Tr) => "Tüm üyeler",
344341 (NoMembers, En) => "No members.",
345342 (NoMembers, Tr) => "Üye yok.",
346343 (NoVisibleRepos, En) => "No visible repositories.",
@@ -451,19 +448,33 @@ pub fn role_for(lang: Lang, user: &str) -> String {
451448 /// The member and team counts on a profile.
452449 pub fn members_and_teams(lang: Lang, members: usize, teams: usize) -> String {
453450 match lang {
454- Lang::En => format!("{members} members \u{b7} {teams} teams"),
451+ Lang::En => format!(
452+ "{members} member{} \u{b7} {teams} team{}",
453+ if members == 1 { "" } else { "s" },
454+ if teams == 1 { "" } else { "s" }
455+ ),
455456 Lang::Tr => format!("{members} üye \u{b7} {teams} takım"),
456457 }
457458 }
458459
459-/// "3 repositories", or "3 depo" in Turkish.
460+/// "1 repository", "3 repositories", or "3 depo" in Turkish (no plural after a number).
460461 pub fn repo_count(lang: Lang, total: u64) -> String {
461462 match lang {
463+ Lang::En if total == 1 => "1 repository".to_owned(),
462464 Lang::En => format!("{total} repositories"),
463465 Lang::Tr => format!("{total} depo"),
464466 }
465467 }
466468
469+/// "1 starred repository", "3 starred repositories", or "3 yıldızlı depo" in Turkish.
470+pub fn starred_count(lang: Lang, total: u64) -> String {
471+ match lang {
472+ Lang::En if total == 1 => "1 starred repository".to_owned(),
473+ Lang::En => format!("{total} starred repositories"),
474+ Lang::Tr => format!("{total} yıldızlı depo"),
475+ }
476+}
477+
467478 /// "Page 2 of 5", or "Sayfa 2 / 5" in Turkish.
468479 pub fn page_of(lang: Lang, page: u64, pages: u64) -> String {
469480 match lang {
@@ -472,11 +483,12 @@ pub fn page_of(lang: Lang, page: u64, pages: u64) -> String {
472483 }
473484 }
474485
475-/// The updated note after a repository's stars: " · updated 3 days ago", or " · 3 gün önce güncellendi".
476-pub fn updated_text(lang: Lang, when: &str) -> String {
486+/// The text around the relative time in the updated note after a repository's stars, as
487+/// (before, after): " · updated 3 days ago", or " · 3 gün önce güncellendi".
488+pub fn updated_parts(lang: Lang) -> (&'static str, &'static str) {
477489 match lang {
478- Lang::En => format!(" \u{b7} updated {when}"),
479- Lang::Tr => format!(" \u{b7} {when} güncellendi"),
490+ Lang::En => (" \u{b7} updated ", ""),
491+ Lang::Tr => (" \u{b7} ", " güncellendi"),
480492 }
481493 }
482494
@@ -578,7 +590,6 @@ mod tests {
578590 K::SortMostStars,
579591 K::NoPublicReposMatch,
580592 K::LocalTime,
581- K::AllMembers,
582593 K::NoMembers,
583594 K::NoVisibleRepos,
584595 K::NoVisibleStarred,
@@ -635,19 +646,16 @@ mod tests {
635646 "bağlı depolarda okuma"
636647 );
637648 assert_eq!(page_of(Lang::En, 2, 5), "Page 2 of 5");
638- assert_eq!(
639- updated_text(Lang::En, "3 days ago"),
640- " \u{b7} updated 3 days ago"
641- );
642- assert_eq!(
643- updated_text(Lang::Tr, "3 gün önce"),
644- " \u{b7} 3 gün önce güncellendi"
645- );
649+ assert_eq!(updated_parts(Lang::En), (" \u{b7} updated ", ""));
650+ assert_eq!(updated_parts(Lang::Tr), (" \u{b7} ", " güncellendi"));
646651 assert_eq!(repo_count(Lang::En, 3), "3 repositories");
647- assert_eq!(
648- members_and_teams(Lang::En, 2, 1),
649- "2 members \u{b7} 1 teams"
650- );
652+ assert_eq!(repo_count(Lang::En, 1), "1 repository");
653+ assert_eq!(repo_count(Lang::Tr, 1), "1 depo");
654+ assert_eq!(starred_count(Lang::En, 1), "1 starred repository");
655+ assert_eq!(starred_count(Lang::En, 2), "2 starred repositories");
656+ assert_eq!(starred_count(Lang::Tr, 2), "2 yıldızlı depo");
657+ assert_eq!(members_and_teams(Lang::En, 2, 1), "2 members \u{b7} 1 team");
658+ assert_eq!(members_and_teams(Lang::En, 1, 3), "1 member \u{b7} 3 teams");
651659 assert_eq!(type_to_confirm(Lang::En, "acme"), "Type acme to confirm");
652660 assert_eq!(
653661 description_too_long(Lang::En, 2000),
crates/forge-web/src/i18n/releases_ci.rsmodified+5 -3
@@ -392,11 +392,11 @@ pub fn page_label(lang: Lang, page: u32) -> String {
392392 }
393393 }
394394
395-/// "scale: 0 — 80 min", the scale of the run list in minutes.
395+/// "scale: 0 to 80 min", the scale of the run list in minutes.
396396 pub fn scale_label(lang: Lang, span: &str) -> String {
397397 match lang {
398- Lang::En => format!("scale: 0 \u{2014} {span}"),
399- Lang::Tr => format!("ölçek: 0 \u{2014} {span}"),
398+ Lang::En => format!("scale: 0 to {span}"),
399+ Lang::Tr => format!("ölçek: 0 ile {span} arası"),
400400 }
401401 }
402402
@@ -427,6 +427,7 @@ pub fn duration_seconds(lang: Lang, secs: i64) -> String {
427427 /// "3 downloads".
428428 pub fn download_count(lang: Lang, count: u64) -> String {
429429 match lang {
430+ Lang::En if count == 1 => "1 download".to_owned(),
430431 Lang::En => format!("{count} downloads"),
431432 Lang::Tr => format!("{count} indirme"),
432433 }
@@ -594,6 +595,7 @@ mod tests {
594595 fn counted_sentences_read_in_both_languages() {
595596 assert_eq!(download_count(Lang::En, 3), "3 downloads");
596597 assert_eq!(download_count(Lang::Tr, 3), "3 indirme");
598+ assert_eq!(download_count(Lang::En, 1), "1 download");
597599 assert_eq!(duration_minutes(Lang::En, 1, 5), "1m 5s");
598600 assert_eq!(duration_minutes(Lang::Tr, 1, 5), "1 dk 5 sn");
599601 assert_eq!(page_label(Lang::Tr, 2), "Sayfa 2");
crates/forge-web/src/lfs/gc.rsmodified+4 -1
@@ -186,7 +186,10 @@ mod tests {
186186 let dir = tempfile::tempdir().unwrap();
187187 let data = dir.path();
188188 let store = Store::open(&data.join("forge.db")).await.unwrap();
189- let user = store.create_user("tahinli", None, "h", false).await.unwrap();
189+ let user = store
190+ .create_user("tahinli", None, "h", false)
191+ .await
192+ .unwrap();
190193 let repo = store
191194 .create_repo(&user.id, "demo", "", Visibility::Public, "main")
192195 .await
crates/forge-web/src/mail/smtp.rsmodified+1 -1
@@ -106,8 +106,8 @@ fn build_transport(
106106
107107 #[cfg(test)]
108108 mod tests {
109- use forge_core::mail::MailKind;
110109 use super::*;
110+ use forge_core::mail::MailKind;
111111
112112 fn settings() -> MailSettings {
113113 MailSettings {
crates/forge-web/src/mail/worker.rsmodified+82 -22
@@ -174,9 +174,17 @@ mod tests {
174174 async fn a_row_leased_before_a_restart_is_sent_by_the_first_pass_after_boot() {
175175 let dir = tempfile::tempdir().expect("tempdir");
176176 let (state, fake) = enabled_state(dir.path()).await;
177- enqueue(&state, "stuck", MailKind::Notification, None, "a@example.com", "Hi", "body")
178- .await
179- .expect("queued");
177+ enqueue(
178+ &state,
179+ "stuck",
180+ MailKind::Notification,
181+ None,
182+ "a@example.com",
183+ "Hi",
184+ "body",
185+ )
186+ .await
187+ .expect("queued");
180188 // A pass that took the row and died before it finished: the lease is still set.
181189 let held = state
182190 .store
@@ -188,7 +196,11 @@ mod tests {
188196
189197 assert_eq!(boot(&state).await.expect("boot"), 1);
190198 tick(&state).await.expect("pass");
191- assert_eq!(fake.sent().len(), 1, "the released row goes out without waiting");
199+ assert_eq!(
200+ fake.sent().len(),
201+ 1,
202+ "the released row goes out without waiting"
203+ );
192204 let row = state.store.recent_mail(10).await.expect("rows").remove(0);
193205 assert_eq!(row.status(), OutboxStatus::Sent);
194206 }
@@ -198,15 +210,31 @@ mod tests {
198210 let dir = tempfile::tempdir().expect("tempdir");
199211 let (state, fake) = enabled_state(dir.path()).await;
200212 assert!(
201- enqueue(&state, "reset:1", MailKind::PasswordReset, None, "a@example.com", "Hi", "body")
202- .await
203- .expect("queued")
213+ enqueue(
214+ &state,
215+ "reset:1",
216+ MailKind::PasswordReset,
217+ None,
218+ "a@example.com",
219+ "Hi",
220+ "body"
221+ )
222+ .await
223+ .expect("queued")
204224 );
205225 // A second enqueue with the same key is a no-op.
206226 assert!(
207- !enqueue(&state, "reset:1", MailKind::PasswordReset, None, "a@example.com", "Hi", "body")
208- .await
209- .expect("again")
227+ !enqueue(
228+ &state,
229+ "reset:1",
230+ MailKind::PasswordReset,
231+ None,
232+ "a@example.com",
233+ "Hi",
234+ "body"
235+ )
236+ .await
237+ .expect("again")
210238 );
211239
212240 tick(&state).await.expect("pass");
@@ -237,9 +265,17 @@ mod tests {
237265 })
238266 .await
239267 .expect("off");
240- enqueue(&state, "k", MailKind::Other, None, "a@example.com", "Hi", "body")
241- .await
242- .expect("queued");
268+ enqueue(
269+ &state,
270+ "k",
271+ MailKind::Other,
272+ None,
273+ "a@example.com",
274+ "Hi",
275+ "body",
276+ )
277+ .await
278+ .expect("queued");
243279 assert_eq!(tick(&state).await.expect("pass"), BACKSTOP);
244280 assert!(fake.sent().is_empty());
245281 let row = state.store.recent_mail(10).await.expect("rows");
@@ -251,12 +287,28 @@ mod tests {
251287 async fn a_transient_failure_is_retried_later_and_a_permanent_one_gives_up() {
252288 let dir = tempfile::tempdir().expect("tempdir");
253289 let (state, fake) = enabled_state(dir.path()).await;
254- enqueue(&state, "retry", MailKind::Other, None, "a@example.com", "Hi", "body")
255- .await
256- .expect("queued");
257- enqueue(&state, "bounce", MailKind::Other, None, "b@example.com", "Hi", "body")
258- .await
259- .expect("queued");
290+ enqueue(
291+ &state,
292+ "retry",
293+ MailKind::Other,
294+ None,
295+ "a@example.com",
296+ "Hi",
297+ "body",
298+ )
299+ .await
300+ .expect("queued");
301+ enqueue(
302+ &state,
303+ "bounce",
304+ MailKind::Other,
305+ None,
306+ "b@example.com",
307+ "Hi",
308+ "body",
309+ )
310+ .await
311+ .expect("queued");
260312 fake.fail_next(MailError::Transient("timeout".into()));
261313 fake.fail_next(MailError::Permanent("550 no such user".into()));
262314
@@ -283,9 +335,17 @@ mod tests {
283335 async fn the_last_try_gives_up_and_an_earlier_one_reschedules() {
284336 let dir = tempfile::tempdir().expect("tempdir");
285337 let (state, fake) = enabled_state(dir.path()).await;
286- enqueue(&state, "stubborn", MailKind::Other, None, "a@example.com", "Hi", "body")
287- .await
288- .expect("queued");
338+ enqueue(
339+ &state,
340+ "stubborn",
341+ MailKind::Other,
342+ None,
343+ "a@example.com",
344+ "Hi",
345+ "body",
346+ )
347+ .await
348+ .expect("queued");
289349 let row = state.store.recent_mail(10).await.expect("rows").remove(0);
290350 fake.fail_next(MailError::Transient("timeout".into()));
291351 fake.fail_next(MailError::Transient("timeout".into()));
crates/forge-web/src/pages/admin_mail.rsmodified+98 -21
@@ -8,7 +8,9 @@
88 //! Saving the settings and queuing a test are audited.
99
1010 use forge_core::config::MailTransport;
11-use forge_core::mail::{MailKind, MailSettings, MailSettingsUpdate, MailState, OutboxEntry, Security};
11+use forge_core::mail::{
12+ MailKind, MailSettings, MailSettingsUpdate, MailState, OutboxEntry, Security,
13+};
1214 use forge_core::time::now_stamp;
1315 use forge_core::tz::format_in_tz;
1416 use forge_core::{AuditAction, Error};
@@ -117,7 +119,11 @@ fn transport_name(transport: MailTransport) -> &'static str {
117119 }
118120
119121 fn tab_class(on: bool) -> &'static str {
120- if on { "subnav-link current" } else { "subnav-link" }
122+ if on {
123+ "subnav-link current"
124+ } else {
125+ "subnav-link"
126+ }
121127 }
122128
123129 fn row_view(entry: &OutboxEntry, now: &str, tz: &str, lang: Lang) -> QueueRow {
@@ -224,7 +230,11 @@ async fn mail_view(
224230 let settings_on = data.tab == Tab::Settings;
225231 let settings_class = tab_class(settings_on);
226232 let queue_class = tab_class(!settings_on);
227- let filter_param = data.queue.as_ref().map(|q| q.filter_param.clone()).unwrap_or_default();
233+ let filter_param = data
234+ .queue
235+ .as_ref()
236+ .map(|q| q.filter_param.clone())
237+ .unwrap_or_default();
228238 Ok(view! {
229239 <section class="page-head">
230240 <h1>(g::t(lang, K::Mail))</h1>
@@ -244,7 +254,7 @@ async fn mail_view(
244254 <h2>(g::t(lang, K::SmtpServer))</h2>
245255 <p class="muted small">(g::t(lang, K::MailTransportNote))</p>
246256 <p class="small">(g::t(lang, K::MailTransportInUse)) " " <code>(data.transport)</code></p>
247- <form method="post" action="/admin/mail">
257+ <form method="post" action="/admin/mail" class="stack">
248258 <input type="hidden" name="csrf" value=(csrf.as_str())>
249259 <label>(g::t(lang, K::MailHost)) <input type="text" name="host" value=(data.host.as_str()) maxlength="253" autocomplete="off"></label>
250260 <label>(g::t(lang, K::MailPort)) <input type="number" name="port" value=(data.port.as_str()) min="1" max="65535"></label>
@@ -588,9 +598,8 @@ async fn queue_action(cx: &Cx, form: QueueForm, action: QueueAction) -> Result<R
588598 if done {
589599 live::bump();
590600 }
591- let filter = MailState::parse(&form.state).map_or_else(String::new, |s| {
592- format!("&state={}", s.as_str())
593- });
601+ let filter = MailState::parse(&form.state)
602+ .map_or_else(String::new, |s| format!("&state={}", s.as_str()));
594603 let location = format!(
595604 "/admin/mail?tab=queue{filter}&notice={}",
596605 enc(g::t(lang, notice))
@@ -840,7 +849,12 @@ mod tests {
840849 assert!(!body.contains("SMTP server"), "no English heading left");
841850 }
842851
843- fn outgoing(to: &str, subject: &str, body: &str, kind: MailKind) -> forge_core::mail::OutgoingMail {
852+ fn outgoing(
853+ to: &str,
854+ subject: &str,
855+ body: &str,
856+ kind: MailKind,
857+ ) -> forge_core::mail::OutgoingMail {
844858 forge_core::mail::OutgoingMail {
845859 to: to.into(),
846860 subject: subject.into(),
@@ -861,9 +875,22 @@ mod tests {
861875 "https://forge.test/reset/SECRET-LINK",
862876 MailKind::PasswordReset,
863877 );
864- fx.state.store.enqueue_mail("reset:1", &reset).await.expect("queued");
865- let later = outgoing("b@example.com", "Queued one", "body", MailKind::Notification);
866- fx.state.store.enqueue_mail("notif:2", &later).await.expect("queued");
878+ fx.state
879+ .store
880+ .enqueue_mail("reset:1", &reset)
881+ .await
882+ .expect("queued");
883+ let later = outgoing(
884+ "b@example.com",
885+ "Queued one",
886+ "body",
887+ MailKind::Notification,
888+ );
889+ fx.state
890+ .store
891+ .enqueue_mail("notif:2", &later)
892+ .await
893+ .expect("queued");
867894 let failed_id = fx
868895 .state
869896 .store
@@ -880,21 +907,44 @@ mod tests {
880907 .await
881908 .expect("failed");
882909
883- let (status, body) = send(&fx.router, "GET", "/admin/mail?tab=queue", Some(ADMIN_TOKEN), None).await;
910+ let (status, body) = send(
911+ &fx.router,
912+ "GET",
913+ "/admin/mail?tab=queue",
914+ Some(ADMIN_TOKEN),
915+ None,
916+ )
917+ .await;
884918 assert_eq!(status, 200);
885- assert!(body.contains("data-live=\"/admin/mail/events\""), "the queue is live");
919+ assert!(
920+ body.contains("data-live=\"/admin/mail/events\""),
921+ "the queue is live"
922+ );
886923 assert!(body.contains("Reset your password") && body.contains("Queued one"));
887924 assert!(body.contains("550 no such user"), "the last error shows");
888925 assert!(!body.contains("SECRET-LINK"), "a body is never rendered");
889926 assert!(body.contains("Retry now") && body.contains("/admin/mail/queue/retry"));
890927
891- let (_, failed_only) = send(&fx.router, "GET", "/admin/mail?tab=queue&state=failed", Some(ADMIN_TOKEN), None).await;
928+ let (_, failed_only) = send(
929+ &fx.router,
930+ "GET",
931+ "/admin/mail?tab=queue&state=failed",
932+ Some(ADMIN_TOKEN),
933+ None,
934+ )
935+ .await;
892936 assert!(failed_only.contains("Reset your password"));
893- assert!(!failed_only.contains("Queued one"), "the filter hides queued mail");
937+ assert!(
938+ !failed_only.contains("Queued one"),
939+ "the filter hides queued mail"
940+ );
894941
895942 let (_, settings) = send(&fx.router, "GET", "/admin/mail", Some(ADMIN_TOKEN), None).await;
896943 assert!(!settings.contains("data-live="), "only the queue is live");
897- assert!(!settings.contains("Reset your password"), "the queue is on its own tab");
944+ assert!(
945+ !settings.contains("Reset your password"),
946+ "the queue is on its own tab"
947+ );
898948 }
899949
900950 #[tokio::test]
@@ -905,9 +955,23 @@ mod tests {
905955 ("POST", "/admin/mail/queue/retry"),
906956 ("POST", "/admin/mail/queue/discard"),
907957 ] {
908- let (anon, _) = send(&fx.router, method, uri, None, Some(format!("csrf={CSRF}&id=x"))).await;
958+ let (anon, _) = send(
959+ &fx.router,
960+ method,
961+ uri,
962+ None,
963+ Some(format!("csrf={CSRF}&id=x")),
964+ )
965+ .await;
909966 assert_eq!(anon, 404, "{method} {uri} for anonymous");
910- let (user, _) = send(&fx.router, method, uri, Some(USER_TOKEN), Some(format!("csrf={CSRF}&id=x"))).await;
967+ let (user, _) = send(
968+ &fx.router,
969+ method,
970+ uri,
971+ Some(USER_TOKEN),
972+ Some(format!("csrf={CSRF}&id=x")),
973+ )
974+ .await;
911975 assert_eq!(user, 404, "{method} {uri} for a plain user");
912976 }
913977 }
@@ -937,7 +1001,11 @@ mod tests {
9371001 let fx = fixture().await;
9381002 for key in ["k1", "k2"] {
9391003 let mail = outgoing("a@example.com", "Hi", "b", MailKind::Notification);
940- fx.state.store.enqueue_mail(key, &mail).await.expect("queued");
1004+ fx.state
1005+ .store
1006+ .enqueue_mail(key, &mail)
1007+ .await
1008+ .expect("queued");
9411009 }
9421010 let ids: Vec<String> = fx
9431011 .state
@@ -949,7 +1017,11 @@ mod tests {
9491017 .map(|r| r.id)
9501018 .collect();
9511019 for id in &ids {
952- fx.state.store.mark_mail_failed(id, "550", None).await.expect("failed");
1020+ fx.state
1021+ .store
1022+ .mark_mail_failed(id, "550", None)
1023+ .await
1024+ .expect("failed");
9531025 }
9541026
9551027 let (status, _) = send(
@@ -1000,7 +1072,12 @@ mod tests {
10001072 .await;
10011073 assert_eq!(status, 303, "refused with a notice, not an error");
10021074 assert_eq!(
1003- fx.state.store.list_mail(Some(MailState::Queued), &now, 10).await.expect("queued").len(),
1075+ fx.state
1076+ .store
1077+ .list_mail(Some(MailState::Queued), &now, 10)
1078+ .await
1079+ .expect("queued")
1080+ .len(),
10041081 1
10051082 );
10061083 let (status, _) = send(
crates/forge-web/src/pages/admin_runners.rsmodified+89 -21
@@ -9,6 +9,8 @@
99 use forge_core::AuditAction;
1010 use forge_core::ci::CiRunner;
1111 use serde::Deserialize;
12+use time::OffsetDateTime;
13+use time::format_description::well_known::Rfc3339;
1214 use topcoat::Result;
1315 use topcoat::context::{Cx, app_context};
1416 use topcoat::router::content::Form;
@@ -24,7 +26,7 @@ use crate::i18n::{self, Key, Lang};
2426 use crate::pages::admin_users::admin_only;
2527 use crate::pages::repo_mirrors::stamp_in_tz;
2628 use crate::state::AppState;
27-use crate::views::{enc, shell};
29+use crate::views::{enc, now_unix, relative_time, shell};
2830
2931 path_param!(runner_id);
3032
@@ -54,22 +56,33 @@ struct DisableForm {
5456 /// One runner row, already formatted.
5557 struct RunnerRow {
5658 name: String,
57- labels: String,
59+ labels: Vec<String>,
60+ /// "5 minutes ago", or "never".
5861 last_seen: String,
62+ /// The absolute time in the viewer's zone, for the `title` tooltip. Empty when never seen.
63+ last_seen_full: String,
5964 disabled: bool,
6065 toggle_action: String,
6166 delete_action: String,
6267 }
6368
64-fn runner_row(runner: &CiRunner, tz: &str, lang: Lang) -> RunnerRow {
69+fn runner_row(runner: &CiRunner, tz: &str, lang: Lang, now: i64) -> RunnerRow {
70+ let (last_seen, last_seen_full) = match runner.last_seen_at.as_deref() {
71+ Some(stamp) => {
72+ let full = stamp_in_tz(stamp, tz);
73+ let relative = match OffsetDateTime::parse(stamp, &Rfc3339) {
74+ Ok(at) => relative_time(lang, at.unix_timestamp(), now),
75+ Err(_) => full.clone(),
76+ };
77+ (relative, full)
78+ }
79+ None => (i18n::t(lang, Key::Never).to_owned(), String::new()),
80+ };
6581 RunnerRow {
6682 name: runner.name.clone(),
67- labels: runner.labels.join(", "),
68- last_seen: runner
69- .last_seen_at
70- .as_deref()
71- .map(|stamp| stamp_in_tz(stamp, tz))
72- .unwrap_or_else(|| i18n::t(lang, Key::Never).to_owned()),
83+ labels: runner.labels.clone(),
84+ last_seen,
85+ last_seen_full,
7386 disabled: runner.disabled,
7487 toggle_action: format!("/admin/runners/{}/disabled", enc(&runner.id)),
7588 delete_action: format!("/admin/runners/{}/delete", enc(&runner.id)),
@@ -128,22 +141,34 @@ async fn runners_view(
128141 <table class="table runners">
129142 <thead>
130143 <tr>
131- <th>(g::t(lang, K::TableName))</th>
132- <th>(g::t(lang, K::TableLabels))</th>
133- <th>(g::t(lang, K::LastSeen))</th>
134- <th>(g::t(lang, K::TableState))</th>
135- <th></th>
144+ <th class="runner-name">(g::t(lang, K::TableName))</th>
145+ <th class="runner-labels">(g::t(lang, K::TableLabels))</th>
146+ <th class="runner-seen">(g::t(lang, K::LastSeen))</th>
147+ <th class="runner-state">(g::t(lang, K::TableState))</th>
148+ <th class="runner-actions"></th>
136149 </tr>
137150 </thead>
138151 <tbody>
139152 for row in rows.iter() {
140153 <tr>
141- <td>(row.name.as_str())</td>
142- <td><code>(row.labels.as_str())</code></td>
143- <td class="small">(row.last_seen.as_str())</td>
144- <td>(if row.disabled { g::t(lang, K::Disabled) } else { g::t(lang, K::Enabled) })</td>
145- <td>
146- <div class="actions">
154+ <td class="runner-name"><strong>(row.name.as_str())</strong></td>
155+ <td class="runner-labels">
156+ <span class="runner-label-list">
157+ for label in row.labels.iter() {
158+ <span class="runner-label">(label.as_str())</span>
159+ }
160+ </span>
161+ </td>
162+ <td class="runner-seen small" title=(row.last_seen_full.as_str())>(row.last_seen.as_str())</td>
163+ <td class="runner-state">
164+ if row.disabled {
165+ <span class="ci-state runner-disabled">(g::t(lang, K::Disabled))</span>
166+ } else {
167+ <span class="ci-state ci-success">(g::t(lang, K::Enabled))</span>
168+ }
169+ </td>
170+ <td class="runner-actions">
171+ <div class="runner-action-row">
147172 <form method="post" action=(row.toggle_action.as_str()) class="inline-form">
148173 <input type="hidden" name="csrf" value=(csrf.as_str())>
149174 <input type="hidden" name="disabled" value=(if row.disabled { "0" } else { "1" })>
@@ -205,12 +230,13 @@ async fn runners_page(cx: &Cx) -> Result<impl View> {
205230 let lang = i18n::lang(cx, Some(&viewer.0));
206231 let state = app_context::<AppState>(cx);
207232 let tz = viewer.0.timezone.clone();
233+ let now = now_unix();
208234 let rows: Vec<RunnerRow> = state
209235 .store
210236 .list_runners()
211237 .await?
212238 .iter()
213- .map(|runner| runner_row(runner, &tz, lang))
239+ .map(|runner| runner_row(runner, &tz, lang, now))
214240 .collect();
215241 let csrf = viewer.1.csrf_token.clone();
216242 let notice = notice_from_query(cx, lang);
@@ -491,6 +517,48 @@ mod tests {
491517 assert!(store.list_runners().await.expect("list").is_empty());
492518 }
493519
520+ #[tokio::test]
521+ async fn runner_labels_are_separate_chips_and_state_is_a_badge() {
522+ let dir = tempfile::tempdir().expect("tempdir");
523+ let (store, router) = fixture(dir.path()).await;
524+ let (_, created) = send(
525+ &router,
526+ "POST",
527+ "/admin/runners/tokens",
528+ Some(ADMIN_TOKEN),
529+ csrf_form(""),
530+ )
531+ .await;
532+ let token = created
533+ .split("--token ")
534+ .nth(1)
535+ .and_then(|rest| rest.split(' ').next())
536+ .expect("token")
537+ .to_owned();
538+ store
539+ .register_runner(
540+ &token,
541+ "tahinli-box",
542+ &["linux".to_owned(), "x86_64".to_owned()],
543+ )
544+ .await
545+ .expect("register");
546+ let (status, page) = send(&router, "GET", "/admin/runners", Some(ADMIN_TOKEN), None).await;
547+ assert_eq!(status, 200);
548+ assert!(page.contains(r#"<span class="runner-label">linux</span>"#));
549+ assert!(page.contains(r#"<span class="runner-label">x86_64</span>"#));
550+ assert!(!page.contains("linux, x86_64"), "labels are not joined");
551+ assert!(page.contains(r#"<span class="ci-state ci-success">enabled</span>"#));
552+
553+ let runner = store.list_runners().await.expect("list").remove(0);
554+ store
555+ .set_runner_disabled(&runner.id, true)
556+ .await
557+ .expect("disable");
558+ let (_, page) = send(&router, "GET", "/admin/runners", Some(ADMIN_TOKEN), None).await;
559+ assert!(page.contains(r#"<span class="ci-state runner-disabled">disabled</span>"#));
560+ }
561+
494562 #[tokio::test]
495563 async fn disable_enable_and_delete_a_runner() {
496564 let dir = tempfile::tempdir().expect("tempdir");
crates/forge-web/src/pages/admin_users.rsmodified+7 -4
@@ -2,6 +2,7 @@
22
33 use forge_core::names::{normalize_name, validate_username};
44 use forge_core::store::user_delete::{DeletionReport, GHOST_USERNAME};
5+use forge_core::tz::format_in_tz;
56 use forge_core::{AuditAction, Session, Store, User};
67 use serde::Deserialize;
78 use topcoat::Result;
@@ -15,6 +16,7 @@ use crate::audit::{self, Actor, Target};
1516 use crate::auth::{check_csrf, current_user, hash_password_async};
1617 use crate::i18n::admin::{self as g, K};
1718 use crate::i18n::{self, Key, Lang};
19+use crate::pages::issues_list::stamp_unix;
1820 use crate::state::AppState;
1921 use crate::views::{alert, enc, shell, user_facing_message};
2022
@@ -54,6 +56,7 @@ async fn users_view(
5456 lang: Lang,
5557 csrf: &str,
5658 viewer_id: &str,
59+ tz: &str,
5760 users: Vec<User>,
5861 error: Option<String>,
5962 ) -> Result<impl View> {
@@ -70,10 +73,10 @@ async fn users_view(
7073 <tbody>
7174 for user in users.into_iter() {
7275 <tr>
73- <td>(user.username.clone())</td>
76+ <td class="nowrap">(user.username.clone())</td>
7477 <td>(user.email.clone().unwrap_or_default())</td>
7578 <td>(if user.is_org() { g::t(lang, K::RoleOrganization) } else if user.is_admin { g::t(lang, K::RoleAdmin) } else { g::t(lang, K::RoleUser) })</td>
76- <td class="small">(user.created_at.clone())</td>
79+ <td class="small nowrap">(format_in_tz(stamp_unix(&user.created_at), tz))</td>
7780 <td>
7881 if user.id != viewer_id && !is_ghost(&user) {
7982 <a class="danger" href=(format!("/admin/users/{}/delete", enc(&user.id)))>(i18n::t(lang, Key::Delete))</a>
@@ -123,7 +126,7 @@ async fn users_page(cx: &Cx) -> Result<impl View> {
123126 let csrf = viewer.1.csrf_token.clone();
124127 let title = g::t(lang, K::Users);
125128 Ok(view! {
126- shell(title: title, viewer: Some(&viewer), users_view(lang: lang, csrf: csrf.as_str(), viewer_id: viewer.0.id.as_str(), users: users, error: None))
129+ shell(title: title, viewer: Some(&viewer), users_view(lang: lang, csrf: csrf.as_str(), viewer_id: viewer.0.id.as_str(), tz: viewer.0.timezone.as_str(), users: users, error: None))
127130 })
128131 }
129132
@@ -160,7 +163,7 @@ async fn users_create(cx: &Cx, Form(form): Form<CreateUserForm>) -> Result<impl
160163 let csrf = viewer.1.csrf_token.clone();
161164 let title = g::t(lang, K::Users);
162165 Ok(view! {
163- shell(title: title, viewer: Some(&viewer), users_view(lang: lang, csrf: csrf.as_str(), viewer_id: viewer.0.id.as_str(), users: users, error: Some(message)))
166+ shell(title: title, viewer: Some(&viewer), users_view(lang: lang, csrf: csrf.as_str(), viewer_id: viewer.0.id.as_str(), tz: viewer.0.timezone.as_str(), users: users, error: Some(message)))
164167 })
165168 }
166169 }
crates/forge-web/src/pages/assets.rsmodified+4 -1
@@ -260,7 +260,10 @@ mod tests {
260260 .unwrap();
261261 let res = router.handle(req).await;
262262 assert_eq!(res.status(), 200);
263- assert_eq!(res.headers()["content-type"], "text/javascript; charset=utf-8");
263+ assert_eq!(
264+ res.headers()["content-type"],
265+ "text/javascript; charset=utf-8"
266+ );
264267 assert!(
265268 res.headers()["cache-control"]
266269 .to_str()
crates/forge-web/src/pages/audit_log.rsmodified+7 -7
@@ -95,7 +95,7 @@ async fn audit_table(lang: Lang, rows: Vec<RowView>, show_actor: bool) -> Result
9595 <p class="muted">(g::t(lang, K::NoEntries))</p>
9696 } else {
9797 <div class="table-wrap">
98- <table class="table">
98+ <table class="table audit-table">
9999 <thead>
100100 <tr>
101101 <th>(g::t(lang, K::TableWhen))</th>
@@ -111,13 +111,13 @@ async fn audit_table(lang: Lang, rows: Vec<RowView>, show_actor: bool) -> Result
111111 <tbody>
112112 for row in rows.into_iter() {
113113 <tr>
114- <td class="small">(row.when.as_str())</td>
114+ <td class="small nowrap">(row.when.as_str())</td>
115115 if show_actor {
116116 <td>(row.actor.as_str())</td>
117117 }
118118 <td><code>(row.action.as_str())</code></td>
119119 <td>(row.target.as_str())</td>
120- <td class="small">(row.ip.as_str())</td>
120+ <td class="small nowrap">(row.ip.as_str())</td>
121121 <td class="small">(row.details.as_str())</td>
122122 </tr>
123123 }
@@ -143,17 +143,17 @@ async fn admin_audit_view(
143143 <p class="muted">(g::t(lang, K::AuditIntro))</p>
144144 </section>
145145 <section class="card">
146- <form method="get" action="/admin/audit" class="stack">
147- <label>
146+ <form method="get" action="/admin/audit" class="filter-bar">
147+ <label class="filter-action">
148148 <span>(g::t(lang, K::ActionLabel))</span>
149- <select name="action">
149+ <select name="action" data-autosubmit="true">
150150 <option value="" selected=(action.is_empty())>(g::t(lang, K::AllActions))</option>
151151 for known in AuditAction::ALL.iter().copied() {
152152 <option value=(known.as_str()) selected=(known.as_str() == action.as_str())>(known.as_str())</option>
153153 }
154154 </select>
155155 </label>
156- <label>
156+ <label class="filter-actor">
157157 <span>(g::t(lang, K::ActorUsername))</span>
158158 <input type="text" name="actor" value=(actor.as_str()) autocomplete="off">
159159 </label>
crates/forge-web/src/pages/ci_runs.rsmodified+317 -62
@@ -387,6 +387,11 @@ struct Rect {
387387 h: String,
388388 /// How the client's ticker moves this box with the clock: `grow`, `edge`, `follow` or `rest`.
389389 tick: Option<String>,
390+ /// A job's box on the timeline: its row (`data-j`), the rows it is linked with (`data-rel`, for
391+ /// the hover highlight) and its name with what it needs, for hover and screen readers.
392+ job: Option<String>,
393+ rel: Option<String>,
394+ title: Option<String>,
390395 }
391396
392397 impl Rect {
@@ -398,9 +403,20 @@ impl Rect {
398403 w: w.to_string(),
399404 h: h.to_string(),
400405 tick: None,
406+ job: None,
407+ rel: None,
408+ title: None,
401409 }
402410 }
403411
412+ /// Marks the box as a job's, as its `JobRow` describes it.
413+ fn of_row(mut self, row: &JobRow) -> Rect {
414+ self.job = Some(row.job.clone());
415+ self.rel = Some(row.rel.clone());
416+ self.title = Some(row.title.clone());
417+ self
418+ }
419+
404420 fn ticking(mut self, how: &str) -> Rect {
405421 self.tick = Some(how.to_owned());
406422 self
@@ -423,6 +439,88 @@ struct Label {
423439 follow: Option<String>,
424440 }
425441
442+/// What marks a job's boxes on the timeline: its row, the rows linked with it and its title.
443+struct JobRow {
444+ job: String,
445+ rel: String,
446+ title: String,
447+}
448+
449+/// A dependency connector of the timeline: an elbow from the end of a needed job to the start of the
450+/// job that needs it, with an arrowhead. `rel` names both rows (`j0 j2`) for the hover highlight, and
451+/// `hot` marks a needed job that failed or still runs.
452+#[derive(Debug, PartialEq)]
453+struct Link {
454+ rel: String,
455+ hot: bool,
456+ parts: Vec<LinkPart>,
457+ /// The horizontal run into a waiting job that starts at the moving `now`: a 1-unit high box the
458+ /// ticker grows.
459+ grow: Option<(i64, i64, i64)>,
460+}
461+
462+/// A piece of a connector drawn in a nested SVG placed at `x`, so the ticker can move it with the
463+/// clock (`edge`) like a running box's edge. `line` and `head` are paths relative to `x`.
464+#[derive(Debug, PartialEq)]
465+struct LinkPart {
466+ x: i64,
467+ tick: Option<&'static str>,
468+ line: Option<String>,
469+ head: Option<String>,
470+}
471+
472+/// How far a connector runs out of a box before it turns, in SVG units.
473+const LINK_STUB: i64 = 6;
474+
475+/// The arrowhead of a connector with its tip at (`x`, `y`): pointing right, or down (`dir` 1) or up
476+/// (`dir` -1) when `vertical`.
477+fn arrow_head(x: i64, y: i64, vertical: bool, dir: i64) -> String {
478+ if vertical {
479+ let base = y - dir * 5;
480+ format!("M{} {base} L{x} {y} L{} {base} Z", x - 3, x + 3)
481+ } else {
482+ format!("M{} {} L{x} {y} L{} {} Z", x - 5, y - 3, x - 5, y + 3)
483+ }
484+}
485+
486+/// The elbow from a box ending at `x0` on height `from` to a box starting `dx` further on height `to`,
487+/// in coordinates relative to the end's anchor: out of the end, down or up to the row, and into the
488+/// start. A start too close to the end (or before it) turns back along the row gap. With `spans`, the
489+/// target box spans the end, so the connector drops onto its edge instead.
490+fn elbow(x0: i64, dx: i64, from: i64, to: i64, spans: bool) -> (String, String) {
491+ let dir = if to > from { 1 } else { -1 };
492+ let out = x0 + LINK_STUB;
493+ if spans {
494+ let edge = to - dir * BAR_H / 2;
495+ return (
496+ format!("M{x0} {from} H{out} V{edge}"),
497+ arrow_head(out, edge, true, dir),
498+ );
499+ }
500+ let tip = x0 + dx;
501+ let line = if dx >= 2 * LINK_STUB {
502+ format!("M{x0} {from} H{} V{to} H{tip}", tip - LINK_STUB)
503+ } else {
504+ let gap = from + dir * ROW_H / 2;
505+ format!(
506+ "M{x0} {from} H{out} V{gap} H{} V{to} H{tip}",
507+ tip - LINK_STUB
508+ )
509+ };
510+ (line, arrow_head(tip, to, false, 0))
511+}
512+
513+/// Where a needed job ends on the timeline, in unix seconds, and whether that end moves with the
514+/// clock: a started job's end (now while it runs), or now for a job still queued. None for a job
515+/// that has not queued.
516+fn link_end(job: &Timing, now: i64) -> Option<(i64, bool)> {
517+ match (job.end(now), job.state) {
518+ (Some(end), _) => Some((end, job.finished.is_none())),
519+ (None, JobState::Queued) if job.queued.is_some() => Some((now, true)),
520+ _ => None,
521+ }
522+}
523+
426524 /// The timeline of a run: its SVG viewBox, its boxes, its connectors and its labels, in draw order.
427525 struct Gantt {
428526 view_box: String,
@@ -431,7 +529,7 @@ struct Gantt {
431529 len: String,
432530 live: bool,
433531 rects: Vec<Rect>,
434- links: Vec<String>,
532+ links: Vec<Link>,
435533 labels: Vec<Label>,
436534 }
437535
@@ -609,25 +707,25 @@ fn row_bar(jobs: &[Timing], origin: i64, scale: i64, now: i64, running: bool) ->
609707 bar
610708 }
611709
612-/// The line under a job's name in the timeline: its queueing lead-in when it had one, else what it
613-/// needs.
710+/// The line under a job's name in the timeline: its queueing lead-in when it had one. What it needs
711+/// is drawn as connectors instead.
614712 fn row_sub(job: &Timing, lang: Lang) -> Option<String> {
615- if let (Some(queued), Some(start)) = (job.queued, job.started)
616- && queued < start
617- {
618- return Some(format!(
713+ let (Some(queued), Some(start)) = (job.queued, job.started) else {
714+ return None;
715+ };
716+ (queued < start).then(|| {
717+ format!(
619718 "{} {}",
620719 state_text(lang, "queued"),
621720 g::duration_seconds(lang, start - queued)
622- ));
623- }
624- (!job.needs.is_empty()).then(|| g::needs_label(lang, &job.needs.join(", ")))
721+ )
722+ })
625723 }
626724
627725 /// The timeline of a run, to scale: an axis of round ticks from the run's start, one row per job with
628-/// its box at its real start and end, a hatched lead-in from its queueing, and a dashed connector from
629-/// each needed job's end to the start of the job that needs it. A blocked job is an outline from its
630-/// needs' end, and a skipped or cancelled one is an outline across the track.
726+/// its box at its real start and end, a hatched lead-in from its queueing, and an elbow connector with
727+/// an arrowhead from each needed job's end to the start of the job that needs it. A blocked job is an
728+/// outline from its needs' end, and a skipped or cancelled one is an outline across the track.
631729 fn gantt(jobs: &[Timing], origin: i64, run_end: Option<i64>, now: i64, lang: Lang) -> Gantt {
632730 let last = jobs
633731 .iter()
@@ -670,7 +768,41 @@ fn gantt(jobs: &[Timing], origin: i64, run_end: Option<i64>, now: i64, lang: Lan
670768 ..Default::default()
671769 });
672770 }
771+ let parent_of = |need: &String| jobs.iter().position(|other| other.name == *need);
772+ let rows: Vec<JobRow> = jobs
773+ .iter()
774+ .enumerate()
775+ .map(|(i, job)| {
776+ let mut rel = vec![i];
777+ rel.extend(job.needs.iter().filter_map(parent_of));
778+ rel.extend(
779+ jobs.iter()
780+ .enumerate()
781+ .filter(|(_, other)| other.needs.contains(&job.name))
782+ .map(|(c, _)| c),
783+ );
784+ let rel: Vec<String> = rel.iter().map(|r| format!("j{r}")).collect();
785+ let title = if job.needs.is_empty() {
786+ job.name.clone()
787+ } else {
788+ format!(
789+ "{}, {}",
790+ job.name,
791+ g::needs_label(lang, &job.needs.join(", "))
792+ )
793+ };
794+ JobRow {
795+ job: i.to_string(),
796+ rel: rel.join(" "),
797+ title,
798+ }
799+ })
800+ .collect();
801+ // Where each job's connectors arrive: the left of its first box, whether that moves with the
802+ // clock, and whether the box spans the whole track.
803+ let mut targets: Vec<Option<(i64, bool, bool)>> = Vec::with_capacity(jobs.len());
673804 for (i, job) in jobs.iter().enumerate() {
805+ let row = &rows[i];
674806 let top = AXIS_H + i as i64 * ROW_H;
675807 let bar_y = top + BAR_DY;
676808 let label_y = (bar_y + BAR_H / 2 + 4).to_string();
@@ -695,16 +827,16 @@ fn gantt(jobs: &[Timing], origin: i64, run_end: Option<i64>, now: i64, lang: Lan
695827 match (job.started, job.end(now)) {
696828 (Some(start), Some(end)) => {
697829 let left = x(start);
830+ let mut first = left;
698831 if let Some(queued) = job.queued.filter(|queued| *queued < start) {
699832 let from = x(queued);
700- g.rects.push(Rect::new(
701- "ci-glead",
702- from,
703- bar_y,
704- (left - from).max(MIN_BOX_W),
705- BAR_H,
706- ));
833+ first = from;
834+ g.rects.push(
835+ Rect::new("ci-glead", from, bar_y, (left - from).max(MIN_BOX_W), BAR_H)
836+ .of_row(row),
837+ );
707838 }
839+ targets.push(Some((first, false, false)));
708840 let width = (x(end) - left).max(MIN_BOX_W);
709841 let live = job.finished.is_none();
710842 let mut bar = Rect::new(
@@ -713,7 +845,8 @@ fn gantt(jobs: &[Timing], origin: i64, run_end: Option<i64>, now: i64, lang: Lan
713845 bar_y,
714846 width,
715847 BAR_H,
716- );
848+ )
849+ .of_row(row);
717850 if live {
718851 bar = bar.ticking("grow");
719852 }
@@ -760,35 +893,34 @@ fn gantt(jobs: &[Timing], origin: i64, run_end: Option<i64>, now: i64, lang: Lan
760893 }
761894 _ => match job.state {
762895 JobState::Queued => {
763- if let Some(queued) = job.queued {
896+ let target = job.queued.map(|queued| {
764897 let from = x(queued);
765898 let width = (x(now) - from).max(MIN_BOX_W);
766- g.rects
767- .push(Rect::new("ci-glead", from, bar_y, width, BAR_H).ticking("grow"));
768- }
899+ g.rects.push(
900+ Rect::new("ci-glead", from, bar_y, width, BAR_H)
901+ .ticking("grow")
902+ .of_row(row),
903+ );
904+ (from, false, false)
905+ });
906+ targets.push(target);
769907 }
770908 JobState::Blocked => {
771- let from = job
909+ // The wait starts when the last needed job ends. While that job runs or queues,
910+ // it starts now.
911+ let ends: Vec<(i64, bool)> = job
772912 .needs
773913 .iter()
774- .filter_map(|need| {
775- jobs.iter()
776- .find(|other| other.name == *need)
777- .and_then(|other| other.end(now))
778- })
779- .max()
780- .unwrap_or(origin);
914+ .filter_map(parent_of)
915+ .filter_map(|j| link_end(&jobs[j], now))
916+ .collect();
917+ let from = ends.iter().map(|(end, _)| *end).max().unwrap_or(origin);
918+ let following = ends.iter().any(|(_, moving)| *moving);
781919 let left = x(from);
782- // The wait starts when the last needed job ends. While that job runs, it starts now.
783- let following = job.needs.iter().any(|need| {
784- jobs.iter().any(|other| {
785- other.name == *need
786- && other.started.is_some()
787- && other.finished.is_none()
788- })
789- });
920+ targets.push(Some((left, following, false)));
790921 let mut wait =
791- Rect::new("ci-gbar ci-wait", left, bar_y, track_end - left, BAR_H);
922+ Rect::new("ci-gbar ci-wait", left, bar_y, track_end - left, BAR_H)
923+ .of_row(row);
792924 if following {
793925 wait = wait.ticking("follow");
794926 }
@@ -804,8 +936,10 @@ fn gantt(jobs: &[Timing], origin: i64, run_end: Option<i64>, now: i64, lang: Lan
804936 });
805937 }
806938 JobState::Skipped | JobState::Cancelled => {
807- g.rects
808- .push(Rect::new("ci-gbar ci-wait", TRACK_X, bar_y, TRACK_W, BAR_H));
939+ targets.push(Some((TRACK_X, false, true)));
940+ g.rects.push(
941+ Rect::new("ci-gbar ci-wait", TRACK_X, bar_y, TRACK_W, BAR_H).of_row(row),
942+ );
809943 g.labels.push(Label {
810944 class: "ci-goff",
811945 x: (TRACK_X + 8).to_string(),
@@ -815,28 +949,67 @@ fn gantt(jobs: &[Timing], origin: i64, run_end: Option<i64>, now: i64, lang: Lan
815949 ..Default::default()
816950 });
817951 }
818- _ => {}
952+ _ => targets.push(None),
819953 },
820954 }
821955 }
956+ let xn = x(now);
822957 for (i, job) in jobs.iter().enumerate() {
823- let Some(start) = job.started else {
958+ let Some((tx, child_moves, spans)) = targets[i] else {
824959 continue;
825960 };
826- for need in &job.needs {
827- let Some(j) = jobs.iter().position(|other| other.name == *need) else {
961+ for j in job.needs.iter().filter_map(parent_of) {
962+ let parent = &jobs[j];
963+ let Some((end, parent_moves)) = link_end(parent, now).filter(|_| j != i) else {
828964 continue;
829965 };
830- let Some(end) = jobs[j].end(now) else {
831- continue;
966+ let (from, to) = (row_mid(j), row_mid(i));
967+ let ex = x(end);
968+ let mut link = Link {
969+ rel: format!("j{j} j{i}"),
970+ hot: matches!(
971+ parent.state,
972+ JobState::Failure | JobState::Error | JobState::Running
973+ ),
974+ parts: Vec::new(),
975+ grow: None,
832976 };
833- g.links.push(format!(
834- "M{} {} H{} V{}",
835- x(end),
836- row_mid(j),
837- x(start),
838- row_mid(i)
839- ));
977+ if parent_moves && child_moves {
978+ // Both ends sit at now: the whole elbow rides the clock like a running box's edge.
979+ let (line, head) = elbow(3, 0, from, to, false);
980+ link.parts.push(LinkPart {
981+ x: xn - 3,
982+ tick: Some("edge"),
983+ line: Some(line),
984+ head: Some(head),
985+ });
986+ } else if child_moves {
987+ // The needed job ended but the wait follows now (another need still runs): a fixed
988+ // turn, a run that grows with the clock and an arrowhead that rides it.
989+ link.parts.push(LinkPart {
990+ x: ex,
991+ tick: None,
992+ line: Some(format!("M0 {from} H{LINK_STUB} V{to}")),
993+ head: None,
994+ });
995+ let run_x = ex + LINK_STUB;
996+ link.grow = Some((run_x, to, (xn - run_x).max(MIN_BOX_W)));
997+ link.parts.push(LinkPart {
998+ x: xn - 3,
999+ tick: Some("edge"),
1000+ line: None,
1001+ head: Some(arrow_head(3, to, false, 0)),
1002+ });
1003+ } else {
1004+ let (line, head) = elbow(0, tx - ex, from, to, spans);
1005+ link.parts.push(LinkPart {
1006+ x: ex,
1007+ tick: None,
1008+ line: Some(line),
1009+ head: Some(head),
1010+ });
1011+ }
1012+ g.links.push(link);
8401013 }
8411014 }
8421015 g
@@ -1395,10 +1568,28 @@ async fn runs_body(
13951568 <div class="ci-gantt-scroll">
13961569 <svg class="ci-gantt" viewBox=(g.view_box.as_str()) role="img" aria-label=(g::t(lang, K::Timeline)) data-origin=(g.origin.as_str()) data-len=(g.len.as_str()) data-live-gantt=(g.live.then_some("true"))>
13971570 for r in g.rects.iter() {
1398- <rect class=(r.class.as_str()) x=(r.x.as_str()) y=(r.y.as_str()) width=(r.w.as_str()) height=(r.h.as_str()) data-tick=(r.tick.as_deref())/>
1571+ if let Some(title) = r.title.as_deref() {
1572+ <rect class=(r.class.as_str()) x=(r.x.as_str()) y=(r.y.as_str()) width=(r.w.as_str()) height=(r.h.as_str()) data-tick=(r.tick.as_deref()) data-j=(r.job.as_deref()) data-rel=(r.rel.as_deref()) role="img" aria-label=(title)><title>(title)</title></rect>
1573+ } else {
1574+ <rect class=(r.class.as_str()) x=(r.x.as_str()) y=(r.y.as_str()) width=(r.w.as_str()) height=(r.h.as_str()) data-tick=(r.tick.as_deref())/>
1575+ }
13991576 }
1400- for d in g.links.iter() {
1401- <path class="ci-glink" d=(d.as_str())/>
1577+ for link in g.links.iter() {
1578+ <g class=(if link.hot { "ci-glink ci-hot" } else { "ci-glink" }) data-rel=(link.rel.as_str()) aria-hidden="true">
1579+ if let Some((gx, gy, gw)) = link.grow {
1580+ <rect class="ci-glink-run" x=(gx.to_string()) y=(gy.to_string()) width=(gw.to_string()) height="1" data-tick="grow"/>
1581+ }
1582+ for part in link.parts.iter() {
1583+ <svg x=(part.x.to_string()) y="0" overflow="visible" data-tick=(part.tick)>
1584+ if let Some(line) = part.line.as_deref() {
1585+ <path class="ci-gline" d=(line)/>
1586+ }
1587+ if let Some(head) = part.head.as_deref() {
1588+ <path class="ci-ghead" d=(head)/>
1589+ }
1590+ </svg>
1591+ }
1592+ </g>
14021593 }
14031594 for t in g.labels.iter() {
14041595 <text class=(t.class) x=(t.x.as_str()) y=(t.y.as_str()) text-anchor=(t.anchor) data-since=(t.since.as_deref()) data-pre=(t.pre.as_deref()) data-post=(t.post.as_deref()) data-follow=(t.follow.as_deref())>(t.text.as_str())</text>
@@ -1903,8 +2094,72 @@ mod tests {
19032094 .collect();
19042095 assert_eq!((bars[0].x.as_str(), bars[0].w.as_str()), ("100", "239"));
19052096 assert_eq!((bars[1].x.as_str(), bars[1].w.as_str()), ("339", "279"));
1906- // The connector leaves the end of test and turns down at the start of build.
1907- assert_eq!(g.links, vec!["M339 44 H339 V84".to_owned()]);
2097+ // The connector leaves the end of test, turns down along the row gap and comes into the
2098+ // start of build from the left, with an arrowhead.
2099+ assert_eq!(
2100+ g.links,
2101+ vec![Link {
2102+ rel: "j0 j1".to_owned(),
2103+ hot: false,
2104+ parts: vec![LinkPart {
2105+ x: 339,
2106+ tick: None,
2107+ line: Some("M0 44 H6 V64 H-6 V84 H0".to_owned()),
2108+ head: Some("M-5 81 L0 84 L-5 87 Z".to_owned()),
2109+ }],
2110+ grow: None,
2111+ }]
2112+ );
2113+ // What build needs is in its box's title, not written under its name.
2114+ assert!(!g.labels.iter().any(|l| l.text.contains("needs")));
2115+ assert_eq!(bars[1].title.as_deref(), Some("build, needs test"));
2116+ assert_eq!(bars[1].rel.as_deref(), Some("j1 j0"));
2117+ assert_eq!(bars[0].rel.as_deref(), Some("j0 j1"));
2118+ }
2119+
2120+ #[test]
2121+ fn connectors_turn_late_when_there_is_room_and_reach_upwards() {
2122+ // build is listed first but needs test, which ends at 600 of a 1200 second axis; build starts
2123+ // at 900.
2124+ let mut build = timing("build", JobState::Success, Some(900), Some(900), Some(1200));
2125+ build.needs = vec!["test".to_owned()];
2126+ let test = timing("test", JobState::Failure, Some(0), Some(0), Some(600));
2127+ let g = gantt(&[build, test], 0, Some(1200), 1200, Lang::En);
2128+ let link = &g.links[0];
2129+ assert!(link.hot, "a failed need lights its connector");
2130+ assert_eq!(link.rel, "j1 j0");
2131+ // From test's end (365) up to build's row and into its start (498).
2132+ assert_eq!(link.parts[0].x, 365);
2133+ assert_eq!(link.parts[0].line.as_deref(), Some("M0 84 H127 V44 H133"));
2134+ }
2135+
2136+ #[test]
2137+ fn a_waiting_job_is_linked_to_its_running_need_at_the_clock() {
2138+ let test = timing("test", JobState::Running, Some(0), Some(0), None);
2139+ let mut build = timing("build", JobState::Blocked, None, None, None);
2140+ build.needs = vec!["test".to_owned()];
2141+ let mut lint = timing("lint", JobState::Skipped, None, None, None);
2142+ lint.needs = vec!["build".to_owned()];
2143+ let g = gantt(&[test, build, lint], 0, Some(30), 30, Lang::En);
2144+ // Only build has a need with an end; the connector rides the moving edge.
2145+ assert_eq!(g.links.len(), 1);
2146+ let link = &g.links[0];
2147+ assert!(link.hot, "a running need lights its connector");
2148+ assert_eq!(link.parts[0].tick, Some("edge"));
2149+ assert_eq!(link.parts[0].x, 100 + 265 - 3);
2150+ }
2151+
2152+ #[test]
2153+ fn a_skipped_job_gets_a_drop_onto_its_outline() {
2154+ let broken = timing("broken", JobState::Failure, Some(0), Some(0), Some(30));
2155+ let mut skipme = timing("skipme", JobState::Skipped, None, None, None);
2156+ skipme.needs = vec!["broken".to_owned()];
2157+ let g = gantt(&[broken, skipme], 0, Some(30), 30, Lang::En);
2158+ let part = &g.links[0].parts[0];
2159+ // Out of broken's end (365), down onto the top edge of skipme's outline.
2160+ assert_eq!(part.x, 365);
2161+ assert_eq!(part.line.as_deref(), Some("M0 44 H6 V73"));
2162+ assert_eq!(part.head.as_deref(), Some("M3 68 L6 73 L9 68 Z"));
19082163 }
19092164
19102165 #[test]
crates/forge-web/src/pages/code_search.rsmodified+9 -2
@@ -201,7 +201,8 @@ async fn search_page(cx: &Cx) -> Result<impl View> {
201201 let path_value = path_glob;
202202 let ref_label = ref_name.clone();
203203
204- let header = ctx.head(state, "code").await?;
204+ let mut header = ctx.head(state, "code").await?;
205+ header.hide_search = true;
205206 Ok(view! {
206207 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
207208 repo_head(head: header)
@@ -346,7 +347,13 @@ mod route_tests {
346347 .unwrap();
347348 let demo = state
348349 .store
349- .create_repo(&tahinli.id, "demo", "A demo repo", Visibility::Public, "main")
350+ .create_repo(
351+ &tahinli.id,
352+ "demo",
353+ "A demo repo",
354+ Visibility::Public,
355+ "main",
356+ )
350357 .await
351358 .unwrap();
352359 let secret = state
crates/forge-web/src/pages/compare.rsmodified+2 -1
@@ -644,7 +644,8 @@ mod tests {
644644 ],
645645 );
646646
647- crate::test_support::create_session(&store, &tahinli.id, "tahinli-token", TAHINLI_CSRF).await;
647+ crate::test_support::create_session(&store, &tahinli.id, "tahinli-token", TAHINLI_CSRF)
648+ .await;
648649 Self {
649650 router,
650651 store,
crates/forge-web/src/pages/dashboard.rsmodified+1 -1
@@ -178,7 +178,7 @@ async fn dashboard(dash: Dashboard, lang: Lang) -> Result<impl View> {
178178 <ul class="attn">
179179 for item in dash.attention.into_iter() {
180180 <li>
181- <a href=(item.href.as_str())><span class="mono">(item.reference.as_str())</span> (item.title.as_str())</a>
181+ <a href=(item.href.as_str())><span class="mono">(item.reference.as_str())</span>" "(item.title.as_str())</a>
182182 <span class="sub">(item.kind) " · " (item.relative.as_str())</span>
183183 </li>
184184 }
crates/forge-web/src/pages/discussion_view.rsmodified+5 -3
@@ -196,7 +196,7 @@ async fn comment_article(item: CommentView) -> Result<impl View> {
196196 if let Some(bar) = reactions {
197197 reaction_row(lang: lang, bar: bar)
198198 }
199- <div class="issue-item-actions">
199+ <div class="discussion-actions">
200200 if let Some(action) = answer_action {
201201 <form method="post" action=(action.as_str())>
202202 <input type="hidden" name="csrf" value=(csrf.as_str())>
@@ -404,7 +404,7 @@ async fn discussion_page(
404404 <section class="issue-head">
405405 <h1 class="issue-heading">(discussion.title.as_str()) " " <span class="issue-number">(number_label.as_str())</span></h1>
406406 <p class="issue-byline">
407- <span class="label-chip">(category)</span>
407+ <span class="discussion-category">(category)</span>
408408 if answered {
409409 " " <span class="issue-badge issue-badge-completed">(g::t(lang, K::Answered))</span>
410410 }
@@ -430,6 +430,7 @@ async fn discussion_page(
430430 reaction_row(lang: lang, bar: bar)
431431 }
432432 if body_mine_actions {
433+ <div class="discussion-actions">
433434 <details class="discussion-reply">
434435 <summary>(g::t(lang, K::Edit))</summary>
435436 <form method="post" action=(edit_action.as_str()) class="stack">
@@ -447,6 +448,7 @@ async fn discussion_page(
447448 <input type="hidden" name="csrf" value=(csrf.as_str())>
448449 <button type="submit" class="link-button">(g::t(lang, K::DeleteDiscussion))</button>
449450 </form>
451+ </div>
450452 }
451453 </article>
452454 for thread in threads.into_iter() {
@@ -461,7 +463,7 @@ async fn discussion_page(
461463 <textarea name="body" rows="6"></textarea>
462464 <span class="muted small">(g::t(lang, K::MarkdownSupported))</span>
463465 </label>
464- <div><button type="submit">(g::t(lang, K::CommentButton))</button></div>
466+ <div><button type="submit" class="primary">(g::t(lang, K::CommentButton))</button></div>
465467 </form>
466468 </section>
467469 } else if locked && signed_in && !archived {
crates/forge-web/src/pages/discussions.rsmodified+2 -2
@@ -323,7 +323,7 @@ async fn discussions_list_page(cx: &Cx) -> Result<impl View> {
323323 <div class="issue-main">
324324 <div class="issue-title-line">
325325 <a class="issue-title" href=(row.href.as_str())>(row.title.as_str())</a>
326- <span class="label-chip">(row.category)</span>
326+ <span class="discussion-category">(row.category)</span>
327327 </div>
328328 <div class="issue-meta muted small">
329329 <span>(by_before)</span>
@@ -399,7 +399,7 @@ async fn new_discussion_body(
399399 <textarea name="body" rows="12">(draft.body.as_str())</textarea>
400400 <span class="muted small">(g::t(lang, K::MarkdownSupported))</span>
401401 </label>
402- <div class="inline-form">
402+ <div class="issue-actions">
403403 <button type="submit" class="primary">(g::t(lang, K::StartDiscussion))</button>
404404 <a href=(cancel.as_str())>(g::t(lang, K::Cancel))</a>
405405 </div>
crates/forge-web/src/pages/edit_history.rsmodified+8 -2
@@ -589,7 +589,10 @@ mod tests {
589589 .await
590590 .unwrap();
591591
592- let link = format!("/tahinli/demo/pulls/1/history/review_comment/{}", comment.id);
592+ let link = format!(
593+ "/tahinli/demo/pulls/1/history/review_comment/{}",
594+ comment.id
595+ );
593596 let (status, history) = send(&fx.router, &link, None).await;
594597 assert_eq!(status, 200);
595598 assert!(history.contains("-first"), "{history}");
@@ -598,7 +601,10 @@ mod tests {
598601 // The same comment under the issue URL is not on that item.
599602 let (status, _) = send(
600603 &fx.router,
601- &format!("/tahinli/demo/issues/1/history/review_comment/{}", comment.id),
604+ &format!(
605+ "/tahinli/demo/issues/1/history/review_comment/{}",
606+ comment.id
607+ ),
602608 None,
603609 )
604610 .await;
crates/forge-web/src/pages/explore.rsmodified+17 -73
@@ -13,7 +13,10 @@ use crate::auth::current_user;
1313 use crate::i18n::orgs::{self as g, K};
1414 use crate::i18n::{self, Lang};
1515 use crate::state::AppState;
16-use crate::views::{enc, now_unix, relative_time, repo_href, shell};
16+use crate::views::repo_list::{
17+ PageLink, RepoRow, SortLink, pager, pager_links, repo_rows, sort_chips,
18+};
19+use crate::views::{enc, now_unix, shell};
1720
1821 const PER_PAGE: u64 = 30;
1922 /// Longest search text kept, in characters.
@@ -34,22 +37,6 @@ struct ExploreQuery {
3437 page: Option<String>,
3538 }
3639
37-/// One listed repo, already formatted for display.
38-struct ExploreRow {
39- href: String,
40- title: String,
41- description: String,
42- stars: u64,
43- updated: String,
44-}
45-
46-/// One sort link: its label, target and whether it is the active order.
47-struct SortLink {
48- label: &'static str,
49- href: String,
50- current: bool,
51-}
52-
5340 /// `/explore` with the given search, sort key and page. An empty search is left out.
5441 fn explore_href(q: &str, sort: &str, page: u64) -> String {
5542 let mut href = String::from("/explore?");
@@ -71,12 +58,6 @@ fn sort_key(raw: Option<&str>) -> &'static str {
7158 .unwrap_or(SORTS[0].0)
7259 }
7360
74-/// Unix seconds of a stored RFC 3339 stamp. An unreadable stamp gives 0.
75-fn stamp_unix(stamp: &str) -> i64 {
76- time::OffsetDateTime::parse(stamp, &time::format_description::well_known::Rfc3339)
77- .map_or(0, |t| t.unix_timestamp())
78-}
79-
8061 #[page("/explore")]
8162 async fn explore_page(cx: &Cx) -> Result<impl View> {
8263 let query = query_params::<ExploreQuery>(cx)?;
@@ -111,15 +92,10 @@ async fn explore_page(cx: &Cx) -> Result<impl View> {
11192 .await?;
11293
11394 let now = now_unix();
114- let rows: Vec<ExploreRow> = listed
95+ let tz = viewer.as_ref().map_or("UTC", |(u, _)| u.timezone.as_str());
96+ let rows: Vec<RepoRow> = listed
11597 .into_iter()
116- .map(|(repo, stars, updated)| ExploreRow {
117- href: repo_href(&repo.owner_name, &repo.name, "", ""),
118- title: format!("{}/{}", repo.owner_name, repo.name),
119- description: repo.description,
120- stars,
121- updated: relative_time(lang, stamp_unix(&updated), now),
122- })
98+ .map(|listed| RepoRow::new(lang, tz, now, listed))
12399 .collect();
124100 let orgs: Vec<String> = state
125101 .store
@@ -129,6 +105,7 @@ async fn explore_page(cx: &Cx) -> Result<impl View> {
129105 .map(|org| org.username)
130106 .collect();
131107 let pages = total.div_ceil(PER_PAGE).max(1);
108+ let page = page.min(pages);
132109 let sort_links: Vec<SortLink> = SORTS
133110 .iter()
134111 .map(|(key, label)| SortLink {
@@ -137,14 +114,13 @@ async fn explore_page(cx: &Cx) -> Result<impl View> {
137114 current: *key == sort,
138115 })
139116 .collect();
140- let prev = (page > 1).then(|| explore_href(&q, sort, page - 1));
141- let next = (page < pages).then(|| explore_href(&q, sort, page + 1));
117+ let nav = pager_links(page, pages, |n| explore_href(&q, sort, n));
142118 let title = g::t(lang, K::Explore);
143119
144120 Ok(view! { cx =>
145121 shell(title: title, viewer: viewer.as_ref(),
146122 explore_body(q: q, sort: sort, sort_links: sort_links, rows: rows,
147- total: total, page: page, pages: pages, prev: prev, next: next, orgs: orgs, lang: lang))
123+ total: total, page: page, pages: pages, nav: nav, orgs: orgs, lang: lang))
148124 })
149125 }
150126
@@ -153,17 +129,17 @@ async fn explore_body(
153129 q: String,
154130 sort: &'static str,
155131 sort_links: Vec<SortLink>,
156- rows: Vec<ExploreRow>,
132+ rows: Vec<RepoRow>,
157133 total: u64,
158134 page: u64,
159135 pages: u64,
160- prev: Option<String>,
161- next: Option<String>,
136+ nav: (Vec<PageLink>, Option<String>, Option<String>),
162137 orgs: Vec<String>,
163138 lang: Lang,
164139 ) -> Result<impl View> {
165140 let empty = rows.is_empty();
166141 let has_orgs = !orgs.is_empty();
142+ let (links, prev, next) = nav;
167143 Ok(view! {
168144 <section class="explore">
169145 <h1>(g::t(lang, K::Explore))</h1>
@@ -179,51 +155,19 @@ async fn explore_body(
179155 </section>
180156 }
181157 <form method="get" action="/explore" class="explore-search" role="search">
182- <input type="search" name="q" value=(q.as_str())
158+ <input type="search" name="q" value=(q.as_str()) data-live-search=""
183159 placeholder=(g::t(lang, K::SearchPublicRepos)) aria-label=(g::t(lang, K::SearchPublicRepos))>
184160 <input type="hidden" name="sort" value=(sort)>
185161 <button type="submit">(g::t(lang, K::Search))</button>
186162 </form>
187- <nav class="explore-sort" aria-label=(g::t(lang, K::SortNav))>
188- <span class="muted small">(g::t(lang, K::SortBy))</span>
189- for link in sort_links.into_iter() {
190- if link.current {
191- <span class="current" aria-current="true">(link.label)</span>
192- } else {
193- <a href=(link.href.as_str())>(link.label)</a>
194- }
195- }
196- </nav>
163+ sort_chips(links: sort_links, lang: lang)
197164 <p class="muted small">(g::repo_count(lang, total))</p>
198165 if empty {
199166 <p class="muted">(g::t(lang, K::NoPublicReposMatch))</p>
200167 } else {
201- <ul class="repo-list">
202- for row in rows.into_iter() {
203- <li class="repo-item">
204- <a class="repo-name" href=(row.href.as_str())>(row.title.as_str())</a>
205- if !row.description.is_empty() {
206- <p class="muted">(row.description.as_str())</p>
207- }
208- <p class="muted small">
209- "\u{2605} " (row.stars.to_string())
210- (g::updated_text(lang, row.updated.as_str()))
211- </p>
212- </li>
213- }
214- </ul>
215- }
216- if pages > 1 {
217- <nav class="pager" aria-label=(g::t(lang, K::Pages))>
218- if let Some(href) = prev {
219- <a href=(href.as_str())>(g::t(lang, K::Previous))</a>
220- }
221- <span class="muted small">(g::page_of(lang, page, pages))</span>
222- if let Some(href) = next {
223- <a href=(href.as_str())>(g::t(lang, K::Next))</a>
224- }
225- </nav>
168+ repo_rows(rows: rows, lang: lang)
226169 }
170+ pager(page: page, pages: pages, links: links, prev: prev, next: next, lang: lang)
227171 </section>
228172 })
229173 }
crates/forge-web/src/pages/fork.rsmodified+7 -1
@@ -169,7 +169,13 @@ mod tests {
169169 .await
170170 .expect("carol");
171171 let demo = store
172- .create_repo(&tahinli.id, "demo", "A demo repo", Visibility::Public, "main")
172+ .create_repo(
173+ &tahinli.id,
174+ "demo",
175+ "A demo repo",
176+ Visibility::Public,
177+ "main",
178+ )
173179 .await
174180 .expect("demo");
175181 let secret = store
crates/forge-web/src/pages/issue_view.rsmodified+3 -2
@@ -230,7 +230,7 @@ async fn edit_item_page(
230230 <textarea name="body" rows="12">(body.as_str())</textarea>
231231 </label>
232232 <div class="issue-actions">
233- <button type="submit">(g::t(lang, K::SaveChanges))</button>
233+ <button type="submit" class="primary">(g::t(lang, K::SaveChanges))</button>
234234 <a href=(back.as_str())>(g::t(lang, K::Cancel))</a>
235235 </div>
236236 </form>
@@ -612,7 +612,8 @@ mod tests {
612612 .unwrap()
613613 .is_none()
614614 {
615- crate::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf").await;
615+ crate::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf")
616+ .await;
616617 }
617618 owner
618619 }
crates/forge-web/src/pages/labels_page.rsmodified+10 -3
@@ -448,11 +448,18 @@ mod tests {
448448 #[tokio::test]
449449 async fn button_shows_only_for_triage_when_no_labels() {
450450 let site = site().await;
451- let (status, body) =
452- send(&site, "GET", "/tahinli/forge/labels", Some(&site.carol), CSRF).await;
451+ let (status, body) = send(
452+ &site,
453+ "GET",
454+ "/tahinli/forge/labels",
455+ Some(&site.carol),
456+ CSRF,
457+ )
458+ .await;
453459 assert_eq!(status, 200);
454460 assert!(body.contains("/tahinli/forge/labels/defaults"));
455- let (status, body) = send(&site, "GET", "/tahinli/forge/labels", Some(&site.bob), CSRF).await;
461+ let (status, body) =
462+ send(&site, "GET", "/tahinli/forge/labels", Some(&site.bob), CSRF).await;
456463 assert_eq!(status, 200);
457464 assert!(!body.contains("/labels/defaults"));
458465 }
crates/forge-web/src/pages/login.rsmodified+6 -3
@@ -492,7 +492,8 @@ mod tests {
492492
493493 post_login(&router, from, (&token.0, &token.1), "tahinli", guess).await;
494494 post_login(&router, from, (&token.0, &token.1), "ghost", guess).await;
495- let (status, _) = post_login(&router, from, (&token.0, &token.1), "tahinli", PASSWORD).await;
495+ let (status, _) =
496+ post_login(&router, from, (&token.0, &token.1), "tahinli", PASSWORD).await;
496497 assert_eq!(status, 303);
497498
498499 let tahinli = state
@@ -563,12 +564,14 @@ mod tests {
563564 for _ in 0..9 {
564565 post_login(&router, from, (&token.0, &token.1), "tahinli", "wrong").await;
565566 }
566- let (status, _) = post_login(&router, from, (&token.0, &token.1), "tahinli", PASSWORD).await;
567+ let (status, _) =
568+ post_login(&router, from, (&token.0, &token.1), "tahinli", PASSWORD).await;
567569 assert_eq!(status, 303);
568570 for _ in 0..9 {
569571 post_login(&router, from, (&token.0, &token.1), "tahinli", "wrong").await;
570572 }
571- let (status, _) = post_login(&router, from, (&token.0, &token.1), "tahinli", PASSWORD).await;
573+ let (status, _) =
574+ post_login(&router, from, (&token.0, &token.1), "tahinli", PASSWORD).await;
572575 assert_eq!(status, 303);
573576 }
574577
crates/forge-web/src/pages/mod.rsmodified+1 -0
@@ -44,6 +44,7 @@ pub mod login;
4444 pub mod media;
4545 pub mod milestones_page;
4646 pub mod new_repo;
47+pub mod not_found_page;
4748 pub mod notifications;
4849 pub mod org_ctx;
4950 pub mod org_members;
crates/forge-web/src/pages/not_found_page.rsadded+83 -0
@@ -0,0 +1,83 @@
1+//! The styled 404 page. Topcoat answers a `not_found()` error with a bare text body, so this layer
2+//! swaps that body for the regular shell plus a short message, for browser requests only.
3+
4+use http::header::ACCEPT;
5+use topcoat::Result;
6+use topcoat::context::Cx;
7+use topcoat::router::error::{NotFoundError, rewrite};
8+use topcoat::router::page;
9+use topcoat::router::request::headers;
10+use topcoat::router::response::Response;
11+use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, StatusCode};
12+use topcoat::view::{View, component, view};
13+
14+use crate::auth::current_user;
15+use crate::i18n::{self, Lang};
16+use crate::views::shell;
17+
18+pub struct NotFoundLayer;
19+
20+impl Layer for NotFoundLayer {
21+ fn path(&self) -> Option<&Path> {
22+ None
23+ }
24+
25+ fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
26+ Box::pin(styled_not_found(cx, body, next))
27+ }
28+}
29+
30+fn texts(lang: Lang) -> (&'static str, &'static str, &'static str) {
31+ match lang {
32+ Lang::En => (
33+ "Page not found",
34+ "The page does not exist, or you do not have access to it.",
35+ "Back to the start",
36+ ),
37+ Lang::Tr => (
38+ "Sayfa bulunamadı",
39+ "Sayfa yok ya da erişim izniniz yok.",
40+ "Başa dön",
41+ ),
42+ }
43+}
44+
45+#[component]
46+async fn not_found_body(lang: Lang) -> Result<impl View> {
47+ let (title, hint, back) = texts(lang);
48+ Ok(view! {
49+ <section class="not-found">
50+ <p class="not-found-code">"404"</p>
51+ <h1>(title)</h1>
52+ <p class="muted">(hint)</p>
53+ <a class="button primary" href="/">(back)</a>
54+ </section>
55+ })
56+}
57+
58+async fn styled_not_found(cx: &Cx, body: Body, next: Next<'_>) -> Result<Response> {
59+ let result = next.run(cx, body).await;
60+ let is_not_found = matches!(&result, Err(e) if e.downcast_ref::<NotFoundError>().is_some());
61+ let wants_html = headers(cx)
62+ .get(ACCEPT)
63+ .and_then(|v| v.to_str().ok())
64+ .is_some_and(|v| v.contains("text/html"));
65+ if !is_not_found || !wants_html {
66+ return result;
67+ }
68+ Err(rewrite(PATH, Body::empty()).method(Method::GET).into())
69+}
70+
71+/// Where the layer sends a browser's 404. The page answers with status 404 itself.
72+const PATH: &str = "/-/not-found";
73+
74+#[page("/-/not-found")]
75+async fn not_found_page(cx: &Cx) -> Result<impl View> {
76+ let viewer = current_user(cx).await?;
77+ let lang = i18n::lang(cx, viewer.as_ref().map(|(user, _)| user));
78+ let title = texts(lang).0;
79+ Ok(view! {
80+ (StatusCode::NOT_FOUND)
81+ shell(title: title, viewer: viewer.as_ref(), not_found_body(lang: lang))
82+ })
83+}
crates/forge-web/src/pages/org_ctx.rsmodified+8 -36
@@ -181,46 +181,18 @@ pub fn take_notice(cx: &Cx, lang: Lang) -> Option<(&'static str, bool)> {
181181 .map(|(_, key, is_error)| (g::t(lang, *key), *is_error))
182182 }
183183
184-/// The org's name, description and tabs. `active` is `members`, `teams` or `settings`.
184+/// The org's name and description. The members, teams and settings links live in the shell
185+/// sidebar (see `views::section_for`).
185186 #[component]
186-pub async fn org_head(
187- name: String,
188- description: String,
189- active: &'static str,
190- is_owner: bool,
191- lang: Lang,
192-) -> Result<impl View> {
193- let members_href = format!("/org/{name}/members");
194- let teams_href = format!("/org/{name}/teams");
195- let settings_href = format!("/org/{name}/settings");
196- let members_tab = active == "members";
197- let teams_tab = active == "teams";
198- let settings_tab = active == "settings";
187+pub async fn org_head(name: String, description: String) -> Result<impl View> {
199188 Ok(view! {
200189 <section class="page-head org-head">
201- <h1>(name.as_str())</h1>
202- if !description.is_empty() {
203- <p class="muted">(description.as_str())</p>
204- }
205- <nav class="org-tabs" aria-label=(g::t(lang, K::Organization))>
206- if members_tab {
207- <span class="current" aria-current="true">(g::t(lang, K::Members))</span>
208- } else {
209- <a href=(members_href.as_str())>(g::t(lang, K::Members))</a>
210- }
211- if teams_tab {
212- <span class="current" aria-current="true">(g::t(lang, K::Teams))</span>
213- } else {
214- <a href=(teams_href.as_str())>(g::t(lang, K::Teams))</a>
215- }
216- if is_owner {
217- if settings_tab {
218- <span class="current" aria-current="true">(g::t(lang, K::Settings))</span>
219- } else {
220- <a href=(settings_href.as_str())>(g::t(lang, K::Settings))</a>
221- }
190+ <div class="org-head-text">
191+ <h1>(name.as_str())</h1>
192+ if !description.is_empty() {
193+ <p class="muted">(description.as_str())</p>
222194 }
223- </nav>
195+ </div>
224196 </section>
225197 })
226198 }
crates/forge-web/src/pages/org_members.rsmodified+1 -1
@@ -82,7 +82,7 @@ async fn members_body(
8282 let remove_action = format!("{base}/members/remove");
8383 let add_action = format!("{base}/members/add");
8484 Ok(view! {
85- org_head(name: name, description: description, active: "members", is_owner: owner, lang: lang)
85+ org_head(name: name, description: description)
8686 org_notice(notice: notice)
8787 <section class="card">
8888 <h2>(g::t(lang, K::Members))</h2>
crates/forge-web/src/pages/org_settings.rsmodified+1 -1
@@ -63,7 +63,7 @@ async fn settings_body(
6363 let delete_action = format!("{base}/settings/delete");
6464 let confirm_label = g::type_to_confirm(lang, &name);
6565 Ok(view! {
66- org_head(name: name, description: description.clone(), active: "settings", is_owner: true, lang: lang)
66+ org_head(name: name, description: description.clone())
6767 org_notice(notice: notice)
6868 <section class="card">
6969 <h2>(g::t(lang, K::Settings))</h2>
crates/forge-web/src/pages/org_teams.rsmodified+5 -5
@@ -164,7 +164,7 @@ async fn teams_body(
164164 ) -> Result<impl View> {
165165 let create_action = format!("{base}/teams/new");
166166 Ok(view! {
167- org_head(name: name, description: description, active: "teams", is_owner: owner, lang: lang)
167+ org_head(name: name, description: description)
168168 org_notice(notice: notice)
169169 <section class="card">
170170 <h2>(g::t(lang, K::Teams))</h2>
@@ -271,7 +271,7 @@ async fn team_body(
271271 let has_choices = !data.choices.is_empty();
272272 let has_description = !data.team_description.is_empty();
273273 Ok(view! {
274- org_head(name: data.org_name.clone(), description: data.org_description.clone(), active: "teams", is_owner: owner, lang: lang)
274+ org_head(name: data.org_name.clone(), description: data.org_description.clone())
275275 org_notice(notice: notice)
276276 <section class="card">
277277 <h2>(data.team_name.as_str())</h2>
@@ -306,7 +306,7 @@ async fn team_body(
306306 <button type="submit" class="primary">(g::t(lang, K::SaveTeam))</button>
307307 </div>
308308 </form>
309- <form method="post" action=(delete_action.as_str()) class="inline-form">
309+ <form method="post" action=(delete_action.as_str()) class="team-form">
310310 <input type="hidden" name="csrf" value=(csrf.as_str())>
311311 <button type="submit" class="danger">(g::t(lang, K::DeleteTeam))</button>
312312 </form>
@@ -338,7 +338,7 @@ async fn team_body(
338338 </ul>
339339 }
340340 if owner {
341- <form method="post" action=(add_member_action.as_str()) class="inline-form">
341+ <form method="post" action=(add_member_action.as_str()) class="team-form">
342342 <input type="hidden" name="csrf" value=(csrf.as_str())>
343343 <input type="text" name="username" placeholder=(g::t(lang, K::Username)) aria-label=(g::t(lang, K::Username)) autocomplete="off" spellcheck="false" required=(true)>
344344 <button type="submit">(g::t(lang, K::AddToTeam))</button>
@@ -368,7 +368,7 @@ async fn team_body(
368368 </ul>
369369 }
370370 if owner && has_choices {
371- <form method="post" action=(add_repo_action.as_str()) class="inline-form">
371+ <form method="post" action=(add_repo_action.as_str()) class="team-form">
372372 <input type="hidden" name="csrf" value=(csrf.as_str())>
373373 <select name="repo_id" aria-label=(g::t(lang, K::Repository))>
374374 for choice in data.choices.iter() {
crates/forge-web/src/pages/profile.rsmodified+173 -156
@@ -1,12 +1,15 @@
11 //! Page: public profile at `/{username}`. Avatar, about (rendered markdown) and local time, then
22 //! three tabs: `overview` (pinned repos, or the most recently active ones when nothing is pinned,
33 //! plus an organization's members and teams), `repositories` and `stars`. The repo tabs list what
4-//! the viewer is allowed to read, 30 per page, with a name filter. Fixed single-segment routes are
5-//! registered statically, so they win over this parameter route.
4+//! the viewer is allowed to read, 30 per page, with a name filter and three sort orders; the
5+//! filtering, sorting and paging run in the database. Fixed single-segment routes are registered
6+//! statically, so they win over this parameter route.
67
78 use forge_core::authz::{Action, authorize};
9+use forge_core::store::RepoSort;
810 use forge_core::store::orgs::OrgMemberRole;
911 use forge_core::store::profile_pins::MAX_PROFILE_PINS;
12+use forge_core::store::repo_listing::RepoScope;
1013 use forge_core::tz::local_time_now;
1114 use forge_core::{Repo, User, Visibility};
1215 use topcoat::Result;
@@ -22,12 +25,15 @@ use crate::i18n::{self, Lang};
2225 use crate::pages::dashboard::badge_class;
2326 use crate::render::markdown::render_markdown;
2427 use crate::state::AppState;
28+use crate::views::repo_list::{
29+ PageLink, RepoRow, SortLink, pager, pager_links, repo_rows, sort_chips,
30+};
2531 use crate::views::{avatar_url, enc, now_unix, repo_href, shell};
2632
2733 path_param!(username);
2834
2935 /// Repos per page on the repositories and stars tabs.
30-const PER_PAGE: usize = 30;
36+const PER_PAGE: u64 = 30;
3137 /// Repos the overview shows when the owner has no visible pins.
3238 const POPULAR_COUNT: usize = 6;
3339 /// Longest name filter kept, in characters.
@@ -37,9 +43,27 @@ const MAX_QUERY_CHARS: usize = 100;
3743 struct ProfileQuery {
3844 tab: Option<String>,
3945 q: Option<String>,
46+ sort: Option<String>,
4047 page: Option<String>,
4148 }
4249
50+/// Sort keys of the repo tabs in the order their chips are shown, with the label of each. The
51+/// first one is the default.
52+const SORTS: [(&str, K); 3] = [
53+ ("updated", K::SortRecentlyUpdated),
54+ ("name", K::Name),
55+ ("stars", K::SortMostStars),
56+];
57+
58+/// Maps the `sort` query value to a key from `SORTS`; anything unknown means the default.
59+fn sort_key(raw: Option<&str>) -> &'static str {
60+ SORTS
61+ .iter()
62+ .map(|(key, _)| *key)
63+ .find(|key| Some(*key) == raw)
64+ .unwrap_or(SORTS[0].0)
65+}
66+
4367 #[page("/{username}")]
4468 async fn profile_page(cx: &Cx) -> Result<impl View> {
4569 let name = path_param::<Username>(cx);
@@ -71,24 +95,13 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
7195 .take(MAX_QUERY_CHARS)
7296 .collect();
7397 let page = page_number(query.page.as_deref());
98+ let sort = sort_key(query.sort.as_deref());
7499
75- // Both lists are read once and filtered by visibility; the tab labels count what is readable.
76- let repos = readable(
77- state,
78- actor,
79- state.store.list_repos_by_owner(&user.id).await?,
80- usize::MAX,
81- )
82- .await?;
83- let starred = readable(
84- state,
85- actor,
86- state.store.starred_repos(&user.id).await?,
87- usize::MAX,
88- )
89- .await?;
90- let repo_total = repos.len();
91- let star_total = starred.len();
100+ // The tab labels count what the viewer may read, with no filter.
101+ let owned = RepoScope::OwnedBy(&user.id);
102+ let starred = RepoScope::StarredBy(&user.id);
103+ let repo_total = state.store.count_visible_repos(owned, actor).await?;
104+ let star_total = state.store.count_visible_repos(starred, actor).await?;
92105
93106 // The overview shows the owner's pins that the viewer may read. With none visible, it shows
94107 // the most recently active repos instead.
@@ -136,30 +149,54 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
136149 let edit_profile = !user.is_org() && actor.is_some_and(|u| u.id == user.id);
137150
138151 let listing = match tab {
139- "repositories" => paginate(
140- repos,
141- &user.username,
142- tab,
143- &q,
144- page,
145- if q.is_empty() {
146- g::t(lang, K::NoVisibleRepos)
147- } else {
148- g::t(lang, K::NoReposMatch)
149- },
150- ),
151- "stars" => paginate(
152- starred,
153- &user.username,
154- tab,
155- &q,
156- page,
157- if q.is_empty() {
158- g::t(lang, K::NoVisibleStarred)
152+ "repositories" | "stars" => {
153+ let scope = if tab == "stars" { starred } else { owned };
154+ let sort_kind = match sort {
155+ "stars" => RepoSort::MostStars,
156+ "name" => RepoSort::Name,
157+ _ => RepoSort::RecentlyUpdated,
158+ };
159+ let search = (!q.is_empty()).then_some(q.as_str());
160+ let (listed, total) = state
161+ .store
162+ .list_visible_repos(scope, actor, search, sort_kind, page, PER_PAGE)
163+ .await?;
164+ let tz = actor.map_or("UTC", |u| u.timezone.as_str());
165+ let now = now_unix();
166+ let empty = match (tab, q.is_empty()) {
167+ (_, false) => g::t(lang, K::NoReposMatch),
168+ ("stars", true) => g::t(lang, K::NoVisibleStarred),
169+ _ => g::t(lang, K::NoVisibleRepos),
170+ };
171+ let count_text = if tab == "stars" {
172+ g::starred_count(lang, total)
159173 } else {
160- g::t(lang, K::NoReposMatch)
161- },
162- ),
174+ g::repo_count(lang, total)
175+ };
176+ let pages = total.div_ceil(PER_PAGE).max(1);
177+ let page = page.min(pages);
178+ Listing {
179+ rows: listed
180+ .into_iter()
181+ .map(|listed| RepoRow::new(lang, tz, now, listed))
182+ .collect(),
183+ page,
184+ pages,
185+ pager: pager_links(page, pages, |n| {
186+ profile_href(&user.username, tab, &q, sort, n)
187+ }),
188+ sort_links: SORTS
189+ .iter()
190+ .map(|(key, label)| SortLink {
191+ label: g::t(lang, *label),
192+ href: profile_href(&user.username, tab, &q, key, 1),
193+ current: *key == sort,
194+ })
195+ .collect(),
196+ count_text,
197+ empty,
198+ }
199+ }
163200 _ => Listing::default(),
164201 };
165202
@@ -182,7 +219,7 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
182219 Ok(view! { cx =>
183220 shell(title: title.as_str(), viewer: viewer.as_ref(),
184221 profile_card(user: user, avatar: avatar, about_html: about_html, local_time: local_time,
185- org: org, lang: lang, tab: tab.to_owned(), q: q, repo_total: repo_total,
222+ org: org, lang: lang, tab: tab.to_owned(), q: q, sort: sort, repo_total: repo_total,
186223 star_total: star_total, cards: cards, from_pins: from_pins,
187224 pins_edit_href: pins_edit_href, edit_profile: edit_profile, listing: listing))
188225 })
@@ -200,15 +237,16 @@ struct PinCard {
200237 stars: u64,
201238 }
202239
203-/// One page of a repo tab: the rows, the match count, the pager links and the empty-list text.
240+/// One page of a repo tab: the rows, the pager, the sort chips, the match count text and the
241+/// empty-list text.
204242 #[derive(Default)]
205243 struct Listing {
206- rows: Vec<Repo>,
207- total: usize,
208- page: usize,
209- pages: usize,
210- prev: Option<String>,
211- next: Option<String>,
244+ rows: Vec<RepoRow>,
245+ page: u64,
246+ pages: u64,
247+ pager: (Vec<PageLink>, Option<String>, Option<String>),
248+ sort_links: Vec<SortLink>,
249+ count_text: String,
212250 empty: &'static str,
213251 }
214252
@@ -222,19 +260,22 @@ fn tab_key(raw: Option<&str>) -> &'static str {
222260 }
223261
224262 /// The `?page=` value, 1-based. Anything unreadable is page 1.
225-fn page_number(raw: Option<&str>) -> usize {
226- raw.and_then(|p| p.parse::<usize>().ok())
227- .unwrap_or(1)
228- .max(1)
263+fn page_number(raw: Option<&str>) -> u64 {
264+ raw.and_then(|p| p.parse::<u64>().ok()).unwrap_or(1).max(1)
229265 }
230266
231-/// The profile URL for a tab, with the name filter and page when they are set.
232-fn profile_href(name: &str, tab: &str, q: &str, page: usize) -> String {
267+/// The profile URL for a tab, with the name filter, a sort other than the default and the page
268+/// when they are set.
269+fn profile_href(name: &str, tab: &str, q: &str, sort: &str, page: u64) -> String {
233270 let mut href = format!("/{}?tab={tab}", enc(name));
234271 if !q.is_empty() {
235272 href.push_str("&q=");
236273 href.push_str(&enc(q));
237274 }
275+ if sort != SORTS[0].0 {
276+ href.push_str("&sort=");
277+ href.push_str(sort);
278+ }
238279 if page > 1 {
239280 href.push_str(&format!("&page={page}"));
240281 }
@@ -245,40 +286,6 @@ fn tab_class(on: bool) -> &'static str {
245286 if on { "tab active" } else { "tab" }
246287 }
247288
248-/// Filters `repos` by name (case-insensitive substring) and returns one page of the matches.
249-/// A page past the end is clamped to the last page.
250-fn paginate(
251- repos: Vec<Repo>,
252- name: &str,
253- tab: &str,
254- q: &str,
255- page: usize,
256- empty: &'static str,
257-) -> Listing {
258- let needle = q.to_lowercase();
259- let matched: Vec<Repo> = repos
260- .into_iter()
261- .filter(|repo| needle.is_empty() || repo.name.to_lowercase().contains(&needle))
262- .collect();
263- let total = matched.len();
264- let pages = total.div_ceil(PER_PAGE).max(1);
265- let page = page.min(pages);
266- let rows = matched
267- .into_iter()
268- .skip((page - 1) * PER_PAGE)
269- .take(PER_PAGE)
270- .collect();
271- Listing {
272- rows,
273- total,
274- page,
275- pages,
276- prev: (page > 1).then(|| profile_href(name, tab, q, page - 1)),
277- next: (page < pages).then(|| profile_href(name, tab, q, page + 1)),
278- empty,
279- }
280-}
281-
282289 /// Whether the viewer may read `repo`. Public repos, and repos the viewer owns or administers,
283290 /// need no role lookup. Other private repos get their collaborator and org roles, and `authorize`
284291 /// makes the final call either way.
@@ -327,8 +334,9 @@ async fn profile_card(
327334 lang: Lang,
328335 tab: String,
329336 q: String,
330- repo_total: usize,
331- star_total: usize,
337+ sort: &'static str,
338+ repo_total: u64,
339+ star_total: u64,
332340 cards: Vec<PinCard>,
333341 from_pins: bool,
334342 pins_edit_href: Option<String>,
@@ -338,16 +346,14 @@ async fn profile_card(
338346 let src = avatar_url(&user.username, avatar.as_deref());
339347 let has_about = !about_html.is_empty();
340348 let is_org = user.is_org();
341- let members_href = format!("/org/{}/members", user.username);
342- let teams_href = format!("/org/{}/teams", user.username);
343349 let base = format!("/{}", enc(&user.username));
344350 let overview_on = tab == "overview";
345351 let repos_on = tab == "repositories";
346352 let stars_on = tab == "stars";
347353 let list_on = repos_on || stars_on;
348- let overview_href = profile_href(&user.username, "overview", "", 1);
349- let repositories_href = profile_href(&user.username, "repositories", "", 1);
350- let stars_href = profile_href(&user.username, "stars", "", 1);
354+ let overview_href = profile_href(&user.username, "overview", "", SORTS[0].0, 1);
355+ let repositories_href = profile_href(&user.username, "repositories", "", SORTS[0].0, 1);
356+ let stars_href = profile_href(&user.username, "stars", "", SORTS[0].0, 1);
351357 let repo_count_text = repo_total.to_string();
352358 let star_count_text = star_total.to_string();
353359 let pinned_heading = if from_pins {
@@ -366,17 +372,14 @@ async fn profile_card(
366372 let filter_label = g::t(lang, K::FilterRepos);
367373 let Listing {
368374 rows,
369- total,
370375 page,
371376 pages,
372- prev,
373- next,
377+ pager: (links, prev, next),
378+ sort_links,
379+ count_text,
374380 empty,
375381 } = listing;
376382 let has_rows = !rows.is_empty();
377- let has_pager = pages > 1;
378- let total_text = g::repo_count(lang, total as u64);
379- let page_label = g::page_of(lang, page as u64, pages as u64);
380383 Ok(view! {
381384 <article class="profile-page">
382385 <header class="profile-head">
@@ -439,13 +442,7 @@ async fn profile_card(
439442 if let Some(summary) = org {
440443 <section class="profile-org">
441444 <h2>(g::t(lang, K::Members))</h2>
442- <p class="muted small">
443- (g::members_and_teams(lang, summary.members.len(), summary.teams))
444- " \u{b7} "
445- <a href=(members_href.as_str())>(g::t(lang, K::AllMembers))</a>
446- " \u{b7} "
447- <a href=(teams_href.as_str())>(g::t(lang, K::Teams))</a>
448- </p>
445+ <p class="muted small">(g::members_and_teams(lang, summary.members.len(), summary.teams))</p>
449446 if summary.members.is_empty() {
450447 <p class="muted">(g::t(lang, K::NoMembers))</p>
451448 } else {
@@ -459,41 +456,23 @@ async fn profile_card(
459456 }
460457 }
461458 if list_on {
462- <form method="get" action=(base.as_str()) class="explore-search" role="search">
463- <input type="hidden" name="tab" value=(tab.as_str())>
464- <input type="search" name="q" value=(q.as_str())
465- placeholder=(filter_label) aria-label=(filter_label)>
466- <button type="submit">(g::t(lang, K::Search))</button>
467- </form>
468- <p class="muted small">(total_text.as_str())</p>
469- if has_rows {
470- <ul class="repo-list">
471- for repo in rows.into_iter() {
472- <li class="repo-item">
473- <a class="repo-name" href=(repo_href(&repo.owner_name, &repo.name, "", ""))>
474- (format!("{}/{}", repo.owner_name, repo.name))
475- </a>
476- <span class=(badge_class(repo.visibility))>(i18n::visibility_label(lang, repo.visibility))</span>
477- if !repo.description.is_empty() {
478- <p class="muted">(repo.description.as_str())</p>
479- }
480- </li>
481- }
482- </ul>
483- } else {
484- <p class="muted">(empty)</p>
485- }
486- if has_pager {
487- <nav class="pager" aria-label=(g::t(lang, K::Pages))>
488- if let Some(href) = prev {
489- <a href=(href.as_str())>(g::t(lang, K::Previous))</a>
490- }
491- <span class="muted small">(page_label.as_str())</span>
492- if let Some(href) = next {
493- <a href=(href.as_str())>(g::t(lang, K::Next))</a>
494- }
495- </nav>
496- }
459+ <section class="repo-listing">
460+ <form method="get" action=(base.as_str()) class="explore-search" role="search">
461+ <input type="hidden" name="tab" value=(tab.as_str())>
462+ <input type="hidden" name="sort" value=(sort)>
463+ <input type="search" name="q" value=(q.as_str()) data-live-search=""
464+ placeholder=(filter_label) aria-label=(filter_label)>
465+ <button type="submit">(g::t(lang, K::Search))</button>
466+ </form>
467+ sort_chips(links: sort_links, lang: lang)
468+ <p class="muted small repo-count">(count_text.as_str())</p>
469+ if has_rows {
470+ repo_rows(rows: rows, lang: lang)
471+ } else {
472+ <p class="muted">(empty)</p>
473+ }
474+ pager(page: page, pages: pages, links: links, prev: prev, next: next, lang: lang)
475+ </section>
497476 }
498477 </article>
499478 })
@@ -600,6 +579,39 @@ mod tests {
600579 assert!(!body.contains("alert(1)"));
601580 }
602581
582+ #[tokio::test]
583+ async fn org_sidebar_shows_settings_to_owners_only() {
584+ let site = site().await;
585+ let owner = site
586+ .store
587+ .create_user("tahinli", None, "not-a-real-hash", false)
588+ .await
589+ .unwrap();
590+ let member = site
591+ .store
592+ .create_user("kaan", None, "not-a-real-hash", false)
593+ .await
594+ .unwrap();
595+ let org = site.store.create_org("forge-org", &owner.id).await.unwrap();
596+ site.store
597+ .add_org_member(
598+ &org.id,
599+ &member.id,
600+ forge_core::store::orgs::OrgMemberRole::Member,
601+ )
602+ .await
603+ .unwrap();
604+ let owner_cookie = sign_in(&site.store, &owner.id, "owner-token").await;
605+ let member_cookie = sign_in(&site.store, &member.id, "member-token").await;
606+ let href = "href=\"/org/forge-org/settings\"";
607+ let (_, as_owner) = get(&site.router, "/org/forge-org/members", Some(&owner_cookie)).await;
608+ assert!(as_owner.contains(href), "owner sees Settings");
609+ let (_, as_member) =
610+ get(&site.router, "/org/forge-org/members", Some(&member_cookie)).await;
611+ assert!(as_member.contains("href=\"/org/forge-org/teams\""));
612+ assert!(!as_member.contains(href), "member does not see Settings");
613+ }
614+
603615 #[tokio::test]
604616 async fn anonymous_and_other_users_see_only_public_repos() {
605617 let site = seeded().await;
@@ -689,15 +701,15 @@ mod tests {
689701 /// A user with 35 public repos, `bulk-00` to `bulk-34`.
690702 async fn bulk_site() -> Site {
691703 let site = site().await;
692- let mira = site
704+ let tahinli = site
693705 .store
694- .create_user("mira", None, "not-a-real-hash", false)
706+ .create_user("tahinli", None, "not-a-real-hash", false)
695707 .await
696708 .unwrap();
697709 for i in 0..35 {
698710 site.store
699711 .create_repo(
700- &mira.id,
712+ &tahinli.id,
701713 &format!("bulk-{i:02}"),
702714 "",
703715 Visibility::Public,
@@ -716,24 +728,29 @@ mod tests {
716728 #[tokio::test]
717729 async fn repositories_tab_pages_thirty_at_a_time() {
718730 let site = bulk_site().await;
719- let (status, first) = get(&site.router, "/mira?tab=repositories", None).await;
731+ let (status, first) = get(&site.router, "/tahinli?tab=repositories&sort=name", None).await;
720732 assert_eq!(status, 200);
721733 assert_eq!(count(&first, "class=\"repo-name\""), 30);
722734 assert!(first.contains("page=2"), "next link: {first}");
723735
724- let (_, second) = get(&site.router, "/mira?tab=repositories&page=2", None).await;
736+ let (_, second) = get(
737+ &site.router,
738+ "/tahinli?tab=repositories&sort=name&page=2",
739+ None,
740+ )
741+ .await;
725742 assert_eq!(count(&second, "class=\"repo-name\""), 5);
726- assert!(second.contains("mira/bulk-34"));
727- assert!(!second.contains("mira/bulk-00"));
743+ assert!(second.contains("tahinli/bulk-34"));
744+ assert!(!second.contains("tahinli/bulk-00"));
728745 }
729746
730747 #[tokio::test]
731748 async fn name_filter_is_a_case_insensitive_substring() {
732749 let site = bulk_site().await;
733- let (_, body) = get(&site.router, "/mira?tab=repositories&q=BULK-1", None).await;
750+ let (_, body) = get(&site.router, "/tahinli?tab=repositories&q=BULK-1", None).await;
734751 assert_eq!(count(&body, "class=\"repo-name\""), 10);
735- assert!(body.contains("mira/bulk-12"));
736- assert!(!body.contains("mira/bulk-22"));
752+ assert!(body.contains("tahinli/bulk-12"));
753+ assert!(!body.contains("tahinli/bulk-22"));
737754 }
738755
739756 #[tokio::test]
crates/forge-web/src/pages/pull_reviews.rsmodified+4 -2
@@ -960,7 +960,8 @@ mod tests {
960960 assert_eq!(reviews[0].state, ReviewState::Approved);
961961
962962 let form = csrf_form("tahinli", &[("state", "approve")]);
963- let (status, location, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
963+ let (status, location, _) =
964+ send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
964965 assert_eq!(status, 303);
965966 assert_eq!(
966967 location.as_deref(),
@@ -1104,7 +1105,8 @@ mod tests {
11041105 assert_eq!(status, 403);
11051106
11061107 let form = csrf_form("tahinli", &[("reason", " ")]);
1107- let (status, location, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
1108+ let (status, location, _) =
1109+ send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
11081110 assert_eq!(status, 303);
11091111 assert!(location.unwrap().ends_with("?review_error=empty"));
11101112
crates/forge-web/src/pages/pull_view.rsmodified+12 -4
@@ -640,8 +640,9 @@ async fn pull_conversation(
640640
641641 let page_title = frame.page_title.clone();
642642 let header = ctx.head(state, "pulls").await?;
643+ let labels_href = repo_href(&owner, &name, "labels.css", "");
643644 Ok(view! { cx =>
644- shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(),
645+ shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), extra_stylesheet: Some(labels_href.as_str()),
645646 repo_head(head: header)
646647 pull_header(frame: frame.clone())
647648 pull_subnav_in(lang: lang, href: href.clone(), active: "conversation".to_owned(),
@@ -1151,7 +1152,8 @@ mod tests {
11511152 let number = open_pull(&fx).await;
11521153 let uri = format!("/tahinli/demo/pulls/{number}/comments");
11531154 let form = csrf_form("tahinli", &[("body", "Looks good to me")]);
1154- let (status, location, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
1155+ let (status, location, _) =
1156+ send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
11551157 assert_eq!(status, 303);
11561158 assert!(
11571159 location
@@ -1207,7 +1209,10 @@ mod tests {
12071209 assert_eq!(status, 200);
12081210 assert!(body.contains("Edit pull request"));
12091211
1210- let form = csrf_form("tahinli", &[("title", "Renamed pull"), ("body", "New text")]);
1212+ let form = csrf_form(
1213+ "tahinli",
1214+ &[("title", "Renamed pull"), ("body", "New text")],
1215+ );
12111216 let (status, location, _) = send(
12121217 &fx.router,
12131218 "POST",
@@ -1294,7 +1299,10 @@ mod tests {
12941299 assert_eq!(status, 303);
12951300 assert_eq!(
12961301 location,
1297- Some(format!("/tahinli/demo/pulls/{number}#comment-{}", comment.id))
1302+ Some(format!(
1303+ "/tahinli/demo/pulls/{number}#comment-{}",
1304+ comment.id
1305+ ))
12981306 );
12991307 let saved = fx
13001308 .store
crates/forge-web/src/pages/releases.rsmodified+9 -4
@@ -802,7 +802,7 @@ async fn release_tag_page(cx: &Cx) -> Result<impl View> {
802802 }
803803 </p>
804804 if !body_html.is_empty() {
805- <div class="markdown-body">(Unescaped::new_unchecked(body_html))</div>
805+ <div class="markdown-body release-body">(Unescaped::new_unchecked(body_html))</div>
806806 }
807807 <h3>(g::t(lang, K::Assets))</h3>
808808 if card.assets.is_empty() {
@@ -824,7 +824,7 @@ async fn release_tag_page(cx: &Cx) -> Result<impl View> {
824824 <li><a href=(archive_zip.as_str())>"zip"</a></li>
825825 </ul>
826826 if writer {
827- <p class="release-actions">
827+ <div class="release-actions">
828828 <a href=(edit_href.as_str())>(g::t(lang, K::Edit))</a>
829829 <form method="post" action=(delete_href.as_str()) class="inline-form">
830830 <input type="hidden" name="csrf" value=(csrf.as_str())>
@@ -834,7 +834,7 @@ async fn release_tag_page(cx: &Cx) -> Result<impl View> {
834834 </label>
835835 <button type="submit">(g::t(lang, K::DeleteRelease))</button>
836836 </form>
837- </p>
837+ </div>
838838 }
839839 </section>
840840 )
@@ -923,7 +923,12 @@ struct EditParts {
923923 }
924924
925925 /// Loads the edit page data for `release`.
926-async fn edit_parts(state: &AppState, ctx: &RepoCtx, release: &Release, lang: Lang) -> Result<EditParts> {
926+async fn edit_parts(
927+ state: &AppState,
928+ ctx: &RepoCtx,
929+ release: &Release,
930+ lang: Lang,
931+) -> Result<EditParts> {
927932 let title = title_of(ctx);
928933 let assets = state.store.list_release_assets(&release.id).await?;
929934 let delete_actions: Vec<String> = assets
crates/forge-web/src/pages/releases_tests.rsmodified+24 -11
@@ -924,8 +924,14 @@ async fn the_edit_page_shows_tag_and_target_controls_and_hides_the_target_once_p
924924 .await;
925925 let html = page.text();
926926 assert!(html.contains("name=\"tag\" value=\"v2.0\""), "{html}");
927- assert!(!html.contains("name=\"target\""), "published hides the target");
928- assert!(html.contains("Published releases keep their commit"), "{html}");
927+ assert!(
928+ !html.contains("name=\"target\""),
929+ "published hides the target"
930+ );
931+ assert!(
932+ html.contains("Published releases keep their commit"),
933+ "{html}"
934+ );
929935 }
930936
931937 #[tokio::test]
@@ -949,12 +955,7 @@ async fn a_published_release_can_be_retagged_through_the_form_and_keeps_its_comm
949955 )
950956 .await;
951957 assert_eq!(reply.status, 303, "body: {}", reply.text());
952- assert!(
953- reply
954- .location
955- .unwrap_or_default()
956- .contains("notice=saved")
957- );
958+ assert!(reply.location.unwrap_or_default().contains("notice=saved"));
958959 let moved = fx
959960 .store
960961 .release(&published.id)
@@ -963,7 +964,11 @@ async fn a_published_release_can_be_retagged_through_the_form_and_keeps_its_comm
963964 .expect("row");
964965 assert_eq!(moved.tag, "v2.1");
965966 assert_eq!(fx.tag_target("v2.1"), Some(fx.main_tip()));
966- assert_eq!(fx.tag_target("v2.0"), Some(fx.main_tip()), "old git tag kept");
967+ assert_eq!(
968+ fx.tag_target("v2.0"),
969+ Some(fx.main_tip()),
970+ "old git tag kept"
971+ );
967972 }
968973
969974 #[tokio::test]
@@ -987,10 +992,18 @@ async fn a_published_target_move_is_refused_on_the_page_and_the_typed_values_sta
987992 ]),
988993 )
989994 .await;
990- assert_eq!(reply.status, 200, "a refused save re-renders: {}", reply.text());
995+ assert_eq!(
996+ reply.status,
997+ 200,
998+ "a refused save re-renders: {}",
999+ reply.text()
1000+ );
9911001 let html = reply.text();
9921002 assert!(html.contains("pick a new tag"), "{html}");
993- assert!(html.contains("Typed title"), "the typed title stays: {html}");
1003+ assert!(
1004+ html.contains("Typed title"),
1005+ "the typed title stays: {html}"
1006+ );
9941007 assert_eq!(fx.tag_target("v2.0"), Some(fx.main_tip()));
9951008 }
9961009
crates/forge-web/src/pages/repo.rsmodified+10 -3
@@ -69,6 +69,7 @@ pub async fn repo_head(head: RepoHead) -> Result<impl View> {
6969 description,
7070 archived,
7171 active,
72+ hide_search,
7273 can_admin,
7374 open_issues,
7475 open_pulls,
@@ -181,7 +182,7 @@ pub async fn repo_head(head: RepoHead) -> Result<impl View> {
181182 if active == "code" && !description.is_empty() {
182183 <p class="lead">(description.as_str())</p>
183184 }
184- if active == "code" {
185+ if active == "code" && !hide_search {
185186 <form method="get" action=(search_action.as_str()) class="repo-search" role="search">
186187 <input type="search" name="q" placeholder=(g::t(lang, K::SearchCodePlaceholder)) aria-label=(g::t(lang, K::SearchCodePlaceholder))>
187188 </form>
@@ -385,7 +386,7 @@ async fn recent_pushes(banners: Vec<PushBanner>, now: i64, lang: Lang) -> Result
385386 <code>(banner.branch)</code>
386387 (g::t(lang, K::HadRecentPushes))
387388 (relative_time(lang, banner.at_unix, now))
388- " — "
389+ ". "
389390 <a href=(banner.href)>(g::t(lang, K::CompareAndPr))</a>
390391 </p>
391392 }
@@ -545,7 +546,13 @@ mod tests {
545546 .unwrap();
546547 let demo = state
547548 .store
548- .create_repo(&tahinli.id, "demo", "A demo repo", Visibility::Public, "main")
549+ .create_repo(
550+ &tahinli.id,
551+ "demo",
552+ "A demo repo",
553+ Visibility::Public,
554+ "main",
555+ )
549556 .await
550557 .unwrap();
551558 let secret = state
crates/forge-web/src/pages/repo_collaborators.rsmodified+3 -0
@@ -27,6 +27,7 @@ use crate::i18n::repo_admin::{self as g, K};
2727 use crate::i18n::{self, Lang};
2828 use crate::pages::repo::repo_head;
2929 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};
30+use crate::pages::repo_settings::settings_nav_for;
3031 use crate::state::AppState;
3132 use crate::views::{alert, avatar_url, display_name, shell};
3233
@@ -293,9 +294,11 @@ async fn collaborators_body(
293294 let remove_action = format!("/{}/settings/collaborators/remove", frame.title);
294295 let add_action = format!("/{}/settings/collaborators/add", frame.title);
295296 let header = frame.head;
297+ let nav_title = frame.title.clone();
296298 let notice = notice.map(|(key, is_error)| (g::t(lang, key), is_error));
297299 Ok(view! {
298300 repo_head(head: header)
301+ settings_nav_for(lang: lang, title: nav_title, current: "collaborators")
299302 if let Some((text, is_error)) = notice {
300303 if is_error {
301304 alert(message: text)
crates/forge-web/src/pages/repo_ctx.rsmodified+3 -0
@@ -58,6 +58,8 @@ pub struct RepoHead {
5858 /// The current header tab: `code`, `issues`, `pulls`, `commits`, `branches`, `tags` or
5959 /// `settings`, or `security`.
6060 pub active: &'static str,
61+ /// Hide the header's code-search box (the code search page draws its own).
62+ pub hide_search: bool,
6163 /// Whether the viewer may open the Settings tab.
6264 pub can_admin: bool,
6365 /// Open issues, for the Issues tab count.
@@ -220,6 +222,7 @@ impl RepoCtx {
220222 description: self.repo.description.clone(),
221223 archived: self.repo.archived,
222224 active,
225+ hide_search: false,
223226 can_admin: self.can_admin(),
224227 open_issues: self.open_issues(state).await?,
225228 open_pulls,
crates/forge-web/src/pages/repo_rename.rsmodified+3 -0
@@ -22,6 +22,7 @@ use crate::i18n::repo_admin::{self as g, K};
2222 use crate::i18n::{self, Lang};
2323 use crate::pages::repo::repo_head;
2424 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};
25+use crate::pages::repo_settings::settings_nav_for;
2526 use crate::state::AppState;
2627 use crate::views::{alert, shell};
2728
@@ -109,6 +110,7 @@ async fn rename_body(
109110 let rename_action = format!("/{title}/settings/rename");
110111 let transfer_action = format!("/{title}/settings/transfer");
111112 let status_href = format!("/{title}/transfer");
113+ let nav_title = title.clone();
112114 let Forms {
113115 rename_name,
114116 rename_error,
@@ -117,6 +119,7 @@ async fn rename_body(
117119 } = forms;
118120 Ok(view! {
119121 repo_head(head: head)
122+ settings_nav_for(lang: lang, title: nav_title, current: "rename")
120123 if let Some(key) = notice {
121124 <section class="card notice" role="status">(g::t(lang, key))</section>
122125 }
crates/forge-web/src/pages/repo_settings.rsmodified+12 -2
@@ -274,6 +274,8 @@ pub async fn settings_nav_for(
274274 let mirrors = format!("/{title}/settings/mirrors");
275275 let secrets = format!("/{title}/settings/secrets");
276276 let general_on = current == "general";
277+ let collaborators_on = current == "collaborators";
278+ let rename_on = current == "rename";
277279 let hooks_on = current == "webhooks";
278280 let mirrors_on = current == "mirrors";
279281 let secrets_on = current == "secrets";
@@ -284,8 +286,16 @@ pub async fn settings_nav_for(
284286 } else {
285287 <a href=(general)>(g::t(lang, K::General))</a>
286288 }
287- <a href=(collaborators)>(g::t(lang, K::Collaborators))</a>
288- <a href=(rename)>(g::t(lang, K::RenameTransferNav))</a>
289+ if collaborators_on {
290+ <a href=(collaborators) aria-current="page">(g::t(lang, K::Collaborators))</a>
291+ } else {
292+ <a href=(collaborators)>(g::t(lang, K::Collaborators))</a>
293+ }
294+ if rename_on {
295+ <a href=(rename) aria-current="page">(g::t(lang, K::RenameTransferNav))</a>
296+ } else {
297+ <a href=(rename)>(g::t(lang, K::RenameTransferNav))</a>
298+ }
289299 if hooks_on {
290300 <a href=(hooks) aria-current="page">(g::t(lang, K::Webhooks))</a>
291301 } else {
crates/forge-web/src/pages/repo_webhooks.rsmodified+2 -1
@@ -1339,7 +1339,8 @@ mod tests {
13391339 );
13401340
13411341 // A private repo is invisible to someone outside it.
1342- let (status, _, _) = send(&fx.app, "GET", "/tahinli/proj/settings/hooks", &carol, &[]).await;
1342+ let (status, _, _) =
1343+ send(&fx.app, "GET", "/tahinli/proj/settings/hooks", &carol, &[]).await;
13431344 assert_eq!(status, 404);
13441345 }
13451346
crates/forge-web/src/pages/settings_appearance.rsmodified+1 -1
@@ -248,7 +248,7 @@ async fn appearance_body(page: AppearancePage) -> Result<impl View> {
248248 </label>
249249 <fieldset class="side-picker">
250250 <legend>(g::t(lang, K::SidebarLabel))</legend>
251- <div class="segmented" role="group">
251+ <div class="segmented snippet-segmented" role="group">
252252 for choice in sidebar.into_iter() {
253253 <label class="segment">
254254 <input type="radio" name="sidebar_side" value=(choice.value) checked=(choice.selected) data-autosubmit="true">
crates/forge-web/src/pages/settings_gpg_tests.rsmodified+4 -1
@@ -155,7 +155,10 @@ async fn deleting_a_key_requires_login_and_csrf() {
155155 )
156156 .await;
157157 assert_eq!(reply.status, 403);
158- assert_eq!(site.store.list_gpg_keys(&tahinli.id).await.unwrap().len(), 1);
158+ assert_eq!(
159+ site.store.list_gpg_keys(&tahinli.id).await.unwrap().len(),
160+ 1
161+ );
159162 }
160163
161164 #[tokio::test]
crates/forge-web/src/pages/settings_notifications.rsmodified+32 -13
@@ -1,6 +1,8 @@
11 //! Page: email notifications (`/settings/notifications`). One checkbox: whether notifications are
22 //! also sent by email. The page notes when the viewer's address is not verified, or when instance
3-//! mail is off, since then nothing is sent. Every POST checks the CSRF token first.
3+//! mail is off, since then nothing is sent, and locks the box until both are fixed. The box saves
4+//! itself on change (soft-nav POST, no reload); the Save button only shows without JavaScript.
5+//! Every POST checks the CSRF token first.
46
57 use forge_core::{Session, Store, User};
68 use serde::Deserialize;
@@ -51,6 +53,9 @@ async fn notifications_body(page: NotificationsPage) -> Result<impl View> {
5153 server_note,
5254 notice,
5355 } = page;
56+ // Nothing can be sent while instance mail is off or the address is unverified, so the box is
57+ // locked and the notes below say why.
58+ let blocked = unverified_note.is_some() || server_note.is_some();
5459 Ok(view! {
5560 <div class="settings-layout">
5661 <section class="page-head">
@@ -62,20 +67,26 @@ async fn notifications_body(page: NotificationsPage) -> Result<impl View> {
6267 </section>
6368 }
6469 <section class="card">
65- <form method="post" action="/settings/notifications" class="stack">
70+ <form method="post" action="/settings/notifications" class="notify-form">
6671 <input type="hidden" name="csrf" value=(csrf.as_str())>
67- <label>
68- <input type="checkbox" name="email_notifications" value="1" checked=(on)>
69- <span>(t(lang, Key::EmailNotifyLabel))</span>
70- </label>
71- <small class="muted">(t(lang, Key::EmailNotifyHelp))</small>
72- if let Some(message) = unverified_note {
73- <p class="muted">(message)</p>
74- }
72+ <div class="check-field">
73+ <label>
74+ <input type="checkbox" name="email_notifications" value="1" checked=(on) disabled=(blocked) data-autosubmit="true">
75+ <span>(t(lang, Key::EmailNotifyLabel))</span>
76+ </label>
77+ <small class="muted">(t(lang, Key::EmailNotifyHelp))</small>
78+ </div>
7579 if let Some(message) = server_note {
76- <p class="muted">(message)</p>
80+ <p class="notice" role="note">(message)</p>
81+ }
82+ if let Some(message) = unverified_note {
83+ <p class="notice" role="note">(message)</p>
7784 }
78- <button type="submit" class="primary">(t(lang, Key::Save))</button>
85+ <noscript>
86+ <div class="actions">
87+ <button type="submit" class="primary" disabled=(blocked)>(t(lang, Key::Save))</button>
88+ </div>
89+ </noscript>
7990 </form>
8091 </section>
8192 </div>
@@ -121,7 +132,7 @@ async fn notifications_save(cx: &Cx, Form(form): Form<NotificationsForm>) -> Res
121132 store
122133 .set_email_notifications(&viewer.0.id, form.email_notifications.is_some())
123134 .await?;
124- Ok(see_other("/settings/notifications?saved=1"))
135+ Ok(see_other("/settings/notifications"))
125136 }
126137
127138 #[cfg(test)]
@@ -221,6 +232,14 @@ mod tests {
221232 body.contains("Email is turned off on this server"),
222233 "{body}"
223234 );
235+ assert!(
236+ body.contains("data-autosubmit"),
237+ "the box saves itself: {body}"
238+ );
239+ assert!(
240+ body.contains("disabled"),
241+ "nothing can be sent, so the box is locked: {body}"
242+ );
224243 }
225244
226245 #[tokio::test]
crates/forge-web/src/pages/snippets.rsmodified+14 -7
@@ -236,6 +236,13 @@ fn file_view(state: &AppState, snippet: &Snippet, file: &SnippetFile) -> FileVie
236236 }
237237 }
238238
239+/// `2026-10-19T18:39:50.4389Z` as `2026-10-19 18:39`: stored timestamps carry nanoseconds.
240+fn short_time(stamp: &str) -> String {
241+ stamp
242+ .get(..16)
243+ .map_or_else(|| stamp.to_owned(), |s| s.replace('T', " "))
244+}
245+
239246 /// The snippet if the viewer may read it, else 404.
240247 async fn readable(cx: &Cx, viewer_id: Option<&str>, snippet_id: &str) -> Result<Snippet> {
241248 let store = &app_context::<AppState>(cx).store;
@@ -444,17 +451,17 @@ async fn snippet_body(
444451 let history_href = format!("/snippets/{snippet_id}/revisions");
445452 let delete_action = format!("/snippets/{snippet_id}/delete");
446453 Ok(view! {
447- <section class="page-head">
454+ <section class="page-head snippet-view-head">
448455 <h1>(title)</h1>
449456 <span class="muted small">(owner) " · " (visibility) " · " (g::updated_on(lang, updated))</span>
450457 </section>
451458 if !description.is_empty() {
452459 <p class="snippet-description">(description)</p>
453460 }
454- <nav class="file-actions" aria-label=(g::t(lang, K::SnippetNav))>
455- <a href=(history_href)>(g::t(lang, K::Revisions))</a>
461+ <nav class="snippet-actions" aria-label=(g::t(lang, K::SnippetNav))>
462+ <a class="button" href=(history_href)>(g::t(lang, K::Revisions))</a>
456463 if let Some(token) = owner_csrf {
457- <a href=(edit_href)>(g::t(lang, K::Edit))</a>
464+ <a class="button" href=(edit_href)>(g::t(lang, K::Edit))</a>
458465 <form method="post" action=(delete_action) class="inline-form">
459466 <input type="hidden" name="csrf" value=(token.as_str())>
460467 <button type="submit" class="danger">(g::t(lang, K::Delete))</button>
@@ -559,7 +566,7 @@ async fn snippets_list(cx: &Cx) -> Result<impl View> {
559566 title: s.title,
560567 owner: s.owner_name,
561568 visibility: visibility_label(lang, s.visibility),
562- meta: g::files_updated(lang, s.file_count, &s.updated_at),
569+ meta: g::files_updated(lang, s.file_count, &short_time(&s.updated_at)),
563570 })
564571 .collect();
565572 let signed_in = viewer.is_some();
@@ -655,7 +662,7 @@ async fn snippet_view(cx: &Cx) -> Result<impl View> {
655662 Some((user, session)) if user.id == snippet.owner_id => Some(session.csrf_token.clone()),
656663 _ => None,
657664 };
658- let updated = snippet.updated_at.clone();
665+ let updated = short_time(&snippet.updated_at);
659666 let visibility = visibility_label(lang, snippet.visibility);
660667 Ok(view! {
661668 shell(title: snippet.title.as_str(), viewer: viewer.as_ref(),
@@ -758,7 +765,7 @@ async fn snippet_revisions(cx: &Cx) -> Result<impl View> {
758765 .map(|(index, rev)| RevisionView {
759766 number: index + 1,
760767 author: rev.author_name,
761- at: rev.created_at,
768+ at: short_time(&rev.created_at),
762769 file_names: rev
763770 .files
764771 .iter()
crates/forge-web/src/pages/wiki.rsmodified+101 -90
@@ -144,45 +144,64 @@ fn revision_rows(ctx: &RepoCtx, revs: &[PageRevision], tz: &str) -> Vec<Revision
144144 .collect()
145145 }
146146
147+/// The header every wiki screen shares: the page title on the left, then the wiki's own
148+/// navigation as a button row (Home, All pages, any page-specific `extra` links such as Edit
149+/// or History) with "New page" as the primary action on the far right for writers.
147150 #[component]
148-async fn wiki_nav(lang: Lang, owner: String, repo: String, can_write: bool) -> Result<impl View> {
151+async fn wiki_head(
152+ lang: Lang,
153+ owner: String,
154+ repo: String,
155+ can_write: bool,
156+ title: String,
157+ extra: Vec<(String, String)>,
158+) -> Result<impl View> {
149159 let home = repo_href(&owner, &repo, "wiki", "");
150160 let pages = repo_href(&owner, &repo, "wiki", "-/pages");
151161 let new = repo_href(&owner, &repo, "wiki", "-/new");
152162 Ok(view! {
153- <nav class="wiki-nav" aria-label=(g::t(lang, K::Wiki))>
154- <a href=(home)>(g::t(lang, K::Home))</a>
155- <a href=(pages)>(g::t(lang, K::AllPages))</a>
156- if can_write {
157- <a href=(new)>(g::t(lang, K::NewPage))</a>
158- }
159- </nav>
163+ <section class="page-head wiki-head">
164+ <h1>(title.as_str())</h1>
165+ <nav class="wiki-actions" aria-label=(g::t(lang, K::PageNav))>
166+ <a class="button" href=(home)>(g::t(lang, K::Home))</a>
167+ <a class="button" href=(pages)>(g::t(lang, K::AllPages))</a>
168+ for (label, href) in extra.into_iter() {
169+ <a class="button" href=(href)>(label)</a>
170+ }
171+ if can_write {
172+ <a class="button primary" href=(new)>(g::t(lang, K::NewPage))</a>
173+ }
174+ </nav>
175+ </section>
160176 })
161177 }
162178
163-#[component]
164-async fn wiki_view_body(
179+/// The Edit / History links shown in the header of a rendered page.
180+fn page_links(
165181 lang: Lang,
166- owner: String,
167- repo: String,
168- name: String,
169- html: String,
182+ owner: &str,
183+ repo: &str,
184+ name: &str,
170185 can_write: bool,
171-) -> Result<impl View> {
172- let edit = repo_href(&owner, &repo, "wiki", &format!("{name}/edit"));
173- let history = repo_href(&owner, &repo, "wiki", &format!("{name}/history"));
174- let title = name.replace('-', " ");
186+) -> Vec<(String, String)> {
187+ let mut links = Vec::new();
188+ if can_write {
189+ links.push((
190+ g::t(lang, K::Edit).to_owned(),
191+ repo_href(owner, repo, "wiki", &format!("{name}/edit")),
192+ ));
193+ }
194+ links.push((
195+ g::t(lang, K::History).to_owned(),
196+ repo_href(owner, repo, "wiki", &format!("{name}/history")),
197+ ));
198+ links
199+}
200+
201+#[component]
202+async fn wiki_view_body(html: String) -> Result<impl View> {
175203 Ok(view! {
176- <section class="wiki-page">
177- <header class="wiki-head">
178- <h1>(title.as_str())</h1>
179- <nav class="file-actions" aria-label=(g::t(lang, K::PageNav))>
180- if can_write {
181- <a href=(edit)>(g::t(lang, K::Edit))</a>
182- }
183- <a href=(history)>(g::t(lang, K::History))</a>
184- </nav>
185- </header>
204+ <section class="card wiki-page">
186205 <div class="markdown-body">(Unescaped::new_unchecked(html))</div>
187206 </section>
188207 })
@@ -197,11 +216,10 @@ async fn wiki_empty_body(
197216 ) -> Result<impl View> {
198217 let new = repo_href(&owner, &repo, "wiki", "-/new");
199218 Ok(view! {
200- <section class="wiki-page">
201- <h1>(g::t(lang, K::Wiki))</h1>
202- <p class="notice">(g::t(lang, K::WikiNoPages))</p>
219+ <section class="card wiki-page">
220+ <p class="muted">(g::t(lang, K::WikiNoPages))</p>
203221 if can_write {
204- <p><a href=(new)>(g::t(lang, K::CreateFirstPage))</a></p>
222+ <a class="button primary" href=(new)>(g::t(lang, K::CreateFirstPage))</a>
205223 }
206224 </section>
207225 })
@@ -213,9 +231,7 @@ async fn wiki_list_body(
213231 owner: String,
214232 repo: String,
215233 names: Vec<String>,
216- can_write: bool,
217234 ) -> Result<impl View> {
218- let new = repo_href(&owner, &repo, "wiki", "-/new");
219235 let rows: Vec<(String, String)> = names
220236 .into_iter()
221237 .map(|name| {
@@ -224,54 +240,42 @@ async fn wiki_list_body(
224240 })
225241 .collect();
226242 Ok(view! {
227- <section class="wiki-page">
228- <h1>(g::t(lang, K::AllPages))</h1>
229- if can_write {
230- <p><a href=(new)>(g::t(lang, K::NewPage))</a></p>
231- }
243+ <section class="card wiki-page">
232244 if rows.is_empty() {
233- <p class="notice">(g::t(lang, K::NoPagesYet))</p>
245+ <p class="muted">(g::t(lang, K::NoPagesYet))</p>
246+ } else {
247+ <ul class="item-list wiki-pages">
248+ for (title, href) in rows.into_iter() {
249+ <li class="item"><a href=(href)>(title.as_str())</a></li>
250+ }
251+ </ul>
234252 }
235- <ul class="wiki-pages">
236- for (title, href) in rows.into_iter() {
237- <li><a href=(href)>(title.as_str())</a></li>
238- }
239- </ul>
240253 </section>
241254 })
242255 }
243256
244257 #[component]
245-async fn wiki_history_body(
246- lang: Lang,
247- owner: String,
248- repo: String,
249- name: String,
250- rows: Vec<RevisionRow>,
251-) -> Result<impl View> {
252- let back = repo_href(&owner, &repo, "wiki", &name);
253- let title = name.replace('-', " ");
258+async fn wiki_history_body(lang: Lang, rows: Vec<RevisionRow>) -> Result<impl View> {
254259 Ok(view! {
255- <section class="wiki-page">
256- <header class="wiki-head">
257- <h1>(title.as_str())</h1>
258- <nav class="file-actions" aria-label=(g::t(lang, K::PageNav))><a href=(back)>(g::t(lang, K::BackToPage))</a></nav>
259- </header>
260+ <section class="card wiki-page">
260261 if rows.is_empty() {
261- <p class="notice">(g::t(lang, K::NoChangesYet))</p>
262+ <p class="muted">(g::t(lang, K::NoChangesYet))</p>
263+ } else {
264+ <div class="table-wrap">
265+ <table class="table wiki-history">
266+ <tbody>
267+ for row in rows.into_iter() {
268+ <tr>
269+ <td class="nowrap"><a href=(row.href)><code>(row.short.as_str())</code></a></td>
270+ <td>(row.subject.as_str())</td>
271+ <td class="muted small nowrap">(row.author.as_str())</td>
272+ <td class="muted small nowrap">(row.when.as_str())</td>
273+ </tr>
274+ }
275+ </tbody>
276+ </table>
277+ </div>
262278 }
263- <table class="wiki-history">
264- <tbody>
265- for row in rows.into_iter() {
266- <tr>
267- <td><a href=(row.href)><code>(row.short.as_str())</code></a></td>
268- <td>(row.subject.as_str())</td>
269- <td class="muted small">(row.author.as_str())</td>
270- <td class="muted small">(row.when.as_str())</td>
271- </tr>
272- }
273- </tbody>
274- </table>
275279 </section>
276280 })
277281 }
@@ -287,14 +291,8 @@ async fn wiki_edit_body(
287291 content: String,
288292 error: Option<String>,
289293 ) -> Result<impl View> {
290- let title = if is_new {
291- g::t(lang, K::NewPage).to_owned()
292- } else {
293- name.replace('-', " ")
294- };
295294 Ok(view! {
296- <section class="wiki-page">
297- <h1>(title.as_str())</h1>
295+ <section class="card wiki-page">
298296 <form method="post" action=(action.as_str()) class="stack wiki-form">
299297 if let Some(message) = error {
300298 alert(message: message.as_str())
@@ -353,13 +351,21 @@ async fn wiki_home(cx: &Cx) -> Result<impl View> {
353351 ctx.repo.name,
354352 g::t(lang, K::Wiki)
355353 );
354+ let (head_title, links) = if body_html.is_some() {
355+ (
356+ g::t(lang, K::Home).to_owned(),
357+ page_links(lang, &owner_name, &repo_name, "Home", can_write),
358+ )
359+ } else {
360+ (g::t(lang, K::Wiki).to_owned(), Vec::new())
361+ };
356362 let header = ctx.head(state, "wiki").await?;
357363 Ok(view! { cx =>
358364 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
359365 repo_head(head: header)
360- wiki_nav(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: can_write)
366+ wiki_head(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: can_write, title: head_title.clone(), extra: links.clone())
361367 if let Some(html) = body_html.clone() {
362- wiki_view_body(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), name: "Home".to_owned(), html: html, can_write: can_write)
368+ wiki_view_body(html: html)
363369 }
364370 if body_html.is_none() {
365371 wiki_empty_body(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: can_write)
@@ -391,8 +397,8 @@ async fn wiki_pages(cx: &Cx) -> Result<impl View> {
391397 Ok(view! { cx =>
392398 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
393399 repo_head(head: header)
394- wiki_nav(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: can_write)
395- wiki_list_body(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), names: names, can_write: can_write)
400+ wiki_head(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: can_write, title: g::t(lang, K::AllPages).to_owned(), extra: Vec::new())
401+ wiki_list_body(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), names: names)
396402 )
397403 })
398404 }
@@ -428,8 +434,8 @@ async fn wiki_page_view(cx: &Cx) -> Result<impl View> {
428434 Ok(view! { cx =>
429435 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
430436 repo_head(head: header)
431- wiki_nav(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: can_write)
432- wiki_view_body(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), name: page_name.clone(), html: html, can_write: can_write)
437+ wiki_head(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: can_write, title: page_name.replace('-', " "), extra: page_links(lang, &owner_name, &repo_name, &page_name, can_write))
438+ wiki_view_body(html: html)
433439 )
434440 })
435441 }
@@ -463,8 +469,8 @@ async fn wiki_page_history(cx: &Cx) -> Result<impl View> {
463469 Ok(view! { cx =>
464470 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
465471 repo_head(head: header)
466- wiki_nav(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: ctx.can_write())
467- wiki_history_body(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), name: page_name.clone(), rows: rows)
472+ wiki_head(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: ctx.can_write(), title: format!("{} \u{b7} {}", page_name.replace('-', " "), g::t(lang, K::History)), extra: vec![(g::t(lang, K::BackToPage).to_owned(), repo_href(&owner_name, &repo_name, "wiki", &page_name))])
473+ wiki_history_body(lang: lang, rows: rows)
468474 )
469475 })
470476 }
@@ -504,10 +510,15 @@ async fn edit_screen(
504510 let repo_name = ctx.repo.name.clone();
505511 let csrf = session.csrf_token.clone();
506512 let base = head.unwrap_or_default();
513+ let head_title = if is_new {
514+ g::t(lang, K::NewPage).to_owned()
515+ } else {
516+ name.replace('-', " ")
517+ };
507518 Ok(view! { cx =>
508519 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
509520 repo_head(head: header)
510- wiki_nav(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: true)
521+ wiki_head(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: !is_new, title: head_title.clone(), extra: Vec::new())
511522 wiki_edit_body(lang: lang, action: action, csrf: csrf, base: base, name: name.clone(), is_new: is_new, content: content, error: error)
512523 )
513524 })
@@ -669,8 +680,8 @@ async fn wiki_settings_body(
669680 enabled: bool,
670681 ) -> Result<impl View> {
671682 Ok(view! {
672- <section class="wiki-page">
673- <h1>(g::t(lang, K::WikiSettings))</h1>
683+ <section class="card">
684+ <h2>(g::t(lang, K::WikiSettings))</h2>
674685 <form method="post" action=(action.as_str()) class="stack wiki-form">
675686 <input type="hidden" name="csrf" value=(csrf.as_str())>
676687 <label class="checkbox">
crates/forge-web/src/raw.rsmodified+7 -1
@@ -741,7 +741,13 @@ mod tests {
741741 let first = get(&fx.router, "GET", "/tahinli/pub/main/hello.txt", None).await;
742742 let etag = header_str(&first, "etag");
743743 assert!(etag.starts_with('"') && etag.ends_with('"'), "etag {etag}");
744- let again = get(&fx.router, "GET", "/tahinli/pub/main/hello.txt", Some(&etag)).await;
744+ let again = get(
745+ &fx.router,
746+ "GET",
747+ "/tahinli/pub/main/hello.txt",
748+ Some(&etag),
749+ )
750+ .await;
745751 assert_eq!(again.status(), 304);
746752 assert_eq!(header_str(&again, "etag"), etag);
747753 }
crates/forge-web/src/signatures.rsmodified+5 -1
@@ -607,7 +607,11 @@ mod tests {
607607 std::fs::create_dir_all(&work).unwrap();
608608 git(&home, &work, &["init", "-q", "-b", "main"]);
609609 git(&home, &work, &["config", "user.name", "Tahinli"]);
610- git(&home, &work, &["config", "user.email", "tahinli@example.com"]);
610+ git(
611+ &home,
612+ &work,
613+ &["config", "user.email", "tahinli@example.com"],
614+ );
611615 std::fs::write(work.join("a.txt"), "a\n").unwrap();
612616 git(&home, &work, &["add", "a.txt"]);
613617 git(
crates/forge-web/src/ssh_backend.rsmodified+7 -1
@@ -179,7 +179,13 @@ mod org_tests {
179179 .unwrap();
180180 state
181181 .store
182- .add_ssh_key(&tahinli.id, "laptop", "ssh-ed25519", person_blob, "SHA256:me")
182+ .add_ssh_key(
183+ &tahinli.id,
184+ "laptop",
185+ "ssh-ed25519",
186+ person_blob,
187+ "SHA256:me",
188+ )
183189 .await
184190 .unwrap();
185191 let backend = SshBackend { state };
crates/forge-web/src/views/mod.rsmodified+68 -12
@@ -4,6 +4,7 @@
44 pub mod commit_status;
55 pub mod diff;
66 pub mod heatmap;
7+pub mod repo_list;
78 pub mod review_thread;
89
910 use std::sync::OnceLock;
@@ -162,11 +163,29 @@ pub async fn shell(
162163 let back = uri(__cx).path_and_query().map(|p| p.as_str().to_owned());
163164 let lang = i18n::lang(__cx, viewer.map(|(user, _)| user));
164165 // The admin area and the user settings swap the global links for their own list. Signed-in only.
165- let section = if signed_in {
166+ let mut section = if signed_in {
166167 section_for(lang, uri(__cx).path())
167168 } else {
168169 None
169170 };
171+ // An org's Settings link is for its owners only.
172+ if let (Some(sec), Some((user, _))) = (section.as_mut(), viewer)
173+ && sec.items.iter().any(|item| item.key == "settings")
174+ && sec.items.iter().any(|item| item.key == "teams")
175+ && let Some(state) = try_app_context::<AppState>(__cx)
176+ {
177+ let owner = state
178+ .store
179+ .orgs_for_user(&user.id)
180+ .await?
181+ .iter()
182+ .any(|(org, role)| {
183+ org.username == sec.title && *role == forge_core::store::orgs::OrgMemberRole::Owner
184+ });
185+ if !owner {
186+ sec.items.retain(|item| item.key != "settings");
187+ }
188+ }
170189 let section_menu = section.clone();
171190 let theme_attr = crate::theme::data_theme(__cx, viewer.map(|(user, _)| user));
172191 // Always set, defaults included, so a page never keeps the colours of the one before it.
@@ -248,7 +267,7 @@ pub async fn shell(
248267 </summary>
249268 <div class="nav-panel">
250269 if let Some(section) = section_menu {
251- section_nav(title: section.title, back: section.back, items: section.items, current: section.current)
270+ section_nav(title: section.title.as_str(), back: section.back, items: section.items, current: section.current)
252271 } else {
253272 side_nav(lang: lang, current: current, unread: unread_menu, repos: side_repos_menu)
254273 }
@@ -323,7 +342,7 @@ pub async fn shell(
323342 if signed_in {
324343 <aside class="shell-sidebar">
325344 if let Some(section) = section {
326- section_nav(title: section.title, back: section.back, items: section.items, current: section.current)
345+ section_nav(title: section.title.as_str(), back: section.back, items: section.items, current: section.current)
327346 } else {
328347 side_nav(lang: lang, current: current, unread: unread_aside, repos: side_repos)
329348 }
@@ -420,7 +439,7 @@ async fn side_nav(
420439 #[derive(Clone)]
421440 pub struct NavItem {
422441 pub key: &'static str,
423- pub href: &'static str,
442+ pub href: String,
424443 pub label: &'static str,
425444 pub icon: &'static str,
426445 }
@@ -428,16 +447,16 @@ pub struct NavItem {
428447 /// A section sidebar: the admin area or user settings, shown in place of the global links.
429448 #[derive(Clone)]
430449 pub struct Section {
431- pub title: &'static str,
450+ pub title: String,
432451 pub back: &'static str,
433452 pub items: Vec<NavItem>,
434453 pub current: &'static str,
435454 }
436455
437456 fn admin_items(lang: Lang) -> Vec<NavItem> {
438- let item = |key, href, label, icon| NavItem {
457+ let item = |key, href: &'static str, label, icon| NavItem {
439458 key,
440- href,
459+ href: href.to_owned(),
441460 label,
442461 icon,
443462 };
@@ -472,10 +491,24 @@ fn admin_items(lang: Lang) -> Vec<NavItem> {
472491 ]
473492 }
474493
494+fn org_items(lang: Lang, org: &str) -> Vec<NavItem> {
495+ let item = |key, label, icon| NavItem {
496+ key,
497+ href: format!("/org/{org}/{key}"),
498+ label,
499+ icon,
500+ };
501+ vec![
502+ item("members", o::t(lang, OK::Members), "users"),
503+ item("teams", o::t(lang, OK::Teams), "teams"),
504+ item("settings", o::t(lang, OK::Settings), "appearance"),
505+ ]
506+}
507+
475508 fn settings_items(lang: Lang) -> Vec<NavItem> {
476- let item = |key, href, label, icon| NavItem {
509+ let item = |key, href: &'static str, label, icon| NavItem {
477510 key,
478- href,
511+ href: href.to_owned(),
479512 label,
480513 icon,
481514 };
@@ -535,8 +568,24 @@ pub fn section_for(lang: Lang, path: &str) -> Option<Section> {
535568 let first = parts.next()?;
536569 let second = parts.next().unwrap_or("");
537570 let (title, items) = match first {
538- "admin" => (ad::t(lang, AK::AdminArea), admin_items(lang)),
539- "settings" => (o::t(lang, OK::Settings), settings_items(lang)),
571+ "admin" => (ad::t(lang, AK::AdminArea).to_owned(), admin_items(lang)),
572+ "settings" => (o::t(lang, OK::Settings).to_owned(), settings_items(lang)),
573+ // An organization's own pages (`/org/{name}/members`, `teams`, `settings`); `/org/new` is
574+ // the create form and keeps the global links.
575+ "org" if !second.is_empty() && second != "new" => {
576+ let third = parts.next().unwrap_or("");
577+ let items = org_items(lang, second);
578+ let current = items
579+ .iter()
580+ .find(|item| item.key == third)
581+ .map_or("", |item| item.key);
582+ return Some(Section {
583+ title: second.to_owned(),
584+ back: t(lang, Key::BackToSite),
585+ items,
586+ current,
587+ });
588+ }
540589 _ => return None,
541590 };
542591 let current = items
@@ -595,6 +644,9 @@ async fn nav_icon(name: &str) -> Result<impl View> {
595644 if name == "back" {
596645 <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M19 12H5M11 6l-6 6 6 6"/></svg>
597646 }
647+ if name == "teams" {
648+ <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="7" r="3"/><circle cx="5" cy="17" r="3"/><circle cx="19" cy="17" r="3"/><path d="M10 9.5 6.5 14.5M14 9.5l3.5 5M8 17h8"/></svg>
649+ }
598650 if name == "users" {
599651 <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><circle cx="9" cy="8" r="4"/><path d="M2 21c0-4 3-6 7-6s7 2 7 6"/><path d="M16 4a4 4 0 0 1 0 8M22 21c0-3-2-5-4-5.5"/></svg>
600652 }
@@ -823,6 +875,7 @@ pub fn human_size(lang: Lang, bytes: u64) -> String {
823875 };
824876 if bytes < 1024 {
825877 match lang {
878+ Lang::En if bytes == 1 => "1 byte".to_owned(),
826879 Lang::En => format!("{bytes} bytes"),
827880 Lang::Tr => format!("{bytes} bayt"),
828881 }
@@ -1154,7 +1207,10 @@ mod tests {
11541207 async fn admin_links_are_shown_to_admins() {
11551208 let html = menu_html(true).await;
11561209 assert!(html.contains("href=\"/admin/users\""));
1157- assert!(!html.contains("Admin:"), "one Admin entry, no per-page items");
1210+ assert!(
1211+ !html.contains("Admin:"),
1212+ "one Admin entry, no per-page items"
1213+ );
11581214 }
11591215 }
11601216
crates/forge-web/src/views/repo_list.rsadded+204 -0
@@ -0,0 +1,204 @@
1+//! Shared pieces of the repo listings on `/explore` and the profile tabs: the repo rows, the sort
2+//! chips and the numbered pager.
3+
4+use forge_core::Visibility;
5+use forge_core::store::ListedRepo;
6+use topcoat::Result;
7+use topcoat::view::{View, component, view};
8+
9+use crate::i18n::orgs::{self as g, K};
10+use crate::i18n::{self, Lang};
11+use crate::pages::dashboard::badge_class;
12+use crate::pages::issue_parts::When;
13+use crate::views::repo_href;
14+
15+/// One listed repo, formatted for display.
16+pub struct RepoRow {
17+ href: String,
18+ title: String,
19+ visibility: Visibility,
20+ description: String,
21+ stars: u64,
22+ when: When,
23+}
24+
25+impl RepoRow {
26+ /// A row for a listed repo (the repo, its star count and its last activity stamp), with the
27+ /// absolute time shown in the viewer's timezone `tz`.
28+ pub fn new(lang: Lang, tz: &str, now: i64, listed: ListedRepo) -> Self {
29+ let (repo, stars, updated) = listed;
30+ Self {
31+ href: repo_href(&repo.owner_name, &repo.name, "", ""),
32+ title: format!("{}/{}", repo.owner_name, repo.name),
33+ visibility: repo.visibility,
34+ description: repo.description,
35+ stars,
36+ when: When::new(lang, &updated, tz, now),
37+ }
38+ }
39+}
40+
41+/// The repo rows: name, visibility badge, a one-line description, stars and the last update.
42+#[component]
43+pub async fn repo_rows(rows: Vec<RepoRow>, lang: Lang) -> Result<impl View> {
44+ let (before, after) = g::updated_parts(lang);
45+ Ok(view! {
46+ <ul class="repo-list">
47+ for row in rows.into_iter() {
48+ <li class="repo-item">
49+ <div class="repo-item-head">
50+ <a class="repo-name" href=(row.href.as_str())>(row.title.as_str())</a>
51+ <span class=(badge_class(row.visibility))>(i18n::visibility_label(lang, row.visibility))</span>
52+ </div>
53+ if !row.description.is_empty() {
54+ <p class="muted repo-desc" title=(row.description.as_str())>(row.description.as_str())</p>
55+ }
56+ <p class="muted small repo-stats">
57+ "\u{2605} " (row.stars.to_string())
58+ (before)
59+ <time datetime=(row.when.iso.as_str()) title=(row.when.absolute.as_str())>(row.when.relative.as_str())</time>
60+ (after)
61+ </p>
62+ </li>
63+ }
64+ </ul>
65+ })
66+}
67+
68+/// One sort chip: its label, target and whether it is the active order.
69+pub struct SortLink {
70+ pub label: &'static str,
71+ pub href: String,
72+ pub current: bool,
73+}
74+
75+/// The "Sort by" chips.
76+#[component]
77+pub async fn sort_chips(links: Vec<SortLink>, lang: Lang) -> Result<impl View> {
78+ Ok(view! {
79+ <nav class="explore-sort" aria-label=(g::t(lang, K::SortNav))>
80+ <span class="muted small">(g::t(lang, K::SortBy))</span>
81+ for link in links.into_iter() {
82+ if link.current {
83+ <span class="current" aria-current="true">(link.label)</span>
84+ } else {
85+ <a href=(link.href.as_str())>(link.label)</a>
86+ }
87+ }
88+ </nav>
89+ })
90+}
91+
92+/// One pager entry: a page number with its link, or a gap (no link, shown as an ellipsis).
93+pub struct PageLink {
94+ label: String,
95+ href: Option<String>,
96+ current: bool,
97+}
98+
99+/// The pages to show for `page` of `pages`: the first, the last and the neighbours of the
100+/// current page, with `None` for a gap. A gap of a single page shows that page instead.
101+fn page_numbers(page: u64, pages: u64) -> Vec<Option<u64>> {
102+ let mut out = Vec::new();
103+ let mut last = 0;
104+ for n in 1..=pages {
105+ let near = n == 1 || n == pages || n.abs_diff(page) <= 1;
106+ let fills_gap = (n == 2 && page == 4) || (n + 1 == pages && page + 3 == pages);
107+ if near || fills_gap {
108+ if n > last + 1 {
109+ out.push(None);
110+ }
111+ out.push(Some(n));
112+ last = n;
113+ }
114+ }
115+ out
116+}
117+
118+/// The numbered pager with Previous and Next, from `pager_links`. Nothing is shown for a single
119+/// page.
120+#[component]
121+pub async fn pager(
122+ page: u64,
123+ pages: u64,
124+ links: Vec<PageLink>,
125+ prev: Option<String>,
126+ next: Option<String>,
127+ lang: Lang,
128+) -> Result<impl View> {
129+ let show = pages > 1;
130+ let label = g::page_of(lang, page, pages);
131+ Ok(view! {
132+ if show {
133+ <nav class="pager pager-numbered" aria-label=(g::t(lang, K::Pages))>
134+ if let Some(href) = prev {
135+ <a class="pager-step" href=(href.as_str()) rel="prev">(g::t(lang, K::Previous))</a>
136+ }
137+ for link in links.into_iter() {
138+ if link.current {
139+ <span class="pager-page current" aria-current="page" title=(label.as_str())>(link.label.as_str())</span>
140+ } else {
141+ if let Some(href) = link.href {
142+ <a class="pager-page" href=(href.as_str())>(link.label.as_str())</a>
143+ } else {
144+ <span class="pager-gap" aria-hidden="true">(link.label.as_str())</span>
145+ }
146+ }
147+ }
148+ if let Some(href) = next {
149+ <a class="pager-step" href=(href.as_str()) rel="next">(g::t(lang, K::Next))</a>
150+ }
151+ </nav>
152+ }
153+ })
154+}
155+
156+/// The pager entries and the Previous and Next links for `page` of `pages`.
157+pub fn pager_links(
158+ page: u64,
159+ pages: u64,
160+ href: impl Fn(u64) -> String,
161+) -> (Vec<PageLink>, Option<String>, Option<String>) {
162+ let links = page_numbers(page, pages)
163+ .into_iter()
164+ .map(|n| match n {
165+ Some(n) => PageLink {
166+ label: n.to_string(),
167+ href: Some(href(n)),
168+ current: n == page,
169+ },
170+ None => PageLink {
171+ label: "\u{2026}".to_owned(),
172+ href: None,
173+ current: false,
174+ },
175+ })
176+ .collect();
177+ let prev = (page > 1).then(|| href(page - 1));
178+ let next = (page < pages).then(|| href(page + 1));
179+ (links, prev, next)
180+}
181+
182+#[cfg(test)]
183+mod tests {
184+ use super::page_numbers;
185+
186+ fn shown(page: u64, pages: u64) -> String {
187+ page_numbers(page, pages)
188+ .into_iter()
189+ .map(|n| n.map_or("...".to_owned(), |n| n.to_string()))
190+ .collect::<Vec<_>>()
191+ .join(" ")
192+ }
193+
194+ #[test]
195+ fn pages_are_compact_with_gaps() {
196+ assert_eq!(shown(1, 1), "1");
197+ assert_eq!(shown(1, 3), "1 2 3");
198+ assert_eq!(shown(5, 12), "1 ... 4 5 6 ... 12");
199+ assert_eq!(shown(1, 12), "1 2 ... 12");
200+ assert_eq!(shown(12, 12), "1 ... 11 12");
201+ assert_eq!(shown(4, 12), "1 2 3 4 5 ... 12");
202+ assert_eq!(shown(9, 12), "1 ... 8 9 10 11 12");
203+ }
204+}
crates/forge-web/tests/advisories_e2e.rsmodified+4 -1
@@ -330,7 +330,10 @@ async fn advisory_alert_opens_on_push_and_follows_dismiss_reopen_and_fix() {
330330 new_repo(&b.http, &tahinli, "app").await;
331331
332332 let work = b.dir.join("app-work");
333- let remote = format!("http://tahinli:{token}@127.0.0.1:{}/tahinli/app.git", b.port);
333+ let remote = format!(
334+ "http://tahinli:{token}@127.0.0.1:{}/tahinli/app.git",
335+ b.port
336+ );
334337 git(
335338 &b.dir,
336339 &["clone", "-q", &remote, work.to_str().expect("utf-8 path")],
crates/forge-web/tests/browse_e2e.rsmodified+4 -3
@@ -402,9 +402,10 @@ async fn browse_end_to_end() {
402402 );
403403 let image_srcs = attr_values(&home_body, "img", "src");
404404 assert!(
405- image_srcs.iter().any(
406- |s| s.starts_with(&format!("{raw_base}/tahinli/pub/main/")) && s.ends_with("img.png")
407- ),
405+ image_srcs
406+ .iter()
407+ .any(|s| s.starts_with(&format!("{raw_base}/tahinli/pub/main/"))
408+ && s.ends_with("img.png")),
408409 "README image must point at the raw origin: {image_srcs:?}"
409410 );
410411
crates/forge-web/tests/ci_e2e.rsmodified+27 -0
@@ -50,9 +50,11 @@ image = "docker.io/library/alpine:3"
5050 run = "echo after"
5151 needs = ["build"]
5252
53+# Runs after `after` so the failure cannot cancel the other jobs first (a failed job fails the run fast).
5354 [jobs.broken]
5455 image = "docker.io/library/alpine:3"
5556 run = "exit 3"
57+needs = ["after"]
5658
5759 [jobs.skipme]
5860 image = "docker.io/library/alpine:3"
@@ -77,9 +79,11 @@ image = "docker.io/library/alpine:3"
7779 run = "echo after"
7880 needs = ["build"]
7981
82+# Runs after `after` so the failure cannot cancel the other jobs first (a failed job fails the run fast).
8083 [jobs.broken]
8184 image = "docker.io/library/alpine:3"
8285 run = "exit 3"
86+needs = ["after"]
8387
8488 [jobs.skipme]
8589 image = "docker.io/library/alpine:3"
@@ -636,6 +640,29 @@ async fn push_run_masks_secrets_keeps_artifacts_and_skips_dependants() {
636640 for job in ["build", "after", "broken", "skipme"] {
637641 assert!(run.body.contains(job), "run page lists {job}");
638642 }
643+ // The timeline draws what a job needs as connectors, not as a line under its name: muted from
644+ // build into after, in the accent from the failed broken onto the skipped skipme.
645+ assert!(
646+ run.body.contains(r#"class="ci-glink" data-rel="j"#),
647+ "build links to after: {}",
648+ run.body
649+ );
650+ assert!(
651+ run.body.contains(r#"class="ci-glink ci-hot" data-rel="j"#),
652+ "broken links to skipme in the accent"
653+ );
654+ assert!(
655+ run.body.contains(r#"class="ci-ghead""#),
656+ "connectors have arrowheads"
657+ );
658+ assert!(
659+ run.body.contains("<title>after, needs build</title>"),
660+ "the dependency is in after's box title"
661+ );
662+ assert!(
663+ !run.body.contains(">needs build<"),
664+ "no needs subtitle under a job's name"
665+ );
639666 }
640667
641668 #[tokio::test]
crates/forge-web/tests/discussions_e2e.rsmodified+11 -3
@@ -206,7 +206,9 @@ async fn discussions_create_reply_answer_lock_and_toggle() {
206206 );
207207
208208 // Turn them on from settings, as the owner.
209- let settings = http.get("/tahinli/pub/settings", Some(tahinli.as_str())).await;
209+ let settings = http
210+ .get("/tahinli/pub/settings", Some(tahinli.as_str()))
211+ .await;
210212 assert_eq!(settings.status, 200, "GET settings");
211213 let csrf = input_value(&settings.body, "csrf");
212214 let res = http
@@ -298,7 +300,11 @@ async fn discussions_create_reply_answer_lock_and_toggle() {
298300 let res = http
299301 .post_form(
300302 &format!("{discussion}/answer"),
301- &[("csrf", &csrf_tahinli), ("comment_id", &top), ("answer", "1")],
303+ &[
304+ ("csrf", &csrf_tahinli),
305+ ("comment_id", &top),
306+ ("answer", "1"),
307+ ],
302308 Some(tahinli.as_str()),
303309 )
304310 .await;
@@ -338,7 +344,9 @@ async fn discussions_create_reply_answer_lock_and_toggle() {
338344 assert_eq!(res.status, 403, "bob locks a discussion");
339345
340346 // Turning discussions off hides the tab and the pages.
341- let settings = http.get("/tahinli/pub/settings", Some(tahinli.as_str())).await;
347+ let settings = http
348+ .get("/tahinli/pub/settings", Some(tahinli.as_str()))
349+ .await;
342350 let csrf = input_value(&settings.body, "csrf");
343351 let res = http
344352 .post_form(
crates/forge-web/tests/lfs_e2e.rsmodified+5 -1
@@ -270,7 +270,11 @@ async fn lfs_end_to_end() {
270270 "user.name",
271271 );
272272 ok(
273- &git(&work, &["config", "user.email", "tahinli@example.com"], &iso),
273+ &git(
274+ &work,
275+ &["config", "user.email", "tahinli@example.com"],
276+ &iso,
277+ ),
274278 "user.email",
275279 );
276280 ok(
crates/forge-web/tests/mirrors_e2e.rsmodified+7 -1
@@ -439,7 +439,13 @@ async fn pull_and_push_mirrors_sync_over_smart_http() {
439439 assert!(src_refs.iter().any(|l| l.ends_with("refs/heads/feature")));
440440
441441 // Pull mirror created through the new-repo form. Creation schedules the first sync now.
442- new_repo(&b.http, &session, "dst", Some((&src_url, "tahinli", &token))).await;
442+ new_repo(
443+ &b.http,
444+ &session,
445+ "dst",
446+ Some((&src_url, "tahinli", &token)),
447+ )
448+ .await;
443449 let dst_url = remote(port, &token, "tahinli", "dst");
444450 wait_for("dst to hold src's heads and tags", || {
445451 branches_and_tags(&dst_url).is_some_and(|refs| refs == src_refs)
crates/forge-web/tests/pulls_e2e.rsmodified+4 -1
@@ -542,7 +542,10 @@ async fn push_to_head_branch_updates_open_pull() {
542542 .await;
543543 assert!(page.contains("pushed new commits"));
544544
545- let commits = b.http.get_cookie(&format!("{path}/commits"), &tahinli).await;
545+ let commits = b
546+ .http
547+ .get_cookie(&format!("{path}/commits"), &tahinli)
548+ .await;
546549 assert_eq!(commits.status, 200, "GET pull commits");
547550 assert!(
548551 commits.body.contains("second on feature2"),
crates/forge-web/tests/snippets_e2e.rsmodified+24 -4
@@ -280,9 +280,19 @@ async fn private_snippet_is_hidden_from_others() {
280280 let env = start().await;
281281 let tahinli = login(&env.app, "tahinli").await;
282282 let bob = login(&env.app, "bob").await;
283- let id = create(&env.app, &tahinli, "Secret", "private", &[("s.txt", "shh\n")]).await;
283+ let id = create(
284+ &env.app,
285+ &tahinli,
286+ "Secret",
287+ "private",
288+ &[("s.txt", "shh\n")],
289+ )
290+ .await;
284291
285- let owner = env.app.get(&format!("/snippets/{id}"), Some(&tahinli)).await;
292+ let owner = env
293+ .app
294+ .get(&format!("/snippets/{id}"), Some(&tahinli))
295+ .await;
286296 assert_eq!(owner.status, 200, "owner can read");
287297 assert_eq!(
288298 env.app
@@ -332,7 +342,14 @@ async fn private_snippet_is_hidden_from_others() {
332342 async fn raw_files_use_the_user_content_origin_and_private_tokens() {
333343 let env = start().await;
334344 let tahinli = login(&env.app, "tahinli").await;
335- let public = create(&env.app, &tahinli, "Pub", "public", &[("notes.md", "# Hi\n")]).await;
345+ let public = create(
346+ &env.app,
347+ &tahinli,
348+ "Pub",
349+ "public",
350+ &[("notes.md", "# Hi\n")],
351+ )
352+ .await;
336353 let private = create(
337354 &env.app,
338355 &tahinli,
@@ -399,7 +416,10 @@ async fn unlisted_is_by_link_only_and_delete_removes_it() {
399416 200
400417 );
401418
402- let page = env.app.get(&format!("/snippets/{id}"), Some(&tahinli)).await;
419+ let page = env
420+ .app
421+ .get(&format!("/snippets/{id}"), Some(&tahinli))
422+ .await;
403423 let csrf = input_value(&page.body, "csrf");
404424 let res = env
405425 .app
crates/forge-web/tests/stars_e2e.rsmodified+12 -2
@@ -359,7 +359,14 @@ async fn star_without_a_valid_csrf_token_is_403() {
359359 async fn star_on_a_private_repo_is_404_for_a_non_reader() {
360360 let env = start(seed_repos).await;
361361 let bob = login(&env.http, "bob").await;
362- let res = post_star(&env.http, "/tahinli/priv/star", "anything", Some(&bob), None).await;
362+ let res = post_star(
363+ &env.http,
364+ "/tahinli/priv/star",
365+ "anything",
366+ Some(&bob),
367+ None,
368+ )
369+ .await;
363370 assert_eq!(res.status, 404);
364371 }
365372
@@ -432,7 +439,10 @@ async fn profile_stars_tab_hides_repos_the_viewer_cannot_read() {
432439 let owner = env.http.get("/bob?tab=stars", Some(&tahinli)).await;
433440 let mut names = starred(&owner.body);
434441 names.sort();
435- assert_eq!(names, vec!["tahinli/priv".to_owned(), "tahinli/pub".to_owned()]);
442+ assert_eq!(
443+ names,
444+ vec!["tahinli/priv".to_owned(), "tahinli/pub".to_owned()]
445+ );
436446 }
437447
438448 #[tokio::test]
crates/forge-web/tests/user_delete_e2e.rsmodified+4 -1
@@ -261,7 +261,10 @@ async fn admin_delete_moves_content_to_ghost_and_pages_still_render() {
261261 assert!(issue.body.contains("Deleted user"), "{}", issue.body);
262262
263263 let tahinli_login = try_login(http, "tahinli").await;
264- assert_ne!(tahinli_login.status, 303, "deleted account must not sign in");
264+ assert_ne!(
265+ tahinli_login.status, 303,
266+ "deleted account must not sign in"
267+ );
265268 assert!(cookie_named(&tahinli_login, "forge_session").is_none());
266269 }
267270
docs/ci.mdmodified+17 -1
@@ -105,6 +105,13 @@ Artifacts are stored under the flattened name: `dist/forge` is stored as `dist_f
105105 - Jobs whose `needs` fail or are skipped are marked `skipped`. A skipped job gets the status
106106 `ci/<job>` = `error` with the description `skipped`.
107107
108+### Fail fast
109+
110+When a job fails or errors, the forge cancels every other job in the run at once: queued and
111+blocked jobs become `cancelled`, and jobs that are already running are told to stop through their
112+heartbeat, so the runner aborts them and they end `cancelled`. The run ends `failure`, so no release
113+is published and no self-update happens. A long `build` does not keep compiling after `test` fails.
114+
108115 ### Releases
109116
110117 A `[release]` table publishes a release from a tag run. It needs at least one glob in `[on] tags`.
@@ -115,6 +122,11 @@ for example one you made by hand, the forge updates it: the existing title and n
115122 the selected artifacts are attached, replacing any asset with the same name. A run where any job
116123 fails or is skipped creates no release. The job needs no token and no `curl`.
117124
125+This holds when jobs run in parallel. If the job that produces the artifacts (say `build`) finishes
126+green while another job (say `test`) is still running or later fails, nothing is published: the
127+release waits for the whole run to be `success`. The forge's own server self-update follows the same
128+rule and only deploys a run whose every job succeeded.
129+
118130 For scripted control, use the REST API with a personal access token stored as a repo secret. See
119131 [api.md](api.md).
120132
@@ -399,7 +411,11 @@ jobs are running, the runner stops claiming, replaces its binary, and exits with
399411 restarts it. It is skipped when the forge's binary is for a different OS or architecture. Set
400412 `auto_update = false` to pin the binary by hand.
401413
402-`concurrency` is the number of jobs run in parallel. The default is 1. Each job runs with no
414+`concurrency` is the number of jobs run in parallel. The default is 1. Jobs without `needs` between
415+them (for example `test` and `build` in this repo's own `ci.toml`) only run at the same time when the
416+forge has capacity for both: set `concurrency = 2` on the runner or register a second runner.
417+Otherwise they queue and run one after the other. Each concurrent job needs its own RAM, so a
418+second Rust build alongside the first needs several more GB even with `CARGO_BUILD_JOBS=1`. Each job runs with no
403419 capabilities and `no_new_privileges`. The builtin executor also runs each job under a seccomp
404420 profile that denies calls such as `mount`, `ptrace`, `bpf` and `unshare`.
405421
scripts/audit/forgeclient.pyadded+104 -0
@@ -0,0 +1,104 @@
1+"""Tiny stdlib HTTP client for the forge audit harness: manual cookies, no auto-redirects."""
2+
3+import json
4+import re
5+import urllib.error
6+import urllib.parse
7+import urllib.request
8+
9+
10+class _NoRedirect(urllib.request.HTTPRedirectHandler):
11+ def redirect_request(self, *args, **kwargs):
12+ return None
13+
14+
15+_OPENER = urllib.request.build_opener(_NoRedirect)
16+
17+
18+class Resp:
19+ def __init__(self, status, headers, body):
20+ self.status = status
21+ self.headers = headers
22+ self.body = body
23+
24+ @property
25+ def text(self):
26+ return self.body.decode("utf-8", "replace")
27+
28+ @property
29+ def location(self):
30+ return self.headers.get("Location", "")
31+
32+ def json(self):
33+ return json.loads(self.body or b"null")
34+
35+
36+def raw_request(url, method="GET", data=None, headers=None, timeout=60):
37+ req = urllib.request.Request(url, data=data, method=method, headers=headers or {})
38+ try:
39+ with _OPENER.open(req, timeout=timeout) as r:
40+ return Resp(r.status, r.headers, r.read())
41+ except urllib.error.HTTPError as e:
42+ return Resp(e.code, e.headers, e.read())
43+
44+
45+class Client:
46+ def __init__(self, base):
47+ self.base = base.rstrip("/")
48+ self.cookies = {}
49+ self.csrf = None
50+
51+ def cookie_header(self):
52+ return "; ".join(f"{k}={v}" for k, v in self.cookies.items())
53+
54+ def _absorb(self, resp):
55+ for sc in resp.headers.get_all("Set-Cookie") or []:
56+ pair = sc.split(";", 1)[0]
57+ if "=" not in pair:
58+ continue
59+ k, v = pair.split("=", 1)
60+ low = sc.lower()
61+ if v == "" or "max-age=0" in low:
62+ self.cookies.pop(k.strip(), None)
63+ else:
64+ self.cookies[k.strip()] = v
65+
66+ def request(self, path, method="GET", data=None, headers=None, follow=True):
67+ url = path if path.startswith("http") else self.base + path
68+ for _ in range(8):
69+ h = {"Origin": self.base, "Referer": url}
70+ h.update(headers or {})
71+ if self.cookies:
72+ h["Cookie"] = self.cookie_header()
73+ resp = raw_request(url, method, data, h)
74+ self._absorb(resp)
75+ if follow and resp.status in (301, 302, 303, 307, 308) and resp.location:
76+ url = urllib.parse.urljoin(url, resp.location)
77+ if resp.status in (301, 302, 303):
78+ method, data = "GET", None
79+ continue
80+ resp.url = url
81+ return resp
82+ resp.url = url
83+ return resp
84+
85+ def get(self, path, **kw):
86+ return self.request(path, **kw)
87+
88+ def post(self, path, fields, follow=True):
89+ if isinstance(fields, dict):
90+ fields = list(fields.items())
91+ if self.csrf and not any(k in ("csrf", "precsrf") for k, _ in fields):
92+ fields = [("csrf", self.csrf)] + list(fields)
93+ body = urllib.parse.urlencode(fields).encode()
94+ return self.request(
95+ path, "POST", body,
96+ {"Content-Type": "application/x-www-form-urlencoded"}, follow=follow,
97+ )
98+
99+
100+def field(html, name):
101+ m = re.search(r'name="%s"[^>]*?value="([^"]*)"' % re.escape(name), html)
102+ if not m:
103+ m = re.search(r'value="([^"]*)"[^>]*?name="%s"' % re.escape(name), html)
104+ return m.group(1) if m else None
scripts/audit/run.shadded+95 -0
@@ -0,0 +1,95 @@
1+#!/usr/bin/env bash
2+# Visual audit harness: builds forge, starts it on a throwaway data dir, seeds realistic data,
3+# screenshots every GET page in several variants and writes target/audit/index.md.
4+#
5+# Usage: scripts/audit/run.sh [--no-build] [--keep-data]
6+# Env: AUDIT_FILTER=regex only routes whose pattern/url matches (e.g. '/issues')
7+# AUDIT_VARIANTS=a,b subset of: desktop-light mobile-light desktop-light-sbright desktop-dark
8+# mobile-dark anon-desktop-light anon-mobile-light anon-desktop-dark
9+# AUDIT_BROWSER=chromium chromium (default, flatpak org.chromium.Chromium), firefox, or both
10+# AUDIT_PORT=17660 forge port (proxy is +10, user content +1)
11+# AUDIT_SSH_PORT=12222 ssh port
12+# AUDIT_OUT=dir output dir (default target/audit)
13+# AUDIT_TARGET=dir cargo target dir (default target/agent-audit)
14+# --keep-data reuses an already seeded data dir (skips seeding) for quick re-shoots.
15+set -euo pipefail
16+
17+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
18+OUT="${AUDIT_OUT:-$ROOT/target/audit}"
19+DATA="$OUT/data"
20+PORT="${AUDIT_PORT:-17660}"
21+TARGET="${AUDIT_TARGET:-target/agent-audit}"
22+BIN="$ROOT/$TARGET/debug/forge"
23+SSH_PORT="${AUDIT_SSH_PORT:-12222}"
24+BUILD=1 KEEP=0
25+for a in "$@"; do
26+ case "$a" in
27+ --no-build) BUILD=0 ;;
28+ --keep-data) KEEP=1 ;;
29+ *) echo "unknown arg $a" >&2; exit 2 ;;
30+ esac
31+done
32+
33+if [[ $BUILD == 1 ]]; then
34+ echo "[run] building forge-web (dev profile)"
35+ (cd "$ROOT" && CARGO_TARGET_DIR="$TARGET" cargo build -p forge-web)
36+fi
37+[[ -x $BIN ]] || { echo "[run] missing $BIN" >&2; exit 1; }
38+
39+# Stop anything left over from an earlier run on our ports.
40+pkill -f -- "--config $OUT/forge.toml" 2>/dev/null || true
41+if [[ $KEEP == 0 || ! -f $OUT/seed.json ]]; then
42+ KEEP=0
43+ rm -rf "$DATA" "$OUT/work" "$OUT/githome" "$OUT/sshkey" "$OUT/seed.json"
44+fi
45+rm -rf "$OUT/shots" "$OUT/tmp" "$OUT/index.md" "$OUT/index.json"
46+mkdir -p "$DATA" "$OUT/shots" "$OUT/tmp"
47+
48+cat > "$OUT/forge.toml" <<EOF
49+database = "$DATA/forge.db"
50+data_dir = "$DATA"
51+listen = "127.0.0.1:$PORT"
52+base_url = "http://127.0.0.1:$PORT"
53+user_content_base_url = "http://127.0.0.1:$((PORT + 1))"
54+user_content_listen = "127.0.0.1:$((PORT + 1))"
55+ssh_listen = "127.0.0.1:$SSH_PORT"
56+ssh_public_host = "127.0.0.1"
57+ssh_public_port = $SSH_PORT
58+registration = "open"
59+trusted_proxies = []
60+
61+[mail]
62+transport = "log"
63+
64+[ci]
65+enabled = true
66+EOF
67+
68+echo "[run] starting forge on 127.0.0.1:$PORT"
69+"$BIN" --config "$OUT/forge.toml" > "$OUT/forge.log" 2>&1 &
70+FORGE_PID=$!
71+cleanup() {
72+ kill "$FORGE_PID" 2>/dev/null || true
73+ wait "$FORGE_PID" 2>/dev/null || true
74+ pkill -f "[f]orge-audit-ff-" 2>/dev/null || true
75+ pkill -f "[u]ser-data-dir=.*forge-audit-cr-" 2>/dev/null || true
76+ rm -rf "$OUT/tmp"
77+ echo "[run] server stopped"
78+}
79+trap cleanup EXIT INT TERM
80+
81+for _ in $(seq 1 120); do
82+ curl -fsS "http://127.0.0.1:$PORT/healthz" >/dev/null 2>&1 && break
83+ kill -0 "$FORGE_PID" 2>/dev/null || { echo "[run] forge exited, see $OUT/forge.log" >&2; tail -20 "$OUT/forge.log" >&2; exit 1; }
84+ sleep 0.5
85+done
86+
87+if [[ $KEEP == 0 ]]; then
88+ echo "[run] seeding"
89+ python3 "$ROOT/scripts/audit/seed.py" "http://127.0.0.1:$PORT" "$OUT" 2>&1 | tee "$OUT/seed.log"
90+fi
91+
92+echo "[run] screenshots"
93+AUDIT_PROXY_PORT="${AUDIT_PROXY_PORT:-$((PORT + 10))}" \
94+ python3 "$ROOT/scripts/audit/shoot.py" "http://127.0.0.1:$PORT" "$OUT" "$ROOT/crates/forge-web/src" 2>&1 | tee "$OUT/shoot.log"
95+echo "[run] done: $OUT/index.md"
scripts/audit/seed.pyadded+534 -0
@@ -0,0 +1,534 @@
1+#!/usr/bin/env python3
2+"""Seeds a fresh forge instance with realistic data through its own HTTP forms and REST API.
3+
4+Usage: seed.py BASE_URL OUT_DIR
5+Writes OUT_DIR/seed.json with the session cookies and the ids the screenshot pass substitutes.
6+Every step is best effort: a failing step is logged and the rest go on.
7+"""
8+
9+import json
10+import os
11+import re
12+import shutil
13+import subprocess
14+import sys
15+import traceback
16+import urllib.parse
17+
18+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
19+from forgeclient import Client, field, raw_request # noqa: E402
20+
21+BASE = sys.argv[1].rstrip("/")
22+OUT = sys.argv[2]
23+PASSWORD = "audit-password-1234"
24+ADMIN, OTHER = "tahinli", "kaan"
25+REPO, PRIV, ORG, ORG_REPO, TEAM = "forge-demo", "dotfiles", "forge-org", "infra", "core"
26+
27+seed = {"base": BASE, "admin": ADMIN, "other": OTHER, "repo": REPO, "private_repo": PRIV,
28+ "org": ORG, "org_repo": ORG_REPO, "team": TEAM, "failed_steps": []}
29+
30+
31+def step(name):
32+ def wrap(fn):
33+ try:
34+ fn()
35+ print(f"[seed] ok {name}", flush=True)
36+ except Exception as e: # best effort
37+ print(f"[seed] FAIL {name}: {e}", flush=True)
38+ traceback.print_exc(limit=2)
39+ seed["failed_steps"].append(f"{name}: {e}")
40+ return fn
41+ return wrap
42+
43+
44+def ok(resp, what):
45+ if resp.status >= 400:
46+ snippet = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", resp.text))[:300]
47+ raise RuntimeError(f"{what} -> HTTP {resp.status}: {snippet}")
48+ return resp
49+
50+
51+def load_csrf(c):
52+ r = ok(c.get("/settings/profile"), "profile page")
53+ c.csrf = field(r.text, "csrf")
54+ if not c.csrf:
55+ raise RuntimeError("no csrf on /settings/profile")
56+
57+
58+admin = Client(BASE)
59+other = Client(BASE)
60+
61+
62+def login(c, user):
63+ r = c.get("/login")
64+ pre = field(r.text, "precsrf")
65+ ok(c.post("/login", {"precsrf": pre, "username": user, "password": PASSWORD, "next": "/"}), "login")
66+ load_csrf(c)
67+
68+
69+@step("setup admin")
70+def _():
71+ r = admin.get("/setup")
72+ pre = field(r.text, "precsrf")
73+ if r.status == 200 and pre:
74+ ok(admin.post("/setup", {"precsrf": pre, "username": ADMIN, "email": "tahinli@example.com",
75+ "password": PASSWORD, "confirm": PASSWORD}), "setup")
76+ load_csrf(admin)
77+ else:
78+ login(admin, ADMIN)
79+
80+
81+@step("create second user")
82+def _():
83+ ok(admin.post("/admin/users", {"username": OTHER, "email": "kaan@example.com",
84+ "password": PASSWORD}), "admin create user")
85+ login(other, OTHER)
86+
87+
88+@step("profile bio")
89+def _():
90+ r = admin.get("/settings/profile")
91+ names = set(re.findall(r'name="([a-z_]+)"', r.text))
92+ fields = {k: "" for k in names if k not in ("csrf",)}
93+ fields.update({k: v for k, v in {
94+ "full_name": "Ahmet Kaan Gümüş", "display_name": "Ahmet Kaan Gümüş", "name": "Ahmet Kaan Gümüş",
95+ "bio": "Building my own forge. Rust, git, and self-hosting.",
96+ "location": "Istanbul", "website": "https://example.com", "pronouns": "he/him",
97+ }.items() if k in names})
98+ ok(admin.post("/settings/profile", fields), "profile save")
99+
100+
101+@step("personal access token")
102+def _():
103+ r = ok(admin.post("/settings/tokens", {"name": "audit-cli", "expires": "90"}), "token create")
104+ m = re.search(r"forge_[A-Za-z0-9_\-]{16,}", r.text)
105+ if not m:
106+ raise RuntimeError("token not shown")
107+ seed["pat"] = m.group(0)
108+ admin.post("/settings/tokens", {"name": "ci-deploy", "expires": "never"})
109+ r = ok(other.post("/settings/tokens", {"name": "kaan-laptop", "expires": "30"}), "token2")
110+ m = re.search(r"forge_[A-Za-z0-9_\-]{16,}", r.text)
111+ seed["pat_other"] = m.group(0) if m else None
112+
113+
114+@step("ssh key")
115+def _():
116+ d = os.path.join(OUT, "sshkey")
117+ shutil.rmtree(d, ignore_errors=True)
118+ os.makedirs(d)
119+ subprocess.run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "tahinli@laptop",
120+ "-f", os.path.join(d, "id")], check=True)
121+ pub = open(os.path.join(d, "id.pub")).read().strip()
122+ ok(admin.post("/settings/keys", {"title": "laptop", "public_key": pub}), "add key")
123+
124+
125+@step("repositories")
126+def _():
127+ ok(admin.post("/new", {"name": REPO, "description": "A demo project for the visual audit: Rust, docs and CI.",
128+ "visibility": "public", "default_branch": "main", "default_labels": "on",
129+ "owner": ADMIN}), "new repo")
130+ ok(admin.post("/new", {"name": PRIV, "description": "Private config files.", "visibility": "private",
131+ "default_branch": "main", "owner": ADMIN}), "new private repo")
132+ ok(other.post("/new", {"name": "kaan-scratch", "description": "Kaan's experiments.",
133+ "visibility": "public", "default_branch": "main", "owner": OTHER}), "kaan repo")
134+
135+
136+def git(cwd, *args, env=None):
137+ e = dict(os.environ, GIT_TERMINAL_PROMPT="0", GIT_CONFIG_NOSYSTEM="1",
138+ GIT_AUTHOR_NAME="Ahmet Kaan Gümüş", GIT_AUTHOR_EMAIL="tahinli@example.com",
139+ GIT_COMMITTER_NAME="Ahmet Kaan Gümüş", GIT_COMMITTER_EMAIL="tahinli@example.com",
140+ HOME=os.path.join(OUT, "githome"))
141+ e.update(env or {})
142+ os.makedirs(e["HOME"], exist_ok=True)
143+ return subprocess.run(["git", *args], cwd=cwd, env=e, check=True, capture_output=True, text=True).stdout
144+
145+
146+def write(root, rel, text):
147+ p = os.path.join(root, rel)
148+ os.makedirs(os.path.dirname(p), exist_ok=True)
149+ with open(p, "w") as f:
150+ f.write(text)
151+
152+
153+README = """# forge-demo
154+
155+A small Rust project used to exercise every page of the forge.
156+
157+## Features
158+
159+- Fast `git` hosting with **smart HTTP** and SSH
160+- Issues, pull requests, releases and a wiki
161+- A commit heatmap that keeps you motivated
162+
163+## Usage
164+
165+```sh
166+cargo run -- --config config/forge.toml
167+```
168+
169+| Command | What it does |
170+| --- | --- |
171+| `serve` | Starts the web UI |
172+| `backup` | Writes a backup set |
173+
174+> Tip: keep the data dir on a fast disk.
175+"""
176+
177+MAIN_RS = """//! Entry point of the demo.
178+
179+use std::env;
180+
181+/// Greets the person named on the command line.
182+fn greet(name: &str) -> String {
183+ format!("Hello, {name}!")
184+}
185+
186+fn main() {
187+ let name = env::args().nth(1).unwrap_or_else(|| "world".to_owned());
188+ println!("{}", greet(&name));
189+}
190+
191+#[cfg(test)]
192+mod tests {
193+ use super::*;
194+
195+ #[test]
196+ fn greets() {
197+ assert_eq!(greet("tahinli"), "Hello, tahinli!");
198+ }
199+}
200+"""
201+
202+CI = """[on]
203+push = ["main"]
204+pull_request = true
205+manual = true
206+
207+[jobs.test]
208+image = "docker.io/library/rust:1"
209+run = \"\"\"
210+cargo test
211+\"\"\"
212+
213+[jobs.lint]
214+image = "docker.io/library/rust:1"
215+run = "cargo clippy"
216+
217+[jobs.package]
218+image = "docker.io/library/rust:1"
219+needs = ["test", "lint"]
220+run = "cargo build --release"
221+
222+[jobs.publish]
223+image = "docker.io/library/rust:1"
224+needs = ["package"]
225+run = "echo publish"
226+"""
227+
228+CARGO_LOCK = """version = 4
229+
230+[[package]]
231+name = "forge-demo"
232+version = "0.2.0"
233+
234+[[package]]
235+name = "smallvec"
236+version = "1.6.0"
237+source = "registry+https://github.com/rust-lang/crates.io-index"
238+"""
239+
240+
241+@step("push git history")
242+def _():
243+ work = os.path.join(OUT, "work", REPO)
244+ shutil.rmtree(work, ignore_errors=True)
245+ os.makedirs(work)
246+ git(work, "init", "-q", "-b", "main")
247+ commits = [
248+ ("2026-09-01T10:00:00", {"README.md": README, "Cargo.toml": '[package]\nname = "forge-demo"\nversion = "0.1.0"\nedition = "2024"\n'},
249+ "Initial commit"),
250+ ("2026-09-03T12:30:00", {"src/main.rs": MAIN_RS}, "Add greeting binary"),
251+ ("2026-09-08T09:15:00", {"docs/guide.md": "# Guide\n\nRun `cargo run`.\n\n## Config\n\nSee `config/forge.toml`.\n",
252+ "config/forge.toml": 'listen = "127.0.0.1:7660"\nregistration = "closed"\n'},
253+ "Add docs and config"),
254+ ("2026-09-15T18:45:00", {".forge/ci.toml": CI, "Cargo.lock": CARGO_LOCK}, "Add CI workflow"),
255+ ("2026-10-01T08:00:00", {"src/lib.rs": "//! Library part.\n\npub fn add(a: u32, b: u32) -> u32 {\n a + b\n}\n",
256+ "Cargo.toml": '[package]\nname = "forge-demo"\nversion = "0.2.0"\nedition = "2024"\n'},
257+ "Release 0.2.0"),
258+ ]
259+ for i, (date, files, msg) in enumerate(commits):
260+ for rel, text in files.items():
261+ write(work, rel, text)
262+ git(work, "add", "-A")
263+ git(work, "commit", "-q", "-m", msg, env={"GIT_AUTHOR_DATE": date, "GIT_COMMITTER_DATE": date})
264+ if i == 2:
265+ git(work, "tag", "-a", "v0.1.0", "-m", "Version 0.1.0")
266+ git(work, "tag", "-a", "v0.2.0", "-m", "Version 0.2.0")
267+ git(work, "checkout", "-q", "-b", "feature/heatmap")
268+ write(work, "src/heatmap.rs", "//! Commit heatmap.\n\npub fn cells(days: usize) -> Vec<u8> {\n vec![0; days]\n}\n")
269+ write(work, "README.md", README + "\n## Heatmap\n\nShows a year of commits.\n")
270+ git(work, "add", "-A")
271+ git(work, "commit", "-q", "-m", "Add commit heatmap module")
272+ write(work, "src/heatmap.rs", "//! Commit heatmap.\n\n/// One cell per day.\npub fn cells(days: usize) -> Vec<u8> {\n vec![0; days]\n}\n")
273+ git(work, "commit", "-q", "-am", "Document heatmap cells")
274+ git(work, "checkout", "-q", "main")
275+ git(work, "checkout", "-q", "-b", "docs/typos")
276+ write(work, "docs/guide.md", "# Guide\n\nRun `cargo run --release`.\n")
277+ git(work, "commit", "-q", "-am", "Fix guide typos")
278+ git(work, "checkout", "-q", "main")
279+ host = urllib.parse.urlsplit(BASE).netloc
280+ url = f"http://{ADMIN}:{seed['pat']}@{host}/{ADMIN}/{REPO}.git"
281+ git(work, "push", "-q", url, "--all")
282+ git(work, "push", "-q", url, "--tags")
283+ seed["head_oid"] = git(work, "rev-parse", "main").strip()
284+ seed["first_oid"] = git(work, "rev-list", "--max-parents=0", "main").strip()
285+ seed["blob_path"] = "src/main.rs"
286+ seed["tree_path"] = "src"
287+ # second repo: a single commit so it is not empty
288+ w2 = os.path.join(OUT, "work", PRIV)
289+ shutil.rmtree(w2, ignore_errors=True)
290+ os.makedirs(w2)
291+ git(w2, "init", "-q", "-b", "main")
292+ write(w2, ".bashrc", "export EDITOR=hx\n")
293+ write(w2, "README.md", "# dotfiles\n\nMy shell setup.\n")
294+ git(w2, "add", "-A")
295+ git(w2, "commit", "-q", "-m", "Add dotfiles")
296+ git(w2, "push", "-q", f"http://{ADMIN}:{seed['pat']}@{host}/{ADMIN}/{PRIV}.git", "main")
297+
298+
299+R = f"/{ADMIN}/{REPO}"
300+
301+
302+@step("labels and milestones")
303+def _():
304+ ok(admin.post(f"{R}/labels", {"name": "ui", "color": "#7c9a6d", "description": "Visual and layout work"}), "label")
305+ ok(admin.post(f"{R}/labels", {"name": "needs-triage", "color": "#d4a72c", "description": ""}), "label2")
306+ ok(admin.post(f"{R}/milestones", {"title": "v0.3.0", "description": "Heatmap and wiki polish",
307+ "due_on": "2026-12-01", "state": "open"}), "milestone")
308+ admin.post(f"{R}/milestones", {"title": "v0.2.0", "description": "Shipped", "due_on": "", "state": "closed"})
309+ r = admin.get(f"{R}/milestones")
310+ m = re.search(r"/milestones/([^/\"]+)/edit", r.text)
311+ seed["milestone_id"] = m.group(1) if m else None
312+
313+
314+@step("issues and comments")
315+def _():
316+ issues = [
317+ ("Heatmap cells overflow on narrow screens", "On a 390px wide phone the heatmap scrolls sideways.\n\n- [ ] fix grid\n- [x] reproduce"),
318+ ("Add dark theme screenshots to the docs", "We should show both themes in `docs/`."),
319+ ("Release assets are missing checksums", "Each release should ship a `SHA256SUMS` file."),
320+ ("Wiki sidebar collapses unexpectedly", "Steps:\n1. open wiki\n2. resize\n\n```rust\nfn main() {}\n```"),
321+ ]
322+ for title, body in issues:
323+ ok(admin.post(f"{R}/issues/new", {"title": title, "body": body}), "issue")
324+ ok(other.post(f"{R}/issues/new", {"title": "Clone URL copy button does nothing", "body": "Firefox 158, clicking copy shows no toast."}), "issue by kaan")
325+ page = admin.get(f"{R}/issues/1").text
326+ labels = re.findall(r'name="label"[^>]*value="([^"]+)"', page) or re.findall(r'value="([^"]+)"[^>]*name="label"', page)
327+ if labels:
328+ admin.post(f"{R}/issues/1/labels", [("label", v) for v in labels[:3]])
329+ admin.post(f"{R}/issues/3/labels", [("label", labels[-1])])
330+ mid = seed.get("milestone_id")
331+ if mid:
332+ admin.post(f"{R}/issues/1/milestone", {"milestone": mid, "milestone_id": mid})
333+ ok(other.post(f"{R}/issues/1/comment", {"body": "I can reproduce this on Android too. :+1:"}), "comment kaan")
334+ ok(admin.post(f"{R}/issues/1/comment", {"body": "Thanks @kaan, looking into the grid now."}), "comment admin")
335+ other.post(f"{R}/issues/2/comment", {"body": "Happy to help with the screenshots."})
336+ page = admin.get(f"{R}/issues/1").text
337+ m = re.search(r"/issues/1/comments/([^/\"]+)/edit", page)
338+ seed["issue_comment_id"] = m.group(1) if m else None
339+ admin.post(f"{R}/issues/1/edit", {"title": "Heatmap cells overflow on narrow screens (mobile)",
340+ "body": issues[0][1] + "\n\nEdited: also on tablets."})
341+ page = admin.get(f"{R}/issues/1").text
342+ m = re.search(r"/issues/1/history/([^/\"]+)/([^/\"]+)", page)
343+ if m:
344+ seed["issue_history"] = [m.group(1), m.group(2)]
345+ admin.post(f"{R}/issues/4/comment", {"body": "Fixed in main.", "action": "close_completed"})
346+
347+
348+@step("pull request")
349+def _():
350+ ok(other.post(f"{R}/pulls", {"title": "Add commit heatmap module", "body": "Adds `src/heatmap.rs`.\n\nCloses #1",
351+ "base": "main", "head": "feature/heatmap"}), "pull by kaan")
352+ admin.post(f"{R}/pulls", {"title": "Fix guide typos", "body": "Small docs fix.", "base": "main", "head": "docs/typos"})
353+ r = admin.get(f"{R}/pulls")
354+ nums = sorted({int(n) for n in re.findall(rf"{re.escape(R)}/pulls/(\d+)", r.text)})
355+ seed["pull_number"] = nums[0] if nums else 6
356+ n = seed["pull_number"]
357+ other.post(f"{R}/pulls/{n}/comments", {"body": "Ready for review."})
358+ admin.post(f"{R}/pulls/{n}/comments", {"body": "Looks good, one nit on the doc comment."})
359+ page = admin.get(f"{R}/pulls/{n}").text
360+ m = re.search(rf"/pulls/{n}/comments/([^/\"]+)/edit", page)
361+ seed["pull_comment_id"] = m.group(1) if m else None
362+ page = admin.get(f"{R}/pulls/{n}/files").text
363+ # leave a review comment on the first diff line if the form exposes its fields
364+ form = re.search(r'<form[^>]*action="[^"]*/review_comments"[^>]*>(.*?)</form>', page, re.S)
365+ if form:
366+ fields = dict(re.findall(r'name="([a-z_]+)"[^>]*value="([^"]*)"', form.group(1)))
367+ fields["body"] = "Consider documenting the return value."
368+ admin.post(f"{R}/pulls/{n}/review_comments", fields)
369+ page = admin.get(f"{R}/pulls/{n}/files").text
370+ m = re.search(rf"/pulls/{n}/review_comments/([^/\"]+)/edit", page)
371+ seed["review_comment_id"] = m.group(1) if m else None
372+
373+
374+@step("release with assets (REST API)")
375+def _():
376+ h = {"Authorization": f"Bearer {seed['pat']}", "Content-Type": "application/json"}
377+ api = f"{BASE}/api/v1/repos/{ADMIN}/{REPO}/releases"
378+ r = raw_request(api, "POST", json.dumps({"tag": "v0.2.0", "title": "Version 0.2.0",
379+ "body": "## Changes\n\n- Library crate\n- CI workflow\n\n**Full changelog**: v0.1.0...v0.2.0"}).encode(), h)
380+ ok(r, "create release")
381+ rid = r.json()["id"]
382+ seed["release_id"] = rid
383+ for name, data, ctype in [("forge-demo-linux-x86_64.tar.gz", os.urandom(40_000), "application/gzip"),
384+ ("SHA256SUMS", b"abc123 forge-demo-linux-x86_64.tar.gz\n", "text/plain")]:
385+ ok(raw_request(f"{api}/{rid}/assets/{name}", "PUT", data,
386+ {"Authorization": f"Bearer {seed['pat']}", "Content-Type": ctype}), "asset")
387+ r = raw_request(api, "POST", json.dumps({"tag": "v0.1.0", "title": "Version 0.1.0", "body": "First release."}).encode(), h)
388+ raw_request(api, "POST", json.dumps({"tag": "v0.3.0-rc1", "target": "main", "title": "0.3.0 RC 1",
389+ "body": "Draft notes.", "draft": True, "prerelease": True}).encode(), h)
390+
391+
392+@step("wiki")
393+def _():
394+ r = admin.get(f"{R}/wiki/-/new")
395+ base = field(r.text, "base") or ""
396+ ok(admin.post(f"{R}/wiki/-/new", {"base": base, "name": "Home",
397+ "content": "# Welcome\n\nThis is the **forge-demo** wiki.\n\n- [[Install]]\n- [[Architecture]]\n",
398+ "message": "Create Home"}), "wiki home")
399+ for name, content in [("Install", "# Install\n\n```sh\ncargo install --path .\n```\n"),
400+ ("Architecture", "# Architecture\n\n| Crate | Role |\n| --- | --- |\n| core | store |\n| web | UI |\n")]:
401+ r = admin.get(f"{R}/wiki/-/new")
402+ admin.post(f"{R}/wiki/-/new", {"base": field(r.text, "base") or "", "name": name, "content": content,
403+ "message": f"Add {name}"})
404+ r = admin.get(f"{R}/wiki/Home/edit")
405+ admin.post(f"{R}/wiki/Home/edit", {"base": field(r.text, "base") or "", "name": "Home",
406+ "content": "# Welcome\n\nThis is the **forge-demo** wiki. Start with [[Install]].\n",
407+ "message": "Tweak Home"})
408+
409+
410+@step("snippets")
411+def _():
412+ r = ok(admin.post("/snippets/new", {"title": "Backup cron", "description": "Nightly backup with restic",
413+ "visibility": "public", "name_0": "backup.sh",
414+ "content_0": "#!/bin/sh\nrestic backup /var/lib/forge\n",
415+ "name_1": "notes.md", "content_1": "# Notes\n\nRun at 03:00.\n"}), "snippet")
416+ m = re.search(r"/snippets/([A-Za-z0-9_-]+)", r.url or "")
417+ sid = m.group(1) if m and m.group(1) != "new" else None
418+ if not sid:
419+ m = re.findall(r'/snippets/([A-Za-z0-9_-]+)"', admin.get("/snippets").text)
420+ sid = next((x for x in m if x != "new"), None)
421+ seed["snippet_id"] = sid
422+ if sid:
423+ r = admin.get(f"/snippets/{sid}/edit")
424+ admin.post(f"/snippets/{sid}/edit", {"title": "Backup cron", "description": "Nightly backup with restic (edited)",
425+ "visibility": "public", "name_0": "backup.sh",
426+ "content_0": "#!/bin/sh\nset -eu\nrestic backup /var/lib/forge\n"})
427+ other.post("/snippets/new", {"title": "fish prompt", "description": "", "visibility": "public",
428+ "name_0": "config.fish", "content_0": "set -g fish_greeting\n"})
429+
430+
431+@step("organization, members and teams")
432+def _():
433+ ok(admin.post("/org/new", {"name": ORG, "description": "The people building forge."}), "org")
434+ ok(admin.post(f"/org/{ORG}/members/add", {"username": OTHER, "role": "member"}), "member add")
435+ ok(admin.post("/new", {"name": ORG_REPO, "description": "Deployment and infra scripts.", "visibility": "public",
436+ "default_branch": "main", "owner": ORG}), "org repo")
437+ ok(admin.post(f"/org/{ORG}/teams/new", {"name": TEAM, "description": "Core maintainers", "role": "write",
438+ "all_repos": ""}), "team")
439+ r = admin.get(f"/org/{ORG}/teams")
440+ m = re.search(rf"/org/{ORG}/teams/([A-Za-z0-9_.-]+)\"", r.text)
441+ if m:
442+ seed["team"] = m.group(1)
443+ admin.post(f"/org/{ORG}/teams/{seed['team']}/members/add", {"username": OTHER})
444+ admin.post(f"/org/{ORG}/teams/new", {"name": "docs", "description": "Docs writers", "role": "read", "all_repos": "on"})
445+
446+
447+@step("stars and watches")
448+def _():
449+ other.post(f"{R}/star", {})
450+ admin.post(f"{R}/star", {})
451+ admin.post(f"/{OTHER}/kaan-scratch/star", {})
452+
453+
454+@step("collaborator")
455+def _():
456+ admin.post(f"{R}/settings/collaborators/add", {"username": OTHER, "role": "write"})
457+
458+
459+@step("discussion")
460+def _():
461+ r = admin.get(f"{R}/discussions/new")
462+ if r.status >= 400:
463+ admin.post(f"{R}/settings/discussions", {"enabled": "1"})
464+ r = admin.get(f"{R}/discussions/new")
465+ cats = re.findall(r'<option value="([^"]+)"', r.text)
466+ ok(admin.post(f"{R}/discussions/new", {"category": cats[0] if cats else "general",
467+ "title": "Roadmap for 0.3", "body": "What should land next?"}), "discussion")
468+ # Discussions share the issue/PR number counter, so find the real number.
469+ nums = re.findall(rf'{re.escape(R)}/discussions/(\d+)', admin.get(f"{R}/discussions").text)
470+ seed["discussion_number"] = int(nums[0]) if nums else 1
471+ other.post(f"{R}/discussions/{seed['discussion_number']}/comments", {"body": "Mobile layout fixes please!"})
472+
473+
474+@step("ci runner registration")
475+def _():
476+ r = ok(admin.post("/admin/runners/tokens", {}), "runner token")
477+ m = re.search(r"--token\s+(\S+)", re.sub(r"<[^>]+>", " ", r.text))
478+ if not m:
479+ raise RuntimeError("token not found")
480+ resp = raw_request(f"{BASE}/api/v1/ci/runners/register", "POST",
481+ json.dumps({"token": m.group(1), "name": "audit-runner-1", "labels": ["linux", "x86_64"]}).encode(),
482+ {"Content-Type": "application/json"})
483+ ok(resp, "register")
484+
485+
486+@step("ci run discovery")
487+def _():
488+ r = admin.get(f"{R}/ci")
489+ if "/ci/runs/" not in r.text:
490+ admin.post(f"{R}/ci", {"ref": "main", "branch": "main"})
491+ r = admin.get(f"{R}/ci")
492+ m = re.search(rf"{re.escape(R)}/ci/runs/(\d+)", r.text)
493+ seed["run_number"] = int(m.group(1)) if m else None
494+ if m:
495+ page = admin.get(f"{R}/ci/runs/{m.group(1)}").text
496+ j = re.search(rf"{re.escape(R)}/ci/jobs/([^/\"]+)", page)
497+ seed["job_id"] = j.group(1) if j else None
498+
499+
500+@step("user id for admin pages")
501+def _():
502+ r = admin.get("/admin/users")
503+ ids = re.findall(r"/admin/users/([^/\"]+)/delete", r.text)
504+ seed["user_id"] = ids[-1] if ids else None
505+
506+
507+@step("webhook")
508+def _():
509+ r = admin.get(f"{R}/settings/hooks/new")
510+ names = set(re.findall(r'name="([a-z_]+)"', r.text))
511+ fields = {"url": "https://hooks.example.com/forge", "secret": "s3cret", "content_type": "json", "active": "on"}
512+ fields = {k: v for k, v in fields.items() if k in names}
513+ admin.post(f"{R}/settings/hooks/new", fields)
514+ m = re.search(r"/settings/hooks/(\w[\w-]*)\"", admin.get(f"{R}/settings/hooks").text)
515+ seed["hook_id"] = m.group(1) if m and m.group(1) != "new" else None
516+
517+
518+@step("secret")
519+def _():
520+ admin.post(f"{R}/settings/secrets", {"name": "DEPLOY_KEY", "value": "hunter2"})
521+
522+
523+@step("final csrf refresh")
524+def _():
525+ load_csrf(admin)
526+ load_csrf(other)
527+
528+
529+seed["admin_cookies"] = admin.cookies
530+seed["admin_csrf"] = admin.csrf
531+seed["other_cookies"] = other.cookies
532+with open(os.path.join(OUT, "seed.json"), "w") as f:
533+ json.dump(seed, f, indent=2)
534+print(f"[seed] done, {len(seed['failed_steps'])} failed steps", flush=True)
scripts/audit/shoot.pyadded+635 -0
@@ -0,0 +1,635 @@
1+#!/usr/bin/env python3
2+"""Screenshots every GET page of the forge through a cookie-injecting proxy and headless Firefox.
3+
4+Usage: shoot.py FORGE_BASE OUT_DIR SRC_DIR
5+Env:
6+ AUDIT_PROXY_PORT proxy port (default 17670)
7+ AUDIT_MARIONETTE marionette port (default 28290)
8+ AUDIT_FILTER regex; only routes whose pattern or url matches are shot
9+ AUDIT_VARIANTS comma list of variants to shoot (default: all)
10+ AUDIT_MAX_HEIGHT crop full-page captures to this height (default 2400)
11+"""
12+
13+import base64
14+import http.server
15+import io
16+import json
17+import os
18+import re
19+import shutil
20+import socket
21+import socketserver
22+import subprocess
23+import sys
24+import tempfile
25+import threading
26+import time
27+import urllib.parse
28+
29+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
30+from forgeclient import Client, raw_request # noqa: E402
31+
32+FORGE = sys.argv[1].rstrip("/")
33+OUT = sys.argv[2]
34+SRC = sys.argv[3]
35+PROXY_PORT = int(os.environ.get("AUDIT_PROXY_PORT", "17670"))
36+MARIONETTE = int(os.environ.get("AUDIT_MARIONETTE", "28290"))
37+FILTER = re.compile(os.environ.get("AUDIT_FILTER", "") or ".*")
38+MAX_H = int(os.environ.get("AUDIT_MAX_HEIGHT", "2400"))
39+PROXY = f"http://127.0.0.1:{PROXY_PORT}"
40+SHOTS = os.path.join(OUT, "shots")
41+seed = json.load(open(os.path.join(OUT, "seed.json")))
42+
43+# ---------------------------------------------------------------- proxy
44+STATE = {"cookie": ""}
45+FORGE_HOST = urllib.parse.urlsplit(FORGE).netloc
46+HOP = {"connection", "keep-alive", "transfer-encoding", "te", "trailer", "upgrade",
47+ "proxy-authorization", "proxy-authenticate", "content-length"}
48+
49+
50+class ProxyHandler(http.server.BaseHTTPRequestHandler):
51+ protocol_version = "HTTP/1.0"
52+
53+ def log_message(self, *a):
54+ pass
55+
56+ def _forward(self):
57+ # Event streams never end; answering 204 stops EventSource and keeps them from starving the
58+ # browser's per-host connection pool (which stalled later navigations for a minute).
59+ if self.path.split("?")[0].endswith(("/stream", "/events")):
60+ self.send_response(204)
61+ self.end_headers()
62+ return
63+ import urllib.request
64+ import urllib.error
65+ length = int(self.headers.get("Content-Length") or 0)
66+ body = self.rfile.read(length) if length else None
67+ headers = {k: v for k, v in self.headers.items() if k.lower() not in HOP | {"host", "cookie"}}
68+ cookie = "; ".join(x for x in [STATE["cookie"], self.headers.get("Cookie", "")] if x)
69+ if cookie:
70+ headers["Cookie"] = cookie
71+ headers["Host"] = FORGE_HOST
72+ if "Origin" in headers:
73+ headers["Origin"] = FORGE
74+ req = urllib.request.Request(FORGE + self.path, data=body, method=self.command, headers=headers)
75+
76+ class NoRedir(urllib.request.HTTPRedirectHandler):
77+ def redirect_request(self, *a, **k):
78+ return None
79+ opener = urllib.request.build_opener(NoRedir)
80+ try:
81+ resp = opener.open(req, timeout=60)
82+ except urllib.error.HTTPError as e:
83+ resp = e
84+ except Exception as e:
85+ self.send_error(502, str(e))
86+ return
87+ self.send_response(resp.status if hasattr(resp, "status") else resp.code)
88+ for k, v in resp.headers.items():
89+ if k.lower() in HOP:
90+ continue
91+ if k.lower() == "location":
92+ v = v.replace(FORGE, PROXY)
93+ self.send_header(k, v)
94+ self.end_headers()
95+ try:
96+ while True:
97+ chunk = resp.read1(65536) if hasattr(resp, "read1") else resp.read(65536)
98+ if not chunk:
99+ break
100+ self.wfile.write(chunk)
101+ self.wfile.flush()
102+ except (BrokenPipeError, ConnectionResetError, socket.timeout, OSError):
103+ pass
104+
105+ do_GET = do_POST = do_HEAD = do_PUT = do_DELETE = do_PATCH = _forward
106+
107+
108+class ThreadedServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
109+ daemon_threads = True
110+ allow_reuse_address = True
111+
112+
113+# ---------------------------------------------------------------- marionette
114+class Marionette:
115+ def __init__(self, port):
116+ self.profile = tempfile.mkdtemp(prefix="forge-audit-ff-", dir=os.path.join(OUT, "tmp"))
117+ with open(os.path.join(self.profile, "user.js"), "w") as f:
118+ for k, v in {
119+ "marionette.port": port, "browser.shell.checkDefaultBrowser": False,
120+ "browser.startup.homepage_override.mstone": "ignore", "datareporting.policy.dataSubmissionEnabled": False,
121+ "toolkit.telemetry.reportingpolicy.firstRun": False, "app.update.disabledForTesting": True,
122+ "browser.aboutwelcome.enabled": False, "ui.prefersReducedMotion": 1,
123+ "layout.css.prefers-color-scheme.content-override": 1, "ui.systemUsesDarkTheme": 0,
124+ "browser.cache.disk.enable": False, "network.proxy.type": 0,
125+ "browser.sessionstore.resume_from_crash": False, "dom.disable_beforeunload": True,
126+ "layout.css.devPixelsPerPx": "1.0",
127+ }.items():
128+ f.write(f"user_pref({json.dumps(k)}, {json.dumps(v)});\n")
129+ env = dict(os.environ, MOZ_HEADLESS="1", MOZ_HEADLESS_WIDTH="1440", MOZ_HEADLESS_HEIGHT="900")
130+ self.proc = subprocess.Popen(["firefox", "--headless", "--marionette", "--remote-allow-system-access", "-no-remote", "-profile", self.profile],
131+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env)
132+ deadline = time.time() + 60
133+ while True:
134+ try:
135+ self.sock = socket.create_connection(("127.0.0.1", port), timeout=5)
136+ break
137+ except OSError:
138+ if time.time() > deadline or self.proc.poll() is not None:
139+ raise RuntimeError("marionette did not come up")
140+ time.sleep(0.3)
141+ self.sock.settimeout(120)
142+ self.buf = b""
143+ self._recv() # handshake
144+ self.msgid = 0
145+ self.cmd("WebDriver:NewSession", {"capabilities": {"alwaysMatch": {"acceptInsecureCerts": True,
146+ "pageLoadStrategy": "normal"}}})
147+ self.cmd("WebDriver:SetTimeouts", {"pageLoad": 30000, "script": 10000})
148+ # Hide the browser chrome and drop its min-width so the content viewport can be phone-narrow
149+ # and exactly the window size.
150+ self.cmd("Marionette:SetContext", {"value": "chrome"})
151+ self.cmd("WebDriver:ExecuteScript", {"script": """
152+ document.getElementById('navigator-toolbox').style.display = 'none';
153+ for (const el of document.querySelectorAll('*')) { el.style.minWidth = '0px'; }
154+ document.documentElement.style.minWidth = '0px';
155+ return 1;""", "args": []})
156+ self.cmd("Marionette:SetContext", {"value": "content"})
157+
158+ def resize(self, w, h):
159+ self.cmd("WebDriver:SetWindowRect", {"width": w, "height": h})
160+ for _ in range(2):
161+ inner = self.cmd("WebDriver:ExecuteScript",
162+ {"script": "return [window.innerWidth, window.innerHeight]", "args": []})["value"]
163+ if inner == [w, h]:
164+ return
165+ rect = self.cmd("WebDriver:GetWindowRect")
166+ self.cmd("WebDriver:SetWindowRect", {"width": rect["width"] + w - inner[0],
167+ "height": rect["height"] + h - inner[1]})
168+
169+ def _recv(self):
170+ while b":" not in self.buf:
171+ self.buf += self.sock.recv(65536)
172+ n, rest = self.buf.split(b":", 1)
173+ n = int(n)
174+ while len(rest) < n:
175+ rest += self.sock.recv(1 << 20)
176+ self.buf = rest[n:]
177+ return json.loads(rest[:n])
178+
179+ def cmd(self, name, params=None):
180+ self.msgid += 1
181+ data = json.dumps([0, self.msgid, name, params or {}]).encode()
182+ self.sock.sendall(str(len(data)).encode() + b":" + data)
183+ while True:
184+ msg = self._recv()
185+ if msg[0] == 1 and msg[1] == self.msgid:
186+ if msg[2]:
187+ raise RuntimeError(f"{name}: {msg[2].get('error')}: {msg[2].get('message', '')[:200]}")
188+ return msg[3]
189+
190+ def shoot(self, url):
191+ self.cmd("WebDriver:Navigate", {"url": url})
192+ self.cmd("WebDriver:ExecuteScript", {"script": "return document.fonts ? document.fonts.ready.then(()=>1) : 1", "args": []})
193+ return base64.b64decode(self.cmd("WebDriver:TakeScreenshot", {"full": True, "hash": False})["value"])
194+
195+ def alive(self):
196+ return self.proc.poll() is None
197+
198+ def close(self):
199+ try:
200+ self.cmd("Marionette:Quit", {"flags": ["eForceQuit"]})
201+ except Exception:
202+ pass
203+ try:
204+ self.proc.wait(10)
205+ except Exception:
206+ self.proc.kill()
207+ shutil.rmtree(self.profile, ignore_errors=True)
208+
209+
210+class Chromium:
211+ """Headless Chromium (flatpak org.chromium.Chromium by default) driven over CDP with a
212+ minimal stdlib websocket client. Exact viewport via device-metrics emulation."""
213+
214+ def __init__(self, port):
215+ self.port = port
216+ self.profile = tempfile.mkdtemp(prefix="forge-audit-cr-", dir=os.path.join(OUT, "tmp"))
217+ cmd = os.environ.get("AUDIT_CHROMIUM", "")
218+ cmd = cmd.split() if cmd else (["flatpak", "run", f"--filesystem={self.profile}", "org.chromium.Chromium"]
219+ if not shutil.which("chromium") else ["chromium"])
220+ self.proc = subprocess.Popen(cmd + ["--headless", "--no-first-run", "--no-default-browser-check",
221+ "--disable-extensions", "--hide-scrollbars", "--mute-audio",
222+ "--disable-background-networking", "--disable-sync",
223+ f"--user-data-dir={self.profile}", f"--remote-debugging-port={port}",
224+ "--remote-allow-origins=*", "about:blank"],
225+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
226+ deadline = time.time() + 60
227+ ws_url = None
228+ while not ws_url:
229+ try:
230+ tabs = json.loads(raw_request(f"http://127.0.0.1:{port}/json/list", timeout=3).body)
231+ ws_url = next((t["webSocketDebuggerUrl"] for t in tabs if t.get("type") == "page"), None)
232+ except Exception:
233+ pass
234+ if not ws_url:
235+ if time.time() > deadline or self.proc.poll() is not None:
236+ raise RuntimeError("chromium devtools did not come up")
237+ time.sleep(0.3)
238+ self._connect(ws_url)
239+ self.msgid = 0
240+ self.events = []
241+ self.cmd("Page.enable")
242+ self.cmd("Runtime.enable")
243+ self.w, self.h = 1440, 900
244+
245+ def _connect(self, ws_url):
246+ u = urllib.parse.urlsplit(ws_url)
247+ self.sock = socket.create_connection((u.hostname, u.port), timeout=120)
248+ key = base64.b64encode(os.urandom(16)).decode()
249+ self.sock.sendall((f"GET {u.path} HTTP/1.1\r\nHost: {u.netloc}\r\nUpgrade: websocket\r\n"
250+ f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n").encode())
251+ self.buf = b""
252+ while b"\r\n\r\n" not in self.buf:
253+ self.buf += self.sock.recv(4096)
254+ head, self.buf = self.buf.split(b"\r\n\r\n", 1)
255+ if b" 101 " not in head.split(b"\r\n")[0]:
256+ raise RuntimeError("websocket upgrade failed: " + head[:100].decode())
257+
258+ def _read(self, n):
259+ while len(self.buf) < n:
260+ chunk = self.sock.recv(1 << 20)
261+ if not chunk:
262+ raise RuntimeError("socket closed")
263+ self.buf += chunk
264+ out, self.buf = self.buf[:n], self.buf[n:]
265+ return out
266+
267+ def _recv_msg(self):
268+ data = b""
269+ while True:
270+ b1, b2 = self._read(2)
271+ n = b2 & 0x7F
272+ if n == 126:
273+ n = int.from_bytes(self._read(2), "big")
274+ elif n == 127:
275+ n = int.from_bytes(self._read(8), "big")
276+ payload = self._read(n)
277+ op = b1 & 0x0F
278+ if op == 8:
279+ raise RuntimeError("socket closed by browser")
280+ if op in (9, 10):
281+ continue
282+ data += payload
283+ if b1 & 0x80:
284+ return json.loads(data)
285+
286+ def _send(self, obj):
287+ data = json.dumps(obj).encode()
288+ n = len(data)
289+ hdr = bytes([0x81])
290+ if n < 126:
291+ hdr += bytes([0x80 | n])
292+ elif n < 65536:
293+ hdr += bytes([0x80 | 126]) + n.to_bytes(2, "big")
294+ else:
295+ hdr += bytes([0x80 | 127]) + n.to_bytes(8, "big")
296+ mask = os.urandom(4)
297+ self.sock.sendall(hdr + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(data)))
298+
299+ def cmd(self, method, params=None):
300+ self.msgid += 1
301+ self._send({"id": self.msgid, "method": method, "params": params or {}})
302+ while True:
303+ msg = self._recv_msg()
304+ if msg.get("id") == self.msgid:
305+ if "error" in msg:
306+ raise RuntimeError(f"{method}: {msg['error']}")
307+ return msg.get("result", {})
308+ if "method" in msg:
309+ self.events.append(msg["method"])
310+
311+ def wait_event(self, name, timeout=30):
312+ end = time.time() + timeout
313+ self.sock.settimeout(timeout)
314+ while name not in self.events:
315+ if time.time() > end:
316+ raise RuntimeError(f"timeout waiting for {name}")
317+ msg = self._recv_msg()
318+ if "method" in msg:
319+ self.events.append(msg["method"])
320+ self.sock.settimeout(120)
321+
322+ def resize(self, w, h):
323+ self.w, self.h = w, h
324+ self.cmd("Emulation.setDeviceMetricsOverride", {"width": w, "height": h, "deviceScaleFactor": 1,
325+ "mobile": w < 600})
326+ self.cmd("Emulation.setTouchEmulationEnabled", {"enabled": w < 600})
327+
328+ def evaluate(self, expr):
329+ r = self.cmd("Runtime.evaluate", {"expression": expr, "awaitPromise": True, "returnByValue": True})
330+ return r.get("result", {}).get("value")
331+
332+ def shoot(self, url):
333+ self.events = []
334+ self.cmd("Page.navigate", {"url": url})
335+ self.wait_event("Page.loadEventFired")
336+ self.evaluate("document.fonts ? document.fonts.ready.then(() => 1) : 1")
337+ self.evaluate("new Promise(r => requestAnimationFrame(() => requestAnimationFrame(() => r(1))))")
338+ height = self.evaluate("Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0)") or self.h
339+ height = max(self.h, min(int(height), MAX_H))
340+ r = self.cmd("Page.captureScreenshot", {"format": "png", "captureBeyondViewport": True,
341+ "clip": {"x": 0, "y": 0, "width": self.w, "height": height, "scale": 1}})
342+ return base64.b64decode(r["data"])
343+
344+ def alive(self):
345+ return self.proc.poll() is None
346+
347+ def close(self):
348+ try:
349+ self.cmd("Browser.close")
350+ except Exception:
351+ pass
352+ try:
353+ self.proc.wait(10)
354+ except Exception:
355+ self.proc.kill()
356+ subprocess.run(["pkill", "-f", f"[u]ser-data-dir={self.profile}"], check=False)
357+ shutil.rmtree(self.profile, ignore_errors=True)
358+
359+
360+ENGINES = [e for e in os.environ.get("AUDIT_BROWSER", "chromium").replace("both", "chromium,firefox").split(",") if e]
361+CDP_PORT = int(os.environ.get("AUDIT_CDP_PORT", "29230"))
362+
363+
364+def open_browser(engine):
365+ return Chromium(CDP_PORT) if engine == "chromium" else Marionette(MARIONETTE)
366+
367+
368+# ---------------------------------------------------------------- routes
369+def discover():
370+ pats = set()
371+ rx = re.compile(r'#\[(?:page|route)\(\s*(?:(GET|POST|PUT|PATCH|DELETE|\*)\s+)?"([^"]+)"')
372+ for root, _, files in os.walk(SRC):
373+ for fn in files:
374+ if fn.endswith(".rs"):
375+ for m in rx.finditer(open(os.path.join(root, fn), encoding="utf-8").read()):
376+ method, path = m.group(1), m.group(2)
377+ if method in (None, "GET"):
378+ pats.add(path)
379+ return sorted(pats)
380+
381+
382+SKIP_PREFIX = ("/api/", "/assets/", "/healthz", "/avatars/", "/notifications/stream")
383+SKIP_SUFFIX = ("/events", "/log.txt", "/badge.svg", "/labels.css", "/info/refs", "/info/lfs/objects/{oid}",
384+ "/archive/{*rest}", "/releases/download/{tag}/{name}", "/artifacts/{artifact_name}",
385+ "/raw/{*rest}", "/open")
386+# Pages whose GET is valid only with a one-time token; shot to see the error/expired state.
387+TOKEN_PAGES = {"/reset/{token}", "/verify/{token}"}
388+
389+
390+def concrete(pat):
391+ """Returns a list of (url, note) for a route pattern, or [] when it cannot be filled."""
392+ s = seed
393+ o, r = s["admin"], s["repo"]
394+ if pat.startswith(SKIP_PREFIX) or pat.endswith(SKIP_SUFFIX):
395+ return []
396+ repo_scoped = pat.startswith("/{owner}/{repo}")
397+ rest = pat
398+ fill = {"{owner}": o, "{repo}": r, "{org}": s["org"], "{team}": s.get("team") or "core",
399+ "{username}": o, "{token}": "expired-token-0000", "{user_id}": s.get("user_id"),
400+ "{id}": s.get("snippet_id"), "{release_id}": s.get("release_id"),
401+ "{milestone_id}": s.get("milestone_id"), "{run_number}": s.get("run_number"),
402+ "{job_id}": s.get("job_id"), "{oid}": s.get("head_oid"), "{tag}": "v0.2.0",
403+ "{wiki_page}": "Install", "{hook_id}": s.get("hook_id"), "{mirror_id}": None,
404+ "{spec}": "main...feature/heatmap"}
405+ if "/pulls/{number}" in pat:
406+ fill["{number}"] = s.get("pull_number")
407+ fill["{comment_id}"] = s.get("pull_comment_id")
408+ if "/review_comments/" in pat:
409+ fill["{comment_id}"] = s.get("review_comment_id")
410+ elif "/discussions/{number}" in pat:
411+ fill["{number}"] = s.get("discussion_number", 1)
412+ else:
413+ fill["{number}"] = 1
414+ fill["{comment_id}"] = s.get("issue_comment_id")
415+ if "/history/{kind}/{target_id}" in pat:
416+ h = s.get("issue_history") if "/issues/" in pat else s.get("pull_history")
417+ if not h:
418+ return []
419+ fill["{kind}"], fill["{target_id}"] = h
420+ out = []
421+ if pat.endswith("{*rest}"):
422+ base = pat[: -len("{*rest}")]
423+ if pat.endswith("/blob/{*rest}"):
424+ variants = [("main/src/main.rs", "rust"), ("main/README.md", "markdown"), ("main/Cargo.lock", "lock")]
425+ elif pat.endswith("/tree/{*rest}"):
426+ variants = [("main/src", ""), ("feature/heatmap", "branch")]
427+ elif pat.endswith("/commits/{*rest}"):
428+ variants = [("main", "")]
429+ else:
430+ return []
431+ for v, note in variants:
432+ out.append((base + v, note))
433+ else:
434+ out.append((pat, ""))
435+ res = []
436+ for url, note in out:
437+ for k, v in fill.items():
438+ if k in url:
439+ if v is None:
440+ url = None
441+ break
442+ url = url.replace(k, str(v))
443+ if url and "{" not in url:
444+ res.append((url, note))
445+ if repo_scoped and pat == "/{owner}/{repo}":
446+ res += [(f"/{o}/{s['private_repo']}", "private"), (f"/{s['org']}/{s['org_repo']}", "org-empty")]
447+ if pat == "/{username}":
448+ res += [(f"/{s['org']}", "org"), (f"/{o}?tab=stars", "stars"), (f"/{o}?tab=repositories", "repos")]
449+ if pat == "/{owner}/{repo}/issues":
450+ res += [(f"/{o}/{r}/issues?state=closed", "closed")]
451+ if pat == "/{owner}/{repo}/pulls/{number}":
452+ res += [(f"/{o}/{r}/pulls/{s.get('pull_number')}/commits", "")] if False else []
453+ if pat == "/{owner}/{repo}/compare":
454+ pass
455+ return res
456+
457+
458+def slugify(url, note):
459+ s = url.strip("/").replace("?", "_").replace("=", "-").replace("&", "_") or "root"
460+ s = re.sub(r"[^A-Za-z0-9._-]+", "_", s)
461+ if note:
462+ s += "--" + note
463+ return s[:150]
464+
465+
466+# ---------------------------------------------------------------- variants
467+VARIANTS = [
468+ # name, auth, theme, sidebar, width, height
469+ ("desktop-light", "user", "light", "left", 1440, 900),
470+ ("mobile-light", "user", "light", "left", 390, 844),
471+ ("desktop-dark", "user", "dark", "left", 1440, 900),
472+ ("mobile-dark", "user", "dark", "left", 390, 844),
473+ ("desktop-light-sbright", "user", "light", "right", 1440, 900),
474+]
475+
476+
477+def area_of(pat):
478+ p = pat
479+ if p.startswith(("/login", "/register", "/logout", "/reset", "/verify", "/forgot", "/two-factor", "/2fa", "/oauth")):
480+ return "auth"
481+ if p.startswith("/admin"):
482+ return "admin"
483+ if p.startswith(("/settings", "/notifications")):
484+ return "settings"
485+ if p.startswith(("/snippets", "/gists")) or "/wiki" in p:
486+ return "wiki-snippets"
487+ if p.startswith(("/orgs", "/{org}")) or p in ("/{username}", "/explore", "/search") or p.startswith("/{username}"):
488+ return "profile-orgs"
489+ if "/actions" in p or "/ci" in p or "/runs" in p or "/runners" in p or "/artifacts" in p:
490+ return "ci"
491+ if "/issues" in p or "/pulls" in p or "/discussions" in p or "/milestones" in p or "/labels" in p:
492+ return "issues-prs"
493+ if p.startswith("/{owner}/{repo}"):
494+ return "repo"
495+ return "profile-orgs"
496+
497+
498+wanted = os.environ.get("AUDIT_VARIANTS", "")
499+if wanted:
500+ keep = set(wanted.split(","))
501+ VARIANTS = [v for v in VARIANTS if v[0] in keep]
502+
503+
504+def set_prefs(theme, sidebar):
505+ c = Client(FORGE)
506+ c.cookies = dict(seed["admin_cookies"])
507+ c.csrf = seed["admin_csrf"]
508+ r = c.post("/settings/appearance", {"theme": theme, "language": "en", "sidebar_side": sidebar}, follow=False)
509+ if r.status >= 400:
510+ r = c.post("/settings/appearance", {"theme": theme, "language": "auto", "sidebar_side": sidebar}, follow=False)
511+ if r.status >= 400:
512+ print(f"[shoot] WARN appearance save -> {r.status}", flush=True)
513+
514+
515+def cookie_for(auth, theme):
516+ if auth == "user":
517+ return "; ".join(f"{k}={v}" for k, v in seed["admin_cookies"].items())
518+ return f"forge_theme={theme}"
519+
520+
521+def status_of(url):
522+ r = raw_request(PROXY + url, headers={"Accept": "text/html"})
523+ st = str(r.status)
524+ if r.status in (301, 302, 303, 307, 308):
525+ loc = r.headers.get("Location", "").replace(PROXY, "")
526+ st += " -> " + loc
527+ return r.status, st
528+
529+
530+def main():
531+ os.makedirs(SHOTS, exist_ok=True)
532+ os.makedirs(os.path.join(OUT, "tmp"), exist_ok=True)
533+ try:
534+ from PIL import Image
535+ except ImportError:
536+ Image = None
537+ srv = ThreadedServer(("127.0.0.1", PROXY_PORT), ProxyHandler)
538+ threading.Thread(target=srv.serve_forever, daemon=True).start()
539+
540+ targets = []
541+ AREAS = globals().setdefault('AREAS', {})
542+ for pat in discover():
543+ for url, note in concrete(pat):
544+ if FILTER.search(pat) or FILTER.search(url):
545+ targets.append((pat, url, slugify(url, note)))
546+ AREAS[slugify(url, note)] = area_of(pat)
547+ print(f"[shoot] {len(targets)} urls, {len(VARIANTS)} variants", flush=True)
548+
549+ rows = {} # slug -> dict
550+ for engine in ENGINES:
551+ prefix = "" if engine == "chromium" else "ff-"
552+ br = open_browser(engine)
553+ prev_prefs = None
554+ try:
555+ for vname, auth, theme, sidebar, w, h in VARIANTS:
556+ vlabel = prefix + vname
557+ if auth == "user" and (theme, sidebar) != prev_prefs:
558+ set_prefs(theme, sidebar)
559+ prev_prefs = (theme, sidebar)
560+ STATE["cookie"] = cookie_for(auth, theme)
561+ br.resize(w, h)
562+ t0, n = time.time(), 0
563+ for pat, url, slug in targets:
564+ row = rows.setdefault(slug, {"area": AREAS[slug], "pattern": pat, "url": url, "status": {}, "files": {}, "errors": {}})
565+ eff = "anon" if AREAS[slug] == "auth" else auth
566+ STATE["cookie"] = cookie_for(eff, theme)
567+ ts = time.time()
568+ code, st = status_of(url)
569+ tstat = time.time() - ts
570+ row["status"][eff] = st
571+ if eff == "anon" and code in (301, 302, 303, 307, 308) and "/login" in st:
572+ continue # private page: the logged-out state is just the login redirect
573+ fname = f"{AREAS[slug]}/{slug}-{w}-{theme}{'-sbright' if sidebar == 'right' else ''}.png"
574+ os.makedirs(os.path.join(SHOTS, AREAS[slug]), exist_ok=True)
575+ try:
576+ png = br.shoot(PROXY + url)
577+ if Image is not None:
578+ im = Image.open(io.BytesIO(png))
579+ if im.height > MAX_H:
580+ im = im.crop((0, 0, im.width, MAX_H))
581+ im.save(os.path.join(SHOTS, fname))
582+ else:
583+ open(os.path.join(SHOTS, fname), "wb").write(png)
584+ row["files"][vlabel] = fname
585+ if time.time() - ts > 8:
586+ print(f"[shoot] SLOW {url} {vlabel}: status {tstat:.0f}s total {time.time() - ts:.0f}s", flush=True)
587+ n += 1
588+ except Exception as e:
589+ row["errors"][vlabel] = str(e)[:200]
590+ print(f"[shoot] FAIL {url} {vlabel}: {e}", flush=True)
591+ if not br.alive() or "socket" in str(e).lower() or "timeout" in str(e).lower():
592+ br.close()
593+ br = open_browser(engine)
594+ br.resize(w, h)
595+ print(f"[shoot] {vlabel}: {n} shots in {time.time() - t0:.0f}s", flush=True)
596+ finally:
597+ br.close()
598+ if any(v[1] == "user" for v in VARIANTS):
599+ set_prefs("light", "left")
600+ srv.shutdown()
601+
602+ write_index(rows)
603+
604+
605+def write_index(rows):
606+ vnames = [("" if e == "chromium" else "ff-") + v[0] for e in ENGINES for v in VARIANTS]
607+ total = sum(len(r["files"]) for r in rows.values())
608+ lines = [
609+ "# Forge visual audit screenshots", "",
610+ f"Browsers: {', '.join(ENGINES)} (Chromium files have no prefix, Firefox files are `ff-*`).", "",
611+ f"Generated {time.strftime('%Y-%m-%d %H:%M:%S')}. {len(rows)} urls, {total} screenshots in `shots/`.",
612+ "Logged-in variants are user `tahinli` (instance admin). `anon-*` are logged out; private pages",
613+ "that redirect to /login are not shot logged out. Full-page captures are cropped at "
614+ f"{MAX_H}px height. Variants: " + ", ".join(f"`{v}`" for v in vnames) + ".", "",
615+ "| area | route | url | status | files |",
616+ "| --- | --- | --- | --- | --- |",
617+ ]
618+ for slug, r in sorted(rows.items(), key=lambda kv: (kv[1]["area"], kv[1]["url"])):
619+ files = " ".join(f"[{v}](shots/{f})" for v, f in r["files"].items()) or "none"
620+ if r["errors"]:
621+ files += " ERR: " + "; ".join(f"{k}: {v}" for k, v in r["errors"].items())
622+ st = f"{r['status'].get('user', '-')} / {r['status'].get('anon', '-')}"
623+ lines.append(f"| {r['area']} | `{r['pattern']}` | `{r['url']}` | {st} | {files} |")
624+ counts = {}
625+ for r in rows.values():
626+ counts[r["area"]] = counts.get(r["area"], 0) + 1
627+ lines += ["", "## Routes per area", ""] + [f"- {a}: {n}" for a, n in sorted(counts.items())]
628+ lines += ["", "## Seed", "", "Failed seed steps: " + (", ".join(seed.get("failed_steps") or []) or "none")]
629+ open(os.path.join(OUT, "index.md"), "w").write("\n".join(lines) + "\n")
630+ json.dump(rows, open(os.path.join(OUT, "index.json"), "w"), indent=1)
631+ print(f"[shoot] index: {os.path.join(OUT, 'index.md')} ({total} screenshots)", flush=True)
632+
633+
634+if __name__ == "__main__":
635+ main()
style/_dashboard.scssmodified+90 -1
@@ -25,8 +25,9 @@
2525 .sec-head {
2626 display: flex;
2727 flex-wrap: wrap;
28- align-items: baseline;
28+ align-items: center;
2929 gap: 12px;
30+ min-height: calc(var(--control-h) + 12px);
3031 margin-bottom: 4px;
3132 padding-bottom: 12px;
3233 border-bottom: 1px solid var(--border);
@@ -182,3 +183,91 @@
182183 font-weight: 600;
183184 }
184185 }
186+
187+// A repo listing (profile tabs): search, sort chips, count, rows and pager as one tight block, so
188+// the profile's section gap does not open between the count line and the list.
189+.repo-listing {
190+ display: flex;
191+ flex-direction: column;
192+ gap: 10px;
193+
194+ > .explore-search,
195+ > .explore-sort,
196+ > p {
197+ margin: 0;
198+ }
199+}
200+
201+.repo-item-head {
202+ display: flex;
203+ align-items: center;
204+ gap: 8px;
205+ min-width: 0;
206+
207+ .repo-name {
208+ min-width: 0;
209+ overflow: hidden;
210+ text-overflow: ellipsis;
211+ white-space: nowrap;
212+ }
213+
214+ .badge {
215+ flex: 0 0 auto;
216+ }
217+}
218+
219+.repo-item .repo-desc {
220+ overflow: hidden;
221+ text-overflow: ellipsis;
222+ white-space: nowrap;
223+}
224+
225+.pager-numbered {
226+ flex-wrap: wrap;
227+ gap: 4px;
228+ font-size: 13px;
229+
230+ .pager-page,
231+ .pager-step,
232+ .pager-gap {
233+ display: inline-flex;
234+ align-items: center;
235+ justify-content: center;
236+ min-width: 30px;
237+ height: 30px;
238+ padding: 0 8px;
239+ border-radius: var(--radius-full);
240+ color: var(--text-2);
241+ text-decoration: none;
242+ }
243+
244+ a:hover {
245+ background: var(--surface-2);
246+ text-decoration: none;
247+ }
248+
249+ .current {
250+ background: var(--accent-soft);
251+ color: var(--accent-ink);
252+ font-weight: 600;
253+ }
254+
255+ .pager-gap {
256+ min-width: 20px;
257+ padding: 0;
258+ }
259+}
260+
261+// Organization pages: the name and description stack; the section links are in the shell sidebar.
262+.org-head {
263+ .org-head-text {
264+ display: grid;
265+ gap: 4px;
266+ min-width: 0;
267+ }
268+
269+ h1,
270+ p {
271+ margin: 0;
272+ }
273+}
style/_heatmap.scssmodified+45 -1
@@ -2,7 +2,14 @@
22 //
33 // The contribution card on the dashboard (views/heatmap.rs). Cells are squares with a 3px gap;
44 // the grid lays out seven rows and fills columns, so a week is one column. Colours come from the
5-// --h0..--h4 tokens, so both themes follow main.scss.
5+// --h0..--h4 tokens below, mixed from the base's surface and the accent, so every accent, base
6+// and theme gets the same scale.
7+//
8+// Level 0 is "nothing": a neutral tint of the surface (a few percent of --text), no accent hue.
9+// Levels 1-4 are the accent mixed into the surface at even steps in oklab. Light ends on
10+// --accent-ink (the darker accent) and dark on --accent (the brighter one), so the strong end
11+// moves away from the surface in both themes. The steps are chosen so L0 to L1 is at least about
12+// 1.65:1 contrast for every base and accent.
613 //
714 // The cell size follows the card: 53 columns fill the card's width, between 11px (then the grid
815 // scrolls inside the card) and 16px. The card is a size container, so 100cqi is its width.
@@ -11,6 +18,14 @@ $cell: var(--cell);
1118 $gap: 3px;
1219
1320 .heat {
21+ --heat-end: var(--accent-ink);
22+ --h0: color-mix(in oklab, var(--text) 5%, var(--surface));
23+ --h1: color-mix(in oklab, var(--heat-end) 40%, var(--surface));
24+ --h2: color-mix(in oklab, var(--heat-end) 60%, var(--surface));
25+ --h3: color-mix(in oklab, var(--heat-end) 80%, var(--surface));
26+ --h4: var(--heat-end);
27+ --h0-edge: color-mix(in oklab, var(--text) 9%, transparent);
28+
1429 container-type: inline-size;
1530 --cell: 11px; // the legend squares; the grid overrides it in .heat-scroll
1631 margin-top: 16px;
@@ -25,6 +40,26 @@ $gap: 3px;
2540 }
2641 }
2742
43+// Dark: L0 is a slightly raised surface and the levels brighten towards --accent.
44+@mixin heat-dark {
45+ --heat-end: var(--accent);
46+ --h0: color-mix(in oklab, var(--text) 7%, var(--surface));
47+ --h1: color-mix(in oklab, var(--heat-end) 35%, var(--surface));
48+ --h2: color-mix(in oklab, var(--heat-end) 55%, var(--surface));
49+ --h3: color-mix(in oklab, var(--heat-end) 75%, var(--surface));
50+ --h0-edge: color-mix(in oklab, var(--text) 7%, transparent);
51+}
52+
53+@media (prefers-color-scheme: dark) {
54+ :root:not([data-theme="light"]) .heat {
55+ @include heat-dark;
56+ }
57+}
58+
59+:root[data-theme="dark"] .heat {
60+ @include heat-dark;
61+}
62+
2863 .heat-head {
2964 display: flex;
3065 flex-wrap: wrap;
@@ -71,6 +106,11 @@ $gap: 3px;
71106 overflow-x: auto;
72107 padding: 4px 2px 12px;
73108 max-width: 100%;
109+
110+ // row-reverse starts the scroll at the right edge, so the newest weeks (today) are in view on
111+ // phones; the auto margin on the grid keeps it at the left when it fits.
112+ display: flex;
113+ flex-direction: row-reverse;
74114 }
75115
76116 .heat-body {
@@ -78,6 +118,8 @@ $gap: 3px;
78118 grid-template-columns: 32px max-content;
79119 column-gap: 8px;
80120 width: max-content;
121+ flex: none;
122+ margin-right: auto;
81123 }
82124
83125 .heat-days {
@@ -127,6 +169,8 @@ $gap: 3px;
127169
128170 .l0 {
129171 background: var(--h0);
172+ // A hairline so empty days still read as cells.
173+ box-shadow: inset 0 0 0 1px var(--h0-edge);
130174 }
131175
132176 .l1 {
style/_pull.scssmodified+104 -0
@@ -689,3 +689,107 @@
689689 padding-right: 14px;
690690 }
691691 }
692+
693+// Issue sidebar label checklist: box and chip on one left-aligned row.
694+.issue-side-section .issue-check {
695+ flex-direction: row;
696+ align-items: center;
697+ justify-content: flex-start;
698+ gap: 8px;
699+ margin: 0 0 8px;
700+ font-weight: 400;
701+
702+ input[type="checkbox"] {
703+ width: auto;
704+ margin: 0;
705+ flex: none;
706+ }
707+}
708+
709+// New issue label picker: the inline-form rule would otherwise flatten the row.
710+.label-picker label {
711+ display: flex;
712+}
713+
714+// Labels page: Edit disclosure and Delete share a centre line; the colour well is a small swatch.
715+.label-actions {
716+ align-items: center;
717+}
718+
719+input[type="color"] {
720+ width: 56px;
721+ height: var(--control-h, 36px);
722+ padding: 3px;
723+ box-sizing: border-box;
724+ border: 1px solid var(--border-strong);
725+ border-radius: var(--radius-md);
726+ background: var(--surface);
727+ cursor: pointer;
728+}
729+
730+// Milestone progress bar: a rounded track with an accent fill.
731+.milestone-progress progress {
732+ appearance: none;
733+ border: 0;
734+ border-radius: var(--radius-full);
735+ background: var(--surface-2);
736+ overflow: hidden;
737+
738+ &::-webkit-progress-bar {
739+ background: var(--border);
740+ border-radius: var(--radius-full);
741+ }
742+
743+ &::-webkit-progress-value {
744+ background: var(--accent);
745+ border-radius: var(--radius-full);
746+ }
747+
748+ &::-moz-progress-bar {
749+ background: var(--accent);
750+ border-radius: var(--radius-full);
751+ }
752+}
753+
754+// Discussions: category chip and the action bar under a post.
755+.discussion-category {
756+ display: inline-flex;
757+ align-items: center;
758+ padding: 2px 10px;
759+ border: 1px solid var(--border);
760+ border-radius: var(--radius-full);
761+ background: var(--surface-2);
762+ color: var(--text);
763+ font-size: 12.5px;
764+ font-weight: 600;
765+}
766+
767+.discussion-actions {
768+ display: flex;
769+ flex-wrap: wrap;
770+ align-items: flex-start;
771+ gap: 4px 16px;
772+ padding: 0 16px 14px;
773+
774+ form {
775+ margin: 0;
776+ }
777+
778+ summary {
779+ cursor: pointer;
780+ color: var(--accent-ink);
781+ }
782+
783+ .discussion-reply {
784+ margin-right: 0;
785+ }
786+
787+ .link-button {
788+ color: var(--accent-ink);
789+ }
790+}
791+
792+// Edit and new forms share one card width.
793+.issue-edit {
794+ max-width: 60rem;
795+}
style/_repo.scssmodified+175 -2
@@ -443,7 +443,7 @@
443443
444444 a {
445445 margin-bottom: -1px;
446- padding: 8px 2px 10px;
446+ padding: 8px 0 10px;
447447 font-size: 14px;
448448 color: var(--muted);
449449 text-decoration: none;
@@ -587,6 +587,15 @@
587587 margin: 0;
588588 padding: 0;
589589 border: 0;
590+
591+ // Same height as the Create button beside it.
592+ .segmented {
593+ height: var(--control-h);
594+ }
595+
596+ .segment > span {
597+ height: calc(var(--control-h) - 6px);
598+ }
590599 }
591600
592601 // The card and the mirror section share one surface.
@@ -646,7 +655,9 @@
646655
647656 .newrepo-labels {
648657 align-self: flex-end;
649- min-height: 38px;
658+ align-items: center;
659+ min-height: var(--control-h);
660+ margin: 0;
650661 }
651662 }
652663
@@ -739,3 +750,165 @@
739750 padding: 16px;
740751 }
741752 }
753+
754+// Audit fixes: repo tab icons sit on the text baseline, listing tables end flush with their
755+// container, and release cards keep their markdown headings in proportion.
756+.repo-tabs .tab {
757+ display: inline-flex;
758+ align-items: center;
759+ gap: 8px;
760+
761+ .tab-icon {
762+ display: inline-flex;
763+ flex: none;
764+ align-items: center;
765+ margin: 0;
766+ }
767+}
768+
769+.tree-table,
770+.refs-table {
771+ th.age,
772+ td.age {
773+ padding-right: 0;
774+ }
775+}
776+
777+.latest-release {
778+ display: flex;
779+ flex-direction: column;
780+ gap: 8px;
781+
782+ h2,
783+ p {
784+ margin: 0;
785+ }
786+}
787+
788+.release-card {
789+ .markdown-body {
790+ margin: 8px 0;
791+
792+ h1,
793+ h2,
794+ h3 {
795+ font-size: 1rem;
796+ margin: 16px 0 8px;
797+ padding-bottom: 0;
798+ border-bottom: 0;
799+ }
800+
801+ > :first-child {
802+ margin-top: 0;
803+ }
804+ }
805+
806+ h3 {
807+ display: flex;
808+ align-items: center;
809+ flex-wrap: wrap;
810+ gap: 8px;
811+ margin: 0 0 6px;
812+ }
813+
814+ > p {
815+ margin: 6px 0;
816+ }
817+}
818+
819+// Form stacks: help text sits right under its field (the stack gap already spaces blocks), and
820+// headings keep a steady distance from the first field.
821+.stack > p {
822+ margin: 0;
823+}
824+
825+.stack > .muted.small {
826+ margin-top: -6px;
827+}
828+
829+.card > h2 + .stack,
830+.card > h2 + form {
831+ margin-top: 12px;
832+}
833+
834+.table.collaborators .inline-form {
835+ display: flex;
836+ align-items: center;
837+ gap: 8px;
838+
839+ select {
840+ width: auto;
841+ min-width: 7rem;
842+ }
843+}
844+
845+// Cards: no doubled space from the first and last paragraph margins; the commit info card
846+// spaces its rows evenly.
847+.card > :first-child {
848+ margin-top: 0;
849+}
850+
851+.card > :last-child {
852+ margin-bottom: 0;
853+}
854+
855+.commit-info {
856+ display: flex;
857+ flex-direction: column;
858+ gap: 8px;
859+
860+ > p,
861+ > details {
862+ margin: 0;
863+ }
864+}
865+
866+// Settings forms: every field in a form shares the form width (urls and secrets no longer stop short).
867+.mirror-form,
868+.webhook-form {
869+ input[type="url"],
870+ input[type="password"] {
871+ max-width: 100%;
872+ }
873+}
874+
875+// Code search options: fields and checkboxes share one bottom line and the control height.
876+.search-options {
877+ align-items: flex-end;
878+ gap: 8px 16px;
879+
880+ label:has(> input[type="checkbox"]) {
881+ align-items: center;
882+ height: var(--control-h);
883+ }
884+
885+ label > input[type="checkbox"] {
886+ margin-top: 0;
887+ }
888+}
889+
890+// Release page: markdown headings in a release body stay in proportion, destructive confirm
891+// rows keep a steady gap.
892+.release-actions {
893+ gap: 12px 16px;
894+}
895+
896+.release-body {
897+ h1,
898+ h2 {
899+ font-size: 1.125rem;
900+ }
901+}
902+
903+.release-actions .inline-form {
904+ display: flex;
905+ align-items: center;
906+ gap: 12px;
907+}
908+
909+@media (max-width: 600px) {
910+ .commit-actions {
911+ margin-left: 0;
912+ flex-basis: 100%;
913+ }
914+}
style/_wiki.scssadded+102 -0
@@ -0,0 +1,102 @@
1+// Wiki: the shared header (title plus the Home / All pages / page links button row, with
2+// "New page" as the primary action at the far right) and the page cards below it.
3+
4+.wiki-head {
5+ align-items: center;
6+}
7+
8+.wiki-head h1 {
9+ font-size: 1.5rem;
10+ margin: 0;
11+ min-width: 0;
12+ overflow-wrap: anywhere;
13+}
14+
15+.wiki-actions {
16+ display: flex;
17+ flex-wrap: wrap;
18+ align-items: center;
19+ gap: 8px;
20+ margin-left: auto;
21+}
22+
23+.wiki-page .markdown-body > :first-child {
24+ margin-top: 0;
25+}
26+
27+.wiki-pages .item a {
28+ font-weight: 500;
29+}
30+
31+.wiki-form textarea {
32+ font-family: var(--mono);
33+ min-height: 24rem;
34+}
35+
36+// A list that fills a card: the card's own padding frames it, so the first and last rows add none.
37+.card > .item-list > .item:first-child {
38+ padding-top: 0;
39+}
40+
41+.card > .item-list > .item:last-child {
42+ padding-bottom: 0;
43+}
44+
45+// Phones: a history row is too wide for one line, so it stacks (subject first, then hash, author
46+// and time) instead of scrolling sideways.
47+@media (max-width: 639px) {
48+ .wiki-history tr {
49+ display: flex;
50+ flex-wrap: wrap;
51+ align-items: baseline;
52+ gap: 2px 12px;
53+ padding: 12px 0;
54+ border-bottom: 1px solid var(--border);
55+ }
56+
57+ .wiki-history tr:first-child {
58+ padding-top: 0;
59+ }
60+
61+ .wiki-history tr:last-child {
62+ padding-bottom: 0;
63+ border-bottom: 0;
64+ }
65+
66+ .wiki-history td {
67+ padding: 0;
68+ border: 0;
69+ }
70+
71+ .wiki-history td:nth-child(2) {
72+ order: -1;
73+ flex: 1 1 100%;
74+ }
75+}
76+
77+// The 404 page: a centred message inside the regular shell.
78+.not-found {
79+ display: flex;
80+ flex-direction: column;
81+ align-items: center;
82+ gap: 8px;
83+ padding: 64px 0;
84+ text-align: center;
85+
86+ h1,
87+ p {
88+ margin: 0;
89+ }
90+
91+ .not-found-code {
92+ font-size: 3rem;
93+ font-weight: 700;
94+ line-height: 1;
95+ color: var(--accent);
96+ }
97+
98+ .button {
99+ align-self: center;
100+ margin-top: 12px;
101+ }
102+}
style/main.scssmodified+461 -21
@@ -455,6 +455,36 @@ label {
455455 }
456456 }
457457
458+// A label wrapping a checkbox or radio is a row: box first, then the text, the box centred on the
459+// first line (20px line, 16px box, 2px top margin below) and long text wrapping beside it. A
460+// <small> helper right after the label starts under the text, not under the box. Only plain,
461+// `.inline` and `.checkbox` labels take this; the classed pickers, segments and tabs lay out their
462+// own labels. :where() keeps it at plain `label` specificity, so container rules (label pickers,
463+// review bar) still win.
464+$check-indent: 16px + 8px;
465+$check-label: 'label:where(:not([class]), .inline, .checkbox):where(:has(> input[type="checkbox"], > input[type="radio"]))';
466+
467+#{$check-label} {
468+ flex-direction: row;
469+ align-items: flex-start;
470+ gap: 8px;
471+ line-height: 20px;
472+ cursor: pointer;
473+
474+ &.inline {
475+ align-items: flex-start;
476+ }
477+
478+ > span {
479+ min-width: 0;
480+ }
481+
482+ + small {
483+ display: block;
484+ margin-left: $check-indent;
485+ }
486+}
487+
458488 input,
459489 select,
460490 textarea {
@@ -496,6 +526,12 @@ input[type="checkbox"] {
496526 box-shadow: none;
497527 }
498528
529+// The box sits 2px down so it centres on a 20px first line of a checkbox label (see above).
530+#{$check-label} > input[type="checkbox"],
531+#{$check-label} > input[type="radio"] {
532+ margin-top: 2px;
533+}
534+
499535 // Native dropdown lists take their colours from the option rule where the browser honours it;
500536 // color-scheme (set on :root above) covers the rest.
501537 // One box for every select: same height, padding and font wherever it sits.
@@ -529,6 +565,13 @@ select optgroup {
529565 appearance: base-select;
530566 }
531567
568+ // base-select lays the select out as a flex row (selected text + ::picker-icon) whose items
569+ // default to the top of the fixed-height box; centre them like a button.
570+ select:not([multiple]):not([size]) {
571+ align-items: center;
572+ padding-block: 0;
573+ }
574+
532575 select:not([multiple]):not([size])::picker-icon {
533576 color: var(--muted);
534577 transition: rotate 0.2s ease;
@@ -748,6 +791,10 @@ code {
748791 gap: 2px;
749792 min-width: 0;
750793 word-break: break-word;
794+
795+ > .badge {
796+ align-self: flex-start;
797+ }
751798 }
752799 }
753800
@@ -780,6 +827,79 @@ code {
780827 font-size: 0.78125rem;
781828 color: var(--muted);
782829 font-weight: 500;
830+ white-space: nowrap;
831+ }
832+
833+ // Code chips (identifiers, action names, hashes) and marked cells stay on one line; a table
834+ // too wide for the screen scrolls inside .table-wrap instead of breaking words.
835+ td code {
836+ white-space: nowrap;
837+ word-break: normal;
838+ }
839+
840+ td.nowrap {
841+ white-space: nowrap;
842+ }
843+}
844+
845+// Audit log: the details column takes the slack, the rest size to their content.
846+.audit-table td:last-child {
847+ min-width: 14rem;
848+ overflow-wrap: anywhere;
849+}
850+
851+.audit-table td:nth-last-child(3) {
852+ white-space: nowrap;
853+}
854+
855+// Filter bar: labelled fields and the submit button on one line, bottom-aligned, wrapping on
856+// narrow screens.
857+.filter-bar {
858+ display: flex;
859+ flex-wrap: wrap;
860+ align-items: flex-end;
861+ gap: 12px;
862+
863+ > label {
864+ flex: 0 1 auto;
865+ min-width: 0;
866+ }
867+
868+ > button,
869+ > .button {
870+ align-self: flex-end;
871+ }
872+
873+ .filter-action select {
874+ width: 18rem;
875+ }
876+
877+ .filter-actor input {
878+ width: 14rem;
879+ }
880+}
881+
882+@media (max-width: 600px) {
883+ .filter-bar > label {
884+ flex: 1 1 100%;
885+
886+ }
887+
888+ .filter-bar .filter-action select,
889+ .filter-bar .filter-actor input {
890+ width: 100%;
891+ max-width: none;
892+ }
893+}
894+
895+@media (max-width: 600px) {
896+ .filter-bar > label {
897+ flex: 1 1 100%;
898+
899+ select,
900+ input {
901+ width: 100%;
902+ }
783903 }
784904 }
785905
@@ -833,7 +953,7 @@ code {
833953 .search-options label {
834954 display: inline-flex;
835955 gap: 4px;
836- align-items: center;
956+ align-items: flex-start;
837957 }
838958
839959 .search-file {
@@ -1497,6 +1617,44 @@ code {
14971617 }
14981618 }
14991619
1620+// Settings > Notifications: the checkbox with its helper, then the notes saying why it is locked.
1621+// One 12px rhythm between the field, each note and the no-JS actions; helper text and notes share
1622+// one size.
1623+.notify-form {
1624+ display: flex;
1625+ flex-direction: column;
1626+ gap: 12px;
1627+
1628+ .check-field {
1629+ display: flex;
1630+ flex-direction: column;
1631+ gap: 2px;
1632+ }
1633+
1634+ small,
1635+ .notice {
1636+ font-size: 0.8125rem;
1637+ line-height: 1.45;
1638+ }
1639+
1640+ .notice {
1641+ margin: 0;
1642+ padding: 8px 12px;
1643+ }
1644+
1645+ .actions {
1646+ margin-top: 0;
1647+ }
1648+
1649+ label:has(> input:disabled) {
1650+ cursor: default;
1651+
1652+ > span {
1653+ color: var(--muted);
1654+ }
1655+ }
1656+}
1657+
15001658 // Commit diffs (rendered by the commit page). Each file: .diff-file > .diff-file-header,
15011659 // then .diff-file-body > table.diff-table with rows .diff-line.{add,del,ctx,hunk}, cells
15021660 // .diff-ln (line numbers) and .diff-code. Long lines scroll inside .diff-file-body.
@@ -1670,6 +1828,14 @@ code {
16701828 border: 1px solid var(--border);
16711829 border-radius: var(--radius-lg);
16721830 overflow-wrap: anywhere;
1831+
1832+ > :first-child {
1833+ margin-top: 0;
1834+ }
1835+
1836+ > :last-child {
1837+ margin-bottom: 0;
1838+ }
16731839 }
16741840
16751841 .profile-repos {
@@ -1864,38 +2030,78 @@ code {
18642030 }
18652031
18662032 .appearance-top {
2033+ // Theme and Language share the width; the sidebar toggle takes its own width. Rows size to their
2034+ // content, so the helper text under a select is never clipped.
18672035 display: grid;
1868- grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr));
2036+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto;
2037+ grid-auto-rows: auto;
18692038 align-items: start;
18702039 gap: 16px 24px;
2040+ min-width: 0;
2041+ height: auto;
2042+ overflow: visible;
2043+
2044+ @media (max-width: 720px) {
2045+ grid-template-columns: minmax(0, 1fr);
2046+ }
18712047
2048+ // Each field: label row, control row, then optional helper text. The label rows are all the
2049+ // same height, so the three labels share a baseline and the three controls sit on one line.
18722050 > label,
18732051 > fieldset {
18742052 display: grid;
2053+ grid-template-rows: auto var(--control-h) auto;
18752054 gap: 4px;
18762055 min-width: 0;
1877- // Helper text sits in a row of its own below, so it never moves the control.
2056+ height: auto;
2057+ overflow: visible;
18782058 align-content: start;
18792059 }
2060+
2061+ > label > span,
2062+ > fieldset > legend {
2063+ line-height: 1.25rem;
2064+ }
2065+
2066+ > label > small {
2067+ display: block;
2068+ font-size: 0.8125rem;
2069+ line-height: 1.45;
2070+ overflow-wrap: anywhere;
2071+ }
18802072 }
18812073
1882-// The sidebar side (appearance settings): a segmented toggle, styled like the snippet switch.
2074+// The sidebar side (appearance settings): the same segmented pill as the New repository
2075+// visibility toggle (.segmented.snippet-segmented), sized to --control-h like the selects.
18832076 .side-picker {
18842077 border: 0;
18852078 padding: 0;
18862079 margin: 0;
18872080 justify-items: start;
18882081
2082+ // A floated legend is laid out as a normal grid item, so it lines up with the other labels.
18892083 legend {
2084+ float: left;
18902085 padding: 0;
1891- margin-bottom: 4px;
2086+ margin: 0;
18922087 font-weight: 500;
18932088 font-size: 0.875rem;
18942089 color: var(--text-2);
18952090 }
18962091
18972092 .segmented {
1898- min-height: 2.5rem;
2093+ height: var(--control-h);
2094+ min-height: 0;
2095+ border-radius: var(--radius-full);
2096+
2097+ // Text-only segments: keep the words on phones too (the shared rule hides them for icons).
2098+ .segment > span {
2099+ width: auto;
2100+ height: calc(var(--control-h) - 6px);
2101+ padding: 0 12px;
2102+ font-size: 0.8125rem;
2103+ line-height: 1;
2104+ }
18992105 }
19002106 }
19012107
@@ -1912,13 +2118,17 @@ code {
19122118
19132119 .colour-group {
19142120 display: grid;
2121+ align-content: start;
19152122 gap: 14px;
19162123 min-width: 0;
19172124 margin: 0;
19182125
1919- legend {
2126+ // Floated, the legend is a normal grid item inside the card instead of sitting on its border.
2127+ > legend {
2128+ float: left;
2129+ width: 100%;
19202130 padding: 0;
1921- margin-bottom: 4px;
2131+ margin: 0;
19222132 font-weight: 600;
19232133 }
19242134 }
@@ -1932,8 +2142,10 @@ code {
19322142 border: 0;
19332143
19342144 legend {
2145+ float: left;
2146+ width: 100%;
19352147 padding: 0;
1936- margin-bottom: 2px;
2148+ margin: 0;
19372149 font-size: 0.875rem;
19382150 color: var(--muted);
19392151 }
@@ -1966,9 +2178,10 @@ code {
19662178 outline-offset: 3px;
19672179 }
19682180
2181+ // The selection ring is drawn inside the swatch, so every swatch keeps the same size.
19692182 input:checked + .accent-swatch,
19702183 input:checked + .base-swatch {
1971- box-shadow: 0 0 0 2px var(--surface), 0 0 0 4px var(--focus);
2184+ box-shadow: inset 0 0 0 2px var(--focus), inset 0 0 0 4px var(--surface);
19722185 }
19732186 }
19742187
@@ -2143,14 +2356,33 @@ code {
21432356 margin: 12px 0;
21442357 }
21452358
2359+// Filter chips reuse .subnav-link for the soft-nav hook, but they are pills:
2360+// one indicator only (the filled pill), never the underline-tab ::after bar.
21462361 .mail-filters .subnav-link {
2147- padding: 4px 10px;
2362+ display: inline-flex;
2363+ align-items: center;
2364+ gap: 6px;
2365+ height: 28px;
2366+ padding: 0 12px;
21482367 border: 1px solid var(--border);
21492368 border-radius: var(--radius-full);
2150-}
2369+ color: var(--text-2);
2370+ white-space: nowrap;
21512371
2152-.mail-filters .subnav-link.current {
2153- border-color: var(--accent);
2372+ &:hover {
2373+ background: var(--surface-2);
2374+ text-decoration: none;
2375+ }
2376+
2377+ &.current {
2378+ border-color: transparent;
2379+ background: var(--accent-soft);
2380+ color: var(--accent-ink);
2381+
2382+ &::after {
2383+ content: none;
2384+ }
2385+ }
21542386 }
21552387
21562388 .mail-queue .mail-actions {
@@ -3537,6 +3769,11 @@ span.reaction {
35373769 flex-direction: column;
35383770 align-items: flex-start;
35393771 }
3772+
3773+ // The 18rem basis is a width in a row; in a column it would be a height.
3774+ .notif-title {
3775+ flex: 0 1 auto;
3776+ }
35403777 }
35413778
35423779 // Signed commit badges: on the commit list and the commit page.
@@ -3604,16 +3841,35 @@ span.reaction {
36043841 }
36053842
36063843 .release-assets td code {
3844+ white-space: normal;
36073845 word-break: break-all;
36083846 }
36093847
3848+.release-assets td:nth-child(2) {
3849+ white-space: nowrap;
3850+}
3851+
3852+.release-assets td:nth-child(4) {
3853+ width: 15rem;
3854+ min-width: 10rem;
3855+}
3856+
36103857 .release-assets .asset-actions {
36113858 white-space: nowrap;
3859+ min-width: 25rem;
36123860 }
36133861
3614-.release-assets .replace-form input[type="file"] {
3615- max-width: 180px;
3862+.release-assets .replace-form {
3863+ display: inline-flex;
3864+ flex-wrap: nowrap;
3865+ align-items: center;
3866+ gap: 6px;
36163867 vertical-align: middle;
3868+ margin-right: 6px;
3869+
3870+ input[type="file"] {
3871+ max-width: 100%;
3872+ }
36173873 }
36183874
36193875 .badge.latest {
@@ -3702,6 +3958,75 @@ span.reaction {
37023958 padding-left: 20px;
37033959 }
37043960
3961+// Admin runners table: name and labels take the slack, the rest size to their content, and the
3962+// actions sit flush right. State reuses the `.ci-state` pill; a disabled runner is muted.
3963+.table.runners {
3964+ th.runner-seen,
3965+ th.runner-state,
3966+ td.runner-seen,
3967+ td.runner-state {
3968+ width: 1%;
3969+ white-space: nowrap;
3970+ }
3971+
3972+ th.runner-actions,
3973+ td.runner-actions {
3974+ width: 1%;
3975+ padding-right: 0;
3976+ text-align: right;
3977+ white-space: nowrap;
3978+ }
3979+
3980+ td.runner-labels {
3981+ width: 50%;
3982+ }
3983+
3984+ // A name is never broken mid-word; a narrow screen scrolls the table inside .table-wrap.
3985+ td.runner-name {
3986+ white-space: nowrap;
3987+ }
3988+}
3989+
3990+.runner-label-list {
3991+ display: flex;
3992+ flex-wrap: wrap;
3993+ gap: 4px;
3994+}
3995+
3996+.runner-label {
3997+ display: inline-block;
3998+ padding: 0 8px;
3999+ border: 1px solid var(--border);
4000+ border-radius: var(--radius-full);
4001+ background: var(--code-bg);
4002+ font-family: var(--mono);
4003+ font-size: 0.75rem;
4004+ line-height: 20px;
4005+ white-space: nowrap;
4006+}
4007+
4008+.ci-state.runner-disabled {
4009+ background: var(--code-bg);
4010+ color: var(--muted);
4011+}
4012+
4013+.runner-action-row {
4014+ display: flex;
4015+ justify-content: flex-end;
4016+ align-items: center;
4017+ gap: 8px;
4018+
4019+ form {
4020+ display: flex;
4021+ margin: 0;
4022+ }
4023+
4024+ button {
4025+ height: var(--control-h);
4026+ margin: 0;
4027+ }
4028+}
4029+
37054030 // CI: runs list and run detail. The split view has the runs on the left and the selected run on the
37064031 // right. Bars and the timeline are SVG, so their sizes are in viewBox units and need no inline style.
37074032 // The timeline sizes match the constants in crates/forge-web/src/pages/ci_runs.rs.
@@ -4033,14 +4358,75 @@ span.reaction {
40334358 fill: var(--muted);
40344359 }
40354360
4361+// Dependency connectors: an elbow from a needed job's end into the start of the job that needs it,
4362+// muted, or in the accent when the needed job failed or still runs. Pieces are nested SVGs placed at
4363+// an x the ticker moves like a running box's edge, so they follow the clock without new math.
40364364 .ci-glink {
4365+ color: var(--muted);
4366+ pointer-events: none;
4367+ transition: opacity 0.12s ease;
4368+
4369+ &.ci-hot {
4370+ color: var(--accent);
4371+ }
4372+}
4373+
4374+.ci-gline {
40374375 fill: none;
4038- stroke: var(--muted);
4039- stroke-width: 1;
4040- stroke-dasharray: 3 3;
4376+ stroke: currentColor;
4377+ stroke-width: 1.25;
4378+ stroke-linejoin: round;
40414379 vector-effect: non-scaling-stroke;
40424380 }
40434381
4382+.ci-ghead,
4383+.ci-glink-run {
4384+ fill: currentColor;
4385+}
4386+
4387+.ci-gedge,
4388+.ci-gon,
4389+.ci-goff {
4390+ pointer-events: none;
4391+}
4392+
4393+.ci-gbar,
4394+.ci-glead {
4395+ transition: opacity 0.12s ease;
4396+}
4397+
4398+// Hovering a job's box lights its connectors and the jobs it is linked with, and fades the rest.
4399+// Each box carries its row (data-j) and the rows linked with it (data-rel).
4400+.ci-gantt:has([data-j]:hover) {
4401+ .ci-glink,
4402+ .ci-gbar,
4403+ .ci-glead {
4404+ opacity: 0.35;
4405+ }
4406+}
4407+
4408+@for $i from 0 through 63 {
4409+ .ci-gantt:has([data-j="#{$i}"]:hover) [data-rel~="j#{$i}"] {
4410+ opacity: 1;
4411+
4412+ &.ci-glink:not(.ci-hot) {
4413+ color: var(--text-2);
4414+ }
4415+
4416+ .ci-gline {
4417+ stroke-width: 2;
4418+ }
4419+ }
4420+}
4421+
4422+@media (prefers-reduced-motion: reduce) {
4423+ .ci-glink,
4424+ .ci-gbar,
4425+ .ci-glead {
4426+ transition: none;
4427+ }
4428+}
4429+
40444430 @keyframes ci-breathe {
40454431 50% {
40464432 opacity: 0.55;
@@ -4207,15 +4593,32 @@ span.reaction {
42074593 variables apply under :root:not([data-theme="light"]) and under :root[data-theme="dark"]. */
42084594 .theme-picker {
42094595 display: inline-flex;
4596+ flex-direction: row;
42104597 align-items: center;
42114598 gap: 8px;
4212- margin-left: auto;
4599+ margin: 0 0 0 auto;
42134600 }
42144601
42154602 .theme-picker label {
42164603 display: inline-flex;
4604+ flex-direction: row;
42174605 align-items: center;
4218- gap: 6px;
4606+ gap: 8px;
4607+ margin: 0;
4608+
4609+ select {
4610+ width: auto;
4611+ height: var(--control-h);
4612+ margin: 0;
4613+ }
4614+}
4615+
4616+.theme-picker .link-button {
4617+ align-self: center;
4618+ margin: 0;
4619+ line-height: var(--control-h);
4620+ height: var(--control-h);
4621+ padding-block: 0;
42194622 }
42204623
42214624 .theme-picker label span {
@@ -4710,6 +5113,21 @@ span.reaction {
47105113 color: var(--muted);
47115114 }
47125115
5116+.snippet-view-head {
5117+ align-items: baseline;
5118+}
5119+
5120+.snippet-actions {
5121+ display: flex;
5122+ flex-wrap: wrap;
5123+ align-items: center;
5124+ gap: 8px;
5125+
5126+ .inline-form {
5127+ display: flex;
5128+ }
5129+}
5130+
47135131 .snippet-file {
47145132 margin-top: 16px;
47155133 }
@@ -4759,6 +5177,7 @@ span.reaction {
47595177 @import "repo";
47605178 @import "pull";
47615179 @import "dashboard";
5180+@import "wiki";
47625181
47635182 // Code inside cards, notices and settings panels must stay inside the card. Long tokens and
47645183 // commands wrap instead of running past the right edge. The rendered README card (.readme) and
@@ -5221,9 +5640,15 @@ span.reaction {
52215640
52225641 @media (max-width: 600px) {
52235642 .security-row {
5643+ align-items: flex-start;
52245644 padding: 14px 16px;
52255645 }
52265646
5647+ // The icon sits on the title's first line (20px box, 1.4 line of 15px) instead of mid-row.
5648+ .security-row > .security-icon {
5649+ margin-top: 0.5px;
5650+ }
5651+
52275652 .security-devices {
52285653 padding: 0 16px 14px 16px;
52295654 }
@@ -5236,3 +5661,18 @@ span.reaction {
52365661 padding-left: 0;
52375662 }
52385663 }
5664+
5665+// Forms under a team card: a control and its button in one row, set off from what is above.
5666+.team-form {
5667+ display: flex;
5668+ flex-wrap: wrap;
5669+ align-items: center;
5670+ gap: 8px;
5671+ margin-top: 12px;
5672+
5673+ input[type="text"],
5674+ select {
5675+ flex: 1 1 12rem;
5676+ min-width: 0;
5677+ }
5678+}