layerfs 0.10.0: the page's live channel returns, out of the install's own folder (#441)

LayerFS's trajectory page is served by a loopback service the host starts once a store exists (no write into the install), keeps its view in location.hash across its 5 s reload, reports every skipped secret-shaped file in sorted order (#477), and drops the unloaded sample. By @Mola-maker.

Run at dfa99f7e merged onto current main:
- mote (macOS, Bun 1.4.2, temp HOME): bun test in packages/layerfs, 64 pass 0 fail, 2 of 2; bun scripts/check.mjs layerfs ok; the temp HOME held nothing from layerfs afterwards.
- WSL2 Ubuntu 24.04 (temp HOME): 64 pass 0 fail, 2 of 2 (#477's item 3 was red here on f3633eaf8).
- Broken by hand: dropping the `location.hash =` assignment in page/app.js turns the hash test red. Earlier rounds' breaks (Origin/Host checks, < escape, start gates, nosniff, sort, restore/settle/round, reload guard) each went red, see the 05:18 and 05:45 reviews.
- Earlier round: the page in a magpie-shaped sandboxed frame with pagePolicy CSP, Chromium and WebKit.
- PR checks: test and on-npm pass.
Not tried: a real magpie window.
This commit is contained in:
mola
2026-10-29 21:07:14 +08:00
committed by GitHub
parent a06512e0b9
commit 443c808517
16 changed files with 895 additions and 115 deletions
+79 -13
View File
@@ -165,21 +165,54 @@ draws its own outline and fills in, a publish pops its Layer badge
easing; with reduced motion preferred, the page simply shows the
finished picture, every icon fully drawn.
A magpie page cannot read plugin-private data: its sandbox forbids
fetch, and the bridge's reads are a fixed host list (`usage:summary`,
`providers:list`) with no entry a plugin can serve its own data
through. So the page animates the sample bundled with it —
`page/trajectory.js`, a labeled recording from the benchmark scenario
(one project, six agents, three checkpoints each), a package asset
that nothing rewrites at runtime. The trajectory itself is computed
on demand from the store's records whenever it is asked for
(`backend.trajectory()`; `tools/gen-trajectory.mjs` uses it to make
the sample). No recording file is maintained per tool call: an
A magpie page cannot fetch, and the bridge's reads are a fixed host
list (`usage:summary`, `providers:list`) with no entry a plugin can
serve its own data through — but magpie lets a page navigate its
frame elsewhere, and pulls a plugin's host part up the moment its
page is requested, waiting up to 7 seconds for it (pageHost /
plugin.Warm). So the page's live channel is the host's own
localhost-only service (`page-service.mjs`), the way page-chat
serves its chat page:
- **The installed page only jumps.** `page/index.html` does one
thing: it reads the port from the plugin's options
(`pagePort`, default 43717) and `location.replace`s its frame to
`http://127.0.0.1:<port>/`. The install's folder is never
renamed, linked, or written into. A user with no store gets no
service and nothing written anywhere.
- **The service returns the page with its data inside.** Each
request rebuilds `backend.trajectory()` on demand and answers one
route, GET /, as HTML: the trajectory UI with the recording
embedded as `<script type="application/json" id="data">`, which
the page reads from the DOM — never by fetch. The page reloads
itself every few seconds, keeping its view across each reload (the
project, the scroll, and the replay position ride in
`location.hash`), so the picture stays live. With no store there
is no service at all, so the frame shows the browser's
refused-to-connect page until the first project is provisioned;
a store with no recorded checkpoints yet shows the page's honest
empty state.
- **The service is closed to other sites.** It emits no CORS
headers and refuses any request carrying an Origin (a sandboxed
iframe's fetch sends `Origin: null`); it serves no `.js` data
file another site could `<script src>` — only `text/html` with
`X-Content-Type-Options: nosniff`; and it checks Host, answering
only `127.0.0.1:<port>` and `localhost:<port>`, so a
DNS-rebinding name is refused. Another site can at most frame
the page; it cannot read it.
- **An Agent activity table** under the replay lists every recorded
tool call — the calling agent, the tool, the project, the branch and
the time, newest last. With no recorded calls the table gives way
to an empty note; all four locales carry the strings.
`backend.trajectory()` itself is computed on demand from the store's
records whenever it is asked for (`tools/gen-trajectory.mjs` uses it
to make the sample). No recording file is maintained in the store: an
earlier version refreshed one in the store after every call, which
cost a branch-chain walk per call — growing with the project's
history — for a file the page cannot read, so the refresh was
removed in 0.7.1. The page declares no `magpie.read` permissions,
and its test asserts it asks for none.
history — for a file the page cannot read, so the refresh was removed
in 0.7.1. The page declares no `magpie.read` permissions, and its
test asserts it asks for none.
## Develop
@@ -195,6 +228,39 @@ node tools/gen-trajectory.mjs # regenerate the page's bundled sample trajector
Zero runtime dependencies; the arguments are JSON Schema, like the other
tools packages. MIT.
## Changes in 0.10.0
The page's live channel comes back, out of the plugin's own folder. The
0.9.0 review was right that nothing may write into the installed
package's folder — an update replaces that folder, two hosts with one
install race on the same file, and an install can be read-only — but its
conclusion, a page that only ever shows the bundled sample, threw away
the real trajectory every desktop had been watching. This version
answers both sides at once, the way page-chat serves its page:
- **The host serves the page itself.** The installed `page/` is
never renamed, linked, or written into: `page/index.html` only
navigates its frame to a localhost-only service the host starts
(`page-service.mjs`, port `pagePort`, default 43717), which
returns the trajectory UI with the live recording embedded in
the HTML. The page reloads itself every few seconds, so the
picture stays live without any file channel.
- **The page gains an Agent activity table** — every recorded tool
call, with the calling agent, the tool, the project, the branch and
the time — so each round's work is visible per agent, not only as
commits on a graph.
- **The service starts only once a store exists** (two read-only
gates: a projects folder that holds entries, and a non-empty
answer from the backend that will serve the calls), so an upgrade
shows the user's real work on the first open, and a user with no
store gets no service and nothing written anywhere.
- `startPageService` lives in `page-service.mjs`, not the entry
module: the plugin host takes every function the entry exports for
an OpenCode plugin factory and calls it at load, so the entry
exports `LayerfsTools` alone (the standalone repo shipped 0.10.0
with the helper in the entry and the whole plugin failed to load
— this is that lesson, applied here from the start).
## Changes in 0.9.0
The registry package is sim-only now. The native backend — the
+10
View File
@@ -0,0 +1,10 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<!-- tools-layerfs: LayerFS workspaces. Leaf-green tile, white leaf in
the shape of LayerFS's own leaf glyph (page/view.js LEAF_GLYPH,
scaled x2), with a forked vein inside it: the branch splitting,
the trajectory page's bough motif. Flat shapes only; the leaf
silhouette carries recognition down to 16 px. -->
<rect x="2" y="2" width="60" height="60" rx="14" fill="#16a34a"/>
<path d="M32 11 C48 19 52 39 32 53 C12 39 16 19 32 11 Z" fill="#ffffff"/>
<path d="M32 50 L32 32 M32 32 C28 27 25 25 22 21 M32 32 C36 27 39 25 42 21" fill="none" stroke="#16a34a" stroke-width="3" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 702 B

+53 -14
View File
@@ -4,19 +4,22 @@
// agent copies no file bytes; a checkpoint stores only what changed.
// Arguments are JSON Schema, so the package needs no dependency.
//
// The page shows the trajectory bundled with the package (page/trajectory.js,
// a labeled sample): the tools never write into the plugin's install
// folder, so no runtime live file exists there — an update replaces
// that folder, two hosts sharing one install would race on the file,
// and an install can be read-only. The live trajectory stays available
// through the tools (history, status) and through backend.trajectory().
// See the README's page section.
// The page's data channel: the plugin host's own localhost-only service
// (page-service.mjs). A magpie page cannot fetch and cannot read
// plugin-private files, so the installed page/index.html only navigates
// its frame to the service, which embeds backend.trajectory() — the
// page's real commits, branches, storage and dedup accounting, with the
// real calling agent on each — in the HTML it returns. The service
// starts only once a store exists; see the README's page section.
//
// Backend: a local content-addressed store with the LayerFS model, in
// layerfs.mjs. The native backend (the real LayerFS SDK) is not shipped
// in this registry package — the SDK is still not published to npm —
// and returns once the plugin can pin it as a dependency. See the README.
import { checkBranch, checkInnerPath, checkProject, checkSourceDir, createBackend } from "./layerfs.mjs"
import { readdirSync } from "node:fs"
import { join } from "node:path"
import { checkBranch, checkInnerPath, checkProject, checkSourceDir, createBackend, storeHome } from "./layerfs.mjs"
import { resolvePagePort, startPageService } from "./page-service.mjs"
const str = (v, name) => {
if (typeof v !== "string" || !v) throw new Error(`${name} is a non-empty string`)
@@ -34,16 +37,52 @@ const callingAgent = (ctx) => {
return typeof a === "string" && a.trim() ? a.trim().slice(0, 40) : ""
}
// ---- the page's live channel: the host's own service ---------------------
// The service starts once per plugin instance, and only once a store
// exists — two read-only gates, so a user with no store gets no service
// and nothing written anywhere: a projects folder that holds entries
// (not merely exists; the backend's constructor mkdirs it), and a
// non-empty answer from the backend that will serve the calls. A host
// whose store gains its first project later starts the service after
// the call that created it (mutate, below). The start is off the tool
// calls' path and every failure is swallowed: a held port or a failed
// read leaves the tools untouched, and the page's redirect simply finds
// nothing listening.
export const LayerfsTools = async (ctx = {}, options = {}) => {
let backendPromise
const backend = () => (backendPromise ??= createBackend(process.env, options))
const execEnabled = () => options?.exec === true || process.env.MAGPIE_LAYERFS_EXEC === "1"
// A call touches only the state its own operation needs. Reads (history,
// resolve, status) change nothing and refresh nothing.
// resolve, status) change nothing and start nothing.
const call = async (fn) => {
const b = await backend()
return fn(b)
}
// The page's service, started once: the gates above, then a listen on
// the configured port (options.pagePort, MAGPIE_LAYERFS_PAGE_PORT,
// else the default). A second call while the first service lives is
// a no-op; a failed start stays failed for this instance, quietly.
let service = null
const ensureService = async () => {
if (service) return
let hasEntries = false
try { hasEntries = readdirSync(join(storeHome(), "projects")).length > 0 } catch { /* no store yet */ }
if (!hasEntries) return
let data
try { data = await (await backend()).trajectory() } catch { return }
if (!data.projects.length) return
service = startPageService({ backend: await backend(), port: resolvePagePort(options) })
}
ensureService().catch(() => { /* no service: the tools are untouched */ })
// A mutating call may have created the store's first project: offer
// the service its start, off the call's path.
const mutate = async (fn) => {
const b = await backend()
const out = await fn(b)
ensureService().catch(() => { /* never on the tool call's path */ })
return out
}
return {
tool: {
@@ -75,7 +114,7 @@ export const LayerfsTools = async (ctx = {}, options = {}) => {
if (args.source === undefined) throw new Error(
"source is required: the directory to import when the project is first created — pass the directory the user chose for this project")
const source = checkSourceDir(str(args.source, "source"), { configDir: ctx.directory })
return call((b) => b.provision(project, branch, source, callingAgent(callCtx)))
return mutate((b) => b.provision(project, branch, source, callingAgent(callCtx)))
},
},
checkpoint: {
@@ -96,7 +135,7 @@ export const LayerfsTools = async (ctx = {}, options = {}) => {
async execute(args, callCtx) {
const project = checkProject(str(args.project, "project"))
const branch = checkBranch(opt(args.branch, "branch", "main"))
return call((b) => b.checkpoint(project, branch, opt(args.message, "message", ""), callingAgent(callCtx)))
return mutate((b) => b.checkpoint(project, branch, opt(args.message, "message", ""), callingAgent(callCtx)))
},
},
fork: {
@@ -116,7 +155,7 @@ export const LayerfsTools = async (ctx = {}, options = {}) => {
const project = checkProject(str(args.project, "project"))
const branch = checkBranch(str(args.branch, "branch"))
const from = checkBranch(opt(args.from, "from", "main"))
return call((b) => b.fork(project, branch, from, callingAgent(callCtx)))
return mutate((b) => b.fork(project, branch, from, callingAgent(callCtx)))
},
},
publish: {
@@ -136,7 +175,7 @@ export const LayerfsTools = async (ctx = {}, options = {}) => {
async execute(args, callCtx) {
const project = checkProject(str(args.project, "project"))
const branch = checkBranch(str(args.branch, "branch"))
return call((b) => b.publish(project, branch, { force: args.force === true, agent: callingAgent(callCtx) }))
return mutate((b) => b.publish(project, branch, { force: args.force === true, agent: callingAgent(callCtx) }))
},
},
exec: {
@@ -168,7 +207,7 @@ export const LayerfsTools = async (ctx = {}, options = {}) => {
const command = str(args.command, "command")
const message = args.message === undefined ? "" : str(args.message, "message")
const timeoutMs = args.timeoutMs === undefined ? 50000 : Number(args.timeoutMs) || 50000
return call((b) => b.exec(project, branch, command, message, timeoutMs, callingAgent(callCtx)))
return mutate((b) => b.exec(project, branch, command, message, timeoutMs, callingAgent(callCtx)))
},
},
history: {
+17 -5
View File
@@ -224,7 +224,11 @@ function walkSourceFiles(dir) {
}
}
walk(dir, "")
return { files, skipped }
// Sorted, not readdir order: readdirSync returns the file system's
// own order (ext4's hash order on Linux, sorted on APFS), and the
// caller reports this list — an unsorted one made the report differ
// by OS, dropping a different name on each (#477).
return { files, skipped: skipped.sort() }
}
// The sim backend's import scan: a manifest { rel: { sha, size, mode } }
@@ -353,11 +357,16 @@ export function defaultRoot(home = homedir()) {
// ---- sim backend ---------------------------------------------------------------
// The store's root: MAGPIE_LAYERFS_HOME moves it, otherwise defaultRoot's
// move-once rule decides (~/.layerfs-tools). The one copy of this rule —
// the backend and the page's startup check read it here.
export const storeHome = () => process.env.MAGPIE_LAYERFS_HOME || defaultRoot()
export class SimBackend {
kind = "sim"
constructor(root) {
this.root = root || process.env.MAGPIE_LAYERFS_HOME || defaultRoot()
this.root = root || storeHome()
this.objectsDir = join(this.root, "store", "objects")
this.projectsDir = join(this.root, "projects")
this.workspacesDir = join(this.root, "workspaces")
@@ -582,7 +591,9 @@ export class SimBackend {
...(created.created ? { projectCreated: true } : {}),
...(created.skipped?.length ? {
importSkipped: created.skipped.length,
skippedSecrets: created.skipped.slice(0, 5),
// every skipped name, sorted (see walkSourceFiles): the old
// slice(0, 5) dropped a different sixth name on each OS.
skippedSecrets: created.skipped,
} : {}),
}
}
@@ -753,8 +764,9 @@ export class SimBackend {
// of every call grew with the history, for a file the page cannot
// read (its bridge serves a fixed host list) and nothing else did
// (round-2 review, item 3). Removed in 0.7.1: no tool call creates
// or updates a trajectory.json anymore. The page keeps its bundled
// sample until the host can serve plugin data to a page.
// or updates a trajectory.json anymore. The page is served by the
// host with its data embedded (page-service.mjs); the bundled
// sample it once shipped is gone.
async resolve(project, branch = "main", inner = "") {
const headId = this.head(project, branch)
+207 -6
View File
@@ -4,6 +4,8 @@ import {
chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync,
rmSync, statSync, symlinkSync, writeFileSync,
} from "node:fs"
import { get as httpGet } from "node:http"
import { createServer as netServer, connect as netConnect } from "node:net"
import { homedir, tmpdir } from "node:os"
import { basename, dirname, join } from "node:path"
import { LayerfsTools } from "./index.mjs"
@@ -33,6 +35,12 @@ afterAll(() => {
Object.assign(process.env, envSnapshot)
}, 120_000)
// Suite hygiene (0.10.0 review, item 3): no test may touch the real
// HOME — the first test calls LayerfsTools with no env at all, so the
// suite pins a scratch home before any test runs; simTools still gives
// each test its own home.
process.env.MAGPIE_LAYERFS_HOME = mkTmp("layerfs-suite-home-")
function fixture() {
const src = mkTmp("layerfs-src-")
mkdirSync(join(src, "docs"), { recursive: true })
@@ -48,18 +56,84 @@ async function simTools(opts = { exec: true }) {
process.env.MAGPIE_LAYERFS_HOME = home
process.env.MAGPIE_LAYERFS_BACKEND = "sim"
delete process.env.MAGPIE_LAYERFS_EXEC
delete process.env.MAGPIE_LAYERFS_EXEC2
delete process.env.MAGPIE_LAYERFS_INSTALL_DIR
delete process.env.MAGPIE_LAYERFS_DATA_DIR
delete process.env.MAGPIE_LAYERFS_PAGE_DIR
delete process.env.MAGPIE_LAYERFS_PAGE_PORT
// Each instance gets its own service port: the host starts one per
// LayerfsTools(), and two instances sharing a port would leave the
// second silently serviceless.
const port = await freePort()
const src = fixture()
// ctx.directory is magpie's CONFIG directory in the real host — the
// harness models it as its own temp dir, never the source
const { tool } = await LayerfsTools({ directory: mkTmp("magpie-config-") }, opts)
const { tool } = await LayerfsTools({ directory: mkTmp("magpie-config-") }, { ...opts, pagePort: port })
// provision's source is a required argument since 0.7.0: the wrapper
// passes the fixture explicitly, the way a caller now must
const call = (name, args) => tool[name].execute(
name === "provision" && args.source === undefined ? { ...args, source: src } : args,
{ agent: "test", abort: AbortSignal.timeout(5000) })
return { call, home, src, tool }
return { call, home, src, tool, port, url: `http://127.0.0.1:${port}/` }
}
// A port nothing holds right now: bind 0, read it back, let go. The
// window between release and the service's bind is small, and a test
// that polls the service fails loudly if it ever loses the race.
const freePort = () => new Promise((resolve, reject) => {
const s = netServer()
s.once("error", reject)
s.listen(0, "127.0.0.1", () => { const p = s.address().port; s.close(() => resolve(p)) })
})
// Poll the service until its embedded trajectory holds the expected
// state: the service starts off the tool calls' path, so a test that
// needs it waits for the state, not for a fixed duration.
async function serviceData(url, want, ms = 8000) {
const deadline = Date.now() + ms
for (;;) {
try {
const res = await fetch(url)
if (res.ok) {
const html = await res.text()
const m = html.match(/<script type="application\/json" id="data">(.*?)<\/script>/s)
if (m) {
const data = JSON.parse(m[1])
if (want(data)) return { data, html }
}
}
} catch { /* the service is not up yet */ }
if (Date.now() > deadline) throw new Error("the service never served the expected state")
await new Promise((r) => setTimeout(r, 50))
}
}
// One GET with caller-chosen headers: the Origin check's own test
// needs the header set, which fetch would also do — but this keeps the
// status, headers and body together for the assertions.
const get = (url, headers = {}) => new Promise((resolve, reject) => {
const req = httpGet(url, { headers }, (res) => {
let body = ""
res.on("data", (c) => (body += c))
res.on("end", () => resolve({ status: res.statusCode, headers: res.headers, body }))
})
req.on("error", reject)
req.end()
})
// One raw request with an explicit Host header: a client library would
// overwrite it with the target, and the Host check's test needs the
// header to say something other than the loopback it connects to.
const rawRequest = (port, host, path = "/") => new Promise((resolve, reject) => {
let buf = ""
const sock = netConnect(port, "127.0.0.1", () => {
sock.write(`GET ${path} HTTP/1.1\r\nHost: ${host}\r\nConnection: close\r\n\r\n`)
})
sock.on("data", (c) => (buf += c))
sock.on("end", () => resolve(buf))
sock.on("error", reject)
})
test("gives eight tools, each with a JSON Schema and an execute", async () => {
const { tool } = await LayerfsTools({})
expect(Object.keys(tool).sort()).toEqual(["checkpoint", "exec", "fork", "history", "provision", "publish", "resolve", "status"])
@@ -311,7 +385,10 @@ test("item 3: an import skips secret-shaped files and reports them", async () =>
const ws = await call("provision", { project: "website" })
expect(ws.files).toBe(4) // only the fixture's real files
expect(ws.importSkipped).toBe(6) // .env, docs/.env.local, .git, id_rsa, cert.pem, sub/.ssh
expect(ws.skippedSecrets).toContain(".env")
// the full sorted list, not a containment check: the old slice(0, 5)
// dropped whichever name readdir order put sixth, so this passed on
// APFS and failed on ext4 (#477)
expect(ws.skippedSecrets).toEqual([".env", ".git", "cert.pem", "docs/.env.local", "id_rsa", "sub/.ssh"])
expect(existsSync(join(ws.path, ".env"))).toBe(false)
expect(existsSync(join(ws.path, "id_rsa"))).toBe(false)
expect(existsSync(join(ws.path, ".git"))).toBe(false)
@@ -355,8 +432,6 @@ test("the registry package ships the sim backend only; native is refused, never
test("item 8 + r2 item 3: no trajectory file in the store, and no tool call writes into the page folder", async () => {
const pageDir = join(import.meta.dir, "page")
const pageFile = join(pageDir, "trajectory.js")
const before = readFileSync(pageFile, "utf8")
const listedBefore = readdirSync(pageDir).sort()
const { call, home } = await simTools()
await call("provision", { project: "website" })
@@ -364,7 +439,6 @@ test("item 8 + r2 item 3: no trajectory file in the store, and no tool call writ
const feat = await call("provision", { project: "website", branch: "feat" })
writeFileSync(join(feat.path, "f.txt"), "f\n")
await call("checkpoint", { project: "website", branch: "feat", message: "work" })
expect(readFileSync(pageFile, "utf8")).toBe(before) // the shipped sample is untouched (item 8)
// the registry review's install-folder rule: a run of mutating calls
// leaves the page folder exactly as shipped — no live file, no tmp file
expect(readdirSync(pageDir).sort()).toEqual(listedBefore)
@@ -617,3 +691,130 @@ test("#360: a legacy root the user made a link is used where it is", () => {
expect(defaultRoot(home)).toBe(join(home, LEGACY_ROOT))
expect(existsSync(join(home, DEFAULT_ROOT))).toBe(false)
})
// ---- 0.10.0: the page is served by the host's own localhost service ----
// The 0.9.0 review holds: nothing writes into the installed plugin's own
// folder — no live file, no link, no rename. The host serves the page
// itself (page-service.mjs): the installed page/index.html only
// navigates its frame to it, and the service embeds backend.trajectory()
// in the HTML it returns. The tests below drive the service over HTTP
// the way a browser would, and the install folder is asserted untouched
// by the run.
test("0.10.0: the service serves the live trajectory, and tool calls write nothing into the package's page folder", async () => {
const { call, url } = await simTools()
const before = readdirSync(join(import.meta.dir, "page")).sort()
await call("provision", { project: "website" })
const { data, html } = await serviceData(url, (x) => !!x.projects.find((p) => p.name === "website"))
expect(data.projects.at(-1).name).toBe("website")
expect(html).toContain('id="graph"')
expect(html).toContain("location.reload()") // the page refreshes itself for liveness
// the answer's shape: HTML only, no-store, nosniff, and no CORS
const res = await fetch(url)
expect(res.status).toBe(200)
expect(res.headers.get("content-type")).toContain("text/html")
expect(res.headers.get("x-content-type-options")).toBe("nosniff")
expect(res.headers.get("cache-control")).toContain("no-store")
expect(res.headers.get("access-control-allow-origin")).toBeNull()
// the package's own page folder is exactly as it was: no live file,
// no link, nothing renamed in or out
expect(readdirSync(join(import.meta.dir, "page")).sort()).toEqual(before)
const st = lstatSync(join(import.meta.dir, "page"))
expect(st.isSymbolicLink()).toBe(false)
expect(st.isDirectory()).toBe(true)
}, 30000)
test("0.10.0: the service refuses cross-origin reads, foreign hosts, and non-root routes", async () => {
const { call, url, port } = await simTools()
await call("provision", { project: "website" })
await serviceData(url, (x) => !!x.projects.find((p) => p.name === "website"))
// a sandboxed iframe's fetch sends Origin: null; a real site's sends
// its own origin — both are refused, and neither gets CORS headers
for (const origin of ["null", "https://evil.example"]) {
const r = await get(url, { origin })
expect(r.status).toBe(403)
expect(r.headers["access-control-allow-origin"]).toBeUndefined()
}
// a DNS-rebinding name arrives with the attacker's Host
const evil = await rawRequest(port, `evil.example:${port}`)
expect(evil).toMatch(/^HTTP\/1\.1 403/)
// the loopback names pass, as does a plain navigation (no Origin)
const local = await rawRequest(port, `localhost:${port}`)
expect(local).toMatch(/^HTTP\/1\.1 200/)
const plain = await get(url)
expect(plain.status).toBe(200)
// there is no .js data file to steal, and no asset route at all
for (const p of ["trajectory-live.js", "app.js", "view.js", "style.css", "trajectory.html"]) {
expect((await get(`${url}${p}`)).status).toBe(404)
}
}, 30000)
test("0.10.0: a commit message cannot break out of the embedded data script", async () => {
const { call, url } = await simTools()
const evil = "x</script><script>alert(1)</script>y"
await call("provision", { project: "website" })
await call("checkpoint", { project: "website", message: evil })
const { data, html } = await serviceData(url,
(x) => (x.projects.find((p) => p.name === "website")?.branches.find((b) => b.name === "main")?.commits ?? [])
.some((c) => c.message === evil))
// the breakout is escaped in the raw HTML, and parses back whole
expect(html).not.toContain("</script><script>alert(1)")
const commit = data.projects.find((p) => p.name === "website").branches
.find((b) => b.name === "main").commits.find((c) => c.message === evil)
expect(commit.message).toBe(evil)
}, 30000)
test("0.10.0: the served trajectory carries per-agent tool-call events", async () => {
const { call, url } = await simTools()
await call("provision", { project: "website" })
await call("fork", { project: "website", branch: "claude", from: "main" })
const ws = await call("provision", { project: "website", branch: "claude" })
writeFileSync(join(ws.path, "x.txt"), "x\n")
await call("checkpoint", { project: "website", branch: "claude", message: "agent work" })
// wait for the checkpoint this test asserts — the one on the claude
// branch — not for any write or any event that happens to arrive
const { data } = await serviceData(url,
(d) => (d.events ?? []).some((e) => e.kind === "checkpoint" && e.branch === "claude"))
// each event names the calling agent, the tool kind, project, branch and time
const e = data.events.filter((x) => x.kind === "checkpoint").at(-1)
expect(e.agent).toBe("test")
expect(e.project).toBe("website")
expect(e.branch).toBe("claude")
expect(typeof e.t).toBe("string")
// provision events carry the workspace path
const p = data.events.find((x) => x.kind === "provision")
expect(p.path).toContain("website")
}, 30000)
test("0.10.0: the service starts only once a store exists — empty or foreign folders start nothing", async () => {
const home = mkTmp("layerfs-home-")
process.env.MAGPIE_LAYERFS_HOME = home
process.env.MAGPIE_LAYERFS_BACKEND = "sim"
delete process.env.MAGPIE_LAYERFS_INSTALL_DIR
delete process.env.MAGPIE_LAYERFS_DATA_DIR
delete process.env.MAGPIE_LAYERFS_PAGE_DIR
// (a) a projects folder holding nothing: no service, and the backend
// is never built — its constructor is what creates the rest of the store
mkdirSync(join(home, "projects"))
const portA = await freePort()
await LayerfsTools({ directory: mkTmp("magpie-config-") }, { pagePort: portA })
await new Promise((r) => setTimeout(r, 300))
await expect(fetch(`http://127.0.0.1:${portA}/`)).rejects.toThrow()
expect(existsSync(join(home, "store"))).toBe(false)
// (b) an entry that is no project: the backend's own answer decides,
// so nothing listens
writeFileSync(join(home, "projects", "not-a-project.txt"), "x")
const portB = await freePort()
await LayerfsTools({ directory: mkTmp("magpie-config-") }, { pagePort: portB })
await new Promise((r) => setTimeout(r, 300))
await expect(fetch(`http://127.0.0.1:${portB}/`)).rejects.toThrow()
// (c) a real project: one instance provisions it, and a fresh instance
// on the same home serves it from the factory call, no tool call needed
const portD = await freePort()
const { tool } = await LayerfsTools({ directory: mkTmp("magpie-config-") }, { pagePort: portD })
await tool.provision.execute({ project: "website", source: fixture() }, { agent: "test", abort: AbortSignal.timeout(5000) })
const portE = await freePort()
await LayerfsTools({ directory: mkTmp("magpie-config-") }, { pagePort: portE })
const { data } = await serviceData(`http://127.0.0.1:${portE}/`, (x) => !!x.projects.find((p) => p.name === "website"))
expect(data.projects.at(-1).name).toBe("website")
}, 30000)
+4
View File
@@ -11,6 +11,10 @@ import { createBackend } from "./layerfs.mjs"
const envSnapshot = { ...process.env }
const dirs = []
const mk = (p) => { const d = mkdtempSync(join(tmpdir(), p)); dirs.push(d); return d }
// Suite hygiene (0.10.0 review, item 3): no test may touch the real
// HOME — the first test calls LayerfsTools with no env at all, so the
// suite pins a scratch home before any test runs.
process.env.MAGPIE_LAYERFS_HOME = mk("lfs-suite-home-")
// The cleanup's time grows with the machine's disk load, not with the
// suite: on a loaded box removing every dir took over bun's default 5s
// hook bar (#362), so the hook carries its own.
+7 -3
View File
@@ -6,8 +6,10 @@
"files": [
"index.mjs",
"layerfs.mjs",
"page-service.mjs",
"page",
"README.md"
"README.md",
"icon.svg"
],
"keywords": [
"magpie",
@@ -23,8 +25,10 @@
],
"license": "MIT",
"magpie": {
"icon": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2NCA2NCI+CiAgPCEtLSB0b29scy1sYXllcmZzOiBMYXllckZTIHdvcmtzcGFjZXMuIExlYWYtZ3JlZW4gdGlsZSwgd2hpdGUgbGVhZiBpbgogICAgICAgdGhlIHNoYXBlIG9mIExheWVyRlMncyBvd24gbGVhZiBnbHlwaCAocGFnZS92aWV3LmpzIExFQUZfR0xZUEgsCiAgICAgICBzY2FsZWQgeDIpLCB3aXRoIGEgZm9ya2VkIHZlaW4gaW5zaWRlIGl0OiB0aGUgYnJhbmNoIHNwbGl0dGluZywKICAgICAgIHRoZSB0cmFqZWN0b3J5IHBhZ2UncyBib3VnaCBtb3RpZi4gRmxhdCBzaGFwZXMgb25seTsgdGhlIGxlYWYKICAgICAgIHNpbGhvdWV0dGUgY2FycmllcyByZWNvZ25pdGlvbiBkb3duIHRvIDE2IHB4LiAtLT4KICA8cmVjdCB4PSIyIiB5PSIyIiB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHJ4PSIxNCIgZmlsbD0iIzE2YTM0YSIvPgogIDxwYXRoIGQ9Ik0zMiAxMSBDNDggMTkgNTIgMzkgMzIgNTMgQzEyIDM5IDE2IDE5IDMyIDExIFoiIGZpbGw9IiNmZmZmZmYiLz4KICA8cGF0aCBkPSJNMzIgNTAgTDMyIDMyIE0zMiAzMiBDMjggMjcgMjUgMjUgMjIgMjEgTTMyIDMyIEMzNiAyNyAzOSAyNSA0MiAyMSIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMTZhMzRhIiBzdHJva2Utd2lkdGg9IjMiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIvPgo8L3N2Zz4K",
"options": {
"exec": false
"exec": false,
"pagePort": 43717
},
"page": {
"file": "page/index.html",
@@ -45,5 +49,5 @@
"directory": "packages/layerfs"
},
"type": "module",
"version": "0.9.0"
"version": "0.10.0"
}
+162
View File
@@ -0,0 +1,162 @@
// The page's live channel, second shape: the plugin host's own
// localhost-only service (page-service.mjs, not the entry module — the
// plugin host takes every function the entry exports for an OpenCode
// plugin factory and calls it with the host's context at load, so the
// entry exports LayerfsTools alone).
//
// Why a service, not a file. A magpie page runs in an iframe with
// sandbox allow-scripts and CSP connect-src 'none': fetch, XHR and
// WebSocket are all refused, and files are readable only from the
// plugin's own install folder (inside()). The previous shape worked
// around that by pointing the installed page/ at a data folder beside
// the store — a junction on Windows, a symlink elsewhere — but the
// install's folder is not ours to rename or link: an update replaces
// it, two hosts race on it, and it can be read-only. This shape keeps
// the install untouched: the host serves the trajectory page itself,
// and the installed page/index.html only navigates its frame to it
// (page/boot.js, the way page-chat does it). magpie pulls the host up
// the moment the page is requested and waits up to 7 seconds for it
// (pageHost / plugin.Warm), so the service is there by the time the
// frame lands.
//
// The service starts only once a store exists (index.mjs's gates: a
// projects folder holding entries, and a backend answering real
// projects). A user with no store gets no service, no files, nothing
// written under ~.
//
// Security — the trajectory names workspace paths and file contents,
// and any website can point a sandboxed iframe at 127.0.0.1, so:
// - no CORS headers are ever emitted, and any request carrying an
// Origin header is refused: the only legitimate caller is a
// navigation, which carries no Origin. A sandboxed iframe's fetch
// sends Origin: null; a real site's sends its own origin. Both are
// refused, and without CORS headers a fetch could not read an
// answer even if one were sent.
// - there is exactly one route, GET /, returning text/html with
// X-Content-Type-Options: nosniff. No .js data file exists for
// another site to <script src> — the data rides inside the HTML as
// <script type="application/json" id="data">, and the page reads it
// from the DOM, never by fetch.
// - the Host header must be 127.0.0.1:<port> or localhost:<port>:
// a DNS-rebinding name resolving to 127.0.0.1 arrives with the
// attacker's Host and is refused.
// - the embedded JSON escapes < as \u003c, so a commit message
// containing </script> cannot break out of the data script.
// - Cache-Control: no-store, so each reload (the page reloads itself
// every few seconds for liveness) re-asks and gets fresh data.
import { createServer } from "node:http"
import { readFileSync } from "node:fs"
import { dirname, join } from "node:path"
import { fileURLToPath } from "node:url"
// The default port, shared with page/boot.js's fallback (a static file
// cannot import it): the user may move it in the plugin's options
// (pagePort), and MAGPIE_LAYERFS_PAGE_PORT moves it for a test run.
export const DEFAULT_PAGE_PORT = 43717
export function resolvePagePort(options = {}, env = process.env) {
for (const raw of [options?.pagePort, env.MAGPIE_LAYERFS_PAGE_PORT]) {
const n = Number(raw)
if (Number.isInteger(n) && n > 0 && n < 65536) return n
}
return DEFAULT_PAGE_PORT
}
const htmlLang = (lang) => {
const l = String(lang || "").toLowerCase()
if (l.startsWith("ja")) return "ja"
if (/^(zh-tw|zh-hk|zh-hant)/.test(l)) return "zh-TW"
if (l.startsWith("zh")) return "zh"
return "en"
}
// Compose the served page from the shell and the UI files beside it:
// the shell carries two markers, one for the style, one for the
// scripts. Everything is inlined — the service has no asset routes to
// probe — and the data script sits before the UI scripts that read it.
function compose(pageDir, data, lang) {
const shell = readFileSync(join(pageDir, "trajectory.html"), "utf8")
const css = readFileSync(join(pageDir, "style.css"), "utf8")
const view = readFileSync(join(pageDir, "view.js"), "utf8")
const app = readFileSync(join(pageDir, "app.js"), "utf8")
if (!shell.includes("<!-- layerfs:style -->") || !shell.includes("<!-- layerfs:scripts -->"))
throw new Error("trajectory.html is missing its injection markers")
const json = JSON.stringify(data).replace(/</g, "\\u003c")
const theme = JSON.stringify({ lang: String(lang || "").slice(0, 20) }).replace(/</g, "\\u003c")
return shell
.replace('<html lang="en">', `<html lang="${htmlLang(lang)}">`)
.replace("<!-- layerfs:style -->", `<style>${css}</style>`)
.replace("<!-- layerfs:scripts -->",
`<script>globalThis.LayerfsTheme = ${theme};</script>` +
`<script type="application/json" id="data">${json}</script>` +
`<script>${view}</script><script>${app}</script>`)
// No reload script here: the page owns its own liveness tick (see
// app.js) — it must write the view into location.hash and skip the
// reload while the replay runs or the menu stands open, and a blind
// timer appended here would reset the view every 5 s regardless.
}
// Start the service. backend answers trajectory(); port is the
// configured port (0 asks the OS for a free one, for tests). The
// returned listening promise resolves to { port, url } once bound, or
// null when the bind fails — a held port leaves no service, and the
// tools are untouched. close() stops the server.
export function startPageService({ backend, port, pageDir }) {
const dir = pageDir ?? join(dirname(fileURLToPath(import.meta.url)), "page")
const server = createServer(async (req, res) => {
const send = (code, body) => {
res.writeHead(code, {
"Content-Type": "text/html; charset=utf-8",
"X-Content-Type-Options": "nosniff",
"Cache-Control": "no-store",
})
res.end(body)
}
const err = (code, text) => send(code, `<!doctype html><title>LayerFS</title><p>${text}</p>`)
// The bound port, not the requested one: a test's port 0 binds
// elsewhere, and a Host naming the requested port must not pass.
const actual = server.address()?.port
if (!actual) { err(503, "not listening"); return }
const host = String(req.headers.host || "").toLowerCase()
if (host !== `127.0.0.1:${actual}` && host !== `localhost:${actual}`) {
err(403, "this service answers only its own loopback names")
return
}
if (req.headers.origin !== undefined) {
err(403, "this service answers navigations, not cross-origin reads")
return
}
let path = "", lang = ""
try {
const u = new URL(req.url, "http://127.0.0.1")
path = u.pathname
lang = u.searchParams.get("lang") || ""
} catch { /* a malformed target is not a route */ }
if (req.method !== "GET" || path !== "/") { err(404, "no such route"); return }
let data
try { data = await backend.trajectory() } catch { err(500, "the trajectory could not be read"); return }
let html
try { html = compose(dir, data, lang) } catch { err(500, "the page could not be composed"); return }
send(200, html)
})
server.on("error", () => { /* a held port or a refused bind: no service */ })
// Unref: a listening server must not keep a test process (or a host
// that is otherwise done) alive on its own — it still answers while
// the process lives for other reasons.
if (typeof server.unref === "function") server.unref()
const listening = new Promise((resolve) => {
server.once("listening", () => {
const p = server.address().port
resolve({ port: p, url: `http://127.0.0.1:${p}/` })
})
server.once("error", () => resolve(null))
})
server.listen(port, "127.0.0.1")
return {
server,
port,
url: `http://127.0.0.1:${port}/`,
listening,
close: () => new Promise((r) => server.close(() => r())),
}
}
+72 -10
View File
@@ -19,24 +19,34 @@ test("the package declares the page magpie shows", () => {
expect(p.file).toBe("page/index.html")
expect(p.icon).toBe("page/icon.svg")
expect(pkg.files).toContain("page")
for (const f of ["index.html", "app.js", "view.js", "style.css", "icon.svg"])
expect(pkg.files).toContain("page-service.mjs")
for (const f of ["index.html", "boot.js", "trajectory.html", "app.js", "view.js", "style.css", "icon.svg"])
expect(existsSync(join(page, f))).toBe(true)
const html = read("index.html")
expect(html).toContain("_magpie/bridge.js") // the host serves the bridge beside every page
expect(html).toContain('src="trajectory.js"')
expect(html).not.toContain("trajectory-live.js") // no runtime live file: the tools never write into the install folder
// the page sandbox forbids inline scripts and any fetch; the only
// data script is the bundled sample trajectory shipped with the page
// the installed page only jumps: it loads the bridge and the boot
// script, and nothing else — no data scripts, no inline scripts
expect(html).toContain('src="boot.js"')
expect(html).not.toContain('src="trajectory.js"')
expect(html).not.toContain('src="trajectory-live.js"')
expect(html).not.toMatch(/<script>(?!\s*src)/)
// the shell the service composes carries the UI and two injection
// markers, and no scripts of its own
const shell = read("trajectory.html")
expect(shell).toContain('id="graph"')
expect(shell).toContain("<!-- layerfs:style -->")
expect(shell).toContain("<!-- layerfs:scripts -->")
expect(shell).not.toMatch(/<script/)
})
test("item 13: the page reads only what package.json declares — nothing — and reaches no network", () => {
// the ecosystem's convention, as the usage page's test states it: the
// set of magpie.read names in the page's scripts equals the declared
// permissions, and no script has a way out of the frame. This page
// declares no permissions: its data is the bundled sample, because
// the bridge's reads are a fixed host list with no plugin-private
// entry (see the README's page section).
// declares no permissions: the installed page only navigates away
// (boot.js, via location.replace — the one network action a page
// like this has), and the served page reads its data from the DOM,
// never by fetch (see the README's page section).
expect(pkg.magpie.permissions).toBeUndefined()
const reads = new Set()
for (const f of readdirSync(page).filter((f) => f.endsWith(".js"))) {
@@ -66,7 +76,7 @@ test("item 14: every locale the package declares page titles for has a full stri
})
test("item 16: the detail card marks its branch with a dot, and the picker is a menu, not a select", () => {
const html = read("index.html")
const html = read("trajectory.html")
expect(html).not.toContain("<select")
expect(html).toContain('id="projBtn"')
expect(html).toContain('id="projList"')
@@ -164,7 +174,7 @@ test("branches name their agent by token, in that agent's colour", () => {
})
test("the page's stat tiles and speed seg are in the markup, magpie-style", () => {
const html = read("index.html")
const html = read("trajectory.html")
expect(html).toContain('class="tiles"')
for (const id of ["nCommits", "tBranches", "vCopies", "vStored", "tDedup", "vSaved"])
expect(html).toContain(`id="${id}"`)
@@ -344,3 +354,55 @@ test("a checkpoint's detail line carries its delta and byte split", () => {
expect(d.delta).toContain("~2 modified")
expect(V.detail(project.branches[1].commits[1], "zh").delta).toContain("新增")
})
test("a reload restores the project, scroll and replay position from location.hash", () => {
// the codec round-trips, including a project name that needs escaping
const hash = V.formatViewHash({ project: "my site", scrollY: 99, playhead: 2.5 })
expect(hash).toBe("#p=my%20site&y=99&t=2.5")
expect(V.parseViewHash(hash)).toEqual({ project: "my site", scrollY: 99, playhead: 2.5 })
// nothing usable in the hash: a plain first look, replay from the start
expect(V.parseViewHash("")).toBeNull()
expect(V.parseViewHash("#y=99")).toBeNull()
expect(V.parseViewHash("#p=demo&y=abc&t=xyz")).toEqual({ project: "demo", scrollY: 0, playhead: 0 })
const second = { name: "api", branches: [{ name: "main", commits: [C("x1", null, "2026-01-01T00:01:00.000Z")] }] }
const projects = [project, second]
// no hash, or a hash naming a project that is gone: no restore
expect(V.resolveRestoredView(projects, "", false)).toBeNull()
expect(V.resolveRestoredView(projects, "#p=ghost&y=10&t=1", false)).toBeNull()
// the second project, mid-replay, scrolled: restored paused, not replayed
const mid = V.resolveRestoredView(projects, "#p=api&y=99&t=0.5", false)
expect(mid).toEqual({ project: "api", scrollY: 99, playhead: 0.5, settled: false })
// a finished replay settles on the final state instead of replaying
const done = V.resolveRestoredView(projects, "#p=demo&y=0&t=5", false)
expect(done).toEqual({ project: "demo", scrollY: 0, playhead: 5, settled: true })
// data shrank since the hash was written: the playhead clamps, settled
const shrunk = V.resolveRestoredView(projects, "#p=api&y=0&t=9", false)
expect(shrunk).toEqual({ project: "api", scrollY: 0, playhead: 1, settled: true })
// reduced motion settles whatever the hash says
const rm = V.resolveRestoredView(projects, "#p=api&y=40&t=0.5", true)
expect(rm).toEqual({ project: "api", scrollY: 40, playhead: 1, settled: true })
// and the page wires it in: the fresh document reads the hash before
// its first show, and the liveness tick writes the hash before it
// reloads — skipping the reload while the replay runs or the menu
// stands open — instead of the old blind 5 s timer.
const app = read("app.js")
expect(app).toContain("resolveRestoredView")
expect(app).toContain("formatViewHash")
expect(app).toContain("location.hash")
expect(app).toContain("location.reload()")
expect(app).toContain("playing || !projList.hidden")
expect(app).toContain("scrollTo")
// the assignment itself, not just the names: keeping the format call
// but dropping the write to location.hash must fail this test
expect(app).toMatch(/location\.hash = V\.formatViewHash/)
// byte counts are whole again: the mid-count fractions are gone
expect(V.bytes(3.164870684975676)).toBe("3 B")
expect(V.bytes(1500)).toBe("1.5 KB")
})
test("the service no longer appends its own blind reload timer", () => {
const svc = readFileSync(join(dir, "page-service.mjs"), "utf8")
expect(svc).not.toContain("setTimeout(() => location.reload(), 5000)")
})
+86 -11
View File
@@ -9,13 +9,14 @@
// counters count up along the same easing magpie itself uses
// (--ease, cubic-bezier(.2,.8,.2,1)).
//
// The data is the trajectory bundled with the package (trajectory.js,
// a labeled sample from the benchmark run). A magpie page cannot read
// plugin-private data: the bridge's reads are a fixed host list
// (usage:summary, providers:list), and the sandbox allows no fetch.
// The tools therefore never write a live file into the plugin's
// install folder; the live trajectory stays available through the
// tools (history, status) and backend.trajectory().
// The data is the trajectory the host service embedded in this page
// (<script type="application/json" id="data">): the service reads it
// from the store on every request, so a reload is always current. A
// page opened without the service — the bundled sample defining
// globalThis.LayerfsTrajectory — still works from that global. A
// magpie page cannot read plugin-private data: the bridge's reads are
// a fixed host list (usage:summary, providers:list), and the sandbox
// allows no fetch, so the service, not a file, is the channel.
(async () => {
const V = globalThis.LayerfsView;
const $ = (id) => document.getElementById(id);
@@ -25,7 +26,12 @@
const PULSE_MS = 650;
let theme = { lang: "en", dark: matchMedia("(prefers-color-scheme: dark)").matches };
try { theme = (await magpie.ready) || theme; } catch { /* standalone preview */ }
// The service hands the language over as LayerfsTheme (the served
// page is outside magpie, so magpie.ready is not there to ask); a
// page still inside magpie asks magpie.ready as before.
const preset = globalThis.LayerfsTheme
if (preset && typeof preset.lang === "string" && preset.lang) theme.lang = preset.lang
else try { theme = (await magpie.ready) || theme; } catch { /* standalone preview */ }
const lang = theme.lang || "en";
const t = V.text(lang);
document.querySelectorAll("[data-t]").forEach((e) => { e.textContent = t[e.dataset.t]; });
@@ -43,15 +49,52 @@
(V.agentOf(branch) || {}).color ||
(lane === 0 ? mainColor() : series()[(lane - 1) % series().length]);
const data = globalThis.LayerfsTrajectory;
// The embedded recording first; the bundled sample's global second.
const embedded = document.getElementById("data");
let data = null;
if (embedded) {
try { data = JSON.parse(embedded.textContent); } catch { /* a broken embed shows the empty state */ }
}
if (!data) data = globalThis.LayerfsTrajectory;
const projects = (data && data.projects || []).filter((p) => p.branches.some((b) => b.commits.length));
if (!projects.length) {
$("stage").hidden = true; $("controls").hidden = true; $("stats").hidden = true;
$("stage").hidden = true; $("controls").hidden = true; $("stats").hidden = true; $("agents").hidden = true;
$("empty").hidden = false; $("empty").textContent = t.noData;
return;
}
$("stamp").textContent = data.sample ? t.sample : `${t.recorded} ${String(data.generatedAt || "").replace("T", " ").slice(0, 19)} · ${data.backend || ""}`;
// Agent activity: every recorded tool call, newest last, each naming
// the calling agent, the tool, the project, the branch and when. The
// events arrive in the service's embedded trajectory; with none
// recorded the table gives way to an empty note.
{
const events = (data.events || []).slice(-40);
const section = $("agents"), rows = $("agentRows"), emptyMsg = $("agentsEmpty");
section.hidden = false;
if (!events.length) {
$("agentTable").hidden = true;
emptyMsg.hidden = false;
emptyMsg.textContent = t.agentsEmpty;
} else {
$("agentTable").hidden = false;
emptyMsg.hidden = true;
for (const e of events) {
const tr = document.createElement("tr");
const cells = [
e.agent || "—", e.kind || "—", e.project || "—", e.branch || "—",
String(e.t || "").replace("T", " ").slice(0, 19),
];
for (const c of cells) {
const td = document.createElement("td");
td.textContent = c;
tr.append(td);
}
rows.append(tr);
}
}
}
// the project picker: a magpie-style menu (a button and a listbox),
// not a native <select> — magpie's own UI never uses one
let currentProject = projects[0].name;
@@ -459,5 +502,37 @@
$("statsLine").textContent =
`${t.stats} · ${t.dedupe} ${totals.dedupRatio ?? "–"}× · ${t.stored} ${V.bytes(totals.storedBytes)} / ${V.bytes(totals.logicalBytes)}`;
show(projects[0].name);
// A reload restores the view the old document left in location.hash
// (see view.js): the project, the scroll, and the replay position —
// paused, not replayed. Without a hash this is a plain first look
// and the replay runs.
const restored = V.resolveRestoredView(projects, location.hash, RM);
show(restored ? restored.project : projects[0].name, !!restored);
if (restored) {
playhead = (restored.settled || RM) ? view.stepsList.length : restored.playhead;
render();
if (restored.scrollY) window.scrollTo(0, restored.scrollY);
}
// Liveness: the page reloads itself every few seconds so the picture
// stays current — but never in the middle of a look. While the
// replay runs or the project menu stands open the tick waits and
// tries again; otherwise it writes the view into the hash first, so
// the fresh document restores exactly this look instead of starting
// over at the first project, the top, and the replay's beginning.
// A reload-only-when-changed tick is not possible in the frame: the
// sandbox allows no fetch, so the page cannot learn whether the
// trajectory moved without reloading — and the service must not
// answer cross-origin reads. The hash is the whole channel.
function armReload() { setTimeout(reloadTick, 5000); }
function reloadTick() {
if (playing || !projList.hidden) { armReload(); return; }
location.hash = V.formatViewHash({
project: currentProject,
scrollY: Math.round(window.scrollY || 0),
playhead,
});
location.reload();
}
armReload();
})();
+42
View File
@@ -0,0 +1,42 @@
// The way in: this page's only job is to navigate its frame to the
// plugin host's own localhost service (page-service.mjs), the way
// page-chat's boot.js does it.
//
// It must jump directly, never probe first: the page's CSP is
// connect-src 'none', so no network probe of any kind is possible —
// even a no-cors probe is rejected, and a probe could never tell
// whether the service is up. The only network action a page like this
// has is navigating elsewhere.
//
// The port comes from the plugin's options (pagePort), falling back to
// the service's default (page-service.mjs's DEFAULT_PAGE_PORT — a
// static file cannot import it, so the number is repeated here and the
// two must match). A second host on the same machine fails to bind and
// leaves its page pointing at the first host's service, which serves
// the same store — the same behaviour page-chat relies on.
//
// The language rides along as a query: the served page is no longer
// inside magpie, so it cannot ask magpie.ready for it. The service
// hands it to the UI as LayerfsTheme; the theme itself stays with the
// system media query, which the served page's CSS already follows.
(async () => {
const DEFAULT_PORT = 43717
let port = DEFAULT_PORT
let lang = ""
try {
const t = await window.magpie?.ready
if (t && typeof t.lang === "string") lang = t.lang
} catch { /* no bridge: the service falls back to English */ }
try {
const o = await window.magpie?.options?.get?.()
const n = Number(o?.pagePort)
if (Number.isInteger(n) && n > 0 && n < 65536) port = n
} catch { /* no options: the default port */ }
const q = new URLSearchParams()
if (lang) q.set("lang", lang)
const qs = q.toString()
location.replace(`http://127.0.0.1:${port}/${qs ? `?${qs}` : ""}`)
})()
+14 -51
View File
@@ -4,58 +4,21 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>LayerFS trajectory</title>
<link rel="stylesheet" href="style.css">
<script src="_magpie/bridge.js"></script>
<script src="trajectory.js"></script>
<script src="view.js"></script>
<script src="app.js" defer></script>
<style>
:root { color-scheme: light dark; }
html, body { margin: 0; height: 100%; }
body {
display: grid; place-items: center;
font: 13px/1.5 var(--magpie-font, -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif);
background: var(--magpie-bg, Canvas); color: var(--magpie-fg, CanvasText);
}
.box { text-align: center; color: var(--magpie-muted, GrayText); }
.box b { display: block; color: var(--magpie-fg, CanvasText); font-size: 14px; margin-bottom: 4px; }
</style>
</head>
<body>
<header>
<div class="hist">
<h1 id="histLine">HISTORY</h1>
<p class="hist-meta" id="histMeta"></p>
</div>
<div class="menu" id="projectMenu" hidden>
<button type="button" id="projBtn" aria-haspopup="listbox" aria-expanded="false"></button>
<div class="menu-list" id="projList" role="listbox" aria-label="project" hidden></div>
</div>
<p class="stamp" id="stamp"></p>
</header>
<section class="stats" id="stats">
<div class="tiles">
<div class="tile"><span class="k" data-t="checkpointsK">Checkpoints</span><span class="v" id="nCommits">0 / 0</span></div>
<div class="tile"><span class="k" data-t="branchesK">Branches</span><span class="v" id="tBranches">0</span></div>
<div class="tile"><span class="k" data-t="asCopies">as copies</span><span class="v" id="vCopies">0 B</span></div>
<div class="tile"><span class="k" data-t="stored">stored</span><span class="v" id="vStored">0 B</span></div>
<div class="tile"><span class="k" data-t="dedupe">dedupe</span><span class="v" id="tDedup">–</span><span class="s saved" id="vSaved"></span></div>
</div>
<div class="bar-row"><span class="bar-label" data-t="asCopies">as copies</span><div class="bar"><i id="barCopies" class="copies"></i></div></div>
<div class="bar-row"><span class="bar-label" data-t="stored">stored</span><div class="bar"><i id="barStored" class="stored"></i></div></div>
<p class="stats-line" id="statsLine"></p>
</section>
<div class="stage" id="stage"><svg id="graph" role="img" aria-label="worktree trajectory"></svg></div>
<div class="legend" id="legend" hidden></div>
<section class="controls" id="controls">
<button type="button" id="play" class="primary">Replay</button>
<input type="range" id="scrub" min="0" max="1000" value="0" step="1" aria-label="replay position">
<div class="seg" id="speed" role="group" aria-label="speed">
<button type="button" data-speed="0.5">0.5×</button>
<button type="button" data-speed="1" aria-selected="true">1×</button>
<button type="button" data-speed="2">2×</button>
<button type="button" data-speed="4">4×</button>
</div>
</section>
<section class="detail" id="detail">
<div class="d-head"><span class="d-branch"><i id="dDot" class="d-dot"></i><span id="dBranch"></span></span><span class="d-time" id="dTime"></span></div>
<p class="d-msg" id="dMsg"></p>
<p class="d-meta"><span id="dMeta"></span> <span id="dDelta" class="delta"></span></p>
</section>
<p class="empty" id="empty" hidden></p>
<div class="box"><b>LayerFS trajectory</b><span>Connecting to the local trajectory service…</span></div>
<script src="_magpie/bridge.js"></script>
<script src="boot.js"></script>
</body>
</html>
+10
View File
@@ -176,3 +176,13 @@ header { display: flex; align-items: baseline; gap: 16px; flex-wrap: wrap; borde
@media (prefers-reduced-motion: reduce) {
#play { transition: none; }
}
/* Agent activity: the per-agent tool-call table under the replay */
section.agents { margin-top: 22px; }
section.agents h2 { margin: 0 0 10px; font-size: 13px; letter-spacing: .06em; text-transform: uppercase; opacity: .75; }
.agent-table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
.agent-table th { text-align: left; font-weight: 600; opacity: .6; padding: 4px 10px; border-bottom: 1px solid var(--magpie-border, rgba(128,128,128,.25)); }
.agent-table td { padding: 5px 10px; border-bottom: 1px solid var(--magpie-border, rgba(128,128,128,.15)); font-variant-numeric: tabular-nums; }
.agent-table tr:last-child td { border-bottom: none; }
.agent-table td:first-child { font-weight: 600; }
.agents-empty { opacity: .6; font-size: 12.5px; margin: 0; }
+73
View File
@@ -0,0 +1,73 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>LayerFS trajectory</title>
<!-- layerfs:style -->
</head>
<body>
<header>
<div class="hist">
<h1 id="histLine">HISTORY</h1>
<p class="hist-meta" id="histMeta"></p>
</div>
<div class="menu" id="projectMenu" hidden>
<button type="button" id="projBtn" aria-haspopup="listbox" aria-expanded="false"></button>
<div class="menu-list" id="projList" role="listbox" aria-label="project" hidden></div>
</div>
<p class="stamp" id="stamp"></p>
</header>
<section class="stats" id="stats">
<div class="tiles">
<div class="tile"><span class="k" data-t="checkpointsK">Checkpoints</span><span class="v" id="nCommits">0 / 0</span></div>
<div class="tile"><span class="k" data-t="branchesK">Branches</span><span class="v" id="tBranches">0</span></div>
<div class="tile"><span class="k" data-t="asCopies">as copies</span><span class="v" id="vCopies">0 B</span></div>
<div class="tile"><span class="k" data-t="stored">stored</span><span class="v" id="vStored">0 B</span></div>
<div class="tile"><span class="k" data-t="dedupe">dedupe</span><span class="v" id="tDedup">–</span><span class="s saved" id="vSaved"></span></div>
</div>
<div class="bar-row"><span class="bar-label" data-t="asCopies">as copies</span><div class="bar"><i id="barCopies" class="copies"></i></div></div>
<div class="bar-row"><span class="bar-label" data-t="stored">stored</span><div class="bar"><i id="barStored" class="stored"></i></div></div>
<p class="stats-line" id="statsLine"></p>
</section>
<div class="stage" id="stage"><svg id="graph" role="img" aria-label="worktree trajectory"></svg></div>
<div class="legend" id="legend" hidden></div>
<section class="controls" id="controls">
<button type="button" id="play" class="primary">Replay</button>
<input type="range" id="scrub" min="0" max="1000" value="0" step="1" aria-label="replay position">
<div class="seg" id="speed" role="group" aria-label="speed">
<button type="button" data-speed="0.5">0.5×</button>
<button type="button" data-speed="1" aria-selected="true">1×</button>
<button type="button" data-speed="2">2×</button>
<button type="button" data-speed="4">4×</button>
</div>
</section>
<section class="detail" id="detail">
<div class="d-head"><span class="d-branch"><i id="dDot" class="d-dot"></i><span id="dBranch"></span></span><span class="d-time" id="dTime"></span></div>
<p class="d-msg" id="dMsg"></p>
<p class="d-meta"><span id="dMeta"></span> <span id="dDelta" class="delta"></span></p>
</section>
<section class="agents" id="agents" hidden>
<h2 data-t="agentsK">Agent activity</h2>
<table class="agent-table" id="agentTable">
<thead><tr>
<th data-t="agentCol">Agent</th>
<th data-t="toolCol">Tool</th>
<th data-t="projectCol">Project</th>
<th data-t="branchCol">Branch</th>
<th data-t="whenCol">When</th>
</tr></thead>
<tbody id="agentRows"></tbody>
</table>
<p class="agents-empty" id="agentsEmpty" hidden></p>
</section>
<p class="empty" id="empty" hidden></p>
<!-- layerfs:scripts -->
</body>
</html>
File diff suppressed because one or more lines are too long
+59 -1
View File
@@ -15,6 +15,8 @@
live: "live", layers: "layers", history: "HISTORY", stats: "store.stats · read-only",
dedupe: "dedupe", graft: "published", twig: "bare twig",
checkpointsK: "Checkpoints", branchesK: "Branches",
agentsK: "Agent activity", agentsEmpty: "No tool calls yet. Each agent's provision, fork, checkpoint and publish lands here as it happens.",
agentCol: "Agent", toolCol: "Tool", projectCol: "Project", branchCol: "Branch", whenCol: "When",
},
zh: {
title: "LayerFS 轨迹", replay: "回放", pause: "暂停",
@@ -26,6 +28,8 @@
live: "条存活分支", layers: "层", history: "HISTORY", stats: "store.stats · 只读",
dedupe: "去重", graft: "已发布", twig: "未发布的枝条",
checkpointsK: "检查点", branchesK: "分支",
agentsK: "Agent 活动", agentsEmpty: "还没有工具调用。每个 agent 的 provision、fork、checkpoint 和 publish 会实时落在这里。",
agentCol: "Agent", toolCol: "工具", projectCol: "项目", branchCol: "分支", whenCol: "时间",
},
"zh-TW": {
title: "LayerFS 軌跡", replay: "重播", pause: "暫停",
@@ -37,6 +41,8 @@
live: "條存活分支", layers: "層", history: "HISTORY", stats: "store.stats · 唯讀",
dedupe: "去重", graft: "已發布", twig: "未發布的枝條",
checkpointsK: "檢查點", branchesK: "分支",
agentsK: "Agent 活動", agentsEmpty: "還沒有工具呼叫。每個 agent 的 provision、fork、checkpoint 和 publish 會即時落在這裡。",
agentCol: "Agent", toolCol: "工具", projectCol: "專案", branchCol: "分支", whenCol: "時間",
},
ja: {
title: "LayerFS の軌跡", replay: "再生", pause: "一時停止",
@@ -48,6 +54,8 @@
live: "本の生存ブランチ", layers: "レイヤー", history: "HISTORY", stats: "store.stats · 読み取り専用",
dedupe: "重複排除", graft: "公開済み", twig: "未公開の枝",
checkpointsK: "チェックポイント", branchesK: "ブランチ",
agentsK: "エージェントの活動", agentsEmpty: "まだツール呼び出しはありません。各エージェントの provision、fork、checkpoint、publish は随時ここに記録されます。",
agentCol: "エージェント", toolCol: "ツール", projectCol: "プロジェクト", branchCol: "ブランチ", whenCol: "時刻",
},
};
@@ -96,7 +104,56 @@
if (n >= 1e9) return (n / 1e9).toFixed(2) + " GB";
if (n >= 1e6) return (n / 1e6).toFixed(1) + " MB";
if (n >= 1e3) return (n / 1e3).toFixed(1) + " KB";
return n + " B";
// byte counts are whole: the counters interpolate mid-replay, and
// an unrounded fraction here used to show as 3.164870684975676 B
return Math.round(n) + " B";
}
// The view state a reload carries in location.hash: the project, the
// vertical scroll, and the replay playhead. The hash survives
// location.reload() in a sandboxed frame and needs no storage, which
// is what makes it usable here: the page cannot fetch, and the
// service must not answer cross-origin reads, so the fresh document
// cannot ask what changed — it can only read what the old document
// left in the hash. Pure, so a test can check the round-trip and
// the restore decision without a DOM.
function formatViewHash(state) {
const p = encodeURIComponent(String(state.project || ""));
const y = Math.max(0, Math.round(Number(state.scrollY) || 0));
const t = Math.max(0, Math.round((Number(state.playhead) || 0) * 1000) / 1000);
return `#p=${p}&y=${y}&t=${t}`;
}
function parseViewHash(hash) {
const h = String(hash || "").replace(/^#/, "");
if (!h) return null;
let params;
try { params = new URLSearchParams(h); } catch { return null; }
const project = params.get("p");
if (!project) return null;
const y = Number(params.get("y"));
const t = Number(params.get("t"));
return {
project,
scrollY: Number.isFinite(y) && y > 0 ? Math.round(y) : 0,
playhead: Number.isFinite(t) && t > 0 ? t : 0,
};
}
// Which view a fresh document restores from the hash, or null for a
// plain first look (no hash, or a hash naming a project that is no
// longer there — a renamed project must not pin the page to a
// ghost). The playhead clamps to the project's steps: the data may
// have grown or shrunk since the hash was written. Under reduced
// motion the page settles on the final state whatever the hash says.
function resolveRestoredView(projects, hash, reducedMotion) {
const parsed = parseViewHash(hash);
if (!parsed) return null;
const project = (projects || []).find((p) => p.name === parsed.project);
if (!project) return null;
const n = steps(project).length;
if (reducedMotion || parsed.playhead >= n) {
return { project: parsed.project, scrollY: parsed.scrollY, playhead: n, settled: true };
}
return { project: parsed.project, scrollY: parsed.scrollY, playhead: Math.min(parsed.playhead, n), settled: false };
}
// Lane 0 is main, the middle bough; other branches follow in the order
@@ -392,5 +449,6 @@
TEXT, text, bytes, lanes, steps, publishes, layout, detail, AGENTS, agentOf,
ICONS, LEAF_GLYPH, glyphFor, iconDraw,
cubicBezier, magpieEase, easeOutCubic, easeOutBack, clamp01, frame, pulse, markInk,
formatViewHash, parseViewHash, resolveRestoredView,
};
})();