diff options
Diffstat (limited to 'web')
56 files changed, 11033 insertions, 0 deletions
diff --git a/web/app_test.go b/web/app_test.go new file mode 100644 index 0000000..8416099 --- /dev/null +++ b/web/app_test.go @@ -0,0 +1,912 @@ +package web + +import ( + "crypto/sha256" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + "testing" + "time" + + "0x4200.cafe/notevi/sidecar" +) + +func logLines(lines ...string) string { return strings.Join(lines, "\n") + "\n" } + +const ( + noteA = `{"time":"2026-07-20T10:00:00Z","op":"note","session":"s1","agent":"codex","model":"gpt-5.6-sol","reasoning":"max","dir":"/repo","change":"aaa","file":"src/lib.rs","start":10,"end":20,"note_id":1,"type":"struct","text":"Cache is a two-level map"}` + noteB = `{"time":"2026-07-25T10:00:00Z","op":"note","session":"s2","agent":"claude","model":"claude-fable-5","reasoning":"xhigh","dir":"/repo","change":"aaa","file":"src/main.rs","note_id":1,"text":"entry point does too much"}` + readA = `{"time":"2026-07-20T09:59:00Z","op":"read","session":"s1","agent":"codex","model":"gpt-5.6-sol","dir":"/repo","change":"aaa","file":"src/lib.rs","start":1,"end":30}` + grepA = `{"time":"2026-07-20T09:58:00Z","op":"grep","session":"s1","agent":"codex","dir":"/repo","change":"aaa","file":"src/lib.rs","pattern":"Cache","matches":3}` +) + +func testSite(t *testing.T) *Site { + t.Helper() + s := buildModel("test", parseLog([]byte(logLines(grepA, readA, noteA, noteB))), "") + s.Theme, s.Light = loadTheme("", "", "dark"), loadTheme("", "", "light") + return s +} + +// testThemes stands in for whatever themes this machine happens to have, so +// the picker's two files are the same in every test run. +func testThemes(dark, light *Theme) *themeSet { + return themesFrom([]*Theme{dark, light}, dark, light) +} + +func TestBuildModel(t *testing.T) { + s := testSite(t) + if s.Change != "aaa" { + t.Errorf("site change = %q, want aaa", s.Change) + } + if len(s.Agents) != 2 || s.Agents[0].Bit != 1 || s.Agents[1].Bit != 2 { + t.Errorf("agents = %+v", s.Agents) + } + f := s.Files["src/lib.rs"] + if f == nil || f.Reads != 1 || f.Greps != 1 || len(f.Notes) != 1 { + t.Fatalf("src/lib.rs = %+v", f) + } + if f.Cov[15] != 1 || f.Mask != 1 { + t.Errorf("coverage = %v mask %d", f.Cov, f.Mask) + } + if got := s.Notes[0].When; got == "" { + t.Error("note has no rendered timestamp") + } +} + +func TestNoteThreadRecursesThroughRepliesAndMentions(t *testing.T) { + entries := parseLog([]byte(logLines( + `{"op":"note","session":"s","agent":"a","change":"aaa","note_id":1,"text":"root"}`, + `{"op":"note","session":"s","agent":"a","change":"aaa","note_id":2,"reply_to":1,"text":"child"}`, + `{"op":"note","session":"s","agent":"a","change":"aaa","note_id":3,"reply_to":2,"text":"grandchild"}`, + `{"op":"note","session":"s","agent":"a","change":"aaa","note_id":4,"text":"[mentions root](../note/1.html)"}`, + `{"op":"note","session":"s","agent":"a","change":"aaa","note_id":5,"reply_to":3,"text":"[also mentions child](note/2)"}`, + `{"op":"note","session":"s","agent":"a","change":"aaa","note_id":6,"reply_to":5,"text":"arbitrarily deeper"}`, + ))) + s := buildModel("test", entries, "") + root, child := s.NoteByID(1), s.NoteByID(2) + if len(root.Replies) != 1 || root.Replies[0].ID != 2 || len(root.Mentions) != 1 || root.Mentions[0].ID != 4 { + t.Fatalf("root edges = replies %+v, mentions %+v", root.Replies, root.Mentions) + } + if len(child.Mentions) != 1 || child.Mentions[0].ID != 5 { + t.Fatalf("child mentions = %+v", child.Mentions) + } + + thread := s.NoteThread(1) + if thread == nil || len(thread.Children) != 2 || thread.Children[0].Via != "reply" || thread.Children[1].Via != "mention" { + t.Fatalf("root thread = %+v", thread) + } + // 1 → 2 → 3 → 5 → 6 proves the renderer's data is recursive rather + // than a fixed parent/child pair. + deep := thread.Children[0].Children[0].Children[0] + if deep.Note.ID != 5 || len(deep.Children) != 1 || deep.Children[0].Note.ID != 6 { + t.Fatalf("deep reply branch = %+v", deep) + } + // Note 5 also mentions note 2. It is fully rendered under note 3, then left + // as a DAG reference on the second path instead of recursing twice. + join := thread.Children[0].Children[1] + if join.Note.ID != 5 || !join.Reference || join.Via != "mention" { + t.Errorf("DAG join = %+v", join) + } +} + +// A ninth agent gets no color instead of overflowing the uint8 mask (and the +// per-mask CSS it would generate). +func TestAgentColorsAreBounded(t *testing.T) { + var lines []string + for i := 0; i < maxAgents+3; i++ { + lines = append(lines, `{"time":"2026-07-20T10:00:00Z","op":"note","agent":"a`+string(rune('a'+i))+`","change":"aaa","note_id":1,"text":"x"}`) + } + s := buildModel("t", parseLog([]byte(logLines(lines...))), "") + if len(s.Agents) != maxAgents+3 { + t.Fatalf("agents = %d", len(s.Agents)) + } + for i, a := range s.Agents { + if i < maxAgents && a.Bit == 0 { + t.Errorf("agent %d has no bit", i) + } + if i >= maxAgents && a.Bit != 0 { + t.Errorf("agent %d got bit %d, want none", i, a.Bit) + } + } + if n := len(s.masks()); n != 1<<maxAgents-1 { + t.Errorf("masks = %d, want %d", n, 1<<maxAgents-1) + } +} + +// A view of one change holds only what was recorded there — but note ids stay +// positional over the whole log, so links survive the scope changing. +func TestModelScopedToAChange(t *testing.T) { + otherChange := `{"time":"2026-07-26T10:00:00Z","op":"note","session":"s3","agent":"codex","dir":"/repo","change":"bbb","file":"src/lib.rs","start":5,"end":6,"note_id":1,"text":"at another change"}` + otherRead := `{"time":"2026-07-26T09:00:00Z","op":"read","session":"s3","agent":"codex","dir":"/repo","change":"bbb","file":"src/other.rs","start":1,"end":9}` + entries := parseLog([]byte(logLines(grepA, readA, noteA, noteB, otherRead, otherChange))) + + all := buildModel("t", entries, "") + if len(all.Notes) != 3 || all.NotesTotal != 3 { + t.Fatalf("unscoped notes = %d of %d", len(all.Notes), all.NotesTotal) + } + if all.Change != "aaa" || all.Votes["aaa"] != 4 || all.Votes["bbb"] != 2 { + t.Errorf("change %q votes %v", all.Change, all.Votes) + } + if strings.Join(all.Ranked, ",") != "aaa,bbb" { + t.Errorf("ranked = %v, want the most-logged change first", all.Ranked) + } + + one := buildModel("t", entries, "aaa") + if len(one.Notes) != 2 { + t.Fatalf("scoped notes = %d, want the two at aaa", len(one.Notes)) + } + if one.NotesTotal != 3 || one.NotesAt["aaa"] != 2 || one.NotesAt["bbb"] != 1 { + t.Errorf("a scoped view must still know the whole log: %d %v", one.NotesTotal, one.NotesAt) + } + if _, ok := one.Files["src/other.rs"]; ok { + t.Error("a file only read at another change leaked into the view") + } + // the read at bbb covered lines 1-9 of another file; lib.rs keeps only aaa's + if f := one.Files["src/lib.rs"]; f == nil || f.Reads != 1 || len(f.Notes) != 1 { + t.Errorf("src/lib.rs at aaa = %+v", f) + } + // ids are the note's position in the log, the same in both views + ids := map[string]int{} + for _, n := range all.Notes { + ids[n.Text] = n.ID + } + for _, n := range one.Notes { + if ids[n.Text] != n.ID { + t.Errorf("note %q is id %d scoped, %d unscoped", n.Text, n.ID, ids[n.Text]) + } + } + // agent colors come from the whole log, so they do not shuffle when the + // scope narrows + if len(one.Agents) != len(all.Agents) { + t.Errorf("agents = %d scoped, %d unscoped", len(one.Agents), len(all.Agents)) + } + for i := range all.Agents { + if one.Agents[i].Name != all.Agents[i].Name || one.Agents[i].Bit != all.Agents[i].Bit { + t.Errorf("agent %d differs: %+v vs %+v", i, one.Agents[i], all.Agents[i]) + } + } +} + +func TestFilterNotes(t *testing.T) { + s := testSite(t) + for _, tc := range []struct { + name string + f NoteFilter + want []string + }{ + {"all", NoteFilter{}, []string{"src/main.rs", "src/lib.rs"}}, // newest first + {"text", NoteFilter{Text: "two-level"}, []string{"src/lib.rs"}}, + {"text is case-insensitive", NoteFilter{Text: "CACHE"}, []string{"src/lib.rs"}}, + {"file substring", NoteFilter{File: "main"}, []string{"src/main.rs"}}, + {"agent", NoteFilter{Agent: "claude"}, []string{"src/main.rs"}}, + {"model", NoteFilter{Model: "gpt-5.6-sol"}, []string{"src/lib.rs"}}, + {"session", NoteFilter{Session: "s2"}, []string{"src/main.rs"}}, + {"kind", NoteFilter{Kind: "struct"}, []string{"src/lib.rs"}}, + {"from", NoteFilter{From: "2026-07-21"}, []string{"src/main.rs"}}, + {"to", NoteFilter{To: "2026-07-21"}, []string{"src/lib.rs"}}, + {"range", NoteFilter{From: "2026-07-19", To: "2026-07-26"}, []string{"src/main.rs", "src/lib.rs"}}, + {"combined", NoteFilter{Agent: "codex", Text: "map"}, []string{"src/lib.rs"}}, + {"no match", NoteFilter{Agent: "codex", Text: "nothing"}, nil}, + } { + t.Run(tc.name, func(t *testing.T) { + var got []string + for _, n := range s.FilterNotes(tc.f) { + got = append(got, n.File) + } + if strings.Join(got, ",") != strings.Join(tc.want, ",") { + t.Errorf("got %v, want %v", got, tc.want) + } + }) + } +} + +func TestFacetsAreDistinctAndSorted(t *testing.T) { + fa := testSite(t).Facets() + if strings.Join(fa.Agents, ",") != "claude,codex" { + t.Errorf("agents = %v", fa.Agents) + } + if strings.Join(fa.Kinds, ",") != "struct" { + t.Errorf("kinds = %v", fa.Kinds) + } + if strings.Join(fa.Sessions, ",") != "s1,s2" { + t.Errorf("sessions = %v", fa.Sessions) + } +} + +func TestSessionsReportWhatIsRunning(t *testing.T) { + now := time.Date(2026, 7, 25, 10, 1, 0, 0, time.UTC) + ss := testSite(t).Sessions(now, liveWindow, 10) + if len(ss) != 2 { + t.Fatalf("sessions = %d", len(ss)) + } + if ss[0].ID != "s2" || !ss[0].Live { + t.Errorf("newest session = %+v, want s2 live", ss[0]) + } + if ss[1].ID != "s1" || ss[1].Live { + t.Errorf("older session = %+v, want s1 not live", ss[1]) + } + if ss[1].LastOp != "note on src/lib.rs" || ss[1].Reads != 1 || ss[1].Greps != 1 { + t.Errorf("s1 activity = %q %d/%d", ss[1].LastOp, ss[1].Reads, ss[1].Greps) + } +} + +func TestNextNoteIDCountsPerSession(t *testing.T) { + entries := parseLog([]byte(logLines(noteA, noteB))) + if got := nextNoteID(entries, "s1"); got != 2 { + t.Errorf("s1 next = %d, want 2", got) + } + if got := nextNoteID(entries, "web:me"); got != 1 { + t.Errorf("fresh session next = %d, want 1", got) + } +} + +// The graph art in front of a templated row must not end up inside a field. +func TestParseRows(t *testing.T) { + out := "@ \x1eabc123\x1fabc1\x1fdef456\x1fdef4\x1fme@x\x1f2026-07-20 10:00\x1fmain\x1fworking copy\x1ffix the thing\n" + + "│\n" + + "~\n" + rows := parseRows([]byte(out), false) + if len(rows) != 3 { + t.Fatalf("rows = %d", len(rows)) + } + r := rows[0] + if r.Graph != "@ " || r.ID != "abc123" || r.Short != "abc1" || r.CommitShort != "def4" || + r.Author != "me@x" || r.Refs != "main" || r.Flags != "working copy" || r.Desc != "fix the thing" { + t.Errorf("row = %+v", r) + } + if !rows[1].Blank() || rows[1].Graph != "│" { + t.Errorf("graph-only row = %+v", rows[1]) + } + op := parseRows([]byte("@ \x1eopid\x1fopid1\x1f\x1f\x1fme@host\x1f2026-07-20 10:00:00\x1f\x1f10:00:05\x1fsnapshot\n"), true) + if len(op) != 1 || op[0].End != "10:00:05" || op[0].Flags != "" || op[0].Desc != "snapshot" { + t.Errorf("op row = %+v", op) + } +} + +func TestCheckRevsetRejectsFlags(t *testing.T) { + if err := checkRevset("--config=x"); err == nil { + t.Error("a leading dash must be refused, jj would read it as a flag") + } + if err := checkRevset("all() & file(x)"); err != nil { + t.Errorf("plain revset refused: %v", err) + } +} + +func TestHrefModes(t *testing.T) { + live := &page{Live: true, Root: "/"} + if got := live.Href("code", "src/a b.rs"); got != "/code/src/a%20b.rs" { + t.Errorf("live code href = %q", got) + } + live.Rev = "xyz" + if got := live.Href("code", "src/a.rs"); got != "/code/src/a.rs?rev=xyz" { + t.Errorf("live code href with rev = %q", got) + } + // notes are read against a change too, so the link keeps it + if got := live.Href("notes"); got != "/notes?rev=xyz" { + t.Errorf("live notes href = %q", got) + } + // "@" is a revset like any other; dropping it would slide the reader back + // to the change the log points at + if got := (&page{Live: true, Root: "/", Rev: "@"}).Href("files"); got != "/files?rev=%40" { + t.Errorf("href browsing @ = %q", got) + } + wide := &page{Live: true, Root: "/", Kind: "file", Rev: "xyz", Scope: "all", Path: "/code/a.rs"} + if got := wide.Href("files"); got != "/files?rev=xyz&scope=all" { + t.Errorf("wide files href = %q", got) + } + if got := wide.ScopeHref("change"); got != "/code/a.rs?rev=xyz" { + t.Errorf("narrowing href = %q", got) + } + if got := wide.BackHref(); got != "/code/a.rs?scope=all" { + t.Errorf("back href = %q", got) + } + if got := (&page{Live: true, Kind: "change", Path: "/change/abc"}).JumpPath(); got != "/files" { + t.Errorf("jump path from a change page = %q", got) + } + static := &page{Root: "../"} + if got := static.Href("code", "src/a.rs"); got != "../code/src/a.rs.html" { + t.Errorf("static code href = %q", got) + } + // a note link carries the note itself, so the page can open focused on it + n := &Note{ID: 7, File: "src/a.rs", Start: 12, End: 20} + if got := (&page{Live: true, Root: "/"}).NoteHref(n); got != "/code/src/a.rs?note=7#L12" { + t.Errorf("live note href = %q", got) + } + if got := (&page{Live: true, Root: "/", Rev: "xyz"}).NoteHref(n); got != "/code/src/a.rs?rev=xyz¬e=7#L12" { + t.Errorf("note href at a revision = %q", got) + } + if got := static.NoteHref(n); got != "../code/src/a.rs.html?note=7#L12" { + t.Errorf("static note href = %q", got) + } + if got := static.Href("change", "abc"); got != "" { + t.Errorf("static change href = %q, want none", got) + } +} + +// ── the web app, end to end ─────────────────────────────────────────────── + +// testRepo makes a one-commit jj repo and returns its path plus the change id. +func testRepo(t *testing.T) (string, string) { + t.Helper() + if _, err := exec.LookPath("jj"); err != nil { + t.Skip("jj not installed") + } + dir := t.TempDir() + env := append(os.Environ(), "JJ_USER=test", "[email protected]", "HOME="+dir) + runJJ := func(args ...string) { + t.Helper() + cmd := exec.Command("jj", args...) + cmd.Dir, cmd.Env = dir, env + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("jj %s: %v\n%s", strings.Join(args, " "), err, out) + } + } + runJJ("git", "init") + if err := os.WriteFile(filepath.Join(dir, "hello.txt"), []byte("one\ntwo\nthree\n"), 0o644); err != nil { + t.Fatal(err) + } + runJJ("describe", "-m", "first change") + change, err := resolveChange(dir, "@") + if err != nil { + t.Fatal(err) + } + return dir, change +} + +func testServer(t *testing.T) (*server, string, string) { + t.Helper() + repo, change := testRepo(t) + logPath := filepath.Join(t.TempDir(), "trace.jsonl") + entry := `{"time":"2026-07-20T10:00:00Z","op":"read","session":"s1","agent":"codex","model":"gpt-5.6-sol","dir":"` + + repo + `","change":"` + change + `","file":"hello.txt","start":1,"end":2}` + note := `{"time":"2026-07-20T10:01:00Z","op":"note","session":"s1","agent":"codex","model":"gpt-5.6-sol","dir":"` + + repo + `","change":"` + change + `","file":"hello.txt","start":2,"end":2,"note_id":1,"text":"second line matters"}` + if err := os.WriteFile(logPath, []byte(logLines(entry, note)), 0o644); err != nil { + t.Fatal(err) + } + dark, light := loadTheme("", "", "dark"), loadTheme("", "", "light") + sv := newServer(newFileLog(logPath), repo, "test", "tester", dark, light, testThemes(dark, light)) + return sv, logPath, change +} + +func get(t *testing.T, h http.Handler, path string, hx bool) *httptest.ResponseRecorder { + t.Helper() + r := httptest.NewRequest("GET", path, nil) + if hx { + r.Header.Set("HX-Request", "true") + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w +} + +func TestServerPages(t *testing.T) { + sv, _, change := testServer(t) + h := sv.handler() + for _, tc := range []struct{ path, want string }{ + {"/", "second line matters"}, + {"/", `id="filetoggle"`}, + {"/", `id="filelist"`}, + {"/files", "hello.txt"}, + {"/tree", `class="file`}, + {"/notes", "second line matters"}, + {"/code/hello.txt", "three"}, + {"/jj", "revset"}, + {"/change/" + change, "first change"}, + {"/style.css", ".am1 {"}, + {"/style.css", `data-files="hidden"`}, + {"/themes.css", `:root[data-theme="zed/one-light"]`}, + {"/themes.js", "VRSITE_THEMES"}, + {"/app.js", "notevi-mode"}, + {"/app.js", "notevi-files-hidden"}, + {"/htmx.min.js", "htmx"}, + } { + w := get(t, h, tc.path, false) + if w.Code != 200 { + t.Errorf("GET %s = %d", tc.path, w.Code) + continue + } + if !strings.Contains(w.Body.String(), tc.want) { + t.Errorf("GET %s does not mention %q", tc.path, tc.want) + } + } +} + +// The current change is on every page, and the view follows it. +func TestCurrentChangeRunsTheView(t *testing.T) { + sv, logPath, change := testServer(t) + + // a second change with nothing recorded at it + empty := filepath.Join(sv.repo, "later.txt") + if err := os.WriteFile(empty, []byte("later\n"), 0o644); err != nil { + t.Fatal(err) + } + cmd := exec.Command("jj", "new", "-m", "a later change") + cmd.Dir, cmd.Env = sv.repo, append(os.Environ(), "JJ_USER=test", "[email protected]", "HOME="+sv.repo) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("jj new: %v\n%s", err, out) + } + later, err := resolveChange(sv.repo, "@") + if err != nil { + t.Fatal(err) + } + h := sv.handler() + + // the default page is the change the log points at, scoped to it + body := get(t, h, "/", false).Body.String() + for _, want := range []string{short(change), "notes here", `class="changebar`} { + if !strings.Contains(body, want) { + t.Errorf("the index does not show the current change (%q missing)", want) + } + } + if !strings.Contains(body, "second line matters") { + t.Error("the note recorded at this change is missing") + } + + // browsing a change nothing was recorded at must not look empty: it says so + // and falls back to the whole log + body = get(t, h, "/?rev="+later, false).Body.String() + if !strings.Contains(body, "nothing recorded at this change") { + t.Errorf("no explanation for an empty change:\n%s", body[:min(len(body), 900)]) + } + if !strings.Contains(body, "second line matters") { + t.Error("the fallback should show the whole log, not nothing") + } + + // a note written from a page at that change is recorded there + form := url.Values{"text": {"written at the later change"}, "rev": {later}} + r := httptest.NewRequest("POST", "/notes", strings.NewReader(form.Encode())) + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + if w.Code != http.StatusSeeOther { + t.Fatalf("POST /notes = %d", w.Code) + } + entries := parseLog(mustRead(t, logPath)) + if last := entries[len(entries)-1]; last.Change != later { + t.Errorf("note recorded at %q, want the change being browsed %q", last.Change, later) + } + + // a note written with no change named lands on the one the log points at, + // not on the working copy, which has moved on + form = url.Values{"text": {"written with nothing named"}} + r = httptest.NewRequest("POST", "/notes", strings.NewReader(form.Encode())) + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + w = httptest.NewRecorder() + h.ServeHTTP(w, r) + entries = parseLog(mustRead(t, logPath)) + if last := entries[len(entries)-1]; last.Change != change { + t.Errorf("unaimed note recorded at %q, want the log's change %q", last.Change, change) + } + + // now that change has a note, scoping to it shows that one alone + body = get(t, h, "/notes?rev="+later, false).Body.String() + if strings.Contains(body, "second line matters") { + t.Error("a note from another change leaked into the scoped view") + } + if !strings.Contains(body, "written at the later change") { + t.Error("the note recorded here is missing") + } + // and the wide view has both, with the other change's note marked + body = get(t, h, "/notes?rev="+later+"&scope=all", false).Body.String() + if !strings.Contains(body, "second line matters") || !strings.Contains(body, "written at the later change") { + t.Error("scope=all must show every change's notes") + } + if !strings.Contains(body, "note am1 away") && !strings.Contains(body, "away") { + t.Error("a note from another change is not marked as such") + } + // links keep both the change and the scope + if !strings.Contains(body, "rev="+later+"&scope=all") { + t.Error("links drop the change or the scope") + } +} + +func mustRead(t *testing.T, path string) []byte { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return b +} + +// ── the server keeps nothing of its own ─────────────────────────────────── +// +// Every byte it writes goes to the log; everything it holds in memory is a +// cache of the log and the repo, so a restart changes nothing and a repo that +// moves underneath it is followed, not remembered. + +func repoState(t *testing.T, repo string) string { + t.Helper() + sum := sha256.New() + err := filepath.WalkDir(repo, func(path string, d os.DirEntry, err error) error { + if err != nil { + return err + } + name := d.Name() + if d.IsDir() { + if name == ".jj" || name == ".git" { + return filepath.SkipDir // caches and mtimes of their own + } + return nil + } + b, err := os.ReadFile(path) + if err != nil { + return err + } + fmt.Fprintf(sum, "%s %x\n", path, sha256.Sum256(b)) + return nil + }) + if err != nil { + t.Fatal(err) + } + // the operation log head: proof we never asked jj to do anything + op, err := jjRun(repo, "op", "log", "-n", "1", "--no-graph", "-T", "id") + if err != nil { + t.Fatal(err) + } + return fmt.Sprintf("%x %s", sum.Sum(nil), op) +} + +func TestServerWritesOnlyTheLog(t *testing.T) { + sv, logPath, change := testServer(t) + h := sv.handler() + before := repoState(t, sv.repo) + logBefore := len(mustRead(t, logPath)) + + for _, path := range []string{"/", "/files", "/notes", "/code/hello.txt", "/tree", + "/jj?revset=all()", "/jj?kind=op", "/change/" + change, "/activity", "/style.css"} { + if w := get(t, h, path, false); w.Code != 200 { + t.Errorf("GET %s = %d", path, w.Code) + } + } + form := url.Values{"text": {"a note from the browser"}, "file": {"hello.txt"}, "change": {change}} + r := httptest.NewRequest("POST", "/notes", strings.NewReader(form.Encode())) + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + h.ServeHTTP(httptest.NewRecorder(), r) + + if after := repoState(t, sv.repo); after != before { + t.Errorf("the repository changed:\n%s\n%s", before, after) + } + if len(mustRead(t, logPath)) <= logBefore { + t.Error("the note did not reach the log") + } + // nothing else appeared next to the log either + dir := filepath.Dir(logPath) + names, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + if len(names) != 1 || filepath.Join(dir, names[0].Name()) != logPath { + var got []string + for _, n := range names { + got = append(got, n.Name()) + } + t.Errorf("the server left files of its own: %v", got) + } +} + +func TestServerWritesBrowserNotesToJJSidecar(t *testing.T) { + repo, change := testRepo(t) + t.Setenv("HOME", repo) + t.Setenv("JJ_USER", "test") + t.Setenv("JJ_EMAIL", "[email protected]") + _, commit, err := resolveRevision(repo, change) + if err != nil { + t.Fatal(err) + } + log, err := sidecar.Open(repo) + if err != nil { + t.Fatal(err) + } + dark, light := loadTheme("", "", "dark"), loadTheme("", "", "light") + sv := newServer(log, repo, "test", "tester", dark, light, testThemes(dark, light)) + before, err := jjRun(repo, "status") + if err != nil { + t.Fatal(err) + } + form := url.Values{"text": {"sidecar browser note"}, "file": {"hello.txt"}, "change": {change}} + r := httptest.NewRequest("POST", "/notes", strings.NewReader(form.Encode())) + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + w := httptest.NewRecorder() + sv.handler().ServeHTTP(w, r) + if w.Code != http.StatusSeeOther { + t.Fatalf("POST /notes = %d: %s", w.Code, w.Body) + } + after, err := jjRun(repo, "status") + if err != nil { + t.Fatal(err) + } + if string(after) != string(before) { + t.Fatalf("project working copy changed:\n--- before\n%s--- after\n%s", before, after) + } + if _, err := os.Stat(filepath.Join(repo, sidecar.LogFile)); !os.IsNotExist(err) { + t.Fatalf("sidecar materialized in project working copy: %v", err) + } + b, err := log.Read() + if err != nil { + t.Fatal(err) + } + entries := parseLog(b) + last := entries[len(entries)-1] + if last.Text != "sidecar browser note" || last.Commit != commit || len(last.Commit) != 40 { + t.Fatalf("sidecar note = %+v", last) + } +} + +var agoRe = regexp.MustCompile(`\d+[smhd] ago|just now`) + +func TestServerHoldsNoStateOfItsOwn(t *testing.T) { + sv, logPath, change := testServer(t) + h := sv.handler() + form := url.Values{"text": {"written before the restart"}, "file": {"hello.txt"}, + "start": {"2"}, "change": {change}} + r := httptest.NewRequest("POST", "/notes", strings.NewReader(form.Encode())) + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + h.ServeHTTP(httptest.NewRecorder(), r) + + // a second server that has only ever seen the log file + fresh := newServer(newFileLog(logPath), sv.repo, "test", "tester", sv.theme, sv.light, sv.themes).handler() + for _, path := range []string{"/", "/notes", "/notes?scope=all", "/code/hello.txt", + "/files", "/tree", "/change/" + change} { + was := agoRe.ReplaceAllString(get(t, h, path, false).Body.String(), "AGO") + is := agoRe.ReplaceAllString(get(t, fresh, path, false).Body.String(), "AGO") + if was != is { + t.Errorf("GET %s differs after a restart — the server is holding state the log does not", path) + } + } +} + +// A change id is a pointer: editing files rewrites the commit under it. Pages +// must follow the content, not a cached snapshot of it. +func TestPagesFollowTheRepo(t *testing.T) { + sv, _, _ := testServer(t) + h := sv.handler() + if body := get(t, h, "/code/hello.txt", false).Body.String(); !strings.Contains(body, "three") { + t.Fatalf("the file did not render:\n%s", body[:min(len(body), 400)]) + } + if err := os.WriteFile(filepath.Join(sv.repo, "hello.txt"), []byte("one\ntwo\nrewritten\n"), 0o644); err != nil { + t.Fatal(err) + } + // someone else's jj command snapshots it: same change, new commit + cmd := exec.Command("jj", "status") + cmd.Dir, cmd.Env = sv.repo, append(os.Environ(), "JJ_USER=test", "[email protected]", "HOME="+sv.repo) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("jj status: %v\n%s", err, out) + } + body := get(t, h, "/code/hello.txt", false).Body.String() + if !strings.Contains(body, "rewritten") { + t.Error("the page still shows the content the change had when it was first read") + } + if strings.Contains(body, "three") { + t.Error("the old content is still on the page") + } +} + +func TestNotesFilterOverHTTP(t *testing.T) { + sv, _, _ := testServer(t) + h := sv.handler() + if b := get(t, h, "/notes/list?text=second", true).Body.String(); !strings.Contains(b, "second line matters") { + t.Error("matching filter dropped the note") + } + b := get(t, h, "/notes/list?text=absent", true).Body.String() + if strings.Contains(b, "second line matters") || !strings.Contains(b, "no notes match") { + t.Errorf("non-matching filter kept the note: %s", b) + } + if !strings.Contains(b, `id="notecount" hx-swap-oob`) { + t.Error("list fragment does not carry the out-of-band count") + } +} + +// A comment posted from the browser lands in the log, shows up in the model, +// and leaves the repository alone. +func TestAddNoteAppendsToLog(t *testing.T) { + sv, logPath, change := testServer(t) + h := sv.handler() + before, err := jjRun(sv.repo, "status") + if err != nil { + t.Fatal(err) + } + + form := url.Values{"file": {"hello.txt"}, "start": {"3"}, "end": {"3"}, + "kind": {"line"}, "text": {"written from the browser"}, "rev": {"@"}} + r := httptest.NewRequest("POST", "/notes", strings.NewReader(form.Encode())) + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + r.Header.Set("HX-Request", "true") + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + if w.Code != 200 { + t.Fatalf("POST /notes = %d: %s", w.Code, w.Body) + } + if !strings.Contains(w.Body.String(), "written from the browser") { + t.Errorf("response does not contain the new note: %s", w.Body) + } + + b, err := os.ReadFile(logPath) + if err != nil { + t.Fatal(err) + } + entries := parseLog(b) + last := entries[len(entries)-1] + if last.Op != "note" || last.Agent != "tester" || last.Session != "web:tester" || + last.File != "hello.txt" || last.Start != 3 || last.Text != "written from the browser" { + t.Errorf("appended entry = %+v", last) + } + if last.Change != change { + t.Errorf("note change = %q, want %q", last.Change, change) + } + if last.NoteID != 1 { + t.Errorf("note id = %d, want 1 (first of this session)", last.NoteID) + } + if last.Time == "" { + t.Error("appended entry has no timestamp") + } + + // visible without a restart, and the line is now marked as noted + if body := get(t, h, "/code/hello.txt", false).Body.String(); !strings.Contains(body, "written from the browser") { + t.Error("the new note is not on the file page") + } + after, err := jjRun(sv.repo, "status") + if err != nil { + t.Fatal(err) + } + if string(before) != string(after) { + t.Errorf("the repository changed:\nbefore %s\nafter %s", before, after) + } +} + +func TestFocusedNoteRendersAndAppendsAnArbitrarilyDeepThread(t *testing.T) { + sv, logPath, change := testServer(t) + h := sv.handler() + post := func(values url.Values) { + t.Helper() + values.Set("change", change) + r := httptest.NewRequest("POST", "/notes", strings.NewReader(values.Encode())) + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + if w.Code != http.StatusSeeOther { + t.Fatalf("POST /notes = %d: %s", w.Code, w.Body) + } + } + post(url.Values{"reply_to": {"1"}, "text": {"child from focused view"}}) + post(url.Values{"reply_to": {"2"}, "text": {"grandchild from focused view"}}) + post(url.Values{"text": {"[backlink to root](/note/1)"}}) + + entries := parseLog(mustRead(t, logPath)) + if len(entries) < 5 || entries[len(entries)-3].ReplyTo != 1 || entries[len(entries)-2].ReplyTo != 2 || entries[len(entries)-1].ReplyTo != 0 { + t.Fatalf("thread entries were not appended as explicit replies plus a plain mention: %+v", entries) + } + body := get(t, h, "/note/1", false).Body.String() + for _, want := range []string{ + "child from focused view", "grandchild from focused view", "backlink to root", + `class="threadnode via-reply"`, `class="threadnode via-mention"`, + `name="reply_to" value="2"`, "reply to #2", "Replies & mentions", + } { + if !strings.Contains(body, want) { + t.Errorf("focused thread is missing %q", want) + } + } + if strings.Index(body, "grandchild from focused view") < strings.Index(body, "child from focused view") { + t.Error("grandchild rendered outside its parent branch") + } +} + +func TestAddNoteRejectsCrossOriginAndEmptyText(t *testing.T) { + sv, _, _ := testServer(t) + h := sv.handler() + + form := url.Values{"text": {"hi"}, "rev": {"@"}} + r := httptest.NewRequest("POST", "/notes", strings.NewReader(form.Encode())) + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + r.Header.Set("Origin", "http://evil.example") + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + if w.Code != http.StatusForbidden { + t.Errorf("cross-origin POST = %d, want 403", w.Code) + } + + r = httptest.NewRequest("POST", "/notes", strings.NewReader(url.Values{"text": {" "}}.Encode())) + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + w = httptest.NewRecorder() + h.ServeHTTP(w, r) + if w.Code != http.StatusBadRequest { + t.Errorf("empty note = %d, want 400", w.Code) + } + + r = httptest.NewRequest("POST", "/notes", strings.NewReader(url.Values{ + "text": {"orphan"}, "reply_to": {"999"}, + }.Encode())) + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + w = httptest.NewRecorder() + h.ServeHTTP(w, r) + if w.Code != http.StatusBadRequest { + t.Errorf("missing reply target = %d, want 400", w.Code) + } +} + +func TestJJQueries(t *testing.T) { + sv, _, change := testServer(t) + h := sv.handler() + + b := get(t, h, "/jj/log?revset="+url.QueryEscape("all()"), true).Body.String() + if !strings.Contains(b, `href="/change/`+change) { + t.Errorf("jj log has no link to the change: %s", b) + } + if !strings.Contains(b, "first change") { + t.Error("jj log does not show the description") + } + b = get(t, h, "/jj/op?limit=5", true).Body.String() + if !strings.Contains(b, "at_op=") { + t.Errorf("op log has no --at-operation links: %s", b) + } + b = get(t, h, "/jj/log?revset="+url.QueryEscape("bogusfn(")+"", true).Body.String() + if !strings.Contains(b, `class="err"`) { + t.Errorf("a bad revset should report jj's error: %s", b) + } + b = get(t, h, "/jj/log?revset="+url.QueryEscape("--config=ui.paginate=never"), true).Body.String() + if !strings.Contains(b, "must not start with") { + t.Errorf("flag-like revset was not refused: %s", b) + } +} + +// Model files are shared across requests and cloned per render; run the +// handlers hard in parallel so -race can complain about it. +func TestConcurrentRequests(t *testing.T) { + sv, _, change := testServer(t) + h := sv.handler() + paths := []string{"/", "/code/hello.txt", "/notes", "/notes/list?text=second", + "/tree", "/files", "/activity?compact=1", "/change/" + change, + "/code/hello.txt?rev=" + change} + done := make(chan struct{}) + for i := 0; i < len(paths)*3; i++ { + go func(p string) { + defer func() { done <- struct{}{} }() + if w := get(t, h, p, false); w.Code != 200 { + t.Errorf("GET %s = %d", p, w.Code) + } + }(paths[i%len(paths)]) + } + for i := 0; i < len(paths)*3; i++ { + <-done + } +} + +func TestCodePageAtMissingRevision(t *testing.T) { + sv, _, _ := testServer(t) + w := get(t, sv.handler(), "/code/nope.txt", false) + if w.Code != 200 || !strings.Contains(w.Body.String(), "not present at this change") { + t.Errorf("missing file = %d: %s", w.Code, w.Body) + } +} + +func TestServerPicksUpLogAppendsFromOtherProcesses(t *testing.T) { + sv, logPath, change := testServer(t) + h := sv.handler() + if strings.Contains(get(t, h, "/notes", false).Body.String(), "from another process") { + t.Fatal("note exists before it was written") + } + f, err := os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY, 0o644) + if err != nil { + t.Fatal(err) + } + line := `{"time":"2026-07-26T10:00:00Z","op":"note","session":"s9","agent":"notevi","change":"` + + change + `","file":"hello.txt","note_id":1,"text":"from another process"}` + if _, err := f.WriteString(line + "\n"); err != nil { + t.Fatal(err) + } + f.Close() + // the poll is stat-based; make sure the mtime moved + future := time.Now().Add(time.Second) + os.Chtimes(logPath, future, future) + + if !strings.Contains(get(t, h, "/notes", false).Body.String(), "from another process") { + t.Error("an append by notevi was not picked up") + } +} diff --git a/web/assets/app.js b/web/assets/app.js new file mode 100644 index 0000000..5dd6ca0 --- /dev/null +++ b/web/assets/app.js @@ -0,0 +1,461 @@ +// app.js — the client half of notevi web. Everything here works in the static +// export too; htmx only takes over the parts that need a server (filters, +// comments, live activity, jj queries). +"use strict"; + +const root = document.documentElement; +const live = root.dataset.live === "1"; + +// ── focus: trace or notes, never both ───────────────────────────────────── +// Coverage and notes want the same pixels (line background, gutter color, +// tree markers), so the whole UI switches between them instead of layering. +function setMode(m) { + root.dataset.mode = m; + localStorage.setItem("notevi-mode", m); + for (const b of document.querySelectorAll(".mode")) + b.setAttribute("aria-pressed", String(b.dataset.mode === m)); +} +for (const b of document.querySelectorAll(".mode")) + b.addEventListener("click", () => setMode(b.dataset.mode)); +setMode(root.dataset.mode || "trace"); + +const typing = e => + /^(INPUT|TEXTAREA|SELECT)$/.test(e.target.tagName) || e.target.isContentEditable; + +// The project hub is fully server-derived; filtering is deliberately local so +// choosing a project does not create another piece of server state. +const projectFind = document.getElementById("projectfind"); +if (projectFind) { + const apply = () => { + const q = projectFind.value.trim().toLowerCase(); + for (const card of document.querySelectorAll(".project-card")) + card.hidden = !!q && !(card.dataset.project || "").toLowerCase().includes(q); + }; + projectFind.addEventListener("input", apply); + projectFind.addEventListener("search", apply); + projectFind.addEventListener("keydown", e => { + if (e.key === "Escape") { projectFind.value = ""; apply(); projectFind.blur(); } + if (e.key === "Enter") { + const first = document.querySelector(".project-card:not([hidden]) a.project-action"); + if (first) first.click(); + } + }); +} + +document.addEventListener("keydown", e => { + if (e.metaKey || e.ctrlKey || e.altKey || typing(e)) return; + if (e.key === "t") setMode(root.dataset.mode === "notes" ? "trace" : "notes"); + if (e.key === "/") { + const f = document.getElementById("filefind"); + if (f) { e.preventDefault(); f.focus(); f.select(); } + } +}); + +// ── theme ───────────────────────────────────────────────────────────────── +// Every theme this machine has is a :root block in themes.css, so wearing one +// is a single attribute — and the menu can therefore preview as it moves. +// Arrow through it or hover and the page changes under you; enter keeps what +// you are wearing, escape puts back the one you came with. +// +// themes.css and themes.js are fetched the first time the menu opens (the +// stylesheet earlier than that, from the head, when a theme is already +// chosen), so a reader who never switches pays nothing for them. +const pick = document.getElementById("themepick"); +if (pick) { + const btn = document.getElementById("themebtn"), + menu = document.getElementById("thememenu"), + find = document.getElementById("themefind"), + list = document.getElementById("themelist"); + const builtin = [ + {id: "system", name: "system", src: "follows the browser"}, + {id: "dark", name: pick.dataset.dark, src: "built with · dark"}, + {id: "light", name: pick.dataset.light, src: "built with · light"}, + ]; + let cur = localStorage.getItem("notevi-theme") || "system"; + let active = null, filled = false, pending = null; + + const wear = id => { + if (id === "system") delete root.dataset.theme; + else root.dataset.theme = id; + }; + // the name of a theme we may not have the menu for yet: kept beside the id + // so the button says something true before themes.js has loaded + const label = id => { + const b = builtin.find(t => t.id === id); + if (b) return b.name; + const t = (window.VRSITE_THEMES || []).find(t => t.id === id); + return t ? t.name : localStorage.getItem("notevi-theme-name") || + id.replace(/^[^/]*\//, "").replace(/[-_]/g, " "); + }; + btn.textContent = label(cur); + + // themes.css is a link and themes.js a script, not a fetch: the static + // export is opened from the filesystem, where fetch() is not allowed + const ensure = () => { + if (!document.getElementById("themescss")) { + const l = document.createElement("link"); + l.rel = "stylesheet"; l.id = "themescss"; l.href = pick.dataset.css; + document.head.append(l); + } + if (window.VRSITE_THEMES) return Promise.resolve(); + if (!pending) pending = new Promise(done => { + const s = document.createElement("script"); + s.src = pick.dataset.js; + s.onload = s.onerror = done; + document.head.append(s); + }); + return pending; + }; + + const row = t => { + const li = document.createElement("li"); + li.setAttribute("role", "option"); + li.id = "themeopt-" + list.children.length; + li.dataset.id = t.id; + li.dataset.q = (t.name + " " + t.src + " " + t.id).toLowerCase(); + const sw = document.createElement("span"); + sw.className = t.sw ? "sw" : "sw none"; // empty, but the names still line up + for (const c of t.sw || []) { + const chip = document.createElement("i"); + chip.style.background = c; + sw.append(chip); + } + li.append(sw); + const nm = document.createElement("span"); + nm.className = "nm"; + nm.textContent = t.name; + const src = document.createElement("span"); + src.className = "src"; + src.textContent = t.src; + li.append(nm, src); + return li; + }; + + const fill = () => { + if (filled) return; + filled = true; + // the two the site was built with are usually in the menu as well, so the + // rows for them can wear the same swatch — and "system", both at once + const all = window.VRSITE_THEMES || []; + const swOf = id => (all.find(t => t.id === id) || {}).sw; + const dsw = swOf(pick.dataset.darkid), lsw = swOf(pick.dataset.lightid); + builtin[0].sw = dsw && lsw && [...dsw.slice(0, 3), ...lsw.slice(0, 3)]; + builtin[1].sw = dsw; + builtin[2].sw = lsw; + for (const t of builtin) list.append(row(t)); + for (const t of window.VRSITE_THEMES || []) + list.append(row({...t, src: t.src + (t.dark ? " · dark" : " · light")})); + if (list.children.length === builtin.length) { + const p = document.createElement("li"); + p.className = "meta"; + p.textContent = "no zed or helix themes found on this machine"; + list.append(p); + } + }; + + const setActive = (li, preview = true) => { + if (!li || li === active) return; + if (active) { + active.classList.remove("on"); + active.removeAttribute("aria-selected"); + } + active = li; + li.classList.add("on"); + li.setAttribute("aria-selected", "true"); + find.setAttribute("aria-activedescendant", li.id); + li.scrollIntoView({block: "nearest"}); + if (preview) wear(li.dataset.id); + }; + + const rows = () => [...list.querySelectorAll("li[data-id]:not([hidden])")]; + const rowFor = id => list.querySelector('li[data-id="' + CSS.escape(id) + '"]'); + + const filter = () => { + const q = find.value.trim().toLowerCase(); + for (const li of list.children) + li.hidden = !!q && !(li.dataset.q || "").includes(q); + if (!active || active.hidden) setActive(rows()[0]); + }; + find.addEventListener("input", filter); + + const open = () => { + if (!menu.hidden) return; + menu.hidden = false; + btn.setAttribute("aria-expanded", "true"); + find.value = ""; + find.focus(); + ensure().then(() => { + fill(); + filter(); + for (const li of list.querySelectorAll("li.cur")) li.classList.remove("cur"); + const here = rowFor(cur); + if (here) here.classList.add("cur"); + setActive(here || rows()[0], false); + }); + }; + + // leaving the menu either keeps what is on screen or puts back what was + // there before it opened — nothing is stored until it is kept + const close = keep => { + if (menu.hidden) return; + if (keep && active) { + cur = active.dataset.id; + localStorage.setItem("notevi-theme", cur); + localStorage.setItem("notevi-theme-name", label(cur)); + btn.textContent = label(cur); + for (const li of list.querySelectorAll("li.cur")) li.classList.remove("cur"); + active.classList.add("cur"); + } + wear(cur); + menu.hidden = true; + btn.setAttribute("aria-expanded", "false"); + }; + + btn.addEventListener("click", () => (menu.hidden ? open() : close(false))); + // mousemove, not mouseover: arrowing scrolls rows under a still pointer, + // and the pointer must not then take the selection back + list.addEventListener("mousemove", e => { + const li = e.target.closest("li[data-id]"); + if (li) setActive(li); + }); + list.addEventListener("click", e => { + const li = e.target.closest("li[data-id]"); + if (li) { setActive(li); close(true); } + }); + find.addEventListener("keydown", e => { + if (e.key === "ArrowDown" || e.key === "ArrowUp") { + e.preventDefault(); + const all = rows(); + if (!all.length) return; + const i = all.indexOf(active), step = e.key === "ArrowDown" ? 1 : -1; + setActive(all[(i + step + all.length) % all.length]); + } else if (e.key === "Enter") { + e.preventDefault(); + close(true); + btn.focus(); + } else if (e.key === "Escape") { + e.preventDefault(); + close(false); + btn.focus(); + } + }); + document.addEventListener("click", e => { + if (!menu.hidden && !pick.contains(e.target)) close(false); + }); + document.addEventListener("keydown", e => { + if (e.key === "Escape") close(false); + if (e.key === "T" && !e.metaKey && !e.ctrlKey && !e.altKey && !typing(e)) { + e.preventDefault(); // or the T lands in the filter we just focused + open(); + } + }); +} + +// ── nav tree ────────────────────────────────────────────────────────────── +const nav = document.getElementById("nav"); +const tree = document.getElementById("tree"); +const state = JSON.parse(localStorage.getItem("notevi-tree") || "{}"); + +// The file tree can get out of the way without losing repository context or +// the navigation footer. Keep the choice across page loads in this browser. +const fileList = document.getElementById("filelist"); +const fileToggle = document.getElementById("filetoggle"); +if (fileList && fileToggle) { + const setFilesHidden = hidden => { + root.dataset.files = hidden ? "hidden" : "shown"; + fileToggle.setAttribute("aria-expanded", String(!hidden)); + fileToggle.textContent = hidden ? "show files" : "hide files"; + localStorage.setItem("notevi-files-hidden", hidden ? "1" : "0"); + }; + setFilesHidden(localStorage.getItem("notevi-files-hidden") === "1"); + fileToggle.addEventListener("click", () => setFilesHidden(root.dataset.files !== "hidden")); +} + +if (nav && tree) { + const base = nav.dataset.root, cur = nav.dataset.current; + fetch(nav.dataset.tree).then(r => r.text()).then(t => { + tree.innerHTML = t.replaceAll('href="@@', 'href="' + base); + for (const d of tree.querySelectorAll("details")) + if (d.dataset.path in state) d.open = !!state[d.dataset.path]; + if (cur) + for (const a of tree.querySelectorAll("a.file")) + if (a.dataset.path === cur) { + a.setAttribute("aria-current", "page"); + for (let e = a.parentElement; e && e !== tree; e = e.parentElement) + if (e.tagName === "DETAILS") e.open = true; + a.scrollIntoView({block: "center"}); + break; + } + tree.addEventListener("toggle", e => { + if (tree.classList.contains("filtering")) return; // filter drives open state + state[e.target.dataset.path] = e.target.open ? 1 : 0; + localStorage.setItem("notevi-tree", JSON.stringify(state)); + }, true); + }).catch(() => { + tree.innerHTML = '<p class="meta">tree needs http — use the <a href="' + + base + 'files.html">file index</a></p>'; + }); +} + +// ── find a file ─────────────────────────────────────────────────────────── +const find = document.getElementById("filefind"); +if (find && tree) { + const apply = () => { + const q = find.value.trim().toLowerCase(); + tree.classList.toggle("filtering", q !== ""); + for (const a of tree.querySelectorAll("a.file")) { + const hit = !q || a.dataset.path.toLowerCase().includes(q); + a.closest("li").hidden = !hit; + a.classList.toggle("hit", !!q && hit); + } + for (const d of tree.querySelectorAll("details")) { + const any = d.querySelector("li:not([hidden])"); + d.hidden = !!q && !any; + d.open = q ? !!any : !!state[d.dataset.path]; + } + }; + find.addEventListener("input", apply); + find.addEventListener("search", apply); + find.addEventListener("keydown", e => { + if (e.key === "Escape") { find.value = ""; apply(); find.blur(); } + if (e.key === "Enter") { + const first = tree.querySelector("li:not([hidden]) a.file"); + if (first) first.click(); + } + }); +} + +// ── code lines: jump to a note, pick a range to comment on ──────────────── +const codeLines = document.querySelectorAll("ol.code li"); +const nstart = document.getElementById("nstart"), nend = document.getElementById("nend"); +let anchor = 0; + +function lineNo(li) { return parseInt(li.id.slice(1), 10) || 0; } + +function markSelection(a, b) { + const lo = Math.min(a, b), hi = Math.max(a, b); + for (const li of codeLines) { + const n = lineNo(li); + li.classList.toggle("sel", n >= lo && n <= hi); + } + if (nstart) nstart.value = lo; + if (nend) nend.value = hi > lo ? hi : ""; +} + +for (const li of codeLines) { + li.addEventListener("click", e => { + const note = li.dataset.note && document.getElementById(li.dataset.note); + if (note && root.dataset.mode === "notes") { + note.scrollIntoView({behavior: "smooth", block: "center"}); + note.classList.remove("flash"); void note.offsetWidth; note.classList.add("flash"); + } + if (!live || root.dataset.mode !== "notes") return; + const n = lineNo(li); + if (e.shiftKey && anchor) markSelection(anchor, n); + else { anchor = n; markSelection(n, n); } + }); +} + +// ⌘/ctrl+enter posts the note form from inside the textarea +for (const ta of document.querySelectorAll(".notform textarea")) + ta.addEventListener("keydown", e => { + if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) ta.form.requestSubmit(); + }); + +// ── conversation ────────────────────────────────────────────────────────── +// A session page opened from a note lands on that note, flashed the same way +// clicking a noted line flashes it. +const conv = document.querySelector(".conv[data-anchor]"); +if (conv && conv.dataset.anchor) { + const here = document.getElementById(conv.dataset.anchor); + if (here) { + here.scrollIntoView({block: "start"}); + here.classList.remove("flash"); void here.offsetWidth; here.classList.add("flash"); + } +} + +// The trip back: a note in a conversation opens the code it was written +// about. The card is the target, so aim anywhere on it — except at the links +// it already carries. +const goTo = w => { location.href = w.dataset.href; }; +for (const w of document.querySelectorAll(".notewrap[data-href]")) { + w.addEventListener("click", e => { if (!e.target.closest("a")) goTo(w); }); + w.addEventListener("keydown", e => { + if (e.key === "Enter" || e.key === " ") { e.preventDefault(); goTo(w); } + }); +} + +// ── arriving at a note ──────────────────────────────────────────────────── +// ?note=N means someone followed a note here rather than opening the file: +// show what they came for — notes focus (coverage hides the note), the card +// flashed in the pane, the lines it covers marked. +// A permalink is the same arrival with nothing to scroll to: the page is the +// note, so it only needs the focus that shows notes at all. +if (document.body.dataset.kind === "note") setMode("notes"); + +const want = new URLSearchParams(location.search).get("note"); +if (want && document.body.dataset.kind === "file" && /^\d+$/.test(want)) { + setMode("notes"); + const card = document.getElementById("note-" + want); + if (card) { + // the card's own range, not the lines' data-note: a line belongs to the + // first note that claimed it, so overlapping notes would mark nothing + const from = +card.dataset.start, to = +card.dataset.end || +card.dataset.start; + let first = null; + for (let n = from; n > 0 && n <= to; n++) { + const li = document.getElementById("L" + n); + if (!li) continue; + li.classList.add("focus"); + first = first || li; + } + // after the browser has had its own go at the #L anchor + if (first) requestAnimationFrame(() => first.scrollIntoView({block: "center"})); + card.scrollIntoView({block: "nearest"}); + card.classList.remove("flash"); void card.offsetWidth; card.classList.add("flash"); + } +} + +// ── note filters ────────────────────────────────────────────────────────── +// Live pages let the server filter (htmx); the static export filters the +// rendered list in place, so the same form works either way. +const filters = document.getElementById("notefilters"); +if (filters) { + const count = document.getElementById("notecount"); + const val = n => (filters.elements[n] ? filters.elements[n].value.trim().toLowerCase() : ""); + const applyLocal = () => { + const text = val("text"), file = val("file"), agent = val("agent"), + model = val("model"), session = val("session"), kind = val("kind"), + from = val("from"), to = val("to"); + let shown = 0; + for (const art of document.querySelectorAll("#notelist .note")) { + // the whole rendered body, not its first <p>: a note is markdown, so it + // may open with a list or a code fence and run to several blocks + const d = art.dataset, el = art.querySelector(".body"); + const body = (el ? el.textContent : "").toLowerCase(); + const ok = + (!text || body.includes(text)) && + (!file || (d.file || "").toLowerCase().includes(file)) && + (!agent || d.agent === filters.elements.agent.value) && + (!model || d.model === filters.elements.model.value) && + (!session || d.session === filters.elements.session.value) && + (!kind || d.kind === filters.elements.kind.value) && + (!from || (d.date && d.date >= from)) && + (!to || (d.date && d.date <= to)); + art.hidden = !ok; + if (ok) shown++; + } + if (count) count.textContent = shown; + }; + if (!live) { + filters.addEventListener("input", applyLocal); + filters.addEventListener("change", applyLocal); + filters.addEventListener("submit", e => { e.preventDefault(); applyLocal(); }); + } + const clear = document.getElementById("clearfilters"); + if (clear) clear.addEventListener("click", () => { + filters.reset(); + for (const el of filters.elements) if (el.name) el.value = ""; + if (live) window.htmx && htmx.trigger(filters, "change"); + else applyLocal(); + }); +} diff --git a/web/assets/bash.scm b/web/assets/bash.scm new file mode 100644 index 0000000..4c7926a --- /dev/null +++ b/web/assets/bash.scm @@ -0,0 +1,21 @@ +; Bash highlights, from tree-sitter/tree-sitter-bash v0.25.1 +; queries/highlights.scm (MIT). Reordered so expansions stay visible inside the +; strings that contain them, and capture names mapped onto zed syntax keys. +; Upstream's @embedded captures are dropped: zed paints `embedded` as plain +; foreground, so they only cost query time. + +["$" "&&" "||" ">" ">>" "<" "|" ";" "=" "!"] @operator + +["case" "do" "done" "elif" "else" "esac" "export" "fi" "for" "function" "if" + "in" "local" "readonly" "select" "then" "unset" "until" "while"] @keyword + +[(string) (raw_string) (heredoc_body) (heredoc_start)] @string +(variable_name) @property +(file_descriptor) @number + +(command_name) @function +(function_definition name: (word) @function) +((command (_) @constant) + (#match? @constant "^-")) + +(comment) @comment diff --git a/web/assets/bemtevi.svg b/web/assets/bemtevi.svg new file mode 100644 index 0000000..e8f7367 --- /dev/null +++ b/web/assets/bemtevi.svg @@ -0,0 +1,31 @@ +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="bem-te-vi"> + <title>bem-te-vi</title> + <!-- + Placeholder mark: a stylized bem-te-vi (great kiskadee). Transparent + background, no external references, legible down to 16px. The orange sliver + at the crown is the patch the bird keeps hidden under its black cap — the + same joke the tool's name makes about its notes. + --> + <defs> + <path id="nv-body" d="M18 32C18 24 27 20 35 21 43 22 49 30 50 39L62 51 60 57 46 49C39 54 23 53 18 42Z"/> + <clipPath id="nv-bodyclip"><use href="#nv-body"/></clipPath> + <clipPath id="nv-headclip"><circle cx="21" cy="24" r="12"/></clipPath> + </defs> + + <use href="#nv-body" fill="#8A5A34"/> + <g clip-path="url(#nv-bodyclip)"> + <ellipse cx="24" cy="46" rx="21" ry="16" fill="#F5C518"/> + <ellipse cx="41" cy="39" rx="10" ry="5.5" transform="rotate(24 41 39)" fill="#7A4E2C"/> + </g> + + <circle cx="21" cy="24" r="12" fill="#F4F1E8"/> + <g clip-path="url(#nv-headclip)"> + <rect x="7" y="10" width="30" height="8" fill="#23201C"/> + <ellipse cx="21" cy="13.2" rx="5" ry="1.9" fill="#F08B1D"/> + <rect x="7" y="18" width="30" height="4" fill="#F4F1E8"/> + <rect x="7" y="22" width="30" height="6" fill="#23201C"/> + </g> + <circle cx="16" cy="24.5" r="2.4" fill="#F4F1E8"/> + <circle cx="16" cy="24.5" r="1.3" fill="#23201C"/> + <path d="M12 23.5.5 28 12 32.5Z" fill="#23201C"/> +</svg> diff --git a/web/assets/c.scm b/web/assets/c.scm new file mode 100644 index 0000000..789bf93 --- /dev/null +++ b/web/assets/c.scm @@ -0,0 +1,36 @@ +; C highlights, from tree-sitter/tree-sitter-c v0.24.2 queries/highlights.scm +; (MIT). Reordered for later-patterns-win, capture names mapped onto zed syntax +; keys (preprocessor directives get @preproc rather than upstream's @keyword, +; which zed themes colour separately). Also loaded ahead of cpp.scm, the way +; upstream composes the C++ highlights. + +["(" ")" "[" "]" "{" "}"] @punctuation.bracket +[";" "," "."] @punctuation.delimiter +["--" "-" "-=" "->" "=" "!=" "*" "&" "&&" "+" "++" "+=" "<" "==" ">" + "||"] @operator + +["break" "case" "const" "continue" "default" "do" "else" "enum" "extern" + "for" "if" "inline" "return" "sizeof" "static" "struct" "switch" "typedef" + "union" "volatile" "while"] @keyword + +["#define" "#elif" "#else" "#endif" "#if" "#ifdef" "#ifndef" + "#include"] @preproc +(preproc_directive) @preproc + +[(type_identifier) (primitive_type) (sized_type_specifier)] @type +(field_identifier) @property +(statement_identifier) @label +((identifier) @constant + (#match? @constant "^[A-Z][A-Z0-9_]*$")) + +(call_expression function: (identifier) @function) +(call_expression function: (field_expression + field: (field_identifier) @function.method)) +(function_declarator declarator: (identifier) @function) +(preproc_function_def name: (identifier) @function) + +(number_literal) @number +(null) @constant +[(string_literal) (char_literal) (system_lib_string)] @string +(escape_sequence) @string.escape +(comment) @comment diff --git a/web/assets/cpp.scm b/web/assets/cpp.scm new file mode 100644 index 0000000..e939a7a --- /dev/null +++ b/web/assets/cpp.scm @@ -0,0 +1,25 @@ +; C++ highlights, from tree-sitter/tree-sitter-cpp v0.23.4 +; queries/highlights.scm (MIT). A supplement loaded after c.scm, as upstream +; composes it, so these patterns win. Capture names mapped onto zed syntax +; keys; `this` gets @variable.special to match what rust.scm does for `self`. + +["catch" "class" "co_await" "co_return" "co_yield" "constexpr" "constinit" + "consteval" "delete" "explicit" "final" "friend" "mutable" "namespace" + "noexcept" "new" "override" "private" "protected" "public" "template" + "throw" "try" "typename" "using" "concept" "requires" "virtual"] @keyword + +(auto) @type +((namespace_identifier) @type + (#match? @type "^[A-Z]")) + +(call_expression function: (qualified_identifier + name: (identifier) @function)) +(template_function name: (identifier) @function) +(template_method name: (field_identifier) @function.method) +(function_declarator declarator: (qualified_identifier + name: (identifier) @function)) +(function_declarator declarator: (field_identifier) @function.method) + +(raw_string_literal) @string +(this) @variable.special +(null "nullptr" @constant) diff --git a/web/assets/go.scm b/web/assets/go.scm new file mode 100644 index 0000000..56f676c --- /dev/null +++ b/web/assets/go.scm @@ -0,0 +1,34 @@ +; Go highlights, from tree-sitter/tree-sitter-go v0.25.0 queries/highlights.scm +; (MIT). Reordered — upstream is written first-pattern-wins, this engine paints +; later patterns over earlier ones — capture names mapped onto zed syntax keys, +; and the builtin-function #match? turned into #any-of?, which needs no regex. + +["(" ")" "[" "]" "{" "}"] @punctuation.bracket +[";" "," "." ":"] @punctuation.delimiter +["--" "-" "-=" ":=" "!" "!=" "..." "*" "*=" "/" "/=" "&" "&&" "&=" "%" "%=" + "^" "^=" "+" "++" "+=" "<-" "<" "<<" "<<=" "<=" "=" "==" ">" ">=" ">>" ">>=" + "|" "|=" "||" "~"] @operator + +["break" "case" "chan" "const" "continue" "default" "defer" "else" + "fallthrough" "for" "func" "go" "goto" "if" "import" "interface" "map" + "package" "range" "return" "select" "struct" "switch" "type" "var"] @keyword + +(type_identifier) @type +(field_identifier) @property +(label_name) @label + +(function_declaration name: (identifier) @function) +(method_declaration name: (field_identifier) @function.method) +(call_expression function: (identifier) @function) +(call_expression function: (selector_expression + field: (field_identifier) @function.method)) +((call_expression function: (identifier) @function.builtin) + (#any-of? @function.builtin "append" "cap" "clear" "close" "complex" "copy" + "delete" "imag" "len" "make" "max" "min" "new" "panic" "print" "println" + "real" "recover")) + +[(int_literal) (float_literal) (imaginary_literal)] @number +[(true) (false) (nil) (iota)] @constant +[(interpreted_string_literal) (raw_string_literal) (rune_literal)] @string +(escape_sequence) @string.escape +(comment) @comment diff --git a/web/assets/htmx.min.js b/web/assets/htmx.min.js new file mode 100644 index 0000000..c62505f --- /dev/null +++ b/web/assets/htmx.min.js @@ -0,0 +1,2 @@ +/* htmx 2.0.4 — https://htmx.org — Zero-Clause BSD — vendored so the app has no network deps */ +var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=cn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true},parseInterval:null,_:null,version:"2.0.4"};Q.onLoad=j;Q.process=kt;Q.on=ye;Q.off=be;Q.trigger=he;Q.ajax=Rn;Q.find=u;Q.findAll=x;Q.closest=g;Q.remove=z;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=$e;Q.defineExtension=Fn;Q.removeExtension=Bn;Q.logAll=V;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:le,canAccessLocalStorage:B,findThisElement:Se,filterValues:hn,swap:$e,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:o,getExpressionVars:En,getHeaders:fn,getInputValues:cn,getInternalData:ie,getSwapSpecification:gn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:ce,makeSettleInfo:xn,oobSwap:He,querySelectorExt:ae,settleImmediately:Kt,shouldCancel:ht,triggerEvent:he,triggerErrorEvent:fe,withExtensions:Ft};const r=["get","post","put","delete","patch"];const H=r.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function c(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ne(){return document}function m(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function o(e,t){while(e&&!t(e)){e=c(e)}return e||null}function i(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function re(t,n){let r=null;o(t,function(e){return!!(r=i(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function T(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function q(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function A(e){const t=ne().createElement("script");se(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function N(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(N(e)){const t=A(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){O(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/<head(\s[^>]*)?>[\s\S]*?<\/head>/i,"");const n=T(t);let r;if(n==="html"){r=new DocumentFragment;const i=q(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=q(t);L(r,i.body);r.title=i.title}else{const i=q('<body><template class="internal-htmx-wrapper">'+t+"</template></body>");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return typeof e==="function"}function D(e){return t(e,"Object")}function ie(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e<t.length;e++){n.push(t[e])}}return n}function se(t,n){if(t){for(let e=0;e<t.length;e++){n(t[e])}}}function X(e){const t=e.getBoundingClientRect();const n=t.top;const r=t.bottom;return n<window.innerHeight&&r>=0}function le(e){return e.getRootNode({composed:true})===document}function F(e){return e.trim().split(/\s+/)}function ce(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function S(e){try{return JSON.parse(e)}catch(e){O(e);return null}}function B(){const e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function U(t){try{const e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function e(e){return vn(ne().body,function(){return eval(e)})}function j(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Q.logger=null}function u(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return u(ne(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(ne(),e)}}function E(){return window}function z(e,t){e=y(e);if(t){E().setTimeout(function(){z(e);e=null},t)}else{c(e).removeChild(e)}}function ue(e){return e instanceof Element?e:null}function $(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function f(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ue(y(e));if(!e){return}if(n){E().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ue(y(e));if(!r){return}if(n){E().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=y(e);e.classList.toggle(t)}function Z(e,t){e=y(e);se(e.parentElement.children,function(e){G(e,t)});K(ue(e),t)}function g(e,t){e=ue(y(e));if(e&&e.closest){return e.closest(t)}else{do{if(e==null||h(e,t)){return e}}while(e=e&&ue(c(e)));return null}}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function ge(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function p(t,r,n){if(r.indexOf("global ")===0){return p(t,r.slice(7),true)}t=y(t);const o=[];{let t=0;let n=0;for(let e=0;e<r.length;e++){const l=r[e];if(l===","&&t===0){o.push(r.substring(n,e));n=e+1;continue}if(l==="<"){t++}else if(l==="/"&&e<r.length-1&&r[e+1]===">"){t--}}if(n<r.length){o.push(r.substring(n))}}const i=[];const s=[];while(o.length>0){const r=ge(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ue(t),ge(r.substr(8)))}else if(r.indexOf("find ")===0){e=u(f(t),ge(r.substr(5)))}else if(r==="next"||r==="nextElementSibling"){e=ue(t).nextElementSibling}else if(r.indexOf("next ")===0){e=pe(t,ge(r.substr(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ue(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,ge(r.substr(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=m(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=f(m(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var pe=function(t,e,n){const r=f(m(t,n)).querySelectorAll(e);for(let e=0;e<r.length;e++){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_PRECEDING){return o}}};var me=function(t,e,n){const r=f(m(t,n)).querySelectorAll(e);for(let e=r.length-1;e>=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ae(e,t){if(typeof e!=="string"){return p(e,t)[0]}else{return p(ne().body,e)[0]}}function y(e,t){if(typeof e==="string"){return u(f(t)||document,e)}else{return e}}function xe(e,t,n,r){if(k(t)){return{target:ne().body,event:J(e),listener:t,options:n}}else{return{target:y(e),event:J(t),listener:n,options:r}}}function ye(t,n,r,o){Vn(function(){const e=xe(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=k(n);return e?n:r}function be(t,n,r){Vn(function(){const e=xe(t,n,r);e.target.removeEventListener(e.event,e.listener)});return k(n)?n:r}const ve=ne().createElement("output");function we(e,t){const n=re(e,t);if(n){if(n==="this"){return[Se(e,t)]}else{const r=p(e,n);if(r.length===0){O('The selector "'+n+'" on '+t+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ue(o(e,function(e){return te(ue(e),t)!=null}))}function Ee(e){const t=re(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ae(e,t)}}else{const n=ie(e);if(n.boosted){return ne().body}else{return e}}}function Ce(t){const n=Q.config.attributesToSettle;for(let e=0;e<n.length;e++){if(t===n[e]){return true}}return false}function Oe(t,n){se(t.attributes,function(e){if(!n.hasAttribute(e.name)&&Ce(e.name)){t.removeAttribute(e.name)}});se(n.attributes,function(e){if(Ce(e.name)){t.setAttribute(e.name,e.value)}})}function Re(t,e){const n=Un(e);for(let e=0;e<n.length;e++){const r=n[e];try{if(r.isInlineSwap(t)){return true}}catch(e){O(e)}}return t==="outerHTML"}function He(e,o,i,t){t=t||ne();let n="#"+ee(o,"id");let s="outerHTML";if(e==="true"){}else if(e.indexOf(":")>0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=p(t,n,false);if(r){se(r,function(e){let t;const n=o.cloneNode(true);t=ne().createDocumentFragment();t.appendChild(n);if(!Re(s,e)){t=f(n)}const r={shouldSwap:true,target:e,fragment:t};if(!he(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);_e(s,e,e,t,i);Te()}se(i.elts,function(e){he(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(ne().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Te(){const e=u("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=u("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){se(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=te(e,"id");const n=ne().getElementById(t);if(n!=null){if(e.moveBefore){let e=u("#--htmx-preserve-pantry--");if(e==null){ne().body.insertAdjacentHTML("afterend","<div id='--htmx-preserve-pantry--'></div>");e=u("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Le(l,e,c){se(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=f(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Ae(e){return function(){G(e,Q.config.addedClass);kt(ue(e));Ne(f(e));he(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=$(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function a(e,t,n,r){Le(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ue(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ae(o))}}}function Ie(e,t){let n=0;while(n<e.length){t=(t<<5)-t+e.charCodeAt(n++)|0}return t}function Pe(t){let n=0;if(t.attributes){for(let e=0;e<t.attributes.length;e++){const r=t.attributes[e];if(r.value){n=Ie(r.name,n);n=Ie(r.value,n)}}}return n}function ke(t){const n=ie(t);if(n.onHandlers){for(let e=0;e<n.onHandlers.length;e++){const r=n.onHandlers[e];be(t,r.event,r.listener)}delete n.onHandlers}}function De(e){const t=ie(e);if(t.timeout){clearTimeout(t.timeout)}if(t.listenerInfos){se(t.listenerInfos,function(e){if(e.on){be(e.on,e.trigger,e.listener)}})}ke(e);se(Object.keys(t),function(e){if(e!=="firstInitCompleted")delete t[e]})}function b(e){he(e,"htmx:beforeCleanupElement");De(e);if(e.children){se(e.children,function(e){b(e)})}}function Me(t,e,n){if(t instanceof Element&&t.tagName==="BODY"){return Ve(t,e,n)}let r;const o=t.previousSibling;const i=c(t);if(!i){return}a(i,t,e,n);if(o==null){r=i.firstChild}else{r=o.nextSibling}n.elts=n.elts.filter(function(e){return e!==t});while(r&&r!==t){if(r instanceof Element){n.elts.push(r)}r=r.nextSibling}b(t);if(t instanceof Element){t.remove()}else{t.parentNode.removeChild(t)}}function Xe(e,t,n){return a(e,e.firstChild,t,n)}function Fe(e,t,n){return a(c(e),e,t,n)}function Be(e,t,n){return a(e,null,t,n)}function Ue(e,t,n){return a(c(e),e.nextSibling,t,n)}function je(e){b(e);const t=c(e);if(t){return t.removeChild(e)}}function Ve(e,t,n){const r=e.firstChild;a(e,r,t,n);if(r){while(r.nextSibling){b(r.nextSibling);e.removeChild(r.nextSibling)}b(r);e.removeChild(r)}}function _e(t,e,n,r,o){switch(t){case"none":return;case"outerHTML":Me(n,r,o);return;case"afterbegin":Xe(n,r,o);return;case"beforebegin":Fe(n,r,o);return;case"beforeend":Be(n,r,o);return;case"afterend":Ue(n,r,o);return;case"delete":je(n);return;default:var i=Un(e);for(let e=0;e<i.length;e++){const s=i[e];try{const l=s.handleSwap(t,n,r,o);if(l){if(Array.isArray(l)){for(let e=0;e<l.length;e++){const c=l[e];if(c.nodeType!==Node.TEXT_NODE&&c.nodeType!==Node.COMMENT_NODE){o.tasks.push(Ae(c))}}}return}}catch(e){O(e)}}if(t==="innerHTML"){Ve(n,r,o)}else{_e(Q.config.defaultSwapStyle,e,n,r,o)}}}function ze(e,n,r){var t=x(e,"[hx-swap-oob], [data-hx-swap-oob]");se(t,function(e){if(Q.config.allowNestedOobSwaps||e.parentElement===null){const t=te(e,"hx-swap-oob");if(t!=null){He(t,e,n,r)}}else{e.removeAttribute("hx-swap-oob");e.removeAttribute("data-hx-swap-oob")}});return t.length>0}function $e(e,t,r,o){if(!o){o={}}e=y(e);const i=o.contextElement?m(o.contextElement,false):ne();const n=document.activeElement;let s={};try{s={elt:n,start:n?n.selectionStart:null,end:n?n.selectionEnd:null}}catch(e){}const l=xn(e);if(r.swapStyle==="textContent"){e.textContent=t}else{let n=P(t);l.title=n.title;if(o.selectOOB){const u=o.selectOOB.split(",");for(let t=0;t<u.length;t++){const a=u[t].split(":",2);let e=a[0].trim();if(e.indexOf("#")===0){e=e.substring(1)}const f=a[1]||"true";const h=n.querySelector("#"+e);if(h){He(f,h,l,i)}}}ze(n,l,i);se(x(n,"template"),function(e){if(e.content&&ze(e.content,l,i)){e.remove()}});if(o.select){const d=ne().createDocumentFragment();se(n.querySelectorAll(o.select),function(e){d.appendChild(e)});n=d}qe(n);_e(r.swapStyle,o.contextElement,e,n,l);Te()}if(s.elt&&!le(s.elt)&&ee(s.elt,"id")){const g=document.getElementById(ee(s.elt,"id"));const p={preventScroll:r.focusScroll!==undefined?!r.focusScroll:!Q.config.defaultFocusScroll};if(g){if(s.start&&g.setSelectionRange){try{g.setSelectionRange(s.start,s.end)}catch(e){}}g.focus(p)}}e.classList.remove(Q.config.swappingClass);se(l.elts,function(e){if(e.classList){e.classList.add(Q.config.settlingClass)}he(e,"htmx:afterSwap",o.eventInfo)});if(o.afterSwapCallback){o.afterSwapCallback()}if(!r.ignoreTitle){kn(l.title)}const c=function(){se(l.tasks,function(e){e.call()});se(l.elts,function(e){if(e.classList){e.classList.remove(Q.config.settlingClass)}he(e,"htmx:afterSettle",o.eventInfo)});if(o.anchor){const e=ue(y("#"+o.anchor));if(e){e.scrollIntoView({block:"start",behavior:"auto"})}}yn(l.elts,r);if(o.afterSettleCallback){o.afterSettleCallback()}};if(r.settleDelay>0){E().setTimeout(c,r.settleDelay)}else{c()}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=S(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(D(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}he(n,i,e)}}}else{const s=r.split(",");for(let e=0;e<s.length;e++){he(n,s[e].trim(),[])}}}const Ke=/\s/;const v=/[\s,]/;const Ge=/[_$a-zA-Z]/;const We=/[_$a-zA-Z0-9]/;const Ze=['"',"'","/"];const w=/[^\s]/;const Ye=/[{(]/;const Qe=/[})]/;function et(e){const t=[];let n=0;while(n<e.length){if(Ge.exec(e.charAt(n))){var r=n;while(We.exec(e.charAt(n+1))){n++}t.push(e.substring(r,n+1))}else if(Ze.indexOf(e.charAt(n))!==-1){const o=e.charAt(n);var r=n;n++;while(n<e.length&&e.charAt(n)!==o){if(e.charAt(n)==="\\"){n++}n++}t.push(e.substring(r,n+1))}else{const i=e.charAt(n);t.push(i)}n++}return t}function tt(e,t,n){return Ge.exec(e.charAt(0))&&e!=="true"&&e!=="false"&&e!=="this"&&e!==n&&t!=="."}function nt(r,o,i){if(o[0]==="["){o.shift();let e=1;let t=" return (function("+i+"){ return (";let n=null;while(o.length>0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=vn(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(ne().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function C(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=C(e,Qe).trim();e.shift()}else{t=C(e,v)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{C(o,w);const l=o.length;const c=C(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};C(o,w);u.pollInterval=d(C(o,/[,\[\s]/));C(o,w);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const a={trigger:c};var i=nt(e,o,"event");if(i){a.eventFilter=i}C(o,w);while(o.length>0&&o[0]!==","){const f=o.shift();if(f==="changed"){a.changed=true}else if(f==="once"){a.once=true}else if(f==="consume"){a.consume=true}else if(f==="delay"&&o[0]===":"){o.shift();a.delay=d(C(o,v))}else if(f==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=C(o,v);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}a.from=s}else if(f==="target"&&o[0]===":"){o.shift();a.target=rt(o)}else if(f==="throttle"&&o[0]===":"){o.shift();a.throttle=d(C(o,v))}else if(f==="queue"&&o[0]===":"){o.shift();a.queue=C(o,v)}else if(f==="root"&&o[0]===":"){o.shift();a[f]=rt(o)}else if(f==="threshold"&&o[0]===":"){o.shift();a[f]=C(o,v)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}r.push(a)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=te(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){ie(e).cancelled=true}function ct(e,t,n){const r=ie(e);r.timeout=E().setTimeout(function(){if(le(e)&&r.cancelled!==true){if(!gt(n,e,Mt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function at(e){return g(e,Q.config.disableSelector)}function ft(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=ne().location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){pt(t,function(e,t){const n=ue(e);if(at(n)){b(n);return}de(r,o,n,t)},n,e,true)})}}function ht(e,t){const n=ue(t);if(!n){return false}if(e.type==="submit"||e.type==="click"){if(n.tagName==="FORM"){return true}if(h(n,'input[type="submit"], button')&&(h(n,"[form]")||g(n,"form")!==null)){return true}if(n instanceof HTMLAnchorElement&&n.href&&(n.getAttribute("href")==="#"||n.getAttribute("href").indexOf("#")!==0)){return true}}return false}function dt(e,t){return ie(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function gt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(ne().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function pt(l,c,e,u,a){const f=ie(l);let t;if(u.from){t=p(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in f)){f.lastValue=new WeakMap}t.forEach(function(e){if(!f.lastValue.has(u)){f.lastValue.set(u,new WeakMap)}f.lastValue.get(u).set(e,e.value)})}se(t,function(i){const s=function(e){if(!le(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(a||ht(e,l)){e.preventDefault()}if(gt(u,l,e)){return}const t=ie(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ue(e.target),u.target)){return}}if(u.once){if(f.triggeredOnce){return}else{f.triggeredOnce=true}}if(u.changed){const n=event.target;const r=n.value;const o=f.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(f.delayed){clearTimeout(f.delayed)}if(f.throttle){return}if(u.throttle>0){if(!f.throttle){he(l,"htmx:trigger");c(l,e);f.throttle=E().setTimeout(function(){f.throttle=null},u.throttle)}}else if(u.delay>0){f.delayed=E().setTimeout(function(){he(l,"htmx:trigger");c(l,e)},u.delay)}else{he(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let xt=null;function yt(){if(!xt){xt=function(){mt=true};window.addEventListener("scroll",xt);window.addEventListener("resize",xt);setInterval(function(){if(mt){mt=false;se(ne().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&X(e)){e.setAttribute("data-hx-revealed","true");const t=ie(e);if(t.initHash){he(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){he(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;he(e,"htmx:trigger");t(e)}};if(r>0){E().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;se(r,function(r){if(s(t,"hx-"+r)){const o=te(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ue(e);if(g(n,Q.config.disableSelector)){b(n);return}de(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){yt();pt(r,n,t,e);bt(ue(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ae(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e<t.length;e++){const n=t[e];if(n.isIntersecting){he(r,"intersect");break}}},o);i.observe(ue(r));pt(ue(r),n,t,e)}else if(!t.firstInitCompleted&&e.trigger==="load"){if(!gt(e,r,Mt("load",{elt:r}))){vt(ue(r),n,t,e.delay)}}else if(e.pollInterval>0){t.polling=true;ct(ue(r),n,e)}else{pt(r,n,t,e)}}function Et(e){const t=ue(e);if(!t){return false}const n=t.attributes;for(let e=0;e<n.length;e++){const r=n[e].name;if(l(r,"hx-on:")||l(r,"data-hx-on:")||l(r,"hx-on-")||l(r,"data-hx-on-")){return true}}return false}const Ct=(new XPathEvaluator).createExpression('.//*[@*[ starts-with(name(), "hx-on:") or starts-with(name(), "data-hx-on:") or'+' starts-with(name(), "hx-on-") or starts-with(name(), "data-hx-on-") ]]');function Ot(e,t){if(Et(e)){t.push(ue(e))}const n=Ct.evaluate(e);let r=null;while(r=n.iterateNext())t.push(ue(r))}function Rt(e){const t=[];if(e instanceof DocumentFragment){for(const n of e.childNodes){Ot(n,t)}}else{Ot(e,t)}return t}function Ht(e){if(e.querySelectorAll){const n=", [hx-boost] a, [data-hx-boost] a, a[hx-boost], a[data-hx-boost]";const r=[];for(const i in Mn){const s=Mn[i];if(s.getSelectors){var t=s.getSelectors();if(t){r.push(t)}}}const o=e.querySelectorAll(H+n+", form, [type='submit'],"+" [hx-ext], [data-hx-ext], [hx-trigger], [data-hx-trigger]"+r.flat().map(e=>", "+e).join(""));return o}else{return[]}}function Tt(e){const t=g(ue(e.target),"button, input[type='submit']");const n=Lt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Lt(e);if(t){t.lastButtonClicked=null}}function Lt(e){const t=g(ue(e.target),"button, input[type='submit']");if(!t){return}const n=y("#"+ee(t,"form"),t.getRootNode())||g(t,"form");if(!n){return}return ie(n)}function At(e){e.addEventListener("click",Tt);e.addEventListener("focusin",Tt);e.addEventListener("focusout",qt)}function Nt(t,e,n){const r=ie(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){vn(t,function(){if(at(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function It(t){ke(t);for(let e=0;e<t.attributes.length;e++){const n=t.attributes[e].name;const r=t.attributes[e].value;if(l(n,"hx-on")||l(n,"data-hx-on")){const o=n.indexOf("-on")+3;const i=n.slice(o,o+1);if(i==="-"||i===":"){let e=n.slice(o+1);if(l(e,":")){e="htmx"+e}else if(l(e,"-")){e="htmx:"+e.slice(1)}else if(l(e,"htmx-")){e="htmx:"+e.slice(5)}Nt(t,e,r)}}}}function Pt(t){if(g(t,Q.config.disableSelector)){b(t);return}const n=ie(t);const e=Pe(t);if(n.initHash!==e){De(t);n.initHash=e;he(t,"htmx:beforeProcessNode");const r=st(t);const o=wt(t,n,r);if(!o){if(re(t,"hx-boost")==="true"){ft(t,n,r)}else if(s(t,"hx-trigger")){r.forEach(function(e){St(t,e,n,function(){})})}}if(t.tagName==="FORM"||ee(t,"type")==="submit"&&s(t,"form")){At(t)}n.firstInitCompleted=true;he(t,"htmx:afterProcessNode")}}function kt(e){e=y(e);if(g(e,Q.config.disableSelector)){b(e);return}Pt(e);se(Ht(e),function(e){Pt(e)});se(Rt(e),It)}function Dt(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function Mt(e,t){let n;if(window.CustomEvent&&typeof window.CustomEvent==="function"){n=new CustomEvent(e,{bubbles:true,cancelable:true,composed:true,detail:t})}else{n=ne().createEvent("CustomEvent");n.initCustomEvent(e,true,true,t)}return n}function fe(e,t,n){he(e,t,ce({error:t},n))}function Xt(e){return e==="htmx:afterProcessNode"}function Ft(e,t){se(Un(e),function(e){try{t(e)}catch(e){O(e)}})}function O(e){if(console.error){console.error(e)}else if(console.log){console.log("ERROR: ",e)}}function he(e,t,n){e=y(e);if(n==null){n={}}n.elt=e;const r=Mt(t,n);if(Q.logger&&!Xt(t)){Q.logger(e,t,n)}if(n.error){O(n.error);he(e,"htmx:error",{errorInfo:n})}let o=e.dispatchEvent(r);const i=Dt(t);if(o&&i!==t){const s=Mt(i,r.detail);o=o&&e.dispatchEvent(s)}Ft(ue(e),function(e){o=o&&(e.onEvent(t,r)!==false&&!r.defaultPrevented)});return o}let Bt=location.pathname+location.search;function Ut(){const e=ne().querySelector("[hx-history-elt],[data-hx-history-elt]");return e||ne().body}function jt(t,e){if(!B()){return}const n=_t(e);const r=ne().title;const o=window.scrollY;if(Q.config.historyCacheSize<=0){localStorage.removeItem("htmx-history-cache");return}t=U(t);const i=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e<i.length;e++){if(i[e].url===t){i.splice(e,1);break}}const s={url:t,content:n,title:r,scroll:o};he(ne().body,"htmx:historyItemCreated",{item:s,cache:i});i.push(s);while(i.length>Q.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(ne().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Vt(t){if(!B()){return null}t=U(t);const n=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e<n.length;e++){if(n[e].url===t){return n[e]}}return null}function _t(e){const t=Q.config.requestClass;const n=e.cloneNode(true);se(x(n,"."+t),function(e){G(e,t)});se(x(n,"[data-disabled-by-htmx]"),function(e){e.removeAttribute("disabled")});return n.innerHTML}function zt(){const e=Ut();const t=Bt||location.pathname+location.search;let n;try{n=ne().querySelector('[hx-history="false" i],[data-hx-history="false" i]')}catch(e){n=ne().querySelector('[hx-history="false"],[data-hx-history="false"]')}if(!n){he(ne().body,"htmx:beforeHistorySave",{path:t,historyElt:e});jt(t,e)}if(Q.config.historyEnabled)history.replaceState({htmx:true},ne().title,window.location.href)}function $t(e){if(Q.config.getCacheBusterParam){e=e.replace(/org\.htmx\.cache-buster=[^&]*&?/,"");if(Y(e,"&")||Y(e,"?")){e=e.slice(0,-1)}}if(Q.config.historyEnabled){history.pushState({htmx:true},"",e)}Bt=e}function Jt(e){if(Q.config.historyEnabled)history.replaceState({htmx:true},"",e);Bt=e}function Kt(e){se(e,function(e){e.call(undefined)})}function Gt(o){const e=new XMLHttpRequest;const i={path:o,xhr:e};he(ne().body,"htmx:historyCacheMiss",i);e.open("GET",o,true);e.setRequestHeader("HX-Request","true");e.setRequestHeader("HX-History-Restore-Request","true");e.setRequestHeader("HX-Current-URL",ne().location.href);e.onload=function(){if(this.status>=200&&this.status<400){he(ne().body,"htmx:historyCacheMissLoad",i);const e=P(this.response);const t=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;const n=Ut();const r=xn(n);kn(e.title);qe(e);Ve(n,t,r);Te();Kt(r.tasks);Bt=o;he(ne().body,"htmx:historyRestore",{path:o,cacheMiss:true,serverResponse:this.response})}else{fe(ne().body,"htmx:historyCacheMissLoadError",i)}};e.send()}function Wt(e){zt();e=e||location.pathname+location.search;const t=Vt(e);if(t){const n=P(t.content);const r=Ut();const o=xn(r);kn(t.title);qe(n);Ve(r,n,o);Te();Kt(o.tasks);E().setTimeout(function(){window.scrollTo(0,t.scroll)},0);Bt=e;he(ne().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{Gt(e)}}}function Zt(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function Yt(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function Qt(e,t){se(e.concat(t),function(e){const t=ie(e);t.requestCount=(t.requestCount||1)-1});se(e,function(e){const t=ie(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});se(t,function(e){const t=ie(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function en(t,n){for(let e=0;e<t.length;e++){const r=t[e];if(r.isSameNode(n)){return true}}return false}function tn(e){const t=e;if(t.name===""||t.name==null||t.disabled||g(t,"fieldset[disabled]")){return false}if(t.type==="button"||t.type==="submit"||t.tagName==="image"||t.tagName==="reset"||t.tagName==="file"){return false}if(t.type==="checkbox"||t.type==="radio"){return t.checked}return true}function nn(t,e,n){if(t!=null&&e!=null){if(Array.isArray(e)){e.forEach(function(e){n.append(t,e)})}else{n.append(t,e)}}}function rn(t,n,r){if(t!=null&&n!=null){let e=r.getAll(t);if(Array.isArray(n)){e=e.filter(e=>n.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);se(e,e=>r.append(t,e))}}function on(t,n,r,o,i){if(o==null||en(t,o)){return}else{t.push(o)}if(tn(o)){const s=ee(o,"name");let e=o.value;if(o instanceof HTMLSelectElement&&o.multiple){e=M(o.querySelectorAll("option:checked")).map(function(e){return e.value})}if(o instanceof HTMLInputElement&&o.files){e=M(o.files)}nn(s,e,n);if(i){sn(o,r)}}if(o instanceof HTMLFormElement){se(o.elements,function(e){if(t.indexOf(e)>=0){rn(e.name,e.value,n)}else{t.push(e)}if(i){sn(e,r)}});new FormData(o).forEach(function(e,t){if(e instanceof File&&e.name===""){return}nn(t,e,n)})}}function sn(e,t){const n=e;if(n.willValidate){he(n,"htmx:validation:validate");if(!n.checkValidity()){t.push({elt:n,message:n.validationMessage,validity:n.validity});he(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})}}}function ln(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function cn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=ie(e);if(s.lastButtonClicked&&!le(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||te(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){on(n,o,i,g(e,"form"),l)}on(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const a=ee(u,"name");nn(a,u.value,o)}const c=we(e,"hx-include");se(c,function(e){on(n,r,i,ue(e),l);if(!h(e,"form")){se(f(e).querySelectorAll(ot),function(e){on(n,r,i,e,l)})}});ln(r,o);return{errors:i,formData:r,values:An(r)}}function un(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function an(e){e=qn(e);let n="";e.forEach(function(e,t){n=un(n,t,e)});return n}function fn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":te(t,"id"),"HX-Current-URL":ne().location.href};bn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(ie(e).boosted){r["HX-Boosted"]="true"}return r}function hn(n,e){const t=re(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){se(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;se(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function dn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function gn(e,t){const n=t||re(e,"hx-swap");const r={swapStyle:ie(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ie(e).boosted&&!dn(e)){r.show="top"}if(n){const s=F(n);if(s.length>0){for(let e=0;e<s.length;e++){const l=s[e];if(l.indexOf("swap:")===0){r.swapDelay=d(l.slice(5))}else if(l.indexOf("settle:")===0){r.settleDelay=d(l.slice(7))}else if(l.indexOf("transition:")===0){r.transition=l.slice(11)==="true"}else if(l.indexOf("ignoreTitle:")===0){r.ignoreTitle=l.slice(12)==="true"}else if(l.indexOf("scroll:")===0){const c=l.slice(7);var o=c.split(":");const u=o.pop();var i=o.length>0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const a=l.slice(5);var o=a.split(":");const f=o.pop();var i=o.length>0?o.join(":"):null;r.show=f;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{O("Unknown modifier in hx-swap: "+l)}}}}return r}function pn(e){return re(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function mn(t,n,r){let o=null;Ft(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(pn(n)){return ln(new FormData,qn(r))}else{return an(r)}}}function xn(e){return{tasks:[],elts:[e]}}function yn(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ue(ae(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ue(ae(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function bn(r,e,o,i){if(i==null){i={}}if(r==null){return i}const s=te(r,e);if(s){let e=s.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=vn(r,function(){return Function("return ("+e+")")()},{})}else{n=S(e)}for(const l in n){if(n.hasOwnProperty(l)){if(i[l]==null){i[l]=n[l]}}}}return bn(ue(c(r)),e,o,i)}function vn(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function wn(e,t){return bn(e,"hx-vars",true,t)}function Sn(e,t){return bn(e,"hx-vals",false,t)}function En(e){return ce(wn(e),Sn(e))}function Cn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function On(t){if(t.responseURL&&typeof URL!=="undefined"){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(ne().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function R(e,t){return t.test(e.getAllResponseHeaders())}function Rn(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return de(t,n,null,null,{targetOverride:y(r)||ve,returnPromise:true})}else{let e=y(r.target);if(r.target&&!e||r.source&&!e&&!y(r.source)){e=ve}return de(t,n,y(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return de(t,n,null,null,{returnPromise:true})}}function Hn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function Tn(e,t,n){let r;let o;if(typeof URL==="function"){o=new URL(t,document.location.href);const i=document.location.origin;r=i===o.origin}else{o=t;r=l(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!r){return false}}return he(e,"htmx:validateUrl",ce({url:o,sameHost:r},n))}function qn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Ln(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function An(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}else{return e[t]}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Ln(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function de(t,n,r,o,i,D){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=ne().body}const M=i.handler||Dn;const X=i.select||null;if(!le(r)){oe(s);return e}const c=i.targetOverride||ue(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:te(r,"hx-target")});oe(l);return e}let u=ie(r);const a=u.lastButtonClicked;if(a){const L=ee(a,"formaction");if(L!=null){n=L}const A=ee(a,"formmethod");if(A!=null){if(A.toLowerCase()!=="dialog"){t=A}}}const f=re(r,"hx-confirm");if(D===undefined){const K=function(e){return de(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:f};if(he(r,"htmx:confirm",G)===false){oe(s);return e}}let h=r;let d=re(r,"hx-sync");let g=null;let F=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ue(ae(r,I))}d=(N[1]||"drop").trim();u=ie(h);if(d==="drop"&&u.xhr&&u.abortable!==true){oe(s);return e}else if(d==="abort"){if(u.xhr){oe(s);return e}else{F=true}}else if(d==="replace"){he(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");g=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){he(h,"htmx:abort")}else{if(g==null){if(o){const P=ie(o);if(P&&P.triggerSpec&&P.triggerSpec.queue){g=P.triggerSpec.queue}}if(g==null){g="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(g==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="all"){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){de(t,n,r,o,i)})}oe(s);return e}}const p=new XMLHttpRequest;u.xhr=p;u.abortable=F;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const B=re(r,"hx-prompt");if(B){var x=prompt(B);if(x===null||!he(r,"htmx:prompt",{prompt:x,target:c})){oe(s);m();return e}}if(f&&!D){if(!confirm(f)){oe(s);m();return e}}let y=fn(r,c,x);if(t!=="get"&&!pn(r)){y["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){y=ce(y,i.headers)}const U=cn(r,t);let b=U.errors;const j=U.formData;if(i.values){ln(j,qn(i.values))}const V=qn(En(r));const v=ln(j,V);let w=hn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=ne().location.href}const S=bn(r,"hx-request");const _=ie(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:_,useUrlParams:E,formData:w,parameters:An(w),unfilteredFormData:v,unfilteredParameters:An(v),headers:y,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!he(r,"htmx:configRequest",C)){oe(s);m();return e}n=C.path;t=C.verb;y=C.headers;w=qn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){he(r,"htmx:validation:halted",C);oe(s);m();return e}const z=n.split("#");const $=z[0];const O=z[1];let R=n;if(E){R=$;const Z=!w.keys().next().done;if(Z){if(R.indexOf("?")<0){R+="?"}else{R+="&"}R+=an(w);if(O){R+="#"+O}}}if(!Tn(r,R,C)){fe(r,"htmx:invalidPath",C);oe(l);return e}p.open(t.toUpperCase(),R,true);p.overrideMimeType("text/html");p.withCredentials=C.withCredentials;p.timeout=C.timeout;if(S.noHeaders){}else{for(const k in y){if(y.hasOwnProperty(k)){const Y=y[k];Cn(p,k,Y)}}}const H={xhr:p,target:c,requestConfig:C,etc:i,boosted:_,select:X,pathInfo:{requestPath:n,finalRequestPath:R,responsePath:null,anchor:O}};p.onload=function(){try{const t=Hn(r);H.pathInfo.responsePath=On(p);M(r,H);if(H.keepIndicators!==true){Qt(T,q)}he(r,"htmx:afterRequest",H);he(r,"htmx:afterOnLoad",H);if(!le(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(le(n)){e=n}}if(e){he(e,"htmx:afterRequest",H);he(e,"htmx:afterOnLoad",H)}}oe(s);m()}catch(e){fe(r,"htmx:onLoadError",ce({error:e},H));throw e}};p.onerror=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendError",H);oe(l);m()};p.onabort=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendAbort",H);oe(l);m()};p.ontimeout=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:timeout",H);oe(l);m()};if(!he(r,"htmx:beforeRequest",H)){oe(s);m();return e}var T=Zt(r);var q=Yt(r);se(["loadstart","loadend","progress","abort"],function(t){se([p,p.upload],function(e){e.addEventListener(t,function(e){he(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});he(r,"htmx:beforeSend",H);const J=E?null:mn(p,r,w);p.send(J);return e}function Nn(e,t){const n=t.xhr;let r=null;let o=null;if(R(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(R(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(R(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=re(e,"hx-push-url");const c=re(e,"hx-replace-url");const u=ie(e).boosted;let a=null;let f=null;if(l){a="push";f=l}else if(c){a="replace";f=c}else if(u){a="push";f=s||i}if(f){if(f==="false"){return{}}if(f==="true"){f=s||i}if(t.pathInfo.anchor&&f.indexOf("#")===-1){f=f+"#"+t.pathInfo.anchor}return{type:a,path:f}}else{return{}}}function In(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Pn(e){for(var t=0;t<Q.config.responseHandling.length;t++){var n=Q.config.responseHandling[t];if(In(n,e.status)){return n}}return{swap:false}}function kn(e){if(e){const t=u("title");if(t){t.innerHTML=e}else{window.document.title=e}}}function Dn(o,i){const s=i.xhr;let l=i.target;const e=i.etc;const c=i.select;if(!he(o,"htmx:beforeOnLoad",i))return;if(R(s,/HX-Trigger:/i)){Je(s,"HX-Trigger",o)}if(R(s,/HX-Location:/i)){zt();let e=s.getResponseHeader("HX-Location");var t;if(e.indexOf("{")===0){t=S(e);e=t.path;delete t.path}Rn("get",e,t).then(function(){$t(e)});return}const n=R(s,/HX-Refresh:/i)&&s.getResponseHeader("HX-Refresh")==="true";if(R(s,/HX-Redirect:/i)){i.keepIndicators=true;location.href=s.getResponseHeader("HX-Redirect");n&&location.reload();return}if(n){i.keepIndicators=true;location.reload();return}if(R(s,/HX-Retarget:/i)){if(s.getResponseHeader("HX-Retarget")==="this"){i.target=o}else{i.target=ue(ae(o,s.getResponseHeader("HX-Retarget")))}}const u=Nn(o,i);const r=Pn(s);const a=r.swap;let f=!!r.error;let h=Q.config.ignoreTitle||r.ignoreTitle;let d=r.select;if(r.target){i.target=ue(ae(o,r.target))}var g=e.swapOverride;if(g==null&&r.swapOverride){g=r.swapOverride}if(R(s,/HX-Retarget:/i)){if(s.getResponseHeader("HX-Retarget")==="this"){i.target=o}else{i.target=ue(ae(o,s.getResponseHeader("HX-Retarget")))}}if(R(s,/HX-Reswap:/i)){g=s.getResponseHeader("HX-Reswap")}var p=s.response;var m=ce({shouldSwap:a,serverResponse:p,isError:f,ignoreTitle:h,selectOverride:d,swapOverride:g},i);if(r.event&&!he(l,r.event,m))return;if(!he(l,"htmx:beforeSwap",m))return;l=m.target;p=m.serverResponse;f=m.isError;h=m.ignoreTitle;d=m.selectOverride;g=m.swapOverride;i.target=l;i.failed=f;i.successful=!f;if(m.shouldSwap){if(s.status===286){lt(o)}Ft(o,function(e){p=e.transformResponse(p,s,o)});if(u.type){zt()}var x=gn(o,g);if(!x.hasOwnProperty("ignoreTitle")){x.ignoreTitle=h}l.classList.add(Q.config.swappingClass);let n=null;let r=null;if(c){d=c}if(R(s,/HX-Reselect:/i)){d=s.getResponseHeader("HX-Reselect")}const y=re(o,"hx-select-oob");const b=re(o,"hx-select");let e=function(){try{if(u.type){he(ne().body,"htmx:beforeHistoryUpdate",ce({history:u},i));if(u.type==="push"){$t(u.path);he(ne().body,"htmx:pushedIntoHistory",{path:u.path})}else{Jt(u.path);he(ne().body,"htmx:replacedInHistory",{path:u.path})}}$e(l,p,x,{select:d||b,selectOOB:y,eventInfo:i,anchor:i.pathInfo.anchor,contextElement:o,afterSwapCallback:function(){if(R(s,/HX-Trigger-After-Swap:/i)){let e=o;if(!le(o)){e=ne().body}Je(s,"HX-Trigger-After-Swap",e)}},afterSettleCallback:function(){if(R(s,/HX-Trigger-After-Settle:/i)){let e=o;if(!le(o)){e=ne().body}Je(s,"HX-Trigger-After-Settle",e)}oe(n)}})}catch(e){fe(o,"htmx:swapError",i);oe(r);throw e}};let t=Q.config.globalViewTransitions;if(x.hasOwnProperty("transition")){t=x.transition}if(t&&he(o,"htmx:beforeTransition",i)&&typeof Promise!=="undefined"&&document.startViewTransition){const v=new Promise(function(e,t){n=e;r=t});const w=e;e=function(){document.startViewTransition(function(){w();return v})}}if(x.swapDelay>0){E().setTimeout(e,x.swapDelay)}else{e()}}if(f){fe(o,"htmx:responseError",ce({error:"Response Status Error Code "+s.status+" from "+i.pathInfo.requestPath},i))}}const Mn={};function Xn(){return{init:function(e){return null},getSelectors:function(){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,n){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,n,r){return false},encodeParameters:function(e,t,n){return null}}}function Fn(e,t){if(t.init){t.init(n)}Mn[e]=ce(Xn(),t)}function Bn(e){delete Mn[e]}function Un(e,n,r){if(n==undefined){n=[]}if(e==undefined){return n}if(r==undefined){r=[]}const t=te(e,"hx-ext");if(t){se(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){r.push(e.slice(7));return}if(r.indexOf(e)<0){const t=Mn[e];if(t&&n.indexOf(t)<0){n.push(t)}}})}return Un(ue(c(e)),n,r)}var jn=false;ne().addEventListener("DOMContentLoaded",function(){jn=true});function Vn(e){if(jn||ne().readyState==="complete"){e()}else{ne().addEventListener("DOMContentLoaded",e)}}function _n(){if(Q.config.includeIndicatorStyles!==false){const e=Q.config.inlineStyleNonce?` nonce="${Q.config.inlineStyleNonce}"`:"";ne().head.insertAdjacentHTML("beforeend","<style"+e+"> ."+Q.config.indicatorClass+"{opacity:0} ."+Q.config.requestClass+" ."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ."+Q.config.requestClass+"."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} </style>")}}function zn(){const e=ne().querySelector('meta[name="htmx-config"]');if(e){return S(e.content)}else{return null}}function $n(){const e=zn();if(e){Q.config=ce(Q.config,e)}}Vn(function(){$n();_n();let e=ne().body;kt(e);const t=ne().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.target;const n=ie(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){Wt();se(t,function(e){he(e,"htmx:restored",{document:ne(),triggerEvent:he})})}else{if(n){n(e)}}};E().setTimeout(function(){he(e,"htmx:load",{});e=null},0)});return Q}();
\ No newline at end of file diff --git a/web/assets/javascript-params.scm b/web/assets/javascript-params.scm new file mode 100644 index 0000000..db300e3 --- /dev/null +++ b/web/assets/javascript-params.scm @@ -0,0 +1,12 @@ +; JavaScript parameters, from tree-sitter/tree-sitter-javascript v0.25.0 +; queries/highlights-params.scm (MIT), verbatim. Its own file because upstream +; keeps it out of the TypeScript composition: there a formal_parameters child +; is always a required_parameter or optional_parameter, so these patterns are +; not merely dead but rejected by the query compiler as impossible. + +(formal_parameters [ + (identifier) @variable.parameter + (array_pattern (identifier) @variable.parameter) + (object_pattern [ + (pair_pattern value: (identifier) @variable.parameter) + (shorthand_property_identifier_pattern) @variable.parameter])]) diff --git a/web/assets/javascript.scm b/web/assets/javascript.scm new file mode 100644 index 0000000..a5c8f01 --- /dev/null +++ b/web/assets/javascript.scm @@ -0,0 +1,52 @@ +; JavaScript highlights, from tree-sitter/tree-sitter-javascript v0.25.0 +; queries/highlights.scm (MIT). Reordered for later-patterns-win and capture +; names mapped onto zed syntax keys. Upstream's @variable.builtin and require() +; patterns are gone: they lean on (#is-not? local), which no query engine +; outside nvim evaluates. Also loaded ahead of typescript.scm, the way upstream +; composes the TypeScript highlights. + +["(" ")" "[" "]" "{" "}"] @punctuation.bracket +[";" (optional_chain) "." ","] @punctuation.delimiter +["-" "--" "-=" "+" "++" "+=" "*" "*=" "**" "**=" "/" "/=" "%" "%=" "<" "<=" + "<<" "<<=" "=" "==" "===" "!" "!=" "!==" "=>" ">" ">=" ">>" ">>=" ">>>" + ">>>=" "~" "^" "&" "|" "^=" "&=" "|=" "&&" "||" "??" "&&=" "||=" + "??="] @operator + +["as" "async" "await" "break" "case" "catch" "class" "const" "continue" + "debugger" "default" "delete" "do" "else" "export" "extends" "finally" "for" + "from" "function" "get" "if" "import" "in" "instanceof" "let" "new" "of" + "return" "set" "static" "switch" "target" "throw" "try" "typeof" "var" + "void" "while" "with" "yield"] @keyword + +[(property_identifier) (shorthand_property_identifier)] @property + +((identifier) @constructor + (#match? @constructor "^[A-Z]")) +([(identifier) (shorthand_property_identifier) + (shorthand_property_identifier_pattern)] @constant + (#match? @constant "^[A-Z_][A-Z0-9_]+$")) + +(function_expression name: (identifier) @function) +(function_declaration name: (identifier) @function) +(method_definition name: (property_identifier) @function.method) +(pair key: (property_identifier) @function.method + value: [(function_expression) (arrow_function)]) +(assignment_expression + left: (member_expression property: (property_identifier) @function.method) + right: [(function_expression) (arrow_function)]) +(variable_declarator name: (identifier) @function + value: [(function_expression) (arrow_function)]) +(assignment_expression left: (identifier) @function + right: [(function_expression) (arrow_function)]) +(call_expression function: (identifier) @function) +(call_expression function: (member_expression + property: (property_identifier) @function.method)) + +[(this) (super)] @variable.special +(number) @number +[(true) (false) (null) (undefined)] @constant +[(string) (template_string)] @string +(escape_sequence) @string.escape +(regex) @string.regex +(template_substitution "${" @punctuation.special "}" @punctuation.special) +(comment) @comment diff --git a/web/assets/json.scm b/web/assets/json.scm new file mode 100644 index 0000000..e82e125 --- /dev/null +++ b/web/assets/json.scm @@ -0,0 +1,13 @@ +; JSON highlights, from tree-sitter/tree-sitter-json v0.24.8 +; queries/highlights.scm (MIT). Reordered so object keys repaint the string +; they are; capture names are already zed syntax keys but for @escape. + +["{" "}" "[" "]"] @punctuation.bracket +[":" ","] @punctuation.delimiter + +(number) @number +[(null) (true) (false)] @constant +(string) @string +(pair key: (string) @string.special.key) +(escape_sequence) @string.escape +(comment) @comment diff --git a/web/assets/jsx.scm b/web/assets/jsx.scm new file mode 100644 index 0000000..708eba2 --- /dev/null +++ b/web/assets/jsx.scm @@ -0,0 +1,16 @@ +; JSX highlights, from tree-sitter/tree-sitter-javascript v0.25.0 +; queries/highlights-jsx.scm (MIT), verbatim but for the capture rename. +; Loaded last for .jsx and .tsx; the plain typescript grammar has no JSX nodes, +; so .ts must not get this file. + +(jsx_opening_element ["<" ">"] @punctuation.bracket) +(jsx_closing_element ["</" ">"] @punctuation.bracket) +(jsx_self_closing_element ["<" "/>"] @punctuation.bracket) + +(jsx_attribute (property_identifier) @attribute) + +; lowercase names are html elements, capitalized ones are components and keep +; the @constructor javascript.scm gave them +((jsx_opening_element (identifier) @tag) (#match? @tag "^[a-z][^.]*$")) +((jsx_closing_element (identifier) @tag) (#match? @tag "^[a-z][^.]*$")) +((jsx_self_closing_element (identifier) @tag) (#match? @tag "^[a-z][^.]*$")) diff --git a/web/assets/one.json b/web/assets/one.json new file mode 100644 index 0000000..cb4ca24 --- /dev/null +++ b/web/assets/one.json @@ -0,0 +1,112 @@ +{ + "name": "One", + "author": "Zed Industries (vendored subset for notevi fallback)", + "themes": [ + { + "name": "One Dark", + "appearance": "dark", + "style": { + "editor.background": "#282c33ff", + "editor.foreground": "#acb2beff", + "background": "#3b414dff", + "panel.background": "#2f343eff", + "surface.background": "#2f343eff", + "border": "#464b57ff", + "editor.line_number": "#4e5a5f", + "text": "#dce0e5ff", + "text.muted": "#a9afbcff", + "text.accent": "#74ade8ff", + "warning": "#dec184ff", + "element.hover": "#363c46ff", + "players": [ + {"cursor": "#74ade8ff"}, {"cursor": "#be5046ff"}, {"cursor": "#bf956aff"}, + {"cursor": "#b477cfff"}, {"cursor": "#6eb4bfff"}, {"cursor": "#d07277ff"}, + {"cursor": "#dec184ff"}, {"cursor": "#a1c181ff"} + ], + "syntax": { + "attribute": {"color": "#74ade8ff"}, + "boolean": {"color": "#bf956aff"}, + "comment": {"color": "#5d636fff"}, + "comment.doc": {"color": "#878e98ff"}, + "constant": {"color": "#dfc184ff"}, + "constructor": {"color": "#73ade9ff"}, + "embedded": {"color": "#dce0e5ff"}, + "enum": {"color": "#6eb4bfff"}, + "function": {"color": "#73ade9ff"}, + "keyword": {"color": "#b477cfff"}, + "label": {"color": "#74ade8ff"}, + "number": {"color": "#bf956aff"}, + "operator": {"color": "#6eb4bfff"}, + "preproc": {"color": "#b477cfff"}, + "primary": {"color": "#acb2beff"}, + "property": {"color": "#d07277ff"}, + "punctuation": {"color": "#acb2beff"}, + "punctuation.bracket": {"color": "#b2b9c6ff"}, + "punctuation.delimiter": {"color": "#b2b9c6ff"}, + "punctuation.special": {"color": "#b1574bff"}, + "string": {"color": "#a1c181ff"}, + "string.escape": {"color": "#878e98ff"}, + "string.regex": {"color": "#bf956aff"}, + "string.special": {"color": "#bf956aff"}, + "type": {"color": "#6eb4bfff"}, + "variable": {"color": "#acb2beff"}, + "variable.parameter": {"color": "#d07277ff"}, + "variable.special": {"color": "#bf956aff"} + } + } + }, + { + "name": "One Light", + "appearance": "light", + "style": { + "editor.background": "#fafafaff", + "editor.foreground": "#242529ff", + "background": "#dcdcddff", + "panel.background": "#ebebecff", + "surface.background": "#ebebecff", + "border": "#c9c9caff", + "editor.line_number": "#b4b4bb", + "text": "#242529ff", + "text.muted": "#58585aff", + "text.accent": "#5c78e2ff", + "warning": "#a48819ff", + "element.hover": "#dfdfe0ff", + "players": [ + {"cursor": "#5c78e2ff"}, {"cursor": "#984ea5ff"}, {"cursor": "#ad6e26ff"}, + {"cursor": "#a349abff"}, {"cursor": "#3a82b7ff"}, {"cursor": "#d36151ff"}, + {"cursor": "#a48819ff"}, {"cursor": "#669f59ff"} + ], + "syntax": { + "attribute": {"color": "#5c78e2ff"}, + "boolean": {"color": "#ad6e25ff"}, + "comment": {"color": "#a2a3a7ff"}, + "comment.doc": {"color": "#7c7e86ff"}, + "constant": {"color": "#c18401ff"}, + "constructor": {"color": "#5c78e2ff"}, + "embedded": {"color": "#242529ff"}, + "enum": {"color": "#3882b7ff"}, + "function": {"color": "#5b79e3ff"}, + "keyword": {"color": "#a449abff"}, + "label": {"color": "#5c78e2ff"}, + "number": {"color": "#ad6e25ff"}, + "operator": {"color": "#3882b7ff"}, + "preproc": {"color": "#a449abff"}, + "primary": {"color": "#242529ff"}, + "property": {"color": "#d3604fff"}, + "punctuation": {"color": "#242529ff"}, + "punctuation.bracket": {"color": "#4d4f52ff"}, + "punctuation.delimiter": {"color": "#4d4f52ff"}, + "punctuation.special": {"color": "#b92b46ff"}, + "string": {"color": "#649f57ff"}, + "string.escape": {"color": "#7c7e86ff"}, + "string.regex": {"color": "#ad6e26ff"}, + "string.special": {"color": "#ad6e26ff"}, + "type": {"color": "#3882b7ff"}, + "variable": {"color": "#242529ff"}, + "variable.parameter": {"color": "#d3604fff"}, + "variable.special": {"color": "#ad6e25ff"} + } + } + } + ] +} diff --git a/web/assets/python.scm b/web/assets/python.scm new file mode 100644 index 0000000..f64e673 --- /dev/null +++ b/web/assets/python.scm @@ -0,0 +1,50 @@ +; Python highlights, from tree-sitter/tree-sitter-python v0.25.0 +; queries/highlights.scm (MIT). Reordered for later-patterns-win, capture names +; mapped onto zed syntax keys, and the builtin-function #match? turned into +; #any-of?. The two casing heuristics stay regexes: nothing else can express +; "CONST_CASE" and "ClassName" over bare identifiers. + +["(" ")" "[" "]" "{" "}"] @punctuation.bracket +[";" "," "." ":"] @punctuation.delimiter +["-" "-=" "!=" "*" "**" "**=" "*=" "/" "//" "//=" "/=" "&" "&=" "%" "%=" + "^" "^=" "+" "->" "+=" "<" "<<" "<<=" "<=" "<>" "=" ":=" "==" ">" ">=" + ">>" ">>=" "|" "|=" "~" "@=" "and" "in" "is" "not" "or" "is not" + "not in"] @operator + +["as" "assert" "async" "await" "break" "class" "continue" "def" "del" "elif" + "else" "except" "exec" "finally" "for" "from" "global" "if" "import" "lambda" + "nonlocal" "pass" "print" "raise" "return" "try" "while" "with" "yield" + "match" "case"] @keyword + +((identifier) @constructor + (#match? @constructor "^[A-Z]")) +((identifier) @constant + (#match? @constant "^[A-Z][A-Z_0-9]*$")) +((identifier) @variable.special + (#any-of? @variable.special "self" "cls")) + +(type (identifier) @type) +(attribute attribute: (identifier) @property) +(function_definition name: (identifier) @function) +(call function: (identifier) @function) +(call function: (attribute attribute: (identifier) @function.method)) +((call function: (identifier) @function.builtin) + (#any-of? @function.builtin "abs" "all" "any" "ascii" "bin" "bool" + "breakpoint" "bytearray" "bytes" "callable" "chr" "classmethod" "compile" + "complex" "delattr" "dict" "dir" "divmod" "enumerate" "eval" "exec" "filter" + "float" "format" "frozenset" "getattr" "globals" "hasattr" "hash" "help" + "hex" "id" "input" "int" "isinstance" "issubclass" "iter" "len" "list" + "locals" "map" "max" "memoryview" "min" "next" "object" "oct" "open" "ord" + "pow" "print" "property" "range" "repr" "reversed" "round" "set" "setattr" + "slice" "sorted" "staticmethod" "str" "sum" "super" "tuple" "type" "vars" + "zip" "__import__")) + +[(integer) (float)] @number +[(none) (true) (false)] @constant +(string) @string +(escape_sequence) @string.escape +(interpolation "{" @punctuation.special "}" @punctuation.special) + +(decorator "@" @attribute) +(decorator [(identifier) (attribute)] @attribute) +(comment) @comment diff --git a/web/assets/rust.scm b/web/assets/rust.scm new file mode 100644 index 0000000..d23fa2c --- /dev/null +++ b/web/assets/rust.scm @@ -0,0 +1,48 @@ +; Minimal rust highlights. Capture names double as zed syntax theme keys. +; Order matters: later patterns paint over earlier ones. + +["(" ")" "[" "]" "{" "}"] @punctuation.bracket +[";" "," "." ":" "::"] @punctuation.delimiter +["=" "==" "!=" "<" ">" "<=" ">=" "+" "-" "*" "/" "%" "&" "|" "^" "!" "&&" "||" + "->" "=>" ".." "..=" "+=" "-=" "*=" "/=" "?" "@" "<<" ">>"] @operator + +["as" "async" "await" "break" "const" "continue" "dyn" "else" "enum" + "extern" "fn" "for" "if" "impl" "in" "let" "loop" "match" "mod" "move" + "pub" "ref" "return" "static" "struct" "trait" "type" "union" + "unsafe" "use" "where" "while"] @keyword +(crate) @keyword +(super) @keyword +(mutable_specifier) @keyword + +(type_identifier) @type +(primitive_type) @type +(field_identifier) @property +(shorthand_field_initializer (identifier) @property) +(enum_variant name: (identifier) @constructor) +(const_item name: (identifier) @constant) +(static_item name: (identifier) @constant) +(boolean_literal) @constant + +(function_item name: (identifier) @function) +(function_signature_item name: (identifier) @function) +(call_expression function: (identifier) @function) +(call_expression function: (scoped_identifier name: (identifier) @function)) +(call_expression function: (field_expression field: (field_identifier) @function)) +(generic_function function: (identifier) @function) +(generic_function function: (scoped_identifier name: (identifier) @function)) +(macro_invocation macro: (identifier) @function) +(macro_invocation macro: (scoped_identifier name: (identifier) @function)) + +(integer_literal) @number +(float_literal) @number +(char_literal) @string +(string_literal) @string +(raw_string_literal) @string +(escape_sequence) @string.escape +(lifetime) @label +(self) @variable.special + +(attribute_item) @attribute +(inner_attribute_item) @attribute +(line_comment) @comment +(block_comment) @comment diff --git a/web/assets/style.css.tmpl b/web/assets/style.css.tmpl new file mode 100644 index 0000000..d555950 --- /dev/null +++ b/web/assets/style.css.tmpl @@ -0,0 +1,592 @@ +/* generated from zed themes "{{.DarkName}}" (dark) + "{{.LightName}}" (light) */ +:root { +{{range .DarkVars}} {{.K}}: {{.V}}; +{{end}} color-scheme: dark; + --note-bg: color-mix(in srgb, var(--note) 4%, transparent); +} +@media (prefers-color-scheme: light) { + :root:not([data-theme="dark"]) { +{{range .LightVars}} {{.K}}: {{.V}}; +{{end}} color-scheme: light; + } +} +:root[data-theme="light"] { +{{range .LightVars}} {{.K}}: {{.V}}; +{{end}} color-scheme: light; +} + +* { box-sizing: border-box; } +body { + margin: 0; + display: grid; + grid-template-columns: 280px minmax(0, 1fr); + background: var(--bg); + color: var(--fg); + font: 15px/1.5 ui-sans-serif, system-ui, sans-serif; +} +:root[data-mode="notes"] body.with-aside, +body.with-aside { grid-template-columns: 280px minmax(0, 1fr) 380px; } +:root[data-mode="trace"] body.with-aside { grid-template-columns: 280px minmax(0, 1fr); } + +/* ── focus: trace or notes ───────────────────────────────────── + The two views compete for the same pixels — line background, gutter + color, tree markers — so the interface shows one at a time. */ +:root[data-mode="trace"] .notes-only { display: none !important; } +:root[data-mode="notes"] .trace-only { display: none !important; } +:root[data-mode="notes"] ol.code li.cov { box-shadow: none; } +:root[data-mode="notes"] ol.code li.cov::before { color: var(--ln); font-weight: 400; } +:root[data-mode="notes"] nav a.file::after, +:root[data-mode="notes"] .filetree a.file::after { display: none; } +:root[data-mode="trace"] ol.code li.noted { background: none; cursor: default; } +:root[data-mode="trace"] ol.code li.noted::before { color: var(--ln); } +:root[data-mode="trace"] nav a.file.has-notes::before, +:root[data-mode="trace"] .filetree a.file.has-notes::before { content: none; } +:root[data-mode="notes"] nav a.file { color: var(--muted); } +:root[data-mode="notes"] nav a.file.has-notes { color: var(--fg); } + +.modes { display: flex; gap: 0; border: 1px solid var(--border); border-radius: 5px; overflow: hidden; } +.modes .mode { + background: none; border: 0; color: var(--muted); + font: inherit; font-size: 11px; padding: 2px 8px; cursor: pointer; +} +.modes .mode:hover { background: var(--hover); color: var(--fg); } +.modes .mode[aria-pressed="true"] { background: var(--hover); color: var(--fg); font-weight: 600; } + +a { color: var(--accent); text-decoration: none; } +a:hover { text-decoration: underline; } +code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.92em; } +h1 { font-size: 1.1rem; margin: 0; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; } +h2 { font-size: 0.95rem; margin: 1.4em 0 0.5em; } + +/* ── left tree ─────────────────────────────────────────────── */ +nav { + border-right: 1px solid var(--border); + background: var(--panel); + padding: 10px 8px; + position: sticky; top: 0; + height: 100vh; overflow: auto; + font-size: 13px; +} +nav > header { + font-weight: 600; margin-bottom: 10px; + display: flex; align-items: center; justify-content: space-between; gap: 8px; +} +nav > header a { color: var(--fg); } +nav .brand { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +/* the bem-te-vi; inline so the brand keeps ellipsing its title */ +nav .brand .mark { width: 1.15em; height: 1.15em; vertical-align: -0.22em; margin-right: 0.4em; } +#filetoggle { + display: block; margin: 0 0 6px auto; + background: none; color: var(--muted); border: 0; + font: inherit; font-size: 11px; padding: 1px 3px; cursor: pointer; +} +#filetoggle:hover { color: var(--fg); } +:root[data-files="hidden"] #filelist { display: none; } + +/* ── the current change ──────────────────────────────────────── + Everything on screen is read at one change: the tree, the code, the + coverage, the notes, and anything you write. It says so, always. */ +.changebar { + margin-bottom: 10px; padding: 7px 8px; + border: 1px solid var(--border); border-left: 3px solid var(--accent); + border-radius: 6px; background: var(--bg); +} +.changebar.away { border-left-color: var(--note); } +.changebar .cid { display: flex; align-items: baseline; gap: 6px; } +.changebar .lbl { color: var(--muted); font-size: 10px; text-transform: uppercase; letter-spacing: 0.06em; } +.changebar .cid code { font-size: 13px; font-weight: 600; color: var(--fg); } +.changebar .cid a code { color: var(--accent); } +.changebar .flags { color: var(--note); font-size: 10px; font-style: italic; margin-left: auto; } +.changebar .desc { + margin: 3px 0 0; font-size: 11.5px; color: var(--muted); + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; +} +.changebar .counts { margin: 5px 0 0; font-size: 11px; color: var(--muted); } +.changebar .counts b { color: var(--fg); font-weight: 600; } +.changebar .away { color: var(--note); } +.changebar .scope { display: flex; gap: 0; margin-top: 7px; border: 1px solid var(--border); border-radius: 5px; overflow: hidden; } +.changebar .scope a { + flex: 1; text-align: center; padding: 2px 4px; + font-size: 11px; color: var(--muted); text-decoration: none; +} +.changebar .scope a:hover { background: var(--hover); color: var(--fg); } +.changebar .scope a.on { background: var(--hover); color: var(--fg); font-weight: 600; } +.changebar .revjump { margin-top: 6px; } +.changebar .revjump input { width: 100%; font-family: ui-monospace, Menlo, monospace; font-size: 11px; } +.changebar .back { margin: 6px 0 0; font-size: 11px; } + +/* a note written at another change: it pins to line numbers that have moved */ +.note.away { border-style: dashed; opacity: 0.82; } +.note.away:hover { opacity: 1; } +.atchg.away { color: var(--note); } +.atchg.away code { color: inherit; } +.find, .filters input, .filters select, .notform input, .notform textarea, .jjform input, .thememenu input { + background: var(--bg); color: var(--fg); + border: 1px solid var(--border); border-radius: 5px; + font: inherit; font-size: 12px; padding: 3px 6px; +} +.find { width: 100%; margin-bottom: 6px; } +.find:focus, .filters input:focus, .notform textarea:focus, .jjform input:focus { + outline: 1px solid var(--accent); border-color: var(--accent); +} +#tree.filtering a.file.hit { background: color-mix(in srgb, var(--accent) 14%, transparent); } +nav details { padding-left: 10px; } +nav summary { cursor: pointer; color: var(--muted); user-select: none; } +nav summary:hover { color: var(--fg); } +nav ul { list-style: none; margin: 0; padding-left: 10px; } +nav a.file { + display: block; position: relative; + padding: 1px 6px 3px; border-radius: 4px; + color: var(--fg); + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; +} +nav a.file:hover { background: var(--hover); text-decoration: none; } +nav a.file[aria-current] { background: var(--hover); } +nav a.file::after { + content: ""; position: absolute; left: 6px; bottom: 1px; height: 2px; + width: calc(var(--pct) - 12px); max-width: calc(100% - 12px); + background: var(--cov); border-radius: 1px; +} +nav a.file.has-notes::before { content: "◆ "; color: var(--note); font-size: 9px; vertical-align: 2px; } +nav a.file.plain { color: var(--muted); } +nav a.file.plain::after { display: none; } +#tree { margin-top: 8px; } +#tree > details { padding-left: 0; } +summary .dot { + display: inline-block; width: 7px; height: 7px; border-radius: 99px; + background: var(--cov); margin-left: 6px; +} +summary .nmark { color: var(--note); font-size: 9px; margin-left: 4px; vertical-align: 1px; } +nav details.t > summary, .filetree details.t > summary { color: var(--fg); } +nav > footer { + margin-top: 14px; border-top: 1px solid var(--border); padding-top: 8px; + display: flex; justify-content: space-between; align-items: center; gap: 8px; +} + +/* ── the theme picker ────────────────────────────────────────── + Every theme on the machine, previewed as you move through it. The + menu is fixed rather than absolute so the scrolling tree above it + cannot clip it. */ +#themebtn { + background: var(--panel); color: var(--muted); + border: 1px solid var(--border); border-radius: 4px; + font: inherit; font-size: 11px; padding: 1px 6px; cursor: pointer; + max-width: 130px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; +} +#themebtn:hover, #themebtn[aria-expanded="true"] { color: var(--fg); background: var(--hover); } +.thememenu { + position: fixed; left: 8px; bottom: 8px; z-index: 20; + width: 264px; max-height: min(60vh, 520px); + display: flex; flex-direction: column; gap: 6px; + background: var(--panel); border: 1px solid var(--border); + border-radius: 7px; padding: 8px; + box-shadow: 0 8px 30px rgb(0 0 0 / 0.35); +} +.thememenu input { width: 100%; } +.thememenu ul { list-style: none; margin: 0; padding: 0; overflow: auto; flex: 1; } +.thememenu li { + display: flex; align-items: center; gap: 7px; + padding: 3px 5px; border-radius: 4px; cursor: pointer; + font-size: 12px; color: var(--fg); +} +/* the menu is hidden until it is opened and the filter hides rows: both are + the hidden attribute, which a display of our own would otherwise outrank */ +.thememenu[hidden], .thememenu li[hidden] { display: none; } +.thememenu li.on { background: var(--hover); } +.thememenu li .nm { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.thememenu li .src { margin-left: auto; color: var(--muted); font-size: 10px; white-space: nowrap; } +.thememenu li.cur .nm::after { content: " ✓"; color: var(--accent); } +.thememenu .sw { display: flex; flex: none; border: 1px solid var(--border); border-radius: 3px; overflow: hidden; } +.thememenu .sw i { display: block; width: 7px; height: 14px; } +.thememenu .sw.none { width: 42px; border-color: transparent; } +.thememenu .hint { margin: 0; font-size: 10px; } + +/* files.html full tree */ +.filetree { font: 13px/1.6 ui-monospace, SFMono-Regular, Menlo, monospace; padding-bottom: 40vh; } +.filetree details { padding-left: 18px; } +.filetree summary { cursor: pointer; color: var(--muted); } +.filetree summary:hover { color: var(--fg); } +.filetree ul { list-style: none; margin: 0; padding-left: 18px; } +.filetree a.file { display: inline-block; position: relative; padding: 0 6px 2px; border-radius: 4px; color: var(--fg); } +.filetree a.file.plain { color: var(--muted); } +.filetree a.file:not(.plain)::after { + content: ""; position: absolute; left: 6px; bottom: 0; height: 2px; + width: calc(var(--pct) - 12px); max-width: calc(100% - 12px); + background: var(--cov); border-radius: 1px; +} +.filetree a.file.has-notes::before { content: "◆ "; color: var(--note); font-size: 9px; vertical-align: 2px; } +.stub { padding: 24px 16px; } + +/* ── main ──────────────────────────────────────────────────── */ +main { min-width: 0; } +.filehead { + position: sticky; top: 0; z-index: 2; + background: color-mix(in srgb, var(--bg) 88%, transparent); + backdrop-filter: blur(6px); + border-bottom: 1px solid var(--border); + padding: 10px 16px; +} +.meta { margin: 4px 0 0; color: var(--muted); font-size: 12.5px; } +.meta code { color: var(--fg); } +.greps code { margin-right: 8px; } +.chip { + display: inline-block; padding: 0 8px; border-radius: 99px; + background: color-mix(in srgb, var(--cov) 22%, transparent); + border: 1px solid var(--cov); color: var(--fg); font-size: 12px; +} +main > section, .notegroup { padding: 0 16px; max-width: 1100px; } +table { border-collapse: collapse; width: 100%; font-size: 13.5px; } +th { text-align: left; color: var(--muted); font-weight: 500; } +th, td { padding: 4px 12px 4px 0; border-bottom: 1px solid var(--border); } +data.bar { + display: inline-block; min-width: 140px; padding-left: 4px; + font-size: 12px; color: var(--muted); + background: linear-gradient(90deg, color-mix(in srgb, var(--cov) 35%, transparent) var(--pct), transparent var(--pct)); + border-radius: 3px; +} + +/* ── code view ─────────────────────────────────────────────── */ +.codewrap { overflow-x: auto; } +ol.code { + list-style: none; margin: 0; padding: 0; + font: 12.5px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; + counter-reset: ln; + tab-size: 4; + content-visibility: auto; + contain-intrinsic-size: auto var(--h, auto); +} +ol.code:first-of-type { padding-top: 8px; } +ol.code:last-of-type { padding-bottom: 40vh; } +ol.code li { + counter-increment: ln; + white-space: pre; + min-height: 1lh; + padding-right: 16px; + /* a #L42 jump must clear the sticky header, or the line lands under it */ + scroll-margin-top: 76px; +} +ol.code li::before { + content: counter(ln); + display: inline-block; width: 5ch; margin-right: 1.5ch; + text-align: right; color: var(--ln); + user-select: none; +} +ol.code li.cov { box-shadow: inset 3px 0 var(--cov); } +ol.code li.cov::before { color: var(--cov); font-weight: 700; } +ol.code li.noted { background: var(--note-bg); cursor: pointer; } +ol.code li.noted::before { color: color-mix(in srgb, var(--note) 55%, var(--ln)); } +ol.code li:target { background: color-mix(in srgb, var(--accent) 18%, transparent); } + +/* ── notes ─────────────────────────────────────────────────── */ +aside { + border-left: 1px solid var(--border); + background: var(--panel); + position: sticky; top: 0; height: 100vh; overflow: auto; + padding: 10px 12px; font-size: 13px; +} +aside summary { cursor: pointer; color: var(--muted); } +.note { + border: 1px solid var(--border); + border-left: 3px solid var(--cov); + border-radius: 6px; + padding: 8px 10px; margin: 10px 0; + background: var(--bg); +} +.note header { display: flex; gap: 8px; align-items: baseline; font-size: 12px; } +.note header a { font-family: ui-monospace, Menlo, monospace; } +.note header em { color: var(--note); font-style: normal; border: 1px solid var(--note); border-radius: 3px; padding: 0 4px; font-size: 11px; } +.note header b { margin-left: auto; color: var(--cov); font-weight: 600; } +.note p { margin: 6px 0 0; line-height: 1.45; } +.note.flash { animation: flash 1.2s ease-out; } + +/* A note body is markdown. It is prose about code inside a card that is + itself only ~320px wide in the columns, so every block here is tuned down + from document scale: headings barely outrank the text, rules and quotes are + hairlines, and nothing may push the card wider than its column. The + selectors carry .body so they outrank .turn p in the conversation view, + where notes are cards too. */ +.note .body > :first-child { margin-top: 6px; } +.note .body p, +.note .body ul, .note .body ol, .note .body blockquote, +.note .body pre, .note .body table { margin: 6px 0 0; } +.note .body p { line-height: 1.45; white-space: normal; } +.note .body :is(h1, h2, h3, h4, h5, h6) { + margin: 10px 0 0; font-size: 1em; font-weight: 600; line-height: 1.3; +} +.note .body h1, .note .body h2 { color: var(--fg); font-size: 1.05em; } +.note .body ul, .note .body ol { padding-left: 1.3em; } +.note .body li { margin: 2px 0; line-height: 1.45; } +.note .body li > p { margin: 0; } +.note .body li::marker { color: var(--muted); } +.note .body blockquote { + border-left: 2px solid var(--border); padding-left: 8px; color: var(--muted); +} +.note .body hr { border: none; border-top: 1px solid var(--border); margin: 10px 0 0; } +.note .body code { background: var(--hover); border-radius: 3px; padding: 0 3px; } +.note .body a { overflow-wrap: anywhere; } +.note .body img { max-width: 100%; height: auto; } +/* a fenced block: the code view's spans without its line-number scaffolding */ +.note .body pre.mdcode { + background: var(--panel); border: 1px solid var(--border); border-radius: 4px; + padding: 6px 8px; overflow-x: auto; + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.92em; + line-height: 1.4; tab-size: 4; +} +.note .body pre.mdcode code { background: none; padding: 0; font-size: inherit; } +.note .body table { border-collapse: collapse; display: block; overflow-x: auto; font-size: 0.95em; } +.note .body :is(th, td) { border: 1px solid var(--border); padding: 2px 6px; text-align: left; } +.note .body th { color: var(--muted); font-weight: 600; } +.note .body input[type="checkbox"] { margin-right: 4px; vertical-align: -1px; } +@keyframes flash { 0% { background: color-mix(in srgb, var(--cov) 30%, var(--bg)); } 100% { background: var(--bg); } } + +.note footer { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 6px; font-size: 11px; } +.note footer code { color: var(--muted); } +.note .model { opacity: 0.85; } +.note .conv { margin-left: auto; } +.note .parent { color: var(--muted); } +.note .relations { + color: var(--note); text-decoration: none; + background: var(--note-bg); border-radius: 3px; padding: 0 4px; +} +.note .relations:hover { color: var(--accent); text-decoration: underline; } +.notecols { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 0 14px; } + +/* the permalink: the one link on a card that names nothing but the note, so + it is the one to hand someone else. Quiet until wanted. */ +.note .perma { color: var(--ln); font-variant-numeric: tabular-nums; text-decoration: none; } +.note .perma:hover { color: var(--accent); text-decoration: underline; } +.note .perma.self { color: var(--muted); } + +/* ── one note, on its own page ───────────────────────────────── + What a shared link opens: the note, then the lines it is about. Wider + than a card in a list — nothing is competing for the room here. */ +.notepage { padding-bottom: 30vh; } +.notepage .onenote .note { margin: 0 0 14px; max-width: 760px; } +.notepage .exhead { margin: 0 0 6px; } +.notepage .excerpt { border: 1px solid var(--border); border-radius: 6px; background: var(--panel); } +.notepage .excerpt ol.code { padding: 6px 0; } +.notepage .excerpt ol.code:last-of-type { padding-bottom: 6px; } +.notepage .more { margin-top: 20px; } +.filehead h1 .lns { color: var(--muted); font-weight: 400; } +.filehead .kind { color: var(--note); font-style: normal; border: 1px solid var(--note); border-radius: 3px; padding: 0 4px; font-size: 11px; } +.filehead .ago { color: var(--muted); } +/* the excerpt exists to show what the note is about, so its lines stay + marked in either focus — the toggle is about reading a whole file */ +:root[data-mode="trace"] .excerpt ol.code li.noted { background: var(--note-bg); cursor: default; } +:root[data-mode="trace"] .excerpt ol.code li.noted::before { color: color-mix(in srgb, var(--note) 55%, var(--ln)); } + +/* Incoming reply and mention edges share one recursively nested discussion. + The narrow rail is intentionally HN-like: enough hierarchy to scan without + turning the existing cards into a second design system. */ +.discussion { max-width: 820px; margin-top: 24px; scroll-margin-top: 16px; } +.discussion h2 { margin-bottom: 6px; } +.discussion h2 .meta { font-size: 11px; font-weight: 400; margin-left: 6px; } +.threadnode { + display: grid; grid-template-columns: 20px minmax(0, 1fr); + align-items: stretch; +} +.threadedge { position: relative; color: var(--muted); text-align: center; font-size: 11px; } +.threadedge::after { + content: ""; position: absolute; top: 20px; bottom: 0; left: 50%; + border-left: 1px solid var(--border); +} +.threadedge span { position: relative; z-index: 1; background: var(--bg); } +.via-mention > .threadedge { color: var(--note); } +.via-mention > .threadedge::after { border-left-style: dashed; border-left-color: var(--note); } +.threadcontent { min-width: 0; } +.threadcontent > .note { margin: 7px 0; } +.threadchildren { min-width: 0; } +.threadref { + margin: 8px 0; padding: 5px 8px; border: 1px dashed var(--border); + border-radius: 5px; background: var(--panel); +} +.replybox { max-width: 760px; margin: 4px 0 10px; } +.replybox > summary { cursor: pointer; color: var(--muted); font-size: 11px; } +.replybox[open] > summary { color: var(--accent); } +.replyform { margin: 5px 0 10px; padding-left: 8px; border-left: 2px solid var(--border); } +.replyform textarea { width: 100%; box-sizing: border-box; } +.threadnode .replybox { margin-left: 1px; } + +/* ── conversation ──────────────────────────────────────────── */ +.convpage { padding: 0 16px 40vh; max-width: 1100px; } +.turn { + display: grid; grid-template-columns: 12ch 8ch minmax(0, 1fr); + gap: 0 10px; align-items: baseline; + padding: 2px 0 2px 8px; border-left: 2px solid transparent; +} +.turn .role { + color: var(--muted); font-size: 11px; text-align: right; + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; +} +.turn time { color: var(--ln); font-size: 11px; font-variant-numeric: tabular-nums; } +.turn p { margin: 0; line-height: 1.5; white-space: pre-wrap; } +.turn .what { + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; +} +.t-say { padding: 8px 0 8px 8px; } +.t-user { border-left-color: var(--accent); } +.t-user .role, .t-user p { color: var(--fg); } +.t-assistant .role { color: var(--cov); } +.t-thinking p { color: var(--muted); font-style: italic; } +.t-tool .role { color: var(--note); } +.t-result .what { color: var(--muted); } +.t-result.bad .what { color: var(--note); } +.t-notevi { border-left-color: var(--cov); background: color-mix(in srgb, var(--cov) 7%, transparent); } +.t-notevi .role { color: var(--cov); font-weight: 600; } +/* A note is what you came to the conversation to find, so it breaks the run + of log lines: the note color's rail, a tinted band, a card instead of a + line. scroll-margin clears the sticky header — the anchored one is + scrolled to on load. */ +.t-note { + padding: 8px 0 8px 8px; + border-left-color: var(--note); + background: color-mix(in srgb, var(--note) 7%, transparent); +} +.t-note .role { color: var(--note); font-weight: 600; } +.t-note .role::before { content: "◆ "; font-size: 9px; vertical-align: 1px; } +.t-note .note { max-width: 640px; margin: 0; scroll-margin-top: 96px; } +.t-note.here { background: color-mix(in srgb, var(--accent) 12%, transparent); } +.t-note.here .note { border-color: var(--accent); border-left-color: var(--accent); } +/* the whole card is the way back to the code; the links inside still work */ +.notewrap { cursor: pointer; } +.notewrap:hover .note, .notewrap:focus-visible .note { + border-color: var(--accent); background: var(--hover); +} +.notewrap:focus-visible { outline: none; } +.notewrap[data-href] .note::after { + content: "open in source →"; display: block; + margin-top: 6px; color: var(--accent); font-size: 11px; opacity: 0; +} +.notewrap:hover .note::after, .notewrap:focus-visible .note::after { opacity: 1; } + +/* ── live activity ─────────────────────────────────────────── */ +.activity { margin-bottom: 10px; } +.actlist { display: flex; flex-direction: column; gap: 3px; } +.act { + display: grid; grid-template-columns: auto minmax(0, 1fr) auto; + gap: 6px; align-items: baseline; font-size: 11px; color: var(--muted); + opacity: 0.55; +} +.act.on { opacity: 1; } +.act .what, .acttable .what { + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; + font-family: ui-monospace, Menlo, monospace; +} +.acttable tr.on td { color: var(--fg); } +.acttable .pulse { color: var(--accent); font-size: 9px; margin-left: 5px; animation: pulse 2s ease-in-out infinite; } +@keyframes pulse { 50% { opacity: 0.25; } } +.acttable .dir { max-width: 18ch; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + +/* ── filters / forms ───────────────────────────────────────── */ +.filters { + display: flex; flex-wrap: wrap; gap: 6px; align-items: center; + padding: 10px 0; position: sticky; top: 0; z-index: 1; + background: var(--bg); +} +.filters input[type="search"] { min-width: 15ch; flex: 1 1 18ch; } +.filters .dates { display: flex; gap: 6px; align-items: center; } +.filters .datef { font-size: 11px; color: var(--muted); display: flex; gap: 4px; align-items: center; } +.filters button, .jjform button, .notform button { + background: var(--panel); color: var(--fg); + border: 1px solid var(--border); border-radius: 5px; + font: inherit; font-size: 12px; padding: 3px 10px; cursor: pointer; +} +.filters button:hover, .jjform button:hover, .notform button:hover { background: var(--hover); } +.count { margin: 0 0 8px; } +.busy { visibility: hidden; color: var(--accent); margin-right: 6px; } +.busy.htmx-request { visibility: visible; animation: pulse 1s linear infinite; } +.notespage, .jjpage { padding: 0 16px 40vh; max-width: 1100px; } +.err { + margin: 12px 16px; padding: 8px 10px; border-radius: 6px; + border: 1px solid var(--note); color: var(--note); + font-family: ui-monospace, Menlo, monospace; font-size: 12.5px; white-space: pre-wrap; +} + +/* ── add a note ────────────────────────────────────────────── */ +.addnote { margin: 10px 0; } +.addnote > summary { cursor: pointer; color: var(--muted); font-size: 13px; } +.notform { display: flex; flex-direction: column; gap: 6px; margin: 8px 0 14px; } +.notform .row { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; } +.notform .row.end { justify-content: space-between; } +.notform input[type="number"] { width: 8ch; } +.notform textarea { resize: vertical; font-family: inherit; } +.notform .on code { color: var(--fg); } +.asidehead { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; } +aside .meta { font-size: 11px; } + +/* lines picked to comment on, and lines you arrived at from a note */ +ol.code li.sel, ol.code li.focus { background: color-mix(in srgb, var(--accent) 16%, transparent); } +ol.code li.sel::before, ol.code li.focus::before { color: var(--accent); } +ol.code li.focus { box-shadow: inset 3px 0 var(--accent); } + +/* ── jj ────────────────────────────────────────────────────── */ +.jjform { display: flex; gap: 6px; align-items: center; padding: 10px 0; } +.jjform input[type="search"] { flex: 1; font-family: ui-monospace, Menlo, monospace; } +.jjform input[type="number"] { width: 8ch; } +.jjlog { font: 12.5px/1.7 ui-monospace, SFMono-Regular, Menlo, monospace; } +.jjrow { display: flex; gap: 8px; align-items: baseline; white-space: pre; } +.jjrow:hover { background: var(--hover); } +.jjrow .graph { color: var(--muted); white-space: pre; } +.jjrow .id { font-weight: 600; } +.jjrow .commit { color: var(--muted); } +.jjrow .when, .jjrow .who { color: var(--muted); } +.jjrow .refs { color: var(--note); } +.jjrow .flags { color: var(--note); font-style: italic; } +.jjrow .desc { color: var(--fg); overflow: hidden; text-overflow: ellipsis; } +.jjrow.blank { color: var(--muted); } +pre.desc { + margin: 0 0 12px; padding: 10px 12px; border-radius: 6px; + border: 1px solid var(--border); background: var(--panel); + font: 12.5px/1.5 ui-monospace, Menlo, monospace; white-space: pre-wrap; +} +table.changed { width: auto; } +table.changed td { border: none; padding: 1px 12px 1px 0; } +table.changed .st { color: var(--muted); font-size: 11px; width: 7ch; } +table.changed .st-added { color: var(--accent); } +table.changed .st-deleted { color: var(--note); } + +/* ── project hub ───────────────────────────────────────────── */ +.projects-main { padding-bottom: 20vh; } +.projects-main > section { max-width: 1200px; } +.project-refresh { margin: 10px 0; } +.project-refresh button, .project-card button, .project-action { + display: inline-block; background: var(--panel); color: var(--fg); + border: 1px solid var(--border); border-radius: 5px; + font: inherit; font-size: 12px; padding: 5px 10px; cursor: pointer; +} +.project-refresh button:hover, .project-card button:hover, .project-action:hover { + background: var(--hover); text-decoration: none; +} +.project-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 10px; } +.project-card { min-width: 0; padding: 12px; border: 1px solid var(--border); border-radius: 7px; background: var(--panel); } +.project-card > header { display: flex; align-items: center; justify-content: space-between; gap: 8px; } +.project-card h3 { min-width: 0; margin: 0; font: 600 14px/1.3 ui-monospace, Menlo, monospace; overflow: hidden; text-overflow: ellipsis; } +.project-path { margin: 8px 0; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.project-state { flex: none; padding: 1px 6px; border: 1px solid var(--border); border-radius: 99px; color: var(--muted); font-size: 10px; text-transform: uppercase; } +.project-state.active { border-color: var(--accent); color: var(--accent); } +.project-state.git { color: var(--note); } +.project-card form, .project-card .project-action { margin-top: 10px; } +.project-message { max-width: 1168px; } +.ok { margin: 12px 16px; padding: 8px 10px; border: 1px solid var(--accent); border-radius: 6px; color: var(--accent); } +.project-card[hidden] { display: none; } + +/* ── agent coverage colors ────────────────────────────────── + A bitmask is its agents' colors averaged. The blend is left to the + browser so these rules hold for any theme: a theme only has to name + --ag0..7, which every theme in themes.css does. */ +{{range .Masks}}.am{{.Mask}} { --cov: {{.Mix}}; } +{{end}} +/* ── syntax (theme colors, italics and weights are vars too, so + switching theme switches those with the colors) ─────────── */ +{{range .Syntax}}.s-{{.Class}} { color: var(--s-{{.Class}}, inherit); font-style: var(--s-{{.Class}}-fs, inherit); font-weight: var(--s-{{.Class}}-fw, inherit); } +{{end}} +@media (max-width: 1100px) { + body, body.with-aside { grid-template-columns: 1fr; } + nav, aside { position: static; height: auto; border: none; border-bottom: 1px solid var(--border); } +} +@media (max-width: 620px) { + .threadnode { grid-template-columns: 14px minmax(0, 1fr); } + .discussion h2 .meta { display: block; margin: 2px 0 0; } + .replyform { padding-left: 5px; } +} diff --git a/web/assets/typescript.scm b/web/assets/typescript.scm new file mode 100644 index 0000000..96cf9c3 --- /dev/null +++ b/web/assets/typescript.scm @@ -0,0 +1,15 @@ +; TypeScript highlights, from tree-sitter/tree-sitter-typescript v0.23.2 +; queries/highlights.scm (MIT). A supplement loaded after javascript.scm, as +; upstream composes it, so these patterns win. Upstream's +; ((identifier) @type (#match? "^[A-Z]")) is dropped: javascript.scm already +; paints capitalized identifiers as @constructor, and repainting every one of +; them as a type costs a second regex per identifier for a worse answer. + +["abstract" "declare" "enum" "implements" "interface" "keyof" "namespace" + "private" "protected" "public" "type" "readonly" "override" + "satisfies"] @keyword + +[(type_identifier) (predefined_type)] @type +(type_arguments "<" @punctuation.bracket ">" @punctuation.bracket) +(required_parameter (identifier) @variable.parameter) +(optional_parameter (identifier) @variable.parameter) diff --git a/web/assets/zig.scm b/web/assets/zig.scm new file mode 100644 index 0000000..a85383a --- /dev/null +++ b/web/assets/zig.scm @@ -0,0 +1,65 @@ +; Zig highlights, from tree-sitter-grammars/tree-sitter-zig v1.1.2 +; queries/highlights.scm (MIT). Reordered for later-patterns-win, capture names +; mapped onto zed syntax keys — upstream's keyword.* split collapses to +; @keyword, which zed themes colour as one — and the #lua-match? identifier +; heuristics rewritten as #match?, which this engine evaluates. + +["(" ")" "[" "]" "{" "}"] @punctuation.bracket +(payload "|" @punctuation.bracket) +[";" "," "." ":" "=>" "->"] @punctuation.delimiter +["=" "==" "!=" "<" ">" "<=" ">=" "+" "+%" "+|" "-" "-%" "-|" "*" "*%" "*|" + "**" "/" "%" "&" "|" "^" "~" "!" "||" "<<" "<<|" ">>" ".." ".*" ".?" "?" + "+=" "+%=" "+|=" "-=" "-%=" "-|=" "*=" "*%=" "*|=" "/=" "%=" "&=" "|=" "^=" + "<<=" "<<|=" ">>="] @operator + +["addrspace" "align" "allowzero" "and" "asm" "async" "await" "break" + "callconv" "catch" "comptime" "const" "continue" "defer" "else" "enum" + "errdefer" "error" "export" "extern" "fn" "for" "if" "inline" "linksection" + "noalias" "noinline" "nosuspend" "opaque" "or" "orelse" "packed" "pub" + "resume" "return" "struct" "suspend" "switch" "test" "threadlocal" "try" + "union" "usingnamespace" "var" "volatile" "while"] @keyword + +(builtin_type) @type +["anyframe" "anytype"] @type +(parameter type: (identifier) @type) +(variable_declaration (identifier) @type "=" + [(struct_declaration) (enum_declaration) (union_declaration) + (opaque_declaration)]) + +["null" "undefined" "unreachable"] @constant +(boolean) @constant +; an enum literal — .ok — is a member with nothing to its left +(field_expression . member: (identifier) @constant) +(enum_declaration (container_field type: (identifier) @constant)) + +(container_field name: (identifier) @property) +(field_initializer . (identifier) @property) +(field_expression (_) member: (identifier) @property) +; .x = 1 inside a Point{...} is a field, not the enum literal above +(initializer_list + (assignment_expression + left: (field_expression . member: (identifier) @property))) +(parameter name: (identifier) @variable.parameter) +(block_label (identifier) @label) +(break_label (identifier) @label) + +(function_declaration name: (identifier) @function) +(call_expression function: (identifier) @function) +(call_expression function: (field_expression member: (identifier) @function.method)) +(builtin_identifier) @function.builtin + +; Zig has no type-identifier node, only the TitleCase convention, and these +; land after the call patterns so that the convention wins the way upstream's +; first-pattern-wins order has it: std.ArrayList(u8) is a type, not a call. +((identifier) @type + (#match? @type "^[A-Z][a-zA-Z0-9_]*$")) +((identifier) @constant + (#match? @constant "^[A-Z][A-Z0-9_]+$")) + +[(integer) (float)] @number +[(string) (multiline_string) (character)] @string +(escape_sequence) @string.escape + +(comment) @comment +((comment) @comment.doc + (#match? @comment.doc "^//[/!]")) diff --git a/web/bench-browser.mjs b/web/bench-browser.mjs new file mode 100644 index 0000000..1e373a3 --- /dev/null +++ b/web/bench-browser.mjs @@ -0,0 +1,135 @@ +#!/usr/bin/env node +// Browser render benchmark for notevi web pages: drives headless Chrome over CDP +// (no npm deps; node >= 22 for native WebSocket). Serves the site dir, loads +// each page N times, reports parse/paint/load timings, node count, and the +// cost of jumping to the bottom of the file. +// +// node bench-browser.mjs SITE_DIR PAGE [PAGE...] [--shot DIR] + +import { spawn } from "node:child_process"; +import { createReadStream, existsSync, mkdirSync, writeFileSync } from "node:fs"; +import http from "node:http"; +import path from "node:path"; +import { tmpdir } from "node:os"; + +const CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"; +const RUNS = 3; + +const args = process.argv.slice(2); +const shotIdx = args.indexOf("--shot"); +let shotDir = null; +if (shotIdx >= 0) { + shotDir = args[shotIdx + 1]; + args.splice(shotIdx, 2); + mkdirSync(shotDir, { recursive: true }); +} +const [siteDir, ...pages] = args; +if (!siteDir || pages.length === 0) { + console.error("usage: node bench-browser.mjs SITE_DIR PAGE [PAGE...] [--shot DIR]"); + process.exit(2); +} + +// ── tiny static server ──────────────────────────────────────────────────── +const types = { html: "text/html", css: "text/css", js: "text/javascript" }; +const server = http.createServer((req, res) => { + const file = path.join(siteDir, decodeURIComponent(new URL(req.url, "http://x").pathname)); + if (!existsSync(file)) { res.writeHead(404).end(); return; } + res.writeHead(200, { "content-type": types[path.extname(file).slice(1)] ?? "text/plain" }); + createReadStream(file).pipe(res); +}); +await new Promise(r => server.listen(0, r)); +const port = server.address().port; + +// ── chrome + CDP ────────────────────────────────────────────────────────── +const profile = path.join(tmpdir(), "notevi-bench-profile"); +const chrome = spawn(CHROME, [ + "--headless=new", "--remote-debugging-port=0", `--user-data-dir=${profile}`, + "--no-first-run", "--disable-extensions", "--window-size=1600,1000", "about:blank", +], { stdio: ["ignore", "ignore", "pipe"] }); +const wsUrl = await new Promise((resolve, reject) => { + let buf = ""; + chrome.stderr.on("data", d => { + buf += d; + const m = buf.match(/DevTools listening on (ws:\/\/\S+)/); + if (m) resolve(m[1]); + }); + chrome.on("exit", () => reject(new Error("chrome exited"))); +}); +const debugPort = new URL(wsUrl).port; +const targets = await (await fetch(`http://127.0.0.1:${debugPort}/json/list`)).json(); +const pageTarget = targets.find(t => t.type === "page"); + +const ws = new WebSocket(pageTarget.webSocketDebuggerUrl); +await new Promise(r => (ws.onopen = r)); +let msgId = 0; +const pending = new Map(); +const eventWaiters = new Map(); +ws.onmessage = e => { + const msg = JSON.parse(e.data); + if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); } + if (msg.method && eventWaiters.has(msg.method)) { + eventWaiters.get(msg.method)(msg.params); + eventWaiters.delete(msg.method); + } +}; +const cdp = (method, params = {}) => new Promise(resolve => { + const id = ++msgId; + pending.set(id, m => resolve(m.result)); + ws.send(JSON.stringify({ id, method, params })); +}); +const waitEvent = method => new Promise(r => eventWaiters.set(method, r)); +const evaluate = async expr => { + const r = await cdp("Runtime.evaluate", { expression: expr, returnByValue: true, awaitPromise: true }); + return r.result?.value; +}; + +await cdp("Page.enable"); +await cdp("Runtime.enable"); + +const median = a => [...a].sort((x, y) => x - y)[a.length >> 1]; + +console.log("page kB nodes parse FCP DCL load toBottom"); +for (const p of pages) { + const url = `http://127.0.0.1:${port}/${p}`; + const runs = []; + for (let i = 0; i < RUNS; i++) { + const loaded = waitEvent("Page.loadEventFired"); + await cdp("Page.navigate", { url }); + await loaded; + const m = await evaluate(`(async () => { + await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r))); + const nav = performance.getEntriesByType("navigation")[0]; + const fcp = performance.getEntriesByType("paint").find(e => e.name === "first-contentful-paint"); + const t0 = performance.now(); + window.scrollTo(0, document.body.scrollHeight); + await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r))); + const toBottom = performance.now() - t0; + return JSON.stringify({ + kb: Math.round(nav.transferSize / 1024), + nodes: document.getElementsByTagName("*").length, + parse: Math.round(nav.domInteractive), + fcp: Math.round(fcp?.startTime ?? -1), + dcl: Math.round(nav.domContentLoadedEventEnd), + load: Math.round(nav.loadEventEnd), + toBottom: Math.round(toBottom), + }); + })()`); + runs.push(JSON.parse(m)); + } + const med = k => median(runs.map(r => r[k])); + console.log( + p.padEnd(38) + String(med("kb")).padStart(6) + String(med("nodes")).padStart(8) + + String(med("parse")).padStart(9) + String(med("fcp")).padStart(8) + + String(med("dcl")).padStart(8) + String(med("load")).padStart(8) + + String(med("toBottom")).padStart(10)); + if (shotDir) { + await evaluate(`window.scrollTo(0, 0)`); + await evaluate(`new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))`); + const shot = await cdp("Page.captureScreenshot", { format: "png" }); + writeFileSync(path.join(shotDir, p.replaceAll("/", "_") + ".png"), Buffer.from(shot.data, "base64")); + } +} + +chrome.kill(); +server.close(); +process.exit(0); diff --git a/web/bench_test.go b/web/bench_test.go new file mode 100644 index 0000000..094eb47 --- /dev/null +++ b/web/bench_test.go @@ -0,0 +1,328 @@ +package web + +import ( + "bytes" + "fmt" + "io" + "testing" +) + +// A realistic Rust chunk (~1.2KB): doc comments, generics, lifetimes, attrs, +// strings with escapes, macros — the constructs the highlighter works hardest +// on. Repetition parses fine; tree-sitter is not a compiler. +var rustChunk = []byte(`//! Module documentation with some text. +use std::{collections::HashMap, sync::Arc}; + +/// A cached entry with generics and lifetimes. +#[derive(Debug, Clone, PartialEq)] +pub struct CacheEntry<'a, T: Clone + Send> { + pub key: &'a str, + pub value: Arc<T>, + hits: u64, + tags: HashMap<String, Vec<u8>>, +} + +pub enum LookupResult<T> { + Hit(Arc<T>), + Miss { reason: &'static str, code: i32 }, + Tombstone, +} + +impl<'a, T: Clone + Send> CacheEntry<'a, T> { + pub fn new(key: &'a str, value: T) -> Self { + let tags = HashMap::new(); + Self { key, value: Arc::new(value), hits: 0, tags } + } + + /// Record a hit and return the running total. + pub fn touch(&mut self) -> u64 { + self.hits = self.hits.saturating_add(1); + if self.hits % 100 == 0 { + println!("entry {} hit {} times \"escaped\"", self.key, self.hits); + } + self.hits + } + + pub fn lookup(&self, keys: &[&str]) -> LookupResult<T> { + match keys.iter().position(|k| *k == self.key) { + Some(_) => LookupResult::Hit(self.value.clone()), + None => LookupResult::Miss { reason: "absent <key>", code: -1 }, + } + } +} + +const MAX_ENTRIES: usize = 4096; +static GREETING: &str = "hello \"quoted\" <world> & friends"; +`) + +// One chunk per language whose query leans on a predicate, to keep an eye on +// what predicates cost: go's builtin list is an #any-of? (a byte compare per +// call), while python, javascript and C run a casing regex over every +// identifier they see — and zig, which names its types by casing alone, runs +// two. +var langChunks = []struct { + path string + src []byte +}{ + {"bench.go", []byte(`// Package cache keeps entries with hit counts. +package cache + +import ( + "fmt" + "sync" +) + +// Entry is one cached value and its hit count. +type Entry struct { + Key string + Value []byte + hits uint64 + tags map[string][]byte +} + +const MaxEntries = 4096 + +func NewEntry(key string, value []byte) *Entry { + return &Entry{Key: key, Value: value, tags: make(map[string][]byte)} +} + +// Touch records a hit and returns the running total. +func (e *Entry) Touch(mu *sync.Mutex) uint64 { + mu.Lock() + defer mu.Unlock() + e.hits++ + if e.hits%100 == 0 { + fmt.Printf("entry %q hit %d times \"escaped\"\n", e.Key, e.hits) + } + return e.hits +} + +func (e *Entry) Lookup(keys []string) ([]byte, bool) { + for _, k := range keys { + if v, ok := e.tags[k]; ok && len(v) > 0 { + return v, true + } + } + return nil, false +} +`)}, + {"bench.py", []byte(`"""Module documentation with some text.""" +import sys +from collections import OrderedDict + +MAX_ENTRIES = 4096 + + +class CacheEntry: + """A cached entry with a hit count.""" + + def __init__(self, key, value): + self.key = key + self.value = value + self.hits = 0 + self.tags = OrderedDict() + + @property + def stale(self): + return self.hits > MAX_ENTRIES + + def touch(self): + self.hits += 1 + if self.hits % 100 == 0: + print(f"entry {self.key} hit {self.hits} times \"escaped\"", file=sys.stderr) + return self.hits + + def lookup(self, keys): + for k in keys: + if k in self.tags: + return self.tags[k], True + return None, False +`)}, + {"bench.js", []byte(`// Cache entries with hit counts. +import { EventEmitter } from "node:events"; + +const MAX_ENTRIES = 4096; + +export class CacheEntry extends EventEmitter { + constructor(key, value) { + super(); + this.key = key; + this.value = value; + this.hits = 0; + this.tags = new Map(); + } + + get stale() { + return this.hits > MAX_ENTRIES; + } + + touch() { + this.hits += 1; + if (this.hits % 100 === 0) { + console.log(` + "`entry ${this.key} hit ${this.hits} times \"escaped\"`" + `); + } + return this.hits; + } + + lookup(keys) { + return keys.map((k) => this.tags.get(k)).find((v) => v !== undefined) ?? null; + } +} +`)}, + {"bench.c", []byte(`/* Cache entries with hit counts. */ +#include <stdio.h> +#include <string.h> + +#define MAX_ENTRIES 4096 + +struct cache_entry { + const char *key; + unsigned char *value; + unsigned long hits; +}; + +static struct cache_entry *entry_new(const char *key, unsigned char *value) { + static struct cache_entry e; + e.key = key; + e.value = value; + e.hits = 0; + return &e; +} + +unsigned long entry_touch(struct cache_entry *e) { + e->hits++; + if (e->hits % 100 == 0) { + fprintf(stderr, "entry %s hit %lu times \"escaped\"\n", e->key, e->hits); + } + return e->hits; +} + +int entry_lookup(struct cache_entry *e, const char *key) { + return e->key != NULL && strcmp(e->key, key) == 0; +} +`)}, + {"bench.zig", []byte(`// Cache entries with hit counts. +const std = @import("std"); + +const MAX_ENTRIES: usize = 4096; + +const CacheEntry = struct { + key: []const u8, + value: []u8, + hits: u64 = 0, + + fn init(key: []const u8, value: []u8) CacheEntry { + return CacheEntry{ .key = key, .value = value }; + } + + fn stale(self: CacheEntry) bool { + return self.hits > MAX_ENTRIES; + } + + fn touch(self: *CacheEntry) u64 { + self.hits += 1; + if (self.hits % 100 == 0) { + std.debug.print("entry {s} hit {d} times \"escaped\"\n", .{ self.key, self.hits }); + } + return self.hits; + } + + fn lookup(self: CacheEntry, keys: []const []const u8) ?[]u8 { + for (keys) |k| { + if (std.mem.eql(u8, k, self.key)) return self.value; + } + return null; + } +}; +`)}, +} + +func synth(chunk []byte, size int) []byte { + var b bytes.Buffer + for b.Len() < size { + b.Write(chunk) + } + return b.Bytes() +} + +func synthRust(size int) []byte { return synth(rustChunk, size) } + +var sizes = []int{128 << 10, 1 << 20, 4 << 20} + +func benchHL(b *testing.B) *highlighter { + b.Helper() + return newHighlighter(loadTheme("", "", "dark"), loadTheme("", "", "light")) +} + +// tree-sitter parse + query + paint only +func BenchmarkClassify(b *testing.B) { + hl := benchHL(b) + for _, size := range sizes { + src := synthRust(size) + b.Run(fmt.Sprintf("%dKB", size>>10), func(b *testing.B) { + b.SetBytes(int64(len(src))) + b.ReportAllocs() + for i := 0; i < b.N; i++ { + hl.classify("bench.rs", src) + } + }) + } +} + +// the same work for the languages whose queries evaluate predicates +func BenchmarkClassifyLangs(b *testing.B) { + hl := benchHL(b) + for _, c := range langChunks { + src := synth(c.src, 1<<20) + b.Run(c.path, func(b *testing.B) { + b.SetBytes(int64(len(src))) + b.ReportAllocs() + for i := 0; i < b.N; i++ { + hl.classify(c.path, src) + } + }) + } +} + +// classify + full per-line HTML emit +func BenchmarkRender(b *testing.B) { + hl := benchHL(b) + for _, size := range sizes { + src := synthRust(size) + b.Run(fmt.Sprintf("%dKB", size>>10), func(b *testing.B) { + b.SetBytes(int64(len(src))) + b.ReportAllocs() + for i := 0; i < b.N; i++ { + f := &File{Path: "bench.rs", NoteAt: map[int]int{}} + f.render(src, hl) + } + }) + } +} + +// template execution for an already-rendered file page +func BenchmarkExecute(b *testing.B) { + hl := benchHL(b) + tpl := newTemplates(hl) + site := &Site{ + Title: "bench", Files: map[string]*File{}, + Theme: loadTheme("", "", "dark"), Light: loadTheme("", "", "light"), + Agents: []*Agent{{Name: "bench", Short: "bench", Bit: 1}}, + } + for _, size := range sizes { + src := synthRust(size) + f := &File{Path: "bench.rs", NoteAt: map[int]int{}, Traced: true, Change: "zzzzzzzz"} + f.cover(1, bytes.Count(src, []byte("\n"))/2, 1) + f.render(src, hl) + p := &page{Site: site, Kind: "file", Title: "bench", Root: "", Current: f.Path, File: f} + b.Run(fmt.Sprintf("%dKB", size>>10), func(b *testing.B) { + b.SetBytes(int64(len(src))) + b.ReportAllocs() + for i := 0; i < b.N; i++ { + if err := tpl.Execute(io.Discard, p); err != nil { + b.Fatal(err) + } + } + }) + } +} diff --git a/web/css.go b/web/css.go new file mode 100644 index 0000000..e2637bc --- /dev/null +++ b/web/css.go @@ -0,0 +1,157 @@ +// css.go — the stylesheet is generated per site: theme colors become custom +// properties, one block per scheme, and the per-agent coverage colors are +// blended from them in the browser so any theme can supply them. +// +// Everything switchable is a custom property on :root. That is what lets +// themes.css hold nothing but one block per theme (writeThemesCSS) and the +// picker repaint the page by setting a single attribute. +package web + +import ( + "encoding/json" + "fmt" + "io" + "strings" + texttemplate "text/template" +) + +type cssVar struct{ K, V string } + +type synCSS struct{ Class string } + +type maskCSS struct { + Mask uint8 + Mix string +} + +func renderCSS(w io.Writer, site *Site) error { + css, err := texttemplate.ParseFS(tfs, "assets/style.css.tmpl") + if err != nil { + return err + } + keys := syntaxKeys(site.Theme, site.Light) + var syn []synCSS + for _, k := range keys { + syn = append(syn, synCSS{Class: cssKey(k)}) + } + var masks []maskCSS + for _, m := range site.masks() { + masks = append(masks, maskCSS{Mask: m, Mix: site.maskMix(m)}) + } + return css.Execute(w, map[string]any{ + "DarkName": site.Theme.Name, "LightName": site.Light.Name, + "DarkVars": themeVars(site.Theme, keys), "LightVars": themeVars(site.Light, keys), + "Syntax": syn, "Masks": masks, + }) +} + +// themeVars is one theme as custom properties: its own colors, the syntax +// colors under the keys the site paints with (resolved along their dots, so a +// theme that only names "punctuation" still colors brackets), and the agent +// colors every coverage blend is mixed from. +func themeVars(t *Theme, keys []string) []cssVar { + // bg and panel are what everything else is read against, so they are the + // two that may not carry a theme's alpha channel through + vars := []cssVar{ + {"--bg", hex6(t.Bg)}, {"--fg", t.Fg}, {"--panel", hex6(t.Panel)}, {"--border", t.Border}, + {"--ln", t.LineNo}, {"--muted", t.Muted}, {"--accent", t.Accent}, + {"--note", t.Note}, {"--hover", t.Hover}, + } + for _, k := range keys { + key := resolveKey(t, k) + if key == "" { + continue + } + s, c := t.Syntax[key], cssKey(k) + vars = append(vars, cssVar{"--s-" + c, s.Color}) + if s.FontStyle != nil && *s.FontStyle != "" && *s.FontStyle != "normal" { + vars = append(vars, cssVar{"--s-" + c + "-fs", *s.FontStyle}) + } + if s.FontWeight != nil && *s.FontWeight > 0 { + vars = append(vars, cssVar{"--s-" + c + "-fw", fmt.Sprintf("%.0f", *s.FontWeight)}) + } + } + for i := 0; i < maxAgents; i++ { + vars = append(vars, cssVar{fmt.Sprintf("--ag%d", i), hex6(t.Player(i))}) + } + return vars +} + +// maskMix is the color of a coverage bitmask: the agent colors it stands for, +// averaged. The average is written as nested color-mix rather than mixed here, +// so the same rule holds for every theme the browser can switch to. +func (s *Site) maskMix(mask uint8) string { + var idx []int + for i, a := range s.Agents { + if a.Bit != 0 && mask&a.Bit != 0 { + idx = append(idx, i) + } + } + return mixExpr(idx) +} + +func mixExpr(idx []int) string { + switch len(idx) { + case 0: + return "var(--fg)" + case 1: + return fmt.Sprintf("var(--ag%d)", idx[0]) + } + return fmt.Sprintf("color-mix(in srgb, var(--ag%d) %.3f%%, %s)", + idx[0], 100/float64(len(idx)), mixExpr(idx[1:])) +} + +// ── the switchable themes ───────────────────────────────────────────────── + +// writeThemesCSS writes one block per theme found on this machine. It is only +// fetched once a theme has been picked (or the picker opened), so the page +// costs nothing for the reader who never switches. +func writeThemesCSS(w io.Writer, themes []*Theme, keys []string) { + fmt.Fprintf(w, "/* %d themes, found on this machine — set data-theme on :root to wear one */\n", len(themes)) + for _, t := range themes { + fmt.Fprintf(w, ":root[data-theme=%q] {\n", t.ID) + for _, v := range themeVars(t, keys) { + fmt.Fprintf(w, " %s: %s;\n", v.K, v.V) + } + scheme := "dark" + if t.Appearance == "light" { + scheme = "light" + } + fmt.Fprintf(w, " color-scheme: %s;\n}\n", scheme) + } +} + +// themeCard is a theme as the picker shows it: a name, where it came from, and +// the few colors that make it recognizable at a glance. +type themeCard struct { + ID string `json:"id"` + Name string `json:"name"` + Src string `json:"src"` + Dark bool `json:"dark"` + Sw []string `json:"sw"` +} + +// writeThemesJS is the picker's menu. It is a script, not JSON, because the +// static export is opened from the filesystem, where fetch() is not allowed +// but a <script src> still loads. +func writeThemesJS(w io.Writer, themes []*Theme) { + cards := make([]themeCard, 0, len(themes)) + for _, t := range themes { + syn := func(key string) string { + if k := resolveKey(t, key); k != "" { + return hex6(t.Syntax[k].Color) + } + return hex6(t.Fg) + } + cards = append(cards, themeCard{ID: t.ID, Name: t.Name, Src: t.Source, + Dark: t.Appearance != "light", + Sw: []string{hex6(t.Bg), hex6(t.Fg), hex6(t.Accent), + syn("keyword"), syn("string"), syn("function")}}) + } + b, err := json.Marshal(cards) + if err != nil { + b = []byte("[]") + } + fmt.Fprintf(w, "// %d themes, written by notevi from this machine's zed and helix installs\n", len(cards)) + fmt.Fprintf(w, "window.VRSITE_THEMES=%s;\n", strings.ReplaceAll(string(b), "},{", "},\n{")) +} diff --git a/web/highlight_test.go b/web/highlight_test.go new file mode 100644 index 0000000..9cb8e36 --- /dev/null +++ b/web/highlight_test.go @@ -0,0 +1,184 @@ +package web + +import ( + "strings" + "sync" + "testing" + + sitter "github.com/tree-sitter/go-tree-sitter" +) + +func testHighlighter(t *testing.T) *highlighter { + t.Helper() + return newHighlighter(loadTheme("", "", "dark"), loadTheme("", "", "light")) +} + +// One snippet per language, mapping a piece of its source to the class the One +// theme implies for it. Everything asserted here is a key both One Dark and +// One Light colour differently from plain foreground. +var samples = []struct { + path string + src string + want map[string]string +}{ + {"a.rs", "// note\nfn main() { let s = \"hi\"; }\n", + map[string]string{"fn": "keyword", `"hi"`: "string", "// note": "comment", "main": "function"}}, + {"a.go", "// note\nfunc main() { s := \"hi\"; _ = s }\n", + map[string]string{"func": "keyword", `"hi"`: "string", "// note": "comment", "main": "function"}}, + {"a.py", "# note\nclass Frame:\n def draw(self):\n widget = Widget\n return len(\"hi\")\n", + map[string]string{"class": "keyword", `"hi"`: "string", "# note": "comment", + "draw": "function", "len": "function", "Frame": "constructor", + "Widget": "constructor", "self": "variable-special", "widget": ""}}, + {"a.js", "// note\nfunction main() { const s = \"hi\"; return s; }\n", + map[string]string{"function": "keyword", `"hi"`: "string", "// note": "comment", "main": "function"}}, + {"a.ts", "// note\nfunction main(n: number): string { return \"hi\"; }\n", + map[string]string{"function": "keyword", `"hi"`: "string", "// note": "comment", + "number": "type", "main": "function"}}, + {"a.tsx", "// note\nconst e = <div id=\"x\" />;\n", + map[string]string{"const": "keyword", `"x"`: "string", "// note": "comment", "id": "attribute"}}, + {"a.c", "// note\n#include <stdio.h>\nint main(void) { const char *s = \"hi\"; return MAX; }\n", + map[string]string{"const": "keyword", `"hi"`: "string", "// note": "comment", + "int": "type", "main": "function", "#include": "preproc", + "<stdio.h>": "string", "MAX": "constant"}}, + {"a.cc", "// note\nnamespace n { class C { const char *s = \"hi\"; }; }\n", + map[string]string{"namespace": "keyword", `"hi"`: "string", "// note": "comment", "char": "type"}}, + // .h goes to the C++ grammar, but c.scm's patterns still have to reach it + {"a.h", "// note\ntemplate <class T> struct Box { T v; };\n", + map[string]string{"template": "keyword", "struct": "keyword", "// note": "comment", "T": "type"}}, + // zig names types by casing rather than by node, so Point and MAX are the + // query's two #match? heuristics rather than anything the grammar reports + {"a.zig", "// note\nconst std = @import(\"std\");\nconst Point = struct { x: u8 };\n" + + "pub fn main() !void {\n const MAX: u8 = 1;\n std.debug.print(\"hi\", .{ .x = MAX });\n}\n", + map[string]string{"const": "keyword", `"hi"`: "string", "// note": "comment", + "main": "function", "@import": "function", "u8": "type", "Point": "type", + "MAX": "constant", "x": "property"}}, + {"a.json", "{\n \"a\": \"hi\",\n \"b\": 12\n}\n", + map[string]string{`"hi"`: "string", `"a"`: "string-special", "12": "number"}}, + {"a.sh", "# note\nif true; then\n ls -l \"$dir\"\nfi\n", + map[string]string{"if": "keyword", "# note": "comment", "ls": "function", + "-l": "constant", "dir": "property"}}, +} + +// classOf reports the single class covering every byte of text's first +// occurrence in src, or "" when the run is unclassified or not uniform. +func classOf(hl *highlighter, path, src, text string) string { + classes := hl.classify(path, []byte(src)) + i := strings.Index(src, text) + if i < 0 { + return "" + } + for j := i + 1; j < i+len(text); j++ { + if classes[j] != classes[i] { + return "" + } + } + return hl.classNames[classes[i]] +} + +func TestClassifyPerLanguage(t *testing.T) { + hl := testHighlighter(t) + for _, s := range samples { + for text, want := range s.want { + if got := classOf(hl, s.path, s.src, text); got != want { + t.Errorf("%s: %q classified %q, want %q", s.path, text, got, want) + } + } + } +} + +func TestClassifyUnknownExtension(t *testing.T) { + hl := testHighlighter(t) + // text that every grammar would happily highlight, under paths none claims + src := []byte("// note\nfn main() { let s = \"hi\"; }\n") + for _, path := range []string{"notes.txt", "README.md", "Makefile", "a/b.unknown", ".gitignore", ""} { + classes := hl.classify(path, src) + if len(classes) != len(src) { + t.Fatalf("%q: got %d classes for %d bytes", path, len(classes), len(src)) + } + for i, c := range classes { + if c != 0 { + t.Fatalf("%q: byte %d classified %q, want plain text", path, i, hl.classNames[c]) + } + } + } +} + +// Every predicate a vendored query uses has to be one go-tree-sitter actually +// evaluates in QueryMatches.Next. Anything else lands in these two buckets, +// where it is parsed, ignored, and silently paints matches it should not. +func TestQueriesUseOnlyEvaluatedPredicates(t *testing.T) { + hl := testHighlighter(t) + for _, g := range grammars { + l := hl.byExt[g.exts[0]] + name := strings.Join(g.scms, "+") + for i := uint(0); i < l.query.PatternCount(); i++ { + for _, p := range l.query.GeneralPredicates(i) { + t.Errorf("%s pattern %d: #%s is not evaluated", name, i, p.Operator) + } + for _, p := range l.query.PropertyPredicates(i) { + t.Errorf("%s pattern %d: #is? %s is not evaluated", name, i, p.Property.Key) + } + } + } +} + +// A query that fails to compile is fatal at startup, so report the real error +// here rather than letting the process exit out from under the test binary. +func TestQueriesCompile(t *testing.T) { + for _, g := range grammars { + var scm strings.Builder + for _, name := range g.scms { + b, err := tfs.ReadFile("assets/" + name + ".scm") + if err != nil { + t.Fatal(err) + } + scm.Write(b) + } + if _, err := sitter.NewQuery(sitter.NewLanguage(g.lang()), scm.String()); err != nil { + t.Errorf("%s: %v", strings.Join(g.scms, "+"), err) + } + } +} + +// Class names are theme syntax keys, so css.go's .s-<key> rules — generated +// from the union of both themes' keys — already cover every new language. +func TestClassNamesHaveTheme(t *testing.T) { + dark, light := loadTheme("", "", "dark"), loadTheme("", "", "light") + hl := newHighlighter(dark, light) + styled := map[string]bool{} + for _, th := range []*Theme{dark, light} { + for k := range th.Syntax { + styled[strings.ReplaceAll(k, ".", "-")] = true + } + } + for _, cls := range hl.classNames[1:] { + if !styled[cls] { + t.Errorf("class %q has no .s-%s rule in either theme", cls, cls) + } + } +} + +func TestClassifyIsRaceFree(t *testing.T) { + hl := testHighlighter(t) + want := make([][]int16, len(samples)) + for i, s := range samples { + want[i] = hl.classify(s.path, []byte(s.src)) + } + var wg sync.WaitGroup + for range 8 { + wg.Add(1) + go func() { + defer wg.Done() + for i, s := range samples { + got := hl.classify(s.path, []byte(s.src)) + for j := range got { + if got[j] != want[i][j] { + t.Errorf("%s: byte %d classified %d, want %d", s.path, j, got[j], want[i][j]) + return + } + } + } + }() + } + wg.Wait() +} diff --git a/web/jj.go b/web/jj.go new file mode 100644 index 0000000..1dd4a4d --- /dev/null +++ b/web/jj.go @@ -0,0 +1,298 @@ +// jj.go — every read of the repository goes through here. +// +// These helpers never modify project history or its working copy +// (--ignore-working-copy means they never even snapshot it). Sidecar mutation +// is isolated in the shared sidecar package. +package web + +import ( + "context" + "fmt" + "os" + "os/exec" + "strings" + "time" +) + +// Field separator inside a templated line, record marker at its start. Both +// are ASCII control characters that cannot appear in ids, names or a +// description's first line, so parsing stays trivial even under a graph. +const ( + jjRec = "\x1e" // as jj prints it + jjSep = "\x1f" + // as it is written inside a jj template string literal + jjRecEsc = `\x1e` + jjSepEsc = `\x1f` +) + +const jjTimeout = 30 * time.Second + +// jjRun executes jj read-only in repo. stderr comes back inside the error so +// the page can show what jj complained about. +func jjRun(repo string, args ...string) ([]byte, error) { + ctx, cancel := context.WithTimeout(context.Background(), jjTimeout) + defer cancel() + cmd := exec.CommandContext(ctx, "jj", append([]string{"--ignore-working-copy"}, args...)...) + cmd.Dir = repo + var errb strings.Builder + cmd.Stderr = &errb + out, err := cmd.Output() + if err != nil { + msg := strings.TrimSpace(errb.String()) + if msg == "" { + msg = err.Error() + } + return out, fmt.Errorf("jj %s: %s", strings.Join(args, " "), msg) + } + return out, nil +} + +// mustJJ is the static-build path: a jj failure there is fatal. +func mustJJ(repo string, args ...string) []byte { + out, err := jjRun(repo, args...) + if err != nil { + fmt.Fprintln(os.Stderr, err) + fatal("repository read failed") + } + return out +} + +// checkRevset rejects input that jj would read as a flag; revsets themselves +// are a query language, not a shell, and are passed as one argv entry. +func checkRevset(r string) error { + r = strings.TrimSpace(r) + if strings.HasPrefix(r, "-") { + return fmt.Errorf("revset must not start with %q", "-") + } + if len(r) > 512 { + return fmt.Errorf("revset too long") + } + return nil +} + +func resolveChange(repo, rev string) (string, error) { + change, _, err := resolveRevision(repo, rev) + return change, err +} + +func resolveRevision(repo, rev string) (change, commit string, err error) { + if rev == "" { + rev = "@" + } + if err := checkRevset(rev); err != nil { + return "", "", err + } + out, err := jjRun(repo, "log", "-r", "exactly(("+rev+"), 1)", "--no-graph", + "-T", "change_id ++ \"\\n\" ++ commit_id ++ \"\\n\"") + if err != nil { + return "", "", err + } + ids := strings.Fields(string(out)) + if len(ids) != 2 { + return "", "", fmt.Errorf("revset %q did not resolve to one change and commit", rev) + } + return ids[0], ids[1], nil +} + +// changeBrief resolves a revset to the one change it names, with everything a +// page says about it. One call answers both "which change" and "which commit +// is under it right now" — the second is what content is cached against, since +// a change id is a pointer and the commit beneath it is rewritten on every +// edit. +func changeBrief(repo, rev string) (Row, error) { + rows, err := LogRows(repo, rev, "", 1) + if err != nil { + return Row{}, err + } + for _, r := range rows { + if !r.Blank() { + return r, nil + } + } + return Row{}, fmt.Errorf("revset %q matches no change", rev) +} + +func fileList(repo, rev string) ([]string, error) { + out, err := jjRun(repo, "file", "list", "-r", rev) + if err != nil { + return nil, err + } + return strings.Split(strings.TrimRight(string(out), "\n"), "\n"), nil +} + +func fileShow(repo, rev, path string) ([]byte, error) { + return jjRun(repo, "file", "show", "-r", rev, "--", path) +} + +// ── log / op log rows ───────────────────────────────────────────────────── + +// A Row is one line of jj output: the graph art it was drawn with, plus the +// fields the inline template produced. Graph-only lines (│, ~) carry Graph +// alone and render as decoration. +type Row struct { + Graph string + ID, Short string + Commit, CommitShort string + Author, When, End string + Refs, Flags, Desc string + Op bool +} + +func (r Row) Blank() bool { return r.ID == "" } + +// tmplFields builds `"\x1e" ++ f1 ++ "\x1f" ++ f2 ... ++ "\n"`: one line per +// row, record-marked so the graph art in front of it is separable. +func tmplFields(fields ...string) string { + return `"` + jjRecEsc + `" ++ ` + strings.Join(fields, ` ++ "`+jjSepEsc+`" ++ `) + ` ++ "\n"` +} + +var ( + commitTmpl = tmplFields( + "change_id", + "change_id.short(8)", + "commit_id", + "commit_id.short(8)", + "author.email()", + `committer.timestamp().format("%Y-%m-%d %H:%M")`, + `bookmarks.join(" ")`, + `separate(" ", if(current_working_copy, "working copy"), if(empty, "empty"), if(conflict, "conflict"), if(divergent, "divergent"))`, + "description.first_line()", + ) + opTmpl = tmplFields( + "id", + "id.short(12)", + `""`, + `""`, + "user", + `time.start().format("%Y-%m-%d %H:%M:%S")`, + `""`, + `time.end().format("%H:%M:%S")`, + "description.first_line()", + ) +) + +func parseRows(out []byte, op bool) []Row { + var rows []Row + for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") { + i := strings.Index(line, jjRec) + if i < 0 { + if strings.TrimSpace(line) != "" { + rows = append(rows, Row{Graph: line, Op: op}) + } + continue + } + f := strings.Split(line[i+len(jjRec):], jjSep) + for len(f) < 9 { + f = append(f, "") + } + r := Row{Graph: line[:i], ID: f[0], Short: f[1], Commit: f[2], CommitShort: f[3], + Author: f[4], When: f[5], Refs: f[6], Flags: f[7], Desc: f[8], Op: op} + if op { + r.End, r.Flags = r.Flags, "" + } + rows = append(rows, r) + } + return rows +} + +// LogRows runs `jj log -r REVSET` with the inline template. atOp, when set, +// runs the query as of that operation — the debugging view. +func LogRows(repo, revset, atOp string, limit int) ([]Row, error) { + if err := checkRevset(revset); err != nil { + return nil, err + } + args := []string{"log", "-T", commitTmpl} + if strings.TrimSpace(revset) != "" { + args = append(args, "-r", revset) + } + if atOp != "" { + if err := checkRevset(atOp); err != nil { + return nil, err + } + args = append(args, "--at-operation", atOp) + } + if limit > 0 { + args = append(args, "-n", fmt.Sprint(limit)) + } + out, err := jjRun(repo, args...) + if err != nil { + return nil, err + } + return parseRows(out, false), nil +} + +func OpRows(repo string, limit int) ([]Row, error) { + args := []string{"op", "log", "-T", opTmpl} + if limit > 0 { + args = append(args, "-n", fmt.Sprint(limit)) + } + out, err := jjRun(repo, args...) + if err != nil { + return nil, err + } + return parseRows(out, true), nil +} + +// ── one change ──────────────────────────────────────────────────────────── + +type ChangeFile struct { + Status, Path string +} + +type Change struct { + Row Row + Desc string + Files []ChangeFile + Stat string + Parents []Row +} + +var statusName = map[string]string{"A": "added", "M": "modified", "D": "deleted", "R": "renamed", "C": "copied"} + +func LoadChange(repo, rev string) (*Change, error) { + rows, err := LogRows(repo, rev, "", 1) + if err != nil { + return nil, err + } + var row Row + for _, r := range rows { + if !r.Blank() { + row = r + break + } + } + if row.Blank() { + return nil, fmt.Errorf("no change matches %q", rev) + } + c := &Change{Row: row} + // full description separately: it is multi-line, so it cannot ride along + // in the one-line-per-row template + if out, err := jjRun(repo, "log", "-r", row.ID, "--no-graph", "-n", "1", "-T", "description"); err == nil { + c.Desc = strings.TrimRight(string(out), "\n") + } + if out, err := jjRun(repo, "diff", "-r", row.ID, "--summary"); err == nil { + for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") { + if len(line) > 2 { + st := statusName[line[:1]] + if st == "" { + st = line[:1] + } + c.Files = append(c.Files, ChangeFile{Status: st, Path: line[2:]}) + } + } + } + if out, err := jjRun(repo, "diff", "-r", row.ID, "--stat"); err == nil { + lines := strings.Split(strings.TrimRight(string(out), "\n"), "\n") + if n := len(lines); n > 0 { + c.Stat = strings.TrimSpace(lines[n-1]) + } + } + if rows, err := LogRows(repo, "parents("+row.ID+")", "", 8); err == nil { + for _, r := range rows { + if !r.Blank() { + c.Parents = append(c.Parents, r) + } + } + } + return c, nil +} diff --git a/web/log.go b/web/log.go new file mode 100644 index 0000000..b45eec5 --- /dev/null +++ b/web/log.go @@ -0,0 +1,56 @@ +package web + +import ( + "fmt" + "os" + "sync" +) + +// logStore is implemented by the production jj sidecar and by the file-backed +// adapter used in tests. Append's callback makes session note numbering atomic +// with the content update. +type logStore interface { + Read() ([]byte, error) + Generation() (string, error) + Append(func(current []byte) ([]byte, error)) error + String() string +} + +type fileLog struct { + path string + mu sync.Mutex +} + +func newFileLog(path string) *fileLog { return &fileLog{path: path} } + +func (l *fileLog) String() string { return l.path } + +func (l *fileLog) Read() ([]byte, error) { return os.ReadFile(l.path) } + +func (l *fileLog) Generation() (string, error) { + info, err := os.Stat(l.path) + if err != nil { + return "", err + } + return fmt.Sprintf("%d:%d", info.Size(), info.ModTime().UnixNano()), nil +} + +func (l *fileLog) Append(makePayload func(current []byte) ([]byte, error)) error { + l.mu.Lock() + defer l.mu.Unlock() + current, err := os.ReadFile(l.path) + if err != nil && !os.IsNotExist(err) { + return err + } + payload, err := makePayload(current) + if err != nil { + return err + } + f, err := os.OpenFile(l.path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644) + if err != nil { + return err + } + defer f.Close() + _, err = f.Write(payload) + return err +} diff --git a/web/markdown.go b/web/markdown.go new file mode 100644 index 0000000..476e67c --- /dev/null +++ b/web/markdown.go @@ -0,0 +1,259 @@ +// markdown.go — note text is markdown. Agents write prose about code: +// backticked identifiers, bullet lists, the occasional fenced snippet, and +// links out. Rendering it as one escaped <p> threw all of that away. +// +// Two things make markdown fit text nobody wrote for a browser: +// +// - angle brackets are never markup. In a note they are code — +// RwLock<SysvarCache> is a type — so the HTML parsers come out and the +// brackets survive as the characters they were typed as. +// - fenced code goes through the same tree-sitter highlighter as the code +// view, so a snippet in a note is painted by the reader's theme exactly +// like the file it was copied from. +package web + +import ( + "bytes" + stdhtml "html" + "html/template" + "net/url" + "path" + "regexp" + "strconv" + "strings" + + "github.com/yuin/goldmark" + "github.com/yuin/goldmark/ast" + "github.com/yuin/goldmark/extension" + mdparser "github.com/yuin/goldmark/parser" + "github.com/yuin/goldmark/renderer" + "github.com/yuin/goldmark/renderer/html" + mdtext "github.com/yuin/goldmark/text" + "github.com/yuin/goldmark/util" +) + +// markdown renders note text. goldmark is safe for concurrent use, which the +// server (a goroutine per request) and the export (a goroutine per file) both +// rely on. +type markdown struct{ md goldmark.Markdown } + +// newMarkdown builds the note renderer. GFM adds the things people actually +// type — tables, ~~strikethrough~~, bare URLs, task lists — and hard wraps +// keep a newline a newline, since a note is typed into a textarea or passed on +// a command line, not authored as a document. +func newMarkdown(hl *highlighter) *markdown { + md := goldmark.New( + goldmark.WithParser(notesParser()), + goldmark.WithExtensions(extension.GFM), + goldmark.WithRendererOptions(html.WithHardWraps()), + ) + // lower priority number wins: this one replaces the stock code-block + // renderers, everything else stays goldmark's + md.Renderer().AddOptions(renderer.WithNodeRenderers( + util.Prioritized(¬eRenderer{hl: hl}, 100))) + return &markdown{md: md} +} + +// goldmark's priorities for the two parsers that read angle brackets as +// markup, from mdparser.DefaultBlockParsers and mdparser.DefaultInlineParsers. +const ( + htmlBlockPriority = 900 + rawHTMLPriority = 400 +) + +// notesParser is goldmark's default parser with those two dropped. Leaving +// them in costs the note either way: goldmark's safe default deletes raw HTML +// outright, so "RwLock<SysvarCache>" loses a word, and the block form +// additionally stops parsing markdown for the rest of the paragraph — a note +// that opens with a quoted <div> would render its links and lists as source. +// Without the parsers a bracket is just a character the text renderer escapes, +// which is both what the writer meant and the one thing a browser cannot act +// on. Dropping by priority keeps every other default, including any upstream +// adds later. +func notesParser() mdparser.Parser { + return mdparser.NewParser( + mdparser.WithBlockParsers(without(mdparser.DefaultBlockParsers(), htmlBlockPriority)...), + mdparser.WithInlineParsers(without(mdparser.DefaultInlineParsers(), rawHTMLPriority)...), + mdparser.WithParagraphTransformers(mdparser.DefaultParagraphTransformers()...), + ) +} + +func without(vs []util.PrioritizedValue, priority int) []util.PrioritizedValue { + out := vs[:0] + for _, v := range vs { + if v.Priority != priority { + out = append(out, v) + } + } + return out +} + +// newNoteLinkParser is shared across one model build. It uses the same parser +// and GFM extensions as rendered note bodies, so only links the reader can +// actually click become mentions (code spans and plain prose do not). +func newNoteLinkParser() mdparser.Parser { + return goldmark.New( + goldmark.WithParser(notesParser()), + goldmark.WithExtensions(extension.GFM), + ).Parser() +} + +func noteLinks(p mdparser.Parser, source string) []int { + if !strings.Contains(source, "note") { + return nil + } + src := []byte(source) + doc := p.Parse(mdtext.NewReader(src)) + seen := map[int]bool{} + var ids []int + _ = ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) { + if !entering || n.Kind() != ast.KindLink { + return ast.WalkContinue, nil + } + id := noteLinkID(string(n.(*ast.Link).Destination)) + if id > 0 && !seen[id] { + seen[id] = true + ids = append(ids, id) + } + return ast.WalkContinue, nil + }) + return ids +} + +// noteLinkID recognizes local links ending in note/N. Leading /, ./ and ../ +// components are all allowed; schemes and protocol-relative hosts are not. +func noteLinkID(destination string) int { + u, err := url.Parse(strings.TrimSpace(destination)) + if err != nil || u.Scheme != "" || u.Host != "" { + return 0 + } + clean := path.Clean("/" + strings.TrimSuffix(u.Path, ".html")) + parts := strings.Split(strings.Trim(clean, "/"), "/") + if len(parts) < 2 || parts[len(parts)-2] != "note" { + return 0 + } + id, err := strconv.Atoi(parts[len(parts)-1]) + if err != nil || id < 1 { + return 0 + } + return id +} + +// render turns one note's text into HTML. A note is never worth losing to a +// renderer error, so a failure falls back to the text as written. +func (m *markdown) render(text string) template.HTML { + if strings.TrimSpace(text) == "" { + return "" + } + var b bytes.Buffer + b.Grow(len(text) + len(text)/2) + if err := m.md.Convert([]byte(text), &b); err != nil { + return template.HTML("<p>" + template.HTMLEscapeString(text) + "</p>") + } + return template.HTML(b.String()) +} + +var noteHrefRE = regexp.MustCompile(`href="([^"]+)"`) + +// renderAt canonicalizes note links for the page carrying the card. A note is +// shown at several URL depths (/notes, /code/x, /note/N, and static variants), +// so leaving its relative Markdown href untouched would make the mention work +// in only one of those places. +func (m *markdown) renderAt(text string, p *page) template.HTML { + body := m.render(text) + if body == "" || p == nil { + return body + } + out := noteHrefRE.ReplaceAllStringFunc(string(body), func(attr string) string { + destination := stdhtml.UnescapeString(attr[len(`href="`) : len(attr)-1]) + id := noteLinkID(destination) + if id == 0 { + return attr + } + if !p.Live && p.Site != nil && p.Site.NoteByID(id) == nil { + return attr + } + href := p.Href("note", strconv.Itoa(id)) + if href == "" { + return attr + } + return `href="` + template.HTMLEscapeString(href) + `"` + }) + return template.HTML(out) +} + +// noteRenderer overrides the two node kinds the stock renderer emits without +// syntax colors. Everything else it renders is fine as goldmark writes it. +type noteRenderer struct{ hl *highlighter } + +func (nr *noteRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) { + reg.Register(ast.KindFencedCodeBlock, nr.renderFenced) + reg.Register(ast.KindCodeBlock, nr.renderIndented) +} + +func (nr *noteRenderer) renderFenced(w util.BufWriter, src []byte, node ast.Node, entering bool) (ast.WalkStatus, error) { + if !entering { + return ast.WalkSkipChildren, nil + } + n := node.(*ast.FencedCodeBlock) + nr.code(w, blockLines(src, n), string(n.Language(src))) + return ast.WalkSkipChildren, nil +} + +func (nr *noteRenderer) renderIndented(w util.BufWriter, src []byte, node ast.Node, entering bool) (ast.WalkStatus, error) { + if !entering { + return ast.WalkSkipChildren, nil + } + nr.code(w, blockLines(src, node), "") + return ast.WalkSkipChildren, nil +} + +// blockLines joins a block node's source lines. They are contiguous in the +// source, but only the segments are authoritative about where the block's +// indentation was stripped. +func blockLines(src []byte, n ast.Node) []byte { + lines := n.Lines() + var b bytes.Buffer + for i := 0; i < lines.Len(); i++ { + seg := lines.At(i) + b.Write(seg.Value(src)) + } + return bytes.TrimRight(b.Bytes(), "\n") +} + +// code writes one code block, syntax-painted when a grammar claims the fence's +// language and plain when none does. It emits the same <span class="s-…"> +// runs as the code view, so the stylesheet already knows how to color it; the +// <li>-per-line scaffolding does not come along, since a snippet has no line +// numbers, no coverage and no notes of its own. +func (nr *noteRenderer) code(w util.BufWriter, src []byte, lang string) { + w.WriteString(`<pre class="mdcode"`) + if lang != "" { + w.WriteString(` data-lang="`) + w.WriteString(template.HTMLEscapeString(lang)) + w.WriteByte('"') + } + w.WriteString("><code>") + + var b strings.Builder + b.Grow(len(src) + len(src)/4) + classes := nr.hl.classifyLang(lang, src) + names := []string(nil) + if nr.hl != nil { + names = nr.hl.classNames + } + for start := 0; start <= len(src); { + end := start + for end < len(src) && src[end] != '\n' { + end++ + } + emitLine(&b, src[start:end], classes[start:end], names) + if end >= len(src) { + break + } + b.WriteByte('\n') + start = end + 1 + } + w.WriteString(b.String()) + w.WriteString("</code></pre>\n") +} diff --git a/web/markdown_test.go b/web/markdown_test.go new file mode 100644 index 0000000..2078bab --- /dev/null +++ b/web/markdown_test.go @@ -0,0 +1,245 @@ +package web + +import ( + "net/http/httptest" + "net/url" + "strings" + "testing" +) + +func testMarkdown(t *testing.T) *markdown { + t.Helper() + return newMarkdown(newHighlighter(loadTheme("", "", "dark"), loadTheme("", "", "light"))) +} + +func TestMarkdownNotes(t *testing.T) { + m := testMarkdown(t) + cases := []struct { + name string + in string + want []string + not []string + }{ + { + name: "inline marks", + in: "`detect()` prefers **direct env** and only walks the tree as *fallback*", + want: []string{"<code>detect()</code>", "<strong>direct env</strong>", "<em>fallback</em>"}, + }, + { + name: "list after a paragraph", + in: "three classes:\n\n- persisted RPC narrowed\n- ingress bounds change", + want: []string{"<p>three classes:</p>", "<ul>", "<li>persisted RPC narrowed</li>"}, + }, + { + name: "bare url", + in: "see https://example.com/x for the rest", + want: []string{`<a href="https://example.com/x">`}, + }, + { + name: "single newlines are kept", + in: "first line\nsecond line", + want: []string{"first line<br>", "second line"}, + not: []string{"<ul>"}, + }, + // the identifiers real notes are full of must survive untouched: + // underscores are not emphasis, "4.2" is not a list, "@" is not a + // mail address + { + name: "code prose is left alone", + in: "4.2 drops stake_minimum_delegation_for_rewards and remove_simple_vote, unlike @", + want: []string{"stake_minimum_delegation_for_rewards", "remove_simple_vote", "4.2 drops"}, + not: []string{"<em>", "<ol>", "<a href"}, + }, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got := string(m.render(c.in)) + for _, w := range c.want { + if !strings.Contains(got, w) { + t.Errorf("missing %q in:\n%s", w, got) + } + } + for _, n := range c.not { + if strings.Contains(got, n) { + t.Errorf("unwanted %q in:\n%s", n, got) + } + } + }) + } +} + +func TestNoteLinksFindOnlyLocalMarkdownLinks(t *testing.T) { + p := newNoteLinkParser() + got := noteLinks(p, strings.Join([]string{ + "[root](/note/2)", + "[same target](note/2#discussion)", + "[static relative](../note/3.html?scope=all)", + "`[code](note/4)` and plain note/5 are not links", + "[remote](https://example.com/note/6)", + "[protocol relative](//example.com/note/7)", + "[reference][n]", + "[n]: ./note/8", + }, "\n\n")) + if len(got) != 3 || got[0] != 2 || got[1] != 3 || got[2] != 8 { + t.Errorf("note links = %v, want [2 3 8]", got) + } + + m := testMarkdown(t) + text := "[note](../note/3.html) and [remote](https://example.com/note/4)" + if body := string(m.renderAt(text, &page{Live: true, Root: "/"})); !strings.Contains(body, `href="/note/3"`) || !strings.Contains(body, `href="https://example.com/note/4"`) { + t.Errorf("live note links were not canonicalized selectively:\n%s", body) + } + if body := string(m.renderAt(text, &page{Root: "../"})); !strings.Contains(body, `href="../note/3.html"`) { + t.Errorf("static note link does not follow the page root:\n%s", body) + } +} + +// Angle brackets in a note are code, never markup: they must come through as +// text, and must not stop the markdown around them from being parsed. That +// second half is what goldmark's HTML *block* parser would break — a note +// opening with a quoted tag would render the rest of its paragraph as source. +func TestMarkdownShowsAngleBracketsAsText(t *testing.T) { + m := testMarkdown(t) + cases := []struct{ name, in string }{ + {"inline", "sysvar_cache: RwLock<SysvarCache> — hoisted out of the loop"}, + {"block, tag alone on the line", "<div>\nthe **wrapper** in [page.go](https://go.dev)"}, + {"script", "<script>alert(1)</script> is quoted from [the file](https://go.dev)"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got := string(m.render(c.in)) + if strings.Contains(got, "<div>") || strings.Contains(got, "<script>") { + t.Errorf("markup reached the page:\n%s", got) + } + if strings.Contains(got, "raw HTML omitted") { + t.Errorf("text was dropped:\n%s", got) + } + for _, w := range []string{"<", ">"} { + if !strings.Contains(got, w) { + t.Errorf("missing %q in:\n%s", w, got) + } + } + if strings.Contains(c.in, "[") && !strings.Contains(got, `<a href="https://go.dev">`) { + t.Errorf("markdown stopped being parsed:\n%s", got) + } + }) + } +} + +// A note is written by whoever ran notevi, so the renderer is the last thing +// standing between the log and the page. +func TestMarkdownDropsDangerousLinks(t *testing.T) { + m := testMarkdown(t) + for _, in := range []string{ + "[click](javascript:alert(1))", + ")", + "[click](vbscript:alert(1))", + } { + if got := string(m.render(in)); strings.Contains(got, "javascript:") || strings.Contains(got, "vbscript:") { + t.Errorf("%q rendered as %s", in, got) + } + } +} + +// A fenced block is painted by the same grammars as the code view, so a +// snippet in a note wears the reader's theme. +func TestMarkdownHighlightsFences(t *testing.T) { + m := testMarkdown(t) + got := string(m.render("```go\nfunc load() error { return nil }\n```")) + for _, w := range []string{`<pre class="mdcode" data-lang="go">`, `<span class="s-keyword">func</span>`, "</code></pre>"} { + if !strings.Contains(got, w) { + t.Errorf("missing %q in:\n%s", w, got) + } + } + // a language no grammar claims still renders, just unpainted + got = string(m.render("```brainfuck\n+[-]<>\n```")) + if !strings.Contains(got, "+[-]<>") { + t.Errorf("unclaimed fence lost its text:\n%s", got) + } + if strings.Contains(got, "<span") { + t.Errorf("unclaimed fence was painted:\n%s", got) + } +} + +// Fence languages are mostly extensions already, so the grammar table does the +// lookup; fenceAliases only has to cover the spelled-out names. Each pair here +// is a snippet the claimed grammar must find something to paint in. +func TestMarkdownFenceLanguages(t *testing.T) { + hl := newHighlighter(loadTheme("", "", "dark"), loadTheme("", "", "light")) + for _, c := range []struct{ lang, src string }{ + {"go", "func f() {}"}, {"GO", "func f() {}"}, {"golang", "func f() {}"}, + {"rs", "fn f() {}"}, {"rust", "fn f() {}"}, + {"py", "def f(): pass"}, {"python", "def f(): pass"}, {"python3", "def f(): pass"}, + {"js", "function f() {}"}, {"javascript", "function f() {}"}, {"node", "function f() {}"}, + {"jsx", "function f() {}"}, {"mjs", "function f() {}"}, + {"ts", "function f(): void {}"}, {"typescript", "function f(): void {}"}, + {"tsx", "function f(): void {}"}, + {"c", "int f(void) { return 0; }"}, + {"cpp", "int f() { return 0; }"}, {"c++", "int f() { return 0; }"}, {"h", "int f();"}, + {"zig", "fn f() void {}"}, + {"json", `{"a": 1}`}, {"jsonc", `{"a": 1}`}, {"json5", `{"a": 1}`}, + {"sh", "for x in a; do echo $x; done"}, {"bash", "for x in a; do echo $x; done"}, + {"shell", "for x in a; do echo $x; done"}, {"zsh", "for x in a; do echo $x; done"}, + {"console", "for x in a; do echo $x; done"}, + } { + if !painted(hl.classifyLang(c.lang, []byte(c.src))) { + t.Errorf("fence language %q painted nothing in %q", c.lang, c.src) + } + } + for _, lang := range []string{"", "text", "brainfuck", " ", "."} { + src := []byte("func f() {}") + if got := hl.classifyLang(lang, src); len(got) != len(src) || painted(got) { + t.Errorf("classifyLang(%q) claimed a grammar it should not have", lang) + } + } +} + +func painted(classes []int16) bool { + for _, c := range classes { + if c != 0 { + return true + } + } + return false +} + +// The note card is the one place all of this has to arrive: the notes page, +// the aside on a file, and the conversation view all render it. +func TestNotePageRendersMarkdown(t *testing.T) { + sv, _, _ := testServer(t) + h := sv.handler() + + form := url.Values{"file": {"hello.txt"}, "text": { + "`cover()` widens the **mask**\n\n- one\n- two\n\n```go\nfunc f() {}\n```"}, "rev": {"@"}} + r := httptest.NewRequest("POST", "/notes", strings.NewReader(form.Encode())) + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + r.Header.Set("HX-Request", "true") + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + if w.Code != 200 { + t.Fatalf("POST /notes = %d: %s", w.Code, w.Body) + } + for _, want := range []string{ + `<div class="body">`, + "<code>cover()</code>", "<strong>mask</strong>", + "<li>one</li>", + `<pre class="mdcode" data-lang="go">`, `<span class="s-keyword">func</span>`, + } { + if !strings.Contains(w.Body.String(), want) { + t.Errorf("missing %q in the posted note card:\n%s", want, w.Body) + } + } + // and again off the page itself, not just the htmx fragment + if b := get(t, h, "/notes", false).Body.String(); !strings.Contains(b, "<code>cover()</code>") { + t.Error("notes page did not render the note as markdown") + } +} + +func TestMarkdownEmpty(t *testing.T) { + m := testMarkdown(t) + for _, in := range []string{"", " ", "\n\n"} { + if got := m.render(in); got != "" { + t.Errorf("render(%q) = %q, want empty", in, got) + } + } +} diff --git a/web/model.go b/web/model.go new file mode 100644 index 0000000..5e90ee1 --- /dev/null +++ b/web/model.go @@ -0,0 +1,621 @@ +// model.go — the log projected into a browsable model. +// +// Everything the site shows is derived here from the notevi log alone: agents and +// their colors, per-file coverage bitmasks, notes, and live session activity. +// The private jj sidecar is the only state. +package web + +import ( + "encoding/json" + "fmt" + "html/template" + "sort" + "strings" + "time" +) + +// Coverage is a uint8 bitmask, so only the first maxAgents agents get a color; +// later ones fall back to the muted "no bit" rendering. +const maxAgents = 8 + +type Entry struct { + Time string `json:"time,omitempty"` + Op string `json:"op"` + Session string `json:"session,omitempty"` + Agent string `json:"agent,omitempty"` + Model string `json:"model,omitempty"` + Reason string `json:"reasoning,omitempty"` + Dir string `json:"dir,omitempty"` + Rev string `json:"rev,omitempty"` + Change string `json:"change,omitempty"` + Commit string `json:"commit,omitempty"` + File string `json:"file,omitempty"` + Start int `json:"start,omitempty"` + End int `json:"end,omitempty"` + Pattern string `json:"pattern,omitempty"` + Matches int `json:"matches,omitempty"` + NoteID int `json:"note_id,omitempty"` + ReplyTo int `json:"reply_to,omitempty"` + Type string `json:"type,omitempty"` + Text string `json:"text,omitempty"` +} + +type Agent struct { + Name, Short, Session, Model, Reason string + Bit uint8 + Reads, Greps, Notes int +} + +type Note struct { + ID int // position in the log, for anchors + NoteID int // the agent's own per-session number + Agent *Agent + Session, Model, Reason string + File, Kind, Text, Change, Commit, Rev string + Start, End int + ReplyTo int + Replies, Mentions []*Note // notes that point back to this one + At time.Time + When, Ago string +} + +// ThreadNode is the tree-shaped rendering of the note DAG. A note reached by +// more than one path is emitted fully once and then as a compact reference, so +// the focused page keeps valid DOM ids and cannot recurse through malformed +// cyclic logs. +type ThreadNode struct { + Note *Note + Via string // "reply" | "mention"; empty for the focused root + Children []*ThreadNode + Reference bool +} + +type File struct { + Path, Change string + Traced bool + Stub string // set when content is not rendered (binary, huge) + Cov []uint8 // 1-based line -> agent bitmask + NoteAt map[int]int // line -> index into Notes + Reads, Greps int + Patterns []string + Notes []*Note + Total, Covered, Pct int + Mask uint8 + Body template.HTML +} + +type Site struct { + Title string + Repo string + Change string // the change most entries were logged at + Only string // the change this view is scoped to ("" = the whole log) + Agents []*Agent + Files map[string]*File // traced files + Order []string // traced paths, sorted + All []*File // every file in the repo at the site change + Notes []*Note // in scope + Entries []Entry // the whole log, scope or no scope + Theme *Theme // dark + Light *Theme + + // counted over the whole log, so a scoped view can still say what it is + // not showing + NotesTotal int + NotesAt map[string]int // change -> notes recorded there + Votes map[string]int // change -> entries recorded there + Ranked []string // changes, most-logged first +} + +// buildModel projects log entries onto agents, files and notes. It never +// touches the repo, so it is cheap enough to redo on every log change. +// +// only, when set, keeps just what was recorded at that change: a read logged +// against another change points at line numbers that have since moved, so a +// view of one change must not inherit them. Two things stay whole-log +// regardless — agent colors, so they do not shuffle when the scope changes, +// and note ids, so a link to a note survives it. +func buildModel(title string, entries []Entry, only string) *Site { + s := &Site{Title: title, Only: only, Files: map[string]*File{}, Entries: entries, + NotesAt: map[string]int{}, Votes: map[string]int{}} + agents := map[string]*Agent{} + noteN := 0 + for _, e := range entries { + if e.Agent == "" { + e.Agent = "unknown" + } + a := agents[e.Agent] + if a == nil { + a = &Agent{Name: e.Agent, Short: strings.SplitN(e.Agent, "_", 2)[0], + Session: e.Session, Model: e.Model, Reason: e.Reason} + if len(s.Agents) < maxAgents { + a.Bit = 1 << len(s.Agents) + } + agents[e.Agent] = a + s.Agents = append(s.Agents, a) + } + if e.Change != "" { + s.Votes[e.Change]++ + } + if e.Op == "note" { + noteN++ + s.NotesTotal++ + s.NotesAt[e.Change]++ + } + if only != "" && e.Change != only { + continue + } + switch e.Op { + case "read": + a.Reads++ + f := s.file(e.File, e.Change) + f.Reads++ + f.cover(e.Start, e.End, a.Bit) + case "grep": + a.Greps++ + if f, ok := s.Files[e.File]; ok || e.File != "" { + if f == nil { // grep on a file we later read + f = s.file(e.File, e.Change) + } + f.Greps++ + f.Patterns = append(f.Patterns, fmt.Sprintf("%s (%d)", e.Pattern, e.Matches)) + } + case "note": + a.Notes++ + at := parseTime(e.Time) + n := &Note{ID: noteN, NoteID: e.NoteID, Agent: a, Session: e.Session, + Model: e.Model, Reason: e.Reason, File: e.File, Change: e.Change, + Commit: e.Commit, Rev: e.Rev, Start: e.Start, End: e.End, ReplyTo: e.ReplyTo, + Kind: e.Type, Text: e.Text, + At: at, When: stamp(at), Ago: ago(at)} + s.Notes = append(s.Notes, n) + if e.File != "" { + f := s.file(e.File, e.Change) + f.Notes = append(f.Notes, n) + } + } + } + for c := range s.Votes { + s.Ranked = append(s.Ranked, c) + } + // most-logged first; ties by id so the pick is stable across rebuilds + sort.Slice(s.Ranked, func(i, j int) bool { + a, b := s.Ranked[i], s.Ranked[j] + if s.Votes[a] != s.Votes[b] { + return s.Votes[a] > s.Votes[b] + } + return a < b + }) + if len(s.Ranked) > 0 { + s.Change = s.Ranked[0] + } + // drop grep-only "files" that are really path filters (dirs, non-files) + for p, f := range s.Files { + if f.Reads == 0 && len(f.Notes) == 0 { + delete(s.Files, p) + } + } + for p := range s.Files { + s.Order = append(s.Order, p) + } + sort.Strings(s.Order) + linkNotes(s.Notes) + return s +} + +func (s *Site) file(path, change string) *File { + f := s.Files[path] + if f == nil { + f = &File{Path: path, NoteAt: map[int]int{}, Traced: true} + s.Files[path] = f + } + if change != "" { + f.Change = change + } + return f +} + +func (f *File) cover(start, end int, bit uint8) { + if start < 1 { + return + } + if end < start { + end = start + } + for len(f.Cov) <= end { + f.Cov = append(f.Cov, 0) + } + for i := start; i <= end; i++ { + f.Cov[i] |= bit + } + f.Mask |= bit +} + +// clone copies the per-render state so one *File from the model can be +// rendered concurrently at several revisions. Cov is read-only during render. +func (f *File) clone() *File { + c := *f + c.NoteAt = map[int]int{} + c.Notes = append([]*Note(nil), f.Notes...) + return &c +} + +// filesAt joins a revision's path list with the traced files, so untraced +// files still appear in the tree. Traced *File values are shared read-only. +func (s *Site) filesAt(paths []string, change string) []*File { + var all []*File + for _, p := range paths { + if p == "" { + continue + } + f := s.Files[p] + if f == nil { + f = &File{Path: p, Change: change, NoteAt: map[int]int{}} + } else { + f.Traced = true + } + all = append(all, f) + } + sort.Slice(all, func(i, j int) bool { return all[i].Path < all[j].Path }) + return all +} + +// masks lists every bitmask combination the colored agents can produce. +func (s *Site) masks() []uint8 { + n := len(s.Agents) + if n > maxAgents { + n = maxAgents + } + var out []uint8 + for m := 1; m < 1<<n; m++ { + out = append(out, uint8(m)) + } + return out +} + +// ── notes: filtering and facets ─────────────────────────────────────────── + +type NoteFilter struct { + Text string // substring of the note body + File string // substring of the file path + Agent string + Model string + Session string + Kind string + Change string + From string // YYYY-MM-DD, inclusive + To string // YYYY-MM-DD, inclusive +} + +func (f NoteFilter) empty() bool { return f == NoteFilter{} } + +func (f NoteFilter) match(n *Note) bool { + has := func(hay, needle string) bool { + return needle == "" || strings.Contains(strings.ToLower(hay), strings.ToLower(needle)) + } + if !has(n.Text, f.Text) || !has(n.File, f.File) { + return false + } + eq := func(got, want string) bool { return want == "" || got == want } + if !eq(n.Agent.Name, f.Agent) || !eq(n.Model, f.Model) || !eq(n.Session, f.Session) || + !eq(n.Kind, f.Kind) || !eq(n.Change, f.Change) { + return false + } + if f.From != "" && (n.At.IsZero() || n.At.Format(dateFmt) < f.From) { + return false + } + if f.To != "" && (n.At.IsZero() || n.At.Format(dateFmt) > f.To) { + return false + } + return true +} + +const dateFmt = "2006-01-02" + +// FilterNotes returns matching notes, newest first (undated notes last). +func (s *Site) FilterNotes(f NoteFilter) []*Note { + var out []*Note + for _, n := range s.Notes { + if f.match(n) { + out = append(out, n) + } + } + sort.SliceStable(out, func(i, j int) bool { return out[i].At.After(out[j].At) }) + return out +} + +// NoteByID finds a note by the id a permalink names. Ids count over the whole +// log and the log only ever grows, so the link a reader was given goes on +// meaning the same note however the site is later scoped or rebuilt. +func (s *Site) NoteByID(id int) *Note { + for _, n := range s.Notes { + if n.ID == id { + return n + } + } + return nil +} + +// linkNotes derives the graph without adding another log operation. Replies +// are explicit reply_to edges; mentions are ordinary local Markdown links to +// /note/N (or an equivalent relative path). If a reply also links its parent, +// the explicit relationship wins and the child is not counted twice. +func linkNotes(notes []*Note) { + byID := make(map[int]*Note, len(notes)) + for _, n := range notes { + byID[n.ID] = n + } + links := newNoteLinkParser() + for _, child := range notes { + if parent := byID[child.ReplyTo]; parent != nil && parent != child { + parent.Replies = append(parent.Replies, child) + } + for _, id := range noteLinks(links, child.Text) { + parent := byID[id] + if parent == nil || parent == child || id == child.ReplyTo { + continue + } + parent.Mentions = append(parent.Mentions, child) + } + } +} + +// NoteThread expands replies and mentions together, oldest first. The global +// seen set turns a DAG into one readable Hacker News-style thread while still +// leaving a reference at every additional incoming edge. +func (s *Site) NoteThread(id int) *ThreadNode { + root := s.NoteByID(id) + if root == nil { + return nil + } + seen := map[int]bool{id: true} + var build func(*Note) *ThreadNode + build = func(n *Note) *ThreadNode { + node := &ThreadNode{Note: n} + for _, edge := range noteEdges(n) { + child := &ThreadNode{Note: edge.Note, Via: edge.Via} + if seen[edge.Note.ID] { + child.Reference = true + } else { + seen[edge.Note.ID] = true + child = build(edge.Note) + child.Via = edge.Via + } + node.Children = append(node.Children, child) + } + return node + } + return build(root) +} + +type noteEdge struct { + Note *Note + Via string +} + +func noteEdges(n *Note) []noteEdge { + seen := map[int]bool{} + edges := make([]noteEdge, 0, len(n.Replies)+len(n.Mentions)) + for _, child := range n.Replies { + seen[child.ID] = true + edges = append(edges, noteEdge{Note: child, Via: "reply"}) + } + for _, child := range n.Mentions { + if !seen[child.ID] { + edges = append(edges, noteEdge{Note: child, Via: "mention"}) + } + } + sort.SliceStable(edges, func(i, j int) bool { return edges[i].Note.ID < edges[j].Note.ID }) + return edges +} + +// Facets are the distinct values the note filters can select, so the form +// only ever offers choices that exist in the log. +type Facets struct { + Agents, Models, Sessions, Kinds, Changes, Files []string +} + +func (s *Site) Facets() *Facets { + fa := &Facets{} + add := func(dst *[]string, seen map[string]bool, v string) { + if v != "" && !seen[v] { + seen[v] = true + *dst = append(*dst, v) + } + } + ag, mo, se, ki, ch, fi := map[string]bool{}, map[string]bool{}, map[string]bool{}, map[string]bool{}, map[string]bool{}, map[string]bool{} + for _, n := range s.Notes { + add(&fa.Agents, ag, n.Agent.Name) + add(&fa.Models, mo, n.Model) + add(&fa.Sessions, se, n.Session) + add(&fa.Kinds, ki, n.Kind) + add(&fa.Changes, ch, n.Change) + add(&fa.Files, fi, n.File) + } + for _, s := range [][]string{fa.Agents, fa.Models, fa.Sessions, fa.Kinds, fa.Changes, fa.Files} { + sort.Strings(s) + } + return fa +} + +// nextNoteID mirrors notevi's numbering: ids count up from 1 within a session. +func nextNoteID(entries []Entry, session string) int { + max := 0 + for _, e := range entries { + if e.Op == "note" && e.Session == session && e.NoteID > max { + max = e.NoteID + } + } + return max + 1 +} + +// ── live activity ───────────────────────────────────────────────────────── + +// A Session is one agent run seen in the log: who it is, what it last did, +// and whether it is still going. This is what "live" shows. +type Session struct { + ID, Agent, Short, Model, Reason, Dir string + Bit uint8 + Last time.Time + Ago, LastOp, File string + Change string + Reads, Greps, Notes int + Live bool +} + +// Sessions groups the log by session (falling back to agent+dir for logs +// without one), newest activity first. Sessions touched within window are +// reported as live. +func (s *Site) Sessions(now time.Time, window time.Duration, limit int) []*Session { + byKey := map[string]*Session{} + var order []*Session + byName := map[string]*Agent{} + for _, a := range s.Agents { + byName[a.Name] = a + } + for _, e := range s.Entries { + name := e.Agent + if name == "" { + name = "unknown" + } + key := e.Session + if key == "" { + key = name + "\x00" + e.Dir + } + v := byKey[key] + if v == nil { + a := byName[name] + v = &Session{ID: e.Session, Agent: name, Dir: e.Dir} + if a != nil { + v.Short, v.Bit = a.Short, a.Bit + } + byKey[key] = v + order = append(order, v) + } + if e.Model != "" { + v.Model, v.Reason = e.Model, e.Reason + } + if e.Dir != "" { + v.Dir = e.Dir + } + if e.Change != "" { + v.Change = e.Change + } + switch e.Op { + case "read": + v.Reads++ + case "grep": + v.Greps++ + case "note": + v.Notes++ + } + if at := parseTime(e.Time); !at.IsZero() && at.After(v.Last) { + v.Last, v.File, v.LastOp = at, e.File, describe(e) + } + } + for _, v := range order { + v.Ago = agoFrom(now, v.Last) + v.Live = !v.Last.IsZero() && now.Sub(v.Last) < window + } + sort.SliceStable(order, func(i, j int) bool { return order[i].Last.After(order[j].Last) }) + if limit > 0 && len(order) > limit { + order = order[:limit] + } + return order +} + +func describe(e Entry) string { + switch e.Op { + case "read": + if e.Start > 0 { + if e.End > e.Start { + return fmt.Sprintf("read %s:%d-%d", e.File, e.Start, e.End) + } + return fmt.Sprintf("read %s:%d", e.File, e.Start) + } + return "read " + e.File + case "grep": + if e.File != "" { + return fmt.Sprintf("grep %q in %s (%d)", e.Pattern, e.File, e.Matches) + } + return fmt.Sprintf("grep %q (%d)", e.Pattern, e.Matches) + case "note": + if e.File != "" { + return "note on " + e.File + } + return "note" + } + return e.Op +} + +// ── sidecar JSONL ───────────────────────────────────────────────────────── + +func parseLog(b []byte) []Entry { + var entries []Entry + for _, line := range strings.Split(string(b), "\n") { + if line == "" { + continue + } + var e Entry + if json.Unmarshal([]byte(line), &e) == nil { + entries = append(entries, e) + } + } + return entries +} + +func readLog(log logStore) []Entry { + b, err := log.Read() + if err != nil { + fatal("%v", err) + } + return parseLog(b) +} + +func appendEntry(log logStore, e *Entry) error { + return log.Append(func(current []byte) ([]byte, error) { + e.NoteID = nextNoteID(parseLog(current), e.Session) + b, err := json.Marshal(e) + return append(b, '\n'), err + }) +} + +// ── time ────────────────────────────────────────────────────────────────── + +func parseTime(s string) time.Time { + if s == "" { + return time.Time{} + } + t, err := time.Parse(time.RFC3339, s) + if err != nil { + return time.Time{} + } + return t +} + +func stamp(t time.Time) string { + if t.IsZero() { + return "" + } + return t.Local().Format("2006-01-02 15:04") +} + +func ago(t time.Time) string { return agoFrom(time.Now(), t) } + +func agoFrom(now, t time.Time) string { + if t.IsZero() { + return "" + } + d := now.Sub(t) + switch { + case d < 0: + return "just now" + case d < time.Minute: + return fmt.Sprintf("%ds ago", int(d.Seconds())) + case d < time.Hour: + return fmt.Sprintf("%dm ago", int(d.Minutes())) + case d < 24*time.Hour: + return fmt.Sprintf("%dh ago", int(d.Hours())) + default: + return fmt.Sprintf("%dd ago", int(d.Hours())/24) + } +} diff --git a/web/page.go b/web/page.go new file mode 100644 index 0000000..0425589 --- /dev/null +++ b/web/page.go @@ -0,0 +1,348 @@ +// page.go — what a template gets, and how links are formed. +// +// The same templates render two ways: as a static export (relative links, +// ".html" suffixes, no server-side features) and as the live web app +// (absolute routes, htmx-driven filters, comments and jj queries). Pages carry +// Live so a template can ask for the difference in one place. +package web + +import ( + "html/template" + "net/url" + "strconv" + "strings" +) + +type page struct { + Site *Site + Title string + Kind string // index | file | files | notes | note | jj | change | session + Root string // static: relative prefix; live: route prefix ending in "/" + Live bool + Rev string // revision being browsed ("" = the change the log points at) + ChangeID string // resolved change id for Rev — what pages name and link + Commit string // the commit under it — what content is read and cached at + Default string // the change the log points at + Path string // this request's path, so the change bar can re-aim it + Current string // current file path, for the tree + User string // who web comments are attributed to + + // what this view is scoped to. Scope is "change" (only what was recorded + // at ChangeID) or "all"; ScopeEmpty means "change" was asked for but + // nothing was ever recorded there, so the whole log is showing instead. + Scope string + ScopeEmpty bool + Here int // notes recorded at this change + Elsewhere int // notes recorded at any other change + ChangeInfo *Row + + Tree template.HTML + File *File + Files []*File // every file at this change, for counts + + // one note on its own page — the permalink. Excerpt is the code it is + // about, already rendered; ExErr says why there is none. + Note *Note + Thread *ThreadNode + Excerpt template.HTML + ExFrom, ExTo int + ExErr string + + Notes []*Note + Filter NoteFilter + Facets *Facets + Sessions []*Session + Compact bool + Window string + + JJ *JJView + Change *Change + Conv *Conv + Err string +} + +// JJView is one rendered jj query: what was asked, and what came back. +type JJView struct { + Root string + Kind string // log | op + Revset string + AtOp string + Limit int + Rows []Row + Err string +} + +// params carries the two things every link must not lose: which change you +// are looking at, and how wide the view is. +func (p *page) params() string { return p.paramsWith(p.Scope) } + +func (p *page) paramsWith(scope string) string { + var q []string + // "@" is a revset like any other now that the default change is the log's, + // so dropping it here would slide the reader off the change they picked + if p.Rev != "" { + q = append(q, "rev="+url.QueryEscape(p.Rev)) + } + if scope == "all" { + q = append(q, "scope=all") + } + if len(q) == 0 { + return "" + } + return "?" + strings.Join(q, "&") +} + +// ScopeHref is this same page seen with the other scope. +func (p *page) ScopeHref(scope string) string { + path := p.Path + if path == "" { + path = p.liveRoot() + } + return path + p.paramsWith(scope) +} + +// BackHref is this page again at the change the log points at. +func (p *page) BackHref() string { + q := "" + if p.Scope == "all" { + q = "?scope=all" + } + return p.JumpPath() + q +} + +// JumpPath is where the change picker submits: your own page when it is one +// that can be read at any change, the file tree otherwise. +func (p *page) JumpPath() string { + switch p.Kind { + case "index", "file", "files", "notes", "note": + if p.Path != "" { + return p.Path + } + } + return p.liveRoot() + "files" +} + +func (p *page) liveRoot() string { + root := p.Root + if root == "" { + return "/" + } + if !strings.HasPrefix(root, "/") { + root = "/" + root + } + if !strings.HasSuffix(root, "/") { + root += "/" + } + return root +} + +// Href maps a logical destination to a URL for this page's mode. Kinds the +// static export has no page for return "", and templates guard on .Live. +func (p *page) Href(kind string, arg ...string) string { + a := "" + if len(arg) > 0 { + a = arg[0] + } + if p.Live { + root := p.liveRoot() + switch kind { + case "": + return root + p.params() + case "notes": + return root + "notes" + p.params() + case "notes-list": + return root + "notes/list" + p.params() + case "files": + return root + "files" + p.params() + case "tree": + return root + "tree" + p.params() + case "jj": + return root + "jj" + case "jj-log": + return root + "jj/log" + case "jj-op": + return root + "jj/op" + case "activity": + return root + "activity" + case "code": + return root + "code/" + escPath(a) + p.params() + case "note": + return root + "note/" + a + case "change": + return root + "change/" + a + case "session": + return root + "session/" + escPath(a) + case "asset": + return root + a + } + return root + } + switch kind { + case "": + return p.Root + "index.html" + case "notes": + return p.Root + "notes.html" + case "files": + return p.Root + "files.html" + case "tree": + return p.Root + "tree.html" + case "code": + return p.Root + "code/" + a + ".html" + case "note": + return p.Root + "note/" + a + ".html" + case "asset": + return p.Root + a + } + return "" +} + +// codeLink is the tree's per-file linker for this page's mode. +func (p *page) codeLink() func(string) string { + return func(path string) string { return p.Href("code", path) } +} + +func escPath(p string) string { + parts := strings.Split(p, "/") + for i, s := range parts { + parts[i] = url.PathEscape(s) + } + return strings.Join(parts, "/") +} + +// ConvHref opens the conversation a note was written in, anchored on it. It +// needs the transcripts on this machine, so the static export has none — and +// the conversation itself does not link back to where you already are. +func (p *page) ConvHref(n *Note) string { + if !p.Live || p.Kind == "session" || n.Session == "" || safeSession(n.Session) != nil { + return "" + } + id := strconv.Itoa(n.ID) + return p.Href("session", n.Session) + "?note=" + id + "#note-" + id +} + +// PermaHref is the note's own page: the link to hand someone else. It is the +// one link on the card that names nothing but the note, so it survives the +// change scope, the filters, and the file having moved on since. +// +// It is empty on the note's own page, which is where it already points, and in +// a static export of a different change, which has no page for it. +func (p *page) PermaHref(n *Note) string { + if p.Kind == "note" && (p.Note == nil || p.Note.ID == n.ID) { + return "" + } + if !p.Live && p.Site != nil && p.Site.NoteByID(n.ID) == nil { + return "" + } + return p.Href("note", strconv.Itoa(n.ID)) +} + +// ThreadHref opens the incoming replies and mentions for a note. The focused +// root only needs an in-page jump; every other card gets its own permalink. +func (p *page) ThreadHref(n *Note) string { + if len(n.Replies) == 0 && len(n.Mentions) == 0 { + return "" + } + if p.Kind == "note" && p.Note != nil && p.Note.ID == n.ID { + return "#discussion" + } + h := p.Href("note", strconv.Itoa(n.ID)) + if h == "" { + return "" + } + return h + "#discussion" +} + +// ReplyHref is the explicit parent link. A static export may not contain the +// parent's change, in which case it leaves the relationship as text instead of +// manufacturing a link to a page the export did not write. +func (p *page) ReplyHref(n *Note) string { + if n.ReplyTo < 1 { + return "" + } + if !p.Live && p.Site != nil && p.Site.NoteByID(n.ReplyTo) == nil { + return "" + } + return p.Href("note", strconv.Itoa(n.ReplyTo)) +} + +// HasCode reports whether this view has a page for a path. The live app can +// render any file at the change it is reading; a static export only wrote the +// ones present at the change it holds, so a note about a file that is not +// there must not offer a link into nothing. +func (p *page) HasCode(path string) bool { + if p.Live { + return path != "" + } + for _, f := range p.Files { + if f.Path == path { + return true + } + } + return false +} + +// NoteHref points at the noted line, or the note list when it is unpinned. +// The ?note= is what turns a jump into an arrival: the page opens in notes +// focus with the card flashed and its lines marked (see app.js). +func (p *page) NoteHref(n *Note) string { + if n.File == "" { + return p.Href("notes") + } + id := strconv.Itoa(n.ID) + h := p.Href("code", n.File) + sep := "?" + if strings.Contains(h, "?") { + sep = "&" + } + h += sep + "note=" + id + if n.Start > 0 { + h += "#L" + strconv.Itoa(n.Start) + } + return h +} + +// newTemplates parses the page templates. The highlighter comes along because +// note bodies are markdown, and a fenced code block in a note is painted by +// the same grammars as the code view. +func newTemplates(hl *highlighter) *template.Template { + md := newMarkdown(hl) + funcs := template.FuncMap{ + "short": short, + "md": md.renderAt, + "band": func(a, b uint8) bool { return b != 0 && a&b != 0 }, + "lines": func(n *Note) string { + if n.Start <= 0 { + return "whole file" + } + if n.End > n.Start { + return ":" + strconv.Itoa(n.Start) + "-" + strconv.Itoa(n.End) + } + return ":" + strconv.Itoa(n.Start) + }, + "base": func(p string) string { + if i := strings.LastIndex(p, "/"); i >= 0 { + return p[i+1:] + } + return p + }, + "dict": func(kv ...any) map[string]any { + m := map[string]any{} + for i := 0; i+1 < len(kv); i += 2 { + m[kv[i].(string)] = kv[i+1] + } + return m + }, + } + tpl, err := template.New("layout.tmpl").Funcs(funcs).ParseFS(tfs, "templates/*.tmpl") + if err != nil { + fatal("%v", err) + } + return tpl +} + +func short(s string) string { + if len(s) > 8 { + return s[:8] + } + return s +} diff --git a/web/permalink_test.go b/web/permalink_test.go new file mode 100644 index 0000000..44f9142 --- /dev/null +++ b/web/permalink_test.go @@ -0,0 +1,210 @@ +package web + +import ( + "os" + "path/filepath" + "strconv" + "strings" + "testing" +) + +func TestNoteByIDSpansTheWholeLog(t *testing.T) { + entries := parseLog([]byte(logLines(noteA, noteB))) + full := buildModel("test", entries, "") + if n := full.NoteByID(2); n == nil || n.Text != "entry point does too much" { + t.Fatalf("NoteByID(2) = %+v", n) + } + if n := full.NoteByID(99); n != nil { + t.Errorf("NoteByID(99) = %+v, want nil", n) + } + // ids are counted over the whole log, so a link keeps meaning the same + // note when the site is scoped to one change — that is the whole point of + // a permalink + scoped := buildModel("test", entries, "aaa") + for _, id := range []int{1, 2} { + a, b := full.NoteByID(id), scoped.NoteByID(id) + if a == nil || b == nil || a.Text != b.Text { + t.Errorf("note %d differs between scopes: %+v vs %+v", id, a, b) + } + } +} + +func TestPermaHref(t *testing.T) { + n := &Note{ID: 7} + if got := (&page{Live: true, Root: "/"}).PermaHref(n); got != "/note/7" { + t.Errorf("live permalink = %q", got) + } + // a permalink names nothing but the note: no rev, no scope, so it means + // the same thing wherever it is pasted + wide := &page{Live: true, Root: "/", Rev: "xyz", Scope: "all"} + if got := wide.PermaHref(n); got != "/note/7" { + t.Errorf("permalink from a scoped view = %q", got) + } + static := &page{Root: "", Site: &Site{Notes: []*Note{n}}} + if got := static.PermaHref(n); got != "note/7.html" { + t.Errorf("static permalink = %q", got) + } + // on the note's own page there is nowhere to go + if got := (&page{Live: true, Root: "/", Kind: "note"}).PermaHref(n); got != "" { + t.Errorf("self permalink = %q, want none", got) + } + // an export holding another change has no page to point at + empty := &page{Root: "", Site: &Site{}} + if got := empty.PermaHref(n); got != "" { + t.Errorf("permalink into an export without the note = %q, want none", got) + } +} + +func TestExcerptShowsTheNotedLinesInContext(t *testing.T) { + hl := newHighlighter(loadTheme("", "", "dark"), loadTheme("", "", "light")) + var b strings.Builder + for i := 1; i <= 60; i++ { + b.WriteString("line\n") + } + src := []byte(b.String()) + + body, from, to := excerptFor("x.txt", src, nil, hl, &Note{ID: 3, Start: 20, End: 24}) + if from != 20-excerptContext || to != 24+excerptContext { + t.Errorf("range = %d–%d, want %d–%d", from, to, 20-excerptContext, 24+excerptContext) + } + got := string(body) + // real line numbers, not the excerpt's own + if !strings.Contains(got, `id="L16"`) || !strings.Contains(got, `id="L28"`) { + t.Errorf("excerpt is not numbered from the file:\n%s", got) + } + if strings.Contains(got, `id="L15"`) || strings.Contains(got, `id="L29"`) { + t.Errorf("excerpt reaches past its context:\n%s", got) + } + // only the noted lines are marked, and they carry the note's anchor + for _, want := range []string{`<li id="L20"`, `class="noted"`, `data-note="note-3"`} { + if !strings.Contains(got, want) { + t.Errorf("missing %q in:\n%s", want, got) + } + } + if n := strings.Count(got, "noted"); n != 5 { + t.Errorf("marked %d lines, want 5 (20–24)", n) + } + + // context is clamped to the file, never past either end + if _, from, to = excerptFor("x.txt", src, nil, hl, &Note{Start: 2, End: 2}); from != 1 { + t.Errorf("excerpt from = %d, want 1", from) + } + if _, from, to = excerptFor("x.txt", src, nil, hl, &Note{Start: 59, End: 59}); to != 60 { + t.Errorf("excerpt to = %d, want 60", to) + } + // a note pinned to no line has nothing to excerpt + if body, _, _ := excerptFor("x.txt", src, nil, hl, &Note{}); body != "" { + t.Errorf("whole-file note produced an excerpt: %s", body) + } +} + +// content-visibility: auto brings style containment with it, and a contained +// element's own counter-reset comes out as 0 whatever value it names. Every +// chunk after the first would then count from 1, so the number a line shows +// has to be set on the line itself. +func TestChunksAreNumberedFromTheirFirstLine(t *testing.T) { + hl := newHighlighter(loadTheme("", "", "dark"), loadTheme("", "", "light")) + var b strings.Builder + for i := 1; i <= chunkLines*2+10; i++ { + b.WriteString("x\n") + } + f := &File{Path: "big.txt", NoteAt: map[int]int{}} + f.render([]byte(b.String()), hl) + got := string(f.Body) + + if strings.Contains(got, "counter-reset") { + t.Error("a chunk still resets the counter on the <ol>, which containment ignores") + } + for _, ln := range []int{1, chunkLines + 1, chunkLines*2 + 1} { + want := `<li id="L` + strconv.Itoa(ln) + `" style="counter-set: ln ` + strconv.Itoa(ln) + `"` + if !strings.Contains(got, want) { + t.Errorf("chunk starting at line %d does not set its number (want %q)", ln, want) + } + } + if n := strings.Count(got, "counter-set"); n != 3 { + t.Errorf("%d lines set the counter, want 3 — one per chunk", n) + } +} + +// The permalink is the link handed to someone else, so it has to open on its +// own: the note, and the code it is about, at the change it was written at. +func TestNotePermalinkOverHTTP(t *testing.T) { + sv, _, _ := testServer(t) + h := sv.handler() + + // testServer's log holds one note, on hello.txt:2 + w := get(t, h, "/note/1", false) + if w.Code != 200 { + t.Fatalf("GET /note/1 = %d: %s", w.Code, w.Body) + } + body := w.Body.String() + for _, want := range []string{ + "second line matters", // the note + `data-kind="note"`, // and its own page, not a list + `<li id="L2"`, // the line it is about… + "two", // …with the code on it + `<li id="L1"`, // in context + "open the whole file", + } { + if !strings.Contains(body, want) { + t.Errorf("permalink page is missing %q", want) + } + } + // the card does not link to the page it is already on + if strings.Contains(body, `class="perma" href`) { + t.Error("the note links to its own page") + } + + // and the notes list offers the link in the first place + if list := get(t, h, "/notes", false).Body.String(); !strings.Contains(list, `class="perma" href="/note/1"`) { + t.Error("the notes page offers no permalink") + } + + for _, path := range []string{"/note/999", "/note/abc", "/note/0"} { + if code := get(t, h, path, false).Code; code != 404 { + t.Errorf("GET %s = %d, want 404", path, code) + } + } +} + +func TestStaticExportWritesNotePages(t *testing.T) { + sv, logPath, change := testServer(t) + extra := logLines( + `{"time":"2026-07-20T10:02:00Z","op":"note","session":"s2","agent":"claude","change":"`+change+`","note_id":1,"reply_to":1,"text":"static child"}`, + `{"time":"2026-07-20T10:03:00Z","op":"note","session":"s3","agent":"codex","change":"`+change+`","note_id":1,"text":"[static mention](note/1)"}`, + ) + if err := os.WriteFile(logPath, append(mustRead(t, logPath), extra...), 0o644); err != nil { + t.Fatal(err) + } + site, _, _ := sv.snap() + out := t.TempDir() + writeSite(site, out, sv.repo, testThemes(sv.theme, sv.light)) + + b, err := os.ReadFile(filepath.Join(out, "note", "1.html")) + if err != nil { + t.Fatalf("no page for note 1: %v", err) + } + page := string(b) + for _, want := range []string{"second line matters", `<li id="L2"`, "two", + `href="../code/hello.txt.html?note=1#L2"`, "static child", "static mention", + `class="threadnode via-reply"`, `class="threadnode via-mention"`, + `href="../note/1.html"`} { + if !strings.Contains(page, want) { + t.Errorf("exported note page is missing %q", want) + } + } + // the links out have to be relative, since an export is opened off a disk + if strings.Contains(page, `href="/`) { + t.Errorf("exported note page carries an absolute link:\n%s", page) + } + if strings.Contains(page, `class="replybox"`) { + t.Error("the static thread offers a reply form without a server") + } + notes, err := os.ReadFile(filepath.Join(out, "notes.html")) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(notes), `class="perma" href="note/1.html"`) { + t.Error("the exported notes page offers no permalink") + } +} diff --git a/web/projects.go b/web/projects.go new file mode 100644 index 0000000..1783a76 --- /dev/null +++ b/web/projects.go @@ -0,0 +1,715 @@ +// projects.go — the stateless, multi-repository front door for the notevi site. +// +// The hub is an index and dispatcher, not another database. It reconstructs +// its project list from .jj/.git markers and notevi sidecars at startup or on an +// explicit refresh. Per-project pages are still served by server, and the only +// writes are the two actions named by their buttons: initialize jj metadata or +// create the normal private notevi sidecar/config. +package web + +import ( + "bytes" + "context" + "crypto/sha256" + "errors" + "fmt" + "html/template" + "io/fs" + "net/http" + "net/url" + "os" + "os/exec" + "path/filepath" + "sort" + "strconv" + "strings" + "sync" + "syscall" + "time" + + "0x4200.cafe/notevi/sidecar" +) + +type projectKind string + +const ( + projectActive projectKind = "active" + projectJJ projectKind = "jj" + projectGit projectKind = "git" +) + +type Project struct { + ID, Key, Name, Path, Relative string + Kind projectKind + Workspaces []string + Entries, Notes, Agents int + Updated, Err string +} + +type projectRuntime struct { + repo string + server *server + handler http.Handler +} + +type projectHub struct { + scanRoot, title, user string + transcriptRoots []string + theme, light *Theme + themes *themeSet + tpl *template.Template + + mu sync.RWMutex + projects map[string]*Project + order []*Project + runtimes map[string]*projectRuntime + scanned time.Time + scanErr string + + refreshMu sync.Mutex + actionMu sync.Mutex +} + +type projectsPage struct { + Title, ScanRoot, Scanned, Message, Err string + Active, Ready, Git []*Project + Theme, Light *Theme +} + +func newProjectHub(scanRoot, title, user string, transcriptRoots []string, theme, light *Theme, themes *themeSet) (*projectHub, error) { + abs, err := filepath.Abs(scanRoot) + if err != nil { + return nil, err + } + tpl, err := template.New("projects.tmpl").ParseFS(tfs, "templates/projects.tmpl") + if err != nil { + return nil, err + } + h := &projectHub{ + scanRoot: abs, title: title, user: user, transcriptRoots: transcriptRoots, + theme: theme, light: light, themes: themes, tpl: tpl, + projects: map[string]*Project{}, runtimes: map[string]*projectRuntime{}, + } + if err := h.refresh(); err != nil { + return nil, err + } + return h, nil +} + +func (h *projectHub) refresh() error { + h.refreshMu.Lock() + defer h.refreshMu.Unlock() + projects, scanErr, err := discoverProjects(h.scanRoot) + if err != nil { + return err + } + byID := make(map[string]*Project, len(projects)) + for _, p := range projects { + byID[p.ID] = p + } + h.mu.Lock() + h.projects, h.order = byID, projects + h.runtimes = map[string]*projectRuntime{} // derived cache; rebuild lazily + h.scanned, h.scanErr = time.Now(), scanErr + h.mu.Unlock() + return nil +} + +type repoCandidate struct { + path string + git bool +} + +func discoverProjects(root string) ([]*Project, string, error) { + var candidates []repoCandidate + var walkErrs []string + err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil { + if path == root { + return err + } + walkErrs = append(walkErrs, fmt.Sprintf("%s: %v", path, err)) + if d != nil && d.IsDir() { + return filepath.SkipDir + } + return nil + } + if !d.IsDir() { + return nil + } + if path != root && skipScanDir(d.Name()) { + return filepath.SkipDir + } + if markerExists(filepath.Join(path, ".jj")) { + candidates = append(candidates, repoCandidate{path: path}) + return filepath.SkipDir + } + if markerExists(filepath.Join(path, ".git")) { + candidates = append(candidates, repoCandidate{path: path, git: true}) + return filepath.SkipDir + } + return nil + }) + if err != nil { + return nil, "", err + } + + // A jj repository can have several workspaces. The repo-local config path is + // stable across them and gives the dashboard one project, not duplicate logs. + groups := map[string]*Project{} + for _, c := range candidates { + if c.git { + key := filepath.Clean(c.path) + p := &Project{ID: projectID("git", key), Key: key, Path: key, Kind: projectGit} + nameProject(p, root) + groups["git\x00"+key] = p + continue + } + out, err := jjRun(c.path, "config", "path", "--repo") + if err != nil { + walkErrs = append(walkErrs, fmt.Sprintf("%s: %v", c.path, err)) + continue + } + key := filepath.Clean(strings.TrimSpace(string(out))) + gkey := "jj\x00" + key + p := groups[gkey] + if p == nil { + p = &Project{ID: projectID("jj", key), Key: key, Path: c.path, Kind: projectJJ} + groups[gkey] = p + } + p.Workspaces = append(p.Workspaces, c.path) + if preferredWorkspace(c.path, p.Path) { + p.Path = c.path + } + } + + projects := make([]*Project, 0, len(groups)) + for _, p := range groups { + if p.Kind != projectGit { + sort.Strings(p.Workspaces) + active, err := hasSidecar(p.Path) + if err != nil { + p.Err = err.Error() + } else if active { + p.Kind = projectActive + loadProjectStats(p) + } + } + nameProject(p, root) + projects = append(projects, p) + } + sort.Slice(projects, func(i, j int) bool { + if projects[i].Kind != projects[j].Kind { + return projects[i].Kind < projects[j].Kind + } + return strings.ToLower(projects[i].Relative) < strings.ToLower(projects[j].Relative) + }) + return projects, strings.Join(walkErrs, "; "), nil +} + +func skipScanDir(name string) bool { + switch name { + case ".git", ".jj", ".cache", ".cargo", ".local", ".npm", ".rustup", ".var", + "node_modules", "target", "vendor": + return true + } + return false +} + +func markerExists(path string) bool { + _, err := os.Lstat(path) + return err == nil +} + +func preferredWorkspace(candidate, current string) bool { + return current == "" || len(candidate) < len(current) || len(candidate) == len(current) && candidate < current +} + +func projectID(kind, key string) string { + sum := sha256.Sum256([]byte(kind + "\x00" + key)) + return fmt.Sprintf("%x", sum[:8]) +} + +func nameProject(p *Project, root string) { + p.Name = filepath.Base(p.Path) + rel, err := filepath.Rel(root, p.Path) + if err != nil || strings.HasPrefix(rel, "..") { + p.Relative = p.Path + } else if rel == "." { + p.Relative = "~" + } else { + p.Relative = "~/" + filepath.ToSlash(rel) + } +} + +// sidecarChanges looks for every description a notevi sidecar has ever had, so +// that a repository the tool has not written to since the rebrand is still +// listed as having a log rather than offered as a fresh start. +func sidecarChanges(repo string) ([]string, error) { + var ids []string + for _, description := range sidecar.Descriptions() { + revset := fmt.Sprintf("root()+ & subject(exact:%s)", strconv.Quote(description)) + out, err := jjRun(repo, "log", "-G", "-r", revset, "-T", "change_id ++ \"\\n\"") + if err != nil { + return nil, err + } + ids = append(ids, strings.Fields(string(out))...) + } + return ids, nil +} + +func hasSidecar(repo string) (bool, error) { + ids, err := sidecarChanges(repo) + if err != nil { + return false, err + } + switch len(ids) { + case 0: + return false, nil + case 1: + return true, nil + default: + return false, fmt.Errorf("found %d private notevi sidecars", len(ids)) + } +} + +func loadProjectStats(p *Project) { + log, err := sidecar.Open(p.Path) + if err != nil { + p.Err = err.Error() + return + } + b, err := log.Read() + if err != nil && !errors.Is(err, sidecar.ErrNoLog) { + p.Err = err.Error() + return + } + entries := parseLog(b) + p.Entries = len(entries) + agents := map[string]bool{} + var latest time.Time + for _, e := range entries { + if e.Op == "note" { + p.Notes++ + } + if e.Agent != "" { + agents[e.Agent] = true + } + if at := parseTime(e.Time); at.After(latest) { + latest = at + } + } + p.Agents = len(agents) + if latest.IsZero() { + p.Updated = "no entries yet" + } else { + p.Updated = ago(latest) + } +} + +func (h *projectHub) handler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("GET /{$}", h.dashboard) + mux.HandleFunc("POST /projects/refresh", h.refreshAction) + mux.HandleFunc("POST /projects/{id}/start", h.startAction) + mux.HandleFunc("POST /git/{id}/init", h.initGitAction) + mux.HandleFunc("GET /p/{id}", h.projectSlash) + mux.HandleFunc("/p/{id}/{rest...}", h.projectRoute) + mux.HandleFunc("GET /style.css", h.styleCSS) + mux.HandleFunc("GET /themes.css", h.themeAsset) + mux.HandleFunc("GET /themes.js", h.themeAsset) + mux.HandleFunc("GET /app.js", h.asset) + mux.HandleFunc("GET /htmx.min.js", h.asset) + mux.HandleFunc("GET /bemtevi.svg", h.asset) + return mux +} + +func (h *projectHub) dashboard(w http.ResponseWriter, r *http.Request) { + h.mu.RLock() + p := projectsPage{Title: h.title, ScanRoot: h.scanRoot, Scanned: h.scanned.Format("2006-01-02 15:04:05"), + Message: r.URL.Query().Get("message"), Err: r.URL.Query().Get("error"), Theme: h.theme, Light: h.light} + if p.Err == "" { + p.Err = h.scanErr + } + for _, project := range h.order { + switch project.Kind { + case projectActive: + p.Active = append(p.Active, project) + case projectJJ: + p.Ready = append(p.Ready, project) + case projectGit: + p.Git = append(p.Git, project) + } + } + h.mu.RUnlock() + var b bytes.Buffer + if err := h.tpl.ExecuteTemplate(&b, "projects", p); err != nil { + http.Error(w, "render: "+err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + b.WriteTo(w) +} + +func (h *projectHub) refreshAction(w http.ResponseWriter, r *http.Request) { + if !localPost(w, r) { + return + } + if err := h.refresh(); err != nil { + homeRedirect(w, r, "", err) + return + } + homeRedirect(w, r, "projects refreshed", nil) +} + +func (h *projectHub) startAction(w http.ResponseWriter, r *http.Request) { + if !localPost(w, r) { + return + } + p := h.project(r.PathValue("id")) + if p == nil || p.Kind != projectJJ { + http.NotFound(w, r) + return + } + h.actionMu.Lock() + err := ensureSidecar(p.Path) + h.actionMu.Unlock() + if err != nil { + homeRedirect(w, r, "", err) + return + } + if err := h.refresh(); err != nil { + homeRedirect(w, r, "", err) + return + } + if active := h.projectByKey(p.Key, projectActive); active != nil { + http.Redirect(w, r, "/p/"+active.ID+"/", http.StatusSeeOther) + return + } + homeRedirect(w, r, "sidecar created", nil) +} + +func (h *projectHub) initGitAction(w http.ResponseWriter, r *http.Request) { + if !localPost(w, r) { + return + } + p := h.project(r.PathValue("id")) + if p == nil || p.Kind != projectGit { + http.NotFound(w, r) + return + } + h.actionMu.Lock() + err := initColocated(p.Path) + h.actionMu.Unlock() + if err != nil { + homeRedirect(w, r, "", err) + return + } + if err := h.refresh(); err != nil { + homeRedirect(w, r, "", err) + return + } + homeRedirect(w, r, "jj initialized; the repository is ready for a notevi sidecar", nil) +} + +func localPost(w http.ResponseWriter, r *http.Request) bool { + if o := r.Header.Get("Origin"); o != "" { + if u, err := url.Parse(o); err != nil || u.Host != r.Host { + http.Error(w, "cross-origin post refused", http.StatusForbidden) + return false + } + } + return true +} + +func homeRedirect(w http.ResponseWriter, r *http.Request, message string, err error) { + q := url.Values{} + if message != "" { + q.Set("message", message) + } + if err != nil { + q.Set("error", err.Error()) + } + to := "/" + if encoded := q.Encode(); encoded != "" { + to += "?" + encoded + } + http.Redirect(w, r, to, http.StatusSeeOther) +} + +func (h *projectHub) project(id string) *Project { + h.mu.RLock() + defer h.mu.RUnlock() + return h.projects[id] +} + +func (h *projectHub) projectByKey(key string, kind projectKind) *Project { + h.mu.RLock() + defer h.mu.RUnlock() + for _, p := range h.order { + if p.Key == key && p.Kind == kind { + return p + } + } + return nil +} + +func (h *projectHub) projectSlash(w http.ResponseWriter, r *http.Request) { + id := r.PathValue("id") + if p := h.project(id); p == nil || p.Kind != projectActive { + http.NotFound(w, r) + return + } + http.Redirect(w, r, "/p/"+id+"/", http.StatusPermanentRedirect) +} + +func (h *projectHub) projectRoute(w http.ResponseWriter, r *http.Request) { + id := r.PathValue("id") + runtime, err := h.runtime(id) + if err != nil { + http.Error(w, err.Error(), http.StatusNotFound) + return + } + rest := r.PathValue("rest") + clone := r.Clone(r.Context()) + u := *r.URL + u.Path, u.RawPath = "/"+rest, "" + clone.URL = &u + clone.RequestURI = u.RequestURI() + runtime.handler.ServeHTTP(w, clone) +} + +func (h *projectHub) runtime(id string) (*projectRuntime, error) { + h.mu.RLock() + if rt := h.runtimes[id]; rt != nil { + h.mu.RUnlock() + return rt, nil + } + p := h.projects[id] + h.mu.RUnlock() + if p == nil || p.Kind != projectActive { + return nil, fmt.Errorf("project not found") + } + log, err := sidecar.Open(p.Path) + if err != nil { + return nil, err + } + title := p.Name + if h.title != "" && h.title != hubDefaultTitle { + title += " — " + h.title + } + sv := newServerAt(log, p.Path, title, h.user, "/p/"+id+"/", h.theme, h.light, h.themes) + sv.tx = newTranscripts(h.transcriptRoots) + rt := &projectRuntime{repo: p.Path, server: sv, handler: sv.handler()} + h.mu.Lock() + if existing := h.runtimes[id]; existing != nil { + rt = existing + } else { + h.runtimes[id] = rt + } + h.mu.Unlock() + return rt, nil +} + +func ensureSidecar(repo string) error { + // Rename a pre-rebrand sidecar first — before taking the lock below, which + // Migrate takes too — so everything after this only sees the current names. + store, err := sidecar.Open(repo) + if err != nil { + return err + } + if _, err := store.Migrate(); err != nil { + return err + } + config, err := jjRun(repo, "config", "path", "--repo") + if err != nil { + return err + } + lockPath := filepath.Join(filepath.Dir(strings.TrimSpace(string(config))), "notevi.lock") + if err := os.MkdirAll(filepath.Dir(lockPath), 0o755); err != nil { + return err + } + f, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + return err + } + defer f.Close() + if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil { + return err + } + defer syscall.Flock(int(f.Fd()), syscall.LOCK_UN) //nolint:errcheck + + configuredValue, configErr := jjRun(repo, "config", "get", "revset-aliases."+sidecar.Alias) + configured := configErr == nil + var id string + if configured { + resolved, err := jjLogValue(repo, "exactly("+sidecar.Alias+", 1)", "change_id") + if err != nil { + return fmt.Errorf("repo-local revset alias %s is invalid: %w", sidecar.Alias, err) + } + valid := fmt.Sprintf("exactly(%s & root()+ & subject(exact:%s), 1)", sidecar.Alias, strconv.Quote(sidecar.Description)) + if _, err := jjLogValue(repo, valid, "change_id"); err != nil { + return fmt.Errorf("repo-local revset alias %s=%q does not name notevi's sidecar: %w", + sidecar.Alias, strings.TrimSpace(string(configuredValue)), err) + } + id = resolved + } else { + ids, err := sidecarChanges(repo) + if err != nil { + return err + } + switch len(ids) { + case 0: + case 1: + id = ids[0] + default: + return fmt.Errorf("found %d root children described %q; cannot choose a notevi sidecar", len(ids), sidecar.Description) + } + } + if id == "" { + if err := jjMutate(repo, "new", "--no-edit", "root()", "-m", sidecar.Description); err != nil { + return err + } + ids, err := sidecarChanges(repo) + if err != nil { + return err + } + if len(ids) != 1 { + return fmt.Errorf("created %q sidecar but found %d matching root children", sidecar.Description, len(ids)) + } + id = ids[0] + } + if !configured { + if err := jjMutate(repo, "config", "set", "--repo", "revset-aliases."+sidecar.Alias, strconv.Quote(id)); err != nil { + return err + } + } + private, err := jjRun(repo, "config", "get", "git.private-commits") + if err != nil { + return err + } + expr := strings.TrimSpace(string(private)) + if !mentionsRevset(expr, sidecar.Alias) { + expr = "(" + expr + ") | " + sidecar.Alias + if err := jjMutate(repo, "config", "set", "--repo", "git.private-commits", strconv.Quote(expr)); err != nil { + return err + } + } + return nil +} + +func jjLogValue(repo, revset, template string) (string, error) { + out, err := jjRun(repo, "log", "-G", "-r", revset, "-T", template) + if err != nil { + return "", err + } + value := strings.TrimSpace(string(out)) + if value == "" { + return "", fmt.Errorf("revision %q produced no %s", revset, template) + } + return value, nil +} + +func mentionsRevset(expr, name string) bool { + for i := 0; i+len(name) <= len(expr); i++ { + if expr[i:i+len(name)] != name { + continue + } + before := i == 0 || !revsetNameByte(expr[i-1]) + after := i+len(name) == len(expr) || !revsetNameByte(expr[i+len(name)]) + if before && after { + return true + } + } + return false +} + +func revsetNameByte(b byte) bool { + return b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z' || b >= '0' && b <= '9' || b == '_' || b == '-' +} + +func jjMutate(repo string, args ...string) error { + ctx, cancel := context.WithTimeout(context.Background(), jjTimeout) + defer cancel() + cmd := exec.CommandContext(ctx, "jj", append([]string{"--ignore-working-copy", "--no-pager"}, args...)...) + cmd.Dir = repo + out, err := cmd.CombinedOutput() + if err != nil { + return fmt.Errorf("jj %s: %s", strings.Join(args, " "), strings.TrimSpace(string(out))) + } + return nil +} + +func initColocated(repo string) error { + if !markerExists(filepath.Join(repo, ".git")) { + return fmt.Errorf("%s is no longer a git repository", repo) + } + if markerExists(filepath.Join(repo, ".jj")) { + return fmt.Errorf("%s already has jj metadata", repo) + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + cmd := exec.CommandContext(ctx, "jj", "git", "init", "--colocate") + cmd.Dir = repo + out, err := cmd.CombinedOutput() + if err != nil { + return fmt.Errorf("jj git init --colocate: %s", strings.TrimSpace(string(out))) + } + return nil +} + +func (h *projectHub) styleCSS(w http.ResponseWriter, _ *http.Request) { + site := buildModel(h.title, nil, "") + site.Theme, site.Light = h.theme, h.light + var b bytes.Buffer + if err := renderCSS(&b, site); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "text/css; charset=utf-8") + b.WriteTo(w) +} + +func (h *projectHub) themeAsset(w http.ResponseWriter, r *http.Request) { + body, ctype := h.themes.JS, "text/javascript; charset=utf-8" + if strings.HasSuffix(r.URL.Path, ".css") { + body, ctype = h.themes.CSS, "text/css; charset=utf-8" + } + w.Header().Set("Content-Type", ctype) + w.Header().Set("Cache-Control", "max-age=300") + w.Write(body) +} + +func (h *projectHub) asset(w http.ResponseWriter, r *http.Request) { + name := strings.TrimPrefix(r.URL.Path, "/") + b, err := tfs.ReadFile("assets/" + name) + if err != nil { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", assetType(name)) + w.Header().Set("Cache-Control", "max-age=300") + w.Write(b) +} + +func serveProjects(addr string, hub *projectHub) { + hub.mu.RLock() + active, ready, git := 0, 0, 0 + for _, p := range hub.order { + switch p.Kind { + case projectActive: + active++ + case projectJJ: + ready++ + case projectGit: + git++ + } + } + hub.mu.RUnlock() + fmt.Printf("notevi web: http://%s — %d projects, %d jj repos ready to start, %d git repos under %s\n", + addr, active, ready, git, hub.scanRoot) + fmt.Println("notevi web: project discovery is in memory; refresh rescans the filesystem") + if err := http.ListenAndServe(addr, hub.handler()); err != nil { + fatal("%v", err) + } +} diff --git a/web/projects_test.go b/web/projects_test.go new file mode 100644 index 0000000..9f911c3 --- /dev/null +++ b/web/projects_test.go @@ -0,0 +1,315 @@ +package web + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "0x4200.cafe/notevi/sidecar" +) + +func projectTestEnv(t *testing.T, home string) { + t.Helper() + t.Setenv("HOME", home) + t.Setenv("JJ_USER", "test") + t.Setenv("JJ_EMAIL", "[email protected]") +} + +func runAt(t *testing.T, dir, name string, args ...string) string { + t.Helper() + cmd := exec.Command(name, args...) + cmd.Dir = dir + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("%s %s in %s: %v\n%s", name, strings.Join(args, " "), dir, err, out) + } + return string(out) +} + +func initJJAt(t *testing.T, dir string) (change, commit string) { + t.Helper() + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + runAt(t, dir, "jj", "git", "init") + if err := os.WriteFile(filepath.Join(dir, "hello.txt"), []byte("one\ntwo\n"), 0o644); err != nil { + t.Fatal(err) + } + runAt(t, dir, "jj", "describe", "-m", "test project") + change, commit, err := resolveRevision(dir, "@") + if err != nil { + t.Fatal(err) + } + return change, commit +} + +func addTestSidecar(t *testing.T, repo, change, commit string) { + t.Helper() + log, err := sidecar.Open(repo) + if err != nil { + t.Fatal(err) + } + line, err := json.Marshal(Entry{ + Time: "2026-08-02T12:00:00Z", Op: "note", Session: "s1", Agent: "codex", + Dir: repo, Rev: "@", Change: change, Commit: commit, File: "hello.txt", + Start: 1, End: 1, NoteID: 1, Text: "project note", + }) + if err != nil { + t.Fatal(err) + } + if err := log.Append(func([]byte) ([]byte, error) { return []byte(line), nil }); err != nil { + t.Fatal(err) + } +} + +func initGitAt(t *testing.T, dir string) { + t.Helper() + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + runAt(t, dir, "git", "init", "-q") + if err := os.WriteFile(filepath.Join(dir, "README.md"), []byte("git only\n"), 0o644); err != nil { + t.Fatal(err) + } +} + +func testProjectHub(t *testing.T, home string) *projectHub { + t.Helper() + dark, light := loadTheme("", "", "dark"), loadTheme("", "", "light") + h, err := newProjectHub(home, hubDefaultTitle, "tester", nil, dark, light, testThemes(dark, light)) + if err != nil { + t.Fatal(err) + } + return h +} + +func projectOfKind(t *testing.T, h *projectHub, kind projectKind, name string) *Project { + t.Helper() + h.mu.RLock() + defer h.mu.RUnlock() + for _, p := range h.order { + if p.Kind == kind && p.Name == name { + return p + } + } + t.Fatalf("no %s project named %s", kind, name) + return nil +} + +func TestDiscoverProjectsClassifiesAndDeduplicates(t *testing.T) { + if _, err := exec.LookPath("jj"); err != nil { + t.Skip("jj not installed") + } + home := t.TempDir() + projectTestEnv(t, home) + active := filepath.Join(home, "src", "active") + change, commit := initJJAt(t, active) + addTestSidecar(t, active, change, commit) + workspace := filepath.Join(home, "src", "active-workspace") + runAt(t, active, "jj", "workspace", "add", workspace) + initJJAt(t, filepath.Join(home, "src", "ready")) + initGitAt(t, filepath.Join(home, "src", "git-only")) + + projects, scanErr, err := discoverProjects(home) + if err != nil || scanErr != "" { + t.Fatalf("discover = %v, %q", err, scanErr) + } + if len(projects) != 3 { + t.Fatalf("projects = %d, want 3: %+v", len(projects), projects) + } + counts := map[projectKind]int{} + for _, p := range projects { + counts[p.Kind]++ + if p.Kind == projectActive { + if p.Entries != 1 || p.Notes != 1 || p.Agents != 1 || len(p.Workspaces) != 2 { + t.Fatalf("active project = %+v", p) + } + } + } + if counts[projectActive] != 1 || counts[projectJJ] != 1 || counts[projectGit] != 1 { + t.Fatalf("classification = %+v", counts) + } +} + +func TestProjectHubRoutesAnExistingLogUnderPrefix(t *testing.T) { + home := t.TempDir() + projectTestEnv(t, home) + repo := filepath.Join(home, "code", "alpha") + change, commit := initJJAt(t, repo) + addTestSidecar(t, repo, change, commit) + hub := testProjectHub(t, home) + p := projectOfKind(t, hub, projectActive, "alpha") + h := hub.handler() + + for _, tc := range []struct{ path, want string }{ + {"/", "alpha"}, + {"/", `id="themepick"`}, + {"/", `data-js="/themes.js"`}, + {"/", `l.href = "/themes.css"`}, + {"/p/" + p.ID + "/", "project note"}, + {"/p/" + p.ID + "/code/hello.txt", "two"}, + {"/p/" + p.ID + "/style.css", ".project-grid"}, + {"/p/" + p.ID + "/jj", "/p/" + p.ID + "/jj/log"}, + } { + w := get(t, h, tc.path, false) + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), tc.want) { + t.Errorf("GET %s = %d, want body containing %q\n%s", tc.path, w.Code, tc.want, w.Body.String()) + } + } + body := get(t, h, "/p/"+p.ID+"/", false).Body.String() + for _, want := range []string{"/p/" + p.ID + "/style.css", "/p/" + p.ID + "/activity", ">projects</a>"} { + if !strings.Contains(body, want) { + t.Errorf("prefixed page lacks %q", want) + } + } + + form := url.Values{"text": {"written through the project route"}, "change": {change}} + r := httptest.NewRequest("POST", "/p/"+p.ID+"/notes", strings.NewReader(form.Encode())) + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + if w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/p/"+p.ID+"/notes" { + t.Fatalf("prefixed POST = %d, location %q: %s", w.Code, w.Header().Get("Location"), w.Body.String()) + } + log, err := sidecar.Open(repo) + if err != nil { + t.Fatal(err) + } + b, err := log.Read() + if err != nil { + t.Fatal(err) + } + entries := parseLog(b) + if last := entries[len(entries)-1]; last.Text != "written through the project route" || last.Change != change { + t.Fatalf("prefixed POST recorded %+v", last) + } +} + +func TestProjectHubStartsAnEmptyPrivateSidecar(t *testing.T) { + home := t.TempDir() + projectTestEnv(t, home) + repo := filepath.Join(home, "code", "ready") + initJJAt(t, repo) + hub := testProjectHub(t, home) + p := projectOfKind(t, hub, projectJJ, "ready") + beforeStatus, _ := jjRun(repo, "status") + _, beforeCommit, err := resolveRevision(repo, "@") + if err != nil { + t.Fatal(err) + } + + r := httptest.NewRequest("POST", "/projects/"+p.ID+"/start", nil) + w := httptest.NewRecorder() + hub.handler().ServeHTTP(w, r) + if w.Code != http.StatusSeeOther || !strings.HasPrefix(w.Header().Get("Location"), "/p/") { + t.Fatalf("start = %d, location %q: %s", w.Code, w.Header().Get("Location"), w.Body.String()) + } + opened := get(t, hub.handler(), w.Header().Get("Location"), false) + if opened.Code != http.StatusOK || !strings.Contains(opened.Body.String(), "ready") { + t.Fatalf("new empty project page = %d: %s", opened.Code, opened.Body.String()) + } + active, err := hasSidecar(repo) + if err != nil || !active { + t.Fatalf("sidecar = %v, %v", active, err) + } + afterStatus, _ := jjRun(repo, "status") + _, afterCommit, err := resolveRevision(repo, "@") + if err != nil { + t.Fatal(err) + } + if string(afterStatus) != string(beforeStatus) || afterCommit != beforeCommit { + t.Fatal("starting the sidecar changed the project working copy") + } + log, err := sidecar.Open(repo) + if err != nil { + t.Fatal(err) + } + if b, err := log.Read(); err != nil || len(b) != 0 { + t.Fatalf("new sidecar log = %q, %v", b, err) + } + if _, err := os.Stat(filepath.Join(repo, sidecar.LogFile)); !os.IsNotExist(err) { + t.Fatalf("sidecar materialized in the project: %v", err) + } + private, err := jjRun(repo, "config", "get", "git.private-commits") + if err != nil || !mentionsRevset(string(private), sidecar.Alias) { + t.Fatalf("private commits = %q, %v", private, err) + } +} + +func TestEnsureVRSidecarRefusesAConflictingAlias(t *testing.T) { + home := t.TempDir() + projectTestEnv(t, home) + repo := filepath.Join(home, "code", "conflict") + initJJAt(t, repo) + runAt(t, repo, "jj", "config", "set", "--repo", "revset-aliases."+sidecar.Alias, `"root()"`) + + err := ensureSidecar(repo) + if err == nil || !strings.Contains(err.Error(), "does not name notevi's sidecar") { + t.Fatalf("ensure with conflicting alias = %v", err) + } + if active, err := hasSidecar(repo); err != nil || active { + t.Fatalf("conflicting alias created a sidecar: %v, %v", active, err) + } + alias := strings.TrimSpace(runAt(t, repo, "jj", "config", "get", "revset-aliases."+sidecar.Alias)) + if alias != "root()" { + t.Fatalf("conflicting alias was overwritten: %q", alias) + } +} + +func TestProjectHubInitializesGitThenRefreshes(t *testing.T) { + home := t.TempDir() + projectTestEnv(t, home) + repo := filepath.Join(home, "code", "git-only") + initGitAt(t, repo) + hub := testProjectHub(t, home) + p := projectOfKind(t, hub, projectGit, "git-only") + + r := httptest.NewRequest("POST", "/git/"+p.ID+"/init", nil) + w := httptest.NewRecorder() + hub.handler().ServeHTTP(w, r) + if w.Code != http.StatusSeeOther { + t.Fatalf("init = %d: %s", w.Code, w.Body.String()) + } + if !markerExists(filepath.Join(repo, ".jj")) { + t.Fatal("colocated jj metadata was not created") + } + projectOfKind(t, hub, projectJJ, "git-only") + if got := string(mustRead(t, filepath.Join(repo, "README.md"))); got != "git only\n" { + t.Fatalf("working file changed: %q", got) + } + + late := filepath.Join(home, "code", "appeared-later") + initJJAt(t, late) + r = httptest.NewRequest("POST", "/projects/refresh", nil) + w = httptest.NewRecorder() + hub.handler().ServeHTTP(w, r) + if w.Code != http.StatusSeeOther { + t.Fatalf("refresh = %d", w.Code) + } + projectOfKind(t, hub, projectJJ, "appeared-later") +} + +func TestProjectHubRefusesCrossOriginMutation(t *testing.T) { + home := t.TempDir() + projectTestEnv(t, home) + repo := filepath.Join(home, "code", "ready") + initJJAt(t, repo) + hub := testProjectHub(t, home) + p := projectOfKind(t, hub, projectJJ, "ready") + r := httptest.NewRequest("POST", "/projects/"+p.ID+"/start", nil) + r.Header.Set("Origin", "https://elsewhere.example") + w := httptest.NewRecorder() + hub.handler().ServeHTTP(w, r) + if w.Code != http.StatusForbidden { + t.Fatalf("cross-origin start = %d", w.Code) + } + if active, err := hasSidecar(repo); err != nil || active { + t.Fatalf("cross-origin request created sidecar: %v, %v", active, err) + } +} diff --git a/web/render.go b/web/render.go new file mode 100644 index 0000000..0bfbdce --- /dev/null +++ b/web/render.go @@ -0,0 +1,462 @@ +// render.go — source to HTML: tree-sitter highlighting, coverage classes and +// note anchors baked into one <ol> per chunk. +package web + +import ( + "bytes" + "html/template" + "path/filepath" + "sort" + "strconv" + "strings" + "unsafe" + + tszig "github.com/tree-sitter-grammars/tree-sitter-zig/bindings/go" + sitter "github.com/tree-sitter/go-tree-sitter" + tsbash "github.com/tree-sitter/tree-sitter-bash/bindings/go" + tsc "github.com/tree-sitter/tree-sitter-c/bindings/go" + tscpp "github.com/tree-sitter/tree-sitter-cpp/bindings/go" + tsgo "github.com/tree-sitter/tree-sitter-go/bindings/go" + tsjs "github.com/tree-sitter/tree-sitter-javascript/bindings/go" + tsjson "github.com/tree-sitter/tree-sitter-json/bindings/go" + tspython "github.com/tree-sitter/tree-sitter-python/bindings/go" + tsrust "github.com/tree-sitter/tree-sitter-rust/bindings/go" + tsts "github.com/tree-sitter/tree-sitter-typescript/bindings/go" +) + +// Lines per content-visibility chunk: the browser skips layout and paint of +// offscreen chunks wholesale, instead of managing one containment context +// per line. +const chunkLines = 800 + +// approximate rendered line height, for contain-intrinsic-size placeholders +const lineHeightPx = 19 + +// render builds the code HTML: <ol> chunks of chunkLines lines, each line an +// <li> with syntax spans, coverage classes and note anchors. One pre-sized +// builder, no fmt, minimal escaping — large files are browser-bound, so the +// output is kept as small and flat as possible. +func (f *File) render(src []byte, hl *highlighter) { + classes := hl.classify(f.Path, src) + f.Total = bytes.Count(src, []byte{'\n'}) + if len(src) > 0 && src[len(src)-1] != '\n' { + f.Total++ + } + f.Covered = 0 + for i := 1; i < len(f.Cov) && i <= f.Total; i++ { + if f.Cov[i] != 0 { + f.Covered++ + } + } + if f.Total > 0 { + f.Pct = f.Covered * 100 / f.Total + } + sort.Slice(f.Notes, func(i, j int) bool { return f.Notes[i].Start < f.Notes[j].Start }) + for ni, n := range f.Notes { + for l := n.Start; l <= n.End && l > 0; l++ { + if _, taken := f.NoteAt[l]; !taken { + f.NoteAt[l] = ni + } + } + } + f.Body = f.emit(src, classes, hl.classNames, 1, f.Total) +} + +// emit writes lines [from..to] as <ol> chunks. from is where the chunking (and +// so the browser's content-visibility windows) starts counting, which is what +// lets an excerpt come out as one chunk rather than a slice of the file's. +func (f *File) emit(src []byte, classes []int16, names []string, from, to int) template.HTML { + if from < 1 { + from = 1 + } + if to > f.Total { + to = f.Total + } + if from > to { + return "" + } + start := 0 + for ln := 1; ln < from; ln++ { // skip to the first line asked for + start = pastEOL(src, start) + } + stop := start + for ln := from; ln <= to; ln++ { + stop = pastEOL(src, stop) + } + var b strings.Builder + span := stop - start + b.Grow(span + span/2 + (to-from+1)*48) + var num []byte + writeInt := func(n int) { num = strconv.AppendInt(num[:0], int64(n), 10); b.Write(num) } + for ln := from; ln <= to; ln++ { + end := start + for end < len(src) && src[end] != '\n' { + end++ + } + opens := (ln-from)%chunkLines == 0 + if opens { + if ln > from { + b.WriteString("</ol>") + } + rem := to - (ln - 1) + if rem > chunkLines { + rem = chunkLines + } + b.WriteString(`<ol class="code" style="--h: `) + writeInt(rem * lineHeightPx) + b.WriteString(`px">`) + } + b.WriteString(`<li id="L`) + writeInt(ln) + b.WriteByte('"') + // Where the chunk's numbering starts. It has to be counter-set on the + // first line rather than counter-reset on the <ol>, because + // content-visibility: auto brings style containment with it and a + // contained element's own counter-reset comes out as 0 no matter what + // value it names — so every chunk but the first would count from 1. + if opens { + b.WriteString(` style="counter-set: ln `) + writeInt(ln) + b.WriteByte('"') + } + mask := uint8(0) + if ln < len(f.Cov) { + mask = f.Cov[ln] + } + ni, noted := f.NoteAt[ln] + if mask != 0 || noted { + b.WriteString(` class="`) + if mask != 0 { + b.WriteString("cov am") + writeInt(int(mask)) + if noted { + b.WriteString(" noted") + } + } else { + b.WriteString("noted") + } + b.WriteByte('"') + } + if noted { + b.WriteString(` data-note="note-`) + writeInt(f.Notes[ni].ID) + b.WriteByte('"') + } + b.WriteByte('>') + emitLine(&b, src[start:end], classes[start:end], names) + b.WriteString("</li>") + start = end + 1 + } + b.WriteString("</ol>") + return template.HTML(b.String()) +} + +// pastEOL is the offset just past the line starting at i. +func pastEOL(src []byte, i int) int { + for i < len(src) && src[i] != '\n' { + i++ + } + if i < len(src) { + i++ + } + return i +} + +// excerptContext is how many lines either side of a note's range its own page +// shows, so the noted lines are read in context rather than in isolation. +const excerptContext = 4 + +// excerptFor renders just the lines a note is about, the way the code view +// would: the file's real line numbers, its coverage tint, and the noted lines +// marked. This is what lets a shared permalink stand on its own — whoever +// opens it sees the note and the code it is about together, without having to +// find their way into the file first. +// +// cov comes from the model and is read-only here, so the caller can pass the +// live *File's slice rather than copying it. +func excerptFor(path string, src []byte, cov []uint8, hl *highlighter, n *Note) (body template.HTML, from, to int) { + total := bytes.Count(src, []byte{'\n'}) + if len(src) > 0 && src[len(src)-1] != '\n' { + total++ + } + end := n.End + if end < n.Start { + end = n.Start + } + if n.Start < 1 || total == 0 { + return "", 0, 0 + } + f := &File{Path: path, Cov: cov, Total: total, Notes: []*Note{n}, NoteAt: map[int]int{}} + for l := n.Start; l <= end; l++ { + f.NoteAt[l] = 0 + } + from, to = n.Start-excerptContext, end+excerptContext + if from < 1 { + from = 1 + } + if to > total { + to = total + } + if from > total { + return "", 0, 0 + } + return f.emit(src, hl.classify(path, src), hl.classNames, from, to), from, to +} + +// emitLine writes one line's spans, merging runs of the same class across +// whitespace-only gaps ("pub fn" is one span, not two) to keep the DOM flat. +func emitLine(b *strings.Builder, line []byte, cls []int16, names []string) { + open := int16(0) + i := 0 + for i < len(line) { + j := i + c := cls[i] + for j < len(line) && cls[j] == c { + j++ + } + if c == 0 { + allSpace := true + for k := i; k < j; k++ { + if line[k] != ' ' && line[k] != '\t' { + allSpace = false + break + } + } + if !(allSpace && open != 0 && j < len(line) && cls[j] == open) { + if open != 0 { + b.WriteString("</span>") + open = 0 + } + } + escapeTo(b, line[i:j]) + } else { + if open != c { + if open != 0 { + b.WriteString("</span>") + } + b.WriteString(`<span class="s-`) + b.WriteString(names[c]) + b.WriteString(`">`) + open = c + } + escapeTo(b, line[i:j]) + } + i = j + } + if open != 0 { + b.WriteString("</span>") + } +} + +// escapeTo escapes the three characters that matter in text content. +func escapeTo(b *strings.Builder, s []byte) { + last := 0 + for i, c := range s { + var rep string + switch c { + case '&': + rep = "&" + case '<': + rep = "<" + case '>': + rep = ">" + default: + continue + } + b.Write(s[last:i]) + b.WriteString(rep) + last = i + 1 + } + b.Write(s[last:]) +} + +// ── highlighting ────────────────────────────────────────────────────────── + +// grammars lists every language the site can highlight: the extensions it +// claims, the vendored queries that paint it, and the cgo grammar. Query files +// concatenate the way upstream composes them — C's patterns underpin C++, +// JavaScript's underpin TypeScript — and the concatenation keeps the +// later-patterns-win order, so the supplement wins where both match. +var grammars = []struct { + exts []string + scms []string + lang func() unsafe.Pointer +}{ + {[]string{".rs"}, []string{"rust"}, tsrust.Language}, + {[]string{".go"}, []string{"go"}, tsgo.Language}, + {[]string{".py", ".pyi"}, []string{"python"}, tspython.Language}, + {[]string{".js", ".mjs", ".cjs", ".jsx"}, []string{"javascript", "javascript-params", "jsx"}, tsjs.Language}, + {[]string{".ts", ".mts", ".cts"}, []string{"javascript", "typescript"}, tsts.LanguageTypescript}, + {[]string{".tsx"}, []string{"javascript", "typescript", "jsx"}, tsts.LanguageTSX}, + {[]string{".c"}, []string{"c"}, tsc.Language}, + // .h is C++'s upstream claim, and the C++ grammar is a superset: C headers + // parse the same under it, C++ headers only parse under it + {[]string{".cc", ".cpp", ".cxx", ".h", ".hh", ".hpp", ".hxx"}, []string{"c", "cpp"}, tscpp.Language}, + {[]string{".zig"}, []string{"zig"}, tszig.Language}, + {[]string{".json"}, []string{"json"}, tsjson.Language}, + {[]string{".sh", ".bash"}, []string{"bash"}, tsbash.Language}, +} + +// language is one grammar's share of the highlighter. Everything here is built +// at startup and never written again, which is what lets classify run from any +// number of goroutines at once. +type language struct { + lang *sitter.Language + query *sitter.Query + captureCls []int16 // capture index -> class id +} + +type highlighter struct { + byExt map[string]*language + classNames []string +} + +// resolveKey finds the theme syntax key for a capture name by stripping dot +// segments; "" when the theme has no entry at all. +func resolveKey(t *Theme, name string) string { + for key := name; key != ""; { + if s, ok := t.Syntax[key]; ok && s.Color != "" { + return key + } + if i := strings.LastIndex(key, "."); i >= 0 { + key = key[:i] + } else { + break + } + } + return "" +} + +// nearFg reports whether a capture would render indistinguishably from plain +// foreground text in the theme. Spans for such captures are pure DOM weight. +func nearFg(t *Theme, name string) bool { + key := resolveKey(t, name) + if key == "" { + return true // no color -> falls through to fg anyway + } + return colorDist(hex6(t.Syntax[key].Color), hex6(t.Fg)) < 2000 +} + +func newHighlighter(dark, light *Theme) *highlighter { + h := &highlighter{byExt: map[string]*language{}, classNames: []string{""}} + for _, g := range grammars { + var scm strings.Builder + for _, name := range g.scms { + b, err := tfs.ReadFile("assets/" + name + ".scm") + if err != nil { + fatal("%v", err) + } + scm.Write(b) + } + l := &language{lang: sitter.NewLanguage(g.lang())} + q, qerr := sitter.NewQuery(l.lang, scm.String()) + if qerr != nil { + fatal("%s query: %v", strings.Join(g.scms, "+"), qerr) + } + l.query = q + for _, name := range q.CaptureNames() { + l.captureCls = append(l.captureCls, h.classFor(dark, light, name)) + } + for _, ext := range g.exts { + h.byExt[ext] = l + } + } + return h +} + +// classFor interns the class id of a capture name, which doubles as a zed +// theme syntax key. Captures both themes paint (nearly) as foreground get id 0 +// and no span at all — punctuation and friends are the bulk of all spans. +func (h *highlighter) classFor(dark, light *Theme, name string) int16 { + if nearFg(dark, name) && nearFg(light, name) { + return 0 + } + key := resolveKey(dark, name) + if key == "" { + key = resolveKey(light, name) + } + cls := strings.ReplaceAll(key, ".", "-") + for i, n := range h.classNames { + if n == cls { + return int16(i) + } + } + h.classNames = append(h.classNames, cls) + return int16(len(h.classNames) - 1) +} + +type paint struct { + start, end uint + pattern uint + cls int16 +} + +// classify paints a file. Extensions no grammar claims come back unclassified +// rather than guessed at. +func (h *highlighter) classify(path string, src []byte) []int16 { + return h.classifyWith(h.byExt[strings.ToLower(filepath.Ext(path))], src) +} + +// fenceAliases maps the fence languages that are not already one of the +// extensions in grammars. Most are ("go", "rs", "py", "ts", "json", "bash"), +// so the grammar table does the bulk of the lookup on its own. +var fenceAliases = map[string]string{ + "golang": ".go", "rust": ".rs", "python": ".py", "python3": ".py", + "javascript": ".js", "node": ".js", "typescript": ".ts", + "c++": ".cc", "shell": ".sh", "zsh": ".sh", "console": ".sh", + "jsonc": ".json", "json5": ".json", +} + +// classifyLang paints a fenced code block, whose language arrives as a name +// rather than a path. Unknown or absent languages come back unclassified, the +// same as an extension no grammar claims. +func (h *highlighter) classifyLang(lang string, src []byte) []int16 { + if h == nil { + return make([]int16, len(src)) + } + name := strings.ToLower(strings.TrimSpace(lang)) + l := h.byExt["."+name] + if l == nil { + l = h.byExt[fenceAliases[name]] + } + return h.classifyWith(l, src) +} + +// classifyWith is safe for concurrent use: the shared per-language query is +// immutable, and parser and cursor are per-call. +// +// Matches arrive already filtered by their #eq?/#match?/#any-of? predicates — +// go-tree-sitter evaluates those in QueryMatches.Next — so every capture here +// is one the query really meant. +func (h *highlighter) classifyWith(l *language, src []byte) []int16 { + classes := make([]int16, len(src)) + if l == nil { + return classes + } + parser := sitter.NewParser() + defer parser.Close() + parser.SetLanguage(l.lang) + tree := parser.Parse(src, nil) + defer tree.Close() + + qc := sitter.NewQueryCursor() + defer qc.Close() + matches := qc.Matches(l.query, tree.RootNode(), src) + var paints []paint + for m := matches.Next(); m != nil; m = matches.Next() { + for _, c := range m.Captures { + if cls := l.captureCls[c.Index]; cls != 0 { + paints = append(paints, paint{c.Node.StartByte(), c.Node.EndByte(), m.PatternIndex, cls}) + } + } + } + // later patterns in the query paint over earlier ones; two captures of one + // pattern must not overlap, since this sort leaves their order arbitrary + sort.Slice(paints, func(i, j int) bool { return paints[i].pattern < paints[j].pattern }) + for _, p := range paints { + for i := p.start; i < p.end && int(i) < len(classes); i++ { + classes[i] = p.cls + } + } + return classes +} diff --git a/web/serve.go b/web/serve.go new file mode 100644 index 0000000..93b3f05 --- /dev/null +++ b/web/serve.go @@ -0,0 +1,774 @@ +// serve.go — notevi web as a live web application. +// +// The server owns nothing. Three rules keep it that way, and app_test.go holds +// each of them: +// +// - The log sidecar is the only thing written. Notes typed in the browser are +// appended to it exactly as notevi appends them; project history and the main +// working copy are only ever read (see jj.go). +// - Memory is a cache, never a source. The model, the per-change +// projections, file lists and rendered pages are all derived from the log +// and the repo, so a restart changes nothing anyone can see. +// - What is cached is keyed by what it was derived from: the log's +// generation, and the commit id — not the change id, which is a pointer +// that moves whenever the change is edited. +// +// What a reader chose lives in the URL (which change, how wide the view) or in +// their own browser (theme, focus, which folders are open). None of it is here. +// +// Pages are rendered per request from the same templates the static export +// uses; htmx swaps the parts that change on their own — filtered note lists, +// the activity of agents currently reading, jj queries. +package web + +import ( + "bytes" + "fmt" + "html/template" + "net/http" + "net/url" + "strconv" + "strings" + "sync" + "time" +) + +// liveWindow is how recently a session must have logged something to count as +// still running. +const liveWindow = 5 * time.Minute + +// renderCacheMax bounds the rendered-file cache; it is dropped wholesale +// whenever the log changes, since coverage is baked into the HTML. +const renderCacheMax = 64 + +type server struct { + log logStore + repo, title, user, session, base string + tpl *template.Template + hl *highlighter + theme, light *Theme + themes *themeSet + tx *transcripts + + mu sync.Mutex + site *Site + entries []Entry + state string + gen int + def string // resolved change the log points at + models map[string]*Site // scope key -> the log projected onto it + trees map[string][]*File // scope key|change -> file list + rendered map[string]*File // gen|scope|change|path -> rendered file +} + +// scopeAll is the key of the unscoped model — the whole log, every change. +const scopeAll = "*" + +func newServer(log logStore, repo, title, user string, theme, light *Theme, themes *themeSet) *server { + return newServerAt(log, repo, title, user, "/", theme, light, themes) +} + +func newServerAt(log logStore, repo, title, user, base string, theme, light *Theme, themes *themeSet) *server { + if themes == nil { + themes = &themeSet{} + } + base = (&page{Root: base}).liveRoot() + hl := newHighlighter(theme, light) + sv := &server{log: log, repo: repo, title: title, user: user, base: base, + session: "web:" + user, theme: theme, light: light, themes: themes, + tpl: newTemplates(hl), models: map[string]*Site{}, trees: map[string][]*File{}, + rendered: map[string]*File{}, tx: newTranscripts(defaultTranscriptRoots())} + sv.hl = hl + sv.reload(true) + return sv +} + +// reload re-reads the log when the sidecar commit id changes. +func (sv *server) reload(force bool) { + state, err := sv.log.Generation() + if err == nil && state == sv.state && !force { + return + } + if err != nil { + if sv.site == nil { + sv.site = sv.dress(buildModel(sv.title, nil, "")) + } + return + } + b, err := sv.log.Read() + if err != nil { + if sv.site == nil { + sv.state = state + sv.site = sv.dress(buildModel(sv.title, nil, "")) + sv.gen++ + } + return + } + sv.entries = parseLog(b) + sv.state = state + sv.site = sv.dress(buildModel(sv.title, sv.entries, "")) + sv.gen++ + sv.def = "" + sv.models = map[string]*Site{} + sv.trees = map[string][]*File{} + sv.rendered = map[string]*File{} +} + +func (sv *server) dress(s *Site) *Site { + s.Theme, s.Light, s.Repo = sv.theme, sv.light, sv.repo + return s +} + +// snap returns the whole-log model, its generation, and the change the log +// points at: the most-logged change this repo actually has, since a log can +// carry entries from several repos, falling back to the working copy. +func (sv *server) snap() (*Site, int, string) { + sv.mu.Lock() + defer sv.mu.Unlock() + sv.reload(false) + if sv.def == "" { + for i, c := range sv.site.Ranked { + if i == 5 { + break // a log with many foreign changes is not worth probing + } + if id, err := resolveChange(sv.repo, c); err == nil { + sv.def = id + break + } + } + if sv.def == "" { + if id, err := resolveChange(sv.repo, "@"); err == nil { + sv.def = id + } else { + sv.def = sv.site.Change + } + } + } + return sv.site, sv.gen, sv.def +} + +// modelFor returns the log projected onto one change, or the whole log when +// change is "". Built once per generation, since the projection is pure. +func (sv *server) modelFor(change string) *Site { + key := change + if key == "" { + key = scopeAll + } + sv.mu.Lock() + defer sv.mu.Unlock() + if s, ok := sv.models[key]; ok { + return s + } + s := sv.site + if change != "" { + s = sv.dress(buildModel(sv.title, sv.entries, change)) + } + sv.models[key] = s + return s +} + +func scopeKey(site *Site) string { + if site.Only == "" { + return scopeAll + } + return site.Only +} + +func (sv *server) filesLocked(site *Site, commit, change string) []*File { + key := scopeKey(site) + "|" + commit + if f, ok := sv.trees[key]; ok { + return f + } + paths, err := fileList(sv.repo, commit) + if err != nil { + return nil + } + f := site.filesAt(paths, change) + sv.trees[key] = f + return f +} + +func (sv *server) files(site *Site, commit, change string) []*File { + sv.mu.Lock() + defer sv.mu.Unlock() + return sv.filesLocked(site, commit, change) +} + +// forgetDefault drops the chosen change so the next request picks again — +// the repo moved under us, which is the repo's business, not ours to remember. +func (sv *server) forgetDefault() { + sv.mu.Lock() + sv.def = "" + sv.mu.Unlock() +} + +// fileAt renders one file: model coverage and notes, source from jj, +// highlighted. commit is the content it is read at and what the cache is keyed +// on — change only names it on the page — so an edit under the same change id +// is a different key, never a stale hit. +func (sv *server) fileAt(site *Site, gen int, commit, change, path string) *File { + key := fmt.Sprintf("%d|%s|%s|%s", gen, scopeKey(site), commit, path) + sv.mu.Lock() + if f, ok := sv.rendered[key]; ok { + sv.mu.Unlock() + return f + } + sv.mu.Unlock() + + var f *File + if base, ok := site.Files[path]; ok { + f = base.clone() + } else { + f = &File{Path: path, Change: change, NoteAt: map[int]int{}} + } + if f.Change == "" { + f.Change = change + } + src, err := fileShow(sv.repo, commit, path) + switch { + case err != nil: + f.Stub = "not present at this change" + case bytes.IndexByte(src, 0) >= 0: + f.Stub = "binary file — not rendered" + case len(src) > 2<<20: + f.Stub = fmt.Sprintf("file too large to render (%d KB)", len(src)/1024) + default: + f.render(src, sv.hl) + } + + sv.mu.Lock() + if len(sv.rendered) > renderCacheMax { + sv.rendered = map[string]*File{} + } + sv.rendered[key] = f + sv.mu.Unlock() + return f +} + +// ── request plumbing ────────────────────────────────────────────────────── + +// newPage answers the two questions every page starts from: which change am I +// looking at, and am I seeing only what was recorded there. ?rev= picks the +// change (default: the one the log points at); ?scope=all widens the view to +// the whole log, and a change nothing was ever recorded at widens by itself, +// so the site never looks mysteriously empty. +func (sv *server) newPage(r *http.Request, kind, title string) (*page, *Site, error) { + full, _, def := sv.snap() + q := r.URL.Query() + path := sv.base + strings.TrimPrefix(r.URL.Path, "/") + p := &page{Site: full, Kind: kind, Title: title, Root: sv.base, Live: true, + User: sv.user, ChangeID: def, Default: def, Path: path, Scope: "change"} + rev := strings.TrimSpace(q.Get("rev")) + target := rev + if target == "" { + target = def + } + row, err := changeBrief(sv.repo, target) + if err != nil { + if rev == "" { + sv.forgetDefault() // the log's change left the repo; pick again + } + p.Facets = full.Facets() + return p, full, err + } + p.ChangeID, p.Commit, p.ChangeInfo = row.ID, row.Commit, &row + if rev != "" && row.ID != def { + p.Rev = rev + } + if q.Get("scope") == "all" { + p.Scope = "all" + } + return p, sv.rescope(p), nil +} + +// rescope picks the model for the change the page settled on. Handlers that +// discover their change from the path (a change page) call it again. +func (sv *server) rescope(p *page) *Site { + full, _, _ := sv.snap() + site := full + p.ScopeEmpty = false + if p.Scope == "change" { + if full.Votes[p.ChangeID] > 0 { + site = sv.modelFor(p.ChangeID) + } else { + p.ScopeEmpty = true // asked for this change, nothing was recorded here + } + } + p.Site, p.Facets = site, site.Facets() + p.Here = full.NotesAt[p.ChangeID] + p.Elsewhere = full.NotesTotal - p.Here + return site +} + +func (sv *server) render(w http.ResponseWriter, p *page) { + var b bytes.Buffer + if err := sv.tpl.Execute(&b, p); err != nil { + http.Error(w, "render: "+err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + b.WriteTo(w) +} + +func (sv *server) frag(w http.ResponseWriter, name string, data any) { + var b bytes.Buffer + if err := sv.tpl.ExecuteTemplate(&b, name, data); err != nil { + http.Error(w, "render: "+err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + b.WriteTo(w) +} + +func htmxReq(r *http.Request) bool { return r.Header.Get("HX-Request") != "" } + +func atoiDefault(s string, def int) int { + if n, err := strconv.Atoi(strings.TrimSpace(s)); err == nil { + return n + } + return def +} + +func (sv *server) handler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("GET /{$}", sv.index) + mux.HandleFunc("GET /files", sv.filesPage) + mux.HandleFunc("GET /tree", sv.treeFrag) + mux.HandleFunc("GET /code/{path...}", sv.codePage) + mux.HandleFunc("GET /notes", sv.notesPage) + mux.HandleFunc("GET /note/{id}", sv.notePage) + mux.HandleFunc("GET /notes/list", sv.notesList) + mux.HandleFunc("POST /notes", sv.addNote) + mux.HandleFunc("GET /activity", sv.activity) + mux.HandleFunc("GET /session/{id}", sv.sessionPage) + mux.HandleFunc("GET /jj", sv.jjPage) + mux.HandleFunc("GET /jj/log", sv.jjLog) + mux.HandleFunc("GET /jj/op", sv.jjOp) + mux.HandleFunc("GET /change/{id}", sv.changePage) + mux.HandleFunc("GET /style.css", sv.styleCSS) + mux.HandleFunc("GET /themes.css", sv.themeAsset) + mux.HandleFunc("GET /themes.js", sv.themeAsset) + mux.HandleFunc("GET /app.js", sv.asset) + mux.HandleFunc("GET /htmx.min.js", sv.asset) + mux.HandleFunc("GET /bemtevi.svg", sv.asset) + return mux +} + +// ── pages ───────────────────────────────────────────────────────────────── + +func (sv *server) index(w http.ResponseWriter, r *http.Request) { + p, site, err := sv.newPage(r, "index", sv.title) + if err != nil { + p.Err = err.Error() + } + p.Notes = site.FilterNotes(NoteFilter{}) + if len(p.Notes) > 24 { + p.Notes = p.Notes[:24] + } + p.Files = sv.files(site, p.Commit, p.ChangeID) + sv.render(w, p) +} + +func (sv *server) filesPage(w http.ResponseWriter, r *http.Request) { + p, site, err := sv.newPage(r, "files", "files — "+sv.title) + if err != nil { + p.Err = err.Error() + sv.render(w, p) + return + } + p.Tree = template.HTML(renderTree(sv.files(site, p.Commit, p.ChangeID), p.codeLink())) + sv.render(w, p) +} + +func (sv *server) treeFrag(w http.ResponseWriter, r *http.Request) { + p, site, err := sv.newPage(r, "files", "") + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + fmt.Fprint(w, renderTree(sv.files(site, p.Commit, p.ChangeID), p.codeLink())) +} + +func (sv *server) codePage(w http.ResponseWriter, r *http.Request) { + path := strings.TrimPrefix(r.PathValue("path"), "/") + p, site, err := sv.newPage(r, "file", path+" — "+sv.title) + if err != nil { + p.Err = err.Error() + sv.render(w, p) + return + } + _, gen, _ := sv.snap() + p.Current = path + p.File = sv.fileAt(site, gen, p.Commit, p.ChangeID, path) + sv.render(w, p) +} + +func (sv *server) notesPage(w http.ResponseWriter, r *http.Request) { + p, site, err := sv.newPage(r, "notes", "notes — "+sv.title) + if err != nil { + p.Err = err.Error() + } + p.Filter = filterFrom(r) + p.Notes = site.FilterNotes(p.Filter) + sv.render(w, p) +} + +// notePage is one note on its own — the permalink. It is looked up in the +// whole-log model, never the scoped one, so a link handed to someone else +// opens whatever change they arrive on. +// +// The page then reads at the change the note was written at, because that is +// where its line numbers mean anything; ?rev= still overrides, for a reader +// asking what those lines say now. +func (sv *server) notePage(w http.ResponseWriter, r *http.Request) { + full, _, _ := sv.snap() + n := full.NoteByID(atoiDefault(r.PathValue("id"), 0)) + if n == nil { + http.Error(w, "no note with that id in this log", http.StatusNotFound) + return + } + p, site, err := sv.newPage(r, "note", noteTitle(n)+" — "+sv.title) + if err != nil { + p.Err = err.Error() + sv.render(w, p) + return + } + p.Note, p.Thread, p.Current = n, full.NoteThread(n.ID), n.File + if p.Rev == "" && n.Change != "" && n.Change != p.ChangeID { + if row, rerr := changeBrief(sv.repo, n.Change); rerr == nil { + p.ChangeID, p.Commit, p.ChangeInfo = row.ID, row.Commit, &row + if row.ID != p.Default { + p.Rev = n.Change + } + site = sv.rescope(p) + } else { + p.ExErr = "the change this note was written at is no longer in the repository" + } + } + if n.File != "" && n.Start > 0 && p.ExErr == "" { + var cov []uint8 + if bf, ok := site.Files[n.File]; ok { + cov = bf.Cov + } + src, ferr := fileShow(sv.repo, p.Commit, n.File) + switch { + case ferr != nil: + p.ExErr = "not present at this change" + case bytes.IndexByte(src, 0) >= 0: + p.ExErr = "binary file — not rendered" + default: + p.Excerpt, p.ExFrom, p.ExTo = excerptFor(n.File, src, cov, sv.hl, n) + } + } + sv.render(w, p) +} + +// noteTitle names a note the way a browser tab and a link preview should: the +// lines it is about, or its id when it is pinned to nothing. +func noteTitle(n *Note) string { + if n.File == "" { + return "note #" + strconv.Itoa(n.ID) + } + name := n.File + if i := strings.LastIndex(name, "/"); i >= 0 { + name = name[i+1:] + } + if n.Start > 0 { + name += ":" + strconv.Itoa(n.Start) + if n.End > n.Start { + name += "-" + strconv.Itoa(n.End) + } + } + return name +} + +func (sv *server) notesList(w http.ResponseWriter, r *http.Request) { + p, site, _ := sv.newPage(r, "notes", "") + p.Filter = filterFrom(r) + p.Notes = site.FilterNotes(p.Filter) + sv.frag(w, "notelist-oob", p) +} + +func filterFrom(r *http.Request) NoteFilter { + q := r.URL.Query() + return NoteFilter{ + Text: q.Get("text"), File: q.Get("file"), Agent: q.Get("agent"), + Model: q.Get("model"), Session: q.Get("session"), Kind: q.Get("kind"), + Change: q.Get("change"), From: q.Get("from"), To: q.Get("to"), + } +} + +// addNote appends a comment written in the browser to the log — the only +// write this program does, and it never touches the repository. +func (sv *server) addNote(w http.ResponseWriter, r *http.Request) { + // the app writes to a file on your disk, so refuse posts a page on + // another origin sent here + if o := r.Header.Get("Origin"); o != "" { + if u, err := url.Parse(o); err != nil || u.Host != r.Host { + http.Error(w, "cross-origin post refused", http.StatusForbidden) + return + } + } + if err := r.ParseForm(); err != nil { + http.Error(w, "bad form", http.StatusBadRequest) + return + } + text := strings.TrimSpace(r.FormValue("text")) + if text == "" { + http.Error(w, "a note needs text", http.StatusBadRequest) + return + } + // a note belongs to the change its writer was reading, which is the one + // the form carries — not the working copy, which may have moved on since + full, _, def := sv.snap() + replyText := strings.TrimSpace(r.FormValue("reply_to")) + replyTo := 0 + if replyText != "" { + var rerr error + replyTo, rerr = strconv.Atoi(replyText) + if rerr != nil || replyTo < 1 || full.NoteByID(replyTo) == nil { + http.Error(w, "reply target is not a note in this log", http.StatusBadRequest) + return + } + } + rev := strings.TrimSpace(r.FormValue("rev")) + target := strings.TrimSpace(r.FormValue("change")) + for _, fallback := range []string{rev, def, "@"} { + if target != "" { + break + } + target = fallback + } + change, commit, err := resolveRevision(sv.repo, target) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if rev == "" { + rev = target + } + start := atoiDefault(r.FormValue("start"), 0) + end := atoiDefault(r.FormValue("end"), 0) + if end < start { + end = start + } + e := Entry{ + Time: time.Now().Format(time.RFC3339), Op: "note", + Session: sv.session, Agent: sv.user, Dir: sv.repo, + Rev: rev, Change: change, Commit: commit, File: strings.TrimSpace(r.FormValue("file")), + Start: start, End: end, ReplyTo: replyTo, + Type: strings.TrimSpace(r.FormValue("kind")), Text: text, + } + + sv.mu.Lock() + err = appendEntry(sv.log, &e) + if err == nil { + sv.reload(true) + } + site := sv.site + sv.mu.Unlock() + if err != nil { + http.Error(w, "write log: "+err.Error(), http.StatusInternalServerError) + return + } + // answer in the same view the writer is looking at, or the note count + // coming back would be the whole log's while their page shows one change + scope := r.FormValue("scope") + if scope != "all" { + site = sv.modelFor(change) + } + + if !htmxReq(r) { + back := r.FormValue("back") + if back == "" { + back = sv.base + "notes" + } + http.Redirect(w, r, back, http.StatusSeeOther) + return + } + p := &page{Site: site, Kind: "file", Root: sv.base, Live: true, User: sv.user, Facets: site.Facets()} + if e.File != "" { + p.File = site.Files[e.File] + } + // the note just written is the last one carrying our session and id + for i := len(site.Notes) - 1; i >= 0; i-- { + if n := site.Notes[i]; n.Session == sv.session && n.NoteID == e.NoteID { + p.Notes = []*Note{n} + break + } + } + sv.frag(w, "note-added", p) +} + +func (sv *server) activity(w http.ResponseWriter, r *http.Request) { + site, _, _ := sv.snap() + limit := 6 + compact := r.URL.Query().Get("compact") != "" + if !compact { + limit = 20 + } + p := &page{Site: site, Root: sv.base, Live: true, Compact: compact, Window: "5 min", + Sessions: site.Sessions(time.Now(), liveWindow, limit)} + sv.frag(w, "activity", p) +} + +// sessionPage shows one session's conversation, with ?note=N anchoring the +// moment a note was written. It renders from the log alone when the harness +// transcript cannot be found — the reading timeline is still worth having. +func (sv *server) sessionPage(w http.ResponseWriter, r *http.Request) { + id := r.PathValue("id") + if err := safeSession(id); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + p, site, err := sv.newPage(r, "session", "session "+short(id)+" — "+sv.title) + if err != nil { + p.Err = err.Error() + } + q := r.URL.Query() + p.Conv = sv.conversation(site, id, atoiDefault(q.Get("note"), 0), q.Get("all") != "") + sv.render(w, p) +} + +// ── jj ──────────────────────────────────────────────────────────────────── + +const defaultLimit = 50 + +func (sv *server) jjView(r *http.Request) *JJView { + q := r.URL.Query() + v := &JJView{Root: sv.base, Kind: q.Get("kind"), Revset: strings.TrimSpace(q.Get("revset")), + AtOp: strings.TrimSpace(q.Get("at_op")), Limit: atoiDefault(q.Get("limit"), defaultLimit)} + if v.Limit < 1 || v.Limit > 1000 { + v.Limit = defaultLimit + } + if v.Kind != "op" { + v.Kind = "log" + } + var err error + if v.Kind == "op" { + v.Rows, err = OpRows(sv.repo, v.Limit) + } else { + v.Rows, err = LogRows(sv.repo, v.Revset, v.AtOp, v.Limit) + } + if err != nil { + v.Err = err.Error() + } + return v +} + +func (sv *server) jjPage(w http.ResponseWriter, r *http.Request) { + p, _, err := sv.newPage(r, "jj", "jj — "+sv.title) + if err != nil { + p.Err = err.Error() + } + p.JJ = sv.jjView(r) + sv.render(w, p) +} + +func (sv *server) jjLog(w http.ResponseWriter, r *http.Request) { + v := sv.jjView(r) + if !htmxReq(r) { + sv.jjPage(w, r) + return + } + sv.frag(w, "jjrows", v) +} + +func (sv *server) jjOp(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + v := &JJView{Root: sv.base, Kind: "op", Limit: atoiDefault(q.Get("limit"), defaultLimit)} + if v.Limit < 1 || v.Limit > 1000 { + v.Limit = defaultLimit + } + var err error + if v.Rows, err = OpRows(sv.repo, v.Limit); err != nil { + v.Err = err.Error() + } + if !htmxReq(r) { + p, _, _ := sv.newPage(r, "jj", "jj op log — "+sv.title) + p.JJ = v + sv.render(w, p) + return + } + sv.frag(w, "jjrows", v) +} + +func (sv *server) changePage(w http.ResponseWriter, r *http.Request) { + id := r.PathValue("id") + p, site, _ := sv.newPage(r, "change", id+" — "+sv.title) + c, err := LoadChange(sv.repo, id) + if err != nil { + p.Err = err.Error() + sv.render(w, p) + return + } + p.Change = c + p.Rev, p.ChangeID, p.Commit = c.Row.ID, c.Row.ID, c.Row.Commit + p.ChangeInfo = &c.Row + p.Title = c.Row.Short + " — " + sv.title + // the page named a change the query string did not, so the view follows it + site = sv.rescope(p) + p.Notes = site.FilterNotes(NoteFilter{Change: c.Row.ID}) + sv.render(w, p) +} + +// ── assets ──────────────────────────────────────────────────────────────── + +func (sv *server) styleCSS(w http.ResponseWriter, r *http.Request) { + site, _, _ := sv.snap() + var b bytes.Buffer + if err := renderCSS(&b, site); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "text/css; charset=utf-8") + b.WriteTo(w) +} + +// themeAsset serves the two files the theme picker needs. Both are written +// once at startup — the machine's themes do not change while we watch a log. +func (sv *server) themeAsset(w http.ResponseWriter, r *http.Request) { + body, ctype := sv.themes.JS, "text/javascript; charset=utf-8" + if strings.HasSuffix(r.URL.Path, ".css") { + body, ctype = sv.themes.CSS, "text/css; charset=utf-8" + } + w.Header().Set("Content-Type", ctype) + w.Header().Set("Cache-Control", "max-age=300") + w.Write(body) +} + +func (sv *server) asset(w http.ResponseWriter, r *http.Request) { + name := strings.TrimPrefix(r.URL.Path, "/") + b, err := tfs.ReadFile("assets/" + name) + if err != nil { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", assetType(name)) + w.Header().Set("Cache-Control", "max-age=300") + w.Write(b) +} + +// assetType covers what embedded assets/ actually holds: scripts and the mark. +func assetType(name string) string { + if strings.HasSuffix(name, ".svg") { + return "image/svg+xml" + } + return "text/javascript; charset=utf-8" +} + +func serve(addr string, log logStore, repo, title, user string, roots []string, theme, light *Theme, themes *themeSet) { + sv := newServer(log, repo, title, user, theme, light, themes) + sv.tx = newTranscripts(roots) + site, _, def := sv.snap() + fmt.Printf("notevi web: http://%s — %d notes, %d agents, repo %s at %s\n", + addr, len(site.Notes), len(site.Agents), repo, short(def)) + fmt.Printf("notevi web: themes — %s dark, %s light, %d more to pick from (%d zed, %d helix)\n", + theme.Name, light.Name, len(sv.themes.List), sv.themes.count("zed"), sv.themes.count("helix")) + fmt.Printf("notevi web: comments are appended to %s; the project working copy is never written to\n", log) + fmt.Printf("notevi web: session transcripts read from %s\n", strings.Join(sv.tx.roots, ", ")) + if err := http.ListenAndServe(addr, sv.handler()); err != nil { + fatal("%v", err) + } +} diff --git a/web/static.go b/web/static.go new file mode 100644 index 0000000..3f3e766 --- /dev/null +++ b/web/static.go @@ -0,0 +1,247 @@ +// static.go — the offline export: the same pages written out as files. +// +// Everything that needs a server (comments, live activity, jj queries) is +// omitted; the trace/notes toggle, the file finder and the note filters all +// keep working, since they run in the browser. +package web + +import ( + "bytes" + "fmt" + "html/template" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync" + "time" +) + +func run(dir string, name string, args ...string) []byte { + cmd := exec.Command(name, args...) + cmd.Dir = dir + out, err := cmd.Output() + if err != nil { + if ee, ok := err.(*exec.ExitError); ok { + os.Stderr.Write(ee.Stderr) + } + fatal("%s %s: %v", name, strings.Join(args, " "), err) + } + return out +} + +func buildSite(log logStore, repoAbs, out, title string, theme, light *Theme, themes *themeSet) { + start := time.Now() + entries := readLog(log) + ranked := buildModel(title, entries, "").Ranked + if len(ranked) == 0 { + fatal("log has no jj change ids") + } + // the most-logged change this repo actually has: a log can span repos, and + // the busiest change in it may belong to another one + var change string + var list []byte + for _, c := range ranked { + out, err := jjRun(repoAbs, "file", "list", "-r", c) + if err == nil { + change, list = c, out + break + } + } + if change == "" { + fatal("none of the log's %d changes are in %s — logs are per repository; point -repo at the one the trace was recorded in", + len(ranked), repoAbs) + } + // an export is a picture of one change, so it holds only what was + // recorded there; the notes page says how much of the log that leaves out + site := buildModel(title, entries, change) + site.Change = change + site.Theme, site.Light, site.Repo = theme, light, repoAbs + site.All = site.filesAt(strings.Split(strings.TrimRight(string(list), "\n"), "\n"), change) + + commit := strings.TrimSpace(string(mustJJ(repoAbs, "log", "-r", site.Change, "--no-graph", "-T", "commit_id"))) + tmp, err := os.MkdirTemp("", "notevi-") + if err != nil { + fatal("%v", err) + } + defer os.RemoveAll(tmp) + archive := exec.Command("git", "-C", repoAbs, "archive", commit) + untar := exec.Command("tar", "-x", "-C", tmp) + untar.Stdin, _ = archive.StdoutPipe() + untar.Stderr = os.Stderr + if err := untar.Start(); err != nil { + fatal("tar: %v", err) + } + if err := archive.Run(); err != nil { + fatal("git archive %s: %v", short(commit), err) + } + if err := untar.Wait(); err != nil { + fatal("tar: %v", err) + } + + writeSite(site, out, tmp, themes) + stubs := 0 + for _, f := range site.All { + if f.Stub != "" { + stubs++ + } + } + fmt.Printf("notevi web: %d files (%d traced, %d not rendered), %d notes, %d agents in %s -> %s\n", + len(site.All), len(site.Order), stubs, len(site.Notes), len(site.Agents), + time.Since(start).Round(time.Millisecond), out) +} + +func writeSite(site *Site, out, srcDir string, themes *themeSet) { + if themes == nil { + themes = &themeSet{} + } + hl := newHighlighter(site.Theme, site.Light) + tpl := newTemplates(hl) + if err := os.MkdirAll(out, 0o755); err != nil { + fatal("%v", err) + } + + each := func(fn func(f *File)) { + sem := make(chan struct{}, runtime.NumCPU()) + var wg sync.WaitGroup + for _, f := range site.All { + wg.Add(1) + sem <- struct{}{} + go func(f *File) { + defer func() { <-sem; wg.Done() }() + fn(f) + }(f) + } + wg.Wait() + } + // phase A: content — coverage percentages must exist before any tree + // or index below is written + each(func(f *File) { + src, err := os.ReadFile(filepath.Join(srcDir, f.Path)) + switch { + case err != nil: + f.Stub = "not present in the archived commit" + case bytes.IndexByte(src, 0) >= 0: + f.Stub = "binary file — not rendered" + case len(src) > 2<<20: + f.Stub = fmt.Sprintf("file too large to render (%d KB)", len(src)/1024) + default: + f.render(src, hl) + } + }) + + cf := mustCreate(filepath.Join(out, "style.css")) + if err := renderCSS(cf, site); err != nil { + fatal("css: %v", err) + } + cf.Close() + for _, name := range []string{"app.js", "bemtevi.svg"} { + b, err := tfs.ReadFile("assets/" + name) + if err != nil { + fatal("%v", err) + } + if err := os.WriteFile(filepath.Join(out, name), b, 0o644); err != nil { + fatal("%v", err) + } + } + // the picker travels with the export: a <script src>/<link> pair loads + // from the filesystem, which is why the menu is a script and not JSON + for name, b := range map[string][]byte{"themes.css": themes.CSS, "themes.js": themes.JS} { + if err := os.WriteFile(filepath.Join(out, name), b, 0o644); err != nil { + fatal("%v", err) + } + } + + // shared tree fragment: the only nav tree, fetched by every page; "@@" is + // replaced with the page root by app.js, since the fragment is fetched + // from any page depth + treeFrag := renderTree(site.All, func(p string) string { return "@@code/" + p + ".html" }) + if err := os.WriteFile(filepath.Join(out, "tree.html"), []byte(treeFrag), 0o644); err != nil { + fatal("%v", err) + } + + facets := site.Facets() + var info *Row + if rows, err := LogRows(site.Repo, site.Change, "", 1); err == nil { + for _, row := range rows { + if !row.Blank() { + r := row + info = &r + break + } + } + } + render := func(path string, p *page) { + p.Site, p.Facets = site, facets + p.ChangeID, p.Default, p.ChangeInfo = site.Change, site.Change, info + p.Scope, p.Here = "change", site.NotesAt[site.Change] + p.Elsewhere = site.NotesTotal - p.Here + p.Files = site.All + f := mustCreate(path) + if err := tpl.Execute(f, p); err != nil { + fatal("render %s: %v", path, err) + } + f.Close() + } + + latest := site.FilterNotes(NoteFilter{}) + if len(latest) > 24 { + latest = latest[:24] + } + render(filepath.Join(out, "index.html"), &page{Kind: "index", Title: site.Title, Notes: latest}) + + fullTree := renderTree(site.All, func(p string) string { return "code/" + p + ".html" }) + render(filepath.Join(out, "files.html"), &page{Kind: "files", Title: "files — " + site.Title, + Tree: template.HTML(fullTree)}) + + render(filepath.Join(out, "notes.html"), &page{Kind: "notes", Title: "notes — " + site.Title, + Notes: site.FilterNotes(NoteFilter{})}) + + // phase B: every file page, in parallel + each(func(f *File) { + dst := filepath.Join(out, "code", f.Path+".html") + os.MkdirAll(filepath.Dir(dst), 0o755) + depth := strings.Count(f.Path, "/") + 1 + render(dst, &page{Kind: "file", Title: f.Path + " — " + site.Title, + Root: strings.Repeat("../", depth), Current: f.Path, File: f}) + }) + + // phase C: a page per note, so a permalink handed to someone else opens + // in the export exactly as it does in the live app. The source is read + // again rather than kept from phase A: an export is a batch job, and the + // alternative is holding every file in memory for the sake of a few + // hundred excerpts. + if err := os.MkdirAll(filepath.Join(out, "note"), 0o755); err != nil { + fatal("%v", err) + } + for _, n := range site.Notes { + p := &page{Kind: "note", Title: noteTitle(n) + " — " + site.Title, + Root: "../", Current: n.File, Note: n, Thread: site.NoteThread(n.ID)} + if n.File != "" && n.Start > 0 { + src, err := os.ReadFile(filepath.Join(srcDir, n.File)) + switch { + case err != nil: + p.ExErr = "not present in the archived commit" + case bytes.IndexByte(src, 0) >= 0: + p.ExErr = "binary file — not rendered" + default: + var cov []uint8 + if f, ok := site.Files[n.File]; ok { + cov = f.Cov + } + p.Excerpt, p.ExFrom, p.ExTo = excerptFor(n.File, src, cov, hl, n) + } + } + render(filepath.Join(out, "note", strconv.Itoa(n.ID)+".html"), p) + } +} + +func mustCreate(path string) *os.File { + f, err := os.Create(path) + if err != nil { + fatal("%v", err) + } + return f +} diff --git a/web/templates/frag-activity.tmpl b/web/templates/frag-activity.tmpl new file mode 100644 index 0000000..071c556 --- /dev/null +++ b/web/templates/frag-activity.tmpl @@ -0,0 +1,36 @@ +{{/* Who is reading the codebase right now, straight off the log tail. */}} +{{define "activity"}} +{{if .Compact}} + <div class="actlist"> + {{range .Sessions}} + <div class="act{{if .Live}} on{{end}}" title="{{.Agent}} · {{.Model}} · {{.Dir}}"> + {{if and $.Live .ID}}<a class="chip am{{.Bit}}" href="{{$.Href "session" .ID}}">{{.Short}}</a> + {{else}}<span class="chip am{{.Bit}}">{{.Short}}</span>{{end}} + <span class="what">{{.LastOp}}</span> + <span class="when">{{.Ago}}</span> + </div> + {{end}} + {{if not .Sessions}}<p class="meta hint">nothing logged yet</p>{{end}} + </div> +{{else}} + <table class="acttable"> + <thead><tr><th>agent</th><th>model</th><th>session</th><th>last op</th><th>when</th><th>r/g/n</th><th>dir</th></tr></thead> + <tbody> + {{range .Sessions}} + <tr class="{{if .Live}}on{{end}}"> + <td><span class="chip am{{.Bit}}">{{.Short}}</span>{{if .Live}}<span class="pulse" title="active">●</span>{{end}}</td> + <td>{{.Model}}{{if .Reason}}<span class="meta">/{{.Reason}}</span>{{end}}</td> + <td>{{if and $.Live .ID}}<a href="{{$.Href "session" .ID}}" title="{{.ID}}"><code>{{short .ID}}</code></a> + {{else}}<code title="{{.ID}}">{{short .ID}}</code>{{end}}</td> + <td class="what">{{.LastOp}}</td> + <td>{{.Ago}}</td> + <td class="meta">{{.Reads}}/{{.Greps}}/{{.Notes}}</td> + <td class="meta dir" title="{{.Dir}}">{{base .Dir}}</td> + </tr> + {{end}} + </tbody> + </table> + {{if not .Sessions}}<p class="meta hint">nothing logged yet</p>{{end}} + <p class="meta">live = active in the last {{.Window}}</p> +{{end}} +{{end}} diff --git a/web/templates/frag-change.tmpl b/web/templates/frag-change.tmpl new file mode 100644 index 0000000..b33d746 --- /dev/null +++ b/web/templates/frag-change.tmpl @@ -0,0 +1,41 @@ +{{/* The change everything on screen is read at, and how wide the view is. + Every page carries it, because every read, note and file listing below + is relative to it. */}} +{{define "changebar"}} +<section class="changebar{{if .Rev}} away{{end}}" aria-label="current change"> + <div class="cid"> + <span class="lbl">change</span> + {{if .Live}}<a href="{{.Href "change" .ChangeID}}" title="{{.ChangeID}}"><code>{{short .ChangeID}}</code></a> + {{else}}<code title="{{.ChangeID}}">{{short .ChangeID}}</code>{{end}} + {{with .ChangeInfo}}{{if .Flags}}<span class="flags">{{.Flags}}</span>{{end}}{{end}} + </div> + {{with .ChangeInfo}} + <p class="desc" title="{{.Desc}}">{{if .Desc}}{{.Desc}}{{else}}(no description){{end}}</p> + {{end}} + + <p class="counts"> + {{if eq .Scope "all"}} + <b>{{.Site.NotesTotal}}</b> notes across every change{{if .Here}} · {{.Here}} here{{end}} + {{else if .ScopeEmpty}} + nothing recorded at this change — showing all <b>{{.Site.NotesTotal}}</b> + {{else}} + <b>{{.Here}}</b> notes here{{if .Elsewhere}} · <span class="away">{{.Elsewhere}} elsewhere</span>{{end}} + {{end}} + </p> + + {{if .Live}} + <div class="scope" role="group" aria-label="what this view covers"> + <a href="{{.ScopeHref "change"}}"{{if eq .Scope "change"}} class="on" aria-current="true"{{end}} + title="only what was recorded at this change">this change</a> + <a href="{{.ScopeHref "all"}}"{{if eq .Scope "all"}} class="on" aria-current="true"{{end}} + title="every change in the log">all</a> + </div> + <form class="revjump" method="get" action="{{.JumpPath}}"> + <input type="search" name="rev" value="{{.Rev}}" placeholder="@, id, revset…" + aria-label="read at another change" autocomplete="off" spellcheck="false"> + {{if eq .Scope "all"}}<input type="hidden" name="scope" value="all">{{end}} + </form> + {{if .Rev}}<p class="back"><a href="{{.BackHref}}">← back to <code>{{short .Default}}</code>, where the log points</a></p>{{end}} + {{end}} +</section> +{{end}} diff --git a/web/templates/frag-jj.tmpl b/web/templates/frag-jj.tmpl new file mode 100644 index 0000000..61040dc --- /dev/null +++ b/web/templates/frag-jj.tmpl @@ -0,0 +1,33 @@ +{{/* jj query results. Live-only, so routes are absolute. */}} +{{define "jjrows"}} +{{if .Err}}<p class="err">{{.Err}}</p>{{end}} +{{if .Rows}} +<div class="jjlog"> + {{range .Rows}} + {{if .Blank}}<div class="jjrow blank"><span class="graph">{{.Graph}}</span></div> + {{else if .Op}} + <div class="jjrow"> + <span class="graph">{{.Graph}}</span> + <a class="id" href="{{$.Root}}jj?at_op={{.ID}}" title="run the commit log as of this operation">{{.Short}}</a> + <span class="when">{{.When}}</span> + <span class="who">{{.Author}}</span> + <span class="desc">{{.Desc}}</span> + <span class="flags">{{.End}}</span> + </div> + {{else}} + <div class="jjrow"> + <span class="graph">{{.Graph}}</span> + <a class="id" href="{{$.Root}}change/{{.ID}}" title="{{.ID}}">{{.Short}}</a> + <code class="commit">{{.CommitShort}}</code> + <span class="when">{{.When}}</span> + <span class="who">{{.Author}}</span> + {{if .Refs}}<span class="refs">{{.Refs}}</span>{{end}} + {{if .Flags}}<span class="flags">{{.Flags}}</span>{{end}} + <a class="desc" href="{{$.Root}}files?rev={{.ID}}" title="browse the tree at this change">{{if .Desc}}{{.Desc}}{{else}}(no description){{end}}</a> + </div> + {{end}} + {{end}} +</div> +{{else if not .Err}}<p class="meta hint">no revisions matched</p>{{end}} +{{if .AtOp}}<p class="meta">as of operation <code>{{short .AtOp}}</code> · <a href="{{.Root}}jj?kind=op">back to the op log</a></p>{{end}} +{{end}} diff --git a/web/templates/frag-note.tmpl b/web/templates/frag-note.tmpl new file mode 100644 index 0000000..3b04e11 --- /dev/null +++ b/web/templates/frag-note.tmpl @@ -0,0 +1,105 @@ +{{define "note"}}{{$n := .N}}{{$p := .P}}{{$away := and $n.Change $p.ChangeID (ne $n.Change $p.ChangeID)}} +<article class="note am{{$n.Agent.Bit}}{{if $away}} away{{end}}" id="note-{{$n.ID}}" + data-agent="{{$n.Agent.Name}}" data-model="{{$n.Model}}" data-session="{{$n.Session}}" + data-kind="{{$n.Kind}}" data-file="{{$n.File}}" data-date="{{if not $n.At.IsZero}}{{$n.At.Format "2006-01-02"}}{{end}}" + data-start="{{$n.Start}}" data-end="{{$n.End}}" data-reply-to="{{$n.ReplyTo}}"> + <header> + {{if $n.File}}<a href="{{$p.NoteHref $n}}" title="{{$n.File}}">{{base $n.File}}{{lines $n}}</a>{{end}} + {{if $n.Kind}}<em>{{$n.Kind}}</em>{{end}} + <b class="who">{{$n.Agent.Short}}</b> + </header> + <div class="body">{{md $n.Text $p}}</div> + <footer class="meta"> + {{with $p.PermaHref $n}}<a class="perma" href="{{.}}" + title="permalink — this note on its own page, with the code it is about">#{{$n.ID}}</a> + {{else}}<span class="perma self">#{{$n.ID}}</span>{{end}} + {{if not $n.At.IsZero}}<time datetime="{{$n.At.Format "2006-01-02T15:04:05Z07:00"}}" title="{{$n.Ago}}">{{$n.When}}</time>{{end}} + {{if $n.Model}}<span class="model">{{$n.Model}}{{if $n.Reason}}/{{$n.Reason}}{{end}}</span>{{end}} + {{if $n.Session}}<code class="sess" title="{{$n.Session}}">{{short $n.Session}}</code>{{end}} + {{if $n.ReplyTo}}{{with $p.ReplyHref $n}}<a class="parent" href="{{.}}" + title="the note this explicitly replies to">reply to #{{$n.ReplyTo}}</a>{{else}}<span class="parent">reply to #{{$n.ReplyTo}}</span>{{end}}{{end}} + {{with $p.ThreadHref $n}}<a class="relations" href="{{.}}" title="notes replying to or mentioning this note"> + {{if $n.Replies}}↳ {{len $n.Replies}} repl{{if eq (len $n.Replies) 1}}y{{else}}ies{{end}}{{end}}{{if and $n.Replies $n.Mentions}} · {{end}}{{if $n.Mentions}}↶ {{len $n.Mentions}} mention{{if ne (len $n.Mentions) 1}}s{{end}}{{end}}</a>{{end}} + {{with $p.ConvHref $n}}<a class="conv" href="{{.}}" title="open the conversation this note was written in">conversation</a>{{end}} + {{if $n.Change}} + {{if $p.Live}}<a class="atchg{{if $away}} away{{end}}" href="{{$p.Href "change" $n.Change}}" + title="{{if $away}}written at another change{{else}}written at this change{{end}}"><code>{{short $n.Change}}</code></a> + {{else}}<code class="atchg{{if $away}} away{{end}}">{{short $n.Change}}</code>{{end}} + {{end}} + </footer> +</article> +{{end}} + +{{define "notelist"}}{{range .Notes}}{{template "note" (dict "N" . "P" $)}}{{end}}{{if not .Notes}}<p class="meta hint empty">no notes match these filters</p>{{end}}{{end}} + +{{/* htmx responses: the list plus an out-of-band count update */}} +{{define "notelist-oob"}}<span id="notecount" hx-swap-oob="true">{{len .Notes}}</span>{{template "notelist" .}}{{end}} + +{{define "note-added"}}{{if .File}}<span id="notecount" hx-swap-oob="true">{{len .File.Notes}}</span>{{end}}{{range .Notes}}{{template "note" (dict "N" . "P" $)}}{{end}}{{end}} + +{{/* A child-note form appears below every full card in a focused thread. It + deliberately uses a normal POST: one append and one redirect rebuild the + entire DAG from the log, including shared mention paths. */}} +{{define "replyform"}}{{$n := .N}}{{$p := .P}} +<details class="replybox"> + <summary>reply to #{{$n.ID}}</summary> + <form class="notform replyform" method="post" action="{{$p.Href "notes"}}"> + <input type="hidden" name="reply_to" value="{{$n.ID}}"> + <input type="hidden" name="rev" value="{{$p.Rev}}"> + <input type="hidden" name="change" value="{{$p.ChangeID}}"> + <input type="hidden" name="scope" value="all"> + <input type="hidden" name="back" value="{{$p.Href "note" (printf "%d" $p.Note.ID)}}#discussion"> + <textarea name="text" rows="2" placeholder="reply… (⌘/ctrl+enter to post)" aria-label="reply to note {{$n.ID}}" required></textarea> + <div class="row end"> + <span class="meta">as <b>{{$p.User}}</b> at <code title="{{$p.ChangeID}}">{{short $p.ChangeID}}</code> → the log</span> + <button type="submit">reply</button> + </div> + </form> +</details> +{{end}} + +{{/* Recursive at arbitrary depth. A DAG join/cycle is a reference rather than + a second card, which keeps ids unique and recursion finite. */}} +{{define "threadnode"}}{{$x := .Node}}{{$p := .P}} +<div class="threadnode via-{{$x.Via}}"> + <div class="threadedge" aria-label="{{$x.Via}}"><span>{{if eq $x.Via "reply"}}↳{{else}}↶{{end}}</span></div> + <div class="threadcontent"> + {{if $x.Reference}} + <p class="threadref meta">{{$x.Via}} also reaches <a href="{{$p.Href "note" (printf "%d" $x.Note.ID)}}">note #{{$x.Note.ID}}</a></p> + {{else}} + {{template "note" (dict "N" $x.Note "P" $p)}} + {{if $p.Live}}{{template "replyform" (dict "N" $x.Note "P" $p)}}{{end}} + {{if $x.Children}}<div class="threadchildren">{{range $x.Children}}{{template "threadnode" (dict "Node" . "P" $p)}}{{end}}</div>{{end}} + {{end}} + </div> +</div> +{{end}} + +{{/* the add-a-comment form; live pages only, since it writes to the log */}} +{{define "noteform"}} +<form class="notform" hx-post="{{.Href "notes"}}" hx-target="#notelist" hx-swap="afterbegin" + hx-on::after-request="if(event.detail.successful){this.reset();{{if eq .Kind "notes"}}htmx.trigger('#notefilters','change');{{end}}}" + method="post" action="{{.Href "notes"}}"> + <input type="hidden" name="rev" value="{{.Rev}}"> + <input type="hidden" name="change" value="{{.ChangeID}}"> + <input type="hidden" name="scope" value="{{.Scope}}"> + <input type="hidden" name="back" value="{{if .File}}{{.Href "code" .File.Path}}{{else}}{{.Href "notes"}}{{end}}"> + <div class="row"> + {{if .File}} + <input type="hidden" name="file" value="{{.File.Path}}"> + <span class="meta on">on <code>{{base .File.Path}}</code></span> + {{else}} + <input type="search" name="file" placeholder="file (optional)" list="filelist" autocomplete="off"> + {{end}} + <input type="number" id="nstart" name="start" min="1" placeholder="from" aria-label="first line"> + <input type="number" id="nend" name="end" min="1" placeholder="to" aria-label="last line"> + <input type="text" name="kind" placeholder="kind" aria-label="kind" list="kindlist" size="6"> + </div> + <textarea name="text" rows="3" placeholder="comment… (⌘/ctrl+enter to post)" required></textarea> + <div class="row end"> + <span class="meta">as <b>{{.User}}</b> at <code title="{{.ChangeID}}">{{short .ChangeID}}</code> → the log</span> + <button type="submit">add note</button> + </div> +</form> +<datalist id="kindlist">{{range .Facets.Kinds}}<option value="{{.}}">{{end}}</datalist> +{{end}} diff --git a/web/templates/layout.tmpl b/web/templates/layout.tmpl new file mode 100644 index 0000000..969cae6 --- /dev/null +++ b/web/templates/layout.tmpl @@ -0,0 +1,94 @@ +<!doctype html> +<html lang="en"{{if .Live}} data-live="1"{{end}}> +<head> +<meta charset="utf-8"> +<meta name="viewport" content="width=device-width, initial-scale=1"> +<title>{{.Title}}</title> +<link rel="icon" type="image/svg+xml" href="{{.Href "asset" "bemtevi.svg"}}"> +<link rel="stylesheet" href="{{.Href "asset" "style.css"}}"> +<script> +// the theme is worn before the first paint. A theme that is not one of the +// two the site was built with lives in themes.css, so pull that in too — +// from here, after style.css, so its :root block is the one that wins. +{const d = document.documentElement, t = localStorage.getItem("notevi-theme"); + if (t && t !== "system") d.dataset.theme = t; + if (t && !/^(system|dark|light)$/.test(t)) { + const l = document.createElement("link"); + l.rel = "stylesheet"; l.id = "themescss"; l.href = "{{.Href "asset" "themes.css"}}"; + document.head.append(l); + } + d.dataset.mode = localStorage.getItem("notevi-mode") || "trace"; + d.dataset.files = localStorage.getItem("notevi-files-hidden") === "1" ? "hidden" : "shown";} +</script> +{{if .Live}}<script src="{{.Href "asset" "htmx.min.js"}}"></script>{{end}} +<script src="{{.Href "asset" "app.js"}}" defer></script> +</head> +<body{{if eq .Kind "file"}} class="with-aside"{{end}} data-kind="{{.Kind}}"> + +<nav aria-label="repository files" id="nav" data-root="{{.Root}}" data-current="{{.Current}}" data-tree="{{.Href "tree"}}"> + <header> + <a class="brand" href="{{.Href ""}}"><img class="mark" src="{{.Href "asset" "bemtevi.svg"}}" alt="" width="20" height="20">{{.Site.Title}}</a> + <div class="modes" role="group" aria-label="focus"> + <button type="button" class="mode" data-mode="trace" title="reading coverage (t)">trace</button> + <button type="button" class="mode" data-mode="notes" title="notes and comments (t)">notes</button> + </div> + </header> + {{template "changebar" .}} + {{if .Live}} + <div id="activity" class="activity" hx-get="{{.Href "activity"}}?compact=1" hx-trigger="load, every 3s" hx-swap="innerHTML"></div> + {{end}} + <button type="button" id="filetoggle" aria-controls="filelist" aria-expanded="true">hide files</button> + <div id="filelist"> + <input id="filefind" class="find" type="search" placeholder="find file…" aria-label="find file" autocomplete="off" spellcheck="false"> + <div id="tree"><p class="meta hint">loading tree…</p></div> + </div> + <footer> + <span> + {{if and .Live (ne .Root "/")}}<a href="/">projects</a> · {{end}} + <a href="{{.Href "notes"}}">notes ({{len .Site.Notes}})</a> · + <a href="{{.Href "files"}}">files</a>{{if .Live}} · + <a href="{{.Href "jj"}}">jj</a>{{end}} + </span> + <div class="themepick" id="themepick" + data-js="{{.Href "asset" "themes.js"}}" data-css="{{.Href "asset" "themes.css"}}" + data-dark="{{.Site.Theme.Name}}" data-light="{{.Site.Light.Name}}" + data-darkid="{{.Site.Theme.ID}}" data-lightid="{{.Site.Light.ID}}"> + <button type="button" id="themebtn" aria-haspopup="listbox" aria-expanded="false" + title="theme — every one installed here (T)">theme</button> + <div class="thememenu" id="thememenu" hidden> + <input id="themefind" type="search" placeholder="filter themes…" aria-label="filter themes" + role="combobox" aria-controls="themelist" aria-autocomplete="list" + autocomplete="off" spellcheck="false"> + <ul id="themelist" role="listbox" aria-label="themes"></ul> + <p class="meta hint">↑↓ preview · enter keeps · esc puts it back</p> + </div> + </div> + </footer> +</nav> + +<main> +{{if .Err}}<p class="err">{{.Err}}</p>{{end}} +{{if eq .Kind "file"}}{{template "page-file" .}} +{{else if eq .Kind "notes"}}{{template "page-notes" .}} +{{else if eq .Kind "note"}}{{template "page-note" .}} +{{else if eq .Kind "files"}}{{template "page-files" .}} +{{else if eq .Kind "jj"}}{{template "page-jj" .}} +{{else if eq .Kind "change"}}{{template "page-change" .}} +{{else if eq .Kind "session"}}{{template "page-session" .}} +{{else}}{{template "page-index" .}}{{end}} +</main> + +{{if eq .Kind "file"}} +<aside aria-label="notes" class="notes-only"> + <header class="asidehead"> + <b>Notes (<span id="notecount">{{len .File.Notes}}</span>)</b> + {{if .Live}}<span class="meta">click a line to attach</span>{{end}} + </header> + {{if .Live}}{{template "noteform" .}}{{end}} + <div id="notelist">{{range .File.Notes}}{{template "note" (dict "N" . "P" $)}}{{end}}</div> + {{if not .File.Notes}}<p class="meta hint">no notes on this file yet</p>{{end}} +</aside> +{{end}} + +</body> +</html> diff --git a/web/templates/page-change.tmpl b/web/templates/page-change.tmpl new file mode 100644 index 0000000..8641da7 --- /dev/null +++ b/web/templates/page-change.tmpl @@ -0,0 +1,38 @@ +{{define "page-change"}} +{{$c := .Change}} +{{$p := .}} +<header class="filehead"> + <h1>{{$c.Row.Short}} <span class="meta">{{$c.Row.Flags}}</span></h1> + <p class="meta"> + commit <code>{{$c.Row.CommitShort}}</code> · {{$c.Row.Author}} · {{$c.Row.When}} + {{if $c.Row.Refs}} · <span class="refs">{{$c.Row.Refs}}</span>{{end}} · + <a href="{{.Href "files" }}">browse the tree here</a> + </p> +</header> + +<section> + {{if $c.Desc}}<pre class="desc">{{$c.Desc}}</pre>{{else}}<p class="meta hint">(no description set)</p>{{end}} + + {{if $c.Parents}} + <p class="meta">parents: + {{range $c.Parents}}<a href="{{$p.Href "change" .ID}}"><code>{{.Short}}</code></a> {{.Desc}} {{end}} + </p> + {{end}} + + <h2>Changed files <span class="meta">{{$c.Stat}}</span></h2> + {{if $c.Files}} + <table class="changed"> + <tbody> + {{range $c.Files}} + <tr><td class="st st-{{.Status}}">{{.Status}}</td> + <td><a href="{{$p.Href "code" .Path}}">{{.Path}}</a></td></tr> + {{end}} + </tbody> + </table> + {{else}}<p class="meta hint">no file changes</p>{{end}} + + <h2>Notes recorded at this change <span class="meta">{{len .Notes}}</span></h2> + <div class="notecols">{{range .Notes}}{{template "note" (dict "N" . "P" $)}}{{end}}</div> + {{if not .Notes}}<p class="meta hint">nothing in the log was written while this change was checked out</p>{{end}} +</section> +{{end}} diff --git a/web/templates/page-file.tmpl b/web/templates/page-file.tmpl new file mode 100644 index 0000000..39a8c44 --- /dev/null +++ b/web/templates/page-file.tmpl @@ -0,0 +1,20 @@ +{{define "page-file"}} +<header class="filehead"> + <h1>{{.File.Path}}</h1> + <p class="meta"> + {{if .File.Traced}} + {{range .Site.Agents}}{{if band $.File.Mask .Bit}}<span class="chip am{{.Bit}}">{{.Short}}</span> {{end}}{{end}} + <span class="trace-only"><data value="{{.File.Pct}}">{{.File.Pct}}% read</data> · + {{.File.Reads}} reads · {{.File.Greps}} greps · </span> + <span class="notes-only">{{len .File.Notes}} note{{if ne (len .File.Notes) 1}}s{{end}} · </span> + {{else}}not traced · {{end}}change + {{if .Live}}<a href="{{.Href "change" .File.Change}}"><code>{{short .File.Change}}</code></a>{{else}}<code>{{short .File.Change}}</code>{{end}} + </p> + {{if .File.Patterns}}<p class="meta greps trace-only">grepped: {{range .File.Patterns}}<code>{{.}}</code> {{end}}</p>{{end}} +</header> +{{if .File.Stub}} +<p class="meta stub">{{.File.Stub}}</p> +{{else}} +<div class="codewrap">{{.File.Body}}</div> +{{end}} +{{end}} diff --git a/web/templates/page-files.tmpl b/web/templates/page-files.tmpl new file mode 100644 index 0000000..3f158fe --- /dev/null +++ b/web/templates/page-files.tmpl @@ -0,0 +1,13 @@ +{{define "page-files"}} +<header class="filehead"> + <h1>Files</h1> + <p class="meta"> + everything at change <code title="{{.ChangeID}}">{{short .ChangeID}}</code> · + <span class="trace-only">traced files carry a coverage bar{{if eq .Scope "change"}}, from reads at this change{{end}}</span> + <span class="notes-only">◆ marks files with notes</span> + </p> +</header> +<section class="filetree"> +{{.Tree}} +</section> +{{end}} diff --git a/web/templates/page-index.tmpl b/web/templates/page-index.tmpl new file mode 100644 index 0000000..93cad6b --- /dev/null +++ b/web/templates/page-index.tmpl @@ -0,0 +1,56 @@ +{{define "page-index"}} +<header class="filehead"> + <h1>{{.Site.Title}}</h1> + <p class="meta"> + {{len .Files}} files at <code title="{{.ChangeID}}">{{short .ChangeID}}</code> · + {{len .Site.Order}} traced, {{len .Site.Notes}} notes + {{if or (eq .Scope "all") .ScopeEmpty}}<span class="away">across every change</span>{{else}}here{{end}} · + theme {{.Site.Theme.Name}} + </p> +</header> + +{{if .Live}} +<section> + <h2>Live <span class="meta">— agents reading this codebase</span></h2> + <div id="activity-full" hx-get="{{.Href "activity"}}" hx-trigger="load, every 3s" hx-swap="innerHTML"> + <p class="meta hint">…</p> + </div> +</section> +{{end}} + +<section class="trace-only"> + <h2>Agents</h2> + <table> + <thead><tr><th>agent</th><th>model</th><th>effort</th><th>session</th><th>reads</th><th>greps</th><th>notes</th></tr></thead> + <tbody> + {{range .Site.Agents}} + <tr><td><span class="chip am{{.Bit}}">{{.Short}}</span></td> + <td>{{.Model}}</td><td>{{.Reason}}</td> + <td>{{if and $.Live .Session}}<a href="{{$.Href "session" .Session}}" title="{{.Session}}"><code>{{short .Session}}</code></a> + {{else}}<code title="{{.Session}}">{{short .Session}}</code>{{end}}</td> + <td>{{.Reads}}</td><td>{{.Greps}}</td><td>{{.Notes}}</td></tr> + {{end}} + </tbody> + </table> +</section> + +<section class="trace-only"> + <h2>Coverage</h2> + <table> + <thead><tr><th>file</th><th>read</th><th>lines</th><th>notes</th></tr></thead> + <tbody> + {{range .Site.Order}}{{with index $.Site.Files .}} + <tr><td><a href="{{$.Href "code" .Path}}">{{.Path}}</a></td> + <td><data class="bar am{{.Mask}}" value="{{.Pct}}" style="--pct:{{.Pct}}%">{{.Pct}}%</data></td> + <td>{{.Covered}}/{{.Total}}</td><td>{{len .Notes}}</td></tr> + {{end}}{{end}} + </tbody> + </table> +</section> + +<section class="notes-only"> + <h2>Latest notes <span class="meta">— <a href="{{.Href "notes"}}">all {{len .Site.Notes}}, with filters</a></span></h2> + <div class="notecols">{{range .Notes}}{{template "note" (dict "N" . "P" $)}}{{end}}</div> + {{if not .Notes}}<p class="meta hint">no notes in the log yet</p>{{end}} +</section> +{{end}} diff --git a/web/templates/page-jj.tmpl b/web/templates/page-jj.tmpl new file mode 100644 index 0000000..24df596 --- /dev/null +++ b/web/templates/page-jj.tmpl @@ -0,0 +1,25 @@ +{{define "page-jj"}} +<header class="filehead"> + <h1>jj</h1> + <p class="meta"> + read-only queries against the repo — <code>--ignore-working-copy</code>, inline templates, nothing written to disk + </p> +</header> + +<section class="jjpage"> + <form class="jjform" method="get" action="{{.Href "jj"}}" + hx-get="{{.Href "jj-log"}}" hx-target="#jjout" hx-swap="innerHTML" hx-indicator="#jjbusy"> + <input type="hidden" name="kind" value="log"> + <input type="search" name="revset" value="{{.JJ.Revset}}" placeholder="revset — e.g. @ | ancestors(trunk(), 10) | description(glob:'*fix*')" autocomplete="off" spellcheck="false"> + <input type="number" name="limit" value="{{.JJ.Limit}}" min="1" max="1000" aria-label="limit" title="limit"> + <button type="submit">jj log</button> + <button type="button" hx-get="{{.Href "jj-op"}}" hx-target="#jjout" hx-include="closest form" hx-indicator="#jjbusy" title="operation log">op log</button> + <span id="jjbusy" class="busy">·</span> + </form> + <p class="meta hint"> + change ids open the change · descriptions browse the tree at that change · + op ids re-run the query <code>--at-operation</code>, which is how you see the repo as it was + </p> + <div id="jjout">{{template "jjrows" .JJ}}</div> +</section> +{{end}} diff --git a/web/templates/page-note.tmpl b/web/templates/page-note.tmpl new file mode 100644 index 0000000..8cd0e64 --- /dev/null +++ b/web/templates/page-note.tmpl @@ -0,0 +1,54 @@ +{{/* One note, on its own — the page a shared permalink opens. + + It has to stand up for a reader who has never seen this site: what was + said, about which lines of which file, at which change, and the code + itself, right there. Everything else on the page is a way further in. */}} +{{define "page-note"}} +{{$n := .Note}} +<header class="filehead"> + <h1>{{if $n.File}}{{base $n.File}}<span class="lns">{{lines $n}}</span>{{else}}Note{{end}}</h1> + <p class="meta"> + note <b>#{{$n.ID}}</b> by <b>{{$n.Agent.Short}}</b>{{if $n.Kind}} · <em class="kind">{{$n.Kind}}</em>{{end}} + {{if not $n.At.IsZero}} · <time datetime="{{$n.At.Format "2006-01-02T15:04:05Z07:00"}}">{{$n.When}}</time> + <span class="ago">({{$n.Ago}})</span>{{end}} + {{if $n.Change}} · read at + {{if .Live}}<a href="{{.Href "change" $n.Change}}"><code>{{short $n.Change}}</code></a> + {{else}}<code title="{{$n.Change}}">{{short $n.Change}}</code>{{end}} + {{end}} + </p> + {{if ne $n.File (base $n.File)}}<p class="meta"><code>{{$n.File}}</code></p>{{end}} +</header> + +<section class="notepage"> + <div class="onenote">{{template "note" (dict "N" $n "P" $)}}</div> + + {{$open := .HasCode $n.File}} + {{if .Excerpt}} + <p class="meta exhead">lines {{.ExFrom}}–{{.ExTo}} of <code>{{$n.File}}</code>{{if $open}} · + <a href="{{.NoteHref $n}}">open the whole file →</a>{{end}}</p> + <div class="codewrap excerpt">{{.Excerpt}}</div> + {{else if .ExErr}} + <p class="meta stub">{{.ExErr}}</p> + {{else if $n.File}} + <p class="meta hint">this note is about the whole file{{if $open}} — + <a href="{{.NoteHref $n}}">open <code>{{base $n.File}}</code> →</a>{{end}}</p> + {{else}} + <p class="meta hint">this note is not pinned to a file</p> + {{end}} + + {{if .Live}}{{template "replyform" (dict "N" $n "P" $)}}{{end}} + + <section class="discussion" id="discussion"> + <h2>Replies & mentions + <span class="meta">{{len $n.Replies}} repl{{if eq (len $n.Replies) 1}}y{{else}}ies{{end}} · {{len $n.Mentions}} mention{{if ne (len $n.Mentions) 1}}s{{end}}</span> + </h2> + {{if .Thread.Children}} + <div class="threadchildren rootchildren">{{range .Thread.Children}}{{template "threadnode" (dict "Node" . "P" $)}}{{end}}</div> + {{else}} + <p class="meta hint">no notes reply to or mention this one yet</p> + {{end}} + </section> + + <p class="meta more"><a href="{{.Href "notes"}}">← every note in the log</a></p> +</section> +{{end}} diff --git a/web/templates/page-notes.tmpl b/web/templates/page-notes.tmpl new file mode 100644 index 0000000..ebd5865 --- /dev/null +++ b/web/templates/page-notes.tmpl @@ -0,0 +1,52 @@ +{{define "facet"}}<select name="{{.Name}}" aria-label="{{.Label}}"> + <option value="">{{.Label}}</option> + {{range .Values}}<option value="{{.}}"{{if eq . $.Sel}} selected{{end}}>{{if $.Short}}{{short .}}…{{else}}{{.}}{{end}}</option> + {{end}}</select>{{end}} + +{{define "page-notes"}} +<header class="filehead"> + <h1>Notes</h1> + <p class="meta"> + {{if eq .Scope "all"}} + all {{.Site.NotesTotal}} in the log, every change + {{else if .ScopeEmpty}} + all {{.Site.NotesTotal}} in the log — nothing was recorded at <code>{{short .ChangeID}}</code> + {{else}} + {{len .Site.Notes}} written at <code title="{{.ChangeID}}">{{short .ChangeID}}</code>{{if .Elsewhere}} · + {{if .Live}}<a href="{{.ScopeHref "all"}}">{{.Elsewhere}} more at other changes</a> + {{else}}{{.Elsewhere}} more at other changes are not in this export{{end}}{{end}} + {{end}} + {{if .Live}} · anything you add here is appended to the private log sidecar at this change — the project working copy is never touched{{end}} + </p> +</header> + +<section class="notespage"> + {{if .Live}} + <details class="addnote"> + <summary>add a note</summary> + {{template "noteform" .}} + </details> + {{end}} + + <form class="filters" id="notefilters" method="get" action="{{.Href "notes"}}" + {{if .Live}}hx-get="{{.Href "notes-list"}}" hx-target="#notelist" hx-swap="innerHTML" + hx-trigger="input delay:250ms, change, search" hx-indicator="#notesbusy"{{end}}> + <input type="search" name="text" value="{{.Filter.Text}}" placeholder="search note text…" autocomplete="off"> + <input type="search" name="file" value="{{.Filter.File}}" placeholder="file path…" list="filelist" autocomplete="off"> + {{template "facet" (dict "Name" "agent" "Label" "any agent" "Values" .Facets.Agents "Sel" .Filter.Agent)}} + {{template "facet" (dict "Name" "model" "Label" "any model" "Values" .Facets.Models "Sel" .Filter.Model)}} + {{template "facet" (dict "Name" "session" "Label" "any session" "Values" .Facets.Sessions "Sel" .Filter.Session "Short" true)}} + {{template "facet" (dict "Name" "kind" "Label" "any kind" "Values" .Facets.Kinds "Sel" .Filter.Kind)}} + <span class="dates"> + <label class="datef">from <input type="date" name="from" value="{{.Filter.From}}"></label> + <label class="datef">to <input type="date" name="to" value="{{.Filter.To}}"></label> + </span> + <button type="submit" class="nohx">filter</button> + <button type="button" id="clearfilters">clear</button> + </form> + <datalist id="filelist">{{range .Facets.Files}}<option value="{{.}}">{{end}}</datalist> + + <p class="meta count"><span id="notesbusy" class="busy">·</span><span id="notecount">{{len .Notes}}</span> notes shown</p> + <div id="notelist">{{template "notelist" .}}</div> +</section> +{{end}} diff --git a/web/templates/page-session.tmpl b/web/templates/page-session.tmpl new file mode 100644 index 0000000..1155b67 --- /dev/null +++ b/web/templates/page-session.tmpl @@ -0,0 +1,70 @@ +{{/* One session's conversation, with its notevi log woven in by time. */}} +{{define "page-session"}} +{{$c := .Conv}} +<header class="filehead"> + <h1> + {{if $c.Agent}}<span class="chip am{{$c.Bit}}">{{$c.Agent}}</span> {{end}} + <code title="{{$c.Session}}">{{short $c.Session}}</code> + </h1> + <p class="meta"> + {{if $c.Model}}{{$c.Model}} · {{end}}{{$c.Reads}} reads · {{$c.Greps}} greps · {{$c.Notes}} notes + {{if $c.Dir}} · <span title="{{$c.Dir}}">{{base $c.Dir}}</span>{{end}} + {{if $c.Harness}} · {{$c.Harness}}{{end}} + </p> + {{if $c.Path}} + <p class="meta"><code>{{$c.Path}}</code></p> + {{else}} + <p class="meta hint">no transcript found for this session — searched + {{if $c.Roots}}{{range $i, $r := $c.Roots}}{{if $i}}, {{end}}<code>{{$r}}</code>{{end}}{{else}}nowhere: <code>-transcripts</code> is empty{{end}} · + showing the notevi log alone</p> + {{end}} + {{if $c.Err}}<p class="err">{{$c.Err}}</p>{{end}} +</header> + +<section class="convpage"> + {{if $c.Windowed}} + <p class="meta"> + moments {{$c.From}}–{{$c.To}} of {{$c.Total}}{{if $c.Anchor}}, around the note{{end}} · + {{if $c.Incomplete}}the rest is beyond what one page renders{{else}}<a href="{{$c.AllHref}}">show the whole conversation</a>{{end}} + </p> + {{end}} + + <div class="conv" data-anchor="{{$c.Anchor}}"> + {{range $c.Turns}} + {{if .Note}} + <div class="turn t-note{{if .Here}} here{{end}}"> + <span class="role">note</span><time>{{.Clock}}</time> + {{if .Note.File}} + <div class="notewrap" data-href="{{$.NoteHref .Note}}" tabindex="0" role="link" + title="open this note on the code it is about">{{template "note" (dict "N" .Note "P" $)}}</div> + {{else}} + <div class="notewrap">{{template "note" (dict "N" .Note "P" $)}}</div> + {{end}} + </div> + {{else if eq .Role "notevi"}} + <div class="turn t-notevi"> + <span class="role">notevi</span><time>{{.Clock}}</time> + {{if .File}}<a class="what" href="{{$.Href "code" .File}}">{{.Text}}</a> + {{else}}<span class="what">{{.Text}}</span>{{end}} + </div> + {{else if eq .Role "tool"}} + <div class="turn t-tool"> + <span class="role">{{.Tool}}</span><time>{{.Clock}}</time> + <code class="what">{{.Detail}}</code> + </div> + {{else if eq .Role "result"}} + <div class="turn t-result{{if eq .Kind "error"}} bad{{end}}"> + <span class="role">→{{if .Tool}} {{.Tool}}{{end}}</span><time></time> + <code class="what">{{.Detail}}</code> + </div> + {{else}} + <div class="turn t-say t-{{.Role}}"> + <span class="role">{{.Role}}</span><time>{{.Clock}}</time> + <p>{{.Text}}</p> + </div> + {{end}} + {{end}} + {{if not $c.Turns}}<p class="meta hint">nothing recorded for this session</p>{{end}} + </div> +</section> +{{end}} diff --git a/web/templates/projects.tmpl b/web/templates/projects.tmpl new file mode 100644 index 0000000..ce75454 --- /dev/null +++ b/web/templates/projects.tmpl @@ -0,0 +1,113 @@ +{{define "projects"}}<!doctype html> +<html lang="en" data-live="1"> +<head> +<meta charset="utf-8"> +<meta name="viewport" content="width=device-width, initial-scale=1"> +<title>{{.Title}}</title> +<link rel="icon" type="image/svg+xml" href="/bemtevi.svg"> +<link rel="stylesheet" href="/style.css"> +<script> +// Match project pages: wear the saved theme before first paint, and load the +// installed-theme stylesheet now only when that saved choice requires it. +{const d = document.documentElement, t = localStorage.getItem("notevi-theme"); + if (t && t !== "system") d.dataset.theme = t; + if (t && !/^(system|dark|light)$/.test(t)) { + const l = document.createElement("link"); + l.rel = "stylesheet"; l.id = "themescss"; l.href = "/themes.css"; + document.head.append(l); + } + d.dataset.mode = localStorage.getItem("notevi-mode") || "trace";} +</script> +<script src="/app.js" defer></script> +</head> +<body class="projects"> +<nav aria-label="projects" id="nav"> + <header><a class="brand" href="/"><img class="mark" src="/bemtevi.svg" alt="" width="20" height="20">{{.Title}}</a></header> + <p class="meta">one process · every local notevi sidecar</p> + <input id="projectfind" class="find" type="search" placeholder="find project…" aria-label="find project" autocomplete="off" spellcheck="false"> + <form method="post" action="/projects/refresh" class="project-refresh"> + <button type="submit">refresh repositories</button> + </form> + <p class="meta">scans <code>{{.ScanRoot}}</code></p> + <p class="meta">last refresh {{.Scanned}}</p> + <footer> + <span>selection and scan results stay in memory</span> + <div class="themepick" id="themepick" + data-js="/themes.js" data-css="/themes.css" + data-dark="{{.Theme.Name}}" data-light="{{.Light.Name}}" + data-darkid="{{.Theme.ID}}" data-lightid="{{.Light.ID}}"> + <button type="button" id="themebtn" aria-haspopup="listbox" aria-expanded="false" + title="theme — every one installed here (T)">theme</button> + <div class="thememenu" id="thememenu" hidden> + <input id="themefind" type="search" placeholder="filter themes…" aria-label="filter themes" + role="combobox" aria-controls="themelist" aria-autocomplete="list" + autocomplete="off" spellcheck="false"> + <ul id="themelist" role="listbox" aria-label="themes"></ul> + <p class="meta hint">↑↓ preview · enter keeps · esc puts it back</p> + </div> + </div> + </footer> +</nav> + +<main class="projects-main"> + <header class="filehead"> + <h1>Projects</h1> + <p class="meta">Choose a notevi log, start one in a jj repository, or colocate jj with an existing Git repository.</p> + </header> + {{if .Message}}<p class="ok project-message">{{.Message}}</p>{{end}} + {{if .Err}}<p class="err project-message">{{.Err}}</p>{{end}} + + <section> + <h2>Logs <span class="meta">— {{len .Active}} repositories with a private sidecar</span></h2> + <div class="project-grid"> + {{range .Active}} + <article class="project-card" data-project="{{.Name}} {{.Relative}}"> + <header><h3><a href="/p/{{.ID}}/">{{.Name}}</a></h3><span class="project-state active">log</span></header> + <p class="project-path" title="{{.Path}}"><code>{{.Relative}}</code></p> + <p class="meta">{{.Entries}} entries · {{.Notes}} notes · {{.Agents}} agents · {{.Updated}}</p> + {{if gt (len .Workspaces) 1}}<p class="meta">{{len .Workspaces}} jj workspaces share this log</p>{{end}} + {{if .Err}}<p class="err">{{.Err}}</p>{{end}} + <a class="project-action" href="/p/{{.ID}}/">open project</a> + </article> + {{end}} + {{if not .Active}}<p class="meta hint">no notevi sidecars found yet</p>{{end}} + </div> + </section> + + <section> + <h2>Ready to start <span class="meta">— {{len .Ready}} jj repositories without a notevi sidecar</span></h2> + <div class="project-grid"> + {{range .Ready}} + <article class="project-card" data-project="{{.Name}} {{.Relative}}"> + <header><h3>{{.Name}}</h3><span class="project-state">jj</span></header> + <p class="project-path" title="{{.Path}}"><code>{{.Relative}}</code></p> + {{if gt (len .Workspaces) 1}}<p class="meta">{{len .Workspaces}} workspaces</p>{{end}} + {{if .Err}}<p class="err">{{.Err}}</p>{{end}} + <form method="post" action="/projects/{{.ID}}/start"> + <button type="submit">start private sidecar</button> + </form> + </article> + {{end}} + {{if not .Ready}}<p class="meta hint">every detected jj repository already has a sidecar</p>{{end}} + </div> + </section> + + <section> + <h2>Git repositories <span class="meta">— {{len .Git}} without jj metadata</span></h2> + <p class="meta">Initializing adds colocated <code>.jj</code> metadata; it does not create a sidecar until you choose “start private sidecar”.</p> + <div class="project-grid"> + {{range .Git}} + <article class="project-card" data-project="{{.Name}} {{.Relative}}"> + <header><h3>{{.Name}}</h3><span class="project-state git">git</span></header> + <p class="project-path" title="{{.Path}}"><code>{{.Relative}}</code></p> + <form method="post" action="/git/{{.ID}}/init"> + <button type="submit">initialize colocated jj</button> + </form> + </article> + {{end}} + {{if not .Git}}<p class="meta hint">no Git-only repositories detected</p>{{end}} + </div> + </section> +</main> +</body> +</html>{{end}} diff --git a/web/theme.go b/web/theme.go new file mode 100644 index 0000000..135af43 --- /dev/null +++ b/web/theme.go @@ -0,0 +1,341 @@ +// theme.go — Zed theme JSON in, CSS custom properties out. Per-agent colors +// come from the theme's player (collaborator) palette. +// +// The two themes named on the command line are what the site is built with; +// themes.go finds the rest of this machine's themes for the picker, and they +// arrive here as the same *Theme. +package web + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "sort" + "strings" +) + +type SyntaxStyle struct { + Color string `json:"color"` + FontStyle *string `json:"font_style"` + FontWeight *float64 `json:"font_weight"` +} + +type Theme struct { + ID, Source string // "zed/one-dark", "zed" | "helix" + Name, Appearance string + Bg, Fg, Panel, Border, LineNo, Muted, Accent string + Note, Hover string + Syntax map[string]SyntaxStyle + Players []string +} + +// defaultTheme finds a zed theme file containing a theme of the wanted +// appearance; "" means fall back to the embedded One family. +func defaultTheme(appearance string) string { + for _, path := range globAll(zedThemeGlobs()) { + b, err := os.ReadFile(path) + if err != nil { + continue + } + fam, err := parseZedFamily(b) + if err != nil { + continue + } + for _, t := range fam { + if t.Appearance == appearance { + return path + } + } + } + return "" +} + +func loadTheme(path, name, appearance string) *Theme { + var b []byte + var err error + if path == "" { + b, err = tfs.ReadFile("assets/one.json") + } else { + b, err = os.ReadFile(path) + } + if err != nil { + fatal("%v", err) + } + fam, err := parseZedFamily(b) + if err != nil { + fatal("bad zed theme %s: %v", path, err) + } + t := fam[0] + if name != "" { + for _, c := range fam { + if c.Name == name { + t = c + } + } + } else { + for _, c := range fam { + if c.Appearance == appearance { + t = c + break + } + } + } + return t +} + +// parseZedFamily reads a zed theme file: one file is a family, and every theme +// in it is one the picker can offer. +func parseZedFamily(b []byte) ([]*Theme, error) { + var family struct { + Name string `json:"name"` + Themes []struct { + Name string `json:"name"` + Appearance string `json:"appearance"` + Style map[string]json.RawMessage `json:"style"` + } `json:"themes"` + } + if err := json.Unmarshal(b, &family); err != nil { + return nil, err + } + if len(family.Themes) == 0 { + return nil, errors.New("no themes in it") + } + var out []*Theme + for _, th := range family.Themes { + get := func(keys ...string) string { + for _, k := range keys { + var s string + if raw, ok := th.Style[k]; ok && json.Unmarshal(raw, &s) == nil && okColor(s) != "" { + return s + } + } + return "" + } + t := &Theme{ID: "zed/" + slug(th.Name), Source: "zed", + Name: th.Name, Appearance: th.Appearance, + Bg: get("editor.background", "background"), + Fg: get("editor.foreground", "text"), + Panel: get("panel.background", "surface.background", "background"), + Border: get("border", "border.variant"), + LineNo: get("editor.line_number"), + Muted: get("text.muted", "text.disabled"), + Accent: get("text.accent", "info"), + Note: get("warning", "conflict", "modified"), + Hover: get("element.hover", "ghost_element.hover"), + } + json.Unmarshal(th.Style["syntax"], &t.Syntax) + for k, s := range t.Syntax { // a theme in the wild does drop the odd "#" + if okColor(s.Color) == "" { + delete(t.Syntax, k) + } + } + t.fill() + var players []struct { + Cursor string `json:"cursor"` + } + json.Unmarshal(th.Style["players"], &players) + var cursors []string + for _, p := range players { + cursors = append(cursors, p.Cursor) + } + t.setPlayers(cursors, t.syntaxColors()) + out = append(out, t) + } + return out, nil +} + +// setPlayers picks the per-agent colors out of the theme's own palette. A zed +// theme has one meant for exactly this — the collaborator cursors — and it is +// asked first; when it runs short, or the theme is a helix one with no such +// palette at all, the code's own colors stand in, since those are what the +// reader is already telling apart on the page. +// +// Within each tier, colors that vanish against fg/bg, collide with the note +// color, or sit on top of one already taken are dropped, and the rest ordered +// greedily for mutual distance, so the first few agents contrast most. +func (t *Theme) setPlayers(tiers ...[]string) { + t.Players = nil + taken := func(c string, of []string) bool { + for _, p := range of { + if colorDist(c, p) <= 60 { + return true + } + } + return false + } + for _, tier := range tiers { + var usable []string + for _, c := range tier { + c = hex6(c) + if len(c) != 7 || taken(c, usable) || taken(c, t.Players) || + colorDist(c, hex6(t.Fg)) <= 60 || colorDist(c, hex6(t.Bg)) <= 60 || + colorDist(c, hex6(t.Note)) <= 60 { + continue + } + usable = append(usable, c) + } + for len(usable) > 0 && len(t.Players) < maxAgents { + best, bestScore := 0, -1 + for i, c := range usable { + score := 1 << 24 // first pick of the first tier: keep theme order + for _, p := range t.Players { + if d := colorDist(c, p); d < score { + score = d + } + } + if score > bestScore { + best, bestScore = i, score + } + } + t.Players = append(t.Players, usable[best]) + usable = append(usable[:best], usable[best+1:]...) + } + } +} + +// fill supplies whatever a theme does not say. Editors leave gaps a web page +// cannot — a zed theme need not name a muted text color, a helix theme has no +// notion of a panel — so every gap is closed with a shade mixed from the +// theme's own background and foreground, or with a color out of its syntax. +// A theme with three colors in it still dresses a whole page. +func (t *Theme) fill() { + bg, fg := hex6(t.Bg), t.Fg + // panel and hover are backgrounds the page writes on, so a theme that + // offers one the text would be lost in does not get to keep it + t.Panel = first(readable(t.Panel, fg, ""), blend(bg, fg, 0.05)) + t.Hover = first(readable(t.Hover, fg, ""), blend(bg, fg, 0.12)) + t.Border = first(t.Border, blend(bg, fg, 0.2)) + t.LineNo = first(t.LineNo, blend(bg, fg, 0.4)) + t.Muted = first(readable(t.Muted, t.Panel, ""), blend(bg, fg, 0.55)) + t.Accent = first(t.Accent, t.syn("function"), t.syn("keyword"), t.syn("type"), fg) + t.Note = first(t.Note, t.syn("warning"), t.syn("number"), t.Accent) +} + +// syn is the theme's color for a syntax key, resolved along its dots. +func (t *Theme) syn(key string) string { + if k := resolveKey(t, key); k != "" { + return t.Syntax[k].Color + } + return "" +} + +// syntaxColors are the theme's own code colors, in the order they stand out +// from one another: what a theme offers when its palette runs short. +func (t *Theme) syntaxColors() []string { + var out []string + for _, k := range []string{"keyword", "function", "string", "type", "constant", + "variable.parameter", "attribute", "constructor", "number", "tag", "property", + "label", "namespace", "operator", "boolean"} { + if c := t.syn(k); c != "" { + out = append(out, c) + } + } + return out +} + +// readable keeps a color only if text in `on` can be seen against it. +func readable(c, on, fallback string) string { + if c == "" || colorDist(hex6(c), hex6(on)) < 2000 { + return fallback + } + return c +} + +// syntaxKeys is every syntax key the site paints, and so every one a theme is +// asked to fill: the union of what the two built-with themes name. +func syntaxKeys(themes ...*Theme) []string { + var keys []string + seen := map[string]bool{} + for _, t := range themes { + for k := range t.Syntax { + if !seen[k] { + seen[k] = true + keys = append(keys, k) + } + } + } + sort.Strings(keys) + return keys +} + +func colorDist(a, b string) int { + var ar, ag, ab, br, bg, bb int + if len(a) != 7 || len(b) != 7 { + return 1 << 24 + } + fmt.Sscanf(a[1:], "%02x%02x%02x", &ar, &ag, &ab) + fmt.Sscanf(b[1:], "%02x%02x%02x", &br, &bg, &bb) + d := func(x, y int) int { return (x - y) * (x - y) } + return int(float64(d(ar, br)+d(ag, bg)+d(ab, bb)) / 3) +} + +var fallbackPalette = []string{"#7aa2f7", "#e0af68", "#9ece6a", "#f7768e", "#bb9af7", "#2ac3de"} + +func (t *Theme) Player(i int) string { + if i < len(t.Players) { + return t.Players[i] + } + return fallbackPalette[i%len(fallbackPalette)] +} + +// okColor keeps a color only if it is one a browser will take: #rgb, #rrggbb +// or #rrggbbaa. Whatever else a theme file says is treated as unsaid, and +// fill() supplies it. +func okColor(c string) string { + if len(c) != 4 && len(c) != 7 && len(c) != 9 || c[0] != '#' { + return "" + } + for _, r := range c[1:] { + if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'f' || r >= 'A' && r <= 'F') { + return "" + } + } + return c +} + +// hex6 strips an alpha channel from #rrggbbaa. +func hex6(c string) string { + if len(c) == 9 && c[0] == '#' { + return c[:7] + } + if len(c) == 4 && c[0] == '#' { // #rgb + return "#" + string([]byte{c[1], c[1], c[2], c[2], c[3], c[3]}) + } + return c +} + +func rgb(c string) (r, g, b int, ok bool) { + c = hex6(c) + if len(c) != 7 || c[0] != '#' { + return 0, 0, 0, false + } + if n, _ := fmt.Sscanf(c[1:], "%02x%02x%02x", &r, &g, &b); n != 3 { + return 0, 0, 0, false + } + return r, g, b, true +} + +// lum is perceived brightness, 0..1 — enough to tell a light theme from a +// dark one when the theme does not say which it is. +func lum(c string) float64 { + r, g, b, ok := rgb(c) + if !ok { + return 0 + } + return (0.299*float64(r) + 0.587*float64(g) + 0.114*float64(b)) / 255 +} + +// blend mixes frac of b into a — for the shades a theme leaves unsaid. +func blend(a, b string, frac float64) string { + ar, ag, ab, ok := rgb(a) + br, bg, bb, ok2 := rgb(b) + if !ok || !ok2 { + return a + } + mix := func(x, y int) int { return int(float64(x) + (float64(y)-float64(x))*frac) } + return fmt.Sprintf("#%02x%02x%02x", mix(ar, br), mix(ag, bg), mix(ab, bb)) +} + +// cssKey is a syntax key as it appears in class and property names. +func cssKey(k string) string { return strings.ReplaceAll(k, ".", "-") } diff --git a/web/themes.go b/web/themes.go new file mode 100644 index 0000000..fd46799 --- /dev/null +++ b/web/themes.go @@ -0,0 +1,445 @@ +// themes.go — the themes this machine already has. Zed keeps families of them +// in JSON, Helix keeps one TOML each with a palette and single inheritance; +// both are read into the same *Theme, so the browser can wear either. +// +// Discovery is best-effort: a theme that will not parse is skipped, never +// fatal. What the site is built with stays what -theme and -light-theme say — +// these only widen what the picker can offer. +package web + +import ( + "bytes" + "os" + "os/exec" + "path/filepath" + "sort" + "strings" + + "github.com/BurntSushi/toml" +) + +// themeSet is those themes plus the two files the browser switches with: one +// CSS block per theme, and the list the picker draws from. +type themeSet struct { + List []*Theme + CSS []byte // themes.css — one :root[data-theme="…"] block per theme + JS []byte // themes.js — window.VRSITE_THEMES, the picker's menu +} + +func newThemeSet(dark, light *Theme) *themeSet { + return themesFrom(discoverThemes(), dark, light) +} + +// themesFrom writes the two files for a given list of themes. The keys the +// site paints with come from the themes it was built with, since those are the +// ones the stylesheet has classes for. +func themesFrom(list []*Theme, dark, light *Theme) *themeSet { + ts := &themeSet{List: list} + keys := syntaxKeys(dark, light) + var css, js bytes.Buffer + writeThemesCSS(&css, ts.List, keys) + writeThemesJS(&js, ts.List) + ts.CSS, ts.JS = css.Bytes(), js.Bytes() + return ts +} + +func (ts *themeSet) count(source string) int { + n := 0 + for _, t := range ts.List { + if t.Source == source { + n++ + } + } + return n +} + +// discoverThemes reads every theme both editors can see, user directories +// first so a theme you installed wins the id over one that merely ships. +func discoverThemes() []*Theme { + var out []*Theme + seen := map[string]bool{} + add := func(t *Theme) { + if t == nil || t.ID == "" || t.Bg == "" || t.Fg == "" || seen[t.ID] { + return + } + seen[t.ID] = true + out = append(out, t) + } + for _, path := range globAll(zedThemeGlobs()) { + b, err := os.ReadFile(path) + if err != nil { + continue + } + fam, err := parseZedFamily(b) + if err != nil { + continue + } + for _, t := range fam { + add(t) + } + } + dirs := helixThemeDirs() + for _, dir := range dirs { + for _, path := range globAll([]string{filepath.Join(dir, "*.toml")}) { + add(loadHelixTheme(path, dirs)) + } + } + sort.Slice(out, func(i, j int) bool { + if out[i].Source != out[j].Source { + return out[i].Source < out[j].Source + } + return strings.ToLower(out[i].Name) < strings.ToLower(out[j].Name) + }) + return out +} + +func globAll(pats []string) []string { + var out []string + for _, p := range pats { + m, _ := filepath.Glob(p) + sort.Strings(m) + out = append(out, m...) + } + return out +} + +func configHome() string { + if d := os.Getenv("XDG_CONFIG_HOME"); d != "" { + return d + } + home, _ := os.UserHomeDir() + return filepath.Join(home, ".config") +} + +func dataHome() string { + if d := os.Getenv("XDG_DATA_HOME"); d != "" { + return d + } + home, _ := os.UserHomeDir() + return filepath.Join(home, ".local", "share") +} + +// zedThemeGlobs: themes you dropped in yourself, then the ones extensions +// brought. Zed's own built-ins live inside the binary, so they are not here. +func zedThemeGlobs() []string { + home, _ := os.UserHomeDir() + mac := filepath.Join(home, "Library", "Application Support", "Zed") + return []string{ + filepath.Join(configHome(), "zed", "themes", "*.json"), + filepath.Join(mac, "themes", "*.json"), + filepath.Join(dataHome(), "zed", "extensions", "installed", "*", "themes", "*.json"), + filepath.Join(mac, "extensions", "installed", "*", "themes", "*.json"), + } +} + +// helixThemeDirs: yours first, then whichever runtime the installed hx uses — +// found the way helix itself looks, by walking out from the binary. +func helixThemeDirs() []string { + home, _ := os.UserHomeDir() + dirs := []string{filepath.Join(configHome(), "helix", "themes")} + var runtimes []string + if r := os.Getenv("HELIX_RUNTIME"); r != "" { + runtimes = append(runtimes, r) + } + runtimes = append(runtimes, + filepath.Join(configHome(), "helix", "runtime"), + filepath.Join(dataHome(), "helix", "runtime")) + if bin, err := exec.LookPath("hx"); err == nil { + if bin, err = filepath.EvalSymlinks(bin); err == nil { + dir := filepath.Dir(bin) + runtimes = append(runtimes, + filepath.Join(dir, "runtime"), + filepath.Join(filepath.Dir(dir), "lib", "helix", "runtime"), + filepath.Join(filepath.Dir(dir), "share", "helix", "runtime")) + } + } + runtimes = append(runtimes, + "/usr/lib/helix/runtime", "/usr/share/helix/runtime", + "/usr/local/lib/helix/runtime", "/opt/homebrew/opt/helix/libexec/runtime", + filepath.Join(home, ".cargo", "share", "helix", "runtime")) + seen := map[string]bool{} + for _, r := range runtimes { + d := filepath.Join(r, "themes") + if seen[d] { + continue + } + seen[d] = true + if fi, err := os.Stat(d); err == nil && fi.IsDir() { + dirs = append(dirs, d) + } + } + return dirs +} + +// ── helix ───────────────────────────────────────────────────────────────── +// +// A helix theme is scope -> style, with colors named out of a [palette] at the +// bottom, and may inherit one other theme by name. Inheritance merges both +// halves before anything resolves, which is what lets a child theme restate +// the palette alone (catppuccin_latte is catppuccin_mocha with new colors). + +type helixStyle struct { + fg, bg string // palette names, hex, or one of the sixteen terminal names + italic bool + bold bool +} + +type helixRaw struct { + scopes map[string]helixStyle + palette map[string]string +} + +func loadHelixTheme(path string, dirs []string) *Theme { + raw := readHelixRaw(path, dirs, 0) + if raw == nil { + return nil + } + name := strings.TrimSuffix(filepath.Base(path), ".toml") + return helixTheme(name, raw) +} + +func readHelixRaw(path string, dirs []string, depth int) *helixRaw { + b, err := os.ReadFile(path) + if err != nil { + return nil + } + var doc map[string]any + if err := toml.Unmarshal(b, &doc); err != nil { + return nil + } + raw := &helixRaw{scopes: map[string]helixStyle{}, palette: map[string]string{}} + if parent, _ := doc["inherits"].(string); parent != "" && depth < 8 { + if p := findHelixTheme(parent, dirs); p != "" { + if base := readHelixRaw(p, dirs, depth+1); base != nil { + raw = base + } + } + } + if pal, ok := doc["palette"].(map[string]any); ok { + for k, v := range pal { + if s, ok := v.(string); ok { + raw.palette[k] = s + } + } + } + delete(doc, "palette") + delete(doc, "inherits") + flattenHelix("", doc, raw.scopes) + return raw +} + +func findHelixTheme(name string, dirs []string) string { + if name == "" || strings.ContainsAny(name, "/\\.") { + return "" + } + for _, d := range dirs { + p := filepath.Join(d, name+".toml") + if _, err := os.Stat(p); err == nil { + return p + } + } + return "" +} + +// flattenHelix walks the decoded document into scope -> style. A table is a +// style when it holds only style keys; anything else is a dotted scope name +// someone wrote out as a table, so it keeps descending. +func flattenHelix(prefix string, m map[string]any, into map[string]helixStyle) { + for k, v := range m { + key := k + if prefix != "" { + key = prefix + "." + k + } + switch v := v.(type) { + case string: + into[key] = helixStyle{fg: v} + case map[string]any: + if st, ok := helixStyleOf(v); ok { + into[key] = st + } else { + flattenHelix(key, v, into) + } + } + } +} + +func helixStyleOf(m map[string]any) (helixStyle, bool) { + var st helixStyle + for k, v := range m { + switch k { + case "fg": + st.fg, _ = v.(string) + case "bg": + st.bg, _ = v.(string) + case "modifiers": + mods, _ := v.([]any) + for _, mod := range mods { + switch mod { + case "italic": + st.italic = true + case "bold": + st.bold = true + } + } + case "underline", "underline_style", "underline_color": + // decoration we have no use for, but still a style + default: + return helixStyle{}, false + } + } + return st, true +} + +// the sixteen names a helix theme may use without a palette entry +var termHex = map[string]string{ + "black": "#000000", "red": "#cd3131", "green": "#0dbc79", "yellow": "#e5e510", + "blue": "#2472c8", "magenta": "#bc3fbc", "cyan": "#11a8cd", "gray": "#8a8a8a", + "light-red": "#f14c4c", "light-green": "#23d18b", "light-yellow": "#f5f543", + "light-blue": "#3b8eea", "light-magenta": "#d670d6", "light-cyan": "#29b8db", + "light-gray": "#c0c0c0", "white": "#e5e5e5", +} + +func (r *helixRaw) color(name string) string { + if name == "" || name == "default" { + return "" + } + if c, ok := r.palette[name]; ok { + name = c + } + if strings.HasPrefix(name, "#") { + return hex6(okColor(name)) + } + return termHex[name] +} + +// fg / bg take the first of several scopes that names one, so a theme that +// skips a scope is answered by whatever it does say. Scope names fall back +// along their dots the way helix resolves them. +func (r *helixRaw) fg(scopes ...string) string { return r.pick(true, scopes) } +func (r *helixRaw) bg(scopes ...string) string { return r.pick(false, scopes) } + +func (r *helixRaw) pick(wantFg bool, scopes []string) string { + for _, scope := range scopes { + for key := scope; key != ""; { + if st, ok := r.scopes[key]; ok { + c := st.bg + if wantFg { + c = st.fg + } + if c := r.color(c); c != "" { + return c + } + } + i := strings.LastIndex(key, ".") + if i < 0 { + break + } + key = key[:i] + } + } + return "" +} + +// zed syntax keys helix spells differently; everything else either matches or +// falls back along its dots (punctuation.bracket -> punctuation). +var helixAlias = map[string]string{ + "number": "constant.numeric", + "boolean": "constant.builtin.boolean", + "property": "variable.other.member", + "preproc": "keyword.directive", + "primary": "variable", + "enum": "type.enum", + "string.escape": "constant.character.escape", + "string.regex": "string.regexp", + "variable.special": "variable.builtin", + "comment.doc": "comment.block.documentation", + "link_uri": "markup.link.url", + "link_text": "markup.link.text", + "title": "markup.heading", + "emphasis": "markup.italic", + "emphasis.strong": "markup.bold", +} + +func helixTheme(name string, raw *helixRaw) *Theme { + bg := raw.bg("ui.background", "ui.window") + fg := raw.fg("ui.text", "ui.window") + if bg == "" || fg == "" { + return nil // a theme that paints on the terminal's colors, not ours + } + t := &Theme{ + ID: "helix/" + slug(name), Source: "helix", Name: name, + Appearance: "dark", Bg: bg, Fg: fg, + Syntax: map[string]SyntaxStyle{}, + } + if lum(bg) > 0.5 { + t.Appearance = "light" + } + // A helix theme dresses an editor, not a web page, so it is read for what + // the page needs and fill() closes the rest. The quiet backgrounds come + // first: a selected menu row is often the theme's loudest color. + t.Panel = raw.bg("ui.statusline", "ui.menu", "ui.popup") + t.Hover = raw.bg("ui.cursorline.primary", "ui.selection", "ui.menu.selected") + t.Border = raw.fg("ui.window") + t.LineNo = raw.fg("ui.linenr") + t.Muted = raw.fg("comment", "ui.linenr") + t.Accent = raw.fg("function", "keyword", "type") + t.Note = raw.fg("warning", "diagnostic.warning", "constant.numeric") + + for scope, st := range raw.scopes { + if strings.HasPrefix(scope, "ui.") { + continue + } + if c := raw.color(st.fg); c != "" { + t.Syntax[scope] = syntaxStyle(c, st.italic, st.bold) + } + } + for key, scope := range helixAlias { + if _, ok := t.Syntax[key]; ok { + continue + } + if st, ok := t.Syntax[resolveKey(t, scope)]; ok { + t.Syntax[key] = st + } + } + t.fill() + t.setPlayers(t.syntaxColors()) + return t +} + +func syntaxStyle(color string, italic, bold bool) SyntaxStyle { + s := SyntaxStyle{Color: color} + if italic { + it := "italic" + s.FontStyle = &it + } + if bold { + w := 700.0 + s.FontWeight = &w + } + return s +} + +func first(vals ...string) string { + for _, v := range vals { + if v != "" { + return v + } + } + return "" +} + +// slug is a theme's id in an attribute and a URL: ascii, lowercase, dashed. +func slug(s string) string { + var b strings.Builder + dash := false + for _, r := range strings.ToLower(s) { + if r >= 'a' && r <= 'z' || r >= '0' && r <= '9' { + b.WriteRune(r) + dash = false + } else if !dash && b.Len() > 0 { + b.WriteByte('-') + dash = true + } + } + return strings.Trim(b.String(), "-") +} diff --git a/web/themes_test.go b/web/themes_test.go new file mode 100644 index 0000000..f50f969 --- /dev/null +++ b/web/themes_test.go @@ -0,0 +1,294 @@ +package web + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// everything a helix theme reader has to survive: quoted scope keys, a +// palette, one of the terminal color names, modifiers, and an inline table +// broken over lines the way a formatter leaves it +const helixSrc = ` +# a comment +"ui.background" = { bg = "base" } +"ui.text" = { fg = "text" } +"ui.linenr" = { fg = "muted" } +"ui.statusline" = { fg = "text", bg = "surface" } +"ui.cursorline.primary" = { bg = "highlight" } +"ui.menu.selected" = { fg = "base", bg = "rose" } +"ui.window" = { fg = "muted" } +comment = { fg = "muted", modifiers = ["italic"] } +keyword = { fg = "pine", modifiers = [ + "bold", +] } +string = "gold" +function = { fg = "rose" } +"constant.numeric" = { fg = "iris" } +"variable.other.member" = { fg = "foam" } +"punctuation" = { fg = "muted" } +warning = { fg = "gold" } +type = "white" + +[palette] +base = "#191724" +text = "#e0def4" +muted = "#6e6a86" +surface = "#1f1d2e" +highlight = "#21202e" +pine = "#31748f" +gold = "#f6c177" +rose = "#ebbcba" +iris = "#c4a7e7" +foam = "#9ccfd8" +` + +func writeTheme(t *testing.T, dir, name, body string) string { + t.Helper() + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, name) + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + return path +} + +func TestHelixTheme(t *testing.T) { + dir := t.TempDir() + path := writeTheme(t, dir, "rose_pine.toml", helixSrc) + th := loadHelixTheme(path, []string{dir}) + if th == nil { + t.Fatal("theme did not load") + } + for _, tc := range []struct{ what, got, want string }{ + {"id", th.ID, "helix/rose-pine"}, + {"source", th.Source, "helix"}, + {"name", th.Name, "rose_pine"}, + {"appearance", th.Appearance, "dark"}, + {"bg", th.Bg, "#191724"}, + {"fg", th.Fg, "#e0def4"}, + {"panel", th.Panel, "#1f1d2e"}, + {"line numbers", th.LineNo, "#6e6a86"}, + {"border", th.Border, "#6e6a86"}, + {"accent", th.Accent, "#ebbcba"}, // function + {"note", th.Note, "#f6c177"}, // warning + {"hover", th.Hover, "#21202e"}, // cursorline, not the loud menu row + {"muted", th.Muted, "#6e6a86"}, // comment + } { + if tc.got != tc.want { + t.Errorf("%s = %q, want %q", tc.what, tc.got, tc.want) + } + } + // syntax keys the site paints with, spelled the way helix spells them + for _, tc := range []struct{ key, want string }{ + {"comment", "#6e6a86"}, + {"keyword", "#31748f"}, + {"string", "#f6c177"}, + {"type", "#e5e5e5"}, // a terminal color name, not a palette one + {"number", "#c4a7e7"}, // zed's name for constant.numeric + {"property", "#9ccfd8"}, // zed's name for variable.other.member + {"punctuation.bracket", "#6e6a86"}, // falls back along its dots + } { + if got := th.syn(tc.key); got != tc.want { + t.Errorf("syntax %s = %q, want %q", tc.key, got, tc.want) + } + } + if s := th.Syntax["comment"]; s.FontStyle == nil || *s.FontStyle != "italic" { + t.Errorf("comment is not italic: %+v", s) + } + if s := th.Syntax["keyword"]; s.FontWeight == nil || *s.FontWeight != 700 { + t.Errorf("keyword is not bold: %+v", s) + } + // agent colors: from the code's own colors, and none of them invisible + if len(th.Players) < 3 { + t.Fatalf("agent colors = %v, want at least 3", th.Players) + } + for _, p := range th.Players { + if colorDist(p, hex6(th.Bg)) <= 60 || colorDist(p, hex6(th.Fg)) <= 60 { + t.Errorf("agent color %s vanishes against the theme", p) + } + } +} + +// A child theme restating only the palette is how helix ships most of its +// families: the parent's scopes have to resolve against the child's colors. +func TestHelixInherits(t *testing.T) { + dir := t.TempDir() + writeTheme(t, dir, "parent.toml", helixSrc) + path := writeTheme(t, dir, "child.toml", ` +inherits = "parent" +comment = { fg = "muted" } + +[palette] +base = "#eff1f5" +text = "#4c4f69" +muted = "#7c7f93" +surface = "#e6e9ef" +highlight = "#dce0e8" +pine = "#1e66f5" +gold = "#df8e1d" +rose = "#ea76cb" +iris = "#8839ef" +foam = "#04a5e5" +`) + th := loadHelixTheme(path, []string{dir}) + if th == nil { + t.Fatal("child theme did not load") + } + if th.Bg != "#eff1f5" || th.Fg != "#4c4f69" { + t.Errorf("inherited scopes kept the parent's palette: bg=%s fg=%s", th.Bg, th.Fg) + } + if th.Appearance != "light" { + t.Errorf("appearance = %q, want light for a pale background", th.Appearance) + } + if got := th.syn("keyword"); got != "#1e66f5" { + t.Errorf("inherited keyword = %q, want the child's pine", got) + } + // the child's own entry wins over the parent's, modifiers and all + if s := th.Syntax["comment"]; s.FontStyle != nil { + t.Errorf("child comment kept the parent's italics: %+v", s) + } +} + +// A theme that names almost nothing still has to dress a whole page. +func TestFillClosesTheGaps(t *testing.T) { + th := &Theme{Bg: "#101010", Fg: "#f0f0f0", Syntax: map[string]SyntaxStyle{ + "function": {Color: "#88c0d0"}, + }} + th.fill() + for _, tc := range []struct{ what, got string }{ + {"panel", th.Panel}, {"border", th.Border}, {"line numbers", th.LineNo}, + {"muted", th.Muted}, {"accent", th.Accent}, {"note", th.Note}, {"hover", th.Hover}, + } { + if okColor(tc.got) == "" { + t.Errorf("%s = %q, want a color", tc.what, tc.got) + } + } + if th.Accent != "#88c0d0" { + t.Errorf("accent = %q, want the theme's own function color", th.Accent) + } + if th.Panel == th.Bg || th.Hover == th.Bg { + t.Errorf("panel %q and hover %q must lift off the background %q", th.Panel, th.Hover, th.Bg) + } + // a panel the text would be lost in is not kept + lost := &Theme{Bg: "#f7f3ee", Fg: "#605a52", Panel: "#605a52"} + lost.fill() + if lost.Panel == "#605a52" { + t.Error("kept a panel the foreground disappears into") + } +} + +func TestZedFamily(t *testing.T) { + fam, err := parseZedFamily([]byte(`{"name":"Fake","themes":[ + {"name":"Fake Dark","appearance":"dark","style":{ + "editor.background":"#101010","editor.foreground":"#e0e0e0", + "text.accent":"0f4b6e","warning":"#e0af68", + "players":[{"cursor":"#7aa2f7"},{"cursor":"#9ece6a"}], + "syntax":{"keyword":{"color":"#bb9af7","font_style":"italic"}, + "string":{"color":"9ece6a"}}}}, + {"name":"Fake Light","appearance":"light","style":{ + "editor.background":"#fafafa","editor.foreground":"#383a42"}}]}`)) + if err != nil { + t.Fatal(err) + } + if len(fam) != 2 { + t.Fatalf("themes = %d, want 2", len(fam)) + } + dark, light := fam[0], fam[1] + if dark.ID != "zed/fake-dark" || light.ID != "zed/fake-light" { + t.Errorf("ids = %q, %q", dark.ID, light.ID) + } + // a theme in the wild does drop the odd "#": what is not a color is + // treated as unsaid, and filled in rather than emitted as nonsense + if dark.Accent == "0f4b6e" { + t.Error("kept a color with no #") + } + if _, ok := dark.Syntax["string"]; ok { + t.Error("kept a syntax color with no #") + } + if dark.syn("keyword") != "#bb9af7" { + t.Errorf("keyword = %q", dark.syn("keyword")) + } + if len(dark.Players) < 2 || dark.Players[0] != "#7aa2f7" { + t.Errorf("agent colors = %v, want the player palette first", dark.Players) + } + // nothing to work from but bg and fg, and still a whole theme + if okColor(light.Muted) == "" || okColor(light.Hover) == "" { + t.Errorf("light theme left gaps: %+v", light) + } +} + +// The picker's two files: a block per theme, and a menu that names them. +func TestThemeFiles(t *testing.T) { + dark, light := loadTheme("", "", "dark"), loadTheme("", "", "light") + helix := loadHelixTheme(writeTheme(t, t.TempDir(), "rose_pine.toml", helixSrc), nil) + ts := themesFrom([]*Theme{dark, light, helix}, dark, light) + + css := string(ts.CSS) + for _, th := range ts.List { + if !strings.Contains(css, `:root[data-theme="`+th.ID+`"]`) { + t.Errorf("no css block for %s", th.ID) + } + if !strings.Contains(string(ts.JS), th.ID) { + t.Errorf("%s is not in the menu", th.ID) + } + } + for _, want := range []string{"--bg:", "--fg:", "--ag0:", "color-scheme: dark", "color-scheme: light"} { + if !strings.Contains(css, want) { + t.Errorf("themes.css never says %q", want) + } + } + // every declaration has to be worth something to the browser + for _, line := range strings.Split(css, "\n") { + if l := strings.TrimSpace(line); strings.HasPrefix(l, "--") && strings.HasSuffix(l, ": ;") { + t.Errorf("empty declaration: %s", l) + } + } + if n := strings.Count(string(ts.JS), `"id":`); n != len(ts.List) { + t.Errorf("menu has %d themes, want %d", n, len(ts.List)) + } +} + +// The two editors' theme directories, as they are on a machine that has them. +func TestDiscoverFindsBothEditors(t *testing.T) { + home := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, "config")) + t.Setenv("XDG_DATA_HOME", filepath.Join(home, "data")) + writeTheme(t, filepath.Join(home, "config", "zed", "themes"), "mine.json", + `{"name":"Mine","themes":[{"name":"Mine Dark","appearance":"dark","style":{ + "editor.background":"#101010","editor.foreground":"#e0e0e0"}}]}`) + writeTheme(t, filepath.Join(home, "data", "zed", "extensions", "installed", "ext", "themes"), + "ext.json", `{"name":"Ext","themes":[{"name":"Ext Light","appearance":"light","style":{ + "editor.background":"#fafafa","editor.foreground":"#383a42"}}]}`) + writeTheme(t, filepath.Join(home, "config", "helix", "themes"), "mine_helix.toml", helixSrc) + + found := map[string]*Theme{} + for _, th := range discoverThemes() { + found[th.ID] = th + } + for _, want := range []string{"zed/mine-dark", "zed/ext-light", "helix/mine-helix"} { + if found[want] == nil { + t.Errorf("did not find %s", want) + } + } +} + +// Coverage colors are mixed in the browser so every theme can supply them. +func TestMaskMix(t *testing.T) { + s := &Site{Agents: []*Agent{{Bit: 1}, {Bit: 2}, {Bit: 4}}} + for _, tc := range []struct { + mask uint8 + want string + }{ + {1, "var(--ag0)"}, + {5, "color-mix(in srgb, var(--ag0) 50.000%, var(--ag2))"}, + {7, "color-mix(in srgb, var(--ag0) 33.333%, color-mix(in srgb, var(--ag1) 50.000%, var(--ag2)))"}, + } { + if got := s.maskMix(tc.mask); got != tc.want { + t.Errorf("mask %d = %q, want %q", tc.mask, got, tc.want) + } + } +} diff --git a/web/transcript.go b/web/transcript.go new file mode 100644 index 0000000..0678b80 --- /dev/null +++ b/web/transcript.go @@ -0,0 +1,602 @@ +// transcript.go — the conversation a session's reading happened inside. +// +// The notevi log says a session read a file at 10:04; the harness that ran that +// session kept the whole conversation on disk, in its own format. Here we find +// that file by session id and flatten both known formats into Turns, so a note +// can be opened at the moment it was written. +// +// Two rules keep this cheap and safe. Tool calls and their output are reduced +// to a line each — transcripts reach megabytes and none of that belongs in a +// page — and nothing outside a configured root is ever opened, with session +// ids checked before they touch the filesystem. +package web + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" +) + +const ( + maxTranscript = 32 << 20 // refuse to parse more than this in one file + transcriptCacheMax = 8 // parsed transcripts are large; keep few + briefLine = 160 // one line of a tool call or its output + maxText = 6000 // one message + convWindow = 80 // turns rendered around the anchored moment + convMax = 1500 // turns rendered by "show all" +) + +// A Turn is one moment in a session: something said, a tool called or answered, +// or — woven in from the notevi log — a read, a grep, a note. +type Turn struct { + Role string // user | assistant | thinking | tool | result | notevi + Kind string // qualifies Role: the notevi op, or "error" on a failed tool + When time.Time + Text string // what was said + Tool string // tool name, on tool and result turns + Detail string // one compact line: the call's arguments, or its output + File string // notevi turns: the file the op touched + Note *Note // notevi note turns: the note itself, rendered as a card + Here bool // the anchored moment +} + +func (t Turn) Clock() string { + if t.When.IsZero() { + return "" + } + return t.When.Local().Format("15:04:05") +} + +// A Transcript is one harness conversation, already normalized. +type Transcript struct { + Path string + Harness string // claude-code | codex + Turns []Turn + Err string +} + +// transcripts finds and parses harness transcripts, remembering what it has +// already parsed. Roots are the only places it will look. +type transcripts struct { + roots []string + + mu sync.Mutex + cache map[string]*Transcript // path|mtime|size -> parsed +} + +func newTranscripts(roots []string) *transcripts { + tx := &transcripts{cache: map[string]*Transcript{}} + for _, r := range roots { + r = strings.TrimSpace(r) + if r == "" { + continue + } + if abs, err := filepath.Abs(r); err == nil { + r = abs + } + tx.roots = append(tx.roots, filepath.Clean(r)) + } + return tx +} + +// defaultTranscriptRoots are where the two harnesses we know about keep their +// conversations. +func defaultTranscriptRoots() []string { + home, err := os.UserHomeDir() + if err != nil { + return nil + } + return []string{filepath.Join(home, ".claude", "projects"), filepath.Join(home, ".codex", "sessions")} +} + +// safeSession refuses ids that could name something we did not mean to open: +// the id goes into a filesystem path, so it must be one plain component. +func safeSession(id string) error { + if id == "" { + return fmt.Errorf("no session id") + } + if len(id) > 128 { + return fmt.Errorf("session id is too long") + } + for _, r := range id { + ok := r == '-' || r == '_' || r == ':' || r == '.' || + '0' <= r && r <= '9' || 'a' <= r && r <= 'z' || 'A' <= r && r <= 'Z' + if !ok { + return fmt.Errorf("session id contains %q", r) + } + } + if strings.Contains(id, "..") { + return fmt.Errorf("session id contains %q", "..") + } + return nil +} + +// mangleDir is how Claude Code names a project directory after its cwd: +// /home/u/0x4200.cafe -> -home-u-0x4200-cafe. +func mangleDir(dir string) string { + return strings.NewReplacer("/", "-", ".", "-").Replace(dir) +} + +// under states the rule the globs below already obey: a transcript we open +// lies inside a configured root. It is checked anyway, so the rule has one +// place to fail rather than living in the shape of two patterns. +func under(root, path string) bool { + rel, err := filepath.Rel(root, path) + if err != nil { + return false + } + return rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) +} + +// find locates a session's transcript. Claude Code writes +// <root>/<mangled cwd>/<session>.jsonl; codex writes +// <root>/YYYY/MM/DD/rollout-<time>-<thread>.jsonl and notevi's session id is that +// thread id, so it is matched on the suffix. Both patterns are tried under +// every root — a root knows its own layout, we do not have to. +func (tx *transcripts) find(session, dir string) string { + if safeSession(session) != nil { + return "" + } + for _, root := range tx.roots { + pats := []string{ + filepath.Join(root, "*", session+".jsonl"), + filepath.Join(root, "*", "*", "*", "rollout-*-"+session+".jsonl"), + } + // the cwd we logged names the directory directly, when it still exists + if dir != "" { + pats = append([]string{filepath.Join(root, mangleDir(dir), session+".jsonl")}, pats...) + } + for _, pat := range pats { + hits, _ := filepath.Glob(pat) + for _, hit := range hits { + if under(root, hit) { + return hit + } + } + } + } + return "" +} + +// load returns the parsed transcript for a session, or nil when there is none. +// Parses are cached by path, mtime and size, so a 5 MB file is read once. +func (tx *transcripts) load(session, dir string) *Transcript { + path := tx.find(session, dir) + if path == "" { + return nil + } + st, err := os.Stat(path) + if err != nil { + return nil + } + key := fmt.Sprintf("%s|%d|%d", path, st.ModTime().UnixNano(), st.Size()) + + tx.mu.Lock() + t, ok := tx.cache[key] + tx.mu.Unlock() + if ok { + return t + } + + t = readTranscript(path, st.Size()) + tx.mu.Lock() + if len(tx.cache) >= transcriptCacheMax { + tx.cache = map[string]*Transcript{} + } + tx.cache[key] = t + tx.mu.Unlock() + return t +} + +// ── parsing ─────────────────────────────────────────────────────────────── + +// One line of either format. Codex wraps every record in "payload"; Claude +// Code puts the model turn in "message". Sniffing per line keeps the two +// parsers independent of any file header. +type rawRecord struct { + Type string `json:"type"` + Timestamp string `json:"timestamp"` + Payload json.RawMessage `json:"payload"` + Message json.RawMessage `json:"message"` +} + +type parser struct { + t *Transcript + tools map[string]string // tool call id -> name, so results keep their name + last time.Time // records without a stamp inherit the previous one +} + +func readTranscript(path string, size int64) *Transcript { + t := &Transcript{Path: path} + if size > maxTranscript { + t.Err = fmt.Sprintf("transcript is %d MB — too large to parse", size>>20) + return t + } + b, err := os.ReadFile(path) + if err != nil { + t.Err = err.Error() + return t + } + p := &parser{t: t, tools: map[string]string{}} + for _, line := range strings.Split(string(b), "\n") { + if line == "" { + continue + } + var rec rawRecord + if json.Unmarshal([]byte(line), &rec) != nil { + continue + } + at := parseTime(rec.Timestamp) + if at.IsZero() { + at = p.last + } else { + p.last = at + } + switch { + case len(rec.Payload) > 0: + t.Harness = "codex" + p.codex(rec, at) + case len(rec.Message) > 0: + t.Harness = "claude-code" + p.claude(rec, at) + } + } + return t +} + +// add drops turns that would render as nothing — empty thinking blocks, +// tool results whose output was pure whitespace. +func (p *parser) add(t Turn) { + if t.Text == "" && t.Detail == "" && t.Tool == "" { + return + } + t.Text = clip(t.Text, maxText) + p.t.Turns = append(p.t.Turns, t) +} + +// ── claude code ─────────────────────────────────────────────────────────── + +type claudeMsg struct { + Role string `json:"role"` + Content json.RawMessage `json:"content"` // a string, or blocks +} + +type claudeBlock struct { + Type string `json:"type"` + Text string `json:"text"` + Thinking string `json:"thinking"` + ID string `json:"id"` + Name string `json:"name"` + Input json.RawMessage `json:"input"` + ToolUseID string `json:"tool_use_id"` + Content json.RawMessage `json:"content"` // tool_result: a string, or blocks + IsError bool `json:"is_error"` +} + +// claude turns records of type user and assistant into Turns; the rest of the +// file (modes, titles, file history, attachments) is harness bookkeeping. +func (p *parser) claude(rec rawRecord, at time.Time) { + if rec.Type != "user" && rec.Type != "assistant" { + return + } + var m claudeMsg + if json.Unmarshal(rec.Message, &m) != nil { + return + } + var text string + if json.Unmarshal(m.Content, &text) == nil { // plain prompts arrive as a string + p.add(Turn{Role: rec.Type, When: at, Text: text}) + return + } + var blocks []claudeBlock + if json.Unmarshal(m.Content, &blocks) != nil { + return + } + for _, b := range blocks { + switch b.Type { + case "text": + p.add(Turn{Role: rec.Type, When: at, Text: b.Text}) + case "thinking": + p.add(Turn{Role: "thinking", When: at, Text: b.Thinking}) + case "tool_use": + p.tools[b.ID] = b.Name + p.add(Turn{Role: "tool", When: at, Tool: b.Name, Detail: callDetail(b.Input)}) + case "tool_result": + t := Turn{Role: "result", When: at, Tool: p.tools[b.ToolUseID], Detail: resultDetail(b.Content)} + if b.IsError { + t.Kind = "error" + } + p.add(t) + } + } +} + +// ── codex ───────────────────────────────────────────────────────────────── + +type codexPayload struct { + Type string `json:"type"` + Role string `json:"role"` + Name string `json:"name"` + CallID string `json:"call_id"` + Arguments json.RawMessage `json:"arguments"` // a JSON string holding JSON + Input json.RawMessage `json:"input"` + Output json.RawMessage `json:"output"` + Content []codexText `json:"content"` + Summary []codexText `json:"summary"` +} + +type codexText struct { + Type string `json:"type"` + Text string `json:"text"` +} + +// codex reads response_items — the model's own history. The event_msg stream +// beside it is the TUI's view of the same turns, so taking both would double +// everything. +func (p *parser) codex(rec rawRecord, at time.Time) { + if rec.Type != "response_item" { + return + } + var pl codexPayload + if json.Unmarshal(rec.Payload, &pl) != nil { + return + } + switch pl.Type { + case "message": + // developer messages are the harness's own instructions, and the first + // user messages are context it injects; neither was said by anyone + if pl.Role == "developer" { + return + } + text := joinText(pl.Content) + if injected(text) { + return + } + role := "assistant" + if pl.Role == "user" { + role = "user" + } + p.add(Turn{Role: role, When: at, Text: text}) + case "reasoning": + // summaries are usually encrypted and come back empty; add drops those + p.add(Turn{Role: "thinking", When: at, Text: joinText(pl.Summary)}) + case "function_call", "custom_tool_call", "web_search_call": + name := pl.Name + if name == "" { + name = strings.TrimSuffix(pl.Type, "_call") + } + p.tools[pl.CallID] = name + detail := callDetail(pl.Arguments) + if detail == "" { + detail = callDetail(pl.Input) + } + p.add(Turn{Role: "tool", When: at, Tool: name, Detail: detail}) + case "function_call_output", "custom_tool_call_output", "web_search_output": + p.add(Turn{Role: "result", When: at, Tool: p.tools[pl.CallID], Detail: resultDetail(pl.Output)}) + } +} + +func joinText(items []codexText) string { + var parts []string + for _, it := range items { + if it.Text != "" { + parts = append(parts, it.Text) + } + } + return strings.Join(parts, "\n\n") +} + +// injected recognizes the wrappers a harness puts around a user turn to carry +// its own state. +func injected(text string) bool { + for _, tag := range []string{"<environment_context>", "<user_instructions>", "<permissions instructions>"} { + if strings.HasPrefix(text, tag) { + return true + } + } + return false +} + +// ── summarizing ─────────────────────────────────────────────────────────── + +// callFields are the arguments worth a line, most telling first. Anything that +// carries file content (new_string, content) is deliberately not here. +var callFields = []string{"command", "cmd", "file_path", "path", "pattern", "query", "url", "prompt", "description"} + +// callDetail reduces a tool call's arguments to their one interesting field. +func callDetail(raw json.RawMessage) string { + if len(raw) == 0 { + return "" + } + var s string + if json.Unmarshal(raw, &s) == nil { // codex passes arguments as a JSON string + raw = json.RawMessage(s) + } + var m map[string]any + if json.Unmarshal(raw, &m) != nil { + return brief(string(raw)) + } + for _, k := range callFields { + if v, ok := m[k].(string); ok && strings.TrimSpace(v) != "" { + return brief(v) + } + } + b, err := json.Marshal(m) + if err != nil { + return "" + } + return brief(string(b)) +} + +// resultDetail summarizes what a tool answered, whether that came back as a +// string, as content blocks, or as an image nobody wants inlined. +func resultDetail(raw json.RawMessage) string { + if len(raw) == 0 { + return "" + } + var s string + if json.Unmarshal(raw, &s) == nil { + return brief(s) + } + var items []codexText + if json.Unmarshal(raw, &items) == nil { + var parts []string + for _, it := range items { + switch { + case it.Text != "": + parts = append(parts, it.Text) + case it.Type != "": + parts = append(parts, "["+it.Type+"]") + } + } + return brief(strings.Join(parts, "\n")) + } + return brief(string(raw)) +} + +// brief keeps a blob's first line and says how much was left behind. Whole +// files and command output pass through here; a page gets their shape, never +// their bytes. +func brief(s string) string { + s = strings.TrimRight(s, "\n") + if strings.TrimSpace(s) == "" { + return "" + } + first, rest, more := strings.Cut(s, "\n") + first = clip(strings.TrimSpace(first), briefLine) + if !more || strings.TrimSpace(rest) == "" { + return first + } + return fmt.Sprintf("%s … +%d lines", first, strings.Count(rest, "\n")+1) +} + +func clip(s string, n int) string { + if len(s) <= n { // bytes first: the common case never allocates + return s + } + r := []rune(s) + if len(r) <= n { + return s + } + return strings.TrimRight(string(r[:n]), " \t") + "…" +} + +// ── one session: the transcript with the notevi log woven in ────────────────── + +// A Conv is what the session page shows: the conversation, the log entries +// that happened during it, and where in a long one we are looking. +type Conv struct { + Session, Agent, Model, Dir string + Bit uint8 + Harness, Path string + Roots []string + Err string + Reads, Greps, Notes int + + Turns []Turn + Total int // moments in the whole conversation + From, To int // 1-based position of Turns within it + Anchor string // element id to scroll to, "" when nothing is anchored + AllHref string // same page, unwindowed + Windowed bool + Incomplete bool // even "show all" had to stop +} + +// sessionTurns are the notevi log's own moments for a session: what it read, +// grepped and noted. +func (s *Site) sessionTurns(id string) []Turn { + var out []Turn + for _, e := range s.Entries { + if e.Session != id || e.Op == "note" { + continue + } + out = append(out, Turn{Role: "notevi", Kind: e.Op, When: parseTime(e.Time), + Text: describe(e), File: e.File}) + } + for _, n := range s.Notes { + if n.Session == id { + out = append(out, Turn{Role: "notevi", Kind: "note", When: n.At, File: n.File, Note: n}) + } + } + return out +} + +// conversation merges a session's transcript with its log entries. Both sides +// are compared as instants — the log stamps carry an offset, transcripts are +// UTC — so ordering is the real one, and only the rendering is local. +func (sv *server) conversation(site *Site, id string, note int, all bool) *Conv { + c := &Conv{Session: id, Roots: sv.tx.roots} + if err := safeSession(id); err != nil { + c.Err = err.Error() + return c + } + for _, s := range site.Sessions(time.Now(), liveWindow, 0) { + if s.ID == id { + c.Agent, c.Model, c.Dir, c.Bit = s.Agent, s.Model, s.Dir, s.Bit + c.Reads, c.Greps, c.Notes = s.Reads, s.Greps, s.Notes + break + } + } + + logged := site.sessionTurns(id) + // the parsed transcript is shared with other requests, so the merge copies + // it rather than appending onto its slice + var turns []Turn + if t := sv.tx.load(id, c.Dir); t != nil { + c.Path, c.Harness, c.Err = t.Path, t.Harness, t.Err + turns = make([]Turn, 0, len(t.Turns)+len(logged)) + turns = append(turns, t.Turns...) + } + turns = append(turns, logged...) + sort.SliceStable(turns, func(i, j int) bool { return turns[i].When.Before(turns[j].When) }) + + at := -1 + if note > 0 { + for i := range turns { + if turns[i].Note != nil && turns[i].Note.ID == note { + at, turns[i].Here = i, true + c.Anchor = fmt.Sprintf("note-%d", note) + break + } + } + } + c.Total = len(turns) + from, window := convWindowAt(turns, at, all) + c.Turns, c.From, c.To = window, from+1, from+len(window) + c.Windowed = len(window) < len(turns) + c.Incomplete = c.Windowed && all + c.AllHref = "/session/" + escPath(id) + "?all=1" + if note > 0 { + c.AllHref += fmt.Sprintf("¬e=%d#note-%d", note, note) + } + return c +} + +// convWindowAt cuts a conversation down to what a page may render: a stretch +// around the anchored moment, or the tail of it when nothing is anchored. +// "show all" raises the bound but does not remove it. +func convWindowAt(turns []Turn, at int, all bool) (int, []Turn) { + n := convWindow + if all { + n = convMax + } + if len(turns) <= n { + return 0, turns + } + if at < 0 { + return len(turns) - n, turns[len(turns)-n:] + } + lo := at - n/2 + if lo < 0 { + lo = 0 + } + if lo+n > len(turns) { + lo = len(turns) - n + } + return lo, turns[lo : lo+n] +} diff --git a/web/transcript_test.go b/web/transcript_test.go new file mode 100644 index 0000000..1c3b3db --- /dev/null +++ b/web/transcript_test.go @@ -0,0 +1,333 @@ +package web + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// Both fixtures are the shapes the real files use: Claude Code writes one +// record per message with content blocks, codex wraps everything in a payload +// and keeps the model's history in response_items. +const claudeJSONL = `{"type":"user","timestamp":"2026-07-20T09:57:00.000Z","sessionId":"s1","cwd":"/repo","message":{"role":"user","content":"read lib.rs and tell me about the cache"}} +{"type":"assistant","timestamp":"2026-07-20T09:57:30.000Z","message":{"role":"assistant","model":"claude-opus-5","content":[{"type":"thinking","thinking":"start with the struct","signature":"CAIS"},{"type":"text","text":"Reading it now."},{"type":"tool_use","id":"toolu_1","name":"Bash","input":{"command":"notevi read src/lib.rs:1-30","description":"read the file"}}]}} +{"type":"user","timestamp":"2026-07-20T09:59:10.000Z","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"1\tuse std::collections::HashMap;\n2\t\n3\tstruct Cache;\n"}]}} +{"type":"mode","timestamp":"2026-07-20T09:59:11.000Z","mode":"default"} +{"type":"assistant","timestamp":"2026-07-20T09:59:40.000Z","message":{"role":"assistant","content":[{"type":"tool_use","id":"toolu_2","name":"Read","input":{"file_path":"/repo/src/main.rs"}}]}} +{"type":"user","timestamp":"2026-07-20T09:59:45.000Z","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_2","is_error":true,"content":[{"type":"text","text":"no such file"}]}]}} +{"type":"assistant","timestamp":"2026-07-20T10:02:30.000Z","message":{"role":"assistant","content":[{"type":"text","text":"It is a two-level map."}]}} +` + +const codexJSONL = `{"timestamp":"2026-07-20T12:00:00.000Z","type":"session_meta","payload":{"id":"019f0000-0000-7000-8000-00000000abcd","cwd":"/repo"}} +{"timestamp":"2026-07-20T12:00:01.000Z","type":"response_item","payload":{"type":"message","role":"developer","content":[{"type":"input_text","text":"You are Codex, an agent."}]}} +{"timestamp":"2026-07-20T12:00:02.000Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"<environment_context>\n <cwd>/repo</cwd>\n</environment_context>"}]}} +{"timestamp":"2026-07-20T12:00:03.000Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"review the cache"}]}} +{"timestamp":"2026-07-20T12:00:04.000Z","type":"response_item","payload":{"type":"reasoning","summary":[{"type":"summary_text","text":"start with lib.rs"}],"encrypted_content":"gAAAA"}} +{"timestamp":"2026-07-20T12:00:05.000Z","type":"response_item","payload":{"type":"function_call","name":"exec_command","call_id":"call_1","arguments":"{\"cmd\":\"notevi read src/lib.rs\",\"workdir\":\"/repo\"}"}} +{"timestamp":"2026-07-20T12:00:06.000Z","type":"response_item","payload":{"type":"function_call_output","call_id":"call_1","output":"Chunk ID: abc123\nOutput:\n1\tstruct Cache;\n"}} +{"timestamp":"2026-07-20T12:00:07.000Z","type":"event_msg","payload":{"type":"agent_message","message":"the cache is two-level"}} +{"timestamp":"2026-07-20T12:00:08.000Z","type":"response_item","payload":{"type":"custom_tool_call","name":"apply_patch","call_id":"call_2","input":"*** Begin Patch\n*** Update File: src/lib.rs\n@@\n-old\n+new\n"}} +{"timestamp":"2026-07-20T12:00:09.000Z","type":"response_item","payload":{"type":"custom_tool_call_output","call_id":"call_2","output":"Exit code: 0\n"}} +{"timestamp":"2026-07-20T12:00:10.000Z","type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"The cache is two-level."}]}} +` + +func writeFile(t *testing.T, path, body string) string { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + return path +} + +func turnLine(tn Turn) string { + s := tn.Role + if tn.Tool != "" { + s += " " + tn.Tool + } + if tn.Text != "" { + s += " " + tn.Text + } + if tn.Detail != "" { + s += " " + tn.Detail + } + return s +} + +func TestParseClaudeTranscript(t *testing.T) { + path := writeFile(t, filepath.Join(t.TempDir(), "s.jsonl"), claudeJSONL) + tr := readTranscript(path, int64(len(claudeJSONL))) + if tr.Harness != "claude-code" || tr.Err != "" { + t.Fatalf("harness = %q err = %q", tr.Harness, tr.Err) + } + want := []string{ + "user read lib.rs and tell me about the cache", + "thinking start with the struct", + "assistant Reading it now.", + "tool Bash notevi read src/lib.rs:1-30", + "result Bash 1\tuse std::collections::HashMap; … +2 lines", + "tool Read /repo/src/main.rs", + "result Read no such file", + "assistant It is a two-level map.", + } + var got []string + for _, tn := range tr.Turns { + got = append(got, turnLine(tn)) + } + if strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Errorf("turns:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) + } + if tr.Turns[6].Kind != "error" { + t.Error("a failed tool result is not marked") + } + if at := tr.Turns[0].When; at.Format(time.RFC3339) != "2026-07-20T09:57:00Z" { + t.Errorf("first turn at %v", at) + } +} + +func TestParseCodexTranscript(t *testing.T) { + path := writeFile(t, filepath.Join(t.TempDir(), "r.jsonl"), codexJSONL) + tr := readTranscript(path, int64(len(codexJSONL))) + if tr.Harness != "codex" || tr.Err != "" { + t.Fatalf("harness = %q err = %q", tr.Harness, tr.Err) + } + want := []string{ + "user review the cache", + "thinking start with lib.rs", + "tool exec_command notevi read src/lib.rs", + "result exec_command Chunk ID: abc123 … +2 lines", + "tool apply_patch *** Begin Patch … +4 lines", + "result apply_patch Exit code: 0", + "assistant The cache is two-level.", + } + var got []string + for _, tn := range tr.Turns { + got = append(got, turnLine(tn)) + } + if strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Errorf("turns:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) + } +} + +// Tool output is what makes these files megabytes; a page gets one line of it. +func TestToolOutputIsSummarized(t *testing.T) { + huge := strings.Repeat("x", 400) + "\n" + strings.Repeat("line\n", 50000) + line := fmt.Sprintf(`{"type":"user","timestamp":"2026-07-20T10:00:00.000Z","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t","content":%q}]}}`, huge) + path := writeFile(t, filepath.Join(t.TempDir(), "big.jsonl"), line+"\n") + tr := readTranscript(path, int64(len(line)+1)) + if len(tr.Turns) != 1 { + t.Fatalf("turns = %d", len(tr.Turns)) + } + if n := len(tr.Turns[0].Detail); n > 4*briefLine { + t.Errorf("summary of a 250 KB result is %d bytes", n) + } + if !strings.Contains(tr.Turns[0].Detail, "+50000 lines") { + t.Errorf("summary does not say what was left out: %q", tr.Turns[0].Detail) + } +} + +func TestTranscriptTooLargeIsRefused(t *testing.T) { + path := writeFile(t, filepath.Join(t.TempDir(), "x.jsonl"), "{}\n") + if tr := readTranscript(path, maxTranscript+1); !strings.Contains(tr.Err, "too large") { + t.Errorf("err = %q", tr.Err) + } +} + +// ── locating ───────────────────────────────────────────────────────────── + +func TestSafeSession(t *testing.T) { + for _, ok := range []string{"s1", "web:goblin", "24983541-2e59-4d47-94bb-837acf8147c3", + "019fa0f1-49de-7e33-af62-6db956589080"} { + if err := safeSession(ok); err != nil { + t.Errorf("safeSession(%q) = %v", ok, err) + } + } + for _, bad := range []string{"", "..", "a/b", `a\b`, "../../etc/passwd", "a..b", "a b", + "a*b", "a\x00b", strings.Repeat("x", 129)} { + if err := safeSession(bad); err == nil { + t.Errorf("safeSession(%q) was accepted", bad) + } + } +} + +func TestFindTranscript(t *testing.T) { + claudeRoot, codexRoot := t.TempDir(), t.TempDir() + const ( + cid = "24983541-2e59-4d47-94bb-837acf8147c3" + xid = "019fa0f1-49de-7e33-af62-6db956589080" + ) + want := writeFile(t, filepath.Join(claudeRoot, "-home-u-0x4200-cafe-proj", cid+".jsonl"), claudeJSONL) + wantX := writeFile(t, filepath.Join(codexRoot, "2026", "07", "26", + "rollout-2026-07-26T21-19-55-"+xid+".jsonl"), codexJSONL) + // a file outside every root must stay invisible + outside := writeFile(t, filepath.Join(t.TempDir(), cid+".jsonl"), claudeJSONL) + + tx := newTranscripts([]string{claudeRoot, codexRoot}) + if got := tx.find(cid, "/home/u/0x4200.cafe/proj"); got != want { + t.Errorf("with the logged cwd: %q, want %q", got, want) + } + if got := tx.find(cid, "/somewhere/else"); got != want { + t.Errorf("with a stale cwd: %q, want %q", got, want) + } + if got := tx.find(xid, ""); got != wantX { + t.Errorf("codex thread: %q, want %q", got, wantX) + } + if got := tx.find("nosuchsession", ""); got != "" { + t.Errorf("unknown session found %q", got) + } + if got := newTranscripts(nil).find(cid, filepath.Dir(outside)); got != "" { + t.Errorf("no roots configured, yet found %q", got) + } + if under(claudeRoot, outside) { + t.Error("a path outside a root passed the check") + } +} + +// A 5 MB transcript is parsed once and then only re-read when it changes. +func TestTranscriptCacheKeyedByFile(t *testing.T) { + root := t.TempDir() + path := writeFile(t, filepath.Join(root, "-repo", "s1.jsonl"), claudeJSONL) + tx := newTranscripts([]string{root}) + + first := tx.load("s1", "/repo") + if first == nil || len(first.Turns) == 0 { + t.Fatal("nothing parsed") + } + if again := tx.load("s1", "/repo"); again != first { + t.Error("an unchanged transcript was parsed twice") + } + writeFile(t, path, claudeJSONL+`{"type":"assistant","timestamp":"2026-07-20T11:00:00.000Z","message":{"role":"assistant","content":[{"type":"text","text":"one more thing"}]}}`+"\n") + future := time.Now().Add(time.Second) + os.Chtimes(path, future, future) + after := tx.load("s1", "/repo") + if after == first || len(after.Turns) != len(first.Turns)+1 { + t.Errorf("a changed transcript was not re-parsed: %d -> %d turns", len(first.Turns), len(after.Turns)) + } + if tx.load("nope", "/repo") != nil { + t.Error("a missing transcript should be nil, not empty") + } +} + +// ── windowing ──────────────────────────────────────────────────────────── + +func TestConvWindowIsBounded(t *testing.T) { + turns := make([]Turn, 500) + for i := range turns { + turns[i] = Turn{Role: "assistant", Text: fmt.Sprint(i)} + } + from, got := convWindowAt(turns, -1, false) + if len(got) != convWindow || from != 500-convWindow || got[len(got)-1].Text != "499" { + t.Errorf("unanchored window = %d turns from %d", len(got), from) + } + from, got = convWindowAt(turns, 200, false) + if len(got) != convWindow || from > 200 || from+len(got) <= 200 { + t.Errorf("window %d..%d does not hold turn 200", from, from+len(got)) + } + from, got = convWindowAt(turns, 498, false) + if len(got) != convWindow || from+len(got) != 500 { + t.Errorf("window near the end = %d..%d", from, from+len(got)) + } + if _, got = convWindowAt(turns, 200, true); len(got) != 500 { + t.Errorf("show all gave %d of 500 turns", len(got)) + } + if _, got = convWindowAt(turns[:10], -1, false); len(got) != 10 { + t.Errorf("short conversation was cut to %d", len(got)) + } +} + +// ── the session page ───────────────────────────────────────────────────── + +// sessionServer is testServer with a Claude Code transcript for session s1, +// filed under the repo path the log entries carry. +func sessionServer(t *testing.T) (*server, string) { + t.Helper() + sv, _, _ := testServer(t) + root := t.TempDir() + writeFile(t, filepath.Join(root, mangleDir(sv.repo), "s1.jsonl"), claudeJSONL) + sv.tx = newTranscripts([]string{root}) + return sv, root +} + +func TestSessionPageInterleavesLogAndTranscript(t *testing.T) { + sv, _ := sessionServer(t) + body := get(t, sv.handler(), "/session/s1?note=1", false).Body.String() + for _, want := range []string{ + "read lib.rs and tell me about the cache", // the conversation + "It is a two-level map.", + "notevi read src/lib.rs:1-30", // a tool call, summarized + "read hello.txt:1-2", // the notevi log, woven in + "second line matters", // the note itself + `data-anchor="note-1"`, // and it is what the page lands on + `class="turn t-note here"`, // marked as the anchored moment + } { + if !strings.Contains(body, want) { + t.Errorf("session page is missing %q", want) + } + } + // the whole file is never in the page + if strings.Contains(body, "use std::collections::HashMap;\n2") { + t.Error("a tool result was dumped in full") + } + // ordering: the note was logged after the first message, before the last + iFirst := strings.Index(body, "read lib.rs and tell me") + iNote := strings.Index(body, "second line matters") + iLast := strings.Index(body, "It is a two-level map.") + if !(iFirst < iNote && iNote < iLast) { + t.Errorf("turns are out of order: %d %d %d", iFirst, iNote, iLast) + } +} + +func TestSessionPageWithoutATranscript(t *testing.T) { + sv, _, _ := testServer(t) + sv.tx = newTranscripts([]string{t.TempDir()}) + body := get(t, sv.handler(), "/session/s1", false).Body.String() + if !strings.Contains(body, "no transcript found") { + t.Error("the page does not say the transcript is missing") + } + if !strings.Contains(body, sv.tx.roots[0]) { + t.Error("the page does not say where it looked") + } + if !strings.Contains(body, "read hello.txt:1-2") || !strings.Contains(body, "second line matters") { + t.Error("the notevi timeline is missing from the fallback") + } +} + +func TestSessionPageRejectsUnsafeIDs(t *testing.T) { + sv, _ := sessionServer(t) + h := sv.handler() + if w := get(t, h, "/session/a%20b", false); w.Code != 400 { + t.Errorf("GET /session/a b = %d, want 400", w.Code) + } + if w := get(t, h, "/session/unknown-session", false); w.Code != 200 || + !strings.Contains(w.Body.String(), "no transcript found") { + t.Errorf("unknown session = %d", w.Code) + } +} + +// Live pages link a note to its conversation; the static export has no server +// to serve one from. +func TestConversationLinksAreLiveOnly(t *testing.T) { + sv, _ := sessionServer(t) + h := sv.handler() + if b := get(t, h, "/notes", false).Body.String(); !strings.Contains(b, `href="/session/s1?note=1#note-1"`) { + t.Error("no conversation link on a note card") + } + if b := get(t, h, "/", false).Body.String(); !strings.Contains(b, `href="/session/s1"`) { + t.Error("the agents table does not link the session") + } + if b := get(t, h, "/activity", true).Body.String(); !strings.Contains(b, `href="/session/s1"`) { + t.Error("the activity table does not link the session") + } + if b := get(t, h, "/session/s1?note=1", false).Body.String(); strings.Contains(b, ">conversation<") { + t.Error("the session page links back to itself") + } + static := &page{Root: "../"} + if got := static.ConvHref(&Note{ID: 1, Session: "s1"}); got != "" { + t.Errorf("static conversation href = %q, want none", got) + } +} diff --git a/web/tree.go b/web/tree.go new file mode 100644 index 0000000..85e5536 --- /dev/null +++ b/web/tree.go @@ -0,0 +1,115 @@ +// tree.go — the repository tree, one fragment shared by every page. +package web + +import ( + "fmt" + "html" + "path/filepath" + "strings" +) + +type treeNode struct { + Name string + Dirs []*treeNode + Files []*File + Mask uint8 // union of traced masks underneath + HasNotes bool + HasTraced bool +} + +func aggregate(n *treeNode) { + for _, f := range n.Files { + if f.Traced { + n.HasTraced = true + n.Mask |= f.Mask + if len(f.Notes) > 0 { + n.HasNotes = true + } + } + } + for _, d := range n.Dirs { + aggregate(d) + n.Mask |= d.Mask + n.HasNotes = n.HasNotes || d.HasNotes + n.HasTraced = n.HasTraced || d.HasTraced + } +} + +func buildTree(files []*File) *treeNode { + root := &treeNode{} + for _, f := range files { + parts := strings.Split(f.Path, "/") + node := root + for _, d := range parts[:len(parts)-1] { + var next *treeNode + for _, c := range node.Dirs { + if c.Name == d { + next = c + } + } + if next == nil { + next = &treeNode{Name: d} + node.Dirs = append(node.Dirs, next) + } + node = next + } + node.Files = append(node.Files, f) + } + return root +} + +// treeHTML renders one unified tree: traced files carry coverage bars, dirs +// with traced content underneath get a mixed-color dot (and ◆ for notes) and +// default open. prefix is the dir path so far, used for state persistence; +// link maps a repo path to the href for that file's page. +func treeHTML(b *strings.Builder, n *treeNode, link func(path string) string, prefix string) { + for _, d := range n.Dirs { + dp := d.Name + if prefix != "" { + dp = prefix + "/" + d.Name + } + openAttr, cls := "", "" + if d.HasTraced { + openAttr, cls = " open", ` class="t"` + } + fmt.Fprintf(b, `<details%s%s data-path="%s"><summary>%s`, cls, openAttr, html.EscapeString(dp), html.EscapeString(d.Name)) + if d.HasTraced { + fmt.Fprintf(b, `<span class="dot trace-only am%d"></span>`, d.Mask) + } + if d.HasNotes { + b.WriteString(`<span class="nmark notes-only">◆</span>`) + } + b.WriteString(`</summary>`) + treeHTML(b, d, link, dp) + b.WriteString(`</details>`) + } + if len(n.Files) == 0 { + return + } + b.WriteString("<ul>") + for _, f := range n.Files { + name := html.EscapeString(filepath.Base(f.Path)) + path := html.EscapeString(f.Path) + if !f.Traced { + fmt.Fprintf(b, `<li><a class="file plain" data-path="%s" href="%s">%s</a></li>`, path, html.EscapeString(link(f.Path)), name) + continue + } + noted := "" + if len(f.Notes) > 0 { + noted = " has-notes" + } + fmt.Fprintf(b, + `<li><a class="file am%d%s" data-path="%s" href="%s" style="--pct:%d%%" title="%d%% read, %d notes">%s</a></li>`, + f.Mask, noted, path, html.EscapeString(link(f.Path)), f.Pct, f.Pct, len(f.Notes), name) + } + b.WriteString("</ul>") +} + +// renderTree is the whole fragment for a file set. +func renderTree(files []*File, link func(string) string) string { + root := buildTree(files) + aggregate(root) + var b strings.Builder + treeHTML(&b, root, link, "") + return b.String() +} diff --git a/web/web.go b/web/web.go new file mode 100644 index 0000000..ad7bd9c --- /dev/null +++ b/web/web.go @@ -0,0 +1,245 @@ +// Package web is notevi's reading room: "notevi web" served or exported. +// +// A notevi log records who read what, where, and what they thought about it. +// This package projects that log onto the jj change the code was read at: the repo +// tree with per-agent coverage colors, tree-sitter highlighted sources with +// coverage-tinted line numbers (colors mix where agents overlap), and notes — +// both the ones agents left and the ones you write in the browser. +// +// It runs as a live web app (default) or writes a static export (-out). +// Either way the log is the only state: notes are appended to a private jj +// sidecar, never to the project working copy. +// +// Theme comes from a Zed theme JSON; per-agent colors come from the theme's +// player (collaborator) palette. Every other theme this machine has — Zed's +// and Helix's both — is offered in the picker, previewed as you move through +// it, and remembered in the browser. +package web + +import ( + "embed" + "flag" + "fmt" + "os" + "os/user" + "path/filepath" + "strings" + "time" + + "0x4200.cafe/notevi/sidecar" +) + +//go:embed templates assets +var tfs embed.FS + +// Titles for a single repository's trace and for the dashboard over all of them. +const ( + defaultTitle = "notevi trace" + hubDefaultTitle = "notevi projects" +) + +func fatal(format string, a ...any) { + fmt.Fprintf(os.Stderr, "notevi web: "+format+"\n", a...) + os.Exit(1) +} + +const usageText = `notevi web — the reading room for notevi trace logs. + +notevi logs every file a coding agent reads, greps and notes, one JSON line +each, keyed to the jj change the code was read at. This serves that log: the +repo tree with per-agent read coverage, syntax-highlighted sources, the notes +agents left, the conversation each note was written in, and jj queries. + +usage: + notevi web [-scan-root DIR] [-addr HOST:PORT] [-user NAME] + serve every discovered project from one dashboard; scans ~ by default + notevi web -repo DIR [-addr HOST:PORT] [-user NAME] + serve one repository directly, preserving the original single-project mode + notevi web [-repo DIR] -out DIR [-watch] + write a static copy instead — no server, so no comments, no live + activity, no jj queries; the focus toggle, filters and file finder + still work, and it holds the one change the log points at + +starting on a new project: + 1. open the dashboard; it discovers jj and Git repositories below ~ + 2. initialize colocated jj or start the private sidecar from its explicit + button — no project registry or scan result is written to disk + 3. give the agents notevi and tell them to read with it; constrain/AGENTS.md + in the notevi repo is a drop-in brief that does, and constrain/ enforces it + 4. let them work, then refresh the dashboard when a new repo appears + +A log belongs to one repository. Entries carry the jj change id they were +recorded at, and the site reads the code at those changes, so a log from another +repo has nothing to show here. Point -repo at the repository the agents ran in. + +Notes written in the browser are appended to the same private jj sidecar, +under -user, at the exact change and commit being read. The project working +copy is never changed, and the app keeps no state of its own. + +The sidecar has no bookmark and is local-only. It is not included in a fresh +clone, so back up the jj repository or export the site when the trace matters. + +Session transcripts (the conversation behind a note) are looked up by session +id under -transcripts; Claude Code and Codex are found automatically. + +The site is built with the two themes -theme and -light-theme name. Every +other theme installed on this machine — Zed families and Helix themes both — +is offered in the picker at the bottom of the tree: it previews as you move +through it, and the browser remembers what you settled on. + +flags: +` + +// Main runs the "notevi web" subcommand; args are everything after "web". +func Main(args []string) { + home, err := os.UserHomeDir() + if err != nil { + home = "." + } + fs := flag.NewFlagSet("notevi web", flag.ExitOnError) + repo := fs.String("repo", "", "serve one jj repo directly (with -out, default: current directory)") + scanRoot := fs.String("scan-root", home, "live dashboard root to scan for jj and Git repositories") + addr := fs.String("addr", "127.0.0.1:4200", "address to serve on") + who := fs.String("user", "", "name your browser notes are logged under (default: $USER)") + out := fs.String("out", "", "write a static site here instead of serving") + themePath := fs.String("theme", defaultTheme("dark"), "zed theme json for the dark scheme (default: discovered, else embedded One Dark)") + themeName := fs.String("theme-name", "", "theme name inside the family") + lightPath := fs.String("light-theme", defaultTheme("light"), "zed theme json for the light scheme (default: discovered, else embedded One Light)") + lightName := fs.String("light-theme-name", "", "theme name inside the light family") + title := fs.String("title", defaultTitle, "site title") + roots := fs.String("transcripts", strings.Join(defaultTranscriptRoots(), ","), + "comma-separated roots to look for harness session transcripts in") + watch := fs.Bool("watch", false, "with -out: watch the trace log and rebuild after changes settle") + debounce := fs.Duration("debounce", 10*time.Minute, "quiet period before a watched rebuild") + fs.Usage = func() { + fmt.Fprint(fs.Output(), usageText) + fs.PrintDefaults() + } + fs.Parse(args) + if *debounce < 0 { + fatal("debounce must not be negative") + } + theme := loadTheme(*themePath, *themeName, "dark") + light := loadTheme(*lightPath, *lightName, "light") + themes := newThemeSet(theme, light) + if *out == "" && *watch { + fatal("-watch is for -out builds; the served app already follows the log") + } + + // Explicit -repo and every static export retain the original one-repository + // path. A bare live invocation is the new, stateless project dashboard. + if *repo == "" && *out == "" { + hubTitle := *title + if hubTitle == defaultTitle { + hubTitle = hubDefaultTitle + } + hub, err := newProjectHub(*scanRoot, hubTitle, username(*who), strings.Split(*roots, ","), theme, light, themes) + if err != nil { + fatal("discover projects: %v", err) + } + serveProjects(*addr, hub) + return + } + + repoPath := *repo + if repoPath == "" { + repoPath = "." + } + repoAbs, err := filepath.Abs(repoPath) + if err != nil { + fatal("%v", err) + } + log, err := sidecar.Open(repoAbs) + if err != nil { + fatal("open jj sidecar: %v", err) + } + if *out == "" { + serve(*addr, log, repoAbs, *title, username(*who), strings.Split(*roots, ","), theme, light, themes) + return + } + build := func() { buildSite(log, repoAbs, *out, *title, theme, light, themes) } + build() + if !*watch { + return + } + fmt.Printf("notevi web: watching %s (rebuild after %s without changes)\n", log, *debounce) + watchLog(log, *debounce, build) +} + +func username(flagValue string) string { + if flagValue != "" { + return flagValue + } + if u := os.Getenv("USER"); u != "" { + return u + } + if u, err := user.Current(); err == nil && u.Username != "" { + return u.Username + } + return "web" +} + +// ── watching the log (static export only) ───────────────────────────────── + +func watchLog(log logStore, debounce time.Duration, rebuild func()) { + watchLogUntil(log, debounce, time.Second, nil, rebuild) +} + +func watchLogUntil(log logStore, debounce, poll time.Duration, done <-chan struct{}, rebuild func()) { + state, err := log.Generation() + if err != nil { + fatal("watch %s: %v", log, err) + } + + ticker := time.NewTicker(poll) + defer ticker.Stop() + var timer *time.Timer + var timerC <-chan time.Time + defer func() { + if timer != nil { + timer.Stop() + } + }() + lastStatErr := "" + + for { + select { + case <-done: + return + + case <-ticker.C: + next, err := log.Generation() + if err != nil { + if msg := err.Error(); msg != lastStatErr { + fmt.Fprintf(os.Stderr, "notevi web: watch %s: %v\n", log, err) + lastStatErr = msg + } + continue + } + lastStatErr = "" + if next == state { + continue + } + state = next + if timer == nil { + timer = time.NewTimer(debounce) + timerC = timer.C + } else { + if !timer.Stop() { + select { + case <-timer.C: + default: + } + } + timer.Reset(debounce) + } + fmt.Printf("notevi web: change detected; rebuild scheduled after %s without changes\n", debounce) + + case <-timerC: + fmt.Println("notevi web: rebuilding after trace changes settled") + timer = nil + timerC = nil + rebuild() + } + } +} diff --git a/web/web_test.go b/web/web_test.go new file mode 100644 index 0000000..3986cdc --- /dev/null +++ b/web/web_test.go @@ -0,0 +1,57 @@ +package web + +import ( + "os" + "path/filepath" + "testing" + "time" +) + +func TestWatchLogDebouncesChanges(t *testing.T) { + logPath := filepath.Join(t.TempDir(), "trace.jsonl") + if err := os.WriteFile(logPath, []byte("initial\n"), 0o644); err != nil { + t.Fatal(err) + } + + done := make(chan struct{}) + stopped := make(chan struct{}) + rebuilt := make(chan struct{}, 2) + go func() { + defer close(stopped) + watchLogUntil(newFileLog(logPath), 60*time.Millisecond, 5*time.Millisecond, done, func() { + rebuilt <- struct{}{} + }) + }() + time.Sleep(20 * time.Millisecond) + + if err := os.WriteFile(logPath, []byte("first change\n"), 0o644); err != nil { + t.Fatal(err) + } + time.Sleep(30 * time.Millisecond) + if err := os.WriteFile(logPath, []byte("second change\n"), 0o644); err != nil { + t.Fatal(err) + } + + select { + case <-rebuilt: + t.Fatal("rebuilt before the debounce interval elapsed") + case <-time.After(40 * time.Millisecond): + } + select { + case <-rebuilt: + case <-time.After(200 * time.Millisecond): + t.Fatal("did not rebuild after changes settled") + } + select { + case <-rebuilt: + t.Fatal("multiple changes produced more than one rebuild") + case <-time.After(40 * time.Millisecond): + } + + close(done) + select { + case <-stopped: + case <-time.After(time.Second): + t.Fatal("watcher did not stop") + } +} |
