git clone https://garage44.eu/jeroen/midas.gitcartopolis-agent · 2026-11-28T16:36:38Z
feat(tree): a project's page from the Map, and which session started which Tapping a project on Goals ▸ Map opens its page in three tabs. Over time is the streams of sessions, now with a dashed curve from the session that started each: `from`, which `midas sessions start` sends when run in a session's worktree, or the session whose branch it began on. Files says how to get the project (ssh clone, https when public, main as a .tar.gz through a new login-only archive route), lists its files at main and renders the README. Settings, an admin's, edits description, visibility (asking before it goes public), main branch, gate, gate nodes and the check before landing. From the page, /v1/projects/set now takes an admin; an agent's key does as before. A public project's own page gains the same download of main.
docs/hub.md | 19 +++-
src/codeview.rs | 6 ++
src/hub.rs | 80 +++++++++++---
src/sessions.rs | 14 ++-
src/tests.rs | 16 +++
web/src/app.css | 57 ++++++++++
web/src/components/projectmap.tsx | 214 +++++++++++++++++++++++++++++++++++---
web/src/lib/api.ts | 26 +++++
web/src/lib/stream.ts | 2 +
9 files changed, 403 insertions(+), 31 deletions(-)
diff --git a/docs/hub.md b/docs/hub.md
index afb8d04..c43d247 100644
--- a/docs/hub.md
+++ b/docs/hub.md
@@ -939,17 +939,26 @@ project's main, with how far. A **band** is sessions that worked in both
(their `repos`), a **dashed curve** techs of one that need a tech of another.
Columns are the tree's: one past the deepest project a project uses; those
that share no code stand apart. Tapping a project says what it uses and what
-uses it, its sessions and techs and its stale pins, and opens **its sessions
-over time** (`research/map/<owner>/<name>`): a stream for it, for each
+uses it, its sessions and techs and its stale pins, and opens **the
+project** (`research/map/<owner>/<name>`), in three tabs. **Over time**: a stream for it, for each
project it uses or that uses it and each other project three or more of
those sessions also worked in, each session a bar from start to end coloured
by how it ended, tied to the other projects it worked in, ◆ when it built a
-tech. The hub draws the map (`GET /v1/hosted/graph`: `graph` and `svg`, read
+tech, and a dashed curve from the session that started it: `from`, which
+`midas sessions start` sends when run in a session's worktree (`MIDAS_OWNER`;
+`sessions::set_from`), or the session whose branch it began on (its `base`).
+**Files** (`…/files/<path>`): how to get it (the workspace's ssh clone, the
+https one when public, and main as a .tar.gz, `GET /v1/repos/<o>/<n>/archive.tar.gz`
+for a login), then its files at main and the README, read through
+`/v1/repos/<o>/<n>/show` and `/about`. **Settings**, an admin's: what it
+is, public or not (asked again before it goes public), its main branch, gate,
+gate nodes and check before landing (`POST /v1/projects/set`, which from the
+page takes an admin; an agent's key with `project_set` as before). A public
+project's own page (codeview.rs) says how to get it the same way. The hub draws the map (`GET /v1/hosted/graph`: `graph` and `svg`, read
at most once a minute); the site's **front page** draws its public part for
anyone (`graph::public`): public projects and the lines between them, techs
built and what was built lately, never a session's count, title or cost.
-Which session started which is not recorded yet, so the streams draw no such
-line. It is
+It is
one file, `hosted/tree.json`: `GET
/v1/hosted/tree`, `POST /v1/hosted/tree` (by `op`, role `steer`), and the
runner's `POST /v1/hosted/runner/scouted`. A round can carry a **focus**:
diff --git a/src/codeview.rs b/src/codeview.rs
index 0b8710b..b3bd0b8 100644
--- a/src/codeview.rs
+++ b/src/codeview.rs
@@ -164,6 +164,12 @@ pub fn page(repo: &str, host: &str, tail: &str, q: &str) -> Result<Option<Page>>
let path = crate::hub::pct_decode(tail.strip_prefix("tree").unwrap_or("").trim_start_matches('/'));
let v = hosted::show(repo, rev.as_deref(), &path)?;
let mut body = String::new();
+ // How to get it, on its front page: clone it, or download main without git.
+ if path.is_empty() && rev.is_none() {
+ body += &format!("<p class=\"get\">Get it: <code>git clone https://{h}/{k}.git</code>, or <a href=\"/{k}/archive/{main}.tar.gz\" download>download {main} as .tar.gz</a>.</p>",
+ h = esc(host), k = esc(key),
+ main = esc(hosted::get(repo).and_then(|r| r["project"]["main"].as_str().map(str::to_string)).as_deref().unwrap_or("main")));
+ }
if !path.is_empty() {
let up = path.rsplit_once('/').map(|(u, _)| u).unwrap_or("");
body += &format!("<p><a href=\"/{}/tree/{}{}\">..</a> <span class=\"muted\">/{}</span></p>", esc(key), link(up), revq, esc(&path));
diff --git a/src/hub.rs b/src/hub.rs
index 4da0afe..616a351 100644
--- a/src/hub.rs
+++ b/src/hub.rs
@@ -344,6 +344,18 @@ pub(crate) fn handle(mut stream: TcpStream, peer: &str) -> Result<()> {
None => respond(&mut stream, 404, "application/json", br#"{"error":"no such mockup"}"#),
};
}
+ // A hosted repository at `rev` as a .tar.gz, for the workspace (the project page's Download): a
+ // private one too, so a login, as the tree's pictures take. A public one is also at `/<o>/<n>/archive/`.
+ if let (true, Some(rest)) = (method == "GET", path.strip_prefix("/v1/repos/").and_then(|r| r.strip_suffix("/archive.tar.gz"))) {
+ if who.principal.is_none() {
+ return respond(&mut stream, 401, "application/json", br#"{"error":"log in first","login":true}"#);
+ }
+ let rev = query.split('&').find_map(|p| p.strip_prefix("rev=")).map(pct_decode).unwrap_or_else(|| "HEAD".into());
+ return match crate::mirror::repo_name(rest).ok().filter(|r| crate::hosted::is_hosted(r)) {
+ Some(repo) => archive(&mut stream, &repo, &rev),
+ None => respond(&mut stream, 404, "application/json", br#"{"error":"no such project"}"#),
+ };
+ }
// A picture of a tech as it really works (tree.rs, `add_shot`): `<tech>/<n>`, read as the tree is.
if let (true, Some(rest)) = (method == "GET", path.strip_prefix("/v1/hosted/tree/shots/")) {
if who.web && who.principal.is_none() {
@@ -1055,7 +1067,13 @@ fn api(method: &str, path: &str, query: &str, body: &Value, who: &Who, peer: &st
Err(why @ crate::sessions::Refused::Conflict(_)) => (409, json!({"error": why.to_string(), "kind": "conflict"})),
}
}
- ("POST", "hosted/start") => (200, json!({"id": crate::sessions::start(&by, &s("prompt").unwrap_or_default(),s("repo").as_deref(), s("base").as_deref(), s("mode").as_deref(), s("model").as_deref(), s("agent").as_deref(), &body["images"])?})),
+ ("POST", "hosted/start") => {
+ let id = crate::sessions::start(&by, &s("prompt").unwrap_or_default(),s("repo").as_deref(), s("base").as_deref(), s("mode").as_deref(), s("model").as_deref(), s("agent").as_deref(), &body["images"])?;
+ if let Some(from) = s("from") {
+ crate::sessions::set_from(&id, &from)?;
+ }
+ (200, json!({"id": id}))
+ }
// A voice conversation about a session, signed with the hub's OpenAI key (discuss.rs).
("POST", "hosted/discuss") => {
let tools: Vec<String> = body["tools"].as_array().into_iter().flatten().filter_map(|t| t.as_str().map(str::to_string)).collect();
@@ -1339,6 +1357,10 @@ fn api(method: &str, path: &str, query: &str, body: &Value, who: &Who, peer: &st
}
("POST", "projects/set") => {
let by_person = p.account.is_some() && crate::accounts::at_least(&p.role, "admin");
+ // On the page a project's settings are an admin's; a caller key (an agent's project_set) as before.
+ if p.account.is_some() && !by_person {
+ return Ok((403, json!({"error": "a project's settings are an admin's to change"})));
+ }
match crate::hosted::set(&s("repo").unwrap_or_default(), body, &by, by_person) {
Ok(v) => (200, v),
Err(e) => (409, json!({"error": format!("{e:#}")})),
@@ -1732,17 +1754,7 @@ fn public_git(stream: &mut TcpStream, reader: &mut BufReader<TcpStream>, g: &Pub
}
// archive/<rev>.tar.gz: what Bun takes as a dependency.
if let Some(rev) = tail.strip_prefix("archive/").and_then(|r| r.strip_suffix(".tar.gz")) {
- if rev.is_empty() || rev.starts_with('-') || !rev.chars().all(|c| c.is_ascii_alphanumeric() || "-_./".contains(c)) {
- return not_found(stream);
- }
- let out = std::process::Command::new("git").arg("-C").arg(crate::hosted::path(&repo))
- .args(["archive", "--format=tar.gz", &format!("--prefix={name}/"), rev]).output()?;
- if !out.status.success() {
- return not_found(stream);
- }
- write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: application/gzip\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", out.stdout.len())?;
- stream.write_all(&out.stdout)?;
- return Ok(());
+ return archive(stream, &repo, rev);
}
use crate::codeview::Page;
match crate::codeview::page(&repo, g.host, tail, query) {
@@ -1762,6 +1774,22 @@ fn public_git(stream: &mut TcpStream, reader: &mut BufReader<TcpStream>, g: &Pub
}
}
+/// A hosted repository at `rev` as a .tar.gz, its files under `<name>/`.
+fn archive(stream: &mut TcpStream, repo: &str, rev: &str) -> Result<()> {
+ let name = repo.trim_end_matches(".git").rsplit('/').next().unwrap_or("repo").to_string();
+ if rev.is_empty() || rev.starts_with('-') || !rev.chars().all(|c| c.is_ascii_alphanumeric() || "-_./".contains(c)) {
+ return respond(stream, 404, "text/plain", b"no such revision\n");
+ }
+ let out = std::process::Command::new("git").arg("-C").arg(crate::hosted::path(repo))
+ .args(["archive", "--format=tar.gz", &format!("--prefix={name}/"), rev]).output()?;
+ if !out.status.success() {
+ return respond(stream, 404, "text/plain", b"no such revision\n");
+ }
+ write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: application/gzip\r\nContent-Disposition: attachment; filename=\"{name}.tar.gz\"\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", out.stdout.len())?;
+ stream.write_all(&out.stdout)?;
+ Ok(())
+}
+
/// `GET /v1/repos/<owner>/<name>/<what>`: a hosted repository read through
/// the API, for sessions and the page. `q` is the query reader of `api`.
fn repo_read(rest: &str, q: &dyn Fn(&str) -> Option<String>) -> Result<(u16, Value)> {
@@ -1779,7 +1807,16 @@ fn repo_read(rest: &str, q: &dyn Fn(&str) -> Option<String>) -> Result<(u16, Val
"log" => json!(crate::hosted::log(&repo, rev.as_deref(), q("n").and_then(|n| n.parse().ok()).unwrap_or(30))?),
"branches" => json!(crate::hosted::branches(&repo)?),
"commit" => crate::hosted::commit(&repo, &rev.unwrap_or_else(|| "HEAD".into()))?,
- _ => return Ok((404, json!({"error": "show, log, branches or commit"}))),
+ // What the project page says of it: how to get it, and its landing settings.
+ "about" => {
+ let r = crate::hosted::get(&repo).unwrap_or_default();
+ let key = repo.trim_end_matches(".git");
+ let ssh = crate::conf::hub().forgejo_ssh.trim_end_matches('/').to_string();
+ json!({"repo": key, "description": r["description"], "public": r["visibility"] == "public",
+ "ssh": if ssh.is_empty() { crate::hosted::url(&repo) } else { format!("{ssh}/{key}.git") },
+ "head": crate::hosted::log(&repo, None, 1)?.first(), "project": r["project"]})
+ }
+ _ => return Ok((404, json!({"error": "show, log, branches, commit or about"}))),
};
Ok((200, v))
}
@@ -2285,6 +2322,23 @@ mod roles {
}
}
+ #[test]
+ fn a_projects_settings_on_the_page_are_an_admins_and_its_about_says_how_to_get_it() {
+ let _g = crate::tests::SERIAL.lock().unwrap_or_else(|p| p.into_inner());
+ crate::tests::scratch("project-page");
+ crate::hosted::create(&crate::hosted::New {
+ owner: "acme", name: "shop", description: "A shop", public: false, gate: Some("true"), gate_nodes: None, by: "test",
+ }).unwrap();
+ let set = json!({"repo": "acme/shop", "description": "The shop"});
+ assert_eq!(status(&person("steer", true), "POST", "/v1/projects/set", set.clone()), 403, "a steer person may not");
+ assert_eq!(status(&person("admin", true), "POST", "/v1/projects/set", set.clone()), 200);
+ assert_eq!(status(&key("operator"), "POST", "/v1/projects/set", set), 200, "an agent's project_set, as before");
+ let (code, about) = api("GET", "/v1/repos/acme/shop/about", "", &json!({}), &person("viewer", true), "203.0.113.9", "10.44.0.1:4791").unwrap();
+ assert_eq!(code, 200);
+ assert_eq!((about["description"].as_str(), about["public"].as_bool()), (Some("The shop"), Some(false)));
+ assert!(about["ssh"].as_str().is_some_and(|s| s.ends_with("acme/shop.git")) && about["head"]["sha"].is_string(), "{about}");
+ }
+
#[test]
fn each_role_may_do_what_it_says_and_no_more() {
let _g = crate::tests::SERIAL.lock().unwrap_or_else(|p| p.into_inner());
diff --git a/src/sessions.rs b/src/sessions.rs
index 93d25a8..de799e4 100644
--- a/src/sessions.rs
+++ b/src/sessions.rs
@@ -1209,6 +1209,16 @@ pub fn set_research(id: &str, origin: &Value) -> Result<()> {
Ok(())
}
+/// The session `id` was started from (`midas sessions start` in a session's worktree): the line the
+/// Map draws between them (graph.rs, projectmap.tsx). Only a session that exists, and never itself.
+pub fn set_from(id: &str, from: &str) -> Result<()> {
+ if !id_ok(from) || from == id || meta(from).is_err() {
+ return Ok(());
+ }
+ update_meta(id, |m| m["from"] = json!(from))?;
+ Ok(())
+}
+
pub fn set_title(id: &str, title: &str, by: &str) -> Result<String> {
let Some(title) = title_of(title) else { bail!("say what to call it") };
let (m, _) = update_meta(id, |m| m["title"] = json!(title))?;
@@ -4336,7 +4346,9 @@ pub fn start_cmd(prompt: &str, repo: Option<&str>, base: Option<&str>, mode: Opt
all.as_array()?.iter().any(|p| p["repo"] == r.as_str()).then_some(r)
};
let repo = repo.map(str::to_string).or_else(here);
- let v = crate::client::post("/v1/hosted/start", &json!({"prompt": prompt, "repo": repo, "base": base, "mode": mode, "model": model, "agent": agent}))?;
+ // Started from within a session: the new one remembers it, for the Map's line between them.
+ let from = std::env::var("MIDAS_OWNER").ok().and_then(|o| o.strip_prefix("session-").map(str::to_string));
+ let v = crate::client::post("/v1/hosted/start", &json!({"prompt": prompt, "repo": repo, "base": base, "mode": mode, "model": model, "agent": agent, "from": from}))?;
let id = v["id"].as_str().ok_or_else(|| anyhow!("the hub gave no id"))?;
eprintln!("{id} queued; a runner (midas sessions run) picks it up. Follow it on the page, Sessions.");
println!("{id}");
diff --git a/src/tests.rs b/src/tests.rs
index cdfeb28..1cc58da 100644
--- a/src/tests.rs
+++ b/src/tests.rs
@@ -2985,6 +2985,7 @@ fn a_public_repository_has_pages_and_a_private_one_none() {
};
let home = html("");
assert!(home.contains("README.md") && home.contains("A test project") && home.contains("git clone https://midas.example/acme/open.git"));
+ assert!(home.contains("href=\"/acme/open/archive/main.tar.gz\""), "a download of main: {home}");
assert!(home.contains("href=\"/acme/open/log\""), "links at the root, as Forgejo had them: {home}");
assert!(html("log").contains("Start open"));
assert!(page("nowhere", "").is_none());
@@ -3162,3 +3163,18 @@ fn a_nodes_readings_are_kept_and_bucketed_over_time() {
// Lines past the window are not read.
assert!(crate::usage::read(30, None)["nodes"].as_object().unwrap().is_empty());
}
+
+#[test]
+fn a_session_started_from_a_session_remembers_it() {
+ use crate::sessions;
+ let _g = SERIAL.lock().unwrap();
+ scratch("started-from");
+ let parent = sessions::start("ana", "build the map", None, None, None, None, None, &Value::Null).unwrap();
+ let child = sessions::start("agent", "the part apart", None, None, None, None, None, &Value::Null).unwrap();
+ sessions::set_from(&child, &parent).unwrap();
+ assert_eq!(sessions::meta(&child).unwrap()["from"], parent.as_str());
+ // Never itself, nor one that is not there.
+ sessions::set_from(&parent, &parent).unwrap();
+ sessions::set_from(&parent, "s99999").unwrap();
+ assert!(sessions::meta(&parent).unwrap()["from"].is_null());
+}
diff --git a/web/src/app.css b/web/src/app.css
index 0a04ba5..c4ac995 100644
--- a/web/src/app.css
+++ b/web/src/app.css
@@ -9847,3 +9847,60 @@ button.tree-lane__name:hover {
box-sizing: border-box;
}
}
+/* A project's page, from the Map (projectmap.tsx): its tabs, its files and how to get it. */
+.pproj__tabs {
+ display: flex;
+ gap: 4px;
+}
+.pfiles__get code {
+ overflow-wrap: anywhere;
+ user-select: all;
+}
+.pfiles__crumbs {
+ font-size: var(--m-font-size-sm);
+}
+.pfiles__list {
+ display: flex;
+ flex-direction: column;
+ border: 1px solid var(--m-border);
+ border-radius: var(--m-radius);
+ background: var(--m-surface);
+}
+.pfiles__entry {
+ display: flex;
+ justify-content: space-between;
+ padding: 6px var(--m-space-2);
+ border-bottom: 1px solid var(--m-border);
+ color: var(--m-text);
+ text-decoration: none;
+}
+.pfiles__entry:last-child {
+ border-bottom: 0;
+}
+.pfiles__entry:hover {
+ background: var(--m-hover);
+}
+.pfiles__text {
+ overflow: auto;
+ max-height: 70vh;
+ margin: 0;
+ padding: var(--m-space-2);
+ border: 1px solid var(--m-border);
+ border-radius: var(--m-radius);
+ background: var(--m-surface-sunken);
+ font-size: 12.5px;
+}
+.pweek__from {
+ fill: none;
+ stroke: #8f6fc4;
+ stroke-width: 1.5;
+ stroke-dasharray: 4 3;
+}
+.pweek__key.from {
+ height: 0;
+ border-top: 2px dashed #8f6fc4;
+ border-radius: 0;
+}
+.pset {
+ max-width: 640px;
+}
diff --git a/web/src/components/projectmap.tsx b/web/src/components/projectmap.tsx
index a97044c..e61939f 100644
--- a/web/src/components/projectmap.tsx
+++ b/web/src/components/projectmap.tsx
@@ -1,8 +1,13 @@
import m from '@garage44/mithril'
-import {Button, Card} from '@garage44/mithril/components'
+import {Button, Card, FieldSwitch, FieldText} from '@garage44/mithril/components'
+import {askConfirm} from '@/components/confirm'
+import {act} from '@/lib/actions'
import {api} from '@/lib/api'
-import type {ProjectGraph, TreeState} from '@/lib/api'
+import type {ProjectGraph, RepoAbout, RepoEntry, TreeState} from '@/lib/api'
+import {markdown} from '@/lib/markdown'
+import {bind} from '@/lib/reactive'
+import {$s} from '@/lib/store'
import {local} from '@/lib/reactive'
import {go} from '@/lib/route'
import {hosted, type Hosted} from '@/lib/stream'
@@ -22,6 +27,11 @@ const state = local({
loading: false,
picked: '',
days: 7,
+ /** Each project's about (how to get it, its settings), and each directory or file read, by `repo:path`. */
+ about: {} as Record<string, RepoAbout | {error: string}>,
+ files: {} as Record<string, RepoEntry | {error: string}>,
+ /** The settings form, for the project it was filled from. */
+ form: {repo: '', description: '', public: false, main: '', gate: '', gate_nodes: '', pre_land: ''},
})
function load() {
@@ -75,7 +85,7 @@ function pickedCard(g: ProjectGraph, name: string): m.Children {
))}
<div class="tree-bar__row">
<Button variant="primary" onclick={() => go(`research/map/${name}`)}>
- Its sessions over time
+ Open the project
</Button>
{p.techs ? (
<Button variant="ghost" onclick={() => {
@@ -163,6 +173,9 @@ function mapPage(): m.Children {
type Outcome = 'landed' | 'ended' | 'working'
+/** The session `h` was started from (`from`), or whose branch it was started on (its `base`). */
+const parentOf = (h: Hosted): string | null => h.from ?? h.base?.match(/^session\/(s\d+)$/)?.[1] ?? null
+
function outcomeOf(h: Hosted): Outcome {
if (h.finished?.outcome === 'landed') return 'landed'
if (h.finished || h.status === 'stopped' || h.status === 'failed') return 'ended'
@@ -176,9 +189,10 @@ const LANE = 13
/**
* One project's sessions over time: a stream for it, then for each project it uses or that uses it, then
* for each other project three or more of these sessions also worked in, then one for everywhere else. A session is a bar from its start to its end in the
- * first of its projects shown, with a tie to each other project it worked in. ◆: it built a tech.
+ * first of its projects shown, with a tie to each other project it worked in. ◆: it built a tech. A
+ * dashed curve runs to a session from the one that started it (`from`) or whose branch it began on.
*/
-function weekPage(d: TreeState | null, name: string): m.Children {
+function timeTab(d: TreeState | null, name: string): m.Children {
const g = state.graph!
const near = [...usesOf(g, name), ...usedBy(g, name)].filter((p, i, a) => a.indexOf(p) === i && p !== name)
const now = Date.now() / 1000
@@ -222,13 +236,24 @@ function weekPage(d: TreeState | null, name: string): m.Children {
const days = Math.round((now - t0) / 86400)
const ticks = Array.from({length: Math.min(days, 12) + 1}, (_, i) => t0 + (i * (now - t0)) / Math.min(days, 12))
const label = (t: number) => new Date(t * 1000).toLocaleDateString(undefined, {day: 'numeric', month: 'short'})
+ // Started from: from the parent's bar, at the moment the child began, to the child's start.
+ const at = new Map(placed.map((p) => [p.h.id, p]))
+ const lines = placed.flatMap((c) => {
+ const from = parentOf(c.h)
+ const p = from ? at.get(from) : undefined
+ if (!p) return []
+ const cx = x(c.start)
+ const cy = top[c.home]! + 8 + c.k * LANE + 4
+ const px = Math.min(Math.max(x(c.start), x(p.start)), Math.max(x(p.end), x(p.start) + 6))
+ const py = top[p.home]! + 8 + p.k * LANE + 4
+ // Starts close together: a bracket out to the left, else an S from one to the other.
+ const mid = (px + cx) / 2
+ const d = cx - px < 28 ? `M${px},${py} C${px - 16},${py} ${cx - 16},${cy} ${cx},${cy}` : `M${px},${py} C${mid + 12},${py} ${mid - 12},${cy} ${cx},${cy}`
+ return [<path d={d} class="pweek__from"><title>{`${c.h.id} was started from ${p.h.id}`}</title></path>]
+ })
return (
<div class="stack">
<div class="tree-bar__row">
- <Button variant="ghost" onclick={() => go('research/map')}>
- ← All projects
- </Button>
- <b class="tree-board__title">{short(name)}</b>
<span class="hint">
{all.length} sessions · {all.filter((h) => outcomeOf(h) === 'landed').length} landed
</span>
@@ -250,6 +275,7 @@ function weekPage(d: TreeState | null, name: string): m.Children {
<rect x={8} y={top[s]} width={X0 + W + 4} height={height(s)} rx={9} class={`pweek__stream${s === name ? ' on' : ''}`} />,
<text x={20} y={top[s]! + height(s) / 2 + 4} class={`pweek__name${s === 'elsewhere' ? ' dim' : ''}`}>{s === 'elsewhere' ? 'elsewhere' : short(s)}</text>,
])}
+ {lines}
{placed.map(({h, home, k, start, end}) => {
const by = top[home]! + 8 + k * LANE
const x1 = x(start)
@@ -277,19 +303,183 @@ function weekPage(d: TreeState | null, name: string): m.Children {
<span><i class="pweek__key ended" />ended without landing</span>
<span><i class="pweek__key working" />at work</span>
<span>│ the same session in another project</span>
+ <span><i class="pweek__key from" />started from</span>
<span>◆ built a tech</span>
</div>
</div>
)
}
-/** The Map's pages: `research/map`, and `research/map/<owner>/<name>` for one project over time. */
+function aboutOf(repo: string): RepoAbout | {error: string} | undefined {
+ if (!(repo in state.about)) {
+ state.about[repo] = {error: ''}
+ api.repoAbout(repo)
+ .then((a) => (state.about[repo] = a))
+ .catch((e: Error) => (state.about[repo] = {error: e.message}))
+ }
+ const a = state.about[repo]
+ return a && 'error' in a && !a.error ? undefined : a
+}
+
+function entryOf(repo: string, path: string): RepoEntry | {error: string} | undefined {
+ const k = `${repo}:${path}`
+ if (!(k in state.files)) {
+ state.files[k] = {error: ''}
+ api.repoShow(repo, path)
+ .then((e) => (state.files[k] = e))
+ .catch((e: Error) => (state.files[k] = {error: e.message}))
+ }
+ const e = state.files[k]
+ return e && 'error' in e && !e.error ? undefined : e
+}
+
+/** How to get the project: clone it (by key for the workspace, over https when public) or download main. */
+function downloadCard(name: string, a: RepoAbout): m.Children {
+ const https = a.public ? `${location.origin}/${name}.git` : ''
+ const tarball = a.public ? `/${name}/archive/main.tar.gz` : `/v1/repos/${name}/archive.tar.gz?rev=main`
+ return (
+ <Card class="pfiles__get" title="Get it">
+ {https ? (
+ <p>
+ Anyone, with git: <code>git clone {https}</code>
+ </p>
+ ) : null}
+ <p>
+ The workspace, by key: <code>git clone {a.ssh}</code>
+ </p>
+ <p>
+ Or <a href={tarball} download={`${short(name)}.tar.gz`}>download main as .tar.gz</a>
+ {a.head ? <span class="hint"> · at {a.head.sha.slice(0, 10)}, {a.head.subject}</span> : null}
+ </p>
+ {a.public ? null : <p class="hint">A private project: the download takes your login, and the clone a key the workspace knows.</p>}
+ </Card>
+ )
+}
+
+/** The project's files at main: a directory as its entries and its README, a file as text. */
+function filesTab(name: string, path: string): m.Children {
+ const a = aboutOf(name)
+ const e = entryOf(name, path)
+ const to = (p: string) => go(`research/map/${name}/files${p ? `/${p}` : ''}`)
+ const parts = path ? path.split('/') : []
+ const readme = e && !('error' in e) && e.kind === 'dir' ? e.entries?.find((x) => x.kind === 'file' && /^readme(\.md|\.markdown|\.txt)?$/i.test(x.name)) : undefined
+ const readmeEntry = readme ? entryOf(name, path ? `${path}/${readme.name}` : readme.name) : undefined
+ return (
+ <div class="stack">
+ {a && !('error' in a) ? downloadCard(name, a) : null}
+ <nav class="pfiles__crumbs">
+ <a href="#" onclick={(ev: Event) => (ev.preventDefault(), to(''))}>{short(name)}</a>
+ {parts.map((p, i) => [' / ', <a href="#" onclick={(ev: Event) => (ev.preventDefault(), to(parts.slice(0, i + 1).join('/')))}>{p}</a>])}
+ </nav>
+ {!e ? <p class="hint">Reading…</p> : 'error' in e ? <p class="hint">{e.error}</p> : e.kind === 'dir' ? (
+ <div class="pfiles__list">
+ {(e.entries ?? [])
+ .slice()
+ .sort((x, y) => (x.kind === y.kind ? x.name.localeCompare(y.name) : x.kind === 'dir' ? -1 : 1))
+ .map((x) => (
+ <a href="#" class="pfiles__entry" onclick={(ev: Event) => (ev.preventDefault(), to(path ? `${path}/${x.name}` : x.name))}>
+ <span>{x.kind === 'dir' ? '▸ ' : ''}{x.name}{x.kind === 'dir' ? '/' : ''}</span>
+ <span class="hint">{x.size != null ? `${x.size} B` : ''}</span>
+ </a>
+ ))}
+ </div>
+ ) : e.text != null ? (
+ <pre class="pfiles__text">{e.text}</pre>
+ ) : (
+ <p class="hint">A binary file of {e.size} bytes.</p>
+ )}
+ {readmeEntry && !('error' in readmeEntry) && readmeEntry.text ? (
+ <Card title={readme!.name} class="pfiles__readme">
+ {/\.(md|markdown)$/i.test(readme!.name) ? markdown(readmeEntry.text) : <pre class="pfiles__text">{readmeEntry.text}</pre>}
+ </Card>
+ ) : null}
+ </div>
+ )
+}
+
+/** An admin's: the description, who may read it, its main branch and how it lands (hosted.rs `set`). */
+function settingsTab(name: string): m.Children {
+ if ($s.role !== 'admin') return <p class="hint">A project's settings are an admin's to change.</p>
+ const a = aboutOf(name)
+ if (!a) return <p class="hint">Reading…</p>
+ if ('error' in a) return <p class="hint">{a.error}</p>
+ const f = state.form
+ if (f.repo !== name) {
+ Object.assign(f, {repo: name, description: a.description ?? '', public: a.public, main: a.project?.main ?? '', gate: a.project?.gate ?? '',
+ gate_nodes: a.project?.gate_nodes ?? '', pre_land: a.project?.pre_land ?? ''})
+ }
+ const save = async () => {
+ if (f.public && !a.public) {
+ const yes = await askConfirm({
+ title: `Make ${short(name)} public?`,
+ text: 'Anyone can then read and clone it, and the public map shows it. Making it private again does not take back what was read or copied meanwhile.',
+ yes: 'Make it public',
+ danger: true,
+ })
+ if (!yes) return
+ }
+ const saved = await act('settings saved', () => api.projectSet(name, {description: f.description, public: f.public, main: f.main, gate: f.gate, gate_nodes: f.gate_nodes, pre_land: f.pre_land}))
+ if (!saved) return
+ // Read again, and the map with it: a description or visibility shows there.
+ delete state.about[name]
+ f.repo = ''
+ state.graph = null
+ }
+ return (
+ <Card title="Settings" class="pset">
+ <FieldText model={bind(f, 'description')} label="What it is" placeholder="One line, as the README's first" />
+ <FieldSwitch model={bind(f, 'public')} label="Public" help="Anyone can read and clone it, without a login, and the public map shows it." />
+ <FieldText model={bind(f, 'main')} label="Main branch" placeholder="main" />
+ <FieldText model={bind(f, 'gate')} label="Landing gate" placeholder="e.g. cargo test" help="The command a branch must pass on a node before it lands on main." />
+ <FieldText model={bind(f, 'gate_nodes')} label="Gate nodes" placeholder="any" help="Which nodes the gate may run on." />
+ <FieldText model={bind(f, 'pre_land')} label="Check before landing" placeholder="(none)" help="A command run in the session's worktree before the gate." />
+ <div class="tree-bar__row">
+ <Button variant="primary" onclick={() => void save()}>
+ Save
+ </Button>
+ </div>
+ </Card>
+ )
+}
+
+const TABS: [string, string][] = [['', 'Over time'], ['files', 'Files'], ['settings', 'Settings']]
+
+/** One project: its sessions over time, its files and how to get it, and (an admin's) its settings. */
+function projectPage(d: TreeState | null, name: string, tab: string, path: string): m.Children {
+ const p = state.graph!.projects.find((x) => x.name === name)!
+ const tabs = TABS.filter(([t]) => t !== 'settings' || $s.role === 'admin')
+ return (
+ <div class="stack">
+ <div class="tree-bar__row">
+ <Button variant="ghost" onclick={() => go('research/map')}>
+ ← All projects
+ </Button>
+ <b class="tree-board__title">{short(name)}</b>
+ <span class="hint">{[p.description, p.public ? 'public' : 'private'].filter(Boolean).join(' · ')}</span>
+ </div>
+ <div class="pproj__tabs" role="tablist">
+ {tabs.map(([t, label]) => (
+ <Button size="sm" variant={tab === t ? 'secondary' : 'ghost'} onclick={() => go(`research/map/${name}${t ? `/${t}` : ''}`)}>
+ {label}
+ </Button>
+ ))}
+ </div>
+ {tab === 'files' ? filesTab(name, path) : tab === 'settings' ? settingsTab(name) : timeTab(d, name)}
+ </div>
+ )
+}
+
+/**
+ * The Map's pages: `research/map`, and a project's at `research/map/<owner>/<name>`, with
+ * `/files/<path>` and `/settings` for its other tabs.
+ */
export function mapView(d: TreeState | null, place: string): m.Children {
if (!state.graph) {
load()
return <p class="hint">{state.error || 'Reading every project…'}</p>
}
- const name = place.replace(/^research\/map\/?/, '')
- if (name && state.graph.projects.some((p) => p.name === name)) return weekPage(d, name)
+ const parts = place.replace(/^research\/map\/?/, '').split('/').filter(Boolean)
+ const name = parts.slice(0, 2).join('/')
+ if (parts.length >= 2 && state.graph.projects.some((p) => p.name === name)) return projectPage(d, name, parts[2] ?? '', parts.slice(3).join('/'))
return mapPage()
}
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
index a0872c9..0445824 100644
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@ -383,6 +383,26 @@ export interface ProjectGraph {
landed: {name: string; repo: string; at: number}[]
}
+export interface RepoAbout {
+ repo: string
+ description?: string
+ public: boolean
+ /** Where the workspace clones it by key. */
+ ssh: string
+ head?: {sha: string; author: string; at: string; subject: string} | null
+ project?: {gate?: string; gate_nodes?: string; pre_land?: string; main?: string} | null
+}
+
+export interface RepoEntry {
+ kind: 'dir' | 'file'
+ path: string
+ commit: string
+ entries?: {name: string; kind: 'dir' | 'file'; size?: number | null}[]
+ text?: string | null
+ size?: number
+ binary?: boolean
+}
+
export interface Direction {
id: string
target: string
@@ -668,6 +688,12 @@ export const api = {
tree: () => get<TreeState>('/v1/hosted/tree'),
/** Goals ▸ Map: every project, which uses which, the sessions between them, and the map drawn (graph.rs). */
graph: () => get<{graph: ProjectGraph; svg: string}>('/v1/hosted/graph'),
+ /** A hosted project: how to get it and its landing settings (hub.rs `repo_read`). */
+ repoAbout: (repo: string) => get<RepoAbout>(`/v1/repos/${repo}/about`),
+ /** A directory's entries or a file's text at the main branch. */
+ repoShow: (repo: string, path: string) => get<RepoEntry>(`/v1/repos/${repo}/show?path=${encodeURIComponent(path)}`),
+ /** A project's description, visibility or landing, changed (hosted.rs `set`; on the page, an admin's). */
+ projectSet: (repo: string, fields: Record<string, unknown>) => post('/v1/projects/set', {repo, ...fields}),
/** A change to it, by op (goal_save, goal_delete, idea, insight_drop, tech_confirm, tech_drop, tech_restore, tech_built, scout): the whole tree after. */
treeOp: (op: string, fields: Record<string, unknown>) => post('/v1/hosted/tree', {op, ...fields}) as Promise<TreeState>,
reopen: (id: string) => post(`/v1/hosted/${id}/reopen`, {}),
diff --git a/web/src/lib/stream.ts b/web/src/lib/stream.ts
index 9704c46..aa3241e 100644
--- a/web/src/lib/stream.ts
+++ b/web/src/lib/stream.ts
@@ -107,6 +107,8 @@ export interface Hosted {
/** When it last did something (a turn began or ended, a person reopened it); a restart does not move it. */
active?: number | null
base: string
+ /** The session it was started from, when one started it (sessions.rs `set_from`). */
+ from?: string | null
/** Its project, as `owner/name`: the repository it works in (none before projects); of several, the first. */
repo?: string | null
/** The projects a session in a folder of its own works in, a worktree each, as its agent added them. */