Show the project's AGENTS.md on a dashboard tab with in-place links

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-06 13:42:38 -08:00
1 parent d84d6a4690
commit 20a349a3f8
12 files changed
+272 -11

No files matched your search

+26 -2
View File
@@ -64,6 +64,11 @@ function takeMarker(item) {
return TASK_MARKERS[m[1]];
}
// While md() runs with a `link` option: a function that takes a link's href and
// returns a click handler to make it an in-page link, or null to leave it to the
// usual rules. Set only for the duration of one md() call.
let linkHook = null;
function safeHref(href) {
if (!href) return null;
const trimmed = String(href).trim();
@@ -117,6 +122,19 @@ function inlineInto(parent, tokens) {
parent.appendChild(document.createElement("br"));
break;
case "link": {
const onOpen = linkHook && linkHook(String(t.href || "").trim());
if (onOpen) {
const a = el("a");
a.href = "#";
a.addEventListener("click", (e) => {
e.preventDefault();
onOpen();
});
if (t.title) a.title = t.title;
inlineInto(a, t.tokens);
parent.appendChild(a);
break;
}
const href = safeHref(t.href);
if (!href) {
inlineInto(parent, t.tokens);
@@ -288,7 +306,7 @@ function blockInto(parent, tokens) {
}
/** Render markdown into a fresh element. Returns the element. */
export function md(source, className = "md") {
export function md(source, className = "md", options = {}) {
const host = el("div", className);
if (!source) return host;
let tokens;
@@ -298,7 +316,13 @@ export function md(source, className = "md") {
host.appendChild(el("p", "md-p", String(source)));
return host;
}
blockInto(host, tokens);
// `options.link`: see linkHook above.
linkHook = typeof options.link === "function" ? options.link : null;
try {
blockInto(host, tokens);
} finally {
linkHook = null;
}
return host;
}
+15 -4
View File
@@ -54,7 +54,7 @@ import { helperRows, showTab } from "../subagents.js";
import { FOOTER_TIERS, footerLabel } from "../workspace.js";
import {
activity, agentAdrift, agentWorking, askBusy, loopDriving, loopWaiting, loopWaitingKey, asked, awaitingReply, byId, dashboardLive, docs, doingNow,
finish, gitAwaiting, isDashboard, isGitBoard, isOpen, isSpecFileView, items, loadOverview, myTurn, openItems,
AGENTS_VIEW, agentsTabShown, finish, gitAwaiting, isDashboard, isGitBoard, isOpen, isSpecFileView, items, loadAgentsDoc, loadOverview, myTurn, openItems,
patience, pressStranded, reviewPending, scan, selSpec, sendCollected, specFileTabs, stagedCount, stranded,
topics, workingMs, WORKING_GRACE_MS,
workspaceFolders,
@@ -67,7 +67,7 @@ import { attachFiles, heldNotes, noteImages, pendingNotes, removeImage } from ".
import { closeMentions } from "../mention-box.js";
import { buildPager, fitGrowBox, markFor, markMore, renderCard, renderEndItem, renderNotice } from "./cards.js";
import { sendState, suggestState } from "../send-state.js";
import { renderBriefButton, renderDoc, renderOverview } from "./docs.js";
import { renderAgentsDoc, renderBriefButton, renderDoc, renderOverview } from "./docs.js";
import { board, renderGitBoard, resetBoard } from "./git-host.js";
import { renderWorkspace, tellFolderIssues } from "./workspace.js";
import { openHelpOn } from "./help-dialog.js";
@@ -535,6 +535,8 @@ export function adopt(body) {
// A spec file tab's file changes under a build, so a tab you are watching
// refetches on every new frame too, not only on the click that opened it.
if (firstLoad || page.S.specDir !== prevSpecDir || page.S.workflow !== prevWorkflow || isSpecFileView(page.view)) loadOverview();
// The Dashboard's AGENTS.md tab: found on arrival, re-read while it is open.
if (firstLoad || page.S.workflow !== prevWorkflow || page.view === AGENTS_VIEW) loadAgentsDoc();
if (announce) showArrival(announce);
// New entries land at the bottom of the rail. Gliding down to them beats
// leaving the list parked where it was while it grew underneath.
@@ -991,7 +993,7 @@ function withFocus(fn) {
// (the dashboard menu, the end page).
function currentScroller() {
if (!drawnView) return null;
if (drawnView.startsWith("doc:") || isSpecFileView(drawnView)) return $("main");
if (drawnView.startsWith("doc:") || isSpecFileView(drawnView) || drawnView === AGENTS_VIEW) return $("main");
if (drawnView === "questions") return $("main").querySelector(":scope > .card.question");
if (drawnView === "ask") return $("main").querySelector(".ask-list");
return null;
@@ -1430,6 +1432,10 @@ function renderViews() {
const fileTabs = specFileTabs();
for (const f of fileTabs) tabs.push({ id: f.id, label: f.label, count: 0 });
if (isSpecFileView(page.view) && !fileTabs.some((f) => f.id === page.view)) page.view = "questions";
// Right after Dashboard: the project's AGENTS.md, present while the file is.
// Like a spec file tab, it sends the person home if the file goes away.
if (agentsTabShown()) tabs.splice(1, 0, { id: AGENTS_VIEW, label: "AGENTS.md", count: 0 });
else if (page.view === AGENTS_VIEW) page.view = "questions";
for (const d of docs()) tabs.push({ id: "doc:" + d.id, label: d.title || "Document", count: 0 });
// The helpers the agent reported, from the first one on; cleared by a
// dashboard hop, which sends the person home like the Overview tab does.
@@ -1482,6 +1488,10 @@ function renderViews() {
// changed on disk since.
render();
if (isSpecFileView(t.id)) loadOverview();
if (t.id === AGENTS_VIEW) {
page.agentsDoc.open = "AGENTS.md";
loadAgentsDoc();
}
});
nav.appendChild(b);
}
@@ -1616,7 +1626,7 @@ function renderMain() {
}
function paintMain(main) {
main.classList.toggle("is-doc", page.view.startsWith("doc:") || isSpecFileView(page.view));
main.classList.toggle("is-doc", page.view.startsWith("doc:") || isSpecFileView(page.view) || page.view === AGENTS_VIEW);
main.classList.toggle("is-ask", page.view === "ask");
// An agent-less session has no questions, docs or board to draw: its whole
@@ -1625,6 +1635,7 @@ function paintMain(main) {
if (page.view.startsWith("doc:")) return renderDoc(main, page.view.slice(4));
if (isSpecFileView(page.view)) return renderOverview(main, page.view);
if (page.view === AGENTS_VIEW) return renderAgentsDoc(main);
if (page.view === "ask") return renderAsk(main);
if (page.view === "subagents") return renderSubagents(main);
+59 -1
View File
@@ -1,6 +1,6 @@
// Plan2Code Web Console - documents: tabs, blocks, print and download, and the brief button; defines only.
import { docs, agentWorking, workingMs, patience, WORKING_GRACE_MS, finish, SPEC_FILES } from "../selectors.js";
import { docs, agentWorking, workingMs, patience, WORKING_GRACE_MS, finish, SPEC_FILES, loadAgentsDoc } from "../selectors.js";
import { el, md } from "../render.js";
import { downloadDocHtml, docSavedNote, downloadDoc, blockBody } from "../doc-files.js";
import { hooks, page, redraw } from "../state.js";
@@ -239,6 +239,64 @@ export function renderOverview(main, kind = "overview") {
main.appendChild(box);
}
// The files the AGENTS.md tab may show: the same two shapes the server serves.
const AGENTS_FILE = /^(?:AGENTS\.md|\.agents-docs\/[A-Za-z0-9._-]+\.md)$/;
// A link in an agent-guide file, resolved against the file it sits in: the
// guide's own name when it points at another agent-guide file, else null (an
// outside link keeps the usual rules).
export function agentsLinkTarget(from, href) {
if (!href || /^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith("#") || href.startsWith("/")) return null;
try {
const u = new URL(href, "http://guide.invalid/" + from);
const rel = decodeURIComponent(u.pathname.slice(1));
return AGENTS_FILE.test(rel) ? rel : null;
} catch {
return null;
}
}
// The Dashboard's AGENTS.md tab: the project's agent guide, read-only, straight
// from disk. A link to another guide file (.agents-docs/...) opens in place,
// with a way back to AGENTS.md.
export function renderAgentsDoc(main) {
const { open, texts } = page.agentsDoc;
const head = el("div", "doc-head");
head.appendChild(el("h2", null, open === "AGENTS.md" ? "AGENTS.md" : open));
const tools = el("div", "doc-tools");
if (open !== "AGENTS.md") {
const guide = el("button", "btn small", "Back to AGENTS.md");
guide.type = "button";
guide.addEventListener("click", () => {
page.agentsDoc.open = "AGENTS.md";
redraw();
main.scrollTop = 0;
});
tools.appendChild(guide);
}
tools.appendChild(backButton());
tools.appendChild(printButton());
head.appendChild(tools);
main.appendChild(head);
main.appendChild(el("p", "help", open + " · read-only, straight from disk"));
const box = el("div", "block settled");
box.appendChild(
md(texts[open] || "", "md", {
link: (href) => {
const rel = agentsLinkTarget(open, href);
if (!rel) return null;
return () => {
page.agentsDoc.open = rel;
redraw();
main.scrollTop = 0;
loadAgentsDoc();
};
},
})
);
main.appendChild(box);
}
// The brief dialog's buttons, wired once at start-up.
export function wireDocs() {
$("btn-brief").addEventListener("click", openBrief);
+41
View File
@@ -333,5 +333,46 @@ export async function loadOverview() {
if (changed) redraw();
}
// The Dashboard's AGENTS.md tab: its view id, and whether it is on now (the
// dashboard, with an AGENTS.md the last read found).
export const AGENTS_VIEW = "agents-md";
export const agentsTabShown = () => isDashboard() && typeof page.agentsDoc.texts["AGENTS.md"] === "string";
// Read one agent-guide file fresh from disk (`rel` as the server names it) and
// keep its text; null when it is not there. Off the dashboard nothing is read.
async function fetchAgentsDoc(rel) {
try {
const res = await fetch("/agents-doc?file=" + encodeURIComponent(rel), { cache: "no-store" });
return res.status === 200 ? await res.text() : null;
} catch {
return null;
}
}
// Fresh from disk every time, like the spec file tabs: AGENTS.md changes under
// init-update, and the tab is only worth having if it shows what is there now.
// Reads AGENTS.md (does the tab exist?) and, when a linked file is open, that
// file too. Repaints only when a tab would appear or vanish or a text changed.
export async function loadAgentsDoc() {
if (!isDashboard()) {
if (Object.keys(page.agentsDoc.texts).length) page.agentsDoc = { open: "AGENTS.md", texts: {} };
return;
}
const open = page.agentsDoc.open;
const rels = open === "AGENTS.md" ? ["AGENTS.md"] : ["AGENTS.md", open];
const found = await Promise.all(rels.map(fetchAgentsDoc));
// The person moved on (Back to AGENTS.md) while this was in flight.
if (!isDashboard() || page.agentsDoc.open !== open) return;
const texts = {};
rels.forEach((rel, i) => {
if (typeof found[i] === "string") texts[rel] = found[i];
});
// A linked file that went missing: back to AGENTS.md itself.
const next = { open: texts[open] === undefined ? "AGENTS.md" : open, texts };
const changed = JSON.stringify(next) !== JSON.stringify(page.agentsDoc);
page.agentsDoc = next;
if (changed) redraw();
}
// The workspace's folders, original first, or none before a frame has them.
export const workspaceFolders = () => (page.wsFrame && Array.isArray(page.wsFrame.folders) ? page.wsFrame.folders : []);
+4
View File
@@ -136,6 +136,10 @@ export const page = {
// for, `files` maps each SPEC_FILES kind (overview, map, draft) that exists
// to `{ file, text }`. See loadOverview().
overview: { key: null, files: {} },
// The Dashboard's AGENTS.md tab: `texts` maps each agent-guide file read so
// far (AGENTS.md, .agents-docs/<name>.md) to its text, `open` is the one in
// view. The tab exists while texts["AGENTS.md"] does. See loadAgentsDoc().
agentsDoc: { open: "AGENTS.md", texts: {} },
// The dashboard's first-open wake-up (boot.js), while it runs. `cards` turns
// true at the glide, which lets the menu in; `entered` once its entrance has
// played; `typed` is how many characters of the note show, or null once all
+25 -1
View File
@@ -30,7 +30,7 @@ import {
} from "./files.mjs";
import { AGENTS_SCHEMA, makeId, normalizeAgents, resolveCommand, validateForSave } from "./agents.mjs";
import { findAgent, loadAgentList } from "./agent-lookup.mjs";
import { checkDocument, cleanupFindings, readSpecFile, removeCleanup } from "./sessions.mjs";
import { checkDocument, cleanupFindings, readAgentsDoc, readSpecFile, removeCleanup } from "./sessions.mjs";
import { SHOTS_DIR_NAME, SHOT_NAME, shotType } from "./patches.mjs";
import { appendChat, currentConversation, pendingChatCount, typedCount } from "./inbox.mjs";
import { specKey } from "./workspace.mjs";
@@ -85,6 +85,7 @@ const ROUTES = [
{ path: "/", method: "GET", run: page },
{ match: (p, req) => req.method === "GET" && SERVABLE.has(p.slice(1)), run: publicFile },
{ path: "/overview", method: "GET", run: overview },
{ path: "/agents-doc", method: "GET", run: agentsDoc },
{ path: "/handoff", method: "GET", run: handoffDoc },
{ path: "/version", method: "GET", run: version },
{ path: "/state", method: "GET", run: stateGet },
@@ -419,6 +420,29 @@ function overview(req, res, ctx, url) {
.catch(noOverview);
}
// The project's AGENTS.md (or one file under .agents-docs/), read-only, for the
// dashboard's AGENTS.md tab. Only a dashboard serves it, and only the two
// shapes readAgentsDoc() allows; anything else, or a missing file, is a 204
// (no tab) so the browser console stays free of a failed request.
function agentsDoc(req, res, ctx, url) {
const state = ctx.readState() || {};
const none = () => {
res.writeHead(204, baseHeaders({ "cache-control": "no-store" }));
res.end();
};
if (state.workflow !== "dashboard") return none();
readAgentsDoc(state.worktree || state.project, url.searchParams.get("file") || "AGENTS.md")
.then((found) =>
found
? send(res, 200, found.text, "text/markdown; charset=utf-8", {
"cache-control": "no-store",
"x-spec-file": encodeURIComponent(found.file),
})
: none()
)
.catch(none);
}
// A handoff's document, read-only, for the dashboard's "Read it all". Only a
// dashboard serves it, and only an id its own scan listed: a used or unknown
// id, or anything that is not a bare handoff id, is a 404.
+22
View File
@@ -540,6 +540,28 @@ export async function readSpecFile(root, specDir, kind) {
}
}
// The project's agent guide as the Dashboard's AGENTS.md tab shows it: only
// AGENTS.md itself or one markdown file directly under .agents-docs/, never any
// other path. Kept inside the root by realpath, like readSpecFile().
const AGENTS_DOC_RE = /^(?:AGENTS\.md|\.agents-docs\/[A-Za-z0-9._-]+\.md)$/;
/**
* `{ file, text }` for an allowed agent-guide file (`rel` as written, with `/`
* separators), or null when it is not allowed, missing or outside the root.
*/
export async function readAgentsDoc(root, rel) {
if (!root || typeof rel !== "string" || !AGENTS_DOC_RE.test(rel)) return null;
try {
const file = path.resolve(root, ...rel.split("/"));
const [realFile, realRoot] = await Promise.all([fs.promises.realpath(file), fs.promises.realpath(root)]);
const inside = path.relative(realRoot, realFile);
if (!inside || inside === ".." || inside.startsWith(".." + path.sep) || path.isAbsolute(inside)) return null;
return { file: rel, text: await fs.promises.readFile(realFile, "utf8") };
} catch {
return null;
}
}
// The line every CLI command hands the agent to end its terminal messages with.
// Under the desktop app the page is already in the window beside the terminal,
// so the address would only be noise there: the line points at the window.