loopable / web /src /artifacts /ArtifactsPage.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
d598032 verified
Raw History Blame Contribute Delete
43.6 kB
import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { ReactNode } from "react";
import { ArrowLeft, FileText, SquaresFour } from "@phosphor-icons/react";
import { CREDENTIALS, QUERY_OPEN_EVENT, TOAST_EVENT } from "../apiContract";
import type { QueryOpenDetail } from "../apiContract";
import { sheetAddressHash } from "../sheet";
import { appPathHash } from "../customer-grid/dataPath";
import { databaseEntries, dataAddressHash } from "../shell/nav";
import type { NavEntry } from "../shell/nav";
import { QueryRail, queryGroups } from "../query/queryParts";
import { call, deleteArtifact, fetchArtifacts, fetchQueryViews, pauseArtifact, resumeArtifact, runArtifact } from "../query/queryApi";
import type { ArtifactPendingDelete, ArtifactTurnResult, SavedQuery } from "../query/queryApi";
import { ModuleHomeHead } from "../home/ModuleHomeHead";
import TruncatedName from "../home/TruncatedName";
import ItemTileMenu, { ItemPermissionError } from "../home/ItemTileMenu";
import { ConfirmDialog } from "../ui/ConfirmDialog";
import { GridIcon, HomeTilePage, HomeTileText, ListIcon } from "../home/HomePage";
import { SharedMark, useShareMarks } from "../home/DatabaseTile";
import type { ApplicationTile } from "../home/HomePage";
import HomeFind, { useHomeFind } from "../home/HomeFind";
import { matchTiles, sortTiles } from "../home/homeFind";
import { HOME_LAYOUT_KEY, NO_SHARE_MARKS, parseLayout, shareMarkKey } from "../home/homeModel";
import type { HomeLayout } from "../home/homeModel";
import WorklistTable, { worklistFigure } from "./WorklistTable";
import { ARTIFACT_UNAVAILABLE, artifactFileHref, fetchWorklist, safeWorklistLink, worklistText } from "./worklistApi";
import type { Artifact, WorklistPage } from "./worklistApi";
import "../styles/sdlc73/intelligence.css";
import "../styles/sdlc76/homes.css";
import "./artifacts.css";
const QueryPage = lazy(() => import("../query/QueryPage"));
type Selection = { item?: string; view?: string };
type WorklistState = { itemId: string; page: WorklistPage | null; loading: boolean; problem: string; refused: boolean };
type FrozenSnapshot = {
title: string; columns: Array<{ key: string; label: string }>; rows: unknown[][];
totals: { count: number; sum: Record<string, unknown> }; row_count: number; shown: number;
note: string | null; frozen_at: string;
};
type SnapshotState = { itemId: string; page: FrozenSnapshot | null; loading: boolean; problem: string };
const object = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
const count = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) >= 0;
function readApplications(body: unknown): ApplicationTile[] {
if (!object(body) || !Array.isArray(body.applications) || body.applications.some((row) =>
!object(row) || typeof row.id !== "string" || !row.id || typeof row.name !== "string"
|| typeof row.type !== "string")) throw new Error("Apps could not be loaded.");
return body.applications as ApplicationTile[];
}
/** An App row as `GET /applications` sends it, with the server-stamped door it was made through. */
export type OriginApplication = ApplicationTile & { origin?: unknown };
const AI_DOORS = new Set(["mcp", "loopy"]);
/** QI24: an App is AI-made when it has no template and its origin door is MCP or the Assistant; a missing origin reads as "app". */
export function isAiMadeApplication(application: OriginApplication): boolean {
if (application.templateKind != null) return false;
const origin = application.origin;
return object(origin) && typeof origin.door === "string" && AI_DOORS.has(origin.door);
}
export function aiMadeApplications<T extends OriginApplication>(applications: readonly T[]): T[] {
return applications.filter(isAiMadeApplication);
}
function readSnapshot(body: unknown, itemId: string): FrozenSnapshot {
if (!object(body) || !object(body.artifact) || body.artifact.id !== itemId || body.artifact.kind !== "snapshot"
|| !object(body.snapshot)) throw new Error("This snapshot could not be read.");
const page = body.snapshot;
if (typeof page.title !== "string" || !Array.isArray(page.columns) || !Array.isArray(page.rows)
|| !object(page.totals) || !count(page.totals.count) || !object(page.totals.sum)
|| !count(page.row_count) || !count(page.shown) || page.shown !== page.rows.length || page.shown > page.row_count
|| !(page.note === null || typeof page.note === "string") || typeof page.frozen_at !== "string"
|| !Number.isFinite(Date.parse(page.frozen_at))) throw new Error("This snapshot could not be read.");
const keys = new Set<string>();
for (const column of page.columns) {
if (!object(column) || typeof column.key !== "string" || !column.key || typeof column.label !== "string"
|| keys.has(column.key)) throw new Error("This snapshot could not be read.");
keys.add(column.key);
}
if (page.rows.some((row) => !Array.isArray(row) || row.length !== keys.size)) throw new Error("This snapshot could not be read.");
return page as FrozenSnapshot;
}
function SnapshotTable({ page }: { page: FrozenSnapshot }) {
return <>
<p className="ar-worklist-count" role="status">{page.shown.toLocaleString()} of {page.row_count.toLocaleString()} rows</p>
{page.note ? <p className="ar-snapshot-note">{worklistText(page.note)}</p> : null}
{page.columns.length ? <div className="ar-worklist-scroll" tabIndex={0} role="region" aria-label="Snapshot table">
<table className="ar-worklist-table" aria-label={worklistText(page.title)}>
<thead><tr>{page.columns.map((column, index) => <th key={column.key} scope="col"
className={page.rows.some((row) => typeof row[index] === "number") || Object.hasOwn(page.totals.sum, column.key) ? "ar-numeric" : undefined}>
{worklistText(column.label)}</th>)}</tr></thead>
<tbody>{page.rows.map((row, rowIndex) => <tr key={rowIndex}>{page.columns.map((column, index) => <td key={column.key}
className={typeof row[index] === "number" ? "ar-numeric" : undefined}>{worklistFigure(row[index])}</td>)}</tr>)}</tbody>
</table>
</div> : null}
{!page.rows.length ? <p className="ar-worklist-empty" role="status">Nothing found.</p> : null}
<section className="ar-snapshot-totals" aria-label="Frozen totals"><h3>Totals</h3>
<dl><div><dt>Rows</dt><dd>{worklistFigure(page.totals.count)}</dd></div>
{Object.entries(page.totals.sum).map(([key, value]) => <div key={key}>
<dt>{worklistText(page.columns.find((column) => column.key === key)?.label ?? key)}</dt>
<dd>{worklistFigure(value)}</dd></div>)}
</dl>
</section>
</>;
}
/** Mount and same-page navigation use exactly the same address parser. */
export function artifactAddress(hash: string): Selection {
const [route, query = ""] = hash.split("?", 2);
if (route !== "#/artifacts" && route !== "#/query") return {};
const params = new URLSearchParams(query);
return { item: params.get("item") || undefined, view: params.get("view") || undefined };
}
const kindLabel = (kind: string) => kind === "pdf" ? "PDF" : kind === "xlsx" ? "Excel"
: kind.charAt(0).toUpperCase() + kind.slice(1);
// C7 file fields are not on the shared Artifact type yet: read them from the raw record, either casing.
type FileFields = { file_id?: unknown; fileId?: unknown; link?: unknown; frozen_at?: unknown };
const FILE_KINDS = new Set(["xlsx", "image"]);
/** A made file (C7 `file_id`, else `ref` as PDF uses it) served by the files route. */
function fileHrefOf(item: Artifact): string | undefined {
const id = item.file_id ?? (FILE_KINDS.has(item.kind) ? item.ref : undefined);
return typeof id === "string" && id.trim() ? artifactFileHref(id) : undefined;
}
/** An artifact link opens only as HTTPS or on this origin, never as a script URL. */
function linkOf(item: Artifact): string | undefined {
const value = item.link;
if (typeof value !== "string" || !value.trim()) return undefined;
const safe = safeWorklistLink(value);
if (safe) return safe;
try {
const url = new URL(value, window.location.href);
return url.origin === window.location.origin && /^https?:$/.test(url.protocol) ? url.href : undefined;
} catch { return undefined; }
}
const plain = worklistText;
const doorLabel = (door: string) => door === "whatsapp" ? "From WhatsApp" : door === "wake" ? "Wake-up" : "From the app";
function relativeTime(at: string) {
const age = Math.max(0, (Date.now() - Date.parse(at)) / 1000);
if (age < 60) return "Just now";
if (age < 3600) return `${Math.floor(age / 60)} min ago`;
if (age < 86400) return `${Math.floor(age / 3600)} hr ago`;
return `${Math.floor(age / 86400)} days ago`;
}
/** A tool argument as a reader says it: "None" for nothing, a filter as "field op value". */
function argText(value: unknown): string {
if (typeof value === "string") return value;
if (typeof value === "number" || typeof value === "boolean") return String(value);
if (Array.isArray(value)) return value.length ? value.map(argText).filter(Boolean).join(", ") : "None";
if (value && typeof value === "object") {
const row = value as Record<string, unknown>;
if ("colId" in row) return [row.colId, row.op, row.value].filter((part) => part != null && part !== "").map(String).join(" ");
const pairs = Object.entries(row).filter(([, item]) => item != null);
return pairs.length ? pairs.map(([key, item]) => `${key.replace(/_/g, " ")} ${argText(item)}`).join(", ") : "None";
}
return "";
}
const toolLabel = (name: string) => kindLabel(name.replace(/_/g, " "));
function SkeletonRows() {
return <div className="intelligence-loading home-tiles home-paged-grid is-grid" aria-label="Loading artifacts" role="status">
{Array.from({ length: 6 }, (_, row) => <div className="home-tile intelligence-skeleton" key={row} aria-hidden="true">
<span /><span /><span />
</div>)}
</div>;
}
/** The server's item actions are the capability, including any future rename route. */
function ArtifactTileActions({ item, onChanged, onRenamed, onDeleted, children }: {
item: Artifact;
onChanged(): void;
onRenamed(saved: Artifact): void;
onDeleted(id: string): void;
children: ReactNode;
}) {
const [receipt, setReceipt] = useState<ArtifactPendingDelete>();
const [failure, setFailure] = useState("");
const [settling, setSettling] = useState(false);
const [revoked, setRevoked] = useState(false);
const writing = useRef(false);
const refuse = (status: number, message: string): never => {
if ([401, 403, 404].includes(status)) {
setRevoked(true);
onChanged();
throw new ItemPermissionError(message);
}
throw new Error(message);
};
const settle = async (decision: "delete" | "keep", dismiss: () => void) => {
if (!receipt || writing.current) return;
writing.current = true;
setSettling(true); setFailure("");
try {
const result = await call<ArtifactTurnResult | { kept: boolean }>("/assistant/confirm", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: receipt.id, decision }),
}, (raw) => {
if (!object(raw) || (typeof raw.kept !== "boolean"
&& (typeof raw.reply !== "string" || !(raw.refused === null || typeof raw.refused === "string")))) {
throw new Error("The decision could not be confirmed. Try again.");
}
return raw as ArtifactTurnResult | { kept: boolean };
});
if (!result.ok) return refuse(result.status, result.message);
const response = result.value;
if (!("kept" in response) && response.refused) throw new ItemPermissionError(plain(response.refused));
if ("kept" in response) {
if (!response.kept) window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: {
text: "That delete request no longer exists.", tone: "info",
} }));
} else if (decision === "delete") onDeleted(item.id);
setReceipt(undefined);
dismiss();
onChanged();
} catch (error) {
const text = error instanceof Error ? error.message : "The decision was not saved. Try again.";
if (error instanceof ItemPermissionError) {
dismiss(); setReceipt(undefined);
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } }));
} else setFailure(text);
} finally { writing.current = false; setSettling(false); }
};
return <ItemTileMenu id={item.id} kind="artifact" name={plain(item.title)} busy={settling}
canRename={!revoked && (item.actions as readonly string[]).includes("rename")}
canDelete={!revoked && item.actions.includes("delete")}
onRename={async (title) => {
const result = await call(`/artifacts/${encodeURIComponent(item.id)}`, {
method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title }),
}, (raw) => {
if (!object(raw) || !object(raw.artifact) || raw.artifact.id !== item.id || raw.artifact.title !== title
|| !Array.isArray(raw.artifact.actions) || raw.artifact.actions.some((action) => typeof action !== "string")) {
throw new Error("The rename could not be confirmed. Reload to check.");
}
return { ...item, ...raw.artifact } as Artifact;
});
if (!result.ok) return refuse(result.status, result.message);
onRenamed(result.value);
}}
prepareDelete={async () => {
const result = await deleteArtifact(item.id);
if (!result.ok) return refuse(result.status, result.message);
const pending = result.value.pendingDelete;
if (!pending || !pending.id || !pending.summary) throw new Error("The delete request could not be confirmed. Try again.");
setReceipt(pending); setFailure("");
return null;
}}
deleteConfirmation={(dismiss) => receipt ? <ConfirmDialog open title="Delete artifact" busy={settling}
body={<><p>{plain(receipt.summary)}</p>{failure ? <p className="home-item-delete-error" role="alert">{failure}</p> : null}</>}
confirmLabel={settling ? "Saving…" : failure ? "Retry delete" : "Delete"} tone="destructive"
onCancel={() => { void settle("keep", dismiss); }} onConfirm={() => { void settle("delete", dismiss); }} /> : null}>
{children}
</ItemTileMenu>;
}
export default function ArtifactsPage({ granted }: { granted: NavEntry[] }) {
const [items, setItems] = useState<Artifact[]>([]);
const [applications, setApplications] = useState<ApplicationTile[]>([]);
const [applicationsProblem, setApplicationsProblem] = useState("");
const [applicationsLoaded, setApplicationsLoaded] = useState(false);
const applicationRequest = useRef<AbortController | null>(null);
const [views, setViews] = useState<SavedQuery[]>([]);
const [selection, setSelection] = useState<Selection>(() => artifactAddress(window.location.hash));
const find = useHomeFind("artifacts", true);
const [layout, setLayoutState] = useState<HomeLayout>(() => {
try { return parseLayout(localStorage.getItem(HOME_LAYOUT_KEY)); } catch { return "grid"; }
});
const [loaded, setLoaded] = useState(false);
const [loading, setLoading] = useState(false);
const [nextCursor, setNextCursor] = useState<string | null>(null);
const [problem, setProblem] = useState("");
// S79-T61 / J28: the skeleton stays, briefly, until the App tiles' share marks settle.
const share = useShareMarks((loaded && !nextCursor) || !!problem);
const shareMarks = share?.marks ?? NO_SHARE_MARKS;
const shareHold = share?.hold === true;
const [busy, setBusy] = useState(false);
const [replies, setReplies] = useState<Record<string, string>>( {});
const [made, setMade] = useState<Record<string, string>>( {});
const [pendingByItem, setPendingByItem] = useState<Record<string, ArtifactPendingDelete>>( {});
const [refreshToken, setRefreshToken] = useState(0);
const [worklistToken, setWorklistToken] = useState(0);
const [worklistState, setWorklistState] = useState<WorklistState>({ itemId: "", page: null, loading: false, problem: "", refused: false });
const worklistRequest = useRef<AbortController | null>(null);
const [snapshotState, setSnapshotState] = useState<SnapshotState>({ itemId: "", page: null, loading: false, problem: "" });
const [snapshotToken, setSnapshotToken] = useState(0);
const inFlight = useRef(false);
const acting = useRef(false);
const sentinel = useRef<HTMLDivElement>(null);
const load = useCallback(async (cursor?: string) => {
if (inFlight.current) return;
inFlight.current = true; setLoading(true);
try {
const result = await fetchArtifacts(cursor);
if (!result.ok) { setProblem(result.message); return; }
setItems((current) => cursor
? [...current, ...result.value.items.filter((row) => !current.some((old) => old.id === row.id))]
: result.value.items);
setNextCursor(result.value.nextCursor);
setLoaded(true); setProblem("");
} finally { inFlight.current = false; setLoading(false); }
}, []);
const loadQueries = useCallback(async () => {
const result = await fetchQueryViews();
if (result.ok) setViews(result.value);
else setProblem(result.message);
}, []);
const loadApplications = useCallback(async () => {
applicationRequest.current?.abort();
const controller = new AbortController();
applicationRequest.current = controller;
setApplications([]); setApplicationsProblem(""); setApplicationsLoaded(false);
try {
const result = await call("/applications", { method: "GET", signal: controller.signal }, readApplications);
if (controller.signal.aborted || applicationRequest.current !== controller) return;
setApplications(result.ok ? result.value : []);
setApplicationsProblem(result.ok ? "" : "Apps could not be loaded.");
setApplicationsLoaded(result.ok);
} catch {
if (!controller.signal.aborted && applicationRequest.current === controller) {
setApplicationsProblem("Apps could not be loaded.");
}
} finally {
if (applicationRequest.current === controller) applicationRequest.current = null;
}
}, []);
const refresh = useCallback(() => {
void load(); void loadQueries(); void loadApplications(); setRefreshToken((value) => value + 1);
}, [load, loadQueries, loadApplications]);
useEffect(() => { refresh(); }, [refresh]);
useEffect(() => {
const changed = () => { void loadApplications(); };
const visible = () => { if (document.visibilityState === "visible") changed(); };
window.addEventListener("aios:applications-changed", changed);
window.addEventListener("focus", changed);
document.addEventListener("visibilitychange", visible);
return () => {
applicationRequest.current?.abort();
window.removeEventListener("aios:applications-changed", changed);
window.removeEventListener("focus", changed);
document.removeEventListener("visibilitychange", visible);
};
}, [loadApplications]);
useEffect(() => {
const consume = () => setSelection(artifactAddress(window.location.hash));
const onOpen = (event: Event) => {
const qid = (event as CustomEvent<QueryOpenDetail>).detail?.qid;
if (!qid) return;
setSelection({ view: qid });
window.location.hash = `#/artifacts?view=${encodeURIComponent(qid)}`;
refresh();
};
window.addEventListener("hashchange", consume);
window.addEventListener(QUERY_OPEN_EVENT, onOpen);
return () => {
window.removeEventListener("hashchange", consume);
window.removeEventListener(QUERY_OPEN_EVENT, onOpen);
};
}, [refresh]);
const selected = useMemo(() => items.find((item) => selection.item ? item.id === selection.item
: selection.view ? item.kind === "query" && item.ref === selection.view : false), [items, selection]);
const showingDetail = !!(selection.item || selection.view);
const homeItems = useMemo(() => sortTiles(matchTiles(items.map((item) => ({ ...item,
key: item.id, name: plain(item.title), updated_at: item.createdAt })), find.query), find.sort, find.opened),
[items, find.query, find.sort, find.opened]);
// QI24: Artifacts lists only Apps an AI made; a template App stays under App only.
const aiApplications = useMemo(() => aiMadeApplications(applications), [applications]);
const homeApplications = useMemo(() => sortTiles(matchTiles(aiApplications.map((application) => ({ ...application,
name: plain(application.name) })), find.query), find.sort, find.opened),
[aiApplications, find.query, find.sort, find.opened]);
const noAiApplications = applicationsLoaded && !applicationsProblem && !aiApplications.length;
const showApplications = (!!homeApplications.length || noAiApplications) && !shareHold;
const reportItemId = selected?.kind === "report" ? selected.id : undefined;
const reportRef = selected?.kind === "report" ? selected.ref : undefined;
const worklist = worklistState.itemId === reportItemId ? worklistState : undefined;
const snapshotItemId = (selected?.kind as string) === "snapshot" ? selected?.id : undefined;
const snapshot = snapshotState.itemId === snapshotItemId ? snapshotState : undefined;
useEffect(() => {
if (!snapshotItemId) { setSnapshotState({ itemId: "", page: null, loading: false, problem: "" }); return; }
const controller = new AbortController();
let live = true;
setSnapshotState({ itemId: snapshotItemId, page: null, loading: true, problem: "" });
void (async () => {
try {
const result = await call(`/artifacts/${encodeURIComponent(snapshotItemId)}/snapshot`,
{ method: "GET", credentials: CREDENTIALS, signal: controller.signal }, (body) => readSnapshot(body, snapshotItemId));
if (!live || controller.signal.aborted) return;
setSnapshotState({ itemId: snapshotItemId, page: result.ok ? result.value : null, loading: false,
problem: result.ok ? "" : [403, 404, 410].includes(result.status) ? ARTIFACT_UNAVAILABLE : result.message });
} catch {
if (live && !controller.signal.aborted) setSnapshotState({ itemId: snapshotItemId, page: null, loading: false,
problem: "This snapshot could not be read." });
}
})();
return () => { live = false; controller.abort(); };
}, [snapshotItemId, refreshToken, snapshotToken]);
useEffect(() => {
worklistRequest.current?.abort();
worklistRequest.current = null;
if (!reportItemId) { setWorklistState({ itemId: "", page: null, loading: false, problem: "", refused: false }); return; }
if (!reportRef) { setWorklistState({ itemId: reportItemId, page: null, loading: false, problem: ARTIFACT_UNAVAILABLE, refused: true }); return; }
const controller = new AbortController();
worklistRequest.current = controller;
setWorklistState({ itemId: reportItemId, page: null, loading: true, problem: "", refused: false });
let live = true;
void fetchWorklist(reportRef, 0, controller.signal).then((result) => {
if (!live || controller.signal.aborted) return;
setWorklistState({ itemId: reportItemId, page: result.ok ? result.value : null, loading: false,
problem: result.ok ? "" : result.message, refused: !result.ok && result.message === ARTIFACT_UNAVAILABLE });
if (worklistRequest.current === controller) worklistRequest.current = null;
});
return () => {
live = false;
worklistRequest.current?.abort();
worklistRequest.current = null;
};
}, [reportItemId, reportRef, refreshToken, worklistToken]);
async function showMoreWorklist() {
if (!reportItemId || !reportRef || !worklist?.page || worklist.loading || worklistRequest.current
|| worklist.page.rows.length >= worklist.page.total) return;
const page = worklist.page;
const controller = new AbortController();
worklistRequest.current = controller;
setWorklistState((current) => ({ ...current, loading: true, problem: "" }));
const result = await fetchWorklist(reportRef, page.rows.length, controller.signal);
if (controller.signal.aborted || worklistRequest.current !== controller) return;
worklistRequest.current = null;
setWorklistState((current) => {
if (current.itemId !== reportItemId) return current;
if (!result.ok) {
const refused = result.message === ARTIFACT_UNAVAILABLE;
return { ...current, page: refused ? null : page, loading: false, problem: result.message, refused };
}
const next = result.value;
if (next.builtAt !== page.builtAt || next.total !== page.total || JSON.stringify(next.columns) !== JSON.stringify(page.columns)) {
return { ...current, loading: false, problem: "This worklist changed. Open it again." };
}
return { ...current, page: { ...next, rows: [...page.rows, ...next.rows] }, loading: false, problem: "" };
});
}
// A deep link may name an older page. Fetch until the item is found or the index ends.
useEffect(() => {
if (loaded && !loading && !problem && !selected && (selection.item || selection.view) && nextCursor) void load(nextCursor);
}, [loaded, loading, problem, selected, selection, nextCursor, load]);
// Finish the permission-filtered index before searching, sorting or paging its tiles.
useEffect(() => {
if (!showingDetail && loaded && !loading && !problem && nextCursor) void load(nextCursor);
}, [showingDetail, loaded, loading, problem, nextCursor, load]);
useEffect(() => {
const target = sentinel.current;
if (!target || !nextCursor || loading || problem || typeof IntersectionObserver === "undefined") return;
const observer = new IntersectionObserver((entries) => {
if (entries.some((entry) => entry.isIntersecting)) void load(nextCursor);
});
observer.observe(target);
return () => observer.disconnect();
}, [nextCursor, loading, problem, load]);
const choose = (item: Artifact) => {
find.recordOpened(item.id);
setSelection({ item: item.id });
window.location.hash = `#/artifacts?item=${encodeURIComponent(item.id)}`;
};
const backHome = () => {
setSelection({});
window.location.hash = "#/artifacts";
};
const setLayout = (next: HomeLayout) => {
setLayoutState(next);
try { localStorage.setItem(HOME_LAYOUT_KEY, next); } catch { /* Keep the choice in memory. */ }
};
const pending = selected ? pendingByItem[selected.id] : undefined;
async function act(item: Artifact, action: "run" | "pause" | "resume" | "delete") {
if (acting.current) return;
acting.current = true; setBusy(true); setProblem("");
try {
if (action === "delete") {
const result = await deleteArtifact(item.id);
if (!result.ok) { setProblem(result.message); return; }
setPendingByItem((current) => ({ ...current, [item.id]: result.value.pendingDelete }));
} else {
const result = await (action === "run" ? runArtifact(item.id) : action === "pause" ? pauseArtifact(item.id) : resumeArtifact(item.id));
if (!result.ok) { setProblem(result.message); return; }
const turn = result.value;
setReplies((current) => ({ ...current, [item.id]: plain(turn.refused || turn.reply) }));
if (turn.pendingDelete) setPendingByItem((current) => ({ ...current, [item.id]: turn.pendingDelete! }));
if (turn.artifacts.length) {
const page = await fetchArtifacts();
if (page.ok) {
const created = page.value.items.filter((row) => turn.artifacts.includes(row.id));
setMade((current) => ({ ...current, [item.id]: `Made ${created.map((row) => plain(row.title)).join(", ") || "an artifact"}.` }));
if (action === "pause" || action === "resume") {
const changed = page.value.items.find((row) => row.kind === item.kind && row.ref === item.ref);
if (changed) choose(changed);
}
}
}
refresh();
}
} finally { acting.current = false; setBusy(false); }
}
async function decide(item: Artifact, request: ArtifactPendingDelete, decision: "delete" | "keep") {
if (acting.current) return;
acting.current = true; setBusy(true); setProblem("");
try {
const result = await call<ArtifactTurnResult | { kept: boolean }>("/assistant/confirm", {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id: request.id, decision }),
}, (raw) => raw as ArtifactTurnResult | { kept: boolean });
if (!result.ok) { setProblem(result.message); return; }
const response = result.value;
const sentence = "kept" in response
? response.kept ? "Kept. Nothing was removed." : "That delete request no longer exists."
: response.refused || response.reply;
setReplies((current) => ({ ...current, [item.id]: plain(sentence) }));
setPendingByItem((current) => { const next = { ...current }; delete next[item.id]; return next; });
refresh();
} finally { acting.current = false; setBusy(false); }
}
const queryChanged = (view: SavedQuery) => {
setViews((current) => [view, ...current.filter((row) => row.id !== view.id)]);
refresh();
};
const database = selected?.toolCall.args.database;
const openHref = selected?.kind === "sheet" && selected.ref ? sheetAddressHash({ wb: selected.ref })
: selected?.kind === "view" && selected.ref && typeof database === "string"
? dataAddressHash({ database, view: selected.ref }) : undefined;
const selectedKind = selected?.kind ?? "";
const fileHref = selected && selectedKind === "xlsx" ? fileHrefOf(selected) ?? linkOf(selected)
: selected && selectedKind === "image" ? fileHrefOf(selected) : undefined;
const snapshotHref = selected && selectedKind === "snapshot" ? linkOf(selected) : undefined;
const fileMissing = FILE_KINDS.has(selectedKind) && !fileHref;
const frozenValue = snapshot?.page?.frozen_at ?? (selected as FileFields | undefined)?.frozen_at;
const frozenAt = typeof frozenValue === "string" && Number.isFinite(Date.parse(frozenValue)) ? frozenValue : undefined;
const queryId = selected?.kind === "query" ? selected.ref || undefined : selection.view;
const unavailableKey = selected
? ((selected.kind === "pdf" && !selected.ref) || fileMissing || worklist?.refused ? selected.id : "")
: loaded && !loading && !problem && !nextCursor && !queryId
? selection.item || selection.view || "" : "";
useEffect(() => {
if (!unavailableKey) return;
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text: ARTIFACT_UNAVAILABLE, tone: "error" } }));
}, [unavailableKey]);
const isSavedQuery = (item: Artifact) => item.kind === "query" && views.some((view) => view.id === item.ref);
const resolveHref = safeWorklistLink(worklist?.page?.resolve.href);
const queryItems = items.filter(isSavedQuery);
const rowItems = items.filter((item) => !isSavedQuery(item));
const queryViews = queryItems.map((item) => views.find((view) => view.id === item.ref)!).filter(Boolean);
const artifactDetails = selected ? <>
{snapshotHref ? <p className="ar-resolve"><a href={snapshotHref}>Artifact link</a></p> : null}
{worklist?.page ? <p className="ar-meta ar-built-at">Built <time dateTime={worklist.page.builtAt}>{new Date(worklist.page.builtAt).toLocaleString()}</time></p> : null}
<p className="ar-meta">{kindLabel(selected.kind)} · {doorLabel(selected.door)} · <time dateTime={selected.createdAt}>{new Date(selected.createdAt).toLocaleString()}</time></p>
<section className="ar-made-by"><h3>Made by</h3><p>{plain(toolLabel(selected.toolCall.name))}</p>
<dl>{Object.entries({ ...selected.toolCall.args, ...(selected.kind === "query"
? { filters: views.find((view) => view.id === selected.ref)?.view.filters,
"source filters": views.find((view) => view.id === selected.ref)?.source.filters } : {}) }).map(([key, value]) =>
value == null ? null : <div key={key}><dt>{plain(key.replace(/_/g, " "))}</dt><dd>{plain(argText(value))}</dd></div>)}
</dl>
</section>
</> : null;
if (!showingDetail) return <div className="shell-home ar-home intelligence-home" role="region" aria-label="Artifacts" data-testid="artifacts-home">
<ModuleHomeHead title="Artifacts" module="artifacts" />
<div className="home-recents-bar">
<div className="home-layout-toggle home-find-toolbar" role="group" aria-label="Layout">
<HomeFind moduleName="Artifacts" query={find.query} sort={find.sort} onQueryChange={find.setQuery} onSortChange={find.setSort} />
<div className="home-find-layout">
<button type="button" className={"home-layout-btn" + (layout === "list" ? " is-on" : "")}
aria-pressed={layout === "list"} aria-label="List" title="List" onClick={() => setLayout("list")}><ListIcon /></button>
<button type="button" className={"home-layout-btn" + (layout === "grid" ? " is-on" : "")}
aria-pressed={layout === "grid"} aria-label="Grid" title="Grid" onClick={() => setLayout("grid")}><GridIcon /></button>
</div>
</div>
</div>
{applicationsProblem ? <div className="intelligence-feedback" role="alert"><span>{applicationsProblem}</span>
<button type="button" className="intelligence-button" onClick={() => void loadApplications()}>Retry</button></div> : null}
{showApplications ? <section className="home-section ar-apps" aria-label="Apps" data-testid="artifacts-apps">
<h2 className="home-section-title">Apps</h2>
{noAiApplications ? <p className="home-empty" role="status" data-testid="artifacts-apps-empty">No Apps made by AI yet.</p> :
<HomeTilePage items={homeApplications} layout={layout} scopeKey={JSON.stringify([find.query, find.sort])}>
{(pageItems) => pageItems.map((application) => {
const database = application.openTarget?.database ?? application.compatibleDatabases?.[0] ?? "";
const href = application.deepLink ? `#${application.deepLink}` : database
? appPathHash({ database, application: application.id }) : "#/app";
return <a key={application.id} className="home-tile ar-app-tile" href={href}
onClick={() => find.recordOpened(application.id)}>
<span className="home-tile-chip shell-db-chip home-app-glyph" aria-hidden="true"><SquaresFour size={16} /></span>
<HomeTileText tile={application} fallback={application.templateLabel ?? ""} />
<SharedMark mark={shareMarks.get(shareMarkKey("app", application.id))} fade={share?.fade === true} pending={share?.pending === true} />
</a>;
})}
</HomeTilePage>}
</section> : null}
{problem ? <div className="intelligence-feedback" role="alert"><span>{plain(problem)}</span>
<button type="button" className="intelligence-button" onClick={refresh}>Retry</button></div> : null}
{!problem && (!loaded || nextCursor || shareHold) ? <SkeletonRows /> : null}
{loaded && !nextCursor && !shareHold ? homeItems.length ? <section className="home-section" aria-label="Artifacts" aria-busy={loading}>
{showApplications ? <h2 className="home-section-title">Artifacts</h2> : null}
<HomeTilePage items={homeItems} layout={layout} scopeKey={JSON.stringify([find.query, find.sort])}>
{(pageItems) => pageItems.map((item) => <ArtifactTileActions key={item.id} item={item} onChanged={refresh}
onRenamed={(saved) => setItems((current) => current.map((row) => row.id === saved.id ? saved : row))}
onDeleted={(id) => setItems((current) => current.filter((row) => row.id !== id))}>
<button type="button" className="home-tile" onClick={() => choose(item)}>
<span className="home-tile-chip home-app-glyph" aria-hidden="true"><FileText size={16} /></span>
<span className="home-tile-text"><TruncatedName>{plain(item.title)}</TruncatedName>
<span className="home-tile-ago">{kindLabel(item.kind)} · {relativeTime(item.createdAt)}</span></span>
</button>
</ArtifactTileActions>)}
</HomeTilePage>
</section> : !problem && !loading ? <p className="home-empty" role="status">
{find.query.trim() ? "No artifacts match that." : "No artifacts yet."}</p> : null : null}
</div>;
return <div className="ar-page">
<div className="ar-back-bar"><button type="button" className="ar-button" onClick={backHome}>
<ArrowLeft size={16} aria-hidden="true" />Back to Artifacts
</button></div>
<div className="ar-detail-layout">
<aside className="ar-list" aria-label="Artifacts">
<ModuleHomeHead title="Artifacts" module="artifacts" className="ar-head" />
<div className="ar-list-scroll">
{!loaded ? <SkeletonRows /> : !items.length ? null : <>
{rowItems.map((item) => <div className="ar-list-item" key={item.id}>
<button className={"ar-row" + (selected?.id === item.id ? " ar-selected" : "")}
type="button" aria-current={selected?.id === item.id ? "true" : undefined} onClick={() => choose(item)}>
<span className="ar-title">{plain(item.title)}</span><span className="ar-meta">{kindLabel(item.kind)}</span>
</button>
<div className="ar-row-meta">
{item.door !== "app" ? <span>{doorLabel(item.door)}</span> : null}
<time dateTime={item.createdAt}>{relativeTime(item.createdAt)}</time>
</div>
</div>)}
{/* Every saved Query answer sits in ONE QueryRail section, grouped by its database. */}
{queryViews.length ? <div className="ar-query-row"><QueryRail groups={queryGroups(queryViews, databaseEntries(granted))}
activeId={queryId || ""} onSelect={(qid) => {
const item = queryItems.find((row) => row.ref === qid);
if (item) choose(item);
else { setSelection({ view: qid }); window.location.hash = `#/artifacts?view=${encodeURIComponent(qid)}`; refresh(); }
}} onDelete={(qid) => {
const item = queryItems.find((row) => row.ref === qid);
if (item) void act(item, "delete");
}} onChanged={queryChanged} /></div> : null}
</>}
<div ref={sentinel} className="ar-page-boundary">{loaded && loading ? <SkeletonRows /> : null}</div>
{nextCursor ? <button type="button" className="ar-button" disabled={loading} onClick={() => void load(nextCursor)}>Load more</button> : null}
</div>
</aside>
<main className="ar-detail">
<div className="ar-feedback" role="status">{problem ? <><span>{plain(problem)}</span>{" "}
<button type="button" className="ar-retry" onClick={refresh}>Try again</button></> : null}</div>
{selected ? <>
<header className="ar-detail-head"><h2>{plain(worklist?.page?.title || selected.title)}</h2>
{frozenAt ? <p className="ar-meta ar-built-at">Frozen <time dateTime={frozenAt}>{new Date(frozenAt).toLocaleString()}</time></p> : null}
{resolveHref && worklist?.page ? <p className="ar-resolve"><a href={resolveHref} target="_blank" rel="noopener noreferrer">Open {plain(worklist.page.resolve.label)}</a></p> : null}
</header>
<div className="ar-actions">
{selected.kind === "pdf" && selected.ref ? <a className="ar-button ar-open-pdf" href={artifactFileHref(selected.ref)}
target="_blank" rel="noopener noreferrer">Open PDF</a> : null}
{selectedKind === "xlsx" && fileHref ? <a className="ar-button ar-open-file" href={fileHref}
download>Download Excel</a> : null}
{selectedKind === "image" && fileHref ? <a className="ar-button ar-open-file" href={fileHref}
target="_blank" rel="noopener noreferrer">Open image</a> : null}
{selected.kind === "report" ? <button type="button" className="ar-button ar-open-worklist" disabled={worklist?.loading}
onClick={() => setWorklistToken((value) => value + 1)}>Open</button> : null}
{selected.actions.includes("open") && openHref ? <a className="ar-button" href={openHref}>Open</a> : null}
{selected.actions.includes("open") && selected.kind === "query" ? <button type="button" className="ar-button" onClick={() => setSelection({ view: selected.ref || undefined })}>Open</button> : null}
{selected.actions.includes("run") ? <button type="button" className="ar-button" disabled={busy} onClick={() => void act(selected, "run")}>Run again</button> : null}
{selected.actions.includes("pause") ? <button type="button" className="ar-button" disabled={busy} onClick={() => void act(selected, "pause")}>Pause</button> : null}
{selected.actions.includes("resume") ? <button type="button" className="ar-button" disabled={busy} onClick={() => void act(selected, "resume")}>Resume</button> : null}
{selected.actions.includes("delete") ? <button type="button" className="ar-button ar-danger" disabled={busy || !!pending} onClick={() => void act(selected, "delete")}>Delete</button> : null}
</div>
{pending ? <section className="ar-confirm" aria-label="Confirm deletion"><p>{plain(pending.summary)}</p>
<div className="ar-confirm-actions">
<button type="button" className="ar-button ar-confirm-delete" disabled={busy} onClick={() => void decide(selected, pending, "delete")}>Delete</button>
<button type="button" className="ar-button" disabled={busy} onClick={() => void decide(selected, pending, "keep")}>Keep</button>
</div></section> : null}
{replies[selected.id] ? <p className="ar-result" role="status">{replies[selected.id]}</p> : null}
{made[selected.id] ? <p className="ar-result">{made[selected.id]}</p> : null}
{selectedKind === "image" && fileHref ? <figure className="ar-image">
<img src={fileHref} alt={plain(selected.title)} /></figure> : null}
{selectedKind === "snapshot" ? <section className="ar-worklist ar-snapshot" aria-label="Frozen snapshot" aria-busy={snapshot?.loading ?? true}>
{snapshot?.page ? <SnapshotTable page={snapshot.page} /> : null}
{snapshot?.loading ?? true ? <div className="ar-worklist-loading" role="status" aria-label="Loading snapshot"><span /><span /></div> : null}
{snapshot?.problem ? <p className="ar-worklist-problem" role="status"><span>{plain(snapshot.problem)}</span>{" "}
<button type="button" className="ar-retry" onClick={() => setSnapshotToken((value) => value + 1)}>Try again</button></p> : null}
</section> : null}
{selected.kind !== "report" || worklist?.refused ? <details className="ar-details ar-artifact-details" key={selected.id}>
<summary>Details</summary><div className="ar-details-content">{artifactDetails}</div>
</details> : null}
{selected.kind === "report" && !worklist?.refused ? <WorklistTable key={selected.id} page={worklist?.page ?? null} details={artifactDetails}
loading={worklist?.loading ?? true} problem={worklist?.problem ?? ""} onShowMore={() => void showMoreWorklist()}
onRetry={() => setWorklistToken((value) => value + 1)} /> : null}
</> : null}
{queryId ? <div className="ar-query"><Suspense fallback={<SkeletonRows />}>
<QueryPage granted={granted} hostedRail selectedId={queryId} refreshToken={refreshToken} />
</Suspense></div> : null}
</main>
</div>
</div>;
}