feat(ui/chat): render Markdown with remark and rehype; remove the React reference

Chat replies, approvals, plans and agent transcripts now parse GitHub
flavoured Markdown with unified (remark-parse, remark-gfm, remark-rehype)
and render the HTML tree as Vue nodes. Raw HTML is dropped, links and
images keep only safe URLs, and #N task references stay linked.

The Astryx React prototype, its dependencies, scripts, theme file and
agent notes are removed.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
samandCopilot committed 2026-11-19 23:35:31 +11:00
1 parent f47aac477a
commit 7673e3a135
21 files changed
+679 -3315

No files matched your search

-32
View File
@@ -145,35 +145,3 @@ pnpm audit # after dependency changes
- Delegate to pi workers when asked, and verify their output. Check for overlap
before merging, rerun their checks on the combined result, and fix what they
find.
<!-- ASTRYX:START -->
Astryx v0.7.16 · 174 components
CLI: run every command as `pnpm exec astryx <cmd>` (shown below as `astryx ...`).
SETUP (once, in app entry e.g. main.tsx) — without these, components render unstyled:
import "@astryxdesign/core/reset.css";
import "@astryxdesign/core/astryx.css";
WORKFLOW — start every page from a template, never from scratch:
1. `astryx build "<idea>"` — names the template to scaffold from and the parts it lacks.
2. `astryx template <name> <path>` — scaffold it; keep its frame, gap and padding; replace the content.
3. `astryx template <Block>` for parts it lacks; `astryx component <Name>` to read props before using one.
Changing an existing page? Keep it: skip step 2 and add blocks/components inside its sections.
Before you deliver a build, run `astryx doctor --built <dir>`; don't deliver it if it fails.
RULES:
- No <div> — components handle all layout and spacing.
- Read `astryx docs layout` before changing a template's frame.
- Dense data = rows (Table, List/Item), not Card-wrapped lists. Badge = counts only.
- Style with component props first, then Tailwind utilities backed by tokens. No raw hex/px.
- THEMES: palettes and custom colors go through the theme, never :root overrides. To make or change a theme (colors, fonts, corners, spacing, a look from a picture), prefer the experimental theme editor over hand-written theme files: `astryx experimental theme editor new <name> --like neutral`, then `editor set <name> <thing> <value>` or `editor how "<what you want>"`; wire it with `astryx theme add <name>`; after each change look at it with `astryx experimental theme editor show <name> --png` and open the PNGs it writes (changes nothing in the app); a theme change is not done until you have looked at the pictures. In code, extend an imported theme to customize it; `theme eject <slug>` only forks source. See `astryx docs theme`.
- SELF-CHECK: re-read the file; replace any style={{…}}, raw <div>/<span>, imported .css/@apply, or hardcoded/arbitrary value (bg-[#fff], p-[13px]) with the component or a token-backed utility.
`astryx help` lists every command. Key ones beyond the workflow:
search "<query>" find any component / hook / doc / template
discover <words> integrations you could add
docs <topic> getting-started, principles, tokens, theme … (`astryx docs` lists all)
docs cli commands and API reference
docs authoring build an integration package, and every field it holds
upgrade --from <old version> --apply run after a dependency bump
<!-- ASTRYX:END -->
-77
View File
@@ -1,77 +0,0 @@
import { Button } from "@astryxdesign/core/Button";
import { Heading } from "@astryxdesign/core/Heading";
import { Layout, LayoutContent, LayoutHeader } from "@astryxdesign/core/Layout";
import { Section } from "@astryxdesign/core/Section";
import { HStack, VStack } from "@astryxdesign/core/Stack";
import { Text } from "@astryxdesign/core/Text";
import type { Area } from "./ShellFrame";
type AreaPageProps = {
area: Exclude<Area, "Composer" | "Runs">;
onOpenRun: () => void;
};
const copy = {
Events: {
heading: "What Archie heard",
subheading: "Incoming evidence and the work it started.",
title: "Checkout timeout rate exceeded 5%",
eyebrow: "Monitoring · 09:38 UTC",
body: "Checkout timeouts rose after the latest release. Archie authenticated the event, bound it to the production checkout target, and started an investigation run.",
action: "Open investigation",
},
Governance: {
heading: "Governance",
subheading: "Policies, autonomy levels and action limits.",
title: "Production rollback requires approval",
eyebrow: "Production · Checkout · Rollback",
body: "The current autonomy level permits read-only investigation. The rollback is reversible, but it changes production. Hard rules and the Timing guard therefore require an operator decision.",
action: "Review decision",
},
Reports: {
heading: "What Archie delivered",
subheading: "Outcomes, evidence and the remaining work.",
title: "Checkout investigation delivered",
eyebrow: "Operations · Waiting on approval",
body: "The investigation and evidence are in Operations. No production change has been made. The underlying release defect remains to be confirmed.",
action: "Open decision trail",
},
} as const;
export function AreaPage({ area, onOpenRun }: AreaPageProps) {
const content = copy[area];
return (
<Layout
height="fill"
padding={4}
contentWidth={960}
header={
<LayoutHeader padding={4} hasDivider>
<VStack gap={1}>
<Heading level={1}>{content.heading}</Heading>
<Text color="secondary">{content.subheading}</Text>
</VStack>
</LayoutHeader>
}
content={
<LayoutContent padding={4}>
<Section>
<VStack gap={3}>
<HStack gap={1} wrap="wrap" vAlign="center">
<Text size="sm" color="secondary">
{content.eyebrow}
</Text>
</HStack>
<Heading level={2}>{content.title}</Heading>
<Text as="p">{content.body}</Text>
<HStack>
<Button label={content.action} variant="primary" onClick={onOpenRun} />
</HStack>
</VStack>
</Section>
</LayoutContent>
}
/>
);
}
-258
View File
@@ -1,258 +0,0 @@
import { useLocalStorage, useWindowSize } from "@uidotdev/usehooks";
import { Avatar } from "@astryxdesign/core/Avatar";
import { BottomSheet } from "@astryxdesign/core/BottomSheet";
import { Button } from "@astryxdesign/core/Button";
import {
ChatComposer,
ChatLayout,
ChatMessage,
ChatMessageBubble,
ChatMessageList,
} from "@astryxdesign/core/Chat";
import { Heading } from "@astryxdesign/core/Heading";
import { useMediaQuery } from "@astryxdesign/core/hooks";
import { Icon } from "@astryxdesign/core/Icon";
import { IconButton } from "@astryxdesign/core/IconButton";
import { Popover } from "@astryxdesign/core/Popover";
import { HStack, StackItem, VStack } from "@astryxdesign/core/Stack";
import { Text } from "@astryxdesign/core/Text";
import { Toolbar } from "@astryxdesign/core/Toolbar";
import mark from "../../assets/brand/archie-mark.svg?url";
export type DockedMessage = {
id: string;
sender: "user" | "assistant";
text: string;
};
type DockedComposerProps = {
context: string;
messages: DockedMessage[];
draft: string;
onDraftChange: (value: string) => void;
onSubmit: (value: string) => void;
onOpenConversation: () => void;
};
const suggestedPrompts = [
"Why does this need approval?",
"What is the risk?",
"What happens if I decline?",
] as const;
export function DockedComposer({
context,
messages,
draft,
onDraftChange,
onSubmit,
onOpenConversation,
}: DockedComposerProps) {
const isNarrow = useMediaQuery("(max-width: 48rem)");
const [isConversationOpen, setIsConversationOpen] = useLocalStorage(
"archie.astryx-reference.chat-open",
messages.length > 0,
);
const { height: viewportHeight } = useWindowSize();
const conversationHeight = Math.max(
280,
Math.min(560, (viewportHeight ?? 656) - 96),
);
function submit(value: string) {
setIsConversationOpen(true);
onSubmit(value);
}
const composer = (
<ChatComposer
density="compact"
elevation="none"
value={draft}
onChange={onDraftChange}
onSubmit={submit}
placeholder="Message Archie"
/>
);
const conversation = (
<VStack
gap={0}
width="100%"
height={isNarrow ? "100%" : conversationHeight}
>
<Toolbar
label="Archie conversation"
size="sm"
variant="transparent"
dividers={["bottom"]}
startContent={
<HStack gap={1} vAlign="center">
<Avatar
src={mark}
name="Archie"
size="sm"
shape="square"
tooltip={false}
/>
<VStack gap={0}>
<Heading level={2}>Archie</Heading>
<Text type="supporting" maxLines={1}>
{context}
</Text>
</VStack>
</HStack>
}
endContent={
<HStack gap={0.5} vAlign="center">
<Button
label="Expand"
variant="ghost"
size="sm"
onClick={onOpenConversation}
/>
<IconButton
label="Hide conversation"
tooltip="Hide conversation"
icon={<Icon icon="chevronDown" />}
variant="ghost"
size="sm"
onClick={() => setIsConversationOpen(false)}
/>
</HStack>
}
/>
<StackItem size="fill">
<ChatLayout
density="compact"
composer={
<VStack gap={1}>
<HStack gap={1} width="100%" isScrollable>
{suggestedPrompts.map((prompt) => (
<StackItem key={prompt} size="static">
<Button
label={prompt}
size="sm"
variant="secondary"
onClick={() => submit(prompt)}
/>
</StackItem>
))}
</HStack>
{composer}
</VStack>
}
>
<ChatMessageList density="compact" align="top">
{messages.map((message) => (
<ChatMessage
key={message.id}
sender={message.sender}
avatar={
message.sender === "assistant" ? (
<Avatar
src={mark}
name="Archie"
size="sm"
shape="square"
tooltip={false}
/>
) : undefined
}
>
<ChatMessageBubble
variant={message.sender === "assistant" ? "ghost" : "filled"}
>
<Text as="p">{message.text}</Text>
</ChatMessageBubble>
</ChatMessage>
))}
</ChatMessageList>
</ChatLayout>
</StackItem>
</VStack>
);
const toggleLabel = isConversationOpen
? "Hide conversation"
: "Show conversation";
const toggle = (
<IconButton
label={toggleLabel}
tooltip={toggleLabel}
icon={
<Icon icon={isConversationOpen ? "chevronDown" : "arrowUp"} />
}
variant="ghost"
size="sm"
/>
);
return (
<VStack width="100%" hAlign="end">
<HStack
gap={2}
padding={2}
width={isNarrow ? "100%" : 440}
vAlign="center"
hAlign="end"
>
{!isConversationOpen && (
<>
<Avatar
src={mark}
name="Archie"
size="sm"
shape="square"
tooltip={false}
/>
<StackItem size="fill">{composer}</StackItem>
</>
)}
{isNarrow ? (
<>
<IconButton
label={toggleLabel}
tooltip={toggleLabel}
icon={
<Icon
icon={isConversationOpen ? "chevronDown" : "arrowUp"}
/>
}
variant="ghost"
size="sm"
onClick={() => setIsConversationOpen((open) => !open)}
/>
<BottomSheet
isOpen={isConversationOpen}
onOpenChange={setIsConversationOpen}
label="Archie conversation"
height="55dvh"
padding={0}
>
{isConversationOpen ? conversation : null}
</BottomSheet>
</>
) : (
<Popover
isOpen={isConversationOpen}
onOpenChange={setIsConversationOpen}
placement="above"
alignment="end"
width={440}
padding={0}
label="Archie conversation"
isModal={false}
presentation="popover"
hasAutoFocus={false}
hasCloseButton={false}
content={isConversationOpen ? conversation : null}
>
{toggle}
</Popover>
)}
</HStack>
</VStack>
);
}
-235
View File
@@ -1,235 +0,0 @@
import { useEffect, useMemo, useState, type ReactNode } from "react";
import { AppShell } from "@astryxdesign/core/AppShell";
import { Badge } from "@astryxdesign/core/Badge";
import { Button } from "@astryxdesign/core/Button";
import { CommandPalette } from "@astryxdesign/core/CommandPalette";
import { DropdownMenu } from "@astryxdesign/core/DropdownMenu";
import { HStack, Stack } from "@astryxdesign/core/Stack";
import { Icon } from "@astryxdesign/core/Icon";
import { Layout, LayoutContent, LayoutFooter } from "@astryxdesign/core/Layout";
import { useMediaQuery } from "@astryxdesign/core/hooks";
import { SideNav, SideNavItem, SideNavSection } from "@astryxdesign/core/SideNav";
import { Text } from "@astryxdesign/core/Text";
import { TextInput } from "@astryxdesign/core/TextInput";
import { TopNav } from "@astryxdesign/core/TopNav";
import { createStaticSource } from "@astryxdesign/core/Typeahead";
import {
BellAlertIcon,
ChatBubbleLeftRightIcon,
ChartBarSquareIcon,
CheckBadgeIcon,
MagnifyingGlassIcon,
QueueListIcon,
ShieldCheckIcon,
} from "@heroicons/react/24/outline";
import wordmark from "../../assets/brand/archie-wordmark.svg?url";
import darkWordmark from "../../assets/brand/archie-wordmark-dark.svg?url";
export type Area = "Composer" | "Runs" | "Events" | "Governance" | "Reports";
type ShellFrameProps = {
activeArea: Area;
pendingCount: number;
onNavigate: (area: Area) => void;
dock?: ReactNode;
children: ReactNode;
};
const navigation = [
{
title: "Work",
items: [
{ label: "Composer", icon: ChatBubbleLeftRightIcon },
{ label: "Runs", icon: QueueListIcon },
{ label: "Events", icon: BellAlertIcon },
],
},
{
title: "Control",
items: [
{ label: "Governance", icon: ShieldCheckIcon },
{ label: "Reports", icon: ChartBarSquareIcon },
],
},
] satisfies Array<{
title: string;
items: Array<{ label: Area; icon: typeof ChatBubbleLeftRightIcon }>;
}>;
type Command = {
id: "composer" | "runs" | "events" | "governance" | "reports";
label: string;
};
const commands: Command[] = [
{ id: "composer", label: "Composer" },
{ id: "runs", label: "Runs" },
{ id: "events", label: "Events" },
{ id: "governance", label: "Governance" },
{ id: "reports", label: "Reports" },
];
export function ShellFrame({
activeArea,
pendingCount,
onNavigate,
dock,
children,
}: ShellFrameProps) {
const [isPaletteOpen, setIsPaletteOpen] = useState(false);
const [isMobileNavOpen, setIsMobileNavOpen] = useState(false);
const source = useMemo(() => createStaticSource(commands), []);
const hasInlineNavigation = useMediaQuery("(min-width: 768px)");
const prefersDark = useMediaQuery("(prefers-color-scheme: dark)");
useEffect(() => {
function openPalette(event: KeyboardEvent) {
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
event.preventDefault();
setIsPaletteOpen(true);
}
}
window.addEventListener("keydown", openPalette);
return () => window.removeEventListener("keydown", openPalette);
}, []);
useEffect(() => {
setIsMobileNavOpen(false);
}, [activeArea]);
function renderNavigation() {
return (
<SideNav
collapsible
resizable={{ defaultWidth: 224, minWidth: 200, maxWidth: 320 }}
>
{navigation.map((section) => (
<SideNavSection key={section.title} title={section.title}>
{section.items.map((item) => (
<SideNavItem
key={item.label}
label={item.label}
icon={item.icon}
isSelected={activeArea === item.label}
onClick={() => navigate(item.label)}
endContent={
item.label === "Runs" && pendingCount > 0 ? (
<Badge variant="warning" label={pendingCount} />
) : undefined
}
/>
))}
</SideNavSection>
))}
</SideNav>
);
}
function navigate(area: Area) {
setIsMobileNavOpen(false);
onNavigate(area);
window.setTimeout(() => setIsMobileNavOpen(false), 0);
}
function chooseCommand(value: Command) {
setIsPaletteOpen(false);
navigate(
value.id === "composer"
? "Composer"
: value.id === "runs"
? "Runs"
: value.id === "events"
? "Events"
: value.id === "governance"
? "Governance"
: "Reports",
);
}
return (
<>
<AppShell
contentPadding={0}
topNav={
<TopNav
label="Archie workspace"
heading={
<img
src={prefersDark ? darkWordmark : wordmark}
alt="Archie"
width={88}
height={24}
/>
}
startContent={
<DropdownMenu
button={{ label: "CatlowTech", variant: "ghost", size: "sm" }}
items={[
{ label: "CatlowTech", endContent: <Badge variant="neutral" label="Instance" /> },
{ type: "divider" },
{ label: "Instance settings", onClick: () => navigate("Governance") },
]}
/>
}
endContent={
<HStack gap={1} vAlign="center">
{hasInlineNavigation && (
<Stack onClick={() => setIsPaletteOpen(true)}>
<TextInput
label="Jump to"
isLabelHidden
size="sm"
width={240}
startIcon={MagnifyingGlassIcon}
placeholder="Jump to…"
value=""
onChange={() => setIsPaletteOpen(true)}
/>
</Stack>
)}
<Button
label="Approvals"
size="sm"
variant="ghost"
icon={<Icon icon={CheckBadgeIcon} size="sm" />}
endContent={pendingCount > 0 ? <Badge variant="warning" label={pendingCount} /> : undefined}
onClick={() => navigate("Runs")}
/>
</HStack>
}
/>
}
sideNav={renderNavigation()}
mobileNav={{
breakpoint: "md",
isOpen: isMobileNavOpen,
onOpenChange: setIsMobileNavOpen,
}}
>
<Layout
height="fill"
padding={0}
content={<LayoutContent padding={0}>{children}</LayoutContent>}
footer={
dock ? (
<LayoutFooter hasDivider label="Composer">
{dock}
</LayoutFooter>
) : undefined
}
/>
</AppShell>
<CommandPalette
label="Jump to"
isOpen={isPaletteOpen}
onOpenChange={setIsPaletteOpen}
searchSource={source}
onValueChange={(value) => {
const command = commands.find((candidate) => candidate.id === value);
if (command) chooseCommand(command);
}}
/>
</>
);
}
-12
View File
@@ -1,12 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Archie · Astryx design reference</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./main.tsx"></script>
</body>
</html>
-152
View File
@@ -1,152 +0,0 @@
import { useState } from "react";
import { createRoot } from "react-dom/client";
import { Theme } from "@astryxdesign/core/theme";
import "@astryxdesign/core/reset.css";
import "@astryxdesign/core/astryx.css";
import { AreaPage } from "./AreaPage";
import { DockedComposer } from "./DockedComposer";
import { ShellFrame, type Area } from "./ShellFrame";
import LandingPage from "./pages/LandingPage";
import ConversationPage, {
type ConversationMessage,
} from "./pages/ConversationPage";
import RunsPage, { type RunDecision } from "./pages/RunsPage";
import { theme } from "./theme";
const answers = [
{
test: /decision|approval|blocked|waiting/i,
text: "One run needs a decision. The checkout investigation recommends a rollback after timeouts rose from 0.4% to 8.1%. Production policy requires your approval before anything changes.",
},
{
test: /risk|impact|go wrong/i,
text: "The rollback carries moderate risk because checkout may briefly lose capacity while the release changes. It is reversible: the current release can be reapplied, and no database change is proposed.",
},
{
test: /declin(e|es|ed|ing)|deny|reject/i,
text: "Declining stops the run before any production change. Archie records the exact decision and evidence; checkout remains unchanged and the timeout investigation remains unresolved.",
},
{
test: /checkout|tim(e|ing)? out/i,
text: "Only checkout is affected. Timeouts rose four minutes after the 09:34 release. That release is the leading suspect, not a confirmed cause. The proposed rollback is reversible and does not change the database.",
},
{
test: /today|did archie|what happened/i,
text: "Archie authenticated the checkout alert, investigated the timeout spike, assessed the proposed rollback, and delivered the evidence for review. Nothing changed in production.",
},
] as const;
function answerFor(prompt: string) {
return (
answers.find(({ test }) => test.test(prompt))?.text ??
"I can explain this page, open a run, or help you review the evidence and policy behind it. This reference does not start live work."
);
}
function App() {
const [activeArea, setActiveArea] = useState<Area>("Composer");
const [draft, setDraft] = useState("");
const [messages, setMessages] = useState<ConversationMessage[]>([]);
const [decision, setDecision] = useState<RunDecision>("pending");
function submit(prompt: string) {
const value = prompt.trim();
if (!value) return;
const id = crypto.randomUUID();
setMessages((current) => [
...current,
{ id: `${id}-user`, sender: "user", text: value },
{ id: `${id}-archie`, sender: "assistant", text: answerFor(value) },
]);
setDraft("");
}
function recordDecision(next: RunDecision) {
setDecision(next);
const outcome =
next === "approved"
? "The operator approved the checkout rollback. This reference would now execute the exact approved action and verify the timeout rate."
: "The operator declined the checkout rollback. No production change was made, and the run stopped at the decision.";
setMessages((current) => [
...current,
{
id: crypto.randomUUID(),
sender: "assistant",
text: outcome,
},
]);
}
const dockedComposer = (
<DockedComposer
context={
activeArea === "Runs"
? "Runs · checkout rollback"
: `${activeArea} · same conversation`
}
messages={messages}
draft={draft}
onDraftChange={setDraft}
onSubmit={submit}
onOpenConversation={() => setActiveArea("Composer")}
/>
);
return (
<ShellFrame
activeArea={activeArea}
pendingCount={decision === "pending" ? 1 : 0}
onNavigate={setActiveArea}
dock={
activeArea !== "Composer" && activeArea !== "Runs"
? dockedComposer
: undefined
}
>
{activeArea === "Composer" &&
(messages.length === 0 ? (
<LandingPage
draft={draft}
onDraftChange={setDraft}
onSubmit={submit}
onNavigate={(area) => {
const destination = {
composer: "Composer",
runs: "Runs",
events: "Events",
governance: "Governance",
reports: "Reports",
} as const;
setActiveArea(destination[area]);
}}
/>
) : (
<ConversationPage
messages={messages}
draft={draft}
onDraftChange={setDraft}
onSubmit={submit}
onOpenRun={() => setActiveArea("Runs")}
decision={decision}
/>
))}
{activeArea === "Runs" && (
<RunsPage
composer={dockedComposer}
decision={decision}
onDecision={recordDecision}
/>
)}
{activeArea !== "Composer" && activeArea !== "Runs" && (
<AreaPage area={activeArea} onOpenRun={() => setActiveArea("Runs")} />
)}
</ShellFrame>
);
}
createRoot(document.getElementById("root")!).render(
<Theme theme={theme}>
<App />
</Theme>,
);
@@ -1,422 +0,0 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
'use client';
import {useState} from 'react';
import {Avatar} from '@astryxdesign/core/Avatar';
import {Badge} from '@astryxdesign/core/Badge';
import {Button} from '@astryxdesign/core/Button';
import {Card} from '@astryxdesign/core/Card';
import {
ChatComposer,
ChatLayout,
ChatMessage,
ChatMessageBubble,
ChatMessageList,
} from '@astryxdesign/core/Chat';
import {ClickableCard} from '@astryxdesign/core/ClickableCard';
import {Dialog, DialogHeader} from '@astryxdesign/core/Dialog';
import {Icon} from '@astryxdesign/core/Icon';
import {
HStack,
Layout,
LayoutContent,
LayoutPanel,
StackItem,
VStack,
} from '@astryxdesign/core/Layout';
import {MetadataList, MetadataListItem} from '@astryxdesign/core/MetadataList';
import {useMediaQuery} from '@astryxdesign/core/hooks';
import {ResizeHandle, useResizable} from '@astryxdesign/core/Resizable';
import {Section} from '@astryxdesign/core/Section';
import {Heading, Text} from '@astryxdesign/core/Text';
import {Toolbar} from '@astryxdesign/core/Toolbar';
import {
ChevronRightIcon,
DocumentTextIcon,
XMarkIcon,
} from '@heroicons/react/24/outline';
import mark from '../../../assets/brand/archie-mark.svg?url';
const ARTIFACT_TITLE = 'Checkout rollback review';
export type ConversationMessage = {
id: string;
sender: 'user' | 'assistant';
text: string;
};
type ConversationDecision = 'pending' | 'approved' | 'declined';
function proposesCheckoutRollback(text: string) {
const normalized = text.toLowerCase();
return (
normalized.includes('checkout') &&
(normalized.includes('rollback') ||
normalized.includes('roll back') ||
(normalized.includes('roll') && normalized.includes('back')))
);
}
function RollbackArtifactBody({
decision,
}: {
decision: ConversationDecision;
}) {
const statusLabel =
decision === 'pending'
? 'Approval Required'
: decision === 'approved'
? 'Completed'
: 'Declined';
const statusVariant =
decision === 'pending'
? 'warning'
: decision === 'approved'
? 'success'
: 'neutral';
return (
<Section variant="transparent" padding={4}>
<VStack gap={2}>
<VStack gap={2}>
<HStack gap={2} wrap="wrap" vAlign="center">
<Badge variant={statusVariant} label={statusLabel} />
<Text type="supporting" color="secondary">
Checkout · Production
</Text>
</HStack>
<Heading level={1}>Roll back checkout</Heading>
<Text as="p" type="body" color="secondary">
{decision === 'pending'
? 'The proposal is limited to checkout and is ready for an operator decision. Reviewing it here does not change production.'
: decision === 'approved'
? 'The operator approved the exact proposal in Runs. The result is recorded with the action trail.'
: 'The operator declined the exact proposal in Runs. No production change was made.'}
</Text>
</VStack>
<MetadataList
columns="single"
label={{position: 'top'}}
title={<Heading level={2}>Decision brief</Heading>}>
<MetadataListItem label="Evidence">
<Text as="p" type="body">
Checkout timeouts rose from 0.4% to 8.1% four minutes after the
09:34 release. No other service showed a comparable increase.
The timing is strong evidence, not a confirmed root cause.
</Text>
</MetadataListItem>
<MetadataListItem label="Risk">
<Text as="p" type="body">
Moderate: checkout may briefly lose capacity while instances
move to the earlier release.
</Text>
</MetadataListItem>
<MetadataListItem label="Reversibility">
<Text as="p" type="body">
The release can be reapplied if the rollback does not restore
checkout. No database change is proposed.
</Text>
</MetadataListItem>
<MetadataListItem label="Policy decision">
<Text as="p" type="body">
Read-only investigation is allowed. This production rollback
requires operator approval in Runs; database changes remain
outside the workflow.
</Text>
</MetadataListItem>
</MetadataList>
</VStack>
</Section>
);
}
function RollbackArtifactCard({
decision,
onOpen,
}: {
decision: ConversationDecision;
onOpen: () => void;
}) {
const statusLabel =
decision === 'pending'
? 'Approval Required'
: decision === 'approved'
? 'Completed'
: 'Declined';
return (
<ClickableCard
label={`Review ${ARTIFACT_TITLE.toLowerCase()}`}
onClick={onOpen}
variant="muted"
padding={3}
width="100%">
<HStack gap={3} vAlign="center">
<Icon icon={DocumentTextIcon} size="md" color="secondary" />
<StackItem size="fill">
<VStack gap={1}>
<HStack gap={2} wrap="wrap" vAlign="center">
<Text type="label" weight="semibold">
{ARTIFACT_TITLE}
</Text>
<Badge
variant={
decision === 'pending'
? 'warning'
: decision === 'approved'
? 'success'
: 'neutral'
}
label={statusLabel}
/>
</HStack>
<Text type="supporting" color="secondary">
Evidence, risk, reversibility, and policy
</Text>
</VStack>
</StackItem>
<Icon icon={ChevronRightIcon} size="sm" color="secondary" />
</HStack>
</ClickableCard>
);
}
function ArtifactToolbar({
onClose,
onOpenRun,
}: {
onClose: () => void;
onOpenRun: () => void;
}) {
return (
<Toolbar
label="Checkout rollback actions"
dividers={['bottom']}
startContent={
<HStack gap={3} vAlign="center">
<Icon icon={DocumentTextIcon} size="sm" color="secondary" />
<VStack gap={0}>
<Text type="label" weight="semibold">
{ARTIFACT_TITLE}
</Text>
<Text type="supporting" color="secondary">
Checkout · Production
</Text>
</VStack>
</HStack>
}
endContent={
<HStack gap={1} vAlign="center">
<Button
label="Open run"
variant="primary"
size="sm"
onClick={onOpenRun}
/>
<Button
label="Close checkout rollback review"
variant="ghost"
size="sm"
icon={<Icon icon={XMarkIcon} size="sm" />}
isIconOnly
onClick={onClose}
/>
</HStack>
}
/>
);
}
export default function ConversationPage({
messages,
draft,
onDraftChange,
onSubmit,
onOpenRun,
decision,
}: {
messages: ConversationMessage[];
draft: string;
onDraftChange(value: string): void;
onSubmit(value: string): void;
onOpenRun(): void;
decision: ConversationDecision;
}) {
const isNarrow = useMediaQuery('(max-width: 48rem)');
const [closedArtifactId, setClosedArtifactId] = useState<string | null>(null);
const [dialogArtifactId, setDialogArtifactId] = useState<string | null>(null);
const artifactResize = useResizable({
defaultSize: 640,
minSize: 480,
maxSize: 960,
});
const latestAssistantIndex = messages.reduce(
(latestIndex, message, index) =>
message.sender === 'assistant' ? index : latestIndex,
-1,
);
const latestAssistantMessage =
latestAssistantIndex >= 0 ? messages[latestAssistantIndex] : null;
const hasRollbackProposal =
latestAssistantMessage != null &&
proposesCheckoutRollback(latestAssistantMessage.text);
const isDesktopArtifactOpen =
hasRollbackProposal &&
latestAssistantMessage != null &&
closedArtifactId !== latestAssistantMessage.id;
const isArtifactDialogOpen =
hasRollbackProposal &&
latestAssistantMessage != null &&
dialogArtifactId === latestAssistantMessage.id;
function openArtifact() {
if (latestAssistantMessage == null || !hasRollbackProposal) {
return;
}
if (isNarrow) {
setDialogArtifactId(latestAssistantMessage.id);
} else {
setClosedArtifactId(null);
}
}
return (
<>
<Layout
height="fill"
padding={0}
content={
<LayoutContent padding={0}>
<HStack height="100%">
<StackItem size="fill">
<VStack gap={0} width="100%" height="100%">
<ChatLayout
density="spacious"
composer={
<ChatComposer
value={draft}
onChange={onDraftChange}
onSubmit={onSubmit}
placeholder="Ask Archie about active work, evidence, or policy…"
/>
}>
<ChatMessageList>
{messages.map((message, index) => {
const isAssistant = message.sender === 'assistant';
const isRollbackMessage =
hasRollbackProposal &&
index === latestAssistantIndex;
return (
<ChatMessage
key={message.id}
sender={message.sender}
avatar={
isAssistant ? (
<Avatar
src={mark}
name="Archie"
size="md"
shape="square"
/>
) : undefined
}>
<ChatMessageBubble
variant={isAssistant ? 'ghost' : 'filled'}>
<Text as="p">{message.text}</Text>
</ChatMessageBubble>
{isRollbackMessage && (
<ChatMessageBubble variant="ghost" width="100%">
<RollbackArtifactCard
decision={decision}
onOpen={openArtifact}
/>
</ChatMessageBubble>
)}
</ChatMessage>
);
})}
</ChatMessageList>
</ChatLayout>
</VStack>
</StackItem>
{isDesktopArtifactOpen && !isNarrow && latestAssistantMessage && (
<>
<ResizeHandle
direction="horizontal"
resizable={artifactResize.props}
isReversed
pillPlacement="start"
hasDivider
label="Resize checkout rollback review"
/>
<LayoutPanel
resizable={artifactResize}
padding={0}
isScrollable={false}
label="Checkout rollback review">
<Card
variant="transparent"
padding={0}
width="100%"
height="100%">
<VStack gap={0} height="100%">
<ArtifactToolbar
onClose={() =>
setClosedArtifactId(latestAssistantMessage.id)
}
onOpenRun={onOpenRun}
/>
<StackItem size="fill" isScrollable>
<RollbackArtifactBody decision={decision} />
</StackItem>
</VStack>
</Card>
</LayoutPanel>
</>
)}
</HStack>
</LayoutContent>
}
/>
{hasRollbackProposal && latestAssistantMessage && (
<Dialog
isOpen={isArtifactDialogOpen}
onOpenChange={isOpen =>
setDialogArtifactId(isOpen ? latestAssistantMessage.id : null)
}
purpose="info"
variant="fullscreen">
<Layout
height="fill"
header={
<DialogHeader
title={ARTIFACT_TITLE}
subtitle="Checkout · Production"
onOpenChange={() => setDialogArtifactId(null)}
endContent={
<Button
label="Open run"
variant="primary"
size="sm"
onClick={onOpenRun}
/>
}
/>
}
content={
<LayoutContent padding={0}>
<RollbackArtifactBody decision={decision} />
</LayoutContent>
}
/>
</Dialog>
)}
</>
);
}
-89
View File
@@ -1,89 +0,0 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
'use client';
import {Button} from '@astryxdesign/core/Button';
import {ChatComposer} from '@astryxdesign/core/Chat';
import {
Layout,
LayoutContent,
VStack,
HStack,
} from '@astryxdesign/core/Layout';
import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';
export type LandingArea =
| 'composer'
| 'runs'
| 'events'
| 'governance'
| 'reports';
const SUGGESTIONS: ReadonlyArray<{
prompt: string;
destination?: LandingArea;
}> = [
{
prompt: 'What needs a decision?',
destination: 'runs',
},
{
prompt: 'Why is checkout timing out?',
},
{
prompt: 'What did Archie do today?',
},
];
export default function LandingPage({
draft,
onDraftChange,
onSubmit,
onNavigate,
}: {
draft: string;
onDraftChange(value: string): void;
onSubmit(value: string): void;
onNavigate(area: LandingArea): void;
}) {
return (
<Layout
height="fill"
contentWidth={720}
padding={6}
content={
<LayoutContent label="Composer">
<VStack gap={8} vAlign="center" minHeight="100%">
<VisuallyHidden as="h1">Composer</VisuallyHidden>
<ChatComposer
value={draft}
onChange={onDraftChange}
onSubmit={onSubmit}
placeholder="Message Archie…"
/>
<VStack gap={2} paddingInline={3} hAlign="center">
<HStack gap={2} wrap="wrap" vAlign="center" hAlign="center">
{SUGGESTIONS.map(suggestion => (
<Button
key={suggestion.prompt}
label={suggestion.prompt}
variant="secondary"
size="sm"
onClick={() => {
onSubmit(suggestion.prompt);
if (suggestion.destination) {
onNavigate(suggestion.destination);
}
}}
/>
))}
</HStack>
</VStack>
</VStack>
</LayoutContent>
}
/>
);
}
-586
View File
@@ -1,586 +0,0 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
'use client';
import {Fragment, useMemo, useState} from 'react';
import type * as React from 'react';
import {BottomSheet} from '@astryxdesign/core/BottomSheet';
import {Button} from '@astryxdesign/core/Button';
import {Divider} from '@astryxdesign/core/Divider';
import {EmptyState} from '@astryxdesign/core/EmptyState';
import {Icon} from '@astryxdesign/core/Icon';
import {
HStack,
Layout,
LayoutContent,
LayoutFooter,
LayoutHeader,
LayoutPanel,
StackItem,
VStack,
} from '@astryxdesign/core/Layout';
import {List, ListItem} from '@astryxdesign/core/List';
import {
MetadataList,
MetadataListItem,
} from '@astryxdesign/core/MetadataList';
import {
PowerSearch,
usePowerSearchConfig,
} from '@astryxdesign/core/PowerSearch';
import type {PowerSearchFilter} from '@astryxdesign/core/PowerSearch';
import {ResizeHandle, useResizable} from '@astryxdesign/core/Resizable';
import {
SegmentedControl,
SegmentedControlItem,
} from '@astryxdesign/core/SegmentedControl';
import {StatusDot} from '@astryxdesign/core/StatusDot';
import {Heading, Text} from '@astryxdesign/core/Text';
import {Timestamp} from '@astryxdesign/core/Timestamp';
import {useMediaQuery} from '@astryxdesign/core/hooks';
import {BellAlertIcon} from '@heroicons/react/24/outline';
export type RunDecision = 'pending' | 'approved' | 'declined';
type RunStatus = 'approval' | 'completed' | 'failed' | 'declined';
interface Run extends Record<string, unknown> {
id: string;
title: string;
workflow: string;
service: string;
environment: string;
status: RunStatus;
startedAt: string;
summary: string;
cause: string;
change: string;
risk: string;
undo: string;
approval: string;
}
const PRIMARY_RUN_ID = 'RUN-2041';
const STATUS_ORDER: RunStatus[] = [
'approval',
'completed',
'failed',
'declined',
];
const STATUS_LABEL: Record<RunStatus, string> = {
approval: 'Approval Required',
completed: 'Completed',
failed: 'Failed',
declined: 'Declined',
};
const STATUS_DOT_VARIANT: Record<
RunStatus,
'warning' | 'success' | 'error' | 'neutral'
> = {
approval: 'warning',
completed: 'success',
failed: 'error',
declined: 'neutral',
};
const BASE_RUNS: Run[] = [
{
id: PRIMARY_RUN_ID,
title: 'Roll back checkout to the last healthy release',
workflow: 'checkout-rollback',
service: 'checkout',
environment: 'production',
status: 'approval',
startedAt: '2026-11-19T09:38:00Z',
summary: 'Likely caused by release 4.9.0',
cause: 'Timeouts rose from 0.4% to 8.1% after release 4.9.0',
change: 'Roll checkout back to 4.8.2',
risk: 'Moderate: brief capacity dip',
undo: 'Yes, reapply 4.9.0',
approval: 'Needs your approval',
},
{
id: 'RUN-2040',
title: 'Rebuild the payments search projection',
workflow: 'projection-rebuild',
service: 'payments',
environment: 'production',
status: 'completed',
startedAt: '2026-11-19T08:52:00Z',
summary: 'Rebuilt 18,420 stale documents',
cause: 'Search results lagged by 12 minutes',
change: 'Rebuilt the search projection',
risk: 'Low',
undo: 'Yes, old projection kept',
approval: 'Allowed',
},
{
id: 'RUN-2039',
title: 'Retry webhook deliveries from the failed queue',
workflow: 'webhook-recovery',
service: 'webhooks',
environment: 'production',
status: 'failed',
startedAt: '2026-11-19T08:11:00Z',
summary: 'Blocked: 2 destinations not on the allowlist',
cause: '2,104 webhook deliveries failed',
change: 'None; nothing was replayed',
risk: 'None',
undo: 'Nothing to undo',
approval: 'Blocked by allowlist',
},
{
id: 'RUN-2038',
title: 'Restore the stale warehouse cache',
workflow: 'cache-restore',
service: 'warehouse',
environment: 'staging',
status: 'completed',
startedAt: '2026-11-18T23:24:00Z',
summary: 'Restored cache generation 41',
cause: 'Staging cache was 2 generations behind',
change: 'Promoted cache generation 41',
risk: 'Low',
undo: 'Yes, generation 40 kept',
approval: 'Allowed',
},
{
id: 'RUN-2037',
title: 'Rotate the notification scheduler worker',
workflow: 'worker-recovery',
service: 'notifications',
environment: 'production',
status: 'completed',
startedAt: '2026-11-18T21:07:00Z',
summary: 'Replaced one unhealthy worker',
cause: 'Worker notifications-7 stopped responding',
change: 'Replaced the worker',
risk: 'Low',
undo: 'Yes',
approval: 'Allowed',
},
{
id: 'RUN-2036',
title: 'Reconcile the expired identity group sync',
workflow: 'identity-reconcile',
service: 'identity',
environment: 'production',
status: 'failed',
startedAt: '2026-11-18T18:43:00Z',
summary: 'Stopped at a protected group; nothing changed',
cause: 'Sync credential expired',
change: 'None; no memberships changed',
risk: 'None',
undo: 'Nothing to undo',
approval: 'Protected groups are excluded',
},
];
const STATUS_VALUES = STATUS_ORDER.map(value => ({
value,
label: STATUS_LABEL[value],
}));
const SERVICE_VALUES = [
{value: 'checkout', label: 'Checkout'},
{value: 'payments', label: 'Payments'},
{value: 'webhooks', label: 'Webhooks'},
{value: 'warehouse', label: 'Warehouse'},
{value: 'notifications', label: 'Notifications'},
{value: 'identity', label: 'Identity'},
];
const ENVIRONMENT_VALUES = [
{value: 'production', label: 'Production'},
{value: 'staging', label: 'Staging'},
];
const fieldDefs = [
{key: 'title', type: 'string', label: 'Title'},
{key: 'id', type: 'string', label: 'Run'},
{key: 'workflow', type: 'string', label: 'Workflow'},
{
key: 'service',
type: 'enum',
label: 'Service',
enumValues: SERVICE_VALUES,
},
{
key: 'environment',
type: 'enum',
label: 'Environment',
enumValues: ENVIRONMENT_VALUES,
},
{
key: 'status',
type: 'enum',
label: 'Status',
enumValues: STATUS_VALUES,
},
] as const;
function getRuns(decision: RunDecision): Run[] {
return BASE_RUNS.map(run => {
if (run.id !== PRIMARY_RUN_ID) {
return run;
}
return {
...run,
status:
decision === 'pending'
? 'approval'
: decision === 'approved'
? 'completed'
: 'declined',
summary:
decision === 'pending'
? run.summary
: decision === 'approved'
? 'Rolled back; timeouts back to 0.4%'
: 'Declined; nothing changed',
};
});
}
function RunRows({
runs,
selectedId,
onSelect,
}: {
runs: Run[];
selectedId: string | null;
onSelect: (id: string) => void;
}) {
const groups = STATUS_ORDER.map(status => ({
status,
items: runs.filter(run => run.status === status),
})).filter(group => group.items.length > 0);
if (groups.length === 0) {
return (
<EmptyState
title="No matching runs"
description="Adjust the status filter or clear search filters."
icon={<Icon icon={BellAlertIcon} size="lg" />}
/>
);
}
return (
<VStack gap={0}>
{groups.map(group => (
<VStack gap={0} key={group.status}>
<HStack
gap={2}
paddingBlock={2}
paddingInline={3}
vAlign="center">
<Text type="label" color="secondary">
{STATUS_LABEL[group.status]}
</Text>
<Text type="supporting" color="secondary">
{group.items.length}
</Text>
</HStack>
<Divider />
<List density="compact" hasDividers>
{group.items.map(run => (
<ListItem
key={run.id}
label={run.title}
description={run.summary}
startContent={
<StatusDot
variant={STATUS_DOT_VARIANT[run.status]}
label={STATUS_LABEL[run.status]}
isPulsing={run.status === 'approval'}
/>
}
endContent={
<Timestamp
value={run.startedAt}
format="relative_short"
color="secondary"
/>
}
onClick={() => onSelect(run.id)}
isSelected={run.id === selectedId}
/>
))}
</List>
</VStack>
))}
</VStack>
);
}
function RunInspector({
run,
decision,
onDecision,
onClose,
}: {
run: Run;
decision: RunDecision;
onDecision: (decision: RunDecision) => void;
onClose?: () => void;
}) {
const needsDecision = run.id === PRIMARY_RUN_ID && decision === 'pending';
return (
<VStack gap={4} padding={4}>
<VStack gap={2}>
<HStack gap={2} vAlign="center" wrap="wrap">
<StackItem size="fill">
<HStack gap={2} vAlign="center" wrap="wrap">
<StatusDot
variant={STATUS_DOT_VARIANT[run.status]}
label={STATUS_LABEL[run.status]}
isPulsing={run.status === 'approval'}
/>
<Text type="supporting" color="secondary">
{STATUS_LABEL[run.status]} · {run.id}
</Text>
</HStack>
</StackItem>
{onClose && (
<Button
label="Close details"
variant="ghost"
size="sm"
onClick={onClose}
/>
)}
</HStack>
<Heading level={2}>{run.title}</Heading>
</VStack>
{needsDecision && (
<HStack gap={2} wrap="wrap">
<Button
label="Approve rollback"
variant="primary"
size="sm"
onClick={() => onDecision('approved')}
/>
<Button
label="Decline rollback"
variant="secondary"
size="sm"
onClick={() => onDecision('declined')}
/>
</HStack>
)}
<MetadataList
columns="single"
label={{position: 'start', width: 96}}>
<MetadataListItem label="Cause">
<Text type="body">{run.cause}</Text>
</MetadataListItem>
<MetadataListItem label="Change">
<Text type="body">{run.change}</Text>
</MetadataListItem>
<MetadataListItem label="Risk">
<Text type="body">{run.risk}</Text>
</MetadataListItem>
<MetadataListItem label="Undo">
<Text type="body">{run.undo}</Text>
</MetadataListItem>
<MetadataListItem label="Approval">
<Text type="body">{run.approval}</Text>
</MetadataListItem>
<MetadataListItem label="Started">
<Timestamp
value={run.startedAt}
format="date_time"
timezoneID="UTC"
/>
</MetadataListItem>
</MetadataList>
</VStack>
);
}
export default function RunsPage({
composer,
decision,
onDecision,
}: {
composer: React.ReactNode;
decision: RunDecision;
onDecision: (decision: RunDecision) => void;
}) {
const [statusFilter, setStatusFilter] = useState('all');
const [filters, setFilters] = useState<PowerSearchFilter[]>([]);
const [selectedId, setSelectedId] = useState<string | null>(PRIMARY_RUN_ID);
const [isMobileInspectorOpen, setIsMobileInspectorOpen] = useState(false);
const {config, applyFilters} = usePowerSearchConfig(fieldDefs, 'Runs');
const isNarrow = useMediaQuery('(max-width: 1024px)');
const inspectorPanel = useResizable({
defaultSize: 380,
minSize: 320,
maxSize: 480,
});
const runs = useMemo(() => getRuns(decision), [decision]);
const visible = useMemo(() => {
const searched = applyFilters(filters, runs);
return statusFilter === 'all'
? searched
: searched.filter(run => run.status === statusFilter);
}, [applyFilters, filters, runs, statusFilter]);
const selected = visible.find(run => run.id === selectedId) ?? null;
const approvalCount = runs.filter(run => run.status === 'approval').length;
const selectRun = (id: string) => {
setSelectedId(id);
if (isNarrow) {
setIsMobileInspectorOpen(true);
}
};
return (
<Fragment>
<Layout
height="fill"
header={
<LayoutHeader hasDivider>
<HStack gap={3} vAlign="center" wrap="wrap">
<StackItem size="fill">
<HStack gap={2} vAlign="center" wrap="wrap">
<Heading level={1}>Runs</Heading>
<Text type="supporting" color="secondary">
{approvalCount} awaiting approval
</Text>
</HStack>
</StackItem>
<SegmentedControl
label="Filter runs by status"
value={statusFilter}
onChange={setStatusFilter}
size="sm">
<SegmentedControlItem label="All" value="all" />
<SegmentedControlItem label="Approval" value="approval" />
<SegmentedControlItem label="Completed" value="completed" />
<SegmentedControlItem label="Failed" value="failed" />
<SegmentedControlItem label="Declined" value="declined" />
</SegmentedControl>
</HStack>
</LayoutHeader>
}
content={
<LayoutContent padding={0}>
<Layout
height="fill"
content={
<LayoutContent padding={0}>
<VStack
gap={0}
height="100%"
minHeight={0}
hAlign="stretch">
<HStack padding={3}>
<StackItem size="fill">
<PowerSearch
config={config}
filters={filters}
onChange={newFilters =>
setFilters([...newFilters])
}
label="Search runs"
placeholder="Search runs..."
resultCount={visible.length}
/>
</StackItem>
</HStack>
<Divider />
<StackItem size="fill" isScrollable>
<RunRows
runs={visible}
selectedId={selected?.id ?? null}
onSelect={selectRun}
/>
</StackItem>
</VStack>
</LayoutContent>
}
end={
isNarrow ? undefined : (
<Fragment>
<ResizeHandle
direction="horizontal"
isReversed
hasDivider
isAlwaysVisible={false}
resizable={inspectorPanel.props}
label="Resize run inspector"
/>
<LayoutPanel
width={inspectorPanel.size}
resizable={inspectorPanel}
padding={0}
isScrollable
label="Run details">
{selected ? (
<RunInspector
run={selected}
decision={decision}
onDecision={onDecision}
/>
) : (
<EmptyState
title="No run selected"
description="Select a run to see its decision record."
icon={<Icon icon={BellAlertIcon} size="lg" />}
isCompact
/>
)}
</LayoutPanel>
</Fragment>
)
}
/>
</LayoutContent>
}
footer={
<LayoutFooter padding={0} label="Composer">
{composer}
</LayoutFooter>
}
/>
{isNarrow && (
<BottomSheet
isOpen={isMobileInspectorOpen && selected !== null}
onOpenChange={setIsMobileInspectorOpen}
label={selected?.title ?? 'Run details'}
height="tall"
padding={0}>
{selected ? (
<RunInspector
run={selected}
decision={decision}
onDecision={onDecision}
onClose={() => setIsMobileInspectorOpen(false)}
/>
) : (
<EmptyState
title="No run selected"
description="Select a run to see its decision record."
icon={<Icon icon={BellAlertIcon} size="lg" />}
isCompact
/>
)}
</BottomSheet>
)}
</Fragment>
);
}
-39
View File
@@ -1,39 +0,0 @@
import { defineTheme } from "@astryxdesign/core/theme";
import "@fontsource-variable/ibm-plex-sans";
import { defaultThemeSlug, themes } from "../src/astryx-themes";
export const theme = defineTheme({
name: "archie-reference",
extends: themes[defaultThemeSlug],
tokens: {
"--font-family-body": '"IBM Plex Sans Variable", system-ui, sans-serif',
"--font-family-heading": "var(--font-family-body)",
"--color-background-body": ["#f5f4f1", "#16171a"],
"--color-background-surface": ["#ffffff", "#1c1d21"],
"--color-background-card": "var(--color-background-surface)",
"--color-background-popover": ["#ffffff", "#202226"],
"--color-background-muted": ["#ecebe7", "#26282c"],
"--color-border": ["#dcdad4", "#313338"],
"--color-border-emphasized": ["#c7c4bd", "#3c3f45"],
"--color-text-primary": ["#1f1f1d", "#e8e6e1"],
"--color-text-secondary": ["#5c5a55", "#a6a39b"],
"--color-accent": "#2e795a",
"--color-text-accent": ["#0c6f4d", "#51a580"],
"--text-heading-1-size": "0.9375rem",
"--text-heading-2-size": "0.9375rem",
"--radius-element": "0.25rem",
"--radius-inner": "0.25rem",
"--radius-container": "0.375rem",
"--radius-page": "0.5rem",
"--color-text-warning": ["#8a5a12", "#d9a45b"],
},
components: {
badge: {
base: { borderRadius: "var(--radius-element)" },
"variant:warning": {
backgroundColor: "color-mix(in srgb, var(--color-text-warning) 10%, transparent)",
color: "var(--color-text-warning)",
},
},
},
});
-14
View File
@@ -1,14 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"types": ["vite/client"],
"strict": true,
"skipLibCheck": true,
"noEmit": true
},
"include": ["**/*.ts", "**/*.tsx"]
}
-12
View File
@@ -1,12 +0,0 @@
import { defineConfig } from "vite";
export default defineConfig({
cacheDir: "../node_modules/.cache/astryx-vite",
build: {
outDir: "../node_modules/.cache/astryx-reference",
emptyOutDir: true,
},
server: {
fs: { allow: [".."] },
},
});
+5 -12
View File
@@ -7,22 +7,15 @@
"dev": "vite",
"build": "vue-tsc -b && vite build",
"preview": "vite preview",
"reference": "vite astryx-reference --config astryx-reference/vite.config.ts --host 127.0.0.1",
"reference:build": "tsc -p astryx-reference && vite build astryx-reference --config astryx-reference/vite.config.ts",
"test": "node --test --experimental-strip-types test/*.test.ts",
"typecheck": "vue-tsc --build --force"
},
"dependencies": {
"@astryxdesign/core": "^0.7.16",
"@astryxdesign/theme-neutral": "^0.7.16",
"@fontsource-variable/ibm-plex-sans": "^5.3.0",
"@fontsource/ibm-plex-mono": "^5.3.0",
"@heroicons/react": "^2.2.0",
"@lucide/vue": "^1.61.0",
"@stylexjs/stylex": "^0.19.2",
"@tailwindcss/vite": "^4.3.3",
"@tanstack/vue-form": "^1.33.5",
"@uidotdev/usehooks": "^2.4.1",
"@vue-flow/background": "^1.3.2",
"@vue-flow/core": "^1.48.2",
"@vueuse/core": "^15.0.0",
@@ -30,23 +23,23 @@
"clsx": "^2.1.1",
"cn": "^0.5.1",
"pinia": "^4.0.3",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"reka-ui": "^2.10.5",
"remark-gfm": "^4.0.1",
"remark-parse": "^11.0.0",
"remark-rehype": "^11.1.2",
"shiki": "^4.5.0",
"tailwind-merge": "^3.7.0",
"tailwindcss": "^4.3.3",
"tw-animate-css": "^1.4.0",
"unified": "^11.0.5",
"vue": "^3.5.42",
"vue-router": "^5.3.1",
"vue-sonner": "^2.0.9",
"yaml": "^2.9.1"
},
"devDependencies": {
"@astryxdesign/cli": "^0.7.16",
"@types/hast": "^3.0.5",
"@types/node": "^26.6.4",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-vue": "^6.0.8",
"@vue/tsconfig": "^0.9.1",
"spotnote": "0.5.0",
+515 -1044
View File
File diff suppressed because it is too large. Load diff
-2
View File
@@ -1,4 +1,2 @@
allowBuilds:
'@astryxdesign/cli': true
'@astryxdesign/core': true
vue-demi: true
-15
View File
@@ -1,15 +0,0 @@
/**
* @generated by `astryx theme` — do not edit manually.
* @astryx-theme-record {"themes":{"neutral":"@astryxdesign/theme-neutral"},"defaultThemeSlug":"neutral"}
*/
import {neutralTheme as _astryxTheme0} from "@astryxdesign/theme-neutral/built";
import "@astryxdesign/theme-neutral/theme.css";
import "@astryxdesign/theme-neutral/fonts.css";
export const themes = {
"neutral": _astryxTheme0,
} as const;
export type ThemeSlug = keyof typeof themes;
export const defaultThemeSlug: keyof typeof themes = "neutral";
-37
View File
@@ -1,37 +0,0 @@
<script setup lang="ts">
import ChatTaskRef from "./ChatTaskRef.vue";
import type { ChatInline } from "./markdown";
/** One inline run: the spans of a paragraph, a heading or a table cell. */
defineProps<{ inline: ChatInline[] }>();
</script>
<template>
<template v-for="(span, i) in inline" :key="i">
<img
v-if="span.kind === 'image'"
:src="span.src"
:alt="span.alt"
loading="lazy"
class="my-1 block max-h-96 max-w-full cursor-pointer rounded-md border border-border bg-card object-contain"
/>
<del v-else-if="span.kind === 'del'">{{ span.text }}</del>
<strong v-else-if="span.kind === 'strong'">{{ span.text }}</strong>
<code
v-else-if="span.kind === 'code'"
class="rounded bg-foreground/10 px-1 py-0.5 font-mono text-[0.9em]"
>{{ span.text }}</code
>
<a
v-else-if="span.kind === 'link'"
:href="span.href"
target="_blank"
rel="noreferrer"
class="text-link underline-offset-4 hover:underline"
>{{ span.text }}</a
>
<ChatTaskRef v-else-if="span.kind === 'taskref'" :id="span.id" />
<em v-else-if="span.kind === 'em'">{{ span.text }}</em>
<template v-else>{{ span.text }}</template>
</template>
</template>
+63 -85
View File
@@ -1,100 +1,78 @@
<script setup lang="ts">
import { computed } from "vue";
import type { Element, ElementContent } from "hast";
import { computed, h, type VNodeChild } from "vue";
import CodeView from "@/base/CodeView.vue";
import ChatInline from "./ChatInline.vue";
import ChatTaskRef from "./ChatTaskRef.vue";
import { parseMarkdown } from "./markdown";
/**
* A reply rendered as semantic HTML: headings, lists, quotes, fenced code,
* tables, inline emphasis. The parse is a computed, so a reply that grows a
* token at a time re-renders from the text it now has rather than accumulating
* markup.
* A reply rendered as semantic HTML. The parse is a computed, so a reply that
* grows a token at a time re-renders from the text it now has rather than
* accumulating markup.
*/
const props = defineProps<{ text: string }>();
const blocks = computed(() => parseMarkdown(props.text));
const heading = "mt-1 mb-2 leading-tight font-semibold tracking-[-0.02em]";
const CLASSES: Record<string, string> = {
h1: `${heading} text-xl`,
h2: `${heading} text-lg`,
h3: `${heading} text-base`,
h4: `${heading} text-base`,
h5: `${heading} text-base`,
h6: `${heading} text-base`,
p: "mb-2.5 last:mb-0",
ul: "my-2.5 flex list-disc flex-col gap-1 pl-5",
ol: "my-2.5 flex list-decimal flex-col gap-1 pl-5",
blockquote: "my-2 border-l-[3px] border-primary pl-3 text-fg-muted",
table: "my-3 w-full border-collapse text-[0.92em]",
th: "border border-border bg-muted px-2 py-1.5 text-left font-semibold",
td: "border border-border px-2 py-1.5 text-left",
code: "rounded bg-foreground/10 px-1 py-0.5 font-mono text-[0.9em]",
a: "text-link underline-offset-4 hover:underline",
img: "my-1 block max-h-96 max-w-full rounded-md border border-border bg-card object-contain",
hr: "my-3 border-border",
};
function textOf(node: ElementContent): string {
if (node.type === "text") return node.value;
if (node.type === "element") return node.children.map(textOf).join("");
return "";
}
function codeBlock(pre: Element): VNodeChild {
const code = pre.children.find(
(child): child is Element => child.type === "element" && child.tagName === "code",
);
const classes = (code?.properties.className as string[] | undefined) ?? [];
const lang = classes.find((name) => name.startsWith("language-"))?.slice(9) ?? "";
return h(CodeView, {
code: textOf(code ?? pre).replace(/\n$/, ""),
lang,
class: "my-2",
});
}
function render(node: ElementContent, key: number): VNodeChild {
if (node.type === "text") return node.value;
if (node.type !== "element") return null;
if (node.tagName === "task-ref") return h(ChatTaskRef, { key, id: Number(node.properties.id) });
if (node.tagName === "pre") return codeBlock(node);
const { className, ...attrs } = node.properties;
const props: Record<string, unknown> = { key, ...attrs, class: CLASSES[node.tagName] ?? className };
if (node.tagName === "a") Object.assign(props, { target: "_blank", rel: "noreferrer" });
if (node.tagName === "img") props.loading = "lazy";
return h(node.tagName, props, node.children.map(render));
}
const content = computed(() =>
parseMarkdown(props.text).children.map((node, i) => render(node as ElementContent, i)),
);
</script>
<template>
<div class="[overflow-wrap:anywhere]">
<template v-for="(block, i) in blocks" :key="i">
<CodeView v-if="block.kind === 'pre'" :code="block.code" :lang="block.lang" class="my-2" />
<table
v-else-if="block.kind === 'table'"
class="my-3 w-full border-collapse text-[0.92em]"
>
<thead>
<tr>
<th
v-for="(cell, c) in block.head"
:key="c"
class="border border-border bg-muted px-2 py-1.5 text-left font-semibold"
>
<ChatInline :inline="cell" />
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, r) in block.rows" :key="r">
<td
v-for="(cell, c) in row"
:key="c"
class="border border-border px-2 py-1.5 text-left"
>
<ChatInline :inline="cell" />
</td>
</tr>
</tbody>
</table>
<blockquote
v-else-if="block.kind === 'blockquote'"
class="my-2 border-l-[3px] border-primary pl-3 text-fg-muted"
>
<ChatInline :inline="block.inline" />
</blockquote>
<h1
v-else-if="block.kind === 'h1'"
class="mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]"
>
<ChatInline :inline="block.inline" />
</h1>
<h2
v-else-if="block.kind === 'h2'"
class="mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]"
>
<ChatInline :inline="block.inline" />
</h2>
<h3
v-else-if="block.kind === 'h3'"
class="mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]"
>
<ChatInline :inline="block.inline" />
</h3>
<ul
v-else-if="block.kind === 'ul'"
class="my-2.5 flex list-disc flex-col gap-1 pl-5"
>
<li v-for="(item, n) in block.items" :key="n">
<ChatInline :inline="item" />
</li>
</ul>
<ol
v-else-if="block.kind === 'ol'"
class="my-2.5 flex list-decimal flex-col gap-1 pl-5"
>
<li v-for="(item, n) in block.items" :key="n">
<ChatInline :inline="item" />
</li>
</ol>
<p v-else-if="block.kind === 'p'" class="mb-2.5 last:mb-0">
<ChatInline :inline="block.inline" />
</p>
</template>
<component :is="() => content" />
</div>
</template>
+59 -191
View File
@@ -1,205 +1,73 @@
import type { Element, ElementContent, Root, RootContent } from "hast";
import remarkGfm from "remark-gfm";
import remarkParse from "remark-parse";
import remarkRehype from "remark-rehype";
import { unified } from "unified";
/**
* Chat markdown.
*
* Telegram-style rich blocks -- headings, lists, quotes, fenced code, tables,
* inline emphasis/links/images -- parsed into a tree that ChatMarkdown renders
* as semantic HTML. The parse is separate from the render so a streamed reply
* can be re-rendered on every frame without re-deciding what the text means.
* Model-written Markdown (GitHub flavoured) parsed into an HTML syntax tree
* that ChatMarkdown renders as Vue nodes. Raw HTML in the source is dropped,
* links and images keep only safe URLs, and a #N outside code and links
* becomes a `task-ref` element.
*/
/** One span of an inline run: what a paragraph's text breaks down into. */
export type ChatInline =
| { kind: "text"; text: string }
| { kind: "strong"; text: string }
| { kind: "em"; text: string }
| { kind: "del"; text: string }
| { kind: "code"; text: string }
| { kind: "link"; text: string; href: string }
| { kind: "taskref"; id: number }
| { kind: "image"; alt: string; src: string };
/** One block of the document. Lists carry their items as inline runs. */
export type ChatBlock =
| { kind: "p" | "h1" | "h2" | "h3" | "blockquote"; inline: ChatInline[] }
| { kind: "ul" | "ol"; items: ChatInline[][] }
| { kind: "pre"; code: string; lang: string }
| { kind: "table"; head: ChatInline[][]; rows: ChatInline[][][] };
const INLINE =
/(!\[[^\]]*\]\((?:https?:\/\/[^\s)]+|data:image\/[^\s)]+|\/[^\s)]+)\)|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\((?:https?:\/\/[^\s)]+|\/[^\s)]+)\)|\*[^*]+\*|_[^_]+_)/g;
const processor = unified().use(remarkParse).use(remarkGfm).use(remarkRehype);
// A #N the model wrote about a task. Not part of a word, entity or path.
const TASK_REF = /(?<![\w&#/])#(\d{1,9})(?!\w)/g;
const SAFE_HREF = /^(?:https?:\/\/|\/(?!\/)|#)/i;
const SAFE_SRC = /^(?:https?:\/\/|\/(?!\/)|data:image\/)/i;
// plainText splits a run of plain text around its task references.
function plainText(text: string): ChatInline[] {
const out: ChatInline[] = [];
let cursor = 0;
for (const match of text.matchAll(TASK_REF)) {
if (match.index > cursor)
out.push({ kind: "text", text: text.slice(cursor, match.index) });
out.push({ kind: "taskref", id: Number(match[1]) });
cursor = match.index + match[0].length;
export function parseMarkdown(text: string | null | undefined): Root {
const tree = processor.runSync(processor.parse(text ?? "")) as Root;
tree.children = clean(tree.children, false) as RootContent[];
return tree;
}
function clean(nodes: Array<RootContent | ElementContent>, literal: boolean): ElementContent[] {
const out: ElementContent[] = [];
for (const node of nodes) {
if (node.type === "text") {
out.push(...(literal ? [node] : taskRefs(node.value)));
} else if (node.type === "element") {
const kept = safeElement(node);
if (!kept) continue;
if (kept !== node) {
out.push(...clean(kept.children, literal));
continue;
}
const inner = literal || ["a", "code", "pre"].includes(node.tagName);
node.children = clean(node.children, inner);
out.push(node);
}
}
if (cursor < text.length) out.push({ kind: "text", text: text.slice(cursor) });
return out;
}
// inlineMarkdown returns the children of one line: plain text and the element
// each matched span becomes, in order.
function inlineMarkdown(text: string): ChatInline[] {
const children: ChatInline[] = [];
// safeElement returns the element, null to drop it, or a wrapper whose
// children replace a link with an unsafe URL.
function safeElement(node: Element): Element | null {
if (node.tagName === "img") {
return SAFE_SRC.test(String(node.properties.src ?? "")) ? node : null;
}
if (node.tagName === "a" && !SAFE_HREF.test(String(node.properties.href ?? ""))) {
return { ...node, tagName: "span", properties: {} };
}
return node;
}
function taskRefs(text: string): ElementContent[] {
const out: ElementContent[] = [];
let cursor = 0;
for (const match of String(text).matchAll(INLINE)) {
if (match.index > cursor)
children.push(...plainText(text.slice(cursor, match.index)));
const value = match[0];
if (value.startsWith("![")) {
const img = value.match(/^!\[([^\]]*)\]\((.+)\)$/);
if (img)
children.push({ kind: "image", alt: img[1] || "Image", src: img[2] });
} else if (value.startsWith("~~")) {
children.push({ kind: "del", text: value.slice(2, -2) });
} else if (value.startsWith("**") || value.startsWith("__")) {
children.push({ kind: "strong", text: value.slice(2, -2) });
} else if (value.startsWith("`")) {
children.push({ kind: "code", text: value.slice(1, -1) });
} else if (value.startsWith("[")) {
const link = value.match(
/^\[([^\]]+)\]\((https?:\/\/[^\s)]+|\/[^\s)]+)\)$/,
);
if (link) children.push({ kind: "link", text: link[1], href: link[2] });
} else {
children.push({ kind: "em", text: value.slice(1, -1) });
}
cursor = match.index + value.length;
}
if (cursor < text.length)
children.push(...plainText(text.slice(cursor)));
return children;
}
export function parseMarkdown(text: string | null | undefined): ChatBlock[] {
const blocks: ChatBlock[] = [];
const lines = String(text || "").split("\n");
let paragraph: string[] = [];
let list: { tag: "ul" | "ol"; items: string[] } | null = null;
let code: string[] | null = null;
let lang = "";
const flushParagraph = () => {
if (paragraph.length) {
blocks.push({ kind: "p", inline: inlineMarkdown(paragraph.join(" ")) });
paragraph = [];
}
};
const flushList = () => {
if (!list) return;
blocks.push({
kind: list.tag,
items: list.items.map((item) => inlineMarkdown(item)),
for (const match of text.matchAll(TASK_REF)) {
if (match.index > cursor) out.push({ type: "text", value: text.slice(cursor, match.index) });
out.push({
type: "element",
tagName: "task-ref",
properties: { id: match[1] },
children: [],
});
list = null;
};
for (let index = 0; index < lines.length; index++) {
const line = lines[index];
if (line.startsWith("```")) {
flushParagraph();
flushList();
if (code) {
blocks.push({ kind: "pre", code: code.join("\n"), lang });
code = null;
} else {
code = [];
lang = line.slice(3).trim().split(/\s/)[0];
}
continue;
}
if (code) {
code.push(line);
continue;
}
const headerCells = tableCells(line);
const separatorCells =
index + 1 < lines.length ? tableCells(lines[index + 1]) : null;
if (
headerCells &&
separatorCells &&
isTableSeparator(separatorCells) &&
headerCells.length === separatorCells.length
) {
flushParagraph();
flushList();
const rows: string[][] = [];
for (index += 2; index < lines.length; index++) {
const cells = tableCells(lines[index]);
if (!cells || cells.length !== headerCells.length) {
index--;
break;
}
rows.push(cells);
}
blocks.push({
kind: "table",
head: headerCells.map((cell) => inlineMarkdown(cell)),
rows: rows.map((row) => row.map((cell) => inlineMarkdown(cell))),
});
continue;
}
if (!line.trim()) {
flushParagraph();
flushList();
continue;
}
const heading = line.match(/^(#{1,3})\s+(.+)$/);
if (heading) {
flushParagraph();
flushList();
blocks.push({
kind: `h${heading[1].length}` as "h1" | "h2" | "h3",
inline: inlineMarkdown(heading[2]),
});
continue;
}
const bullet = line.match(/^\s*[-*]\s+(.+)$/);
const ordered = line.match(/^\s*\d+[.)]\s+(.+)$/);
if (bullet || ordered) {
flushParagraph();
const tag = ordered ? "ol" : "ul";
if (!list || list.tag !== tag) {
flushList();
list = { tag, items: [] };
}
list.items.push((bullet || ordered)![1]);
continue;
}
if (line.startsWith(">")) {
flushParagraph();
flushList();
blocks.push({
kind: "blockquote",
inline: inlineMarkdown(line.replace(/^>\s?/, "")),
});
continue;
}
paragraph.push(line);
cursor = match.index + match[0].length;
}
flushParagraph();
flushList();
if (code) blocks.push({ kind: "pre", code: code.join("\n"), lang });
return blocks;
}
function tableCells(line: string): string[] | null {
const value = String(line || "").trim();
if (!value.includes("|")) return null;
const unwrapped = value.replace(/^\|/, "").replace(/\|$/, "");
const cells = unwrapped.split("|").map((cell) => cell.trim());
return cells.length > 1 && cells.every((cell) => cell !== "") ? cells : null;
}
function isTableSeparator(cells: string[]): boolean {
return cells.every((cell) => /^:?-{3,}:?$/.test(cell));
if (cursor < text.length) out.push({ type: "text", value: text.slice(cursor) });
return out;
}
+36
View File
@@ -0,0 +1,36 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { Element, Root } from "hast";
import { parseMarkdown } from "../src/chat/markdown.ts";
function elements(tree: Root | Element, tag: string): Element[] {
const found: Element[] = [];
for (const child of tree.children) {
if (child.type !== "element") continue;
if (child.tagName === tag) found.push(child);
found.push(...elements(child, tag));
}
return found;
}
// Guards the chat renderer against script URLs and against #N task links
// appearing inside code or existing links.
test("parseMarkdown keeps only safe URLs and links task references in prose", () => {
const cases = [
{ md: "[x](javascript:alert(1))", tag: "a", count: 0 },
{ md: "[x](https://example.com)", tag: "a", count: 1 },
{ md: "[x](//evil.example)", tag: "a", count: 0 },
{ md: "![x](javascript:alert(1))", tag: "img", count: 0 },
{ md: "![x](data:image/png;base64,AA==)", tag: "img", count: 1 },
{ md: "<script>alert(1)</script>", tag: "script", count: 0 },
{ md: "See #12 and #13.", tag: "task-ref", count: 2 },
{ md: "`#12` and [#13](https://example.com)", tag: "task-ref", count: 0 },
{ md: "```\n#12\n```", tag: "task-ref", count: 0 },
{ md: "issue#12 and a/#12", tag: "task-ref", count: 0 },
];
for (const { md, tag, count } of cases) {
assert.equal(elements(parseMarkdown(md), tag).length, count, md);
}
});
+1 -1
View File
@@ -15,5 +15,5 @@
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
"include": ["src/**/*.ts", "src/**/*.vue"]
}