mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-28 21:46:15 +01:00
feat(runner): add SDK and developer tooling (#12608)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The runner package already provides the production protocol and execution spine. > - Contributors still need stable SDK surfaces, deterministic test tools, and local inspection tools. > - Those surfaces share generated contracts and must change as one package boundary. > - This pull request adds the package-local SDK, labs, examples, and drift checks. > - The benefit is a reviewable developer platform that does not change application execution selection. ## Linked Issues or Issue Description **Subsystem affected** `packages/paperclip-runner` — runner SDK, conformance tools, and developer tooling. **Problem or motivation** The production runner spine is present, but package consumers cannot build deterministic integrations, inspect sessions, or verify provider-neutral behavior through supported surfaces. **Proposed solution** Add browser, React, standalone, live-session, scenario, conformance, and evaluation surfaces. Add generated contract inventories and package-local verification scripts. Keep production application routing unchanged. **Alternatives considered** We considered splitting each generated catalog, SDK surface, and demo into separate pull requests. Those changes share exports, fixtures, and drift gates. Splitting them would create intermediate package states that do not build. **Roadmap alignment** No overlapping item appears in `ROADMAP.md`. This work extends the runner package that is already on `master`. ## What Changed - Add browser, React, standalone, live-session, and issue-thread SDK surfaces. - Add deterministic mock control-plane, scenario, conformance, replay, and evaluation tools. - Add bounded Codex, OpenCode, and ACPX development transports and fixtures. - Keep deferred managed-provider execution fail-closed. Persisted compatibility data remains readable. - Add generated capability inventories with their source files and drift checks. - Add examples, package documentation, browser checks, and clean-consumer checks. - Preserve the reviewed protocol bounds, replay compatibility aliases, process environment isolation, and semantic redaction limits. - Update the ACPX package patch that the existing workspace patch registry already tracks. - Do not change `pnpm-lock.yaml`, repository workflows, server runtime selection, or the application UI. ## Verification GitHub Actions is the verification authority for this pull request. The repository CI, package TypeScript and Rust checks, package tests, generated-output drift checks, browser checks, security scans, and Greptile review must pass on the exact head. Local test suites were not run because this series uses parallel GitHub Actions for verification. ## Risks This is a large greenfield package change. The main risks are public export drift, generated-output drift, and optional React consumer compatibility. Package boundary checks, clean-consumer checks, and browser tests cover those risks. Production adapter selection and server execution are outside this pull request. ## Stack 1. **This PR:** runner SDK and developer tooling. 2. [Codex production server integration](https://github.com/paperclipai/paperclip/pull/12616). 3. [Provider-neutral task-thread UI](https://github.com/paperclipai/paperclip/pull/12617). ## Model Used OpenAI Codex, GPT-5, high-reasoning mode, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have described the issue in-PR following the feature request template - [x] I have not referenced internal/instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal Paperclip ticket id - [ ] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge
This commit is contained in:
1 parent
b5fd13e09f
commit
560e7e48b5
381 files changed
+97707
-2393
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,161 @@
|
||||
import { useEffect, useRef, useState, type FormEvent } from "react";
|
||||
|
||||
import type { CapabilityComposerModel } from "../../../src/issue-thread/types";
|
||||
|
||||
/**
|
||||
* Composer (contract §4). `data-composer-state` is the single test and
|
||||
* screenshot hook. Draft text survives refresh through localStorage keyed by
|
||||
* session id; Stop never discards the transcript.
|
||||
*/
|
||||
|
||||
export interface ComposerProps {
|
||||
model: CapabilityComposerModel;
|
||||
sessionId: string;
|
||||
onSend: (message: string) => void;
|
||||
onStop: () => void;
|
||||
onRetry: () => void;
|
||||
onReset: () => void;
|
||||
onFocusPending: (interactionId: string) => void;
|
||||
/** The clean room resets into a new tenant, so it names the action itself. */
|
||||
resetLabel?: string;
|
||||
}
|
||||
|
||||
function draftKey(sessionId: string): string {
|
||||
return `paperclip-runner.capability.draft.${sessionId}`;
|
||||
}
|
||||
|
||||
function readDraft(sessionId: string): string {
|
||||
try {
|
||||
return window.localStorage.getItem(draftKey(sessionId)) ?? "";
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
export function Composer(props: ComposerProps) {
|
||||
const {
|
||||
model,
|
||||
sessionId,
|
||||
onSend,
|
||||
onStop,
|
||||
onRetry,
|
||||
onReset,
|
||||
onFocusPending,
|
||||
resetLabel = "Reset scenario",
|
||||
} = props;
|
||||
const [value, setValue] = useState(() => readDraft(sessionId));
|
||||
const inputRef = useRef<HTMLTextAreaElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setValue(readDraft(sessionId));
|
||||
}, [sessionId]);
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
window.localStorage.setItem(draftKey(sessionId), value);
|
||||
} catch {
|
||||
// A blocked storage quota must not break the session.
|
||||
}
|
||||
}, [sessionId, value]);
|
||||
|
||||
const editable = model.state === "ready" || model.state === "streaming";
|
||||
const canSend = editable && value.trim().length > 0;
|
||||
|
||||
function submit(event: FormEvent) {
|
||||
event.preventDefault();
|
||||
if (!canSend) return;
|
||||
onSend(value.trim());
|
||||
setValue("");
|
||||
}
|
||||
|
||||
return (
|
||||
<form
|
||||
className="pit-composer"
|
||||
data-composer-state={model.state}
|
||||
onSubmit={submit}
|
||||
aria-label="Send a message to the agent"
|
||||
>
|
||||
<div className="pit-composer-inner">
|
||||
{model.helper !== null ? (
|
||||
<p className="pit-composer-helper">
|
||||
{model.helper}
|
||||
{model.state === "waiting" && model.pendingInteractionId !== null ? (
|
||||
<>
|
||||
{" "}
|
||||
<button
|
||||
type="button"
|
||||
className="pit-link-button"
|
||||
data-testid="pending-anchor"
|
||||
onClick={() => onFocusPending(model.pendingInteractionId as string)}
|
||||
>
|
||||
Go to the pending request
|
||||
</button>
|
||||
</>
|
||||
) : null}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{model.reason !== null ? (
|
||||
<p className="pit-composer-reason" data-testid="composer-reason">
|
||||
{model.reason}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="pit-composer-row">
|
||||
<label className="pit-visually-hidden" htmlFor="composer-input">
|
||||
Message
|
||||
</label>
|
||||
<textarea
|
||||
className="pit-composer-input"
|
||||
id="composer-input"
|
||||
ref={inputRef}
|
||||
rows={2}
|
||||
value={value}
|
||||
disabled={!editable}
|
||||
placeholder={editable ? "Message the agent…" : ""}
|
||||
onChange={(event) => setValue(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
if (canSend) {
|
||||
onSend(value.trim());
|
||||
setValue("");
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
{model.state === "streaming" ? (
|
||||
<button
|
||||
type="button"
|
||||
className="pit-button"
|
||||
data-variant="destructive"
|
||||
onClick={onStop}
|
||||
data-testid="composer-stop"
|
||||
>
|
||||
Stop
|
||||
</button>
|
||||
) : model.state === "reconnecting" ? (
|
||||
<button type="button" className="pit-button" onClick={onRetry}>
|
||||
Retry now
|
||||
</button>
|
||||
) : model.state === "disabled" ? (
|
||||
<button type="button" className="pit-button" onClick={onReset}>
|
||||
{resetLabel}
|
||||
</button>
|
||||
) : null}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
className="pit-button"
|
||||
data-variant="primary"
|
||||
disabled={!canSend || model.state === "sending"}
|
||||
data-testid="composer-send"
|
||||
>
|
||||
{model.state === "sending" ? "Sending…" : model.state === "streaming" ? "Steer" : "Send"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,646 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import type { CapabilityDevtoolsSnapshot } from "../../../src/devtools";
|
||||
import { Icon, type IconName } from "./Icons";
|
||||
import { EvalAssertions, type EvalAssertion } from "./ThreadItems";
|
||||
|
||||
export type CapabilityDevtoolsTab =
|
||||
| "eval"
|
||||
| "evidence"
|
||||
| "timeline"
|
||||
| "state"
|
||||
| "diff"
|
||||
| "documents"
|
||||
| "protocol"
|
||||
| "trace"
|
||||
| "runtime"
|
||||
| "authority";
|
||||
type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
|
||||
|
||||
export interface EvalInspectorReport {
|
||||
attemptId: string;
|
||||
caseId: string;
|
||||
disposition: string;
|
||||
passed: boolean;
|
||||
checks: EvalAssertion[];
|
||||
run: {
|
||||
model: string;
|
||||
provider: string;
|
||||
driver: string;
|
||||
providerVersion: string | null;
|
||||
runnerProvider: string;
|
||||
configuration: string;
|
||||
sessionId: string;
|
||||
providerSessionId: string | null;
|
||||
agentVersion: string | null;
|
||||
retainedSession: boolean | null;
|
||||
retainedSessionStatus: string | null;
|
||||
fixtureDigest: string;
|
||||
runnerPackageDigest: string;
|
||||
runnerdDigest: string;
|
||||
runnerBuild: string;
|
||||
startedAt: string;
|
||||
finishedAt: string;
|
||||
durationMs: number;
|
||||
initialRevision: number;
|
||||
finalRevision: number;
|
||||
usage: {
|
||||
agentTurns: number;
|
||||
providerRequests: number | null;
|
||||
inputTokens: number;
|
||||
outputTokens: number;
|
||||
cachedInputTokens: number;
|
||||
reasoningTokens: number;
|
||||
providerReportedCostNanodollars?: number;
|
||||
estimatedCostNanodollars: number;
|
||||
pricingVersion: string;
|
||||
} | null;
|
||||
};
|
||||
}
|
||||
|
||||
function JsonTree({ value, name = "root" }: { value: Json; name?: string }) {
|
||||
if (value === null || typeof value !== "object") {
|
||||
return <span className="pit-json-value">{JSON.stringify(value)}</span>;
|
||||
}
|
||||
const entries = Array.isArray(value)
|
||||
? value.map((entry, index) => [String(index), entry] as const)
|
||||
: Object.entries(value);
|
||||
return (
|
||||
<details className="pit-json-node" open={name === "root"}>
|
||||
<summary>
|
||||
{name}{" "}
|
||||
<span className="pit-muted">
|
||||
{Array.isArray(value) ? `[${entries.length}]` : `{${entries.length}}`}
|
||||
</span>
|
||||
</summary>
|
||||
<div className="pit-json-children">
|
||||
{entries.map(([key, entry]) => (
|
||||
<div className="pit-json-row" key={key}>
|
||||
<span className="pit-json-key">{key}</span>
|
||||
{entry !== null && typeof entry === "object" ? (
|
||||
<JsonTree value={entry as Json} name={key} />
|
||||
) : (
|
||||
<JsonTree value={entry as Json} />
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
interface DiffRow {
|
||||
path: string;
|
||||
before: Json | undefined;
|
||||
after: Json | undefined;
|
||||
}
|
||||
|
||||
function diff(
|
||||
before: Json | undefined,
|
||||
after: Json | undefined,
|
||||
path = "state",
|
||||
): DiffRow[] {
|
||||
if (JSON.stringify(before) === JSON.stringify(after)) return [];
|
||||
if (
|
||||
before !== null &&
|
||||
after !== null &&
|
||||
typeof before === "object" &&
|
||||
typeof after === "object" &&
|
||||
!Array.isArray(before) &&
|
||||
!Array.isArray(after)
|
||||
) {
|
||||
const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
|
||||
return [...keys].flatMap((key) =>
|
||||
diff(before[key], after[key], `${path}.${key}`),
|
||||
);
|
||||
}
|
||||
return [{ path, before, after }];
|
||||
}
|
||||
|
||||
function download(snapshot: CapabilityDevtoolsSnapshot) {
|
||||
const blob = new Blob([JSON.stringify(snapshot, null, 2)], {
|
||||
type: "application/json",
|
||||
});
|
||||
const url = URL.createObjectURL(blob);
|
||||
const anchor = document.createElement("a");
|
||||
anchor.href = url;
|
||||
anchor.download = `paperclip-devtools-r${snapshot.currentRevision}.json`;
|
||||
anchor.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
const TABS: ReadonlyArray<{
|
||||
id: CapabilityDevtoolsTab;
|
||||
icon: IconName;
|
||||
label: string;
|
||||
}> = [
|
||||
{ id: "evidence", icon: "evidence", label: "Evidence" },
|
||||
{ id: "timeline", icon: "timeline", label: "Timeline" },
|
||||
{ id: "state", icon: "state", label: "State" },
|
||||
{ id: "diff", icon: "diff", label: "Diff" },
|
||||
{ id: "documents", icon: "documents", label: "Documents" },
|
||||
{ id: "protocol", icon: "protocol", label: "Protocol" },
|
||||
{ id: "trace", icon: "protocol", label: "Provider trace" },
|
||||
{ id: "runtime", icon: "terminal", label: "Runtime" },
|
||||
{ id: "authority", icon: "authority", label: "Authority" },
|
||||
];
|
||||
|
||||
function documentsOf(state: Json): Array<{
|
||||
id: string;
|
||||
key: string;
|
||||
title: string;
|
||||
revisions: Array<{
|
||||
id: string;
|
||||
revision: number;
|
||||
body: string;
|
||||
changeSummary: string | null;
|
||||
createdAt: string;
|
||||
}>;
|
||||
}> {
|
||||
if (state === null || typeof state !== "object" || Array.isArray(state))
|
||||
return [];
|
||||
const documents = state.documents;
|
||||
if (!Array.isArray(documents)) return [];
|
||||
return documents.flatMap((value) => {
|
||||
if (value === null || typeof value !== "object" || Array.isArray(value))
|
||||
return [];
|
||||
const revisions = Array.isArray(value.revisions)
|
||||
? value.revisions.flatMap((candidate) => {
|
||||
if (
|
||||
candidate === null ||
|
||||
typeof candidate !== "object" ||
|
||||
Array.isArray(candidate)
|
||||
)
|
||||
return [];
|
||||
return [
|
||||
{
|
||||
id: String(candidate.id ?? ""),
|
||||
revision: Number(candidate.revision ?? 0),
|
||||
body: String(candidate.body ?? ""),
|
||||
changeSummary:
|
||||
candidate.changeSummary === null
|
||||
? null
|
||||
: String(candidate.changeSummary ?? ""),
|
||||
createdAt: String(candidate.createdAt ?? ""),
|
||||
},
|
||||
];
|
||||
})
|
||||
: [];
|
||||
return [
|
||||
{
|
||||
id: String(value.id ?? ""),
|
||||
key: String(value.key ?? ""),
|
||||
title: String(value.title ?? "Untitled"),
|
||||
revisions,
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
export function DevtoolsInspector({
|
||||
snapshot,
|
||||
onFork,
|
||||
tab,
|
||||
onTabChange,
|
||||
evalReport,
|
||||
}: {
|
||||
snapshot: CapabilityDevtoolsSnapshot;
|
||||
onFork: (revision: number) => void;
|
||||
tab: CapabilityDevtoolsTab;
|
||||
onTabChange: (tab: CapabilityDevtoolsTab) => void;
|
||||
evalReport?: EvalInspectorReport | null;
|
||||
}) {
|
||||
const [query, setQuery] = useState("");
|
||||
const latest = snapshot.revisions.at(-1)!;
|
||||
const [revision, setRevision] = useState(latest.revision);
|
||||
const [following, setFollowing] = useState(true);
|
||||
const [compareRevision, setCompareRevision] = useState(
|
||||
snapshot.revisions[0]!.revision,
|
||||
);
|
||||
const selected =
|
||||
snapshot.revisions.find((entry) => entry.revision === revision) ?? latest;
|
||||
const compared =
|
||||
snapshot.revisions.find((entry) => entry.revision === compareRevision) ??
|
||||
snapshot.revisions[0]!;
|
||||
const rows = useMemo(
|
||||
() => diff(compared.state as Json, selected.state as Json),
|
||||
[compared.state, selected.state],
|
||||
);
|
||||
const normalized = query.trim().toLowerCase();
|
||||
const revisions = snapshot.revisions.filter(
|
||||
(entry) =>
|
||||
normalized.length === 0 ||
|
||||
JSON.stringify(entry).toLowerCase().includes(normalized),
|
||||
);
|
||||
const protocol = snapshot.protocol.filter(
|
||||
(entry) =>
|
||||
normalized.length === 0 ||
|
||||
JSON.stringify(entry).toLowerCase().includes(normalized),
|
||||
);
|
||||
const documents = useMemo(
|
||||
() => documentsOf(selected.state as Json),
|
||||
[selected.state],
|
||||
);
|
||||
const [documentId, setDocumentId] = useState("");
|
||||
const document =
|
||||
documents.find((entry) => entry.id === documentId) ?? documents[0] ?? null;
|
||||
const [documentRevision, setDocumentRevision] = useState(0);
|
||||
const visibleDocumentRevision =
|
||||
document?.revisions.find((entry) => entry.revision === documentRevision) ??
|
||||
document?.revisions.at(-1) ??
|
||||
null;
|
||||
useEffect(() => {
|
||||
if (following) setRevision(latest.revision);
|
||||
}, [following, latest.revision]);
|
||||
|
||||
return (
|
||||
<section className="pit-devtools" data-testid="devtools-inspector">
|
||||
<div className="pit-devtools-toolbar">
|
||||
<span className="pit-devtools-brand">
|
||||
<Icon name="activity" /> State monitor
|
||||
</span>
|
||||
<input
|
||||
id="devtools-search"
|
||||
className="pit-input"
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder="operation, entity, turn…"
|
||||
/>
|
||||
<button
|
||||
className="pit-icon-button"
|
||||
type="button"
|
||||
aria-pressed={!following}
|
||||
onClick={() => setFollowing((value) => !value)}
|
||||
title={following ? "Pause live updates" : "Follow latest revision"}
|
||||
aria-label={
|
||||
following ? "Pause live updates" : "Follow latest revision"
|
||||
}
|
||||
>
|
||||
<Icon name={following ? "pause" : "play"} />
|
||||
</button>
|
||||
<button
|
||||
className="pit-icon-button"
|
||||
type="button"
|
||||
onClick={() => download(snapshot)}
|
||||
title="Export redacted snapshot"
|
||||
aria-label="Export redacted snapshot"
|
||||
>
|
||||
<Icon name="download" />
|
||||
</button>
|
||||
<button
|
||||
className="pit-button"
|
||||
type="button"
|
||||
onClick={() => onFork(revision)}
|
||||
>
|
||||
<Icon name="branch" /> Fork r{revision}
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
className="pit-devtools-tabs"
|
||||
role="tablist"
|
||||
aria-label="Developer tools"
|
||||
>
|
||||
{[
|
||||
...(evalReport
|
||||
? [
|
||||
{
|
||||
id: "eval" as const,
|
||||
icon: "evidence" as const,
|
||||
label: "Eval",
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...TABS,
|
||||
].map(({ id, icon, label }) => (
|
||||
<button
|
||||
key={id}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={tab === id}
|
||||
className="pit-tab"
|
||||
onClick={() => onTabChange(id)}
|
||||
>
|
||||
<span className="pit-tab-glyph">
|
||||
<Icon name={icon} />
|
||||
</span>
|
||||
<span>{label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{tab === "eval" && evalReport ? (
|
||||
<div className="pit-devtools-pane pit-eval-inspector">
|
||||
<div className="pit-eval-summary-head">
|
||||
<a href="../../index.html">← Eval suite</a>
|
||||
<strong>
|
||||
{evalReport.passed
|
||||
? "PASS"
|
||||
: evalReport.disposition.replaceAll("_", " ").toUpperCase()}
|
||||
</strong>
|
||||
<code>{evalReport.attemptId}</code>
|
||||
</div>
|
||||
<dl className="pit-eval-run-facts">
|
||||
<div>
|
||||
<dt>Model</dt>
|
||||
<dd>
|
||||
{evalReport.run.model.startsWith(`${evalReport.run.provider}/`)
|
||||
? evalReport.run.model
|
||||
: `${evalReport.run.provider}/${evalReport.run.model}`}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Configuration</dt>
|
||||
<dd>{evalReport.run.configuration}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Session</dt>
|
||||
<dd>{evalReport.run.sessionId}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Provider session</dt>
|
||||
<dd>{evalReport.run.providerSessionId ?? "unavailable"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Driver</dt>
|
||||
<dd>
|
||||
{evalReport.run.driver}
|
||||
{evalReport.run.providerVersion
|
||||
? ` · ${evalReport.run.providerVersion}`
|
||||
: ""}
|
||||
</dd>
|
||||
</div>
|
||||
{evalReport.run.agentVersion ? (
|
||||
<div>
|
||||
<dt>Agent version</dt>
|
||||
<dd>{evalReport.run.agentVersion}</dd>
|
||||
</div>
|
||||
) : null}
|
||||
<div>
|
||||
<dt>Retained session</dt>
|
||||
<dd>
|
||||
{evalReport.run.retainedSession === true
|
||||
? (evalReport.run.retainedSessionStatus ?? "retained")
|
||||
: "not applicable"}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Duration</dt>
|
||||
<dd>{evalReport.run.durationMs} ms</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Fixture</dt>
|
||||
<dd>{evalReport.run.fixtureDigest}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>State</dt>
|
||||
<dd>
|
||||
r{evalReport.run.initialRevision} → r
|
||||
{evalReport.run.finalRevision}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Tokens</dt>
|
||||
<dd>
|
||||
{evalReport.run.usage === null
|
||||
? "unknown"
|
||||
: `${evalReport.run.usage.inputTokens} in · ${evalReport.run.usage.outputTokens} out · ${evalReport.run.usage.cachedInputTokens} cached`}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Agent turns</dt>
|
||||
<dd>{evalReport.run.usage?.agentTurns ?? "unknown"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Provider requests</dt>
|
||||
<dd>{evalReport.run.usage?.providerRequests ?? "unavailable"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Estimated cost</dt>
|
||||
<dd>
|
||||
{evalReport.run.usage === null
|
||||
? "unknown"
|
||||
: `$${(evalReport.run.usage.estimatedCostNanodollars / 1_000_000_000).toFixed(6)} · ${evalReport.run.usage.pricingVersion}`}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Provider list cost</dt>
|
||||
<dd>
|
||||
{typeof evalReport.run.usage
|
||||
?.providerReportedCostNanodollars !== "number"
|
||||
? "unknown"
|
||||
: `$${(evalReport.run.usage.providerReportedCostNanodollars / 1_000_000_000).toFixed(6)}`}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Runner</dt>
|
||||
<dd>{evalReport.run.runnerPackageDigest}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Runner build</dt>
|
||||
<dd>{evalReport.run.runnerBuild}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>runnerd</dt>
|
||||
<dd>{evalReport.run.runnerdDigest}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<h3>Assertions</h3>
|
||||
<EvalAssertions assertions={evalReport.checks} />
|
||||
</div>
|
||||
) : null}
|
||||
{tab === "timeline" ? (
|
||||
<div className="pit-devtools-list">
|
||||
{revisions.map((entry) => (
|
||||
<button
|
||||
type="button"
|
||||
className="pit-devtools-event"
|
||||
data-selected={entry.revision === revision}
|
||||
key={entry.revision}
|
||||
onClick={() => {
|
||||
setFollowing(false);
|
||||
setRevision(entry.revision);
|
||||
}}
|
||||
>
|
||||
<strong>r{entry.revision}</strong>
|
||||
<span>{entry.operationId}</span>
|
||||
<span className="pit-muted">{entry.turnId ?? "session"}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{tab === "state" ? (
|
||||
<div className="pit-devtools-pane">
|
||||
<label className="pit-card-meta" htmlFor="devtools-revision">
|
||||
Revision
|
||||
</label>
|
||||
<select
|
||||
id="devtools-revision"
|
||||
className="pit-select"
|
||||
value={revision}
|
||||
onChange={(event) => setRevision(Number(event.target.value))}
|
||||
>
|
||||
{snapshot.revisions.map((entry) => (
|
||||
<option key={entry.revision} value={entry.revision}>
|
||||
r{entry.revision} · {entry.operationId}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<JsonTree value={selected.state as Json} />
|
||||
</div>
|
||||
) : null}
|
||||
{tab === "diff" ? (
|
||||
<div className="pit-devtools-pane">
|
||||
<div className="pit-button-row">
|
||||
<select
|
||||
className="pit-select"
|
||||
aria-label="Compare from revision"
|
||||
value={compareRevision}
|
||||
onChange={(event) =>
|
||||
setCompareRevision(Number(event.target.value))
|
||||
}
|
||||
>
|
||||
{snapshot.revisions.map((entry) => (
|
||||
<option key={entry.revision} value={entry.revision}>
|
||||
from r{entry.revision}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
className="pit-select"
|
||||
aria-label="Compare to revision"
|
||||
value={revision}
|
||||
onChange={(event) => setRevision(Number(event.target.value))}
|
||||
>
|
||||
{snapshot.revisions.map((entry) => (
|
||||
<option key={entry.revision} value={entry.revision}>
|
||||
to r{entry.revision}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
{rows.map((row) => (
|
||||
<div className="pit-diff-row" key={row.path}>
|
||||
<strong>{row.path}</strong>
|
||||
<del>{JSON.stringify(row.before)}</del>
|
||||
<ins>{JSON.stringify(row.after)}</ins>
|
||||
</div>
|
||||
))}
|
||||
{rows.length === 0 ? (
|
||||
<p className="pit-muted">No changes between these revisions.</p>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
{tab === "documents" ? (
|
||||
documents.length === 0 ? (
|
||||
<div className="pit-devtools-empty">
|
||||
<span aria-hidden="true">▤</span>
|
||||
<p>No documents exist at r{selected.revision}.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="pit-document-browser">
|
||||
<div className="pit-document-sidebar">
|
||||
{documents.map((entry) => (
|
||||
<button
|
||||
type="button"
|
||||
key={entry.id}
|
||||
data-selected={entry.id === document?.id}
|
||||
onClick={() => {
|
||||
setDocumentId(entry.id);
|
||||
setDocumentRevision(0);
|
||||
}}
|
||||
>
|
||||
<strong>{entry.key}</strong>
|
||||
<span>{entry.title}</span>
|
||||
<small>
|
||||
{entry.revisions.length} revision
|
||||
{entry.revisions.length === 1 ? "" : "s"}
|
||||
</small>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{document !== null && visibleDocumentRevision !== null ? (
|
||||
<article className="pit-document-viewer">
|
||||
<header>
|
||||
<div>
|
||||
<span className="pit-card-meta">{document.key}</span>
|
||||
<h4>{document.title}</h4>
|
||||
</div>
|
||||
<select
|
||||
className="pit-select"
|
||||
aria-label="Document revision"
|
||||
value={visibleDocumentRevision.revision}
|
||||
onChange={(event) =>
|
||||
setDocumentRevision(Number(event.target.value))
|
||||
}
|
||||
>
|
||||
{document.revisions.map((entry) => (
|
||||
<option key={entry.id} value={entry.revision}>
|
||||
r{entry.revision}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</header>
|
||||
{visibleDocumentRevision.changeSummary ? (
|
||||
<p className="pit-document-summary">
|
||||
{visibleDocumentRevision.changeSummary}
|
||||
</p>
|
||||
) : null}
|
||||
<pre className="pit-document-body">
|
||||
{visibleDocumentRevision.body}
|
||||
</pre>
|
||||
</article>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
) : null}
|
||||
{tab === "protocol" ? (
|
||||
<div className="pit-devtools-list">
|
||||
{protocol.map((entry) => (
|
||||
<details className="pit-runner-event" key={entry.id}>
|
||||
<summary>
|
||||
<strong>{entry.boundary}</strong> · {entry.event}
|
||||
</summary>
|
||||
<JsonTree value={entry.detail as Json} />
|
||||
</details>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{tab === "trace" ? (
|
||||
snapshot.providerTrace ? (
|
||||
<div className="pit-devtools-pane">
|
||||
<p>
|
||||
<strong>{snapshot.providerTrace.status}</strong> · expires{" "}
|
||||
{snapshot.providerTrace.expiresAt}
|
||||
</p>
|
||||
<h3>Raw frame → Interpretation → PRP events → Presentation</h3>
|
||||
<JsonTree
|
||||
value={
|
||||
{
|
||||
frames: snapshot.providerTrace.frames,
|
||||
interpretations: snapshot.providerTrace.interpretations,
|
||||
} as Json
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="pit-devtools-empty">
|
||||
<span aria-hidden="true">◇</span>
|
||||
<p>
|
||||
Raw provider capture was off for this run. Canonical protocol
|
||||
records remain available in Protocol.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
) : null}
|
||||
{tab === "runtime" ? (
|
||||
<div className="pit-devtools-pane">
|
||||
<JsonTree value={snapshot.runtime as Json} />
|
||||
</div>
|
||||
) : null}
|
||||
{tab === "authority" ? (
|
||||
<div className="pit-devtools-pane">
|
||||
<JsonTree value={snapshot.authority as Json} />
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { CapabilityEvidenceRunnerRecord } from "../../../src/issue-thread/types.js";
|
||||
import { groupCapabilityRunnerEvents } from "./EvidencePanel.js";
|
||||
|
||||
function record(
|
||||
ordinal: number,
|
||||
event: string,
|
||||
turnId = "turn-1",
|
||||
): CapabilityEvidenceRunnerRecord {
|
||||
return {
|
||||
id: `event-${ordinal}`,
|
||||
turnId,
|
||||
kind: "provider_event",
|
||||
ordinal,
|
||||
detail: `provider event · ${event}`,
|
||||
details: [{ label: "Event", value: event }],
|
||||
};
|
||||
}
|
||||
|
||||
describe("Runner event grouping", () => {
|
||||
it("aggregates each delta category per turn at its first position", () => {
|
||||
const session: CapabilityEvidenceRunnerRecord = {
|
||||
id: "event-1",
|
||||
turnId: "turn-0",
|
||||
kind: "session",
|
||||
ordinal: 1,
|
||||
detail: "session · started",
|
||||
details: [{ label: "Action", value: "started" }],
|
||||
};
|
||||
const groups = groupCapabilityRunnerEvents([
|
||||
session,
|
||||
record(2, "assistant_delta"),
|
||||
record(3, "reasoning_delta"),
|
||||
record(4, "assistant_delta"),
|
||||
record(5, "assistant_delta", "turn-2"),
|
||||
]);
|
||||
|
||||
expect(groups.map((group) => [group.event, group.records.map((entry) => entry.ordinal)])).toEqual([
|
||||
[null, [1]],
|
||||
["assistant_delta", [2, 4]],
|
||||
["reasoning_delta", [3]],
|
||||
["assistant_delta", [5]],
|
||||
]);
|
||||
});
|
||||
|
||||
it("leaves non-delta events individually expandable", () => {
|
||||
const groups = groupCapabilityRunnerEvents([
|
||||
record(1, "turn_started"),
|
||||
record(2, "tool_result"),
|
||||
]);
|
||||
|
||||
expect(groups).toHaveLength(2);
|
||||
expect(groups.every((group) => group.event === null && group.records.length === 1)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,622 @@
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
|
||||
import type {
|
||||
CapabilityEvidenceModel,
|
||||
CapabilityEvidenceRunnerRecord,
|
||||
CapabilityEvidenceSectionId,
|
||||
CapabilityEvidenceToolRow,
|
||||
CapabilityIssueThreadSnapshot,
|
||||
CapabilityJsonValue,
|
||||
CapabilityToolDisposition,
|
||||
} from "../../../src/issue-thread/types";
|
||||
import type { CapabilityDevtoolsSnapshot } from "../../../src/devtools";
|
||||
import { DevtoolsInspector, type CapabilityDevtoolsTab, type EvalInspectorReport } from "./DevtoolsInspector";
|
||||
import { Icon } from "./Icons";
|
||||
import { capabilitySemanticToolDescriptor } from "../../../src/semantic-tools/catalog";
|
||||
import {
|
||||
CAPABILITY_EVIDENCE_SECTIONS,
|
||||
capabilityDispositionLabel,
|
||||
} from "../../../src/issue-thread/types";
|
||||
|
||||
/**
|
||||
* Evidence panel (contract §7): eight accordion sections in fixed order with a
|
||||
* turn selector. Every record is rendered from the snapshot; the panel derives
|
||||
* no verdicts of its own.
|
||||
*/
|
||||
|
||||
const DISPOSITION_ORDER: CapabilityToolDisposition[] = [
|
||||
"always_agent_tool",
|
||||
"optional_agent_tool",
|
||||
"control_plane_owned",
|
||||
];
|
||||
|
||||
export interface CapabilityRunnerEventGroup {
|
||||
id: string;
|
||||
event: string | null;
|
||||
records: CapabilityEvidenceRunnerRecord[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream deltas are useful evidence but terrible default reading material.
|
||||
* Aggregate each sanitized delta category within a turn at its first position;
|
||||
* expanding the group still exposes every individual event in ordinal order.
|
||||
*/
|
||||
export function groupCapabilityRunnerEvents(
|
||||
records: readonly CapabilityEvidenceRunnerRecord[],
|
||||
): CapabilityRunnerEventGroup[] {
|
||||
const groups: CapabilityRunnerEventGroup[] = [];
|
||||
const deltaGroups = new Map<string, CapabilityRunnerEventGroup>();
|
||||
for (const record of records) {
|
||||
const event = record.details.find((entry) => entry.label === "Event")?.value ?? null;
|
||||
if (event === null || !event.endsWith("_delta")) {
|
||||
groups.push({ id: record.id, event: null, records: [record] });
|
||||
continue;
|
||||
}
|
||||
const key = `${record.turnId}:${event}`;
|
||||
const existing = deltaGroups.get(key);
|
||||
if (existing !== undefined) {
|
||||
existing.records.push(record);
|
||||
continue;
|
||||
}
|
||||
const group = { id: `delta:${key}`, event, records: [record] };
|
||||
deltaGroups.set(key, group);
|
||||
groups.push(group);
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
function RunnerEvent({ record }: { record: CapabilityEvidenceRunnerRecord }) {
|
||||
return (
|
||||
<details className="pit-runner-event" data-record-id={record.id}>
|
||||
<summary className="pit-runner-event-summary">
|
||||
<span className="pit-record-title">#{record.ordinal} {record.kind}</span>
|
||||
<span className="pit-record-detail">{record.detail}</span>
|
||||
<span className="pit-activity-caret" aria-hidden="true">›</span>
|
||||
</summary>
|
||||
<dl className="pit-runner-event-details">
|
||||
{record.details.length === 0 ? (
|
||||
<>
|
||||
<dt>Detail</dt>
|
||||
<dd>No additional sanitized fields were retained.</dd>
|
||||
</>
|
||||
) : (
|
||||
record.details.map((entry, index) => (
|
||||
<div key={`${entry.label}:${index}`}>
|
||||
<dt>{entry.label}</dt>
|
||||
<dd>{entry.value}</dd>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</dl>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
function RunnerEventGroup({ group }: { group: CapabilityRunnerEventGroup }) {
|
||||
if (group.event === null) return <RunnerEvent record={group.records[0]!} />;
|
||||
return (
|
||||
<details className="pit-runner-group" data-runner-delta-group={group.event}>
|
||||
<summary className="pit-runner-group-summary">
|
||||
<span className="pit-activity-caret" aria-hidden="true">›</span>
|
||||
<span className="pit-record-title">{group.event}</span>
|
||||
<span className="pit-record-detail">
|
||||
{group.records.length} streamed update{group.records.length === 1 ? "" : "s"}
|
||||
</span>
|
||||
</summary>
|
||||
<div className="pit-runner-group-events">
|
||||
{group.records.map((record) => <RunnerEvent key={record.id} record={record} />)}
|
||||
</div>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
export interface EvidencePanelProps {
|
||||
snapshot: CapabilityIssueThreadSnapshot;
|
||||
devtools?: CapabilityDevtoolsSnapshot | null;
|
||||
evalReport?: EvalInspectorReport | null;
|
||||
onForkRevision?: (revision: number) => void;
|
||||
layout: "side" | "overlay" | "segment";
|
||||
width: number;
|
||||
selectedTurnId: string | "all";
|
||||
openSections: CapabilityEvidenceSectionId[];
|
||||
highlightedRecordId: string | null;
|
||||
onSelectTurn: (turnId: string | "all") => void;
|
||||
onToggleSection: (section: CapabilityEvidenceSectionId) => void;
|
||||
onClose: () => void;
|
||||
onJumpToThread: (anchorId: string) => void;
|
||||
onInvokeTool?: (operationId: string, input: CapabilityJsonValue) => Promise<CapabilityJsonValue>;
|
||||
}
|
||||
|
||||
function sectionCount(
|
||||
evidence: CapabilityEvidenceModel,
|
||||
section: CapabilityEvidenceSectionId,
|
||||
turnId: string | "all",
|
||||
): string {
|
||||
if (section === "tools") {
|
||||
const records = filterByTurn(evidence.tools, turnId);
|
||||
return String(new Set(records.flatMap((record) => record.rows.map((row) => row.operationId))).size);
|
||||
}
|
||||
if (section === "parity") {
|
||||
const rows = filterByTurn(evidence.parity, turnId);
|
||||
const passing = rows.filter((row) => row.verdict === "pass").length;
|
||||
return `${passing}/${rows.length}`;
|
||||
}
|
||||
const rows = filterByTurn(
|
||||
evidence[section] as ReadonlyArray<{ turnId: string }>,
|
||||
turnId,
|
||||
);
|
||||
return String(rows.length);
|
||||
}
|
||||
|
||||
function starterInput(schema: { properties?: Readonly<Record<string, { type?: string | readonly string[]; enum?: readonly CapabilityJsonValue[]; default?: CapabilityJsonValue }>>; required?: readonly string[] } | undefined): Record<string, CapabilityJsonValue> {
|
||||
const result: Record<string, CapabilityJsonValue> = {};
|
||||
for (const name of schema?.required ?? []) {
|
||||
const property = schema?.properties?.[name];
|
||||
if (property?.default !== undefined) result[name] = property.default;
|
||||
else if (property?.enum?.[0] !== undefined) result[name] = property.enum[0];
|
||||
else if (name === "idempotencyKey") result[name] = `devtools-${Date.now()}`;
|
||||
else if (property?.type === "integer" || property?.type === "number") result[name] = 0;
|
||||
else if (property?.type === "boolean") result[name] = false;
|
||||
else if (property?.type === "array") result[name] = [];
|
||||
else if (property?.type === "object") result[name] = {};
|
||||
else result[name] = "";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function ToolsBrowser({ records, onInvoke }: { records: CapabilityEvidenceModel["tools"]; onInvoke?: (operationId: string, input: CapabilityJsonValue) => Promise<CapabilityJsonValue> }) {
|
||||
const [collapsed, setCollapsed] = useState<CapabilityToolDisposition[]>([]);
|
||||
const [selected, setSelected] = useState<CapabilityEvidenceToolRow | null>(null);
|
||||
const [inputText, setInputText] = useState("{}");
|
||||
const [invocationResult, setInvocationResult] = useState<CapabilityJsonValue | null>(null);
|
||||
const [invocationError, setInvocationError] = useState<string | null>(null);
|
||||
const [invoking, setInvoking] = useState(false);
|
||||
const rows = useMemo(() => {
|
||||
const unique = new Map<string, CapabilityEvidenceToolRow>();
|
||||
for (const record of records) {
|
||||
for (const row of record.rows) unique.set(row.operationId, row);
|
||||
}
|
||||
return [...unique.values()];
|
||||
}, [records]);
|
||||
const descriptor = selected === null ? undefined : capabilitySemanticToolDescriptor(selected.operationId);
|
||||
|
||||
useEffect(() => {
|
||||
if (selected === null) return;
|
||||
setInputText(JSON.stringify(starterInput(descriptor?.inputSchema), null, 2));
|
||||
setInvocationResult(null);
|
||||
setInvocationError(null);
|
||||
}, [descriptor, selected]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selected === null) return;
|
||||
const close = (event: KeyboardEvent) => { if (event.key === "Escape") setSelected(null); };
|
||||
document.addEventListener("keydown", close);
|
||||
return () => document.removeEventListener("keydown", close);
|
||||
}, [selected]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="pit-tool-groups">
|
||||
{DISPOSITION_ORDER.map((disposition) => {
|
||||
const group = rows.filter((row) => row.disposition === disposition);
|
||||
if (group.length === 0) return null;
|
||||
const folded = collapsed.includes(disposition);
|
||||
const title = disposition === "control_plane_owned"
|
||||
? "Control plane (not exposed to the agent)"
|
||||
: capabilityDispositionLabel(disposition);
|
||||
return (
|
||||
<section className="pit-tool-group" data-group={disposition} key={disposition}>
|
||||
<h4>
|
||||
<button type="button" className="pit-tool-group-toggle" aria-expanded={!folded} onClick={() => setCollapsed((current) => current.includes(disposition) ? current.filter((entry) => entry !== disposition) : [...current, disposition])}>
|
||||
<span aria-hidden="true">{folded ? "›" : "⌄"}</span>
|
||||
<span>{title}</span>
|
||||
<span className="pit-section-count">{group.length}</span>
|
||||
</button>
|
||||
</h4>
|
||||
{!folded ? (
|
||||
<div className="pit-tool-group-rows">
|
||||
{group.map((row) => (
|
||||
<button type="button" className="pit-tool-row" key={row.operationId} data-disposition={disposition} onClick={() => setSelected(row)}>
|
||||
<span className="pit-record-title">{row.operationId}</span>
|
||||
<span className="pit-tool-row-description">{row.description}</span>
|
||||
{row.grant !== null && disposition === "optional_agent_tool" ? <span className="pit-grant">{row.grant}</span> : null}
|
||||
<span className="pit-activity-caret" aria-hidden="true">›</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{selected !== null ? (
|
||||
<div className="pit-dialog-backdrop" onMouseDown={(event) => { if (event.target === event.currentTarget) setSelected(null); }}>
|
||||
<div className="pit-dialog pit-tool-dialog" data-invokable={onInvoke !== undefined} role="dialog" aria-modal="true" aria-labelledby="tool-dialog-title">
|
||||
<header className="pit-tool-dialog-head">
|
||||
<div><span className="pit-card-meta">Semantic tool · v{descriptor?.version ?? 1}</span><h2 id="tool-dialog-title">{descriptor?.title ?? selected.operationId}</h2></div>
|
||||
<button type="button" className="pit-icon-button" aria-label="Close tool details" title="Close tool details" onClick={() => setSelected(null)}><Icon name="close" /></button>
|
||||
</header>
|
||||
<div className="pit-tool-dialog-grid" data-invokable={onInvoke !== undefined}>
|
||||
<div className="pit-tool-reference">
|
||||
<code className="pit-tool-operation">{selected.operationId}</code>
|
||||
<p>{descriptor?.description ?? selected.description}</p>
|
||||
<dl className="pit-tool-facts">
|
||||
<div><dt>Placement</dt><dd>{capabilityDispositionLabel(selected.disposition)}</dd></div>
|
||||
<div><dt>Required claims</dt><dd>{descriptor?.requiredClaims.join(", ") || selected.grant || "None"}</dd></div>
|
||||
<div><dt>Task modes</dt><dd>{descriptor?.allowedModes.join(", ") || "—"}</dd></div>
|
||||
<div><dt>Actor roles</dt><dd>{descriptor?.allowedRoles?.join(", ") || "Any allowed role"}</dd></div>
|
||||
</dl>
|
||||
<div>
|
||||
<h3 className="pit-tool-schema-title">Input schema</h3>
|
||||
<pre className="pit-code">{JSON.stringify(descriptor?.inputSchema ?? {}, null, 2)}</pre>
|
||||
</div>
|
||||
</div>
|
||||
{onInvoke !== undefined ? (
|
||||
<div className="pit-tool-tester">
|
||||
<h3 className="pit-tool-schema-title">Invoke in conversation</h3>
|
||||
<p className="pit-muted">Runs through the real semantic dispatcher and records a turn, evidence, and company-state changes.</p>
|
||||
<label className="pit-card-meta" htmlFor="tool-test-input">Parameters (JSON)</label>
|
||||
<textarea id="tool-test-input" className="pit-tool-test-input" value={inputText} onChange={(event) => setInputText(event.target.value)} spellCheck={false} />
|
||||
<button type="button" className="pit-button" disabled={invoking} onClick={() => {
|
||||
let parsed: CapabilityJsonValue;
|
||||
try {
|
||||
parsed = JSON.parse(inputText) as CapabilityJsonValue;
|
||||
} catch (error) {
|
||||
setInvocationError(error instanceof Error ? error.message : String(error));
|
||||
return;
|
||||
}
|
||||
setInvoking(true);
|
||||
setInvocationError(null);
|
||||
setInvocationResult(null);
|
||||
void onInvoke(selected.operationId, parsed)
|
||||
.then(setInvocationResult)
|
||||
.catch((error) => setInvocationError(error instanceof Error ? error.message : String(error)))
|
||||
.finally(() => setInvoking(false));
|
||||
}}>{invoking ? "Invoking…" : "Invoke as tool call"}</button>
|
||||
{invocationError !== null ? <p className="pit-error" role="alert">{invocationError}</p> : null}
|
||||
{invocationResult !== null ? <pre className="pit-code" data-testid="tool-test-result">{JSON.stringify(invocationResult, null, 2)}</pre> : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function filterByTurn<T extends { turnId: string }>(
|
||||
rows: ReadonlyArray<T>,
|
||||
turnId: string | "all",
|
||||
): T[] {
|
||||
return turnId === "all" ? [...rows] : rows.filter((row) => row.turnId === turnId);
|
||||
}
|
||||
|
||||
function Section({
|
||||
id,
|
||||
title,
|
||||
count,
|
||||
open,
|
||||
onToggle,
|
||||
children,
|
||||
}: {
|
||||
id: CapabilityEvidenceSectionId;
|
||||
title: string;
|
||||
count: string;
|
||||
open: boolean;
|
||||
onToggle: () => void;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<section className="pit-section" data-evidence-section={id}>
|
||||
<h3>
|
||||
<button
|
||||
type="button"
|
||||
className="pit-section-button"
|
||||
aria-expanded={open}
|
||||
aria-controls={`evidence-section-${id}`}
|
||||
onClick={onToggle}
|
||||
>
|
||||
<span aria-hidden="true">{open ? "⌄" : "›"}</span>
|
||||
{title}
|
||||
<span className="pit-section-count">{count}</span>
|
||||
</button>
|
||||
</h3>
|
||||
<div className="pit-section-body" id={`evidence-section-${id}`} hidden={!open}>
|
||||
{children}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function EvidencePanel(props: EvidencePanelProps) {
|
||||
const [devtoolsTab, setDevtoolsTab] = useState<CapabilityDevtoolsTab>(props.evalReport ? "eval" : "evidence");
|
||||
const {
|
||||
snapshot,
|
||||
devtools,
|
||||
evalReport,
|
||||
onForkRevision = () => undefined,
|
||||
layout,
|
||||
width,
|
||||
selectedTurnId,
|
||||
openSections,
|
||||
highlightedRecordId,
|
||||
onSelectTurn,
|
||||
onToggleSection,
|
||||
onClose,
|
||||
onJumpToThread,
|
||||
onInvokeTool,
|
||||
} = props;
|
||||
const headingRef = useRef<HTMLHeadingElement | null>(null);
|
||||
const evidence = snapshot.evidence;
|
||||
|
||||
useEffect(() => {
|
||||
// Contract §9.2: opening Evidence moves focus to its heading.
|
||||
headingRef.current?.focus();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
// Contract §9.1: Escape closes the desktop overlay sheet. The side panel is
|
||||
// a persistent region rather than a sheet, and the mobile segment is a tab
|
||||
// view, so neither of those is dismissible this way.
|
||||
if (layout !== "overlay") return;
|
||||
function onKeyDown(event: KeyboardEvent) {
|
||||
if (event.key !== "Escape") return;
|
||||
// A modal dialog owns Escape while it is open (§6 reset confirm).
|
||||
if (document.querySelector('[role="dialog"][aria-modal="true"]') !== null) return;
|
||||
onClose();
|
||||
}
|
||||
document.addEventListener("keydown", onKeyDown);
|
||||
return () => document.removeEventListener("keydown", onKeyDown);
|
||||
}, [layout, onClose]);
|
||||
|
||||
const isOpen = (section: CapabilityEvidenceSectionId) => openSections.includes(section);
|
||||
|
||||
return (
|
||||
<aside
|
||||
className="pit-panel"
|
||||
data-layout={layout}
|
||||
data-testid="evidence-panel"
|
||||
style={layout === "side" ? { width: `${width}px` } : undefined}
|
||||
aria-label="Evidence"
|
||||
>
|
||||
<div className="pit-panel-chrome">
|
||||
<h2 className="pit-visually-hidden" tabIndex={-1} ref={headingRef}>Developer tools</h2>
|
||||
<span className="pit-panel-kicker"><Icon name="activity" /> Paperclip DevTools</span>
|
||||
<button type="button" className="pit-icon-button" onClick={onClose} aria-label="Close DevTools" title="Close DevTools">
|
||||
<Icon name="close" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{devtools !== undefined ? (
|
||||
<>
|
||||
{devtools === null ? (
|
||||
<p className="pit-muted pit-devtools-loading">Loading company state…</p>
|
||||
) : (
|
||||
<DevtoolsInspector snapshot={devtools} onFork={onForkRevision} tab={devtoolsTab} onTabChange={setDevtoolsTab} evalReport={evalReport} />
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{devtoolsTab === "evidence" ? <div className="pit-evidence-browser">
|
||||
<div className="pit-evidence-filter">
|
||||
<label className="pit-card-meta" htmlFor="evidence-turn-selector">Evidence scope</label>
|
||||
<select className="pit-select" id="evidence-turn-selector" value={selectedTurnId} onChange={(event) => onSelectTurn(event.target.value as string | "all")}>
|
||||
{snapshot.turns.map((turn) => <option key={turn.id} value={turn.id}>Turn {turn.ordinal}</option>)}
|
||||
<option value="all">All turns</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<Section
|
||||
id="tools"
|
||||
title="Tools exposed"
|
||||
count={sectionCount(evidence, "tools", selectedTurnId)}
|
||||
open={isOpen("tools")}
|
||||
onToggle={() => onToggleSection("tools")}
|
||||
>
|
||||
<ToolsBrowser records={filterByTurn(evidence.tools, selectedTurnId)} onInvoke={onInvokeTool} />
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
id="calls"
|
||||
title="Calls & results"
|
||||
count={sectionCount(evidence, "calls", selectedTurnId)}
|
||||
open={isOpen("calls")}
|
||||
onToggle={() => onToggleSection("calls")}
|
||||
>
|
||||
{filterByTurn(evidence.calls, selectedTurnId).map((record) => (
|
||||
<div
|
||||
className="pit-record"
|
||||
key={record.id}
|
||||
data-record-id={record.id}
|
||||
data-highlighted={highlightedRecordId === record.id}
|
||||
>
|
||||
<span className="pit-record-title">
|
||||
{record.operationId} · v{record.version} · {record.outcome}
|
||||
</span>
|
||||
<span className="pit-record-detail">{record.providerRequest}</span>
|
||||
<span className="pit-record-detail">{record.dispatchedCommand}</span>
|
||||
<span className="pit-record-detail">{JSON.stringify(record.result)}</span>
|
||||
{record.redactions.length > 0 ? (
|
||||
<span className="pit-record-detail">
|
||||
••• redacted by {record.redactions.join(", ")}
|
||||
</span>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
className="pit-link-button"
|
||||
onClick={() => onJumpToThread(record.threadAnchorId)}
|
||||
>
|
||||
Show in thread
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
id="authorization"
|
||||
title="Authorization"
|
||||
count={sectionCount(evidence, "authorization", selectedTurnId)}
|
||||
open={isOpen("authorization")}
|
||||
onToggle={() => onToggleSection("authorization")}
|
||||
>
|
||||
{filterByTurn(evidence.authorization, selectedTurnId).map((record) => (
|
||||
<div
|
||||
className="pit-record"
|
||||
key={record.id}
|
||||
data-record-id={record.id}
|
||||
data-allowed={record.allowed}
|
||||
data-highlighted={highlightedRecordId === record.id}
|
||||
>
|
||||
<span className="pit-record-title">
|
||||
<span aria-hidden="true">{record.allowed ? "✓" : "✕"}</span>{" "}
|
||||
{record.operationId} · {record.phase} · {record.allowed ? "allowed" : "denied"}
|
||||
</span>
|
||||
<span className="pit-record-detail">{record.reason}</span>
|
||||
<span className="pit-record-detail">
|
||||
claims: {record.claimsConsidered.join(", ") || "none"}
|
||||
</span>
|
||||
{record.redactions.length > 0 ? (
|
||||
<span className="pit-record-detail">
|
||||
••• redacted by {record.redactions.join(", ")}
|
||||
</span>
|
||||
) : null}
|
||||
{record.stateChangeRef !== null ? (
|
||||
<span className="pit-record-detail">state: {record.stateChangeRef}</span>
|
||||
) : null}
|
||||
{record.threadAnchorId.length > 0 ? (
|
||||
<button
|
||||
type="button"
|
||||
className="pit-link-button"
|
||||
onClick={() => onJumpToThread(record.threadAnchorId)}
|
||||
>
|
||||
Show in thread
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
id="control_plane"
|
||||
title="Control plane"
|
||||
count={sectionCount(evidence, "control_plane", selectedTurnId)}
|
||||
open={isOpen("control_plane")}
|
||||
onToggle={() => onToggleSection("control_plane")}
|
||||
>
|
||||
{filterByTurn(evidence.control_plane, selectedTurnId).map((record) => (
|
||||
<div
|
||||
className="pit-record"
|
||||
key={record.id}
|
||||
data-record-id={record.id}
|
||||
data-highlighted={highlightedRecordId === record.id}
|
||||
>
|
||||
<span className="pit-record-title">
|
||||
{record.category} · {record.outcome} · rev {record.stateRevision}
|
||||
</span>
|
||||
<span className="pit-record-detail">{record.reason}</span>
|
||||
</div>
|
||||
))}
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
id="runner"
|
||||
title="Runner & events"
|
||||
count={sectionCount(evidence, "runner", selectedTurnId)}
|
||||
open={isOpen("runner")}
|
||||
onToggle={() => onToggleSection("runner")}
|
||||
>
|
||||
{groupCapabilityRunnerEvents(filterByTurn(evidence.runner, selectedTurnId)).map((group) => (
|
||||
<RunnerEventGroup key={group.id} group={group} />
|
||||
))}
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
id="state"
|
||||
title="State diff"
|
||||
count={sectionCount(evidence, "state", selectedTurnId)}
|
||||
open={isOpen("state")}
|
||||
onToggle={() => onToggleSection("state")}
|
||||
>
|
||||
{filterByTurn(evidence.state, selectedTurnId).map((record) => (
|
||||
<div
|
||||
className="pit-record"
|
||||
key={record.id}
|
||||
data-record-id={record.id}
|
||||
data-highlighted={highlightedRecordId === record.id}
|
||||
>
|
||||
<span className="pit-record-title">
|
||||
revision {record.fromRevision} → {record.toRevision}
|
||||
</span>
|
||||
{record.rows.map((row) => (
|
||||
<div className="pit-diff-row" key={`${row.entityClass}-${row.entityRef}`}>
|
||||
<span className="pit-record-detail">
|
||||
{row.entityClass} · {row.entityRef}
|
||||
</span>
|
||||
<span className="pit-record-detail">
|
||||
{row.before} → {row.after}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
id="traceability"
|
||||
title="Traceability"
|
||||
count={sectionCount(evidence, "traceability", selectedTurnId)}
|
||||
open={isOpen("traceability")}
|
||||
onToggle={() => onToggleSection("traceability")}
|
||||
>
|
||||
{filterByTurn(evidence.traceability, selectedTurnId).map((record) => (
|
||||
<div className="pit-record" key={record.id} data-record-id={record.id}>
|
||||
<span className="pit-record-title">
|
||||
{record.caseId} · {record.group}
|
||||
</span>
|
||||
<span className="pit-record-detail">{record.sourceAnchor}</span>
|
||||
<span className="pit-record-detail">{record.browserEvidenceRecipe}</span>
|
||||
<span className="pit-record-detail">
|
||||
expects: {record.expectedSemanticOperations.join(", ")}
|
||||
</span>
|
||||
<span className="pit-record-detail">
|
||||
forbids: {record.forbiddenOperations.join(", ") || "none"}
|
||||
</span>
|
||||
<span className="pit-record-detail">
|
||||
grants: {record.requiredCapabilityGrants.join(", ") || "none"}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
id="parity"
|
||||
title="Parity"
|
||||
count={sectionCount(evidence, "parity", selectedTurnId)}
|
||||
open={isOpen("parity")}
|
||||
onToggle={() => onToggleSection("parity")}
|
||||
>
|
||||
{filterByTurn(evidence.parity, selectedTurnId).map((record) => (
|
||||
<div className="pit-record" key={record.id} data-record-id={record.id}>
|
||||
<span className="pit-verdict" data-verdict={record.verdict}>
|
||||
<span aria-hidden="true">
|
||||
{record.verdict === "pass" ? "✓" : record.verdict === "fail" ? "✕" : "—"}
|
||||
</span>
|
||||
{record.verdict === "intentional_gap" ? "intentional gap" : record.verdict}
|
||||
</span>
|
||||
<span className="pit-record-detail">{record.assertion}</span>
|
||||
{record.note !== null ? (
|
||||
<span className="pit-record-detail">{record.note}</span>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</Section>
|
||||
</div> : null}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
export const CAPABILITY_EVIDENCE_SECTION_IDS = CAPABILITY_EVIDENCE_SECTIONS.map(
|
||||
(section) => section.id,
|
||||
);
|
||||
@@ -0,0 +1,32 @@
|
||||
export type IconName =
|
||||
| "activity" | "authority" | "branch" | "close" | "diff" | "documents"
|
||||
| "download" | "evidence" | "pause" | "play" | "protocol" | "reset"
|
||||
| "spark" | "state" | "stop" | "terminal" | "timeline";
|
||||
|
||||
const PATHS: Record<IconName, string> = {
|
||||
activity: "M3 12h3l2-6 4 12 3-9 2 5h4",
|
||||
authority: "M12 3l7 4v5c0 4.6-2.8 7.6-7 9-4.2-1.4-7-4.4-7-9V7zM9 12l2 2 4-4",
|
||||
branch: "M6 3v12a3 3 0 0 0 3 3h6M15 18l-3-3m3 3-3 3M6 7h6a3 3 0 0 0 3-3V3",
|
||||
close: "M5 5l14 14M19 5 5 19",
|
||||
diff: "M8 5v14M4 9h8M17 7v10M14 12h6",
|
||||
documents: "M6 3h9l3 3v15H6zM15 3v4h4M9 11h6M9 15h6",
|
||||
download: "M12 3v12m-5-5 5 5 5-5M5 21h14",
|
||||
evidence: "M4 5h16v14H4zM8 9h8M8 13h5",
|
||||
pause: "M8 5v14M16 5v14",
|
||||
play: "M8 5v14l11-7z",
|
||||
protocol: "M4 8h14m-3-3 3 3-3 3M20 16H6m3-3-3 3 3 3",
|
||||
reset: "M5 8a8 8 0 1 1-1 7M5 8V3m0 5h5",
|
||||
spark: "M12 2l1.7 5.3L19 9l-5.3 1.7L12 16l-1.7-5.3L5 9l5.3-1.7zM19 16l.8 2.2L22 19l-2.2.8L19 22l-.8-2.2L16 19l2.2-.8z",
|
||||
state: "M9 4H6a2 2 0 0 0-2 2v3M15 4h3a2 2 0 0 1 2 2v3M9 20H6a2 2 0 0 1-2-2v-3M15 20h3a2 2 0 0 0 2-2v-3M9 9h6v6H9z",
|
||||
stop: "M7 7h10v10H7z",
|
||||
terminal: "M5 7l4 5-4 5m7 0h7",
|
||||
timeline: "M5 5v14M5 8h5M5 13h9M5 18h13",
|
||||
};
|
||||
|
||||
export function Icon({ name }: { name: IconName }) {
|
||||
return (
|
||||
<svg className="pit-icon" viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d={PATHS[name]} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,528 @@
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
|
||||
import type {
|
||||
CapabilityThreadInteractionCard,
|
||||
CapabilityThreadInteractionState,
|
||||
} from "../../../src/issue-thread/types";
|
||||
import { Chip } from "./primitives";
|
||||
|
||||
/**
|
||||
* Native interaction cards (contract §5). All five `request_human_input`
|
||||
* kinds render typed controls; the card never asks the user to type an answer
|
||||
* into the composer.
|
||||
*
|
||||
* The submit handler posts to the package server, which stores the response in
|
||||
* the mock control plane before the runner is resumed. The card only leaves
|
||||
* `submitting` when the server acknowledges — there is no optimistic
|
||||
* resolution here.
|
||||
*/
|
||||
|
||||
export interface CapabilityInteractionResponse {
|
||||
interactionId: string;
|
||||
outcome: "answered" | "accepted" | "rejected";
|
||||
result: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const STATE_GLYPH: Record<CapabilityThreadInteractionState, string> = {
|
||||
pending: "⏳",
|
||||
submitting: "⏳",
|
||||
accepted: "✓",
|
||||
answered: "✓",
|
||||
rejected: "✕",
|
||||
stale_target: "⌛",
|
||||
superseded_by_comment: "⌛",
|
||||
expired: "⌛",
|
||||
withdrawn: "⌛",
|
||||
issue_closed: "⌛",
|
||||
};
|
||||
|
||||
const RESOLVED_STATES = new Set<CapabilityThreadInteractionState>([
|
||||
"accepted",
|
||||
"answered",
|
||||
"rejected",
|
||||
"stale_target",
|
||||
"superseded_by_comment",
|
||||
"expired",
|
||||
"withdrawn",
|
||||
"issue_closed",
|
||||
]);
|
||||
|
||||
function stateTone(state: CapabilityThreadInteractionState) {
|
||||
if (state === "accepted" || state === "answered") return "success" as const;
|
||||
if (state === "rejected") return "danger" as const;
|
||||
if (state === "pending" || state === "submitting") return "accent" as const;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function InteractionCard({
|
||||
card,
|
||||
onRespond,
|
||||
onOpenEvidence,
|
||||
autoFocus,
|
||||
}: {
|
||||
card: CapabilityThreadInteractionCard;
|
||||
onRespond?: (response: CapabilityInteractionResponse) => void;
|
||||
onOpenEvidence?: (section: string, recordId: string) => void;
|
||||
autoFocus?: boolean;
|
||||
}) {
|
||||
const titleId = useId();
|
||||
const [answers, setAnswers] = useState<Record<string, string>>({});
|
||||
const [selected, setSelected] = useState<string[]>(() =>
|
||||
card.payload.kind === "checkbox"
|
||||
? card.payload.options.filter((option) => option.defaultSelected).map((option) => option.id)
|
||||
: card.payload.kind === "suggest_tasks"
|
||||
? card.payload.tasks.map((task) => task.id)
|
||||
: [],
|
||||
);
|
||||
const [verdicts, setVerdicts] = useState<Record<string, string>>({});
|
||||
const [reasons, setReasons] = useState<Record<string, string>>({});
|
||||
const [rejectReason, setRejectReason] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const firstControl = useRef<HTMLElement | null>(null);
|
||||
const stateChip = useRef<HTMLSpanElement | null>(null);
|
||||
const previousState = useRef<CapabilityThreadInteractionState>(card.state);
|
||||
const resolved = RESOLVED_STATES.has(card.state);
|
||||
const busy = card.state === "submitting";
|
||||
|
||||
useEffect(() => {
|
||||
// Contract §9.2: resolving a card moves focus to its state chip. The
|
||||
// controls the user just used unmount on resolve, so without this the
|
||||
// keyboard caret would fall back to `body` exactly when the card changes.
|
||||
const from = previousState.current;
|
||||
previousState.current = card.state;
|
||||
if (from === card.state) return;
|
||||
if (!RESOLVED_STATES.has(from) && RESOLVED_STATES.has(card.state)) {
|
||||
stateChip.current?.focus();
|
||||
}
|
||||
}, [card.state]);
|
||||
|
||||
function respond(response: CapabilityInteractionResponse) {
|
||||
setError(null);
|
||||
onRespond?.(response);
|
||||
}
|
||||
|
||||
function toggle(list: string[], id: string): string[] {
|
||||
return list.includes(id) ? list.filter((entry) => entry !== id) : [...list, id];
|
||||
}
|
||||
|
||||
return (
|
||||
<section
|
||||
className="pit-interaction"
|
||||
data-interaction-id={card.interactionId}
|
||||
data-interaction-kind={card.interactionKind}
|
||||
data-interaction-state={card.state}
|
||||
aria-labelledby={titleId}
|
||||
id={`interaction-${card.interactionId}`}
|
||||
>
|
||||
<div className="pit-card-head">
|
||||
<h3 className="pit-interaction-title" id={titleId}>
|
||||
{card.title}
|
||||
</h3>
|
||||
<Chip
|
||||
tone={stateTone(card.state)}
|
||||
testId="interaction-state-chip"
|
||||
tabIndex={-1}
|
||||
chipRef={stateChip}
|
||||
>
|
||||
<span aria-hidden="true">{STATE_GLYPH[card.state]}</span>
|
||||
{card.stateLabel}
|
||||
</Chip>
|
||||
</div>
|
||||
|
||||
<p className="pit-card-body">{card.prompt}</p>
|
||||
|
||||
{card.target !== null ? (
|
||||
<p className="pit-card-meta">
|
||||
Target:{" "}
|
||||
<a href={card.target.href} data-testid="interaction-target">
|
||||
{card.target.label}
|
||||
</a>
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{card.payload.kind === "confirmation" ? (
|
||||
<p className="pit-quote">{card.payload.targetSummary}</p>
|
||||
) : null}
|
||||
|
||||
{resolved ? (
|
||||
<div className="pit-interaction-controls">
|
||||
{card.resolvedSummary.length > 0 ? (
|
||||
<ul className="pit-summary-list">
|
||||
{card.resolvedSummary.map((entry) => (
|
||||
<li key={entry}>{entry}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
{card.reason !== null ? <blockquote className="pit-quote">{card.reason}</blockquote> : null}
|
||||
{card.supersededBy !== null ? (
|
||||
<p className="pit-card-meta">
|
||||
<a href={card.supersededBy.href}>{card.supersededBy.label}</a>
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
) : (
|
||||
<div className="pit-interaction-controls">
|
||||
{card.payload.kind === "questions"
|
||||
? card.payload.questions.map((question, index) => (
|
||||
<div className="pit-field" key={question.id}>
|
||||
<span className="pit-field-label" id={`${titleId}-${question.id}`}>
|
||||
{question.prompt}
|
||||
</span>
|
||||
{question.control === "text" ? (
|
||||
<input
|
||||
className="pit-input"
|
||||
type="text"
|
||||
aria-labelledby={`${titleId}-${question.id}`}
|
||||
disabled={busy}
|
||||
value={answers[question.id] ?? ""}
|
||||
onChange={(event) =>
|
||||
setAnswers((current) => ({ ...current, [question.id]: event.target.value }))
|
||||
}
|
||||
/>
|
||||
) : question.control === "select" ? (
|
||||
<select
|
||||
className="pit-select"
|
||||
aria-labelledby={`${titleId}-${question.id}`}
|
||||
disabled={busy}
|
||||
value={answers[question.id] ?? ""}
|
||||
onChange={(event) =>
|
||||
setAnswers((current) => ({ ...current, [question.id]: event.target.value }))
|
||||
}
|
||||
>
|
||||
<option value="">Choose…</option>
|
||||
{(question.options ?? []).map((option) => (
|
||||
<option key={option} value={option}>
|
||||
{option}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
<div role="radiogroup" aria-labelledby={`${titleId}-${question.id}`}>
|
||||
{(question.options ?? []).map((option, optionIndex) => (
|
||||
<label className="pit-option-row" key={option}>
|
||||
<input
|
||||
type="radio"
|
||||
name={`${card.interactionId}-${question.id}`}
|
||||
value={option}
|
||||
disabled={busy}
|
||||
ref={
|
||||
index === 0 && optionIndex === 0
|
||||
? (node) => {
|
||||
firstControl.current = node;
|
||||
if (autoFocus === true && node !== null) node.focus();
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
checked={answers[question.id] === option}
|
||||
onChange={() =>
|
||||
setAnswers((current) => ({ ...current, [question.id]: option }))
|
||||
}
|
||||
/>
|
||||
<span>{option}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))
|
||||
: null}
|
||||
|
||||
{card.payload.kind === "checkbox"
|
||||
? card.payload.options.map((option, index) => (
|
||||
<label className="pit-option-row" key={option.id}>
|
||||
<input
|
||||
type="checkbox"
|
||||
disabled={busy}
|
||||
checked={selected.includes(option.id)}
|
||||
ref={
|
||||
index === 0
|
||||
? (node) => {
|
||||
if (autoFocus === true && node !== null) node.focus();
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onChange={() => setSelected((current) => toggle(current, option.id))}
|
||||
/>
|
||||
<span>{option.label}</span>
|
||||
</label>
|
||||
))
|
||||
: null}
|
||||
|
||||
{card.payload.kind === "suggest_tasks"
|
||||
? card.payload.tasks.map((task) => (
|
||||
<label className="pit-option-row" key={task.id}>
|
||||
<input
|
||||
type="checkbox"
|
||||
disabled={busy}
|
||||
checked={selected.includes(task.id)}
|
||||
onChange={() => setSelected((current) => toggle(current, task.id))}
|
||||
/>
|
||||
<span>
|
||||
<strong>{task.title}</strong>
|
||||
<br />
|
||||
<span className="pit-card-meta">{task.description}</span>
|
||||
</span>
|
||||
</label>
|
||||
))
|
||||
: null}
|
||||
|
||||
{card.payload.kind === "item_verdicts"
|
||||
? card.payload.items.map((item) => (
|
||||
<div className="pit-field" key={item.id}>
|
||||
<span className="pit-field-label" id={`${titleId}-${item.id}`}>
|
||||
{item.title}
|
||||
</span>
|
||||
<div
|
||||
className="pit-segmented-verdicts"
|
||||
role="radiogroup"
|
||||
aria-labelledby={`${titleId}-${item.id}`}
|
||||
>
|
||||
{(["approve", "reject", "defer"] as const).map((verdict) => (
|
||||
<button
|
||||
key={verdict}
|
||||
type="button"
|
||||
className="pit-button"
|
||||
role="radio"
|
||||
aria-checked={
|
||||
(item.lockedVerdict ?? verdicts[item.id] ?? "") === verdict
|
||||
}
|
||||
disabled={busy || item.lockedVerdict != null}
|
||||
onClick={() =>
|
||||
setVerdicts((current) => ({ ...current, [item.id]: verdict }))
|
||||
}
|
||||
>
|
||||
{verdict}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{item.requireReason === true ? (
|
||||
<textarea
|
||||
className="pit-textarea"
|
||||
aria-label={`Reason for ${item.title}`}
|
||||
disabled={busy || item.lockedVerdict != null}
|
||||
value={reasons[item.id] ?? ""}
|
||||
onChange={(event) =>
|
||||
setReasons((current) => ({ ...current, [item.id]: event.target.value }))
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
))
|
||||
: null}
|
||||
|
||||
{card.payload.kind === "confirmation" && card.payload.requireRejectReason ? (
|
||||
<div className="pit-field">
|
||||
<label className="pit-field-label" htmlFor={`${titleId}-reject-reason`}>
|
||||
Reason (required to request changes)
|
||||
</label>
|
||||
<textarea
|
||||
className="pit-textarea"
|
||||
id={`${titleId}-reject-reason`}
|
||||
disabled={busy}
|
||||
value={rejectReason}
|
||||
onChange={(event) => setRejectReason(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{error !== null ? (
|
||||
<p className="pit-composer-reason" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="pit-button-row">
|
||||
{card.payload.kind === "confirmation" ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="pit-button"
|
||||
data-variant="primary"
|
||||
disabled={busy}
|
||||
ref={(node) => {
|
||||
if (autoFocus === true && node !== null && firstControl.current === null) {
|
||||
firstControl.current = node;
|
||||
node.focus();
|
||||
}
|
||||
}}
|
||||
onClick={() =>
|
||||
respond({
|
||||
interactionId: card.interactionId,
|
||||
outcome: "accepted",
|
||||
result: { accepted: true },
|
||||
})
|
||||
}
|
||||
>
|
||||
{card.payload.acceptLabel}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="pit-button"
|
||||
data-variant="destructive"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
if (
|
||||
card.payload.kind === "confirmation" &&
|
||||
card.payload.requireRejectReason &&
|
||||
rejectReason.trim().length === 0
|
||||
) {
|
||||
setError("A reason is required to request changes.");
|
||||
return;
|
||||
}
|
||||
respond({
|
||||
interactionId: card.interactionId,
|
||||
outcome: "rejected",
|
||||
result: { accepted: false, reason: rejectReason },
|
||||
});
|
||||
}}
|
||||
>
|
||||
{card.payload.rejectLabel}
|
||||
</button>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{card.payload.kind === "questions" ? (
|
||||
<button
|
||||
type="button"
|
||||
className="pit-button"
|
||||
data-variant="primary"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
const missing =
|
||||
card.payload.kind === "questions"
|
||||
? card.payload.questions.filter(
|
||||
(question) =>
|
||||
question.required === true &&
|
||||
(answers[question.id] ?? "").trim().length === 0,
|
||||
)
|
||||
: [];
|
||||
if (missing.length > 0) {
|
||||
setError(`Answer every required question (${missing.length} remaining).`);
|
||||
return;
|
||||
}
|
||||
respond({
|
||||
interactionId: card.interactionId,
|
||||
outcome: "answered",
|
||||
result: { answers },
|
||||
});
|
||||
}}
|
||||
>
|
||||
{card.payload.submitLabel}
|
||||
</button>
|
||||
) : null}
|
||||
|
||||
{card.payload.kind === "checkbox" ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="pit-button"
|
||||
data-variant="primary"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
if (card.payload.kind !== "checkbox") return;
|
||||
if (selected.length < card.payload.minSelected) {
|
||||
setError(`Select at least ${card.payload.minSelected}.`);
|
||||
return;
|
||||
}
|
||||
if (selected.length > card.payload.maxSelected) {
|
||||
setError(`Select at most ${card.payload.maxSelected}.`);
|
||||
return;
|
||||
}
|
||||
respond({
|
||||
interactionId: card.interactionId,
|
||||
outcome: "accepted",
|
||||
result: { selected },
|
||||
});
|
||||
}}
|
||||
>
|
||||
{card.payload.acceptLabel}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="pit-button"
|
||||
data-variant="destructive"
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
respond({
|
||||
interactionId: card.interactionId,
|
||||
outcome: "rejected",
|
||||
result: { selected: [] },
|
||||
})
|
||||
}
|
||||
>
|
||||
{card.payload.rejectLabel}
|
||||
</button>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{card.payload.kind === "suggest_tasks" ? (
|
||||
<button
|
||||
type="button"
|
||||
className="pit-button"
|
||||
data-variant="primary"
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
respond({
|
||||
interactionId: card.interactionId,
|
||||
outcome: "accepted",
|
||||
result: { acceptedTaskIds: selected },
|
||||
})
|
||||
}
|
||||
>
|
||||
{card.payload.acceptLabel}
|
||||
</button>
|
||||
) : null}
|
||||
|
||||
{card.payload.kind === "item_verdicts" ? (
|
||||
<button
|
||||
type="button"
|
||||
className="pit-button"
|
||||
data-variant="primary"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
if (card.payload.kind !== "item_verdicts") return;
|
||||
const submitted = card.payload.items.filter(
|
||||
(item) => item.lockedVerdict == null && verdicts[item.id] !== undefined,
|
||||
);
|
||||
const missingReason = submitted.filter(
|
||||
(item) =>
|
||||
item.requireReason === true && (reasons[item.id] ?? "").trim().length === 0,
|
||||
);
|
||||
if (missingReason.length > 0) {
|
||||
setError(`A reason is required for ${missingReason.length} item(s).`);
|
||||
return;
|
||||
}
|
||||
if (submitted.length === 0) {
|
||||
setError("Choose a verdict for at least one item.");
|
||||
return;
|
||||
}
|
||||
respond({
|
||||
interactionId: card.interactionId,
|
||||
outcome: "answered",
|
||||
result: {
|
||||
verdicts: submitted.map((item) => ({
|
||||
id: item.id,
|
||||
verdict: verdicts[item.id],
|
||||
reason: reasons[item.id] ?? null,
|
||||
})),
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
{card.payload.submitLabel}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="pit-link-button"
|
||||
onClick={() => onOpenEvidence?.(card.evidenceRef.section, card.evidenceRef.recordId)}
|
||||
>
|
||||
View request evidence
|
||||
</button>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
import type { CapabilityIssueThreadSnapshot } from "../../../src/issue-thread/types";
|
||||
import { Icon } from "./Icons";
|
||||
import { Chip, PriorityIcon, StatusBadge } from "./primitives";
|
||||
|
||||
/**
|
||||
* Sticky issue header (contract §1 and §2). The three identity chips are never
|
||||
* hidden by scroll, mode is data rather than styling, and on mobile Stop stays
|
||||
* outside the overflow menu whenever a turn is active.
|
||||
*/
|
||||
|
||||
export interface IssueHeaderProps {
|
||||
snapshot: CapabilityIssueThreadSnapshot;
|
||||
scenarios: string[];
|
||||
/** `chat` is the clean room: no preset scenario, no recording to replay. */
|
||||
surface?: "issue" | "chat";
|
||||
/** Immutable eval recordings use the same inspector without live controls. */
|
||||
readOnly?: boolean;
|
||||
/** Clean-room tenant token, rendered so identity rotation is visible. */
|
||||
cleanRoomToken?: string | null;
|
||||
evidenceOpen: boolean;
|
||||
denialCount: number;
|
||||
segment: "thread" | "evidence";
|
||||
onToggleEvidence: () => void;
|
||||
onSelectScenario: (scenario: string) => void;
|
||||
onReplay: () => void;
|
||||
onReset: () => void;
|
||||
onStop: () => void;
|
||||
onSelectSegment: (segment: "thread" | "evidence") => void;
|
||||
}
|
||||
|
||||
export function IssueHeader(props: IssueHeaderProps) {
|
||||
const {
|
||||
snapshot,
|
||||
scenarios,
|
||||
surface = "issue",
|
||||
readOnly = false,
|
||||
cleanRoomToken = null,
|
||||
evidenceOpen,
|
||||
denialCount,
|
||||
segment,
|
||||
onToggleEvidence,
|
||||
onSelectScenario,
|
||||
onReplay,
|
||||
onReset,
|
||||
onStop,
|
||||
onSelectSegment,
|
||||
} = props;
|
||||
const chat = surface === "chat";
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const menuRef = useRef<HTMLDivElement | null>(null);
|
||||
const turnActive = snapshot.composer.state === "streaming" || snapshot.composer.state === "sending";
|
||||
|
||||
useEffect(() => {
|
||||
if (!menuOpen) return;
|
||||
function onKeyDown(event: KeyboardEvent) {
|
||||
if (event.key === "Escape") setMenuOpen(false);
|
||||
}
|
||||
document.addEventListener("keydown", onKeyDown);
|
||||
return () => document.removeEventListener("keydown", onKeyDown);
|
||||
}, [menuOpen]);
|
||||
|
||||
return (
|
||||
<header className="pit-header" data-session-mode={snapshot.mode}>
|
||||
<div className="pit-header-primary">
|
||||
<div className="pit-header-title-row">
|
||||
<span className="pit-identifier">{snapshot.issue.identifier}</span>
|
||||
<h1 className="pit-title">{snapshot.issue.title}</h1>
|
||||
<StatusBadge status={snapshot.issue.status} />
|
||||
</div>
|
||||
<div className="pit-header-controls">
|
||||
{!chat && !readOnly ? (
|
||||
<>
|
||||
<label className="pit-visually-hidden" htmlFor="scenario-picker">Scenario</label>
|
||||
<select className="pit-select pit-desktop-only" id="scenario-picker" value={snapshot.issue.fixtureProfile} onChange={(event) => onSelectScenario(event.target.value)} data-testid="scenario-picker">
|
||||
{scenarios.map((scenario) => <option key={scenario} value={scenario}>{scenario}</option>)}
|
||||
</select>
|
||||
<button type="button" className="pit-button pit-desktop-only" onClick={onReplay} data-testid="replay-button"><Icon name="play" /> Replay</button>
|
||||
</>
|
||||
) : null}
|
||||
{!readOnly ? <button type="button" className="pit-icon-button pit-desktop-only" data-variant="destructive" onClick={onReset} data-testid="reset-button" title={chat ? "Reset chat" : "Reset scenario"} aria-label={chat ? "Reset chat" : "Reset scenario"}><Icon name="reset" /></button> : null}
|
||||
{!readOnly ? <button type="button" className="pit-icon-button" data-variant="destructive" onClick={onStop} disabled={!turnActive} data-testid="stop-button" title="Stop turn" aria-label="Stop turn"><Icon name="stop" /></button> : null}
|
||||
<button type="button" className="pit-button pit-desktop-only" aria-expanded={evidenceOpen} onClick={onToggleEvidence} data-testid="evidence-toggle"><Icon name="evidence" /> DevTools{denialCount > 0 ? ` (${denialCount})` : ""}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pit-header-context">
|
||||
<div className="pit-chip-row" data-testid="identity-chips">
|
||||
<Chip tone={snapshot.mode === "live" ? "live" : undefined} testId="agent-chip">
|
||||
{snapshot.identity.agentLabel}
|
||||
{snapshot.identity.replaySource !== null
|
||||
? ` · ${snapshot.identity.replaySource} source`
|
||||
: ""}
|
||||
</Chip>
|
||||
<Chip testId="runner-chip">
|
||||
<span
|
||||
className="pit-process-dot"
|
||||
data-attached={snapshot.identity.runnerAttached}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
{snapshot.identity.runnerLabel}
|
||||
<span className="pit-visually-hidden">
|
||||
{snapshot.identity.runnerAttached ? "attached" : "detached"}
|
||||
</span>
|
||||
</Chip>
|
||||
<Chip tone="mock" title={snapshot.identity.controlPlaneTooltip} testId="control-plane-chip">
|
||||
{snapshot.identity.controlPlaneLabel}
|
||||
</Chip>
|
||||
{chat && cleanRoomToken !== null ? (
|
||||
<Chip tone="accent" testId="clean-room-identity">
|
||||
Clean room {cleanRoomToken}
|
||||
</Chip>
|
||||
) : null}
|
||||
</div>
|
||||
<PriorityIcon priority={snapshot.issue.priority} />
|
||||
{snapshot.issue.assignee !== null ? <span className="pit-assignee">{snapshot.issue.assignee}</span> : null}
|
||||
<span className="pit-run-state" title={snapshot.issue.runState}>{snapshot.issue.runState}</span>
|
||||
|
||||
<div className="pit-menu pit-mobile-only" ref={menuRef}>
|
||||
<button
|
||||
type="button"
|
||||
className="pit-button"
|
||||
aria-expanded={menuOpen}
|
||||
aria-haspopup="menu"
|
||||
onClick={() => setMenuOpen((current) => !current)}
|
||||
data-testid="overflow-menu-button"
|
||||
>
|
||||
<span aria-hidden="true">⋯</span>
|
||||
<span className="pit-visually-hidden">More actions</span>
|
||||
</button>
|
||||
{menuOpen ? (
|
||||
<div className="pit-menu-list" role="menu" data-testid="overflow-menu">
|
||||
{chat ? null : (
|
||||
<>
|
||||
<label className="pit-menu-item" htmlFor="scenario-picker-mobile">
|
||||
Scenario
|
||||
<select
|
||||
className="pit-select"
|
||||
id="scenario-picker-mobile"
|
||||
value={snapshot.issue.fixtureProfile}
|
||||
onChange={(event) => {
|
||||
setMenuOpen(false);
|
||||
onSelectScenario(event.target.value);
|
||||
}}
|
||||
>
|
||||
{scenarios.map((scenario) => (
|
||||
<option key={scenario} value={scenario}>
|
||||
{scenario}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className="pit-menu-item"
|
||||
onClick={() => {
|
||||
setMenuOpen(false);
|
||||
onReplay();
|
||||
}}
|
||||
>
|
||||
Replay
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className="pit-menu-item"
|
||||
onClick={() => {
|
||||
setMenuOpen(false);
|
||||
onReset();
|
||||
}}
|
||||
>
|
||||
{chat ? "Reset chat" : "Reset scenario"}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div className="pit-segmented" role="tablist" aria-label="Thread or evidence">
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
className="pit-segment"
|
||||
aria-selected={segment === "thread"}
|
||||
onClick={() => onSelectSegment("thread")}
|
||||
data-testid="segment-thread"
|
||||
>
|
||||
Thread
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
className="pit-segment"
|
||||
aria-selected={segment === "evidence"}
|
||||
onClick={() => onSelectSegment("evidence")}
|
||||
data-testid="segment-evidence"
|
||||
>
|
||||
Evidence
|
||||
{denialCount > 0 ? (
|
||||
<span className="pit-segment-badge" data-testid="segment-denial-badge">
|
||||
{denialCount}
|
||||
</span>
|
||||
) : null}
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { CapabilitySurface } from "./route";
|
||||
import { Icon } from "./Icons";
|
||||
|
||||
/**
|
||||
* Top-level surface switch (Capability plan revision 5).
|
||||
*
|
||||
* Capability now has two primary paths, not one path with a mode toggle: the
|
||||
* preset scenario explorer and a clean-room chat that starts from nothing. They
|
||||
* are different jobs, so they get links rather than tabs — the clean-room entry
|
||||
* has to be reachable from the landing page without first choosing a scenario.
|
||||
*
|
||||
* These are real anchors on purpose. The entry must survive a hard refresh, be
|
||||
* copyable, and open in a new tab, which a button handler would not give.
|
||||
*/
|
||||
export interface CapabilityChatHistoryItem {
|
||||
sessionId: string;
|
||||
identifier: string;
|
||||
title: string;
|
||||
updatedAt: string;
|
||||
current: boolean;
|
||||
}
|
||||
|
||||
export function SurfaceNav({ surface, history = [], activeSessionId = null, onNewChat, onSelectHistory }: {
|
||||
surface: CapabilitySurface;
|
||||
history?: CapabilityChatHistoryItem[];
|
||||
activeSessionId?: string | null;
|
||||
onNewChat?: () => void;
|
||||
onSelectHistory?: (sessionId: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<aside className="pit-surface-nav" aria-label="Runner navigation" data-testid="surface-nav">
|
||||
<div className="pit-sidebar-brand"><Icon name="activity" /><span>Runner lab</span></div>
|
||||
<nav className="pit-sidebar-primary" aria-label="Capability surfaces">
|
||||
<a className="pit-surface-link" href="#/issue/hb-baseline" aria-current={surface === "issue" ? "page" : undefined} data-testid="surface-issue-link">
|
||||
<Icon name="timeline" /><span>Scenario explorer</span>
|
||||
</a>
|
||||
<button type="button" className="pit-surface-link" onClick={onNewChat} disabled={onNewChat === undefined} data-testid="surface-chat-link">
|
||||
<Icon name="spark" /><span>New chat</span>
|
||||
</button>
|
||||
</nav>
|
||||
{surface === "chat" ? (
|
||||
<section className="pit-session-history" aria-labelledby="session-history-title">
|
||||
<h2 id="session-history-title">Session history</h2>
|
||||
<div className="pit-session-history-list">
|
||||
{history.map((item) => (
|
||||
<button type="button" key={item.sessionId} className="pit-session-history-item" data-selected={activeSessionId === item.sessionId} onClick={() => onSelectHistory?.(item.sessionId)}>
|
||||
<span className="pit-session-history-title">{item.title}</span>
|
||||
<span>{item.identifier}{item.current ? " · current" : ""}</span>
|
||||
</button>
|
||||
))}
|
||||
{history.length === 0 ? <p className="pit-muted">No chats yet.</p> : null}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,616 @@
|
||||
import { useState } from "react";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import remarkGfm from "remark-gfm";
|
||||
|
||||
import type {
|
||||
CapabilityEvidenceSectionId,
|
||||
CapabilityThreadItem,
|
||||
CapabilityThreadTurn,
|
||||
} from "../../../src/issue-thread/types";
|
||||
import { InteractionCard, type CapabilityInteractionResponse } from "./InteractionCard";
|
||||
import { Chip, StatusBadge, Timestamp, formatBytes } from "./primitives";
|
||||
|
||||
export interface EvalAssertion {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
passed: boolean;
|
||||
detail: string;
|
||||
definition: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function EvalAssertions({ assertions }: { assertions: EvalAssertion[] }) {
|
||||
const [selected, setSelected] = useState<EvalAssertion | null>(null);
|
||||
if (assertions.length === 0) return null;
|
||||
return (
|
||||
<>
|
||||
<div className="pit-inline-assertions" aria-label="Eval assertions">
|
||||
{assertions.map((assertion) => (
|
||||
<button type="button" key={assertion.id} data-passed={assertion.passed} onClick={() => setSelected(assertion)}>
|
||||
<strong>{assertion.passed ? "✓ PASS" : "✕ FAIL"} · {assertion.title}</strong>
|
||||
<span>{assertion.detail}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{selected !== null ? (
|
||||
<div className="pit-dialog-backdrop" onMouseDown={(event) => { if (event.target === event.currentTarget) setSelected(null); }}>
|
||||
<div className="pit-dialog pit-eval-check-dialog" role="dialog" aria-modal="true" aria-labelledby="eval-check-title">
|
||||
<header className="pit-tool-dialog-head"><div><span className="pit-card-meta">Eval assertion · {selected.id}</span><h2 id="eval-check-title">{selected.title}</h2></div><button type="button" className="pit-icon-button" aria-label="Close assertion" onClick={() => setSelected(null)}>×</button></header>
|
||||
<p>{selected.description}</p>
|
||||
<p className="pit-card-meta">Observed result</p><p>{selected.detail}</p>
|
||||
<p className="pit-card-meta">Original case definition</p><pre className="pit-code">{JSON.stringify(selected.definition, null, 2)}</pre>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Progressive disclosure budget from contract §3 (T4). */
|
||||
const VISIBLE_STRIPS = 3;
|
||||
|
||||
const STATUS_GLYPH = { ok: "✓", denied: "✕", running: "⏳" } as const;
|
||||
|
||||
function MarkdownBody({ children }: { children: string }) {
|
||||
return (
|
||||
<div className="pit-card-body pit-markdown">
|
||||
<ReactMarkdown remarkPlugins={[remarkGfm]}>{children}</ReactMarkdown>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export interface ThreadCallbacks {
|
||||
onOpenEvidence: (section: CapabilityEvidenceSectionId, recordId: string) => void;
|
||||
onRespond: (response: CapabilityInteractionResponse) => void;
|
||||
focusInteractionId: string | null;
|
||||
}
|
||||
|
||||
function ToolStrip({
|
||||
item,
|
||||
callbacks,
|
||||
}: {
|
||||
item: Extract<CapabilityThreadItem, { kind: "tool_activity" }>;
|
||||
callbacks: ThreadCallbacks;
|
||||
}) {
|
||||
return (
|
||||
<details
|
||||
id={item.id}
|
||||
className="pit-activity-item"
|
||||
data-thread-item="tool_activity"
|
||||
data-status={item.status}
|
||||
data-tool-strip={item.operationId}
|
||||
>
|
||||
<summary className="pit-activity-summary">
|
||||
<span className="pit-activity-glyph" aria-hidden="true">
|
||||
{STATUS_GLYPH[item.status]}
|
||||
</span>
|
||||
<span className="pit-visually-hidden">{item.status}</span>
|
||||
<span className="pit-activity-operation">{item.operationId}</span>
|
||||
<span className="pit-activity-description">{item.summary}</span>
|
||||
<span className="pit-activity-caret" aria-hidden="true">›</span>
|
||||
</summary>
|
||||
<div className="pit-activity-detail">
|
||||
<p className="pit-card-meta">Sanitized tool input and result</p>
|
||||
<div className="pit-activity-payloads">
|
||||
<pre className="pit-code">{JSON.stringify(item.input, null, 2)}</pre>
|
||||
<pre className="pit-code">{JSON.stringify(item.result, null, 2)}</pre>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="pit-link-button"
|
||||
onClick={() =>
|
||||
callbacks.onOpenEvidence(item.evidenceRef.section, item.evidenceRef.recordId)
|
||||
}
|
||||
>
|
||||
View in Evidence
|
||||
</button>
|
||||
</div>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
function ProgressItem({
|
||||
item,
|
||||
}: {
|
||||
item: Extract<CapabilityThreadItem, { kind: "progress_activity" }>;
|
||||
}) {
|
||||
return (
|
||||
<details
|
||||
id={item.id}
|
||||
className="pit-activity-item pit-progress-activity"
|
||||
data-thread-item="progress_activity"
|
||||
data-activity={item.activity}
|
||||
data-status={item.status}
|
||||
open={item.status === "running"}
|
||||
>
|
||||
<summary className="pit-activity-summary">
|
||||
<span className="pit-activity-glyph" aria-hidden="true">
|
||||
{item.status === "running" ? "⏳" : "✓"}
|
||||
</span>
|
||||
<span className="pit-activity-operation">{item.label}</span>
|
||||
<span className="pit-activity-description">{item.summary}</span>
|
||||
<span className="pit-activity-caret" aria-hidden="true">›</span>
|
||||
</summary>
|
||||
<div className="pit-activity-detail">
|
||||
{Object.entries(item.details).map(([name, value]) =>
|
||||
name === "withheld" ? null : (
|
||||
<div className="pit-activity-field" key={name}>
|
||||
<span>{name}</span>
|
||||
<pre className="pit-code">{typeof value === "string" ? value : JSON.stringify(value, null, 2)}</pre>
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
{Array.isArray(item.details.withheld) ? (
|
||||
<p className="pit-withheld-note">
|
||||
Not available here: {item.details.withheld.join(", ")}.
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
function valueRecord(value: unknown): Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
}
|
||||
|
||||
function ProviderActivity({ item, callbacks }: {
|
||||
item: Extract<CapabilityThreadItem, { kind: "provider_activity" }>;
|
||||
callbacks: ThreadCallbacks;
|
||||
}) {
|
||||
const payload = valueRecord(item.payload);
|
||||
const steps = Array.isArray(payload.steps) ? payload.steps.map(valueRecord) : [];
|
||||
const children = Array.isArray(payload.children) ? payload.children.map(valueRecord) : [];
|
||||
const sources = Array.isArray(payload.sources) ? payload.sources.map(valueRecord) : [];
|
||||
const output = typeof payload.output === "string" ? payload.output : "";
|
||||
const glyph = item.status === "running" ? "⏳" : item.status === "failed" ? "✕" : item.status === "interrupted" ? "■" : "✓";
|
||||
return (
|
||||
<details id={item.id} className="pit-activity-item pit-provider-activity" data-thread-item="provider_activity" data-family={item.family} data-status={item.status} open={item.status === "running"}>
|
||||
<summary className="pit-activity-summary"><span className="pit-activity-glyph" aria-hidden="true">{glyph}</span><span className="pit-activity-operation">{item.title}</span><span className="pit-activity-description">{item.summary}</span><span className="pit-activity-caret" aria-hidden="true">›</span></summary>
|
||||
<div className="pit-activity-detail">
|
||||
{steps.length > 0 ? <ol className="pit-provider-plan">{steps.map((step, index) => <li key={String(step.stepId ?? index)} data-plan-status={String(step.status ?? "pending")}><span aria-hidden="true">{step.status === "completed" ? "✓" : step.status === "blocked" ? "!" : step.status === "in_progress" ? "◐" : "○"}</span>{String(step.body ?? "")}</li>)}</ol> : null}
|
||||
{children.length > 0 ? <ul className="pit-provider-tree">{children.map((child, index) => <li key={String(child.childId ?? index)}><strong>{String(child.role ?? "Child agent")}</strong><span>{String(child.status ?? "unknown")}</span><small>{String(child.summary ?? "")}</small></li>)}</ul> : null}
|
||||
{sources.length > 0 ? <ul className="pit-provider-sources">{sources.map((source, index) => { const url = typeof source.url === "string" && /^https?:\/\//.test(source.url) ? source.url : null; return <li key={String(source.sourceId ?? index)}>{url === null ? <span>{String(source.title ?? "Unavailable source")}</span> : <a href={url} target="_blank" rel="noreferrer">{String(source.title ?? url)}</a>}<small>Provider-reported</small></li>; })}</ul> : null}
|
||||
{output.length > 0 ? <pre className="pit-provider-output" aria-label="Command output">{output}</pre> : null}
|
||||
{item.family === "model_identity" ? <dl className="pit-provider-fields"><dt>Requested</dt><dd>{String(payload.requestedModel ?? "—")}</dd><dt>Effective</dt><dd>{String(payload.effectiveModel ?? "—")}</dd></dl> : null}
|
||||
{item.family === "artifact" && typeof payload.reference === "string" ? <button type="button" className="pit-link-button">Open {payload.reference}</button> : null}
|
||||
<button type="button" className="pit-link-button" onClick={() => callbacks.onOpenEvidence(item.evidenceRef.section, item.evidenceRef.recordId)}>View in Evidence</button>
|
||||
</div>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
function FileDiff({ diff }: { diff: string | null }) {
|
||||
if (diff === null) return <p className="pit-workspace-binary">Binary or oversized file; textual diff unavailable.</p>;
|
||||
return (
|
||||
<pre className="pit-workspace-diff" aria-label="Unified file diff">
|
||||
{diff.split("\n").map((line, index) => (
|
||||
<span
|
||||
key={`${index}:${line}`}
|
||||
data-diff-line={line.startsWith("+") && !line.startsWith("+++")
|
||||
? "addition"
|
||||
: line.startsWith("-") && !line.startsWith("---")
|
||||
? "deletion"
|
||||
: line.startsWith("@@")
|
||||
? "hunk"
|
||||
: "context"}
|
||||
>{line || " "}{"\n"}</span>
|
||||
))}
|
||||
</pre>
|
||||
);
|
||||
}
|
||||
|
||||
function WorkspaceChanges({
|
||||
item,
|
||||
}: {
|
||||
item: Extract<CapabilityThreadItem, { kind: "workspace_changes" }>;
|
||||
}) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [selectedPath, setSelectedPath] = useState<string | null>(null);
|
||||
const files = item.changeSet.files;
|
||||
const visible = expanded ? files : files.slice(0, 3);
|
||||
const selected = files.find((file) => file.path === selectedPath) ?? null;
|
||||
const stats = (file: (typeof files)[number]) => (
|
||||
<span className="pit-workspace-stats">
|
||||
{file.additions === null ? null : <span data-stat="add">+{file.additions}</span>}
|
||||
{file.deletions === null ? null : <span data-stat="delete">-{file.deletions}</span>}
|
||||
</span>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<article id={item.id} className="pit-workspace-card" data-thread-item="workspace_changes">
|
||||
<header className="pit-workspace-head">
|
||||
<span className="pit-workspace-icon" aria-hidden="true">▣</span>
|
||||
<span>
|
||||
<strong>{item.changeSet.complete ? "Edited" : "Editing"} {files.length} file{files.length === 1 ? "" : "s"}</strong>
|
||||
<small>{item.changeSet.source === "runner_verified" ? "Verified from workspace" : "Reported by harness"}</small>
|
||||
</span>
|
||||
<span className="pit-workspace-total">
|
||||
{item.changeSet.totals.additions === null ? null : <span data-stat="add">+{item.changeSet.totals.additions}</span>}
|
||||
{item.changeSet.totals.deletions === null ? null : <span data-stat="delete">-{item.changeSet.totals.deletions}</span>}
|
||||
</span>
|
||||
<button type="button" className="pit-workspace-review" onClick={() => setSelectedPath(files[0]?.path ?? null)}>Review</button>
|
||||
</header>
|
||||
<div className="pit-workspace-files">
|
||||
{visible.map((file) => (
|
||||
<button type="button" key={`${file.operation}:${file.path}`} onClick={() => setSelectedPath(file.path)}>
|
||||
<span className="pit-workspace-path">
|
||||
{file.previousPath === null ? file.path : `${file.previousPath} → ${file.path}`}
|
||||
<small>{file.operation.replace("_", " ")}</small>
|
||||
</span>
|
||||
{stats(file)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{files.length > 3 ? (
|
||||
<button type="button" className="pit-workspace-more" onClick={() => setExpanded((value) => !value)}>
|
||||
{expanded ? "Show fewer files" : `Show ${files.length - 3} more files`} <span aria-hidden="true">⌄</span>
|
||||
</button>
|
||||
) : null}
|
||||
</article>
|
||||
{selected !== null ? (
|
||||
<div className="pit-dialog-backdrop" onMouseDown={(event) => { if (event.target === event.currentTarget) setSelectedPath(null); }}>
|
||||
<div className="pit-dialog pit-workspace-dialog" role="dialog" aria-modal="true" aria-labelledby="workspace-diff-title">
|
||||
<header className="pit-tool-dialog-head">
|
||||
<div>
|
||||
<span className="pit-card-meta">{selected.operation.replace("_", " ")} · workspace diff</span>
|
||||
<h2 id="workspace-diff-title">{selected.path}</h2>
|
||||
</div>
|
||||
{stats(selected)}
|
||||
<button type="button" className="pit-icon-button" aria-label="Close diff" onClick={() => setSelectedPath(null)}>×</button>
|
||||
</header>
|
||||
{files.length > 1 ? (
|
||||
<nav className="pit-workspace-file-nav" aria-label="Changed files">
|
||||
{files.map((file) => <button type="button" key={file.path} data-selected={file.path === selected.path} onClick={() => setSelectedPath(file.path)}>{file.path}</button>)}
|
||||
</nav>
|
||||
) : null}
|
||||
<FileDiff diff={selected.diff} />
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function WorkspaceFileReference({
|
||||
item,
|
||||
}: {
|
||||
item: Extract<CapabilityThreadItem, { kind: "workspace_file_reference" }>;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const extension = item.reference.path.includes(".")
|
||||
? item.reference.path.split(".").at(-1)?.toUpperCase()
|
||||
: "FILE";
|
||||
const presentation = item.reference.presentation === "document"
|
||||
? "Document"
|
||||
: item.reference.presentation === "code"
|
||||
? "Code"
|
||||
: item.reference.presentation === "image"
|
||||
? "Image"
|
||||
: "File";
|
||||
return (
|
||||
<>
|
||||
<article id={item.id} className="pit-file-reference-card" data-thread-item="workspace_file_reference">
|
||||
<span className="pit-file-reference-icon" aria-hidden="true">▤</span>
|
||||
<span className="pit-file-reference-copy">
|
||||
<strong>{item.reference.displayName}</strong>
|
||||
<small>{presentation} · {extension}{item.reference.line === null ? "" : ` · line ${item.reference.line}`}</small>
|
||||
</span>
|
||||
<button type="button" className="pit-workspace-review" onClick={() => setOpen(true)}>Open</button>
|
||||
</article>
|
||||
{open ? (
|
||||
<div className="pit-dialog-backdrop" onMouseDown={(event) => { if (event.target === event.currentTarget) setOpen(false); }}>
|
||||
<div className="pit-dialog pit-file-reference-dialog" role="dialog" aria-modal="true" aria-labelledby="workspace-file-title">
|
||||
<header className="pit-tool-dialog-head">
|
||||
<div><span className="pit-card-meta">{item.reference.path}</span><h2 id="workspace-file-title">{item.reference.displayName}</h2></div>
|
||||
<button type="button" className="pit-icon-button" aria-label="Close file" onClick={() => setOpen(false)}>×</button>
|
||||
</header>
|
||||
<div className="pit-file-reference-preview">
|
||||
{item.reference.preview === null
|
||||
? <p className="pit-workspace-binary">Preview unavailable. The reference remains recorded with its normalized workspace path.</p>
|
||||
: item.reference.presentation === "document"
|
||||
? <MarkdownBody>{item.reference.preview}</MarkdownBody>
|
||||
: <pre className="pit-code">{item.reference.preview}</pre>}
|
||||
{item.reference.previewTruncated ? <p className="pit-withheld-note">Preview truncated by the runner.</p> : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ThreadItemView({
|
||||
item,
|
||||
callbacks,
|
||||
}: {
|
||||
item: CapabilityThreadItem;
|
||||
callbacks: ThreadCallbacks;
|
||||
}) {
|
||||
switch (item.kind) {
|
||||
case "user_message":
|
||||
return (
|
||||
<article
|
||||
id={item.id}
|
||||
className="pit-message"
|
||||
data-role="user"
|
||||
data-thread-item="user_message"
|
||||
>
|
||||
<div className="pit-card-head">
|
||||
<span className="pit-card-author">{item.author}</span>
|
||||
<Timestamp value={item.at} />
|
||||
</div>
|
||||
<MarkdownBody>{item.body}</MarkdownBody>
|
||||
</article>
|
||||
);
|
||||
|
||||
case "agent_message":
|
||||
return (
|
||||
<article
|
||||
id={item.id}
|
||||
className="pit-message"
|
||||
data-role="assistant"
|
||||
data-thread-item="agent_message"
|
||||
data-streaming={item.streaming}
|
||||
>
|
||||
<div className="pit-card-head">
|
||||
<span className="pit-card-author">{item.author}</span>
|
||||
<Timestamp value={item.at} />
|
||||
{item.streaming ? (
|
||||
<Chip tone="accent" testId="streaming-indicator">
|
||||
<span aria-hidden="true">⏳</span>
|
||||
Streaming
|
||||
</Chip>
|
||||
) : null}
|
||||
</div>
|
||||
<MarkdownBody>{item.body}</MarkdownBody>
|
||||
</article>
|
||||
);
|
||||
|
||||
case "durable_comment":
|
||||
return (
|
||||
<article id={item.id} className="pit-card" data-thread-item="durable_comment">
|
||||
<div className="pit-card-head">
|
||||
<span className="pit-card-author">{item.author}</span>
|
||||
<Timestamp value={item.at} />
|
||||
<span
|
||||
className="pit-durable-tag"
|
||||
title={`Recorded by the ${item.operationId} semantic operation.`}
|
||||
>
|
||||
<span aria-hidden="true">◆</span>
|
||||
Recorded to mock thread
|
||||
</span>
|
||||
</div>
|
||||
<div className="pit-card-body">{item.body}</div>
|
||||
<button
|
||||
type="button"
|
||||
className="pit-link-button"
|
||||
onClick={() =>
|
||||
callbacks.onOpenEvidence(item.evidenceRef.section, item.evidenceRef.recordId)
|
||||
}
|
||||
>
|
||||
View in Evidence
|
||||
</button>
|
||||
</article>
|
||||
);
|
||||
|
||||
case "tool_activity":
|
||||
return <ToolStrip item={item} callbacks={callbacks} />;
|
||||
|
||||
case "progress_activity":
|
||||
return <ProgressItem item={item} />;
|
||||
|
||||
case "workspace_changes":
|
||||
return <WorkspaceChanges item={item} />;
|
||||
|
||||
case "workspace_file_reference":
|
||||
return <WorkspaceFileReference item={item} />;
|
||||
|
||||
case "provider_activity":
|
||||
return <ProviderActivity item={item} callbacks={callbacks} />;
|
||||
|
||||
case "denial":
|
||||
return (
|
||||
<div id={item.id} className="pit-strip pit-denial" data-status="denied" data-thread-item="denial">
|
||||
<div className="pit-strip-button">
|
||||
<span className="pit-strip-glyph" aria-hidden="true">
|
||||
✕
|
||||
</span>
|
||||
<span className="pit-strip-operation">{item.operationId}</span>
|
||||
<span className="pit-strip-summary" data-testid="denial-reason">
|
||||
{item.reason}
|
||||
</span>
|
||||
</div>
|
||||
<div className="pit-strip-detail">
|
||||
<button
|
||||
type="button"
|
||||
className="pit-link-button"
|
||||
onClick={() =>
|
||||
callbacks.onOpenEvidence(item.evidenceRef.section, item.evidenceRef.recordId)
|
||||
}
|
||||
>
|
||||
View in Evidence
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
case "interaction":
|
||||
return (
|
||||
<InteractionCard
|
||||
card={item}
|
||||
autoFocus={callbacks.focusInteractionId === item.interactionId}
|
||||
onRespond={callbacks.onRespond}
|
||||
onOpenEvidence={(section, recordId) =>
|
||||
callbacks.onOpenEvidence(section as CapabilityEvidenceSectionId, recordId)
|
||||
}
|
||||
/>
|
||||
);
|
||||
|
||||
case "document":
|
||||
return (
|
||||
<article id={item.id} className="pit-card" data-thread-item="document">
|
||||
<div className="pit-card-head">
|
||||
<span className="pit-card-author">{item.title}</span>
|
||||
<span className="pit-card-meta">{item.documentKey}</span>
|
||||
<Timestamp value={item.at} />
|
||||
</div>
|
||||
<div className="pit-card-body">
|
||||
<span className="pit-card-meta" data-testid="revision-chain">
|
||||
{item.revisionFrom === null ? `r${item.revisionTo}` : `r${item.revisionFrom} → r${item.revisionTo}`}
|
||||
</span>
|
||||
{" · "}
|
||||
{item.author}
|
||||
{item.staleBehind !== null ? (
|
||||
<>
|
||||
{" "}
|
||||
<Chip>
|
||||
<span aria-hidden="true">⌛</span>
|
||||
Stale — {item.staleBehind} newer revision(s)
|
||||
</Chip>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="pit-link-button"
|
||||
onClick={() =>
|
||||
callbacks.onOpenEvidence(item.evidenceRef.section, item.evidenceRef.recordId)
|
||||
}
|
||||
>
|
||||
View diff
|
||||
</button>
|
||||
</article>
|
||||
);
|
||||
|
||||
case "deliverable":
|
||||
return (
|
||||
<article id={item.id} className="pit-card" data-thread-item="deliverable">
|
||||
<div className="pit-card-head">
|
||||
<span className="pit-card-author">{item.filename}</span>
|
||||
<Timestamp value={item.at} />
|
||||
</div>
|
||||
<div className="pit-card-body">
|
||||
<span className="pit-card-meta">
|
||||
{item.deliverableKind} · {formatBytes(item.byteSize)} · registered by {item.registeredBy}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="pit-link-button"
|
||||
onClick={() =>
|
||||
callbacks.onOpenEvidence(item.evidenceRef.section, item.evidenceRef.recordId)
|
||||
}
|
||||
>
|
||||
Download {item.filename}
|
||||
</button>
|
||||
</article>
|
||||
);
|
||||
|
||||
case "dependency":
|
||||
return (
|
||||
<article id={item.id} className="pit-card" data-thread-item="dependency">
|
||||
<div className="pit-card-head">
|
||||
<span className="pit-card-author">Delegation</span>
|
||||
<Timestamp value={item.at} />
|
||||
</div>
|
||||
<ul className="pit-summary-list">
|
||||
{item.createdTasks.map((task) => (
|
||||
<li key={task.identifier}>
|
||||
<span className="pit-record-title">{task.identifier}</span> {task.title}
|
||||
</li>
|
||||
))}
|
||||
{item.blockerEdges.map((edge) => (
|
||||
<li key={edge}>{edge}</li>
|
||||
))}
|
||||
</ul>
|
||||
</article>
|
||||
);
|
||||
|
||||
case "disposition":
|
||||
return (
|
||||
<article id={item.id} className="pit-card pit-terminal-card" data-thread-item="disposition">
|
||||
<div className="pit-card-head">
|
||||
<StatusBadge status={item.status} />
|
||||
<span className="pit-card-meta">{item.operationId}</span>
|
||||
<Timestamp value={item.at} />
|
||||
</div>
|
||||
<div className="pit-card-body">{item.body}</div>
|
||||
{item.blockerOwner !== null ? (
|
||||
<p className="pit-card-meta">Blocker owner: {item.blockerOwner}</p>
|
||||
) : null}
|
||||
</article>
|
||||
);
|
||||
|
||||
case "system_notice":
|
||||
return (
|
||||
<p id={item.id} className="pit-notice" data-thread-item="system_notice">
|
||||
<span aria-hidden="true">{item.glyph}</span>
|
||||
<span className="pit-notice-text">{item.text}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="pit-link-button"
|
||||
onClick={() =>
|
||||
callbacks.onOpenEvidence(item.evidenceRef.section, item.evidenceRef.recordId)
|
||||
}
|
||||
>
|
||||
Details
|
||||
</button>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function TurnGroup({
|
||||
turn,
|
||||
callbacks,
|
||||
assertions = {},
|
||||
terminalAssertions = [],
|
||||
}: {
|
||||
turn: CapabilityThreadTurn;
|
||||
callbacks: ThreadCallbacks;
|
||||
assertions?: Record<string, EvalAssertion[]>;
|
||||
terminalAssertions?: EvalAssertion[];
|
||||
}) {
|
||||
const [showAllStrips, setShowAllStrips] = useState(false);
|
||||
const stripIndexes = turn.items
|
||||
.map((item, index) => (item.kind === "tool_activity" ? index : -1))
|
||||
.filter((index) => index >= 0);
|
||||
const hiddenStripIndexes = new Set(
|
||||
showAllStrips ? [] : stripIndexes.slice(VISIBLE_STRIPS),
|
||||
);
|
||||
|
||||
return (
|
||||
<section className="pit-turn" data-turn-id={turn.id} aria-label={`Turn ${turn.ordinal}`}>
|
||||
<h2 className="pit-turn-header">
|
||||
<span className="pit-turn-label">
|
||||
Turn {turn.ordinal} · {turn.mode} · {turn.toolCallCount} tool call
|
||||
{turn.toolCallCount === 1 ? "" : "s"} ·{" "}
|
||||
{new Date(turn.at).toISOString().slice(11, 19)}
|
||||
</span>
|
||||
{turn.stoppedByUser ? (
|
||||
<span className="pit-stopped-marker" data-testid="stopped-marker">
|
||||
Stopped by user
|
||||
</span>
|
||||
) : null}
|
||||
</h2>
|
||||
{turn.items.map((item, index) => hiddenStripIndexes.has(index) ? null : (
|
||||
<div className="pit-eval-item" key={item.id}>
|
||||
<ThreadItemView item={item} callbacks={callbacks} />
|
||||
<EvalAssertions assertions={assertions[item.id] ?? []} />
|
||||
</div>
|
||||
))}
|
||||
{hiddenStripIndexes.size > 0 ? (
|
||||
<button
|
||||
type="button"
|
||||
className="pit-more-button"
|
||||
onClick={() => setShowAllStrips(true)}
|
||||
>
|
||||
{hiddenStripIndexes.size} more…
|
||||
</button>
|
||||
) : null}
|
||||
<EvalAssertions assertions={terminalAssertions} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import type {
|
||||
CapabilityIssueThreadSnapshot,
|
||||
CapabilityThreadInteractionState,
|
||||
CapabilityThreadItem,
|
||||
} from "../../../src/issue-thread/types";
|
||||
import type { CapabilityInteractionResponse } from "./InteractionCard";
|
||||
|
||||
/**
|
||||
* `fake`-mode interaction store.
|
||||
*
|
||||
* The screenshot matrix runs without a session server, so this module plays
|
||||
* the mock control plane's role for the deterministic fixtures only: it stores
|
||||
* the response and then hands back a new snapshot, mirroring the live authority
|
||||
* path (store first, resume second) rather than resolving the card optimistically
|
||||
* in the card component. Live mode never reaches this code — it posts to the
|
||||
* package server instead.
|
||||
*/
|
||||
|
||||
function resolvedState(
|
||||
outcome: CapabilityInteractionResponse["outcome"],
|
||||
): { state: CapabilityThreadInteractionState; label: string } {
|
||||
if (outcome === "accepted") return { state: "accepted", label: "Accepted" };
|
||||
if (outcome === "rejected") return { state: "rejected", label: "Changes requested" };
|
||||
return { state: "answered", label: "Answered" };
|
||||
}
|
||||
|
||||
function summarise(response: CapabilityInteractionResponse): string[] {
|
||||
const result = response.result;
|
||||
if (Array.isArray(result.selected)) return result.selected.map((entry) => String(entry));
|
||||
if (Array.isArray(result.acceptedTaskIds)) {
|
||||
return result.acceptedTaskIds.map((entry) => `Accepted ${String(entry)}`);
|
||||
}
|
||||
if (Array.isArray(result.verdicts)) {
|
||||
return result.verdicts.map((entry) => {
|
||||
const verdict = entry as { id?: unknown; verdict?: unknown };
|
||||
return `${String(verdict.id)} — ${String(verdict.verdict)}`;
|
||||
});
|
||||
}
|
||||
if (typeof result.answers === "object" && result.answers !== null) {
|
||||
return Object.entries(result.answers as Record<string, unknown>).map(
|
||||
([key, value]) => `${key} — ${String(value)}`,
|
||||
);
|
||||
}
|
||||
if (result.accepted === true) return ["Accepted"];
|
||||
return [];
|
||||
}
|
||||
|
||||
function applyToItem(
|
||||
item: CapabilityThreadItem,
|
||||
response: CapabilityInteractionResponse,
|
||||
): CapabilityThreadItem {
|
||||
if (item.kind !== "interaction" || item.interactionId !== response.interactionId) return item;
|
||||
const view = resolvedState(response.outcome);
|
||||
return {
|
||||
...item,
|
||||
state: view.state,
|
||||
stateLabel: view.label,
|
||||
resolvedSummary: summarise(response),
|
||||
reason: typeof response.result.reason === "string" ? response.result.reason : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Store the typed response, then return the snapshot the card renders from. */
|
||||
export function applyFakeInteractionResponse(
|
||||
snapshot: CapabilityIssueThreadSnapshot,
|
||||
response: CapabilityInteractionResponse,
|
||||
): CapabilityIssueThreadSnapshot {
|
||||
const turns = snapshot.turns.map((turn) => ({
|
||||
...turn,
|
||||
items: turn.items.map((item) => applyToItem(item, response)),
|
||||
}));
|
||||
const stillPending = turns.some(
|
||||
(turn) => turn.items.some((item) => item.kind === "interaction" && item.state === "pending"),
|
||||
);
|
||||
return {
|
||||
...snapshot,
|
||||
turns,
|
||||
composer: stillPending
|
||||
? snapshot.composer
|
||||
: { state: "ready", helper: null, reason: null, pendingInteractionId: null },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
# Capability issue-thread fonts
|
||||
|
||||
The Capability issue-thread bundle includes Latin-subset WOFF2 files so captures
|
||||
do not depend on fonts installed on the host.
|
||||
|
||||
## Inter
|
||||
|
||||
- Upstream: https://github.com/rsms/inter
|
||||
- Version: 4.1
|
||||
- Source: `ui/public/fonts/InterVariable.woff2`
|
||||
- License: SIL Open Font License 1.1
|
||||
- License text: https://github.com/rsms/inter/blob/v4.1/LICENSE.txt
|
||||
|
||||
The bundled file is subset from the repository's unmodified upstream Inter 4.1
|
||||
variable WOFF2. CSS exposes weights 400 through 700.
|
||||
|
||||
## DejaVu Sans Mono
|
||||
|
||||
- Upstream: https://dejavu-fonts.github.io/
|
||||
- Version: 2.37
|
||||
- Source faces: DejaVu Sans Mono Book and Bold; DejaVu Sans Book for status glyphs
|
||||
- License: Bitstream Vera Fonts license; DejaVu changes are public domain
|
||||
- License text: https://dejavu-fonts.github.io/License.html
|
||||
|
||||
The bundled files are Latin subsets of the Book and Bold faces. The source font
|
||||
copyright and permission notice follow.
|
||||
|
||||
> Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is a
|
||||
> trademark of Bitstream, Inc.
|
||||
>
|
||||
> Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
> of the fonts accompanying this license ("Fonts") and associated documentation
|
||||
> files (the "Font Software"), to reproduce and distribute the Font Software,
|
||||
> including without limitation the rights to use, copy, merge, publish,
|
||||
> distribute, and/or sell copies of the Font Software, and to permit persons to
|
||||
> whom the Font Software is furnished to do so, subject to the following
|
||||
> conditions:
|
||||
>
|
||||
> The above copyright and trademark notices and this permission notice shall be
|
||||
> included in all copies of one or more of the Font Software typefaces.
|
||||
>
|
||||
> The Font Software may be modified, altered, or added to, and in particular the
|
||||
> designs of glyphs or characters in the Fonts may be modified and additional
|
||||
> glyphs or characters may be added to the Fonts, only if the fonts are renamed
|
||||
> to names not containing either the words "Bitstream" or the word "Vera".
|
||||
>
|
||||
> This License becomes null and void to the extent applicable to Fonts or Font
|
||||
> Software that has been modified and is distributed under the "Bitstream Vera"
|
||||
> names.
|
||||
>
|
||||
> The Font Software may be sold as part of a larger software package but no copy
|
||||
> of one or more of the Font Software typefaces may be sold by itself.
|
||||
>
|
||||
> THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
||||
> OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
|
||||
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
|
||||
> TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME FOUNDATION
|
||||
> BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL,
|
||||
> SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION
|
||||
> OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO
|
||||
> USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
>
|
||||
> Except as contained in this notice, the names of Gnome, the Gnome Foundation,
|
||||
> and Bitstream Inc., shall not be used in advertising or otherwise to promote
|
||||
> the sale, use or other dealings in the Font Software without prior written
|
||||
> authorization from the Gnome Foundation or Bitstream Inc., respectively.
|
||||
|
||||
## Noto Sans Symbols 2
|
||||
|
||||
- Upstream: https://github.com/notofonts/symbols
|
||||
- Version: 2.003
|
||||
- Source face: Noto Sans Symbols 2 Regular
|
||||
- License: SIL Open Font License 1.1
|
||||
- License text: https://github.com/notofonts/symbols/blob/main/OFL.txt
|
||||
|
||||
The 1.2 kB bundled subset contains only the two hourglass glyphs that are not
|
||||
present in Inter or DejaVu Sans. It is exposed under the same package-specific
|
||||
symbol fallback family using a disjoint `unicode-range`.
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,260 @@
|
||||
import type { CapabilityIssueThreadSnapshot } from "../../../src/issue-thread/types";
|
||||
import type { CapabilityDevtoolsSnapshot } from "../../../src/devtools";
|
||||
import type { CapabilityJsonValue } from "../../../src/mock-core/capability-control-plane-types";
|
||||
import {
|
||||
CAPABILITY_TURN_STREAM_ACCEPT,
|
||||
CapabilityTurnStreamError,
|
||||
readCapabilityTurnStream,
|
||||
} from "../../../src/live/turn-stream";
|
||||
|
||||
/**
|
||||
* Browser client for the package session server.
|
||||
*
|
||||
* Every response is a server-projected `CapabilityIssueThreadSnapshot`. The client
|
||||
* posts intents and renders what comes back; it never patches the snapshot
|
||||
* locally, which is what keeps policy and state authority on the server
|
||||
* (contract §11).
|
||||
*
|
||||
* A turn is the one route that answers with many of those projections instead
|
||||
* of one: `send` consumes NDJSON frames as the provider produces them, hands
|
||||
* each interim view to `onFrame`, and resolves with the settled payload. The
|
||||
* authority rule is unchanged — every frame is still a server projection, and
|
||||
* the settled one is final.
|
||||
*/
|
||||
|
||||
const BASE = "/api/capability/ui";
|
||||
|
||||
/**
|
||||
* Every route is session-scoped and mediated by the per-browser capability
|
||||
* cookie the server sets, so the cookie has to ride along. Stated rather than
|
||||
* left to the default so a future change to this client cannot silently drop
|
||||
* the capability and fall back to session-id-only access (track 7U).
|
||||
*/
|
||||
const CREDENTIALS = "same-origin" as const;
|
||||
|
||||
export interface CapabilityCleanRoomIdentity {
|
||||
token: string;
|
||||
sequence: number;
|
||||
companyId: string;
|
||||
actorId: string;
|
||||
taskId: string;
|
||||
identifier: string;
|
||||
}
|
||||
|
||||
export interface CapabilityHarnessConfiguration {
|
||||
provider: "codex" | "opencode" | "acpx";
|
||||
model: string | null;
|
||||
acpxAgent?: "claude" | "codex";
|
||||
lifecyclePolicy:
|
||||
| { mode: "per_turn"; idleTimeoutMs: null }
|
||||
| { mode: "warm"; idleTimeoutMs: number };
|
||||
}
|
||||
|
||||
export interface CapabilityLiveResponse {
|
||||
sessionId: string;
|
||||
view: CapabilityIssueThreadSnapshot;
|
||||
surface?: "issue" | "cleanroom";
|
||||
/** Present on the clean-room surface so the UI can show which tenant is live. */
|
||||
identity?: CapabilityCleanRoomIdentity;
|
||||
limits?: { maxTurns: number; maxMessageBytes: number };
|
||||
turns?: number;
|
||||
configuration?: CapabilityHarnessConfiguration;
|
||||
runtime?: {
|
||||
providerSessionId: string | null;
|
||||
driverSessionId?: string | null;
|
||||
runnerPid: number | null;
|
||||
providerPid: number | null;
|
||||
sidecarPid?: number | null;
|
||||
agentPid?: number | null;
|
||||
providerVersion?: string | null;
|
||||
agentServerVersion?: string | null;
|
||||
agentRuntimeVersion?: string | null;
|
||||
acpProtocolVersion?: number | null;
|
||||
executionKind: "local_process" | "remote_service";
|
||||
status: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface CapabilityToolTestResponse extends CapabilityLiveResponse {
|
||||
toolResult: CapabilityJsonValue;
|
||||
toolTurnId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The server names its own failures. Surfacing the code lets the clean room say
|
||||
* "this chat hit its turn limit" instead of "500", and — more importantly —
|
||||
* lets a failure to start real Codex read as a failure rather than quietly
|
||||
* degrading into a fixture.
|
||||
*/
|
||||
export class CapabilityLiveError extends Error {
|
||||
constructor(
|
||||
readonly code: string,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "CapabilityLiveError";
|
||||
}
|
||||
}
|
||||
|
||||
async function readError(response: Response, path: string): Promise<CapabilityLiveError> {
|
||||
try {
|
||||
const body = (await response.json()) as { error?: string; message?: string };
|
||||
return new CapabilityLiveError(
|
||||
body.error ?? `http_${response.status}`,
|
||||
body.message ?? `${path} failed with ${response.status}`,
|
||||
);
|
||||
} catch {
|
||||
return new CapabilityLiveError(`http_${response.status}`, `${path} failed with ${response.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function post<T = CapabilityLiveResponse>(path: string, body: unknown): Promise<T> {
|
||||
const response = await fetch(`${BASE}${path}`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
credentials: CREDENTIALS,
|
||||
});
|
||||
if (!response.ok) throw await readError(response, path);
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
|
||||
/** Interim projection delivered while the turn is still running. */
|
||||
export type CapabilityTurnFrameHandler = (view: CapabilityIssueThreadSnapshot) => void;
|
||||
|
||||
export interface CapabilitySendOptions {
|
||||
onFrame?: CapabilityTurnFrameHandler;
|
||||
/** Abort the turn stream — used when the surface is torn down or rotated. */
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
async function postTurnStream(
|
||||
path: string,
|
||||
body: unknown,
|
||||
options: CapabilitySendOptions,
|
||||
): Promise<CapabilityLiveResponse> {
|
||||
const response = await fetch(`${BASE}${path}`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", accept: CAPABILITY_TURN_STREAM_ACCEPT },
|
||||
body: JSON.stringify(body),
|
||||
credentials: CREDENTIALS,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
});
|
||||
// Admission failures still answer with a JSON body and a real status code,
|
||||
// because they are decided before the first frame is written.
|
||||
if (!response.ok) throw await readError(response, path);
|
||||
try {
|
||||
return await readCapabilityTurnStream<CapabilityIssueThreadSnapshot, CapabilityLiveResponse>(
|
||||
response,
|
||||
(frame) => options.onFrame?.(frame.view),
|
||||
);
|
||||
} catch (cause) {
|
||||
if (cause instanceof CapabilityTurnStreamError) {
|
||||
throw new CapabilityLiveError(cause.code, cause.message);
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
}
|
||||
|
||||
export const capabilityLiveClient = {
|
||||
async devtools(sessionId: string): Promise<CapabilityDevtoolsSnapshot> {
|
||||
const response = await fetch(`${BASE}/devtools?sessionId=${encodeURIComponent(sessionId)}`, {
|
||||
credentials: CREDENTIALS,
|
||||
});
|
||||
if (!response.ok) throw await readError(response, "/devtools");
|
||||
return (await response.json()) as CapabilityDevtoolsSnapshot;
|
||||
},
|
||||
fork(sessionId: string, revision: number): Promise<CapabilityLiveResponse> {
|
||||
return post("/devtools/fork", { sessionId, revision });
|
||||
},
|
||||
invokeTool(
|
||||
sessionId: string,
|
||||
operationId: string,
|
||||
input: CapabilityJsonValue,
|
||||
): Promise<CapabilityToolTestResponse> {
|
||||
return post("/tool", { sessionId, operationId, input }) as Promise<CapabilityToolTestResponse>;
|
||||
},
|
||||
async load(sessionId: string | null): Promise<CapabilityLiveResponse> {
|
||||
const query = sessionId === null ? "" : `?sessionId=${encodeURIComponent(sessionId)}`;
|
||||
const response = await fetch(`${BASE}/session${query}`, { credentials: CREDENTIALS });
|
||||
if (!response.ok) throw await readError(response, "/session");
|
||||
return (await response.json()) as CapabilityLiveResponse;
|
||||
},
|
||||
create(scenario: string): Promise<CapabilityLiveResponse> {
|
||||
return post("/session", { scenario });
|
||||
},
|
||||
/** Reconnect to a clean room, or open one when there is nothing to resume. */
|
||||
async loadCleanRoom(sessionId: string | null, configuration: CapabilityHarnessConfiguration): Promise<CapabilityLiveResponse> {
|
||||
const query = new URLSearchParams({ provider: configuration.provider });
|
||||
if (sessionId !== null) query.set("sessionId", sessionId);
|
||||
if (configuration.model !== null) query.set("model", configuration.model);
|
||||
if (configuration.acpxAgent) query.set("acpxAgent", configuration.acpxAgent);
|
||||
query.set("lifecycleMode", configuration.lifecyclePolicy.mode);
|
||||
if (configuration.lifecyclePolicy.mode === "warm") {
|
||||
query.set("idleTimeoutMs", String(configuration.lifecyclePolicy.idleTimeoutMs));
|
||||
}
|
||||
const response = await fetch(`${BASE}/cleanroom/session?${query.toString()}`, { credentials: CREDENTIALS });
|
||||
if (!response.ok) throw await readError(response, "/cleanroom/session");
|
||||
return (await response.json()) as CapabilityLiveResponse;
|
||||
},
|
||||
/** `New chat`: retire the current room and mint a new mock tenant. */
|
||||
newCleanRoom(sessionId: string | null, configuration: CapabilityHarnessConfiguration): Promise<CapabilityLiveResponse> {
|
||||
return post("/cleanroom/session", { ...(sessionId === null ? {} : { sessionId }), ...configuration });
|
||||
},
|
||||
/**
|
||||
* Runs one turn. `onFrame` fires for every interim projection the server
|
||||
* writes while the POST is open; the resolved value is the settled payload.
|
||||
*/
|
||||
send(
|
||||
sessionId: string,
|
||||
message: string,
|
||||
options: CapabilitySendOptions = {},
|
||||
): Promise<CapabilityLiveResponse> {
|
||||
return postTurnStream("/message", { sessionId, message }, options);
|
||||
},
|
||||
stop(sessionId: string): Promise<CapabilityLiveResponse> {
|
||||
return post("/interrupt", { sessionId });
|
||||
},
|
||||
reset(sessionId: string): Promise<CapabilityLiveResponse> {
|
||||
return post("/reset", { sessionId });
|
||||
},
|
||||
reconnect(sessionId: string): Promise<CapabilityLiveResponse> {
|
||||
return post("/reconnect", { sessionId });
|
||||
},
|
||||
respond(
|
||||
sessionId: string,
|
||||
interactionId: string,
|
||||
outcome: string,
|
||||
result: unknown,
|
||||
): Promise<CapabilityLiveResponse> {
|
||||
return post("/interaction", { sessionId, interactionId, outcome, result });
|
||||
},
|
||||
};
|
||||
|
||||
const SESSION_STORAGE_KEY = "paperclip-runner.capability.session";
|
||||
/**
|
||||
* The clean room keeps its own key. Sharing one would let a scenario session id
|
||||
* be handed to the clean-room route (and the reverse) after a refresh, which is
|
||||
* exactly the cross-surface bleed the isolation criterion forbids.
|
||||
*/
|
||||
const CLEAN_ROOM_STORAGE_KEY = "paperclip-runner.capability.cleanroom.session";
|
||||
|
||||
function storageKey(surface: "issue" | "cleanroom"): string {
|
||||
return surface === "cleanroom" ? CLEAN_ROOM_STORAGE_KEY : SESSION_STORAGE_KEY;
|
||||
}
|
||||
|
||||
export function rememberSession(sessionId: string, surface: "issue" | "cleanroom" = "issue"): void {
|
||||
try {
|
||||
window.localStorage.setItem(storageKey(surface), sessionId);
|
||||
} catch {
|
||||
// Refresh restore falls back to a fresh session when storage is blocked.
|
||||
}
|
||||
}
|
||||
|
||||
export function recallSession(surface: "issue" | "cleanroom" = "issue"): string | null {
|
||||
try {
|
||||
return window.localStorage.getItem(storageKey(surface));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
|
||||
import { App } from "./App";
|
||||
import "./issue-thread.css";
|
||||
|
||||
// `?capture=1` freezes animation, caret, and smooth scrolling so the
|
||||
// screenshot matrix is byte-stable across runs (contract §10.1).
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const hashQuery = window.location.hash.split("?")[1] ?? "";
|
||||
if (params.get("capture") === "1" || new URLSearchParams(hashQuery).get("capture") === "1") {
|
||||
document.documentElement.dataset.capture = "true";
|
||||
}
|
||||
|
||||
const root = document.getElementById("root");
|
||||
if (root === null) {
|
||||
throw new Error("Capability issue-thread root element is missing");
|
||||
}
|
||||
|
||||
createRoot(root).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,91 @@
|
||||
import type { ReactNode, Ref } from "react";
|
||||
|
||||
import type { CapabilityTaskStatus } from "../../../src/mock-core/capability-control-plane-types";
|
||||
|
||||
/**
|
||||
* Package-local equivalents of the product StatusBadge/chip anatomy. Every
|
||||
* state pairs color with a glyph and text so the surface stays readable
|
||||
* without color (contract §9.5).
|
||||
*/
|
||||
|
||||
const STATUS_COPY: Record<CapabilityTaskStatus, { label: string; glyph: string }> = {
|
||||
backlog: { label: "Backlog", glyph: "○" },
|
||||
todo: { label: "Todo", glyph: "○" },
|
||||
in_progress: { label: "In progress", glyph: "◐" },
|
||||
in_review: { label: "In review", glyph: "◑" },
|
||||
done: { label: "Done", glyph: "✓" },
|
||||
blocked: { label: "Blocked", glyph: "✕" },
|
||||
cancelled: { label: "Cancelled", glyph: "–" },
|
||||
};
|
||||
|
||||
const PRIORITY_GLYPH: Record<string, string> = {
|
||||
critical: "▲▲",
|
||||
high: "▲",
|
||||
medium: "▬",
|
||||
low: "▼",
|
||||
};
|
||||
|
||||
export function StatusBadge({ status }: { status: CapabilityTaskStatus }) {
|
||||
const copy = STATUS_COPY[status];
|
||||
return (
|
||||
<span className="pit-status-badge" data-status={status}>
|
||||
<span aria-hidden="true">{copy.glyph}</span>
|
||||
{copy.label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function PriorityIcon({ priority }: { priority: string }) {
|
||||
return (
|
||||
<span className="pit-priority">
|
||||
<span aria-hidden="true">{PRIORITY_GLYPH[priority] ?? "▬"}</span>{" "}
|
||||
{priority.charAt(0).toUpperCase() + priority.slice(1)} priority
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function Chip({
|
||||
tone,
|
||||
children,
|
||||
title,
|
||||
testId,
|
||||
/** Set to -1 so focus management can land on a chip without adding a tab stop. */
|
||||
tabIndex,
|
||||
chipRef,
|
||||
}: {
|
||||
tone?: "live" | "mock" | "accent" | "success" | "danger";
|
||||
children: ReactNode;
|
||||
title?: string;
|
||||
testId?: string;
|
||||
tabIndex?: number;
|
||||
chipRef?: Ref<HTMLSpanElement>;
|
||||
}) {
|
||||
return (
|
||||
<span
|
||||
className="pit-chip"
|
||||
data-tone={tone}
|
||||
title={title}
|
||||
data-testid={testId}
|
||||
tabIndex={tabIndex}
|
||||
ref={chipRef}
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function Timestamp({ value }: { value: string }) {
|
||||
// Rendered from fixture data with a fixed locale so captures stay stable.
|
||||
const stamp = new Date(value);
|
||||
const hours = String(stamp.getUTCHours()).padStart(2, "0");
|
||||
const minutes = String(stamp.getUTCMinutes()).padStart(2, "0");
|
||||
const seconds = String(stamp.getUTCSeconds()).padStart(2, "0");
|
||||
return (
|
||||
<time className="pit-card-meta" dateTime={value}>
|
||||
{hours}:{minutes}:{seconds}
|
||||
</time>
|
||||
);
|
||||
}
|
||||
|
||||
/** Re-exported so the thread strip and the deliverable card share one unit. */
|
||||
export { capabilityFormatBytes as formatBytes } from "../../../src/issue-thread/types";
|
||||
@@ -0,0 +1,75 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseCapabilityRoute, capabilityRouteHref } from "./route";
|
||||
|
||||
function at(hash: string, search = "") {
|
||||
return parseCapabilityRoute({ hash, search });
|
||||
}
|
||||
|
||||
describe("Capability issue-thread routes", () => {
|
||||
it("keeps the existing deterministic scenario deep links intact", () => {
|
||||
const route = at("#/issue/dp-documents?shot=document-revision&panel=state&rec=doc-1&at=3&seg=evidence");
|
||||
|
||||
expect(route.surface).toBe("issue");
|
||||
expect(route.fixtureProfile).toBe("dp-documents");
|
||||
expect(route.shot).toBe("document-revision");
|
||||
expect(route.panel).toBe("state");
|
||||
expect(route.record).toBe("doc-1");
|
||||
expect(route.at).toBe(3);
|
||||
expect(route.segment).toBe("evidence");
|
||||
expect(route.mode).toBe("fake");
|
||||
expect(capabilityRouteHref(route, {})).toBe(
|
||||
"#/issue/dp-documents?shot=document-revision&panel=state&rec=doc-1&at=3&seg=evidence",
|
||||
);
|
||||
});
|
||||
|
||||
it("still infers replay mode from the replay shot and honours an explicit mode", () => {
|
||||
expect(at("#/issue/hb-baseline?shot=replay-mode").mode).toBe("replay");
|
||||
expect(at("#/issue/hb-baseline?mode=live").mode).toBe("live");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Capability clean-room route", () => {
|
||||
it("is reachable without naming a scenario", () => {
|
||||
const route = at("#/chat");
|
||||
|
||||
expect(route.surface).toBe("chat");
|
||||
expect(route.shot).toBe(null);
|
||||
expect(route.at).toBe(null);
|
||||
expect(capabilityRouteHref(route, {})).toBe("#/chat");
|
||||
});
|
||||
|
||||
it("is always live: no URL can downgrade it to a fixture or a recording", () => {
|
||||
for (const hash of [
|
||||
"#/chat",
|
||||
"#/chat?mode=fake",
|
||||
"#/chat?mode=replay",
|
||||
"#/chat?shot=replay-mode",
|
||||
"#/chat?shot=thread-baseline&at=4",
|
||||
]) {
|
||||
const route = at(hash);
|
||||
expect(route.surface, hash).toBe("chat");
|
||||
expect(route.mode, hash).toBe("live");
|
||||
expect(route.shot, hash).toBe(null);
|
||||
expect(route.at, hash).toBe(null);
|
||||
}
|
||||
expect(at("", "?mode=fake#/chat").surface).toBe("issue");
|
||||
});
|
||||
|
||||
it("carries only the evidence deep-link parameters back into its own href", () => {
|
||||
const route = at("#/chat?panel=calls&rec=call-1&seg=evidence");
|
||||
|
||||
expect(route.panel).toBe("calls");
|
||||
expect(route.record).toBe("call-1");
|
||||
expect(route.segment).toBe("evidence");
|
||||
expect(capabilityRouteHref(route, {})).toBe("#/chat?panel=calls&rec=call-1&seg=evidence");
|
||||
expect(capabilityRouteHref(route, { panel: null, record: null, segment: "thread" })).toBe("#/chat");
|
||||
});
|
||||
|
||||
it("switches surfaces without dragging scenario state across", () => {
|
||||
const chat = at("#/chat");
|
||||
expect(capabilityRouteHref(chat, { surface: "issue", fixtureProfile: "ar-artifacts" })).toBe(
|
||||
"#/issue/ar-artifacts?mode=live",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* Deterministic route scheme from the Capability UX contract §10.1, plus the
|
||||
* Capability clean-room surface.
|
||||
*
|
||||
* `#/issue/<fixtureProfile>?shot=<slug>&panel=<section>&rec=<id>&at=<ordinal>&seg=thread|evidence`
|
||||
* `#/chat?panel=<section>&rec=<id>&seg=thread|evidence`
|
||||
*
|
||||
* Parameters are also accepted on the document query string so a capture tool
|
||||
* can address a state without depending on hash-fragment escaping.
|
||||
*
|
||||
* The clean-room surface has no fixture, shot, or replay ordinal by design: it
|
||||
* starts blank and is always a live Codex session. `mode` is pinned to `live`
|
||||
* there rather than parsed, so no URL can talk the clean room into answering
|
||||
* with a fixture or a recording.
|
||||
*/
|
||||
|
||||
import type { CapabilityEvidenceSectionId } from "../../../src/issue-thread/types";
|
||||
import { CAPABILITY_EVIDENCE_SECTIONS } from "../../../src/issue-thread/types";
|
||||
import { CAPABILITY_DEFAULT_FIXTURE_PROFILE } from "../../../src/issue-thread/fixtures";
|
||||
|
||||
export type CapabilitySurface = "issue" | "chat";
|
||||
|
||||
export interface CapabilityRoute {
|
||||
surface: CapabilitySurface;
|
||||
fixtureProfile: string;
|
||||
shot: string | null;
|
||||
panel: CapabilityEvidenceSectionId | null;
|
||||
record: string | null;
|
||||
at: number | null;
|
||||
segment: "thread" | "evidence";
|
||||
/** `live` opts into the package session server; otherwise fixtures render. */
|
||||
mode: "fake" | "live" | "replay";
|
||||
}
|
||||
|
||||
const SECTION_IDS = new Set<string>(CAPABILITY_EVIDENCE_SECTIONS.map((section) => section.id));
|
||||
|
||||
function mergeParams(search: string, hash: string): URLSearchParams {
|
||||
const params = new URLSearchParams(search);
|
||||
const queryIndex = hash.indexOf("?");
|
||||
if (queryIndex >= 0) {
|
||||
for (const [key, value] of new URLSearchParams(hash.slice(queryIndex + 1))) {
|
||||
params.set(key, value);
|
||||
}
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
export function parseCapabilityRoute(url: {
|
||||
search: string;
|
||||
hash: string;
|
||||
}): CapabilityRoute {
|
||||
const params = mergeParams(url.search, url.hash);
|
||||
const path = url.hash.replace(/^#/, "").split("?")[0] ?? "";
|
||||
const chat = /^\/chat\/?$/.test(path);
|
||||
const match = /^\/issue\/([^/?]+)/.exec(path);
|
||||
const shot = chat ? null : params.get("shot");
|
||||
const requestedMode = params.get("mode");
|
||||
const panel = params.get("panel");
|
||||
const at = params.get("at");
|
||||
const segment = params.get("seg");
|
||||
const mode = chat
|
||||
? ("live" as const)
|
||||
: requestedMode === "live" || requestedMode === "replay" || requestedMode === "fake"
|
||||
? requestedMode
|
||||
: shot === "replay-mode"
|
||||
? "replay"
|
||||
: "fake";
|
||||
return {
|
||||
surface: chat ? "chat" : "issue",
|
||||
fixtureProfile: match?.[1] ?? CAPABILITY_DEFAULT_FIXTURE_PROFILE,
|
||||
shot,
|
||||
panel: panel !== null && SECTION_IDS.has(panel) ? (panel as CapabilityEvidenceSectionId) : null,
|
||||
record: params.get("rec"),
|
||||
at: chat || at === null || !/^\d+$/.test(at) ? null : Number.parseInt(at, 10),
|
||||
segment: segment === "evidence" ? "evidence" : "thread",
|
||||
mode,
|
||||
};
|
||||
}
|
||||
|
||||
export function capabilityRouteHref(route: CapabilityRoute, overrides: Partial<CapabilityRoute>): string {
|
||||
const next = { ...route, ...overrides };
|
||||
const params = new URLSearchParams();
|
||||
if (next.surface === "chat") {
|
||||
if (next.panel !== null) params.set("panel", next.panel);
|
||||
if (next.record !== null) params.set("rec", next.record);
|
||||
if (next.segment !== "thread") params.set("seg", next.segment);
|
||||
const chatQuery = params.toString();
|
||||
return `#/chat${chatQuery.length > 0 ? `?${chatQuery}` : ""}`;
|
||||
}
|
||||
if (next.shot !== null) params.set("shot", next.shot);
|
||||
if (next.mode !== "fake") params.set("mode", next.mode);
|
||||
if (next.panel !== null) params.set("panel", next.panel);
|
||||
if (next.record !== null) params.set("rec", next.record);
|
||||
if (next.at !== null) params.set("at", String(next.at));
|
||||
if (next.segment !== "thread") params.set("seg", next.segment);
|
||||
const query = params.toString();
|
||||
return `#/issue/${next.fixtureProfile}${query.length > 0 ? `?${query}` : ""}`;
|
||||
}
|
||||
Reference in new issue
Block a user