mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-19 05:11:18 -08:00
Add a Prototypes tab: list a spec's saved prototypes, read an md in place, open an html in a browser
AI Assisted
This commit is contained in:
1 parent
b38f2b987b
commit
ba19f79f1c
16 files changed
+511
-28
No files matched your search
@@ -22,14 +22,29 @@ export function linkToOpen(raw) {
|
||||
|
||||
/** Opens `href` (from linkToOpen) in the default browser; false when it could not start one. */
|
||||
export function openLink(href) {
|
||||
return launch(href, process.env.BROWSER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a local file the server already checked (an absolute path, such as a
|
||||
* saved prototype's .html) with the system's default handler for its type,
|
||||
* which for a web page is the default browser; false when nothing started.
|
||||
*/
|
||||
export function openFile(file) {
|
||||
if (typeof file !== "string" || !file) return false;
|
||||
return launch(file, null);
|
||||
}
|
||||
|
||||
// The system's own opener, handed one target as one argument, never a shell.
|
||||
function launch(target, linuxOpener) {
|
||||
// Tests, and a person who turned the console's own browser launches off.
|
||||
if (process.env.NO_BROWSER || process.env.PLAN2CODE_NO_BROWSER) return true;
|
||||
const [cmd, args] =
|
||||
process.platform === "win32"
|
||||
? ["rundll32.exe", ["url.dll,FileProtocolHandler", href]]
|
||||
? ["rundll32.exe", ["url.dll,FileProtocolHandler", target]]
|
||||
: process.platform === "darwin"
|
||||
? ["open", [href]]
|
||||
: [process.env.BROWSER || "xdg-open", [href]];
|
||||
? ["open", [target]]
|
||||
: [linuxOpener || "xdg-open", [target]];
|
||||
try {
|
||||
const child = spawn(cmd, args, { detached: true, stdio: "ignore", windowsHide: true });
|
||||
child.on("error", () => {});
|
||||
|
||||
@@ -56,6 +56,7 @@ import {
|
||||
activity, agentAdrift, agentWorking, askBusy, loopDriving, loopWaiting, loopWaitingKey, asked, awaitingReply, byId, dashboardLive, docs, doingNow,
|
||||
AGENTS_VIEW, agentsTabShown, finish, gitAwaiting, isDashboard, isGitBoard, isOpen, isSpecFileView, items, loadAgentsDoc, loadOverview, loadSpecCarry, myTurn, openItems,
|
||||
finishKey, overviewSpec, patience, pressStranded, reviewPending, scan, selSpec, sendCollected, specFileTabs, stagedCount, stranded,
|
||||
PROTOTYPES_VIEW, prototypesTabShown, loadPrototypes,
|
||||
topics, workingMs, WORKING_GRACE_MS,
|
||||
workspaceFolders,
|
||||
} from "../selectors.js";
|
||||
@@ -68,7 +69,7 @@ import { closeMentions } from "../mention-box.js";
|
||||
import { destroyFields } from "../md-field.js";
|
||||
import { buildPager, fitGrowBox, markFor, markMore, renderCard, renderEndItem, renderNotice } from "./cards.js";
|
||||
import { sendState, suggestState } from "../send-state.js";
|
||||
import { renderAgentsDoc, renderBriefButton, renderDoc, renderOverview } from "./docs.js";
|
||||
import { renderAgentsDoc, renderBriefButton, renderDoc, renderOverview, renderPrototypes } from "./docs.js";
|
||||
import { board, renderGitBoard, resetBoard } from "./git-host.js";
|
||||
import { renderWorkspace, tellFolderIssues } from "./workspace.js";
|
||||
import { openHelpOn } from "./help-dialog.js";
|
||||
@@ -550,6 +551,7 @@ 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();
|
||||
else if (page.view === PROTOTYPES_VIEW) loadPrototypes();
|
||||
// A New Session in the app leaves the spec it was in; the fresh dashboard picks it up once its scan is here.
|
||||
loadSpecCarry();
|
||||
// The Dashboard's AGENTS.md tab: found on arrival, re-read while it is open.
|
||||
@@ -1030,7 +1032,7 @@ function withFocus(fn) {
|
||||
// (the dashboard menu, the end page).
|
||||
function currentScroller() {
|
||||
if (!drawnView) return null;
|
||||
if (drawnView.startsWith("doc:") || isSpecFileView(drawnView) || drawnView === AGENTS_VIEW) return $("main");
|
||||
if (drawnView.startsWith("doc:") || isSpecFileView(drawnView) || drawnView === AGENTS_VIEW || drawnView === PROTOTYPES_VIEW) return $("main");
|
||||
if (drawnView === "questions") return $("main").querySelector(":scope > .card.question");
|
||||
if (drawnView === "ask") return $("main").querySelector(".ask-list");
|
||||
return null;
|
||||
@@ -1481,6 +1483,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";
|
||||
// After the spec file tabs: the spec's saved prototypes, present while its
|
||||
// prototypes/ folder holds an .md or .html. Gone, it sends the person home.
|
||||
if (prototypesTabShown()) tabs.push({ id: PROTOTYPES_VIEW, label: "Prototypes", count: 0 });
|
||||
else if (page.view === PROTOTYPES_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 });
|
||||
@@ -1533,10 +1539,14 @@ function renderViews() {
|
||||
save();
|
||||
}
|
||||
page.view = t.id === "questions" && finish() ? "end" : t.id;
|
||||
// The tab always opens on the list, so the .md last read there must not
|
||||
// paint first.
|
||||
if (t.id === PROTOTYPES_VIEW) page.prototypes = { ...page.prototypes, open: null, texts: {} };
|
||||
// The cached text paints at once; the fresh read repaints if the file
|
||||
// changed on disk since.
|
||||
render();
|
||||
if (isSpecFileView(t.id)) loadOverview();
|
||||
if (t.id === PROTOTYPES_VIEW) loadPrototypes();
|
||||
if (t.id === AGENTS_VIEW) {
|
||||
page.agentsDoc.open = "AGENTS.md";
|
||||
loadAgentsDoc();
|
||||
@@ -1696,7 +1706,10 @@ function renderMain() {
|
||||
}
|
||||
|
||||
function paintMain(main) {
|
||||
main.classList.toggle("is-doc", page.view.startsWith("doc:") || isSpecFileView(page.view) || page.view === AGENTS_VIEW);
|
||||
main.classList.toggle(
|
||||
"is-doc",
|
||||
page.view.startsWith("doc:") || isSpecFileView(page.view) || page.view === AGENTS_VIEW || page.view === PROTOTYPES_VIEW
|
||||
);
|
||||
main.classList.toggle("is-ask", page.view === "ask");
|
||||
|
||||
// An agent-less session has no questions, docs or board to draw: its whole
|
||||
@@ -1706,6 +1719,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 === PROTOTYPES_VIEW) return renderPrototypes(main);
|
||||
if (page.view === "ask") {
|
||||
const held = heldAsk;
|
||||
heldAsk = null;
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
// 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, loadAgentsDoc } from "../selectors.js";
|
||||
import {
|
||||
docs, agentWorking, workingMs, patience, WORKING_GRACE_MS, finish, SPEC_FILES, loadAgentsDoc, openPrototypeDoc, closePrototypeDoc,
|
||||
} 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";
|
||||
@@ -297,6 +299,70 @@ export function renderAgentsDoc(main) {
|
||||
main.appendChild(box);
|
||||
}
|
||||
|
||||
// A saved prototype page, handed to the server to open in the person's
|
||||
// default browser (the app's webview opens no windows, and a page served over
|
||||
// http cannot open a file:// link). A failure says so on the banner.
|
||||
async function openPrototypePage(spec, name) {
|
||||
const ok = await fetch("/open-prototype", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ spec, name }),
|
||||
})
|
||||
.then((res) => res.ok)
|
||||
.catch(() => false);
|
||||
if (!ok) hooks.banner(`${name} could not open in your browser. Open it from ${spec}/prototypes/ yourself.`, "warn");
|
||||
}
|
||||
|
||||
// The Prototypes tab: the .md and .html files in the spec's prototypes/
|
||||
// folder. An .md opens in place, with a way back to the list (like Back to
|
||||
// AGENTS.md); an .html opens in the default browser.
|
||||
export function renderPrototypes(main) {
|
||||
const { key, files, open, texts } = page.prototypes;
|
||||
const reading = open && typeof texts[open] === "string";
|
||||
const head = el("div", "doc-head");
|
||||
head.appendChild(el("h2", null, reading ? open : "Prototypes"));
|
||||
const tools = el("div", "doc-tools");
|
||||
if (reading) {
|
||||
const list = el("button", "btn small", "Back to Prototypes");
|
||||
list.type = "button";
|
||||
list.addEventListener("click", () => {
|
||||
closePrototypeDoc();
|
||||
main.scrollTop = 0;
|
||||
});
|
||||
tools.appendChild(list);
|
||||
}
|
||||
tools.appendChild(backButton());
|
||||
if (reading) tools.appendChild(printButton());
|
||||
head.appendChild(tools);
|
||||
main.appendChild(head);
|
||||
main.appendChild(el("p", "help", `${key}/prototypes/${reading ? open : ""} · read-only, straight from disk`));
|
||||
if (reading) {
|
||||
const box = el("div", "block settled");
|
||||
box.appendChild(md(texts[open], "md"));
|
||||
main.appendChild(box);
|
||||
return;
|
||||
}
|
||||
const list = el("ul", "proto-list");
|
||||
for (const f of files) {
|
||||
const row = el("li", "proto-row");
|
||||
const b = el("button", "proto-open", null);
|
||||
b.type = "button";
|
||||
b.appendChild(el("span", "proto-kind proto-kind-" + f.kind, f.kind === "md" ? "MD" : "HTML"));
|
||||
b.appendChild(el("span", "proto-name", f.name));
|
||||
b.appendChild(el("span", "proto-how", f.kind === "md" ? "Read it here" : "Opens in your browser ↗"));
|
||||
b.title = f.kind === "md" ? `Read ${f.name} here` : `Open ${f.name} in your default browser`;
|
||||
b.addEventListener("click", () => {
|
||||
if (f.kind === "md") {
|
||||
openPrototypeDoc(f.name);
|
||||
main.scrollTop = 0;
|
||||
} else openPrototypePage(key, f.name);
|
||||
});
|
||||
row.appendChild(b);
|
||||
list.appendChild(row);
|
||||
}
|
||||
main.appendChild(list);
|
||||
}
|
||||
|
||||
// The brief dialog's buttons, wired once at start-up.
|
||||
export function wireDocs() {
|
||||
$("btn-brief").addEventListener("click", openBrief);
|
||||
|
||||
@@ -322,6 +322,8 @@ async function fetchSpecFile(spec, kind) {
|
||||
// is the work already in front of it. Repaints only when a tab would appear,
|
||||
// vanish or show different text.
|
||||
export async function loadOverview() {
|
||||
// The Prototypes tab rides on every reason the spec file tabs re-read.
|
||||
loadPrototypes();
|
||||
const spec = overviewSpec();
|
||||
const kinds = isDashboard() ? SPEC_FILES.map((f) => f.id) : ["overview"];
|
||||
const files = {};
|
||||
@@ -338,6 +340,60 @@ export async function loadOverview() {
|
||||
if (changed) redraw();
|
||||
}
|
||||
|
||||
// The Prototypes tab: present while the spec in view has .md or .html files
|
||||
// in its prototypes/ folder, on the dashboard and in a session alike.
|
||||
export const PROTOTYPES_VIEW = "prototypes";
|
||||
export const prototypesTabShown = () => page.prototypes.key === overviewSpec() && page.prototypes.files.length > 0;
|
||||
|
||||
async function fetchPrototypeList(spec) {
|
||||
try {
|
||||
const res = await fetch("/prototypes?spec=" + encodeURIComponent(spec), { cache: "no-store" });
|
||||
if (res.status !== 200) return [];
|
||||
const body = await res.json();
|
||||
return Array.isArray(body.files) ? body.files : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchPrototypeDoc(spec, name) {
|
||||
try {
|
||||
const res = await fetch("/prototype?spec=" + encodeURIComponent(spec) + "&name=" + encodeURIComponent(name), { cache: "no-store" });
|
||||
return res.status === 200 ? await res.text() : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Fresh from disk every time, like the spec file tabs: the list, and the .md
|
||||
// in view when one is open. A spec switch goes back to the list; an open .md
|
||||
// that went missing goes back to the list too. Repaints only on a change.
|
||||
export async function loadPrototypes() {
|
||||
const spec = overviewSpec();
|
||||
const open = page.prototypes.key === spec ? page.prototypes.open : null;
|
||||
const files = spec ? await fetchPrototypeList(spec) : [];
|
||||
const text = spec && open && files.some((f) => f.name === open) ? await fetchPrototypeDoc(spec, open) : null;
|
||||
// The selection or the open file moved on while this was in flight.
|
||||
if (spec !== overviewSpec() || (page.prototypes.key === spec && page.prototypes.open !== open)) return;
|
||||
const next = { key: spec, files, open: typeof text === "string" ? open : null, texts: typeof text === "string" ? { [open]: text } : {} };
|
||||
const changed = JSON.stringify(next) !== JSON.stringify(page.prototypes);
|
||||
page.prototypes = next;
|
||||
if (changed) redraw();
|
||||
}
|
||||
|
||||
// Open one .md from the list in place.
|
||||
export function openPrototypeDoc(name) {
|
||||
page.prototypes = { ...page.prototypes, open: name };
|
||||
redraw();
|
||||
loadPrototypes();
|
||||
}
|
||||
|
||||
// Back from an .md to the list.
|
||||
export function closePrototypeDoc() {
|
||||
page.prototypes = { ...page.prototypes, open: null, texts: {} };
|
||||
redraw();
|
||||
}
|
||||
|
||||
// A New Session in the desktop app leaves the spec it was in for the fresh
|
||||
// dashboard (spec-carry.mjs). Asked once per page, before the picker is
|
||||
// touched; used only if the picker lists that spec, else the default stands.
|
||||
|
||||
@@ -138,6 +138,11 @@ 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 Prototypes tab: `key` is the spec dir `files` ([{ name, kind }], the
|
||||
// .md and .html in its prototypes/ folder) was read for, `open` the .md in
|
||||
// view (null for the list), `texts` the .md texts read so far. The tab
|
||||
// exists while `files` has any. See loadPrototypes().
|
||||
prototypes: { key: null, files: [], open: null, texts: {} },
|
||||
// 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().
|
||||
|
||||
@@ -40,3 +40,22 @@
|
||||
.doc-saved code { font-family: var(--mono); font-size: 11.5px; color: var(--ink-2); }
|
||||
.doc-head { align-items: center; }
|
||||
|
||||
|
||||
/* ------------------------------------------------------ prototypes tab */
|
||||
|
||||
/* The spec's saved prototypes: one row per .md (read here) or .html (opens
|
||||
in the browser), as wide as a doc. */
|
||||
.proto-list { list-style: none; margin: 0 auto; padding: 0; max-width: min(var(--card-width), 100%); display: grid; gap: 8px; }
|
||||
.proto-open {
|
||||
width: 100%; display: flex; align-items: center; gap: 12px; text-align: left;
|
||||
padding: 12px 14px; border: 1px solid var(--rule); border-radius: 10px;
|
||||
background: var(--panel); color: var(--ink); font: inherit; cursor: pointer;
|
||||
}
|
||||
.proto-open:hover, .proto-open:focus-visible { border-color: var(--accent); background: var(--accent-soft); }
|
||||
.proto-kind {
|
||||
flex: none; min-width: 44px; text-align: center; padding: 3px 6px; border-radius: 6px;
|
||||
font: 700 10.5px/1.2 var(--mono); letter-spacing: 0.05em; border: 1px solid var(--rule-2); color: var(--ink-2);
|
||||
}
|
||||
.proto-kind-html { border-color: var(--accent); color: var(--accent); }
|
||||
.proto-name { flex: 1; min-width: 0; font-weight: 600; overflow-wrap: anywhere; }
|
||||
.proto-how { flex: none; font-size: 12px; color: var(--ink-3); }
|
||||
+59
-17
@@ -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, readAgentsDoc, readSpecFile, removeCleanup } from "./sessions.mjs";
|
||||
import { checkDocument, cleanupFindings, listPrototypes, prototypeHtmlPath, readAgentsDoc, readPrototype, readSpecFile, removeCleanup } from "./sessions.mjs";
|
||||
import { SHOTS_DIR_NAME, SHOT_NAME, shotType, isOpen } from "./patches.mjs";
|
||||
import { appendChat, currentConversation, pendingChatCount, typedCount } from "./inbox.mjs";
|
||||
import { specKey } from "./workspace.mjs";
|
||||
@@ -52,7 +52,7 @@ import { cleanSetting, offered } from "./public/subagents.js";
|
||||
import { DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, accentId, cardWidth } from "./public/palette.js";
|
||||
import { SERVABLE, TYPES, asset } from "./static.mjs";
|
||||
import { handoffsDir, isHandoffId } from "./handoffs.mjs";
|
||||
import { linkToOpen, openLink } from "./open-link.mjs";
|
||||
import { linkToOpen, openFile, openLink } from "./open-link.mjs";
|
||||
import {
|
||||
NotepadError,
|
||||
addImage,
|
||||
@@ -87,6 +87,8 @@ const ROUTES = [
|
||||
{ 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: "/prototypes", method: "GET", run: prototypesList },
|
||||
{ path: "/prototype", method: "GET", run: prototypeDoc },
|
||||
{ path: "/handoff", method: "GET", run: handoffDoc },
|
||||
{ path: "/version", method: "GET", run: version },
|
||||
{ path: "/state", method: "GET", run: stateGet },
|
||||
@@ -121,6 +123,7 @@ const ROUTES = [
|
||||
{ match: (p, req) => p.startsWith("/uploads/") || req.url.startsWith("/uploads/"), run: uploads },
|
||||
{ path: "/submit", method: "POST", origin: true, run: submit },
|
||||
{ path: "/open-link", method: "POST", origin: true, run: openLinkRoute },
|
||||
{ path: "/open-prototype", method: "POST", origin: true, run: openPrototypeRoute },
|
||||
{ path: "/chat", method: "POST", origin: true, run: chat },
|
||||
{ path: "/chat/decision", method: "POST", origin: true, run: chatDecision },
|
||||
{ path: "/workspace", method: "GET", run: workspaceGet },
|
||||
@@ -395,20 +398,11 @@ function renderIndex(ctx) {
|
||||
// project root, and names the file it read in X-Spec-File.
|
||||
function overview(req, res, ctx, url) {
|
||||
const state = ctx.readState() || {};
|
||||
const asked = url.searchParams.get("spec");
|
||||
const kind = url.searchParams.get("file") || "overview";
|
||||
const spec =
|
||||
state.workflow === "dashboard"
|
||||
? (state.scan?.specs || []).some((s) => s && s.dir === asked)
|
||||
? asked
|
||||
: ""
|
||||
: state.specDir;
|
||||
const spec = specInView(state, url.searchParams.get("spec"));
|
||||
// Most specs have no overview.md yet, which is normal, not an error: 204
|
||||
// keeps the browser console free of a failed request per pick.
|
||||
const noOverview = () => {
|
||||
res.writeHead(204, baseHeaders({ "cache-control": "no-store" }));
|
||||
res.end();
|
||||
};
|
||||
const noOverview = () => noContent(res);
|
||||
readSpecFile(state.worktree || state.project, spec, kind)
|
||||
.then((found) =>
|
||||
found
|
||||
@@ -422,16 +416,64 @@ function overview(req, res, ctx, url) {
|
||||
.catch(noOverview);
|
||||
}
|
||||
|
||||
// The spec a spec-file route may read: on a dashboard the one asked for, but
|
||||
// only when its own scan found it; on every other workflow the session's own.
|
||||
function specInView(state, asked) {
|
||||
if (state.workflow !== "dashboard") return state.specDir || "";
|
||||
return (state.scan?.specs || []).some((s) => s && s.dir === asked) ? asked : "";
|
||||
}
|
||||
|
||||
// No file to show: a 204, so the browser console stays free of a failed
|
||||
// request per spec that has none.
|
||||
function noContent(res) {
|
||||
res.writeHead(204, baseHeaders({ "cache-control": "no-store" }));
|
||||
res.end();
|
||||
}
|
||||
|
||||
// The Prototypes tab's list: the .md and .html files in the spec's
|
||||
// prototypes/ folder (listPrototypes() keeps it inside the project), as
|
||||
// { files: [{ name, kind }] }, or a 204 when there are none.
|
||||
function prototypesList(req, res, ctx, url) {
|
||||
const state = ctx.readState() || {};
|
||||
listPrototypes(state.worktree || state.project, specInView(state, url.searchParams.get("spec")))
|
||||
.then((files) => (files.length ? json(res, 200, { files }, { "cache-control": "no-store" }) : noContent(res)))
|
||||
.catch(() => noContent(res));
|
||||
}
|
||||
|
||||
// One .md from the spec's prototypes/ folder, read-only; anything else is a 204.
|
||||
function prototypeDoc(req, res, ctx, url) {
|
||||
const state = ctx.readState() || {};
|
||||
readPrototype(state.worktree || state.project, specInView(state, url.searchParams.get("spec")), url.searchParams.get("name"))
|
||||
.then((found) => (found ? send(res, 200, found.text, "text/markdown; charset=utf-8", { "cache-control": "no-store" }) : noContent(res)))
|
||||
.catch(() => noContent(res));
|
||||
}
|
||||
|
||||
// A saved prototype page, opened in the person's default browser (the app's
|
||||
// webview opens no windows, and a file:// link from an http page is blocked).
|
||||
// The page names only the spec and a bare file name; prototypeHtmlPath()
|
||||
// turns that into a path inside the spec's prototypes/ folder or refuses it,
|
||||
// so nothing else on disk can be opened this way.
|
||||
function openPrototypeRoute(req, res, ctx) {
|
||||
return readBody(req, res, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const state = ctx.readState() || {};
|
||||
prototypeHtmlPath(state.worktree || state.project, specInView(state, body && body.spec), body && body.name)
|
||||
.then((file) => {
|
||||
if (!file) return json(res, 404, { error: "no such prototype page" });
|
||||
if (!openFile(file)) return json(res, 500, { error: "no browser could be started" });
|
||||
return json(res, 200, { ok: true });
|
||||
})
|
||||
.catch(() => json(res, 500, { error: "no browser could be started" }));
|
||||
});
|
||||
}
|
||||
|
||||
// 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();
|
||||
};
|
||||
const none = () => noContent(res);
|
||||
if (state.workflow !== "dashboard") return none();
|
||||
readAgentsDoc(state.worktree || state.project, url.searchParams.get("file") || "AGENTS.md")
|
||||
.then((found) =>
|
||||
|
||||
@@ -600,6 +600,86 @@ export async function readSpecFile(root, specDir, kind) {
|
||||
}
|
||||
}
|
||||
|
||||
// The Prototypes tab: the .md and .html files saved directly in a spec's
|
||||
// prototypes/ folder (a UI prototype's page and its brief). A name never
|
||||
// carries a separator, and every file's realpath must sit inside the folder's,
|
||||
// which must sit inside the root's, so `../`, an absolute path and a link
|
||||
// pointing anywhere else all come back null.
|
||||
const PROTOTYPE_NAME_RE = /^[^\\/:*?"<>|]+\.(md|html?)$/i;
|
||||
const insideOf = (outer, inner) => {
|
||||
const rel = path.relative(outer, inner);
|
||||
return Boolean(rel) && rel !== ".." && !rel.startsWith(".." + path.sep) && !path.isAbsolute(rel);
|
||||
};
|
||||
const prototypeKind = (name) => (/\.md$/i.test(name) ? "md" : "html");
|
||||
|
||||
// The real path of the spec's prototypes/ folder, or null.
|
||||
async function prototypesDir(root, specDir) {
|
||||
if (!root || !specDir || typeof specDir !== "string" || path.isAbsolute(specDir)) return null;
|
||||
try {
|
||||
const [realDir, realRoot] = await Promise.all([
|
||||
fs.promises.realpath(path.resolve(root, specDir, "prototypes")),
|
||||
fs.promises.realpath(root),
|
||||
]);
|
||||
return insideOf(realRoot, realDir) ? realDir : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// The real path of one prototype file of `kind` (md or html), or null.
|
||||
async function prototypeFile(root, specDir, name, kind) {
|
||||
const dir = await prototypesDir(root, specDir);
|
||||
return dir ? fileIn(dir, name, kind) : null;
|
||||
}
|
||||
|
||||
// The real path of `name` (a bare .md or .html name of `kind`) directly in the
|
||||
// already-resolved prototypes folder `dir`, as a regular file, or null.
|
||||
async function fileIn(dir, name, kind) {
|
||||
if (typeof name !== "string" || !PROTOTYPE_NAME_RE.test(name) || prototypeKind(name) !== kind) return null;
|
||||
try {
|
||||
const real = await fs.promises.realpath(path.join(dir, name));
|
||||
if (path.dirname(real) !== dir || !(await fs.promises.stat(real)).isFile()) return null;
|
||||
return real;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The prototype files of a spec as [{ name, kind }] ("md" or "html"), by name; [] when there are none. */
|
||||
export async function listPrototypes(root, specDir) {
|
||||
const dir = await prototypesDir(root, specDir);
|
||||
if (!dir) return [];
|
||||
let names;
|
||||
try {
|
||||
names = await fs.promises.readdir(dir);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const found = await Promise.all(
|
||||
names.filter((n) => PROTOTYPE_NAME_RE.test(n)).map(async (n) => ((await fileIn(dir, n, prototypeKind(n))) ? n : null))
|
||||
);
|
||||
return found
|
||||
.filter(Boolean)
|
||||
.sort((a, b) => a.localeCompare(b, "en", { sensitivity: "base" }))
|
||||
.map((name) => ({ name, kind: prototypeKind(name) }));
|
||||
}
|
||||
|
||||
/** `{ file, text }` for one .md in the spec's prototypes/ folder, or null. */
|
||||
export async function readPrototype(root, specDir, name) {
|
||||
const real = await prototypeFile(root, specDir, name, "md");
|
||||
if (!real) return null;
|
||||
try {
|
||||
return { file: name, text: await fs.promises.readFile(real, "utf8") };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The real path of one .html (or .htm) in the spec's prototypes/ folder, or null. */
|
||||
export async function prototypeHtmlPath(root, specDir, name) {
|
||||
return prototypeFile(root, specDir, name, "html");
|
||||
}
|
||||
|
||||
// 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().
|
||||
|
||||
Reference in new issue
Block a user