feat(webui): land the Phase 1 foundation on the navigation restructure
Two Vue branches were in flight and looked like competing versions of the same change. They were not: this branch had the navigation restructure (Phase 4) and the route table, and the other worktree had the Phase 1 foundation, still uncommitted. Neither had ported a page. This reconciles them. What came across from the foundation: - lib/api.ts, the one client every request goes through, so the CSRF and Content-Type headers live in a single place, plus the four framework-free modules it needs: uuid, stream-state, format, task-meta. - loadTaskMeta() at boot, so /api/task-meta replaces the freeze-dried lifecycle defaults instead of the catalogue being frozen into the bundle. - capabilities.ts keeps the other branch's pure hiddenRoutes, but reads route.meta.section. The other version read route.section, which is always undefined for this route table, so its capability gating was silently dead. The route table stays this branch's: internal/gateway's registry test holds it in parity with the agent-facing page index in both directions, and the other branch's table fails it with seven errors. The frame is Tailwind on the shell, not a ported stylesheet. layout.css described a shell, a topbar and a nav as authored classes, but the topbar is a Vue component like every other surface and emits none of them, so two thirds of that file had no consumer. What the frame needs is now the shell element's own utilities plus the canvas, focus floor and motion preference in style.css's base layer, where a global element rule belongs. Verified equal to the stylesheet it replaces: 20px radius, hairline border, blur(28px) saturate(1.2), and the narrow-screen collapse. Also fixes the bundle freshness check failing on the first build after any change, which had cost both branches of this port a rebuild-and-retry. ui/dist is committed, so nothing ignores it and Tailwind's content detection scanned it, making every build an input to the next: class strings left in the bundle generated utilities for classes nothing references any more, so an unchanged tree built a different bundle. Excluding it also drops ~12KB of dead CSS.
This commit is contained in:
12 files changed
+598
-65
No files matched your search
+39
-11
@@ -4,24 +4,52 @@ import { onMounted } from "vue";
|
||||
import Topbar from "@/components/topbar/Topbar.vue";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { hidden, loadCapabilities } from "@/lib/capabilities";
|
||||
import { loadTaskMeta } from "@/lib/task-meta";
|
||||
|
||||
onMounted(() => {
|
||||
// Asked for once, after the shell is up: the nav paints immediately and
|
||||
// loses the entries this process cannot back a moment later, rather than
|
||||
// holding the page behind a request. A failed read hides nothing.
|
||||
void loadCapabilities();
|
||||
|
||||
// The lifecycle vocabulary -- status labels, pill severity, "needs you"
|
||||
// grouping, and the operator actions -- is served by /api/task-meta. Asked
|
||||
// for once, after the shell is up: the freeze-dried defaults paint
|
||||
// immediately and this replaces them, so a catalogue change on the server
|
||||
// reaches the browser without a UI release. loadTaskMeta never throws (a
|
||||
// failed read keeps the defaults), so it needs no catch here.
|
||||
void loadTaskMeta();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<TooltipProvider :delay-duration="350">
|
||||
<Topbar :hidden="hidden" />
|
||||
<main class="min-h-[calc(100svh-3.5rem)]">
|
||||
<!--
|
||||
Keyed on the path and its parameters but not the query: a query-only
|
||||
change is an entry state, so the page keeps the operator's filters,
|
||||
while two different :id values get fresh instances.
|
||||
-->
|
||||
<RouterView v-slot="{ Component, route }">
|
||||
<component :is="Component" :key="route.path" />
|
||||
</RouterView>
|
||||
</main>
|
||||
<!--
|
||||
One contained, rounded surface floating on the canvas `body` carries:
|
||||
framing the workspace gives the panels an edge to sit against, and lets
|
||||
the light behind read through rather than stopping at the first opaque
|
||||
card. The frame is a desktop affordance, so at the narrow breakpoint it
|
||||
goes edge to edge instead of insetting a rounded card on a phone.
|
||||
|
||||
`backdrop-filter` makes this a containing block for `position: fixed`,
|
||||
so the chat launcher has to render outside this element.
|
||||
-->
|
||||
<div
|
||||
class="flex min-h-[calc(100vh-2rem)] flex-col overflow-hidden rounded-xl border border-[var(--hairline)] bg-[var(--workspace)] shadow-[var(--shadow-workspace)] backdrop-blur-[28px] backdrop-saturate-[1.2] max-[900px]:min-h-screen max-[900px]:rounded-none max-[900px]:border-0 max-[900px]:shadow-none"
|
||||
>
|
||||
<Topbar :hidden="hidden" />
|
||||
<main class="w-full flex-1 overflow-x-hidden p-8 max-[900px]:p-4">
|
||||
<!--
|
||||
Keyed on the path and its parameters but not the query: a query-only
|
||||
change is an entry state, so the page keeps the operator's filters,
|
||||
while two different :id values get fresh instances -- without that
|
||||
the second id diffs the first one in place and the previous task's
|
||||
open tab stays open on the next (W11).
|
||||
-->
|
||||
<RouterView v-slot="{ Component, route }">
|
||||
<component :is="Component" :key="route.path" />
|
||||
</RouterView>
|
||||
</main>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</template>
|
||||
@@ -0,0 +1,246 @@
|
||||
// Single place that knows how to talk to archied. Every feature folder goes
|
||||
// through api.* below, and every api.* method goes through send(), so the CSRF
|
||||
// header, the Content-Type, the request timeout, and the error shape live in
|
||||
// this one file.
|
||||
import { streamStateFor, type StreamState } from "./stream-state";
|
||||
import { randomUUID } from "./uuid";
|
||||
|
||||
// DEFAULT_TIMEOUT_MS bounds a request so a daemon that accepts the connection
|
||||
// but never answers cannot leave the UI in a loading state with no way back.
|
||||
// The retry affordances rely on fetch settling, so bound it.
|
||||
const DEFAULT_TIMEOUT_MS = 15000;
|
||||
|
||||
/** Query values are omitted when empty, so the server sees an absent filter. */
|
||||
export type QueryParams = Record<string, string | number | null | undefined>;
|
||||
|
||||
/** Opaque payloads are passed through unchanged; the server owns their shape. */
|
||||
export type Payload = Record<string, unknown>;
|
||||
|
||||
// qs builds a query string, omitting empty values so the server sees an
|
||||
// absent filter rather than an empty one.
|
||||
function qs(params?: QueryParams): string {
|
||||
const q = new URLSearchParams();
|
||||
for (const [k, v] of Object.entries(params || {})) {
|
||||
if (v !== "" && v != null) q.set(k, String(v));
|
||||
}
|
||||
const s = q.toString();
|
||||
return s ? `?${s}` : "";
|
||||
}
|
||||
|
||||
// errorMessage prefers what the server actually said. archied answers these
|
||||
// with http.Error, i.e. a plain-text reason -- "task is not awaiting
|
||||
// approval", "max retries reached (3/3)", "Content-Type must be
|
||||
// application/json" -- and discarding it in favour of "409 Conflict" throws
|
||||
// away the only part an operator can act on.
|
||||
async function errorMessage(res: Response): Promise<string> {
|
||||
try {
|
||||
const body = (await res.text()).trim();
|
||||
if (body) return body.split("\n")[0].slice(0, 200);
|
||||
} catch {
|
||||
// Body already consumed or unreadable; fall through to the status.
|
||||
}
|
||||
return `${res.status} ${res.statusText}`;
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
|
||||
constructor(message: string, status: number) {
|
||||
super(message);
|
||||
this.name = "ApiError";
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
/** How a failed operator action should render. */
|
||||
export type ActionErrorKind = "session-expired" | "refused" | "broken";
|
||||
|
||||
// classifyActionError turns a failed operator action into a rendering
|
||||
// decision. archied's own handlers already return distinguishable status
|
||||
// codes for a refused mutation (400/403/409/415 -- bad input, missing CSRF,
|
||||
// cross-origin, conflicting state, a body that is not JSON) versus a broken
|
||||
// one (5xx, or no status at all when fetch itself failed -- network drop,
|
||||
// timeout); 401 additionally means the session -- archied's own token cookie,
|
||||
// or an upstream forward-auth proxy sitting in front of it -- has expired
|
||||
// rather than that the action was rejected or the daemon is unwell.
|
||||
export function classifyActionError(err: unknown): { kind: ActionErrorKind; message: string } {
|
||||
const status = err instanceof ApiError ? err.status : undefined;
|
||||
const message = err instanceof Error && err.message ? err.message : "Action failed";
|
||||
if (status === 401) return { kind: "session-expired", message };
|
||||
if (status !== undefined && status >= 400 && status < 500) return { kind: "refused", message };
|
||||
return { kind: "broken", message };
|
||||
}
|
||||
|
||||
// send is the only fetch() in the dashboard. It converts a non-ok response
|
||||
// into an ApiError carrying the server's own explanation and a usable status,
|
||||
// and hands the raw Response back so the streaming caller can read the body
|
||||
// itself.
|
||||
async function send(path: string, init: RequestInit): Promise<Response> {
|
||||
const res = await fetch(path, init);
|
||||
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
|
||||
return res;
|
||||
}
|
||||
|
||||
interface RequestOptions {
|
||||
method?: string;
|
||||
body?: unknown;
|
||||
timeoutMs?: number;
|
||||
parse?: boolean;
|
||||
}
|
||||
|
||||
// request performs a JSON request. Every mutating method must declare a JSON
|
||||
// body: archied's handlers run authorizeTaskMutation first, and it answers 415
|
||||
// unless Content-Type is application/json -- including for a mutation that has
|
||||
// no body to send, because that requirement is what makes a simple cross-origin
|
||||
// form post inexpressible. Sending the header on every mutation, rather than
|
||||
// only where a payload happens to exist, is what keeps a bodyless DELETE or
|
||||
// approve from being refused.
|
||||
async function request<T = unknown>(path: string, opts: RequestOptions = {}): Promise<T> {
|
||||
const { method = "GET", body, timeoutMs = DEFAULT_TIMEOUT_MS, parse = true } = opts;
|
||||
const headers: Record<string, string> = { Accept: "application/json" };
|
||||
const init: RequestInit = { method, headers, signal: AbortSignal.timeout(timeoutMs) };
|
||||
if (method !== "GET") {
|
||||
headers["Content-Type"] = "application/json";
|
||||
headers["X-Archie-CSRF"] = "1";
|
||||
}
|
||||
if (body !== undefined) init.body = JSON.stringify(body);
|
||||
|
||||
const res = await send(path, init);
|
||||
return (parse ? await res.json() : undefined) as T;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
summary: <T = unknown>() => request<T>("/api/summary"),
|
||||
tasks: <T = unknown>() => request<T>("/api/tasks"),
|
||||
taskMeta: <T = unknown>() => request<T>("/api/task-meta"),
|
||||
task: <T = unknown>(id: string) => request<T>(`/api/tasks/${encodeURIComponent(id)}`),
|
||||
taskAttempts: <T = unknown>(id: string) => request<T>(`/api/tasks/${encodeURIComponent(id)}/attempts`),
|
||||
taskChanges: <T = unknown>(id: string, params?: QueryParams) =>
|
||||
request<T>(`/api/tasks/${encodeURIComponent(id)}/changes` + qs(params)),
|
||||
taskDebug: <T = unknown>(id: string, params?: QueryParams) =>
|
||||
request<T>(`/api/tasks/${encodeURIComponent(id)}/debug` + qs(params)),
|
||||
taskAction: <T = unknown>(id: string, action: string) =>
|
||||
request<T>(`/api/tasks/${encodeURIComponent(id)}/action`, { method: "POST", body: { action } }),
|
||||
setup: <T = unknown>() => request<T>("/api/setup"),
|
||||
capabilities: <T = unknown>() => request<T>("/api/capabilities"),
|
||||
workflows: <T = unknown>() => request<T>("/api/workflows"),
|
||||
workRequest: <T = unknown>(workRequest: Payload) => request<T>("/api/work-requests", { method: "POST", body: workRequest }),
|
||||
skills: <T = unknown>() => request<T>("/api/skills"),
|
||||
channels: <T = unknown>() => request<T>("/api/channels"),
|
||||
curators: <T = unknown>() => request<T>("/api/curators"),
|
||||
channelReload: <T = unknown>(id: string) =>
|
||||
request<T>(`/api/channels/${encodeURIComponent(id)}/reload`, { method: "POST", body: {} }),
|
||||
config: <T = unknown>() => request<T>("/api/config"),
|
||||
version: <T = unknown>() => request<T>("/api/version"),
|
||||
configUpdate: <T = unknown>(updates: Payload) => request<T>("/api/config", { method: "PATCH", body: { updates } }),
|
||||
configRepoUpdate: <T = unknown>(owner: string, name: string, field: string, value: unknown) =>
|
||||
request<T>(`/api/config/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`, {
|
||||
method: "PATCH",
|
||||
body: { field, value },
|
||||
}),
|
||||
configReset: <T = unknown>(key: string) => request<T>("/api/config/reset", { method: "POST", body: { key } }),
|
||||
logs: <T = unknown>(params?: QueryParams) => request<T>("/api/logs" + qs(params)),
|
||||
taskLogs: <T = unknown>(id: string, params?: QueryParams) =>
|
||||
request<T>(`/api/tasks/${encodeURIComponent(id)}/logs` + qs(params)),
|
||||
// A download is a navigation, not a fetch: the browser must own the
|
||||
// Content-Disposition filename and stream the body to disk rather than hold
|
||||
// a whole log in memory. The URL builder is the client-side contract, and
|
||||
// log-row keeps it beside the panel that uses it.
|
||||
taskLogDownloadURL: (id: string, attempt?: number | null) =>
|
||||
`/api/tasks/${encodeURIComponent(id)}/logs/download` + (attempt == null ? "" : `?attempt=${attempt}`),
|
||||
captures: <T = unknown>(limit?: number) => request<T>("/api/captures" + qs({ limit })),
|
||||
mappings: <T = unknown>() => request<T>("/api/mappings"),
|
||||
mappingCreate: <T = unknown>(mapping: Payload) => request<T>("/api/mappings", { method: "POST", body: mapping }),
|
||||
mappingUpdate: <T = unknown>(id: string, mapping: Payload) =>
|
||||
request<T>(`/api/mappings/${encodeURIComponent(id)}`, { method: "PATCH", body: mapping }),
|
||||
// A delete answers 204, so there is no body to parse.
|
||||
mappingDelete: (id: string) => request<void>(`/api/mappings/${encodeURIComponent(id)}`, { method: "DELETE", parse: false }),
|
||||
mappingPreview: <T = unknown>(captureId: string, fields: unknown) =>
|
||||
request<T>("/api/mappings/preview", { method: "POST", body: { capture_id: captureId, fields } }),
|
||||
bindings: <T = unknown>() => request<T>("/api/bindings"),
|
||||
bindingCreate: <T = unknown>(binding: Payload) => request<T>("/api/bindings", { method: "POST", body: binding }),
|
||||
bindingUpdate: <T = unknown>(id: string, binding: Payload) =>
|
||||
request<T>(`/api/bindings/${encodeURIComponent(id)}`, { method: "PATCH", body: binding }),
|
||||
bindingDelete: (id: string) => request<void>(`/api/bindings/${encodeURIComponent(id)}`, { method: "DELETE", parse: false }),
|
||||
bindingApprove: <T = unknown>(id: string) => request<T>(`/api/bindings/${encodeURIComponent(id)}/approve`, { method: "POST" }),
|
||||
chatSessions: <T = unknown>() => request<T>("/api/chat/sessions"),
|
||||
chatMessages: <T = unknown>(id: string) => request<T>(`/api/chat/sessions/${encodeURIComponent(id)}/messages`),
|
||||
chatTurns: <T = unknown>(id: string) => request<T>(`/api/chat/sessions/${encodeURIComponent(id)}/turns`),
|
||||
chatCancel: <T = unknown>(sessionID: string) => request<T>("/api/chat/cancel", { method: "POST", body: { session_id: sessionID } }),
|
||||
// The page the operator was on when they asked, so a chat answer can be
|
||||
// about what they were looking at. History routing makes that the pathname.
|
||||
chatMessage: <T = unknown>(channelID: string, text: string) =>
|
||||
request<T>("/api/chat/message", {
|
||||
method: "POST",
|
||||
body: {
|
||||
channel_id: channelID,
|
||||
source_id: randomUUID(),
|
||||
text,
|
||||
page: location.pathname + location.search || "/",
|
||||
},
|
||||
}),
|
||||
chatPersona: <T = unknown>(sessionID: string, name: string) =>
|
||||
request<T>("/api/chat/persona", { method: "POST", body: { session_id: sessionID, name } }),
|
||||
chatUpdate: <T = unknown>() => request<T>("/api/chat/update"),
|
||||
chatUpdateDefer: <T = unknown>(snapshot: unknown) => request<T>("/api/chat/update/defer", { method: "POST", body: { snapshot } }),
|
||||
// Installing restarts archied, so it is allowed far longer than a normal
|
||||
// request before the UI gives up.
|
||||
chatUpdateInstall: <T = unknown>(snapshot: unknown) =>
|
||||
request<T>("/api/chat/update/install", { method: "POST", body: { snapshot }, timeoutMs: 120000 }),
|
||||
chatDangerous: <T = unknown>() => request<T>("/api/chat/dangerous"),
|
||||
chatDangerousRequest: <T = unknown>(kind: string, spec: unknown) =>
|
||||
request<T>(`/api/chat/dangerous/${encodeURIComponent(kind)}`, { method: "POST", body: { spec } }),
|
||||
chatDangerousDecision: <T = unknown>(id: string, decision: string) =>
|
||||
request<T>(`/api/chat/dangerous/${encodeURIComponent(id)}/decision`, { method: "POST", body: { decision } }),
|
||||
// A server-sent event stream cannot be parsed as JSON and outlives a normal
|
||||
// request, so the caller owns the abort controller and the timeout, and
|
||||
// reads the body itself. Only the URL, headers, and failure shape are shared.
|
||||
chatStream: (payload: unknown, opts: { signal?: AbortSignal } = {}) =>
|
||||
send("/api/chat/stream", {
|
||||
method: "POST",
|
||||
headers: { Accept: "text/event-stream", "Content-Type": "application/json", "X-Archie-CSRF": "1" },
|
||||
body: JSON.stringify(payload),
|
||||
signal: opts.signal,
|
||||
}),
|
||||
};
|
||||
|
||||
/**
|
||||
* Subscribe to archied's event stream. Returns an unsubscribe function.
|
||||
* Reconnection is the browser's job via EventSource, but a closed stream is
|
||||
* surfaced to the caller so the UI can show it rather than silently freezing.
|
||||
*/
|
||||
export function subscribeEvents(
|
||||
onEvent: (event: unknown) => void,
|
||||
onStateChange?: (state: StreamState) => void,
|
||||
): () => void {
|
||||
const src = new EventSource("/events");
|
||||
src.onopen = () => onStateChange?.("live");
|
||||
src.onerror = () => onStateChange?.("reconnecting");
|
||||
src.onmessage = (e) => {
|
||||
try {
|
||||
onEvent(JSON.parse(e.data));
|
||||
} catch {
|
||||
/* a malformed frame should not kill the stream */
|
||||
}
|
||||
};
|
||||
return () => src.close();
|
||||
}
|
||||
|
||||
export function subscribeLogs(
|
||||
onEntry: (entry: unknown) => void,
|
||||
onStateChange?: (state: StreamState) => void,
|
||||
): () => void {
|
||||
const src = new EventSource("/api/logs/stream");
|
||||
src.onopen = () => onStateChange?.("live");
|
||||
// onerror fires both for a drop the browser will retry and for one it has
|
||||
// given up on; readyState is what tells them apart.
|
||||
src.onerror = () => onStateChange?.(streamStateFor(src.readyState));
|
||||
src.onmessage = (event) => {
|
||||
try {
|
||||
onEntry(JSON.parse(event.data));
|
||||
} catch {
|
||||
/* malformed log frame */
|
||||
}
|
||||
};
|
||||
return () => src.close();
|
||||
}
|
||||
+26
-13
@@ -1,24 +1,39 @@
|
||||
// Which dashboard sections the serving process can actually back.
|
||||
//
|
||||
// From the UI cutover the dashboard is served by more than one composition,
|
||||
// and a section with nothing behind it still answers -- an empty list, a
|
||||
// "disabled" marker, a 501 -- which the browser cannot tell from a quiet
|
||||
// deployment. GET /api/capabilities says which sections are backed here, and
|
||||
// the nav drops the rest.
|
||||
import { ref } from "vue";
|
||||
|
||||
import { api } from "@/lib/api";
|
||||
import { routes } from "@/router";
|
||||
|
||||
/** The `sections` map GET /api/capabilities returns. */
|
||||
export type CapabilitySections = Record<string, boolean>;
|
||||
|
||||
interface RouteMeta {
|
||||
section?: string;
|
||||
/**
|
||||
* The route fields hiddenRoutes reads. The section lives under `meta` because
|
||||
* the route table is an untyped literal: internal/gateway's registry test
|
||||
* parses `const routes = [` and one route per line out of the source, so it
|
||||
* cannot carry a type annotation.
|
||||
*/
|
||||
export interface SectionedRoute {
|
||||
path: string;
|
||||
meta?: { section?: string };
|
||||
}
|
||||
|
||||
/** hidden lists the route paths this composition cannot serve. */
|
||||
export const hidden = ref<string[]>([]);
|
||||
|
||||
function hiddenFor(sections: CapabilitySections | undefined): string[] {
|
||||
// hiddenRoutes returns the paths whose section the server reported it cannot
|
||||
// serve. An unreported section stays visible: a page that says "unavailable"
|
||||
// is recoverable, a navigation entry that silently vanished is not, so an
|
||||
// older server or a failed capabilities read shows everything.
|
||||
export function hiddenRoutes(sections: CapabilitySections | null | undefined, table: SectionedRoute[]): string[] {
|
||||
if (!sections) return [];
|
||||
return (routes as Array<{ path: string; meta?: RouteMeta }>)
|
||||
.filter((route) => {
|
||||
const section = route.meta?.section;
|
||||
return typeof section === "string" && sections[section] === false;
|
||||
})
|
||||
.map((route) => route.path);
|
||||
return table.filter((r) => typeof r.meta?.section === "string" && sections[r.meta.section] === false).map((r) => r.path);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -28,10 +43,8 @@ function hiddenFor(sections: CapabilitySections | undefined): string[] {
|
||||
*/
|
||||
export async function loadCapabilities(): Promise<void> {
|
||||
try {
|
||||
const response = await fetch("/api/capabilities", { headers: { Accept: "application/json" } });
|
||||
if (!response.ok) return;
|
||||
const body = (await response.json()) as { sections?: CapabilitySections } | null;
|
||||
hidden.value = hiddenFor(body?.sections);
|
||||
const body = await api.capabilities<{ sections?: CapabilitySections } | null>();
|
||||
hidden.value = hiddenRoutes(body?.sections, routes as SectionedRoute[]);
|
||||
} catch {
|
||||
// Offline or an older server: every section stays visible.
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* Display formatting shared across the dashboard pages. Pure functions: no
|
||||
* DOM, no framework.
|
||||
*/
|
||||
|
||||
/** Humanised relative time: "2 min ago". Raw timestamps make people do maths. */
|
||||
export function ago(value: string | number | Date | null | undefined): string {
|
||||
if (!value) return "—";
|
||||
const then = value instanceof Date ? value : new Date(value);
|
||||
const secs = Math.floor((Date.now() - then.getTime()) / 1000);
|
||||
if (!Number.isFinite(secs)) return "—";
|
||||
if (secs < 45) return "just now";
|
||||
const units: Array<[string, number]> = [
|
||||
["min", 60],
|
||||
["hr", 3600],
|
||||
["day", 86400],
|
||||
["wk", 604800],
|
||||
];
|
||||
let label = "min";
|
||||
let size = 60;
|
||||
for (const [l, s] of units) {
|
||||
if (secs >= s) [label, size] = [l, s];
|
||||
}
|
||||
const n = Math.floor(secs / size);
|
||||
return `${n} ${label}${n === 1 ? "" : "s"} ago`;
|
||||
}
|
||||
|
||||
/** Compact number: 2_400_000 -> "2.4M". Long digit strings do not scan. */
|
||||
export function compact(n: number | null | undefined): string {
|
||||
if (n == null || Number.isNaN(n)) return "—";
|
||||
return new Intl.NumberFormat(undefined, { notation: "compact", maximumFractionDigits: 1 }).format(n);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// What an EventSource error actually means.
|
||||
//
|
||||
// EventSource fires onerror both for a dropped connection it will retry and
|
||||
// for one it has given up on. Reporting "reconnecting" for both left the logs
|
||||
// page showing a permanent amber "reconnecting" pill against a stream that had
|
||||
// stopped for good, next to text claiming live logs were still arriving
|
||||
// (archie-core-c5bz).
|
||||
//
|
||||
// readyState is the difference: CONNECTING means a retry is scheduled, CLOSED
|
||||
// means the browser will not try again.
|
||||
|
||||
/** The state the UI reports for an event stream. */
|
||||
export type StreamState = "live" | "reconnecting" | "unavailable";
|
||||
|
||||
/**
|
||||
* streamStateFor maps an EventSource readyState to the state the UI reports:
|
||||
* "live", "reconnecting", or "unavailable".
|
||||
*/
|
||||
export function streamStateFor(readyState: number): StreamState {
|
||||
// Numeric literals rather than EventSource.* so this is testable without one.
|
||||
if (readyState === 0) return "reconnecting";
|
||||
if (readyState === 1) return "live";
|
||||
return "unavailable";
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
// Central lifecycle vocabulary for the dashboard. The backend is the source of
|
||||
// truth: /api/task-meta returns the statuses (label, pill severity, "needs you"
|
||||
// grouping) and operator actions (label, button variant, confirm prompt). This
|
||||
// module fetches that catalog and exposes the accessors the rest of the UI
|
||||
// reads, so no surface keeps a hand-synced copy of the vocabulary.
|
||||
//
|
||||
// The defaults below are a freeze-dried snapshot that render immediately and
|
||||
// keep working when archied is unreachable; loadTaskMeta() replaces them with
|
||||
// the live catalog as soon as it arrives. They must match the backend catalog
|
||||
// so drawing the page never flashes a stale label.
|
||||
//
|
||||
// loadTaskMeta() is called once at boot by main.ts. The catalog is held in
|
||||
// refs, so a late-arriving catalog re-renders whatever already read it; there
|
||||
// is no separate "re-render the mounted route" step the way the Preact shell
|
||||
// needed one.
|
||||
//
|
||||
// The dashboard draws a line here between two kinds of vocabulary. Anything
|
||||
// that is *presentation* -- a status's label, pill severity and "needs you"
|
||||
// grouping, or a control's label and confirm prompt -- is served, because the
|
||||
// server owns the words as well as the ids.
|
||||
import { computed, shallowRef } from "vue";
|
||||
|
||||
import { api } from "./api";
|
||||
|
||||
/** A lifecycle status as the server describes it. */
|
||||
export interface StatusMeta {
|
||||
id: string;
|
||||
label: string;
|
||||
kind: string;
|
||||
needs_you?: boolean;
|
||||
}
|
||||
|
||||
/** An operator control as the server describes it. */
|
||||
export interface ActionMeta {
|
||||
id: string;
|
||||
label: string;
|
||||
kind: string;
|
||||
confirm?: string;
|
||||
}
|
||||
|
||||
const DEFAULT_STATUSES: StatusMeta[] = [
|
||||
{ id: "queued", label: "Queued", kind: "idle" },
|
||||
{ id: "running", label: "Working", kind: "info" },
|
||||
{ id: "waiting_human", label: "Waiting for you", kind: "warn", needs_you: true },
|
||||
{ id: "pr_open", label: "In review", kind: "ok" },
|
||||
{ id: "merged", label: "Merged", kind: "ok" },
|
||||
{ id: "parked", label: "Parked", kind: "warn", needs_you: true },
|
||||
{ id: "dead", label: "Stopped (too many retries)", kind: "danger" },
|
||||
{ id: "rejected", label: "Rejected", kind: "danger" },
|
||||
{ id: "closed_wont_do", label: "Won't do", kind: "idle" },
|
||||
];
|
||||
|
||||
const DEFAULT_ACTIONS: ActionMeta[] = [
|
||||
{ id: "cancel", label: "Cancel", kind: "quiet", confirm: `Cancel "{title}"? This closes the forge issue.` },
|
||||
{ id: "stop", label: "Stop", kind: "primary", confirm: `Stop "{title}"? Recoverable work will remain parked.` },
|
||||
{ id: "approve", label: "Approve", kind: "primary" },
|
||||
{ id: "reject", label: "Reject", kind: "quiet", confirm: `Reject "{title}"? This closes the forge issue.` },
|
||||
{ id: "retry", label: "Retry", kind: "primary" },
|
||||
{ id: "abandon", label: "Abandon", kind: "quiet", confirm: `Abandon "{title}"? This closes the forge issue.` },
|
||||
{ id: "archive", label: "Archive", kind: "quiet", confirm: `Archive the local record for "{title}"?` },
|
||||
{ id: "open_pr", label: "Open PR", kind: "link" },
|
||||
{ id: "open_issue", label: "Open issue", kind: "link" },
|
||||
];
|
||||
|
||||
const statuses = shallowRef<StatusMeta[]>([...DEFAULT_STATUSES]);
|
||||
const actions = shallowRef<ActionMeta[]>([...DEFAULT_ACTIONS]);
|
||||
|
||||
const statusById = computed(() => new Map(statuses.value.map((s) => [s.id, s])));
|
||||
const actionById = computed(() => new Map(actions.value.map((a) => [a.id, a])));
|
||||
|
||||
// loadTaskMeta upgrades the dashboard from the server catalog. It never throws:
|
||||
// a failed fetch keeps the defaults so the UI still renders.
|
||||
export async function loadTaskMeta(): Promise<void> {
|
||||
try {
|
||||
const data = await api.taskMeta<{ statuses?: StatusMeta[]; actions?: ActionMeta[] } | null>();
|
||||
if (Array.isArray(data?.statuses)) statuses.value = data.statuses;
|
||||
if (Array.isArray(data?.actions)) actions.value = data.actions;
|
||||
} catch {
|
||||
// archied unreachable or not yet serving this route; keep the defaults.
|
||||
}
|
||||
}
|
||||
|
||||
/** statusLabel is the human-readable name for a lifecycle status. */
|
||||
export function statusLabel(id: string): string {
|
||||
return statusById.value.get(id)?.label || id || "Unknown";
|
||||
}
|
||||
|
||||
/** statusKind is the pill severity token (idle, info, ok, warn, danger). */
|
||||
export function statusKind(id: string): string {
|
||||
return statusById.value.get(id)?.kind || "idle";
|
||||
}
|
||||
|
||||
/** statusList returns every known lifecycle status in display order. */
|
||||
export function statusList(): StatusMeta[] {
|
||||
return statuses.value;
|
||||
}
|
||||
|
||||
/** statusIds returns every known lifecycle status id, in display order. */
|
||||
export function statusIds(): string[] {
|
||||
return statuses.value.map((s) => s.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* attentionStatusIds is the set of statuses that count toward the "Needs you"
|
||||
* filter (work that is waiting on a human).
|
||||
*/
|
||||
export function attentionStatusIds(): Set<string> {
|
||||
return new Set(statuses.value.filter((s) => s.needs_you).map((s) => s.id));
|
||||
}
|
||||
|
||||
/**
|
||||
* actionFor returns the presentation metadata for an operator control, or null
|
||||
* if the backend has never seen it.
|
||||
*/
|
||||
export function actionFor(id: string): ActionMeta | null {
|
||||
return actionById.value.get(id) || null;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* randomUUID keeps client-generated identifiers working on HTTP deployments.
|
||||
* crypto.randomUUID is restricted to secure contexts, while getRandomValues
|
||||
* remains available on the older browsers and plain-HTTP origins Archie
|
||||
* supports.
|
||||
*/
|
||||
export function randomUUID(cryptoAPI: Crypto | undefined = globalThis.crypto): string {
|
||||
if (typeof cryptoAPI?.randomUUID === "function") return cryptoAPI.randomUUID();
|
||||
|
||||
const bytes = new Uint8Array(16);
|
||||
if (typeof cryptoAPI?.getRandomValues === "function") {
|
||||
cryptoAPI.getRandomValues(bytes);
|
||||
} else {
|
||||
for (let index = 0; index < bytes.length; index += 1) {
|
||||
bytes[index] = Math.floor(Math.random() * 256);
|
||||
}
|
||||
}
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));
|
||||
return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
|
||||
}
|
||||
@@ -4,6 +4,9 @@ import { createApp } from "vue";
|
||||
|
||||
import App from "./App.vue";
|
||||
import router from "./router";
|
||||
// One stylesheet: the design tokens, and the element defaults that have no
|
||||
// component to live in (the canvas, the focus floor, the motion preference).
|
||||
// Everything else is Tailwind on the component that owns it.
|
||||
import "./style.css";
|
||||
|
||||
createApp(App).use(router).mount("#app");
|
||||
@@ -4,6 +4,14 @@
|
||||
@import "tw-animate-css";
|
||||
@import "shadcn-vue/tailwind.css";
|
||||
|
||||
/* ui/dist is committed, so nothing ignores it and Tailwind's automatic content
|
||||
detection scans it. That makes every build an input to the next one: class
|
||||
strings left in the committed bundle generate utilities for classes nothing
|
||||
references any more, so rebuilding an unchanged tree produced a different
|
||||
bundle and tools/uidist.sh's freshness check failed on the first build after
|
||||
every change. The bundle is generated, never a source. */
|
||||
@source not "../dist";
|
||||
|
||||
/* The theme is an attribute on <html>, not a class, so the inline script in
|
||||
index.html can set it before the first paint and a reload does not flash the
|
||||
wrong palette. */
|
||||
@@ -220,5 +228,42 @@
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
@apply font-sans;
|
||||
/* The luminous canvas the shell floats on. Large, off-axis and
|
||||
low-frequency, so it lights the workspace rather than competing with
|
||||
it, and fixed so the surface above reads as glass rather than a
|
||||
scrolling image. The padding is the margin the frame sits inside. */
|
||||
background:
|
||||
radial-gradient(70rem 40rem at 8% -10%, var(--wash-a), transparent 62%),
|
||||
radial-gradient(56rem 34rem at 92% 4%, var(--wash-b), transparent 58%),
|
||||
radial-gradient(48rem 30rem at 50% 108%, var(--wash-c), transparent 60%),
|
||||
var(--background);
|
||||
background-attachment: fixed;
|
||||
padding: 1rem;
|
||||
}
|
||||
/* The focus floor. A component may style its own focus state; this
|
||||
guarantees that nothing is ever focused and invisible for a keyboard
|
||||
user. `:focus-visible` rather than `:focus` so a mouse click does not
|
||||
draw a ring around what was clicked. */
|
||||
:focus-visible {
|
||||
outline: 2px solid var(--primary);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
/* The frame is a desktop affordance: below this width the workspace goes
|
||||
edge to edge, because a rounded card inset on a phone wastes the only
|
||||
axis that matters. */
|
||||
@media (max-width: 900px) {
|
||||
body {
|
||||
padding: 0;
|
||||
}
|
||||
}
|
||||
/* An accessibility invariant, not a nicety: nothing animates for someone
|
||||
who has asked it not to. */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
animation-duration: 0.01ms !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user