xonecas.io
8356
Wx

www-xonecas-io / commit 7eb683c

dev server inlines the Rats devnotes script into every page (1012)

Co-Authored-By: Claude Opus 5.5

Sean Caetano Martin2026-11-08 7eb683ceb357124d0ceee73d9ebdf3f2fd57ab6f parent 34ff7e1

4 files changed

cmd/site/devnotes.go+39−0
@@ -0,0 +1,39 @@
1+package main
2+
3+import (
4+ "bytes"
5+ _ "embed"
6+ "net/http"
7+ "os"
8+ "path"
9+ "path/filepath"
10+ "strings"
11+)
12+
13+// devnotesJS is the output of `rat-king devnotes script`: Ctrl+click a page to file a Rats ticket.
14+//
15+//go:embed devnotes.js
16+var devnotesJS []byte
17+
18+// devnotes serves dir like next, with the devnotes script inlined into every HTML page.
19+// Only the dev server uses it, so built pages never carry the script.
20+func devnotes(dir string, next http.Handler) http.Handler {
21+ tag := append(append([]byte("<script>"), devnotesJS...), "</script></body>"...)
22+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
23+ p := path.Clean(r.URL.Path)
24+ if strings.HasSuffix(r.URL.Path, "/") {
25+ p = path.Join(p, "index.html")
26+ }
27+ var b []byte
28+ err := os.ErrNotExist
29+ if strings.HasSuffix(p, ".html") {
30+ b, err = os.ReadFile(filepath.Join(dir, filepath.FromSlash(p)))
31+ }
32+ if err != nil {
33+ next.ServeHTTP(w, r)
34+ return
35+ }
36+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
37+ w.Write(bytes.Replace(b, []byte("</body>"), tag, 1))
38+ })
39+}
cmd/site/devnotes.js+120−0
@@ -0,0 +1,120 @@
1+// Rats devnotes: Ctrl+click anything on this page and write a ticket about it.
2+// It works only on a loopback address, with `rat-king devnotes` running. See
3+// the rats skill. Embed it in development builds only.
4+(() => {
5+ const PORT = 7287;
6+ const LOOPBACK = /^(localhost|127\.0\.0\.1|\[::1\]|.+\.localhost)$/;
7+ if (!LOOPBACK.test(location.hostname) || window.__ratsDevnotes) return;
8+ window.__ratsDevnotes = true;
9+
10+ const NAMED = "li, tr, p, pre, img, video, audio, h1, h2, h3, h4, blockquote, figure, button, a, label, summary, input, textarea, select";
11+ const MAX_TEXT = 600;
12+ let float = null;
13+ const closeFloat = () => {
14+ float?.remove();
15+ float = null;
16+ };
17+
18+ const clickedText = (target) => {
19+ const selection = getSelection();
20+ if (selection?.toString() && selection.containsNode(target, true)) return selection.toString();
21+ const named = target.closest(NAMED);
22+ if (!named) return "";
23+ if (named instanceof HTMLImageElement) return named.alt || "An image";
24+ if (named instanceof HTMLMediaElement) return `A ${named.tagName.toLowerCase()}`;
25+ if ("value" in named && !(named instanceof HTMLButtonElement)) return String(named.value);
26+ return named.innerText || named.getAttribute("aria-label") || "";
27+ };
28+
29+ const nameOf = (element) => {
30+ const classes = typeof element.className === "string" ? element.className.trim().split(/\s+/).filter(Boolean).slice(0, 3) : [];
31+ return element.tagName.toLowerCase() + (element.id ? `#${element.id}` : "") + classes.map((name) => `.${name}`).join("");
32+ };
33+
34+ const contextOf = (target) => {
35+ const clean = clickedText(target).trim().replace(/\s+\n/g, "\n");
36+ const shown = clean.length > MAX_TEXT ? `${clean.slice(0, MAX_TEXT)}…` : clean;
37+ const quote = shown.split("\n").map((line) => `> ${line}`).join("\n");
38+ return `## Context\n\nFiled from \`${location.href}\`, on \`${nameOf(target)}\`.${shown ? `\n\n${quote}` : ""}\n`;
39+ };
40+
41+ const write = (target, x, y) => {
42+ closeFloat();
43+ const context = contextOf(target);
44+ const host = document.createElement("div");
45+ const root = host.attachShadow({ mode: "open" });
46+ root.innerHTML = `<style>
47+ :host { all: initial; position: fixed; z-index: 2147483647; width: 320px; padding: 8px; background: #1c1f22; box-shadow: 0 8px 32px #0009; }
48+ * { font: 13px/1.5 "JetBrains Mono", monospace; color: #d8dcdf; box-sizing: border-box; }
49+ textarea { display: block; width: 100%; height: 80px; padding: 8px 12px; border: 0; outline: 0; resize: none; background: #2a2e32; }
50+ p { margin: 8px 0 0; }
51+ [hidden] { display: none; }
52+ </style><textarea placeholder="What should change?" spellcheck="false" aria-label="New ticket"></textarea><p hidden></p>`;
53+ const note = root.querySelector("textarea");
54+ const message = root.querySelector("p");
55+ const say = (text) => {
56+ message.textContent = text;
57+ message.hidden = false;
58+ };
59+ let sending = false;
60+ const submit = async () => {
61+ const [title = "", ...rest] = note.value.trim().split("\n");
62+ if (!title.trim() || sending) return;
63+ sending = true;
64+ const more = rest.join("\n").trim();
65+ let reply;
66+ try {
67+ reply = await fetch(`http://127.0.0.1:${PORT}/ticket`, {
68+ method: "POST",
69+ headers: { "Content-Type": "application/json" },
70+ body: JSON.stringify({ title: title.trim(), body: more ? `${more}\n\n${context}` : context }),
71+ });
72+ } catch {
73+ sending = false;
74+ return say(`Nothing answers on port ${PORT}. Run rat-king devnotes in the project's folder.`);
75+ }
76+ const answer = await reply.json().catch(() => ({}));
77+ sending = false;
78+ if (!reply.ok) return say(answer.error ?? `The ticket was refused: ${reply.status}`);
79+ note.hidden = true;
80+ say(`Ticket ${answer.id}`);
81+ setTimeout(() => float === host && closeFloat(), 1500);
82+ };
83+ host.addEventListener("keydown", (event) => {
84+ event.stopPropagation();
85+ if (event.key === "Escape") closeFloat();
86+ else if (event.key === "Enter" && !event.shiftKey) {
87+ event.preventDefault();
88+ void submit();
89+ }
90+ });
91+ document.documentElement.append(host);
92+ const { width, height } = host.getBoundingClientRect();
93+ host.style.left = `${Math.max(0, Math.min(x, innerWidth - width))}px`;
94+ host.style.top = `${Math.max(0, Math.min(y, innerHeight - height))}px`;
95+ float = host;
96+ note.focus();
97+ };
98+
99+ // The press itself opens the form: it would clear a selection, a press on an
100+ // image starts a drag that never ends in a click, and a canvas takes the pointer.
101+ const inFloat = (event) => float && event.composedPath().includes(float);
102+ const isTicketClick = (event) => event.ctrlKey && event.button === 0 && !inFloat(event);
103+ const swallow = (event) => {
104+ event.preventDefault();
105+ event.stopPropagation();
106+ };
107+ // Stopped, not prevented: preventing it would cancel the mousedown.
108+ document.addEventListener("pointerdown", (event) => isTicketClick(event) && event.stopPropagation(), true);
109+ document.addEventListener("click", (event) => isTicketClick(event) && swallow(event), true);
110+ document.addEventListener(
111+ "mousedown",
112+ (event) => {
113+ if (inFloat(event)) return;
114+ if (!isTicketClick(event)) return closeFloat();
115+ swallow(event);
116+ write(event.target, event.clientX, event.clientY);
117+ },
118+ true,
119+ );
120+})();
cmd/site/main.go+1−1
@@ -80,7 +80,7 @@ func main() {
8080 addr := fs.String("addr", ":8080", "listen address, on every interface so the host can reach the VM")
8181 fs.Parse(os.Args[2:])
8282 log.Printf("serving %s on %s", *dir, *addr)
83- log.Fatal(http.ListenAndServe(*addr, http.FileServer(http.Dir(*dir))))
83+ log.Fatal(http.ListenAndServe(*addr, devnotes(*dir, http.FileServer(http.Dir(*dir)))))
8484 default:
8585 fmt.Fprintln(os.Stderr, "usage: site import|build|serve [flags]")
8686 os.Exit(2)
tickets/1012-rats-injection-script.md+17−4
@@ -2,17 +2,30 @@
22 id: 1012
33 title: rats injection script
44 type: feature
5-status: todo
5+status: review
66 priority: p2
77 created: 2026-11-08T01:09:27Z
8-updated: 2026-11-08T01:43:50Z
8+updated: 2026-11-08T02:45:41Z
99 source: human
1010 area: site
11-moves: 2026-11-08T01:43:50Z inbox todo drag
11+moves: 2026-11-08T01:43:50Z inbox todo drag; 2026-11-08T02:43:19Z todo doing drag; 2026-11-08T02:45:41Z doing review agent
1212 ---
1313
14-Rats provider a script
14+Rats provides a script, should be in your skill some where or on the cli. It's experimental so let's see if it works
1515
1616 ## Notes
1717
1818 - 2026-11-08 01:09Z (agent): Triage: type feature (it was bug), area site, priority p2 kept. The ticket has only a title so far. I read 'rats injection script' as embedding the 'rat-king devnotes script' snippet in the site's dev builds, so you can Ctrl+click a page to file a ticket. That depends on 1002 (scaffold and dev server). Question: is that what you mean, or is it about something else?
19+
20+- 2026-11-08 02:45Z (agent): Done. The dev server ('make serve' / 'site serve') now inlines the Rats devnotes script before </body> in every HTML page it serves. 'site build' and public/ never carry it.
21+
22+ - cmd/site/devnotes.js: the output of 'rat-king devnotes script', vendored as is.
23+ - cmd/site/devnotes.go: wraps the file server, embeds the script and injects it into .html responses only.
24+
25+ To use it: run 'rat-king devnotes' in this project's folder in a terminal tile, open the site on a loopback address, Ctrl+click anything.
26+
27+ GOTCHA: the script only turns on for localhost/127.0.0.1. On http://192.168.122.10:8080 (the 1013 route) it stays off by design. From the host, use: ssh -L 8080:localhost:8080 -L 7287:localhost:7287 vm, then open http://localhost:8080.
28+
29+ CHECKED (in the VM, headless agent-browser on 127.0.0.1:8080): script loaded, Ctrl+click on the homepage opened the form, Enter sent the request, and with no 'rat-king devnotes' running it replied 'Nothing answers on port 7287'. On 192.168.122.10 it stayed off. curl: /, /projects/ and other .html pages carry it, site.css is unchanged, 404 and ../ traversal still 404, public/ has no copy. go vet and go test pass.
30+
31+ NOT CHECKED: a ticket actually filed through it. That needs 'rat-king devnotes' running and would put a test ticket on your board, so I left that first real one to you. The dev server is running with the change.