// ---------------------------------------------------------------------------
// automation/HarnessPanel.tsx — the HARNESS tab (owner item 3, rulings R7/R8,
// contract C4 · W36-T31).
//
// Owner, verbatim (2026-08-18): *"For each of the tenant's Agent, I think we need
// another tab beside Properties/Run history. This new module under agent is
// supposed to host any file pertaining to the agent skills, router etc. So we
// build a user can build a custom harness for each agent through the chat
// interface."*
//
// ⛔⛔ R8 IS THE WHOLE SHAPE AND IT IS ENFORCED ON THE SERVER, NOT HERE. Every save
// APPENDS a version; there is no overwrite door and no edit-in-place. A ROLL-BACK
// IS A WRITE OF AN OLDER BODY, never a delete — so "restore v1" produces v4 whose
// `restoredFrom` is 1, and the history keeps v2 and v3 saying what actually
// happened rather than what somebody last wanted it to look like. This panel
// paints that model; it does not implement it, and it must never offer a control
// whose name implies otherwise ("Replace", "Overwrite", "Discard v2").
//
// ⛔ R8 IS DELIBERATELY NOT R9, and the two sit one screen apart. An agent-authored
// ACTION's config is agent-only (item 8); a harness file is editable by BOTH the
// user and the agent. Do not copy either posture onto the other.
//
// ⚠ THIS PANEL IS THE ONE PLACE THE CAPS ARE VISIBLE. `limits` rides every C4
// payload precisely so a control can say "this file is full" BEFORE a write fails,
// and `trimmed` reports the one cap that acts WITHOUT refusing — history older than
// `maxVersions` is gone, and a reader who cannot see that would infer the file was
// only ever saved twice. Both are rendered, never inferred.
// ---------------------------------------------------------------------------
import { useCallback, useEffect, useRef, useState } from "react";
import type { HarnessDoc, HarnessFile, HarnessLimits, HarnessProposal } from "./automationApi";
import {
approveHarnessProposal, AutomationError, deleteHarness, getHarnessProposal, listHarness,
proposeHarnessVersion, readHarness, rejectHarnessProposal, writeHarness,
} from "./automationApi";
import "./automation.css";
/** The files a fresh agent is offered, as NAMES only. Nothing is created until somebody saves. */
const SUGGESTED_PATHS = ["skills/router.md", "skills/recurring.md"];
function kb(bytes: number): string {
if (bytes < 1024) return `${bytes} bytes`;
return `${(bytes / 1024).toFixed(bytes < 10240 ? 1 : 0)} KB`;
}
/**
* `2026-08-18T14:50:09Z` as something a person reads. ⚠ Falls back to the raw string rather than
* to an empty cell: an unparseable stamp is still evidence of WHEN, and a blank reads as "never".
*/
function when(iso: string): string {
if (!iso) return "";
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return iso;
return d.toLocaleString(undefined, {
year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit",
});
}
/** Who wrote it, in words. R8's point is that BOTH may, so the answer is always stated. */
const byline = (author: string, kind: string) =>
`${kind === "agent" ? "the automation" : author || "a person"}`;
type HarnessBusy = "" | "open" | "save" | "delete" | "propose" | "approve" | "reject";
/** Pure review state, exported so the exact approval surface can be rendered and inspected. */
export function HarnessProposalReview({
proposal,
busy,
onApprove,
onReject,
}: {
proposal: HarnessProposal;
busy: HarnessBusy;
onApprove: () => void;
onReject: () => void;
}) {
return (
{proposal.summary || `Proposed from version ${proposal.baseVersion}.`}
{proposal.provider ? ` Model: ${proposal.provider}.` : ""}
);
}
export default function HarnessPanel({ agentId }: { agentId: string }) {
const [files, setFiles] = useState(null);
const [limits, setLimits] = useState(null);
const [listErr, setListErr] = useState("");
const [open, setOpen] = useState(null);
const [openErr, setOpenErr] = useState("");
const [draft, setDraft] = useState("");
const [busy, setBusy] = useState("");
const [newPath, setNewPath] = useState("");
const [note, setNote] = useState("");
const [proposalPrompt, setProposalPrompt] = useState("");
const [proposal, setProposal] = useState(null);
const [proposalNote, setProposalNote] = useState("");
/** Which older version is being previewed, or 0 for the current one. */
const [at, setAt] = useState(0);
const dirty = useRef(false);
/**
* ⛔ THE OPEN THAT WOULD THROW AWAY TYPING, HELD UNTIL IT IS CONFIRMED.
*
* Every other control here is safe to misclick: R8 means nothing is ever destroyed on the
* server. The ONE thing that can be lost is a body somebody has typed and not saved, and it is
* lost by the most inviting click on the panel (a version in the history, one row from Save).
* ⚠ Deliberately NOT `window.confirm`. A native dialog blocks the whole tab, cannot be styled,
* and reads as a browser error rather than as this panel asking a question.
*/
const [holdOpen, setHoldOpen] = useState<{ path: string; version: number } | null>(null);
const refresh = useCallback(async (signal?: AbortSignal) => {
try {
const r = await listHarness(agentId, signal);
if (signal?.aborted) return;
setFiles(r.files || []);
setLimits(r.limits || null);
setListErr("");
} catch (e: unknown) {
if (signal?.aborted) return;
setFiles([]);
setListErr(e instanceof AutomationError ? e.message : "the harness could not be read");
}
}, [agentId]);
useEffect(() => {
const ac = new AbortController();
void refresh(ac.signal);
return () => ac.abort();
}, [refresh]);
/**
* Open one file at one version.
* ⚠ THE DRAFT IS ONLY ADOPTED WHEN IT IS SAFE TO. Reading an OLDER version fills the editor with
* that body on purpose — that is how a roll-back is composed, and the save button says so — but
* it must not silently throw away something half-typed, so an unsaved edit is confirmed in words
* by the caller rather than by a browser dialog this panel cannot style.
*/
const openFile = useCallback(async (path: string, version = 0, force = false) => {
// The guard fires only when something WOULD be lost: a typed body, going somewhere else.
if (!force && dirty.current && !(open?.path === path && (at || 0) === version)) {
setHoldOpen({ path, version });
return;
}
setHoldOpen(null);
setBusy("open");
setOpenErr("");
setNote("");
try {
const doc = await readHarness(agentId, path, version || undefined);
setOpen(doc);
setDraft(doc.body);
setAt(version || 0);
dirty.current = false;
setProposal(null);
setProposalNote("");
if (!version) {
try {
const pending = await getHarnessProposal(agentId, path);
setProposal(pending.proposal || null);
if (pending.proposal?.status === "approving") {
setProposalNote("A prior approval was interrupted. Finish it without creating a duplicate version.");
}
} catch (e: unknown) {
setProposalNote(e instanceof AutomationError
? e.message
: "the pending proposal could not be read");
}
}
} catch (e: unknown) {
// ⛔ THE SERVER'S OWN SENTENCE. A trimmed version answers 410 with a sentence naming the cap;
// replacing it with "could not open" throws away the only part a person can act on.
setOpenErr(e instanceof AutomationError ? e.message : "that file could not be opened");
} finally {
setBusy("");
}
}, [agentId, open, at]);
const save = useCallback(async (restoredFrom?: number) => {
if (!open) return;
setBusy("save");
setNote("");
try {
const doc = await writeHarness(agentId, {
path: open.path,
body: draft,
// ⛔ `user`, ALWAYS, from this panel. `authorKind` is a claim about who DRAFTED the body,
// and everything typed here was typed by the person at the keyboard. The agent's own
// writes go through `record_version()` on the server with no session at all; a client
// that stamped "agent" on a hand-typed file would make the history a record of nothing.
authorKind: "user",
...(restoredFrom ? { restoredFrom } : {}),
});
setOpen(doc);
setDraft(doc.body);
setAt(0);
dirty.current = false;
setNote(restoredFrom
? `Version ${restoredFrom} is back, saved as version ${doc.atVersion}. Nothing was deleted.`
: `Saved as version ${doc.atVersion}.`);
await refresh();
} catch (e: unknown) {
setNote(e instanceof AutomationError ? e.message : "that file could not be saved");
} finally {
setBusy("");
}
}, [agentId, open, draft, refresh]);
const create = useCallback(async () => {
const path = newPath.trim();
if (!path) return;
setBusy("save");
setNote("");
try {
const doc = await writeHarness(agentId, { path, body: "", authorKind: "user" });
setNewPath("");
setOpen(doc);
setDraft(doc.body);
setAt(0);
dirty.current = false;
await refresh();
} catch (e: unknown) {
setNote(e instanceof AutomationError ? e.message : "that file could not be created");
} finally {
setBusy("");
}
}, [agentId, newPath, refresh]);
const drop = useCallback(async (path: string) => {
setBusy("delete");
setNote("");
try {
await deleteHarness(agentId, path);
if (open?.path === path) {
setOpen(null);
setDraft("");
}
await refresh();
} catch (e: unknown) {
setNote(e instanceof AutomationError ? e.message : "that file could not be deleted");
} finally {
setBusy("");
}
}, [agentId, open, refresh]);
const askAgent = useCallback(async () => {
if (!open || at || draft !== open.body || !proposalPrompt.trim()) return;
setBusy("propose");
setProposalNote("");
try {
const result = await proposeHarnessVersion(agentId, open.path, proposalPrompt.trim());
setProposal(result.proposal);
setProposalNote("Proposal ready. The current harness is unchanged until you approve it.");
} catch (e: unknown) {
setProposalNote(e instanceof AutomationError
? e.message
: "the automation could not propose a harness version");
} finally {
setBusy("");
}
}, [agentId, open, at, draft, proposalPrompt]);
const approveProposal = useCallback(async () => {
if (!proposal) return;
setBusy("approve");
setProposalNote("");
try {
const result = await approveHarnessProposal(agentId, proposal.id);
setOpen(result.file);
setDraft(result.file.body);
setAt(0);
dirty.current = false;
setProposal(null);
setProposalPrompt("");
setProposalNote(`Approved as version ${result.file.atVersion}.`);
await refresh();
} catch (e: unknown) {
setProposalNote(e instanceof AutomationError
? e.message
: "that proposal could not be approved");
} finally {
setBusy("");
}
}, [agentId, proposal, refresh]);
const rejectProposal = useCallback(async () => {
if (!proposal) return;
setBusy("reject");
setProposalNote("");
try {
await rejectHarnessProposal(agentId, proposal.id);
setProposal(null);
setProposalNote("Proposal rejected. No harness version was created.");
} catch (e: unknown) {
setProposalNote(e instanceof AutomationError
? e.message
: "that proposal could not be rejected");
} finally {
setBusy("");
}
}, [agentId, proposal]);
const full = !!(limits && files && files.length >= limits.maxFiles);
const tooBig = !!(limits && new TextEncoder().encode(draft).length > limits.maxBodyBytes);
if (files === null) {
return
Reading this automation's harness files.
;
}
return (
{listErr ?
{listErr}
: null}
{/* ── the file list ─────────────────────────────────────────────────────────────────── */}
{!files.length && !listErr ? (
This automation has no harness files yet.
) : null}
{files.map((f) => (
{/* ⚠ DELETING A FILE IS NOT THE THING R8 FORBIDS. R8 forbids a roll-back implemented as
a delete. Removing a file is a person deciding it should not exist, which is a
different act and gets a different, quieter control. */}
))}
{/* ── add a file ────────────────────────────────────────────────────────────────────── */}
{/* ⛔ THE CAP IS SAID BEFORE IT BITES, not after. `limits` rides the payload for exactly
this; a ceiling a person meets as a refusal is a ceiling nobody could plan around. */}
{full
? `This automation already has the maximum of ${limits?.maxFiles} harness files. `
+ "Delete one to add another."
: `A path like ${SUGGESTED_PATHS.join(" or ")}. `
+ (limits ? `Up to ${limits.maxFiles} files, ${kb(limits.maxBodyBytes)} each.` : "")}
{openErr ?
{openErr}
: null}
{holdOpen ? (
The changes you typed into {open?.path} have not been saved, and opening{" "}
{holdOpen.version ? `version ${holdOpen.version}` : holdOpen.path} would replace them.
{at ? (
/* ⛔ AN OLDER BODY IS LABELLED AS ONE, LOUDLY. Without this the editor shows an old
body in the same frame as the current one, and Save then looks like an ordinary
save rather than a roll-back. Naming it is what makes the next click honest. */
You are reading version {at} of {open.versions + open.trimmed}. Saving it writes a
NEW version that restores this one. Nothing in between is deleted.
: null}
>
) : null}
{/* ── the history ─────────────────────────────────────────────────────────────── */}
Version history
{open.history.map((v) => (
))}
{/* ⛔ THE CAP THAT ACTS WITHOUT REFUSING. Past `maxVersions` the OLDEST bodies are
dropped, and a history that simply started at v14 would read as a file first saved
at v14. R6's second sentence: a limit that bites is REPORTED. */}
{open.trimmed ? (
The {open.trimmed} oldest version{open.trimmed === 1 ? "" : "s"} of this file
{open.trimmed === 1 ? " has" : " have"} been dropped, because only the newest{" "}
{limits?.maxVersions} are kept. What they said is gone; that they existed is not.