Chat
Chat composes unboxed agent answers, native activity disclosures, collapsible user bubbles, controlled waiting queues, and native or controlled composers.
@duskmoon-dev/components/chatUsage
When to use
- Use it to clarify state, metadata, content hierarchy, or loading without creating a new workflow.
- Pair it with semantic content so visual treatment never becomes the only source of meaning.
Implementation notes
Features
Focuses on status, metadata, empty/loading states, or content grouping without owning application state.
Uses DuskMoon tokens so the component follows the active docs theme.
Chat is most often configured through `placement`, `timeline`, `hover`, `targetId`.
Renders a start-aligned turn with structural slots
Feature Demos
Feature demos are authored for the component page, then supplemented with behavior scenarios from the component test coverage.
Run project tests Not executed
npm testnpm testWorking directory: /workspace/example
The host withdrew this request after the turn ended.
Open the original terminal client to answer this request.
Timeline Approvals and Composer Context
Host-owned approval requests stay next to tool calls in the agent timeline. Decisions remain pending until the demo host confirms them; expired requests and requests answered elsewhere keep their details without actions. The composer context shares the surface across compact and ghost variants and exposes a named goal action.
Source
import React, { useEffect, useRef, useState } from "react";
import { Chat, type ChatRequestState } from "@duskmoon-dev/components/chat";
/** The demo host, rather than Chat.Request, confirms each delayed decision. */
export function ChatRequestsPreview() {
const [state, setState] = useState<ChatRequestState>("pending");
const [pending, setPending] = useState(false);
const [value, setValue] = useState("");
const [sent, setSent] = useState("");
const [goal, setGoal] = useState(true);
const [compact, setCompact] = useState(true);
const [ghost, setGhost] = useState(false);
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
useEffect(() => () => clearTimeout(timer.current), []);
function decide(next: ChatRequestState) {
if (timer.current || state !== "pending") return;
setPending(true);
timer.current = setTimeout(() => {
setState(next);
setPending(false);
timer.current = undefined;
}, 650);
}
function reset() {
clearTimeout(timer.current);
timer.current = undefined;
setPending(false);
setState("pending");
}
return (
<div
data-chat-requests-demo
style={{ width: "min(44rem, 100%)", display: "grid", gap: "1rem" }}
>
<div
className="chat-demo-controls"
role="group"
aria-label="Demo controls"
>
<button type="button" className="btn btn-sm" onClick={reset}>
Reset approval request
</button>
<label>
<input
type="checkbox"
className="checkbox checkbox-sm"
checked={compact}
onChange={(event) => setCompact(event.currentTarget.checked)}
/>{" "}
Compact composer
</label>
<label>
<input
type="checkbox"
className="checkbox checkbox-sm"
checked={ghost}
onChange={(event) => setGhost(event.currentTarget.checked)}
/>{" "}
Ghost composer
</label>
</div>
<Chat.Agent>
<Chat.Header>Assistant</Chat.Header>
<Chat.Content>
I can check the changes. This command needs your approval first.
</Chat.Content>
<Chat.Tool status="pending" open>
<Chat.ToolHeader>
Run project tests <Chat.ToolStatus>Not executed</Chat.ToolStatus>
</Chat.ToolHeader>
<Chat.ToolCall>
<code>npm test</code>
</Chat.ToolCall>
<Chat.ToolResult>
This preview records a decision without executing the command.
</Chat.ToolResult>
</Chat.Tool>
<Chat.Request
title="Allow the assistant to run npm test?"
state={state}
pending={pending}
actions={[
{
id: "approve",
label: "Approve",
tone: "primary",
onSelect: () => decide("approved"),
},
{
id: "session",
label: "Approve for this session",
onSelect: () => decide("approved-for-session"),
},
{
id: "decline",
label: "Decline",
tone: "danger",
onSelect: () => decide("declined"),
},
]}
>
<pre aria-label="Requested command">
<code>npm test</code>
</pre>
<p>Working directory: /workspace/example</p>
</Chat.Request>
<Chat.Request
title="Apply changes to three files?"
state="expired"
explanation={
<p>The host withdrew this request after the turn ended.</p>
}
/>
<Chat.Request
title="Confirm the deployment?"
state="answer-elsewhere"
explanation={
<p>Open the original terminal client to answer this request.</p>
}
/>
</Chat.Agent>
<Chat.Composer
compact={compact}
className={ghost ? "chat-composer-ghost" : undefined}
value={value}
onValueChange={setValue}
onSubmit={(submission) => setSent(submission.value)}
textareaProps={{
"aria-label": "Approval demo message",
placeholder: "Keep writing while the host confirms a decision…",
}}
context={
<Chat.ComposerContext>
<Chat.ComposerContextItem icon={<span>⌘</span>}>
/workspace/example
</Chat.ComposerContextItem>
{goal ? (
<Chat.ComposerContextItem
action={{
label: "Clear active goal",
children: "×",
onClick: () => setGoal(false),
}}
>
Goal: verify the changes
</Chat.ComposerContextItem>
) : null}
<Chat.ComposerContextEnd>
<Chat.ComposerConnection
state="connected"
label="Local host connected"
/>
</Chat.ComposerContextEnd>
</Chat.ComposerContext>
}
/>
{sent ? (
<p role="status" aria-label="Demo submitted message">
Submitted: {sent}
</p>
) : null}
</div>
);
}
Loading rich editor. Your draft is preserved.
Review the latest changes.Export preserved draft
Host: idle; model: standard; waiting messages: 0.
Compact Composer and Model Menu
Core 1.21.5 composition using public ComposerSettings menus and an attached context bar with an Add menu, approval choice, model/effort menus and ready-image thumbnails. The primary action sends a draft or stops a running turn. Choices wait for the in-memory host to acknowledge them; this demo changes no real permissions.
Source
import React, { useId, useRef, useState, useSyncExternalStore } from "react";
import {
ChatAuthoritativeQueue,
Chat,
ComposerSettings,
ChatSessionComposer,
Button,
createComposerRecoveryOwner,
exportComposerText,
type ChatSessionComposerHandle,
type ComposerAttachmentOptions,
type ComposerCapabilities,
type ComposerCompletionProvider,
type ComposerDocument,
type ComposerProviderCandidate,
type ComposerDocumentUpdate,
type ComposerDraft,
type ComposerDraftAdapter,
type ComposerQueueEditorProps,
type ComposerQueueMutation,
type ComposerQueueMutationResult,
type ComposerQueueProjection,
type ComposerReceipt,
type ComposerRuntimeState,
type ComposerSessionHost,
type ComposerSettingRequest,
type ComposerSettingResult,
type ComposerSubmission,
} from "@duskmoon-dev/components";
import { RichChatComposer } from "@duskmoon-dev/components/chat/rich";
const scope = { contextKey: "demo-repository", conversationId: "demo-thread" };
const capabilities: ComposerCapabilities = {
protocolVersion: 1,
documentVersions: [1],
intents: ["send", "follow_up", "steer"],
commands: true,
attachments: true,
queue: { edit: "document", remove: true, promote: true },
durableRecovery: false,
};
type Admission = "accept" | "reject" | "unknown";
interface DemoState {
readonly runtime: ComposerRuntimeState;
readonly queue: ComposerQueueProjection;
readonly settingsRevision: number;
readonly model: string;
readonly effort: string;
readonly approval: string;
readonly events: readonly string[];
}
/** Abortable demo latency, not an upload or execution transport. */
function pause(signal: AbortSignal) {
return new Promise<void>((resolve, reject) => {
if (signal.aborted) {
reject(new DOMException("Cancelled", "AbortError"));
return;
}
const abort = () => {
clearTimeout(timer);
reject(new DOMException("Cancelled", "AbortError"));
};
const timer = setTimeout(() => {
signal.removeEventListener("abort", abort);
resolve();
}, 400);
signal.addEventListener("abort", abort, { once: true });
});
}
const settingsValues: Record<string, readonly string[]> = {
model: ["standard", "fast"],
effort: ["low", "medium", "high", "max"],
approval: ["ask", "auto", "full"],
};
/** Stable per-preview host: memory only, lost on page reload. */
function createDemoHost() {
const recovery = createComposerRecoveryOwner();
const receipts = new Map<string, ComposerReceipt>();
const drafts = new Map<string, ComposerDraft>();
const listeners = new Set<() => void>();
let admission: Admission = "accept";
let failPreparation = true;
let turnCounter = 0;
const preparations = new Set<string>();
let state: DemoState = {
runtime: { status: "idle" },
queue: { protocolVersion: 1, scope, revision: 0, items: [] },
settingsRevision: 0,
model: "standard",
effort: "medium",
approval: "ask",
events: [],
};
function publish(next: Partial<DemoState>, event?: string) {
state = {
...state,
...next,
events: event ? [...state.events.slice(-7), event] : state.events,
};
listeners.forEach((listener) => listener());
}
function accept(snapshot: ComposerSubmission): ComposerReceipt {
const identity = {
protocolVersion: 1 as const,
clientSubmissionId: snapshot.clientSubmissionId,
scope: snapshot.scope,
outcome: "accepted" as const,
};
if (snapshot.operation === "command") {
const result = { help: "Use /review for a prompt or @ for a reference." };
publish({}, `Command result: ${JSON.stringify(result)}`);
return { ...identity, operation: "command", result };
}
const text =
exportComposerText(snapshot.document) || "Attachment-only prompt";
if (snapshot.intent === "follow_up") {
const id = `waiting-${snapshot.clientSubmissionId}`;
const queue = {
...state.queue,
revision: state.queue.revision + 1,
items: [
...state.queue.items,
{
id,
document: snapshot.document,
attachments: snapshot.attachments,
capabilities: capabilities.queue,
},
],
};
publish({ queue }, `Follow-up admitted: ${text}`);
return {
...identity,
operation: "prompt",
delivery: "follow_up",
persistence: "volatile",
queueItemId: id,
queueRevision: queue.revision,
};
}
const turnId =
snapshot.intent === "steer"
? snapshot.targetTurnId
: `demo-turn-${++turnCounter}`;
publish(
{ runtime: { status: "running", activeTurnId: turnId } },
`${snapshot.intent === "steer" ? "Steer" : "Prompt"} admitted: ${text}`,
);
return {
...identity,
operation: "prompt",
delivery: snapshot.intent === "steer" ? "steer" : "immediate",
persistence: "volatile",
turnId,
};
}
const host: ComposerSessionHost = {
capabilities,
recovery,
commandOperation: (command) =>
command.commandId === "help" ? "command" : "prompt",
async submit(snapshot, signal) {
const mode = admission;
await pause(signal);
const existing = receipts.get(snapshot.clientSubmissionId);
if (existing) return existing;
if (mode === "reject") {
const receipt: ComposerReceipt = {
protocolVersion: 1,
scope: snapshot.scope,
clientSubmissionId: snapshot.clientSubmissionId,
operation: snapshot.operation,
outcome: "rejected",
error: {
code: "demo_rejection",
message:
"Demo host rejected this request. Edit or change the outcome and submit again.",
},
};
receipts.set(snapshot.clientSubmissionId, receipt);
publish({}, "Request rejected; draft retained.");
return receipt;
}
const receipt = accept(snapshot);
receipts.set(snapshot.clientSubmissionId, receipt);
if (mode !== "unknown") return receipt;
publish(
{},
"Demo response lost after admission. Check submission status to reconcile.",
);
return {
protocolVersion: 1,
scope: snapshot.scope,
clientSubmissionId: snapshot.clientSubmissionId,
operation: snapshot.operation,
outcome: "unknown",
error: {
code: "demo_response_lost",
message:
"Admission response was lost; do not assume failure or resend as a new request.",
},
};
},
async reconcile(snapshot, signal) {
await pause(signal);
const receipt = receipts.get(snapshot.clientSubmissionId);
publish(
{},
receipt
? `Reconciled: ${receipt.outcome}`
: "No admission record found; outcome remains unresolved.",
);
return receipt ?? { outcome: "not_found" };
},
async authorizeRetry() {
publish(
{},
"Demo host authorized retry using the original submission identity.",
);
return true;
},
};
const draftAdapter: ComposerDraftAdapter = {
async load({ scope: owner, draftKey, signal }) {
await pause(signal);
return drafts.get(JSON.stringify([owner, draftKey]));
},
async save(draft, signal) {
await pause(signal);
drafts.set(JSON.stringify([draft.scope, draft.draftKey]), draft);
publish({}, `Draft revision ${draft.revision} saved in demo memory.`);
},
};
const attachmentOptions: Omit<ComposerAttachmentOptions, "scope"> = {
policy: {
accept: "image/*,.txt,.md,.pdf",
maxFiles: 3,
maxFileBytes: 2 * 1024 * 1024,
},
async prepare(file, { entryId, signal, reportProgress }) {
reportProgress(0.25);
await pause(signal);
if (failPreparation && !preparations.has(entryId)) {
preparations.add(entryId);
throw new Error("Demo preparation failed once. Retry this attachment.");
}
reportProgress(1);
return {
providerId: "demo-files",
reference: { entryId, name: file.name },
};
},
// Omitted canRecover: saved occurrences require reattachment after remount.
};
return {
host,
draftAdapter,
attachmentOptions,
getSnapshot: () => state,
subscribe(listener: () => void) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
setAdmission(value: Admission) {
admission = value;
},
setFailPreparation(value: boolean) {
failPreparation = value;
},
start() {
publish(
{
runtime: {
status: "running",
activeTurnId: `demo-turn-${++turnCounter}`,
},
},
"Demo turn started; no model is executing.",
);
},
stop() {
publish(
{ runtime: { status: "idle" } },
"Stop acknowledged by demo host; queued messages remain waiting.",
);
},
invoke() {
publish(
{},
"Provider invocation executed independently of prompt admission.",
);
},
async mutate(
request: ComposerQueueMutation,
signal: AbortSignal,
): Promise<ComposerQueueMutationResult> {
await pause(signal);
const item = state.queue.items.find(
(entry) => entry.id === request.itemId,
);
if (
request.expectedRevision !== state.queue.revision ||
!item ||
(request.operation === "promote" &&
request.targetTurnId !== state.runtime.activeTurnId)
) {
return {
requestId: request.requestId,
outcome: "rejected",
projection: state.queue,
error: {
code: "queue_conflict",
message:
"Demo queue changed; use the canonical projection and try again.",
},
};
}
const queue: ComposerQueueProjection = {
...state.queue,
revision: state.queue.revision + 1,
items:
request.operation === "edit"
? state.queue.items.map((entry) =>
entry.id === item.id
? { ...entry, document: request.document }
: entry,
)
: state.queue.items.filter((entry) => entry.id !== item.id),
};
publish(
{ queue },
`Queue ${request.operation} acknowledged for ${request.itemId}.`,
);
return {
requestId: request.requestId,
outcome: "accepted",
projection: queue,
};
},
applyProjection(queue: ComposerQueueProjection) {
if (queue.revision >= state.queue.revision) publish({ queue });
},
async requestSetting(
request: ComposerSettingRequest,
signal: AbortSignal,
): Promise<ComposerSettingResult> {
await pause(signal);
const identity = {
requestId: request.requestId,
scopeKey: request.scopeKey,
settingId: request.settingId,
revision: state.settingsRevision + 1,
};
if (
request.expectedRevision !== state.settingsRevision ||
request.value === "restricted" ||
!(settingsValues[request.settingId] ?? []).includes(request.value)
) {
return {
...identity,
outcome: "rejected",
message:
"Demo host declined this model; the current selection is retained.",
};
}
return { ...identity, outcome: "accepted", value: request.value };
},
acknowledgeSetting(result: ComposerSettingResult) {
publish(
{
settingsRevision: result.revision,
...(result.outcome === "accepted"
? { [result.settingId]: result.value }
: {}),
},
`${result.settingId} change ${result.outcome}.`,
);
},
};
}
const providers: readonly ComposerCompletionProvider[] = [
{
providerId: "demo-files",
label: "Repository references",
icon: <DemoIcon name="reference" />,
sourceLabel: "Demo",
trigger: { text: "@", position: "word" },
async query(request, signal) {
await pause(signal);
return {
request,
candidates: (
[
{
id: "readme",
label: "README.md",
description: "Demo reference, resolved by the host",
action: {
type: "insert",
content: [
{
type: "reference",
nodeId: `${request.requestId}-reference`,
providerId: "demo-files",
refId: "README.md",
label: "README.md",
plainText: "@README.md",
},
],
},
},
{
id: "private",
label: "Private document",
disabledReason: "Host has not granted access",
action: { type: "insert", content: [] },
},
] satisfies ComposerProviderCandidate[]
).filter((candidate) =>
candidate.label.toLowerCase().includes(request.query.toLowerCase()),
),
};
},
},
{
providerId: "demo-commands",
label: "Commands",
icon: <DemoIcon name="command" />,
sourceLabel: "Demo",
trigger: { text: "/", position: "leading" },
async query(request, signal) {
await pause(signal);
return {
request,
candidates: (
[
{
id: "help",
label: "/help",
description: "Show available commands",
action: {
type: "insert",
command: { providerId: "demo-commands", commandId: "help" },
content: [{ type: "text", text: "/help " }],
},
},
{
id: "review",
label: "/review",
description: "Review the current changes",
action: {
type: "insert",
command: { providerId: "demo-commands", commandId: "review" },
content: [{ type: "text", text: "/review " }],
},
},
{
id: "inspect",
label: "/inspect",
description: "Inspect the current session",
action: {
type: "invoke",
command: { providerId: "demo-commands", commandId: "inspect" },
},
},
] satisfies ComposerProviderCandidate[]
).filter((candidate) => candidate.label.includes(request.query)),
};
},
},
{
providerId: "demo-skills",
label: "Skills",
icon: <DemoIcon name="skill" />,
sourceLabel: "Demo",
trigger: { text: "/", position: "leading" },
async query(request, signal) {
await pause(signal);
return {
request,
candidates: (
[
{
id: "summarize",
label: "/summarize",
description: "Summarize changes and completed checks",
action: {
type: "insert",
content: [
{
type: "text",
text: "Summarize the changes and list the checks that passed. ",
},
],
},
},
] satisfies ComposerProviderCandidate[]
).filter((candidate) => candidate.label.includes(request.query)),
};
},
},
];
const demoIcons = {
start: "m8 5 11 7-11 7Z",
remount: "M3 11a9 9 0 1 1 2.6 7.4M3 4v7h7",
clear: "M3 6h18M9 6V3h6v3M5 6l1 15h12l1-15M10 10v7M14 10v7",
reference: "M14 2H6v20h12V6ZM14 2v5h5M8 12h8M8 16h5",
quote: "M3 6h7v7H3ZM14 6h7v7h-7ZM10 13c0 4-2 6-5 6M21 13c0 4-2 6-5 6",
command: "m4 6 6 6-6 6M13 18h7",
skill: "m12 3 8 4v10l-8 4-8-4V7ZM4 7l8 4 8-4M12 11v10",
review: "m15 4 5 5-11 11H4v-5ZM13 6l5 5",
settings: "M4 7h16M4 17h16M8 4v6M16 14v6",
help: "M12 8h.01M12 12v5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z",
inspect: "M4 4h16v16H4ZM7 8l3 3-3 3M12 15h5",
save: "M5 3h12l4 4v14H3V3ZM7 3v6h10V3M7 21v-8h10v8",
cancel: "m6 6 12 12M6 18 18 6",
};
type DemoIconName = keyof typeof demoIcons;
function DemoIcon({ name }: { name: DemoIconName }) {
return (
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
>
<path d={demoIcons[name]} />
</svg>
);
}
function DemoAction({
label,
icon,
...props
}: {
label: string;
icon: DemoIconName;
} & React.ComponentProps<typeof Button>) {
return (
<Button
type="button"
appearance="ghost"
color="base"
size="sm"
shape="circle"
{...props}
aria-label={label}
title={label}
>
<DemoIcon name={icon} />
</Button>
);
}
/** Core owns menu sizing/placement; the native Popover owns dismissal and focus. */
function DemoPopover({
label,
icon,
children,
}: {
label: string;
icon: DemoIconName;
children: React.ReactNode;
}) {
const id = useId();
const anchorName = `--demo-${id.replace(/[^a-zA-Z0-9_-]/g, "")}`;
const [open, setOpen] = useState(false);
return (
<>
<button
type="button"
className="popover-menu-item"
aria-label={label}
title={label}
popoverTarget={id}
aria-controls={id}
aria-expanded={open}
style={{ anchorName } as React.CSSProperties}
>
<DemoIcon name={icon} />
<span>{label}</span>
</button>
<div
id={id}
popover="auto"
className="popover popover-menu chat-composer-menu chat-demo-popover"
role="group"
aria-label={label}
style={{ positionAnchor: anchorName } as React.CSSProperties}
onToggle={(event) =>
setOpen(event.currentTarget.matches(":popover-open"))
}
>
{children}
</div>
</>
);
}
const models = [
["standard", "Standard demo model", "Standard"],
["fast", "Fast demo model", "Fast"],
["restricted", "Restricted model (host rejects)", "Restricted"],
] as const;
const efforts = ["low", "medium", "high", "max"];
const effortLabels = ["Low", "Medium", "High", "Max"];
const approvals = [
["ask", "Ask for approval", "Review each action before it runs."],
["auto", "Approve for me", "Request review for sensitive actions."],
["full", "Full access", "Allow actions without an approval prompt."],
] as const;
const menuGroups = [
{
id: "approval",
label: "Approval mode",
settingIds: ["approval"],
appearance: "access" as const,
},
{
id: "model",
label: "Model settings",
settingIds: ["model", "effort"],
nestedSettingIds: ["model"],
appearance: "model" as const,
},
];
function QueueDocumentEditor({
value,
onChange,
onSave,
onCancel,
pending,
}: ComposerQueueEditorProps) {
return (
<>
{value.content.map((node, index) =>
node.type === "text" ? (
<textarea
key={index}
className="chat-composer-input"
aria-label={`Queued text ${index + 1}`}
value={node.text}
disabled={pending}
onChange={(event) =>
onChange({
...value,
content: value.content.map((entry, at) =>
at === index
? { type: "text", text: event.currentTarget.value }
: entry,
),
})
}
/>
) : (
<p key={node.nodeId}>
{node.type === "reference" ? node.label : node.text}
</p>
),
)}
<DemoAction
label="Save queued document"
icon="save"
disabled={pending}
onClick={onSave}
/>
<DemoAction
label="Cancel"
icon="cancel"
disabled={pending}
onClick={onCancel}
/>
</>
);
}
function SessionDemo({ rich }: { rich: boolean }) {
const [demo] = useState(createDemoHost);
const state = useSyncExternalStore(
demo.subscribe,
demo.getSnapshot,
demo.getSnapshot,
);
const [value, setValue] = useState<ComposerDocumentUpdate>({
document: {
schemaVersion: 1,
content: [{ type: "text", text: "Review the latest changes." }],
},
revision: 0,
origin: "replace",
originId: "demo-initial",
});
const [mount, setMount] = useState(0);
const [admission, setAdmission] = useState<Admission>("accept");
const [intent, setIntent] = useState<"follow_up" | "steer">("follow_up");
const [failPreparation, setFailPreparation] = useState(true);
const editor = useRef<ChatSessionComposerHandle>(null);
const occurrence = useRef(0);
const Composer = rich ? RichChatComposer : ChatSessionComposer;
function replace(document: ComposerDocument) {
setValue((current) => ({
document,
revision: current.revision + 1,
origin: "replace",
originId: `demo-replace-${++occurrence.current}`,
}));
}
const addMenu = (
<>
<DemoPopover label="Demo controls" icon="settings">
<div className="chat-demo-controls">
<DemoAction
label="Start demo turn"
icon="start"
onClick={demo.start}
/>
</div>
<div className="chat-demo-fields">
<label>
Admission outcome{" "}
<select
className="select select-sm"
value={admission}
onChange={(event) => {
const next = event.currentTarget.value as Admission;
setAdmission(next);
demo.setAdmission(next);
}}
>
<option value="accept">Accept</option>
<option value="reject">Reject</option>
<option value="unknown">Lose response after admission</option>
</select>
</label>
<label>
Running intent{" "}
<select
className="select select-sm"
value={intent}
onChange={(event) =>
setIntent(event.currentTarget.value as "follow_up" | "steer")
}
>
<option value="follow_up">Follow-up</option>
<option value="steer">Steer active turn</option>
</select>
</label>
<label>
<input
type="checkbox"
className="checkbox checkbox-sm"
checked={failPreparation}
onChange={(event) => {
setFailPreparation(event.currentTarget.checked);
demo.setFailPreparation(event.currentTarget.checked);
}}
/>{" "}
Fail first preparation
</label>
</div>
<div className="chat-demo-controls">
<DemoAction
label="Remount editor"
icon="remount"
onClick={() => setMount((current) => current + 1)}
/>
<DemoAction
label="Replace with empty document"
icon="clear"
onClick={() =>
replace({
schemaVersion: 1,
content: [{ type: "text", text: "" }],
})
}
/>
{rich ? (
<>
<DemoAction
label="Insert reference"
icon="reference"
onClick={() =>
editor.current?.insertReference({
type: "reference",
nodeId: `demo-ref-${++occurrence.current}`,
providerId: "demo-files",
refId: "README.md",
label: "README.md",
plainText: "@README.md",
})
}
/>
<DemoAction
label="Insert quote"
icon="quote"
onClick={() =>
editor.current?.insertQuote({
type: "quote",
nodeId: `demo-quote-${++occurrence.current}`,
text: "Keep user edits while admission is pending.",
source: {
messageId: "demo-message",
conversationId: scope.conversationId,
label: "Earlier assistant reply",
},
})
}
/>
<DemoAction
label="Claim /help command"
icon="command"
onClick={() =>
editor.current?.claimCommand(
{ providerId: "demo-commands", commandId: "help" },
"/help",
)
}
/>
<DemoAction
label="Claim /review prompt"
icon="review"
onClick={() =>
editor.current?.claimCommand(
{ providerId: "demo-commands", commandId: "review" },
"/review",
)
}
/>
</>
) : null}
</div>
</DemoPopover>
<DemoPopover label="Composer help" icon="help">
<div className="popover-body">
<p>
Cmd/Ctrl+Enter sends; Enter adds a line. Type @ for references or /
for commands and editable skills.
</p>
<p>
Add up to three images, .txt, .md or .pdf files, each at most 2 MiB.
If preparation fails, use Retry.
</p>
<p>
Save a draft before remounting to try restoration; files then
require reattachment. Stop is independent of sending and
preparation.
</p>
<p>
This interactive demo keeps files, drafts and recovery in memory. It
has no backend; reloading the page discards its state.
</p>
</div>
</DemoPopover>
<DemoPopover label="Inspect demo state" icon="inspect">
<details>
<summary>Current portable document</summary>
<pre aria-label="Current portable document">
{JSON.stringify(value.document, null, 2)}
</pre>
</details>
<p>
Host: {state.runtime.status}; model: {state.model}; queue revision:{" "}
{state.queue.revision}.
</p>
<div aria-label="Demo host events" role="log" aria-live="off">
{state.events.length ? (
state.events.map((event, index) => (
<p key={`${index}-${event}`}>{event}</p>
))
) : (
<p>No events yet.</p>
)}
</div>
</DemoPopover>
</>
);
return (
<div
className="chat-demo chat-session-demo"
data-chat-session-demo={rich ? "rich" : "plain"}
>
<p className="sr-only" role="status">
Host: {state.runtime.status}; model: {state.model}; queue revision:{" "}
{state.queue.revision}.
</p>
<ChatAuthoritativeQueue
projection={state.queue}
capabilities={capabilities.queue}
targetTurnId={state.runtime.activeTurnId}
onMutation={demo.mutate}
onProjection={demo.applyProjection}
renderDocumentEditor={(props) => <QueueDocumentEditor {...props} />}
/>
<Composer
compact
addMenu={addMenu}
attachLabel="Add files and more"
className="chat-composer-ghost"
key={mount}
ref={editor}
value={value}
onDocumentChange={setValue}
scope={scope}
draftKey="demo-draft"
host={demo.host}
runtime={state.runtime}
policy={{ runningIntent: intent }}
options={{
model: state.model,
effort: state.effort,
approval: state.approval,
}}
draftAdapter={demo.draftAdapter}
attachmentOptions={demo.attachmentOptions}
providers={providers}
onProviderInvoke={demo.invoke}
onStop={demo.stop}
context={
<Chat.ComposerContext>
<Chat.ComposerContextItem icon={<DemoIcon name="reference" />}>
demo-repository
</Chat.ComposerContextItem>
<Chat.ComposerContextEnd>
<Chat.ComposerConnection state="connected" />
</Chat.ComposerContextEnd>
</Chat.ComposerContext>
}
allowAttachmentOnly
label={rich ? "Rich demo message" : "Semantic demo message"}
>
<ComposerSettings
variant="menu"
groups={menuGroups}
scopeKey={scope.conversationId}
revision={state.settingsRevision}
settings={[
{
id: "approval",
label: "Approval mode",
value: state.approval,
choices: approvals.map(([value, label, description]) => ({
value,
label,
description,
tone: value === "full" ? ("warning" as const) : undefined,
})),
},
{
id: "model",
label: "Model",
value: state.model,
choices: models.map(([value, label]) => ({ value, label })),
},
{
id: "effort",
label: "Reasoning effort",
value: state.effort,
ordered: true,
defaultValue: "medium",
choices: efforts.map((value, index) => ({
value,
label: effortLabels[index],
})),
},
]}
onRequest={demo.requestSetting}
onAcknowledged={demo.acknowledgeSetting}
/>
</Composer>
</div>
);
}
export function SemanticComposerPreview() {
return <SessionDemo rich={false} />;
}
export function RichComposerPreview() {
return <SessionDemo rich />;
}
/** Focused Core 1.21.1 composition; settings still require host acknowledgment. */
export function CompactComposerPreview() {
const [demo] = useState(() => {
const host = createDemoHost();
host.setFailPreparation(false);
return host;
});
const state = useSyncExternalStore(
demo.subscribe,
demo.getSnapshot,
demo.getSnapshot,
);
const [rich, setRich] = useState(true);
const [value, setValue] = useState<ComposerDocumentUpdate>({
document: {
schemaVersion: 1,
content: [{ type: "text", text: "Review the latest changes." }],
},
revision: 0,
origin: "replace",
originId: "compact-initial",
});
const Composer = rich ? RichChatComposer : ChatSessionComposer;
return (
<div className="chat-demo chat-session-demo" data-chat-compact-demo>
<Composer
compact
attachLabel="Add files and more"
addMenu={
<>
<DemoPopover label="Composer help" icon="help">
<div className="popover-body">
<p>
Cmd/Ctrl+Enter sends; Enter adds a line. Add files with +;
images become thumbnails after preparation. Type / to choose
skills or commands, or @ for repository references.
</p>
<p>
Choose a model and reasoning effort from the model menu.
Switch editors from Add. Stop and follow-up submission are
independent.
</p>
<p>
This in-memory demo applies model choices only after the host
acknowledges them.
</p>
</div>
</DemoPopover>
<label className="chat-composer-menu-field">
<span>
<input
type="checkbox"
className="checkbox checkbox-sm"
checked={rich}
onChange={(event) => setRich(event.currentTarget.checked)}
/>{" "}
Use rich editor
</span>
</label>
</>
}
className="chat-composer-ghost"
value={value}
onDocumentChange={setValue}
scope={scope}
draftKey="compact-demo"
host={demo.host}
runtime={state.runtime}
attachmentOptions={demo.attachmentOptions}
providers={providers}
onProviderInvoke={demo.invoke}
options={{
model: state.model,
effort: state.effort,
approval: state.approval,
}}
onStop={demo.stop}
context={
<Chat.ComposerContext>
<Chat.ComposerContextItem icon={<DemoIcon name="reference" />}>
demo-repository
</Chat.ComposerContextItem>
<Chat.ComposerContextEnd>
<Chat.ComposerConnection state="connected" />
</Chat.ComposerContextEnd>
</Chat.ComposerContext>
}
allowAttachmentOnly
label="Compact demo message"
>
<ComposerSettings
variant="menu"
groups={menuGroups}
scopeKey={scope.conversationId}
revision={state.settingsRevision}
settings={[
{
id: "approval",
label: "Approval mode",
value: state.approval,
choices: approvals.map(([value, label, description]) => ({
value,
label,
description,
tone: value === "full" ? ("warning" as const) : undefined,
})),
},
{
id: "model",
label: "Model",
value: state.model,
choices: models.map(([value, label]) => ({ value, label })),
},
{
id: "effort",
label: "Reasoning effort",
value: state.effort,
ordered: true,
defaultValue: "medium",
choices: efforts.map((value, index) => ({
value,
label: effortLabels[index],
})),
},
]}
onRequest={demo.requestSetting}
onAcknowledged={demo.acknowledgeSetting}
/>
</Composer>
<p className="sr-only" role="status" aria-label="Compact host state">
Host: {state.runtime.status}; model: {state.model}; waiting messages:{" "}
{state.queue.items.length}.
{state.events.at(-1) ? ` ${state.events.at(-1)}` : ""}
</p>
</div>
);
}
Host: idle; model: standard; queue revision: 0.
Waiting messages
0 queuedSemantic Composer and Recovery
Controlled semantic plain editor with a typed in-memory host. Use the Add menu for explicit draft save, editor remount and demo controls. Try admission recovery, attachment preparation retry and follow-ups during a running turn. The existing string-based Composer remains available below.
Source
import React, { useId, useRef, useState, useSyncExternalStore } from "react";
import {
ChatAuthoritativeQueue,
Chat,
ComposerSettings,
ChatSessionComposer,
Button,
createComposerRecoveryOwner,
exportComposerText,
type ChatSessionComposerHandle,
type ComposerAttachmentOptions,
type ComposerCapabilities,
type ComposerCompletionProvider,
type ComposerDocument,
type ComposerProviderCandidate,
type ComposerDocumentUpdate,
type ComposerDraft,
type ComposerDraftAdapter,
type ComposerQueueEditorProps,
type ComposerQueueMutation,
type ComposerQueueMutationResult,
type ComposerQueueProjection,
type ComposerReceipt,
type ComposerRuntimeState,
type ComposerSessionHost,
type ComposerSettingRequest,
type ComposerSettingResult,
type ComposerSubmission,
} from "@duskmoon-dev/components";
import { RichChatComposer } from "@duskmoon-dev/components/chat/rich";
const scope = { contextKey: "demo-repository", conversationId: "demo-thread" };
const capabilities: ComposerCapabilities = {
protocolVersion: 1,
documentVersions: [1],
intents: ["send", "follow_up", "steer"],
commands: true,
attachments: true,
queue: { edit: "document", remove: true, promote: true },
durableRecovery: false,
};
type Admission = "accept" | "reject" | "unknown";
interface DemoState {
readonly runtime: ComposerRuntimeState;
readonly queue: ComposerQueueProjection;
readonly settingsRevision: number;
readonly model: string;
readonly effort: string;
readonly approval: string;
readonly events: readonly string[];
}
/** Abortable demo latency, not an upload or execution transport. */
function pause(signal: AbortSignal) {
return new Promise<void>((resolve, reject) => {
if (signal.aborted) {
reject(new DOMException("Cancelled", "AbortError"));
return;
}
const abort = () => {
clearTimeout(timer);
reject(new DOMException("Cancelled", "AbortError"));
};
const timer = setTimeout(() => {
signal.removeEventListener("abort", abort);
resolve();
}, 400);
signal.addEventListener("abort", abort, { once: true });
});
}
const settingsValues: Record<string, readonly string[]> = {
model: ["standard", "fast"],
effort: ["low", "medium", "high", "max"],
approval: ["ask", "auto", "full"],
};
/** Stable per-preview host: memory only, lost on page reload. */
function createDemoHost() {
const recovery = createComposerRecoveryOwner();
const receipts = new Map<string, ComposerReceipt>();
const drafts = new Map<string, ComposerDraft>();
const listeners = new Set<() => void>();
let admission: Admission = "accept";
let failPreparation = true;
let turnCounter = 0;
const preparations = new Set<string>();
let state: DemoState = {
runtime: { status: "idle" },
queue: { protocolVersion: 1, scope, revision: 0, items: [] },
settingsRevision: 0,
model: "standard",
effort: "medium",
approval: "ask",
events: [],
};
function publish(next: Partial<DemoState>, event?: string) {
state = {
...state,
...next,
events: event ? [...state.events.slice(-7), event] : state.events,
};
listeners.forEach((listener) => listener());
}
function accept(snapshot: ComposerSubmission): ComposerReceipt {
const identity = {
protocolVersion: 1 as const,
clientSubmissionId: snapshot.clientSubmissionId,
scope: snapshot.scope,
outcome: "accepted" as const,
};
if (snapshot.operation === "command") {
const result = { help: "Use /review for a prompt or @ for a reference." };
publish({}, `Command result: ${JSON.stringify(result)}`);
return { ...identity, operation: "command", result };
}
const text =
exportComposerText(snapshot.document) || "Attachment-only prompt";
if (snapshot.intent === "follow_up") {
const id = `waiting-${snapshot.clientSubmissionId}`;
const queue = {
...state.queue,
revision: state.queue.revision + 1,
items: [
...state.queue.items,
{
id,
document: snapshot.document,
attachments: snapshot.attachments,
capabilities: capabilities.queue,
},
],
};
publish({ queue }, `Follow-up admitted: ${text}`);
return {
...identity,
operation: "prompt",
delivery: "follow_up",
persistence: "volatile",
queueItemId: id,
queueRevision: queue.revision,
};
}
const turnId =
snapshot.intent === "steer"
? snapshot.targetTurnId
: `demo-turn-${++turnCounter}`;
publish(
{ runtime: { status: "running", activeTurnId: turnId } },
`${snapshot.intent === "steer" ? "Steer" : "Prompt"} admitted: ${text}`,
);
return {
...identity,
operation: "prompt",
delivery: snapshot.intent === "steer" ? "steer" : "immediate",
persistence: "volatile",
turnId,
};
}
const host: ComposerSessionHost = {
capabilities,
recovery,
commandOperation: (command) =>
command.commandId === "help" ? "command" : "prompt",
async submit(snapshot, signal) {
const mode = admission;
await pause(signal);
const existing = receipts.get(snapshot.clientSubmissionId);
if (existing) return existing;
if (mode === "reject") {
const receipt: ComposerReceipt = {
protocolVersion: 1,
scope: snapshot.scope,
clientSubmissionId: snapshot.clientSubmissionId,
operation: snapshot.operation,
outcome: "rejected",
error: {
code: "demo_rejection",
message:
"Demo host rejected this request. Edit or change the outcome and submit again.",
},
};
receipts.set(snapshot.clientSubmissionId, receipt);
publish({}, "Request rejected; draft retained.");
return receipt;
}
const receipt = accept(snapshot);
receipts.set(snapshot.clientSubmissionId, receipt);
if (mode !== "unknown") return receipt;
publish(
{},
"Demo response lost after admission. Check submission status to reconcile.",
);
return {
protocolVersion: 1,
scope: snapshot.scope,
clientSubmissionId: snapshot.clientSubmissionId,
operation: snapshot.operation,
outcome: "unknown",
error: {
code: "demo_response_lost",
message:
"Admission response was lost; do not assume failure or resend as a new request.",
},
};
},
async reconcile(snapshot, signal) {
await pause(signal);
const receipt = receipts.get(snapshot.clientSubmissionId);
publish(
{},
receipt
? `Reconciled: ${receipt.outcome}`
: "No admission record found; outcome remains unresolved.",
);
return receipt ?? { outcome: "not_found" };
},
async authorizeRetry() {
publish(
{},
"Demo host authorized retry using the original submission identity.",
);
return true;
},
};
const draftAdapter: ComposerDraftAdapter = {
async load({ scope: owner, draftKey, signal }) {
await pause(signal);
return drafts.get(JSON.stringify([owner, draftKey]));
},
async save(draft, signal) {
await pause(signal);
drafts.set(JSON.stringify([draft.scope, draft.draftKey]), draft);
publish({}, `Draft revision ${draft.revision} saved in demo memory.`);
},
};
const attachmentOptions: Omit<ComposerAttachmentOptions, "scope"> = {
policy: {
accept: "image/*,.txt,.md,.pdf",
maxFiles: 3,
maxFileBytes: 2 * 1024 * 1024,
},
async prepare(file, { entryId, signal, reportProgress }) {
reportProgress(0.25);
await pause(signal);
if (failPreparation && !preparations.has(entryId)) {
preparations.add(entryId);
throw new Error("Demo preparation failed once. Retry this attachment.");
}
reportProgress(1);
return {
providerId: "demo-files",
reference: { entryId, name: file.name },
};
},
// Omitted canRecover: saved occurrences require reattachment after remount.
};
return {
host,
draftAdapter,
attachmentOptions,
getSnapshot: () => state,
subscribe(listener: () => void) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
setAdmission(value: Admission) {
admission = value;
},
setFailPreparation(value: boolean) {
failPreparation = value;
},
start() {
publish(
{
runtime: {
status: "running",
activeTurnId: `demo-turn-${++turnCounter}`,
},
},
"Demo turn started; no model is executing.",
);
},
stop() {
publish(
{ runtime: { status: "idle" } },
"Stop acknowledged by demo host; queued messages remain waiting.",
);
},
invoke() {
publish(
{},
"Provider invocation executed independently of prompt admission.",
);
},
async mutate(
request: ComposerQueueMutation,
signal: AbortSignal,
): Promise<ComposerQueueMutationResult> {
await pause(signal);
const item = state.queue.items.find(
(entry) => entry.id === request.itemId,
);
if (
request.expectedRevision !== state.queue.revision ||
!item ||
(request.operation === "promote" &&
request.targetTurnId !== state.runtime.activeTurnId)
) {
return {
requestId: request.requestId,
outcome: "rejected",
projection: state.queue,
error: {
code: "queue_conflict",
message:
"Demo queue changed; use the canonical projection and try again.",
},
};
}
const queue: ComposerQueueProjection = {
...state.queue,
revision: state.queue.revision + 1,
items:
request.operation === "edit"
? state.queue.items.map((entry) =>
entry.id === item.id
? { ...entry, document: request.document }
: entry,
)
: state.queue.items.filter((entry) => entry.id !== item.id),
};
publish(
{ queue },
`Queue ${request.operation} acknowledged for ${request.itemId}.`,
);
return {
requestId: request.requestId,
outcome: "accepted",
projection: queue,
};
},
applyProjection(queue: ComposerQueueProjection) {
if (queue.revision >= state.queue.revision) publish({ queue });
},
async requestSetting(
request: ComposerSettingRequest,
signal: AbortSignal,
): Promise<ComposerSettingResult> {
await pause(signal);
const identity = {
requestId: request.requestId,
scopeKey: request.scopeKey,
settingId: request.settingId,
revision: state.settingsRevision + 1,
};
if (
request.expectedRevision !== state.settingsRevision ||
request.value === "restricted" ||
!(settingsValues[request.settingId] ?? []).includes(request.value)
) {
return {
...identity,
outcome: "rejected",
message:
"Demo host declined this model; the current selection is retained.",
};
}
return { ...identity, outcome: "accepted", value: request.value };
},
acknowledgeSetting(result: ComposerSettingResult) {
publish(
{
settingsRevision: result.revision,
...(result.outcome === "accepted"
? { [result.settingId]: result.value }
: {}),
},
`${result.settingId} change ${result.outcome}.`,
);
},
};
}
const providers: readonly ComposerCompletionProvider[] = [
{
providerId: "demo-files",
label: "Repository references",
icon: <DemoIcon name="reference" />,
sourceLabel: "Demo",
trigger: { text: "@", position: "word" },
async query(request, signal) {
await pause(signal);
return {
request,
candidates: (
[
{
id: "readme",
label: "README.md",
description: "Demo reference, resolved by the host",
action: {
type: "insert",
content: [
{
type: "reference",
nodeId: `${request.requestId}-reference`,
providerId: "demo-files",
refId: "README.md",
label: "README.md",
plainText: "@README.md",
},
],
},
},
{
id: "private",
label: "Private document",
disabledReason: "Host has not granted access",
action: { type: "insert", content: [] },
},
] satisfies ComposerProviderCandidate[]
).filter((candidate) =>
candidate.label.toLowerCase().includes(request.query.toLowerCase()),
),
};
},
},
{
providerId: "demo-commands",
label: "Commands",
icon: <DemoIcon name="command" />,
sourceLabel: "Demo",
trigger: { text: "/", position: "leading" },
async query(request, signal) {
await pause(signal);
return {
request,
candidates: (
[
{
id: "help",
label: "/help",
description: "Show available commands",
action: {
type: "insert",
command: { providerId: "demo-commands", commandId: "help" },
content: [{ type: "text", text: "/help " }],
},
},
{
id: "review",
label: "/review",
description: "Review the current changes",
action: {
type: "insert",
command: { providerId: "demo-commands", commandId: "review" },
content: [{ type: "text", text: "/review " }],
},
},
{
id: "inspect",
label: "/inspect",
description: "Inspect the current session",
action: {
type: "invoke",
command: { providerId: "demo-commands", commandId: "inspect" },
},
},
] satisfies ComposerProviderCandidate[]
).filter((candidate) => candidate.label.includes(request.query)),
};
},
},
{
providerId: "demo-skills",
label: "Skills",
icon: <DemoIcon name="skill" />,
sourceLabel: "Demo",
trigger: { text: "/", position: "leading" },
async query(request, signal) {
await pause(signal);
return {
request,
candidates: (
[
{
id: "summarize",
label: "/summarize",
description: "Summarize changes and completed checks",
action: {
type: "insert",
content: [
{
type: "text",
text: "Summarize the changes and list the checks that passed. ",
},
],
},
},
] satisfies ComposerProviderCandidate[]
).filter((candidate) => candidate.label.includes(request.query)),
};
},
},
];
const demoIcons = {
start: "m8 5 11 7-11 7Z",
remount: "M3 11a9 9 0 1 1 2.6 7.4M3 4v7h7",
clear: "M3 6h18M9 6V3h6v3M5 6l1 15h12l1-15M10 10v7M14 10v7",
reference: "M14 2H6v20h12V6ZM14 2v5h5M8 12h8M8 16h5",
quote: "M3 6h7v7H3ZM14 6h7v7h-7ZM10 13c0 4-2 6-5 6M21 13c0 4-2 6-5 6",
command: "m4 6 6 6-6 6M13 18h7",
skill: "m12 3 8 4v10l-8 4-8-4V7ZM4 7l8 4 8-4M12 11v10",
review: "m15 4 5 5-11 11H4v-5ZM13 6l5 5",
settings: "M4 7h16M4 17h16M8 4v6M16 14v6",
help: "M12 8h.01M12 12v5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z",
inspect: "M4 4h16v16H4ZM7 8l3 3-3 3M12 15h5",
save: "M5 3h12l4 4v14H3V3ZM7 3v6h10V3M7 21v-8h10v8",
cancel: "m6 6 12 12M6 18 18 6",
};
type DemoIconName = keyof typeof demoIcons;
function DemoIcon({ name }: { name: DemoIconName }) {
return (
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
>
<path d={demoIcons[name]} />
</svg>
);
}
function DemoAction({
label,
icon,
...props
}: {
label: string;
icon: DemoIconName;
} & React.ComponentProps<typeof Button>) {
return (
<Button
type="button"
appearance="ghost"
color="base"
size="sm"
shape="circle"
{...props}
aria-label={label}
title={label}
>
<DemoIcon name={icon} />
</Button>
);
}
/** Core owns menu sizing/placement; the native Popover owns dismissal and focus. */
function DemoPopover({
label,
icon,
children,
}: {
label: string;
icon: DemoIconName;
children: React.ReactNode;
}) {
const id = useId();
const anchorName = `--demo-${id.replace(/[^a-zA-Z0-9_-]/g, "")}`;
const [open, setOpen] = useState(false);
return (
<>
<button
type="button"
className="popover-menu-item"
aria-label={label}
title={label}
popoverTarget={id}
aria-controls={id}
aria-expanded={open}
style={{ anchorName } as React.CSSProperties}
>
<DemoIcon name={icon} />
<span>{label}</span>
</button>
<div
id={id}
popover="auto"
className="popover popover-menu chat-composer-menu chat-demo-popover"
role="group"
aria-label={label}
style={{ positionAnchor: anchorName } as React.CSSProperties}
onToggle={(event) =>
setOpen(event.currentTarget.matches(":popover-open"))
}
>
{children}
</div>
</>
);
}
const models = [
["standard", "Standard demo model", "Standard"],
["fast", "Fast demo model", "Fast"],
["restricted", "Restricted model (host rejects)", "Restricted"],
] as const;
const efforts = ["low", "medium", "high", "max"];
const effortLabels = ["Low", "Medium", "High", "Max"];
const approvals = [
["ask", "Ask for approval", "Review each action before it runs."],
["auto", "Approve for me", "Request review for sensitive actions."],
["full", "Full access", "Allow actions without an approval prompt."],
] as const;
const menuGroups = [
{
id: "approval",
label: "Approval mode",
settingIds: ["approval"],
appearance: "access" as const,
},
{
id: "model",
label: "Model settings",
settingIds: ["model", "effort"],
nestedSettingIds: ["model"],
appearance: "model" as const,
},
];
function QueueDocumentEditor({
value,
onChange,
onSave,
onCancel,
pending,
}: ComposerQueueEditorProps) {
return (
<>
{value.content.map((node, index) =>
node.type === "text" ? (
<textarea
key={index}
className="chat-composer-input"
aria-label={`Queued text ${index + 1}`}
value={node.text}
disabled={pending}
onChange={(event) =>
onChange({
...value,
content: value.content.map((entry, at) =>
at === index
? { type: "text", text: event.currentTarget.value }
: entry,
),
})
}
/>
) : (
<p key={node.nodeId}>
{node.type === "reference" ? node.label : node.text}
</p>
),
)}
<DemoAction
label="Save queued document"
icon="save"
disabled={pending}
onClick={onSave}
/>
<DemoAction
label="Cancel"
icon="cancel"
disabled={pending}
onClick={onCancel}
/>
</>
);
}
function SessionDemo({ rich }: { rich: boolean }) {
const [demo] = useState(createDemoHost);
const state = useSyncExternalStore(
demo.subscribe,
demo.getSnapshot,
demo.getSnapshot,
);
const [value, setValue] = useState<ComposerDocumentUpdate>({
document: {
schemaVersion: 1,
content: [{ type: "text", text: "Review the latest changes." }],
},
revision: 0,
origin: "replace",
originId: "demo-initial",
});
const [mount, setMount] = useState(0);
const [admission, setAdmission] = useState<Admission>("accept");
const [intent, setIntent] = useState<"follow_up" | "steer">("follow_up");
const [failPreparation, setFailPreparation] = useState(true);
const editor = useRef<ChatSessionComposerHandle>(null);
const occurrence = useRef(0);
const Composer = rich ? RichChatComposer : ChatSessionComposer;
function replace(document: ComposerDocument) {
setValue((current) => ({
document,
revision: current.revision + 1,
origin: "replace",
originId: `demo-replace-${++occurrence.current}`,
}));
}
const addMenu = (
<>
<DemoPopover label="Demo controls" icon="settings">
<div className="chat-demo-controls">
<DemoAction
label="Start demo turn"
icon="start"
onClick={demo.start}
/>
</div>
<div className="chat-demo-fields">
<label>
Admission outcome{" "}
<select
className="select select-sm"
value={admission}
onChange={(event) => {
const next = event.currentTarget.value as Admission;
setAdmission(next);
demo.setAdmission(next);
}}
>
<option value="accept">Accept</option>
<option value="reject">Reject</option>
<option value="unknown">Lose response after admission</option>
</select>
</label>
<label>
Running intent{" "}
<select
className="select select-sm"
value={intent}
onChange={(event) =>
setIntent(event.currentTarget.value as "follow_up" | "steer")
}
>
<option value="follow_up">Follow-up</option>
<option value="steer">Steer active turn</option>
</select>
</label>
<label>
<input
type="checkbox"
className="checkbox checkbox-sm"
checked={failPreparation}
onChange={(event) => {
setFailPreparation(event.currentTarget.checked);
demo.setFailPreparation(event.currentTarget.checked);
}}
/>{" "}
Fail first preparation
</label>
</div>
<div className="chat-demo-controls">
<DemoAction
label="Remount editor"
icon="remount"
onClick={() => setMount((current) => current + 1)}
/>
<DemoAction
label="Replace with empty document"
icon="clear"
onClick={() =>
replace({
schemaVersion: 1,
content: [{ type: "text", text: "" }],
})
}
/>
{rich ? (
<>
<DemoAction
label="Insert reference"
icon="reference"
onClick={() =>
editor.current?.insertReference({
type: "reference",
nodeId: `demo-ref-${++occurrence.current}`,
providerId: "demo-files",
refId: "README.md",
label: "README.md",
plainText: "@README.md",
})
}
/>
<DemoAction
label="Insert quote"
icon="quote"
onClick={() =>
editor.current?.insertQuote({
type: "quote",
nodeId: `demo-quote-${++occurrence.current}`,
text: "Keep user edits while admission is pending.",
source: {
messageId: "demo-message",
conversationId: scope.conversationId,
label: "Earlier assistant reply",
},
})
}
/>
<DemoAction
label="Claim /help command"
icon="command"
onClick={() =>
editor.current?.claimCommand(
{ providerId: "demo-commands", commandId: "help" },
"/help",
)
}
/>
<DemoAction
label="Claim /review prompt"
icon="review"
onClick={() =>
editor.current?.claimCommand(
{ providerId: "demo-commands", commandId: "review" },
"/review",
)
}
/>
</>
) : null}
</div>
</DemoPopover>
<DemoPopover label="Composer help" icon="help">
<div className="popover-body">
<p>
Cmd/Ctrl+Enter sends; Enter adds a line. Type @ for references or /
for commands and editable skills.
</p>
<p>
Add up to three images, .txt, .md or .pdf files, each at most 2 MiB.
If preparation fails, use Retry.
</p>
<p>
Save a draft before remounting to try restoration; files then
require reattachment. Stop is independent of sending and
preparation.
</p>
<p>
This interactive demo keeps files, drafts and recovery in memory. It
has no backend; reloading the page discards its state.
</p>
</div>
</DemoPopover>
<DemoPopover label="Inspect demo state" icon="inspect">
<details>
<summary>Current portable document</summary>
<pre aria-label="Current portable document">
{JSON.stringify(value.document, null, 2)}
</pre>
</details>
<p>
Host: {state.runtime.status}; model: {state.model}; queue revision:{" "}
{state.queue.revision}.
</p>
<div aria-label="Demo host events" role="log" aria-live="off">
{state.events.length ? (
state.events.map((event, index) => (
<p key={`${index}-${event}`}>{event}</p>
))
) : (
<p>No events yet.</p>
)}
</div>
</DemoPopover>
</>
);
return (
<div
className="chat-demo chat-session-demo"
data-chat-session-demo={rich ? "rich" : "plain"}
>
<p className="sr-only" role="status">
Host: {state.runtime.status}; model: {state.model}; queue revision:{" "}
{state.queue.revision}.
</p>
<ChatAuthoritativeQueue
projection={state.queue}
capabilities={capabilities.queue}
targetTurnId={state.runtime.activeTurnId}
onMutation={demo.mutate}
onProjection={demo.applyProjection}
renderDocumentEditor={(props) => <QueueDocumentEditor {...props} />}
/>
<Composer
compact
addMenu={addMenu}
attachLabel="Add files and more"
className="chat-composer-ghost"
key={mount}
ref={editor}
value={value}
onDocumentChange={setValue}
scope={scope}
draftKey="demo-draft"
host={demo.host}
runtime={state.runtime}
policy={{ runningIntent: intent }}
options={{
model: state.model,
effort: state.effort,
approval: state.approval,
}}
draftAdapter={demo.draftAdapter}
attachmentOptions={demo.attachmentOptions}
providers={providers}
onProviderInvoke={demo.invoke}
onStop={demo.stop}
context={
<Chat.ComposerContext>
<Chat.ComposerContextItem icon={<DemoIcon name="reference" />}>
demo-repository
</Chat.ComposerContextItem>
<Chat.ComposerContextEnd>
<Chat.ComposerConnection state="connected" />
</Chat.ComposerContextEnd>
</Chat.ComposerContext>
}
allowAttachmentOnly
label={rich ? "Rich demo message" : "Semantic demo message"}
>
<ComposerSettings
variant="menu"
groups={menuGroups}
scopeKey={scope.conversationId}
revision={state.settingsRevision}
settings={[
{
id: "approval",
label: "Approval mode",
value: state.approval,
choices: approvals.map(([value, label, description]) => ({
value,
label,
description,
tone: value === "full" ? ("warning" as const) : undefined,
})),
},
{
id: "model",
label: "Model",
value: state.model,
choices: models.map(([value, label]) => ({ value, label })),
},
{
id: "effort",
label: "Reasoning effort",
value: state.effort,
ordered: true,
defaultValue: "medium",
choices: efforts.map((value, index) => ({
value,
label: effortLabels[index],
})),
},
]}
onRequest={demo.requestSetting}
onAcknowledged={demo.acknowledgeSetting}
/>
</Composer>
</div>
);
}
export function SemanticComposerPreview() {
return <SessionDemo rich={false} />;
}
export function RichComposerPreview() {
return <SessionDemo rich />;
}
/** Focused Core 1.21.1 composition; settings still require host acknowledgment. */
export function CompactComposerPreview() {
const [demo] = useState(() => {
const host = createDemoHost();
host.setFailPreparation(false);
return host;
});
const state = useSyncExternalStore(
demo.subscribe,
demo.getSnapshot,
demo.getSnapshot,
);
const [rich, setRich] = useState(true);
const [value, setValue] = useState<ComposerDocumentUpdate>({
document: {
schemaVersion: 1,
content: [{ type: "text", text: "Review the latest changes." }],
},
revision: 0,
origin: "replace",
originId: "compact-initial",
});
const Composer = rich ? RichChatComposer : ChatSessionComposer;
return (
<div className="chat-demo chat-session-demo" data-chat-compact-demo>
<Composer
compact
attachLabel="Add files and more"
addMenu={
<>
<DemoPopover label="Composer help" icon="help">
<div className="popover-body">
<p>
Cmd/Ctrl+Enter sends; Enter adds a line. Add files with +;
images become thumbnails after preparation. Type / to choose
skills or commands, or @ for repository references.
</p>
<p>
Choose a model and reasoning effort from the model menu.
Switch editors from Add. Stop and follow-up submission are
independent.
</p>
<p>
This in-memory demo applies model choices only after the host
acknowledges them.
</p>
</div>
</DemoPopover>
<label className="chat-composer-menu-field">
<span>
<input
type="checkbox"
className="checkbox checkbox-sm"
checked={rich}
onChange={(event) => setRich(event.currentTarget.checked)}
/>{" "}
Use rich editor
</span>
</label>
</>
}
className="chat-composer-ghost"
value={value}
onDocumentChange={setValue}
scope={scope}
draftKey="compact-demo"
host={demo.host}
runtime={state.runtime}
attachmentOptions={demo.attachmentOptions}
providers={providers}
onProviderInvoke={demo.invoke}
options={{
model: state.model,
effort: state.effort,
approval: state.approval,
}}
onStop={demo.stop}
context={
<Chat.ComposerContext>
<Chat.ComposerContextItem icon={<DemoIcon name="reference" />}>
demo-repository
</Chat.ComposerContextItem>
<Chat.ComposerContextEnd>
<Chat.ComposerConnection state="connected" />
</Chat.ComposerContextEnd>
</Chat.ComposerContext>
}
allowAttachmentOnly
label="Compact demo message"
>
<ComposerSettings
variant="menu"
groups={menuGroups}
scopeKey={scope.conversationId}
revision={state.settingsRevision}
settings={[
{
id: "approval",
label: "Approval mode",
value: state.approval,
choices: approvals.map(([value, label, description]) => ({
value,
label,
description,
tone: value === "full" ? ("warning" as const) : undefined,
})),
},
{
id: "model",
label: "Model",
value: state.model,
choices: models.map(([value, label]) => ({ value, label })),
},
{
id: "effort",
label: "Reasoning effort",
value: state.effort,
ordered: true,
defaultValue: "medium",
choices: efforts.map((value, index) => ({
value,
label: effortLabels[index],
})),
},
]}
onRequest={demo.requestSetting}
onAcknowledged={demo.acknowledgeSetting}
/>
</Composer>
<p className="sr-only" role="status" aria-label="Compact host state">
Host: {state.runtime.status}; model: {state.model}; waiting messages:{" "}
{state.queue.items.length}.
{state.events.at(-1) ? ` ${state.events.at(-1)}` : ""}
</p>
</div>
);
}
Host: idle; model: standard; queue revision: 0.
Waiting messages
0 queuedLoading rich editor. Your draft is preserved.
Review the latest changes.Export preserved draft
Rich Composer and Authoritative Queue
Optional /chat/rich editor with atomic references, attributed quotes, claimed prompt/action commands and editable skills. Start a demo turn, send follow-ups or steer, then edit/remove/promote confirmed queue items. Model selection changes only after host acknowledgment; the restricted choice demonstrates rejection. Copy/paste and undo stay editor-owned. The fake host stores only page-lifetime memory.
Source
import React, { useId, useRef, useState, useSyncExternalStore } from "react";
import {
ChatAuthoritativeQueue,
Chat,
ComposerSettings,
ChatSessionComposer,
Button,
createComposerRecoveryOwner,
exportComposerText,
type ChatSessionComposerHandle,
type ComposerAttachmentOptions,
type ComposerCapabilities,
type ComposerCompletionProvider,
type ComposerDocument,
type ComposerProviderCandidate,
type ComposerDocumentUpdate,
type ComposerDraft,
type ComposerDraftAdapter,
type ComposerQueueEditorProps,
type ComposerQueueMutation,
type ComposerQueueMutationResult,
type ComposerQueueProjection,
type ComposerReceipt,
type ComposerRuntimeState,
type ComposerSessionHost,
type ComposerSettingRequest,
type ComposerSettingResult,
type ComposerSubmission,
} from "@duskmoon-dev/components";
import { RichChatComposer } from "@duskmoon-dev/components/chat/rich";
const scope = { contextKey: "demo-repository", conversationId: "demo-thread" };
const capabilities: ComposerCapabilities = {
protocolVersion: 1,
documentVersions: [1],
intents: ["send", "follow_up", "steer"],
commands: true,
attachments: true,
queue: { edit: "document", remove: true, promote: true },
durableRecovery: false,
};
type Admission = "accept" | "reject" | "unknown";
interface DemoState {
readonly runtime: ComposerRuntimeState;
readonly queue: ComposerQueueProjection;
readonly settingsRevision: number;
readonly model: string;
readonly effort: string;
readonly approval: string;
readonly events: readonly string[];
}
/** Abortable demo latency, not an upload or execution transport. */
function pause(signal: AbortSignal) {
return new Promise<void>((resolve, reject) => {
if (signal.aborted) {
reject(new DOMException("Cancelled", "AbortError"));
return;
}
const abort = () => {
clearTimeout(timer);
reject(new DOMException("Cancelled", "AbortError"));
};
const timer = setTimeout(() => {
signal.removeEventListener("abort", abort);
resolve();
}, 400);
signal.addEventListener("abort", abort, { once: true });
});
}
const settingsValues: Record<string, readonly string[]> = {
model: ["standard", "fast"],
effort: ["low", "medium", "high", "max"],
approval: ["ask", "auto", "full"],
};
/** Stable per-preview host: memory only, lost on page reload. */
function createDemoHost() {
const recovery = createComposerRecoveryOwner();
const receipts = new Map<string, ComposerReceipt>();
const drafts = new Map<string, ComposerDraft>();
const listeners = new Set<() => void>();
let admission: Admission = "accept";
let failPreparation = true;
let turnCounter = 0;
const preparations = new Set<string>();
let state: DemoState = {
runtime: { status: "idle" },
queue: { protocolVersion: 1, scope, revision: 0, items: [] },
settingsRevision: 0,
model: "standard",
effort: "medium",
approval: "ask",
events: [],
};
function publish(next: Partial<DemoState>, event?: string) {
state = {
...state,
...next,
events: event ? [...state.events.slice(-7), event] : state.events,
};
listeners.forEach((listener) => listener());
}
function accept(snapshot: ComposerSubmission): ComposerReceipt {
const identity = {
protocolVersion: 1 as const,
clientSubmissionId: snapshot.clientSubmissionId,
scope: snapshot.scope,
outcome: "accepted" as const,
};
if (snapshot.operation === "command") {
const result = { help: "Use /review for a prompt or @ for a reference." };
publish({}, `Command result: ${JSON.stringify(result)}`);
return { ...identity, operation: "command", result };
}
const text =
exportComposerText(snapshot.document) || "Attachment-only prompt";
if (snapshot.intent === "follow_up") {
const id = `waiting-${snapshot.clientSubmissionId}`;
const queue = {
...state.queue,
revision: state.queue.revision + 1,
items: [
...state.queue.items,
{
id,
document: snapshot.document,
attachments: snapshot.attachments,
capabilities: capabilities.queue,
},
],
};
publish({ queue }, `Follow-up admitted: ${text}`);
return {
...identity,
operation: "prompt",
delivery: "follow_up",
persistence: "volatile",
queueItemId: id,
queueRevision: queue.revision,
};
}
const turnId =
snapshot.intent === "steer"
? snapshot.targetTurnId
: `demo-turn-${++turnCounter}`;
publish(
{ runtime: { status: "running", activeTurnId: turnId } },
`${snapshot.intent === "steer" ? "Steer" : "Prompt"} admitted: ${text}`,
);
return {
...identity,
operation: "prompt",
delivery: snapshot.intent === "steer" ? "steer" : "immediate",
persistence: "volatile",
turnId,
};
}
const host: ComposerSessionHost = {
capabilities,
recovery,
commandOperation: (command) =>
command.commandId === "help" ? "command" : "prompt",
async submit(snapshot, signal) {
const mode = admission;
await pause(signal);
const existing = receipts.get(snapshot.clientSubmissionId);
if (existing) return existing;
if (mode === "reject") {
const receipt: ComposerReceipt = {
protocolVersion: 1,
scope: snapshot.scope,
clientSubmissionId: snapshot.clientSubmissionId,
operation: snapshot.operation,
outcome: "rejected",
error: {
code: "demo_rejection",
message:
"Demo host rejected this request. Edit or change the outcome and submit again.",
},
};
receipts.set(snapshot.clientSubmissionId, receipt);
publish({}, "Request rejected; draft retained.");
return receipt;
}
const receipt = accept(snapshot);
receipts.set(snapshot.clientSubmissionId, receipt);
if (mode !== "unknown") return receipt;
publish(
{},
"Demo response lost after admission. Check submission status to reconcile.",
);
return {
protocolVersion: 1,
scope: snapshot.scope,
clientSubmissionId: snapshot.clientSubmissionId,
operation: snapshot.operation,
outcome: "unknown",
error: {
code: "demo_response_lost",
message:
"Admission response was lost; do not assume failure or resend as a new request.",
},
};
},
async reconcile(snapshot, signal) {
await pause(signal);
const receipt = receipts.get(snapshot.clientSubmissionId);
publish(
{},
receipt
? `Reconciled: ${receipt.outcome}`
: "No admission record found; outcome remains unresolved.",
);
return receipt ?? { outcome: "not_found" };
},
async authorizeRetry() {
publish(
{},
"Demo host authorized retry using the original submission identity.",
);
return true;
},
};
const draftAdapter: ComposerDraftAdapter = {
async load({ scope: owner, draftKey, signal }) {
await pause(signal);
return drafts.get(JSON.stringify([owner, draftKey]));
},
async save(draft, signal) {
await pause(signal);
drafts.set(JSON.stringify([draft.scope, draft.draftKey]), draft);
publish({}, `Draft revision ${draft.revision} saved in demo memory.`);
},
};
const attachmentOptions: Omit<ComposerAttachmentOptions, "scope"> = {
policy: {
accept: "image/*,.txt,.md,.pdf",
maxFiles: 3,
maxFileBytes: 2 * 1024 * 1024,
},
async prepare(file, { entryId, signal, reportProgress }) {
reportProgress(0.25);
await pause(signal);
if (failPreparation && !preparations.has(entryId)) {
preparations.add(entryId);
throw new Error("Demo preparation failed once. Retry this attachment.");
}
reportProgress(1);
return {
providerId: "demo-files",
reference: { entryId, name: file.name },
};
},
// Omitted canRecover: saved occurrences require reattachment after remount.
};
return {
host,
draftAdapter,
attachmentOptions,
getSnapshot: () => state,
subscribe(listener: () => void) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
setAdmission(value: Admission) {
admission = value;
},
setFailPreparation(value: boolean) {
failPreparation = value;
},
start() {
publish(
{
runtime: {
status: "running",
activeTurnId: `demo-turn-${++turnCounter}`,
},
},
"Demo turn started; no model is executing.",
);
},
stop() {
publish(
{ runtime: { status: "idle" } },
"Stop acknowledged by demo host; queued messages remain waiting.",
);
},
invoke() {
publish(
{},
"Provider invocation executed independently of prompt admission.",
);
},
async mutate(
request: ComposerQueueMutation,
signal: AbortSignal,
): Promise<ComposerQueueMutationResult> {
await pause(signal);
const item = state.queue.items.find(
(entry) => entry.id === request.itemId,
);
if (
request.expectedRevision !== state.queue.revision ||
!item ||
(request.operation === "promote" &&
request.targetTurnId !== state.runtime.activeTurnId)
) {
return {
requestId: request.requestId,
outcome: "rejected",
projection: state.queue,
error: {
code: "queue_conflict",
message:
"Demo queue changed; use the canonical projection and try again.",
},
};
}
const queue: ComposerQueueProjection = {
...state.queue,
revision: state.queue.revision + 1,
items:
request.operation === "edit"
? state.queue.items.map((entry) =>
entry.id === item.id
? { ...entry, document: request.document }
: entry,
)
: state.queue.items.filter((entry) => entry.id !== item.id),
};
publish(
{ queue },
`Queue ${request.operation} acknowledged for ${request.itemId}.`,
);
return {
requestId: request.requestId,
outcome: "accepted",
projection: queue,
};
},
applyProjection(queue: ComposerQueueProjection) {
if (queue.revision >= state.queue.revision) publish({ queue });
},
async requestSetting(
request: ComposerSettingRequest,
signal: AbortSignal,
): Promise<ComposerSettingResult> {
await pause(signal);
const identity = {
requestId: request.requestId,
scopeKey: request.scopeKey,
settingId: request.settingId,
revision: state.settingsRevision + 1,
};
if (
request.expectedRevision !== state.settingsRevision ||
request.value === "restricted" ||
!(settingsValues[request.settingId] ?? []).includes(request.value)
) {
return {
...identity,
outcome: "rejected",
message:
"Demo host declined this model; the current selection is retained.",
};
}
return { ...identity, outcome: "accepted", value: request.value };
},
acknowledgeSetting(result: ComposerSettingResult) {
publish(
{
settingsRevision: result.revision,
...(result.outcome === "accepted"
? { [result.settingId]: result.value }
: {}),
},
`${result.settingId} change ${result.outcome}.`,
);
},
};
}
const providers: readonly ComposerCompletionProvider[] = [
{
providerId: "demo-files",
label: "Repository references",
icon: <DemoIcon name="reference" />,
sourceLabel: "Demo",
trigger: { text: "@", position: "word" },
async query(request, signal) {
await pause(signal);
return {
request,
candidates: (
[
{
id: "readme",
label: "README.md",
description: "Demo reference, resolved by the host",
action: {
type: "insert",
content: [
{
type: "reference",
nodeId: `${request.requestId}-reference`,
providerId: "demo-files",
refId: "README.md",
label: "README.md",
plainText: "@README.md",
},
],
},
},
{
id: "private",
label: "Private document",
disabledReason: "Host has not granted access",
action: { type: "insert", content: [] },
},
] satisfies ComposerProviderCandidate[]
).filter((candidate) =>
candidate.label.toLowerCase().includes(request.query.toLowerCase()),
),
};
},
},
{
providerId: "demo-commands",
label: "Commands",
icon: <DemoIcon name="command" />,
sourceLabel: "Demo",
trigger: { text: "/", position: "leading" },
async query(request, signal) {
await pause(signal);
return {
request,
candidates: (
[
{
id: "help",
label: "/help",
description: "Show available commands",
action: {
type: "insert",
command: { providerId: "demo-commands", commandId: "help" },
content: [{ type: "text", text: "/help " }],
},
},
{
id: "review",
label: "/review",
description: "Review the current changes",
action: {
type: "insert",
command: { providerId: "demo-commands", commandId: "review" },
content: [{ type: "text", text: "/review " }],
},
},
{
id: "inspect",
label: "/inspect",
description: "Inspect the current session",
action: {
type: "invoke",
command: { providerId: "demo-commands", commandId: "inspect" },
},
},
] satisfies ComposerProviderCandidate[]
).filter((candidate) => candidate.label.includes(request.query)),
};
},
},
{
providerId: "demo-skills",
label: "Skills",
icon: <DemoIcon name="skill" />,
sourceLabel: "Demo",
trigger: { text: "/", position: "leading" },
async query(request, signal) {
await pause(signal);
return {
request,
candidates: (
[
{
id: "summarize",
label: "/summarize",
description: "Summarize changes and completed checks",
action: {
type: "insert",
content: [
{
type: "text",
text: "Summarize the changes and list the checks that passed. ",
},
],
},
},
] satisfies ComposerProviderCandidate[]
).filter((candidate) => candidate.label.includes(request.query)),
};
},
},
];
const demoIcons = {
start: "m8 5 11 7-11 7Z",
remount: "M3 11a9 9 0 1 1 2.6 7.4M3 4v7h7",
clear: "M3 6h18M9 6V3h6v3M5 6l1 15h12l1-15M10 10v7M14 10v7",
reference: "M14 2H6v20h12V6ZM14 2v5h5M8 12h8M8 16h5",
quote: "M3 6h7v7H3ZM14 6h7v7h-7ZM10 13c0 4-2 6-5 6M21 13c0 4-2 6-5 6",
command: "m4 6 6 6-6 6M13 18h7",
skill: "m12 3 8 4v10l-8 4-8-4V7ZM4 7l8 4 8-4M12 11v10",
review: "m15 4 5 5-11 11H4v-5ZM13 6l5 5",
settings: "M4 7h16M4 17h16M8 4v6M16 14v6",
help: "M12 8h.01M12 12v5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z",
inspect: "M4 4h16v16H4ZM7 8l3 3-3 3M12 15h5",
save: "M5 3h12l4 4v14H3V3ZM7 3v6h10V3M7 21v-8h10v8",
cancel: "m6 6 12 12M6 18 18 6",
};
type DemoIconName = keyof typeof demoIcons;
function DemoIcon({ name }: { name: DemoIconName }) {
return (
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
>
<path d={demoIcons[name]} />
</svg>
);
}
function DemoAction({
label,
icon,
...props
}: {
label: string;
icon: DemoIconName;
} & React.ComponentProps<typeof Button>) {
return (
<Button
type="button"
appearance="ghost"
color="base"
size="sm"
shape="circle"
{...props}
aria-label={label}
title={label}
>
<DemoIcon name={icon} />
</Button>
);
}
/** Core owns menu sizing/placement; the native Popover owns dismissal and focus. */
function DemoPopover({
label,
icon,
children,
}: {
label: string;
icon: DemoIconName;
children: React.ReactNode;
}) {
const id = useId();
const anchorName = `--demo-${id.replace(/[^a-zA-Z0-9_-]/g, "")}`;
const [open, setOpen] = useState(false);
return (
<>
<button
type="button"
className="popover-menu-item"
aria-label={label}
title={label}
popoverTarget={id}
aria-controls={id}
aria-expanded={open}
style={{ anchorName } as React.CSSProperties}
>
<DemoIcon name={icon} />
<span>{label}</span>
</button>
<div
id={id}
popover="auto"
className="popover popover-menu chat-composer-menu chat-demo-popover"
role="group"
aria-label={label}
style={{ positionAnchor: anchorName } as React.CSSProperties}
onToggle={(event) =>
setOpen(event.currentTarget.matches(":popover-open"))
}
>
{children}
</div>
</>
);
}
const models = [
["standard", "Standard demo model", "Standard"],
["fast", "Fast demo model", "Fast"],
["restricted", "Restricted model (host rejects)", "Restricted"],
] as const;
const efforts = ["low", "medium", "high", "max"];
const effortLabels = ["Low", "Medium", "High", "Max"];
const approvals = [
["ask", "Ask for approval", "Review each action before it runs."],
["auto", "Approve for me", "Request review for sensitive actions."],
["full", "Full access", "Allow actions without an approval prompt."],
] as const;
const menuGroups = [
{
id: "approval",
label: "Approval mode",
settingIds: ["approval"],
appearance: "access" as const,
},
{
id: "model",
label: "Model settings",
settingIds: ["model", "effort"],
nestedSettingIds: ["model"],
appearance: "model" as const,
},
];
function QueueDocumentEditor({
value,
onChange,
onSave,
onCancel,
pending,
}: ComposerQueueEditorProps) {
return (
<>
{value.content.map((node, index) =>
node.type === "text" ? (
<textarea
key={index}
className="chat-composer-input"
aria-label={`Queued text ${index + 1}`}
value={node.text}
disabled={pending}
onChange={(event) =>
onChange({
...value,
content: value.content.map((entry, at) =>
at === index
? { type: "text", text: event.currentTarget.value }
: entry,
),
})
}
/>
) : (
<p key={node.nodeId}>
{node.type === "reference" ? node.label : node.text}
</p>
),
)}
<DemoAction
label="Save queued document"
icon="save"
disabled={pending}
onClick={onSave}
/>
<DemoAction
label="Cancel"
icon="cancel"
disabled={pending}
onClick={onCancel}
/>
</>
);
}
function SessionDemo({ rich }: { rich: boolean }) {
const [demo] = useState(createDemoHost);
const state = useSyncExternalStore(
demo.subscribe,
demo.getSnapshot,
demo.getSnapshot,
);
const [value, setValue] = useState<ComposerDocumentUpdate>({
document: {
schemaVersion: 1,
content: [{ type: "text", text: "Review the latest changes." }],
},
revision: 0,
origin: "replace",
originId: "demo-initial",
});
const [mount, setMount] = useState(0);
const [admission, setAdmission] = useState<Admission>("accept");
const [intent, setIntent] = useState<"follow_up" | "steer">("follow_up");
const [failPreparation, setFailPreparation] = useState(true);
const editor = useRef<ChatSessionComposerHandle>(null);
const occurrence = useRef(0);
const Composer = rich ? RichChatComposer : ChatSessionComposer;
function replace(document: ComposerDocument) {
setValue((current) => ({
document,
revision: current.revision + 1,
origin: "replace",
originId: `demo-replace-${++occurrence.current}`,
}));
}
const addMenu = (
<>
<DemoPopover label="Demo controls" icon="settings">
<div className="chat-demo-controls">
<DemoAction
label="Start demo turn"
icon="start"
onClick={demo.start}
/>
</div>
<div className="chat-demo-fields">
<label>
Admission outcome{" "}
<select
className="select select-sm"
value={admission}
onChange={(event) => {
const next = event.currentTarget.value as Admission;
setAdmission(next);
demo.setAdmission(next);
}}
>
<option value="accept">Accept</option>
<option value="reject">Reject</option>
<option value="unknown">Lose response after admission</option>
</select>
</label>
<label>
Running intent{" "}
<select
className="select select-sm"
value={intent}
onChange={(event) =>
setIntent(event.currentTarget.value as "follow_up" | "steer")
}
>
<option value="follow_up">Follow-up</option>
<option value="steer">Steer active turn</option>
</select>
</label>
<label>
<input
type="checkbox"
className="checkbox checkbox-sm"
checked={failPreparation}
onChange={(event) => {
setFailPreparation(event.currentTarget.checked);
demo.setFailPreparation(event.currentTarget.checked);
}}
/>{" "}
Fail first preparation
</label>
</div>
<div className="chat-demo-controls">
<DemoAction
label="Remount editor"
icon="remount"
onClick={() => setMount((current) => current + 1)}
/>
<DemoAction
label="Replace with empty document"
icon="clear"
onClick={() =>
replace({
schemaVersion: 1,
content: [{ type: "text", text: "" }],
})
}
/>
{rich ? (
<>
<DemoAction
label="Insert reference"
icon="reference"
onClick={() =>
editor.current?.insertReference({
type: "reference",
nodeId: `demo-ref-${++occurrence.current}`,
providerId: "demo-files",
refId: "README.md",
label: "README.md",
plainText: "@README.md",
})
}
/>
<DemoAction
label="Insert quote"
icon="quote"
onClick={() =>
editor.current?.insertQuote({
type: "quote",
nodeId: `demo-quote-${++occurrence.current}`,
text: "Keep user edits while admission is pending.",
source: {
messageId: "demo-message",
conversationId: scope.conversationId,
label: "Earlier assistant reply",
},
})
}
/>
<DemoAction
label="Claim /help command"
icon="command"
onClick={() =>
editor.current?.claimCommand(
{ providerId: "demo-commands", commandId: "help" },
"/help",
)
}
/>
<DemoAction
label="Claim /review prompt"
icon="review"
onClick={() =>
editor.current?.claimCommand(
{ providerId: "demo-commands", commandId: "review" },
"/review",
)
}
/>
</>
) : null}
</div>
</DemoPopover>
<DemoPopover label="Composer help" icon="help">
<div className="popover-body">
<p>
Cmd/Ctrl+Enter sends; Enter adds a line. Type @ for references or /
for commands and editable skills.
</p>
<p>
Add up to three images, .txt, .md or .pdf files, each at most 2 MiB.
If preparation fails, use Retry.
</p>
<p>
Save a draft before remounting to try restoration; files then
require reattachment. Stop is independent of sending and
preparation.
</p>
<p>
This interactive demo keeps files, drafts and recovery in memory. It
has no backend; reloading the page discards its state.
</p>
</div>
</DemoPopover>
<DemoPopover label="Inspect demo state" icon="inspect">
<details>
<summary>Current portable document</summary>
<pre aria-label="Current portable document">
{JSON.stringify(value.document, null, 2)}
</pre>
</details>
<p>
Host: {state.runtime.status}; model: {state.model}; queue revision:{" "}
{state.queue.revision}.
</p>
<div aria-label="Demo host events" role="log" aria-live="off">
{state.events.length ? (
state.events.map((event, index) => (
<p key={`${index}-${event}`}>{event}</p>
))
) : (
<p>No events yet.</p>
)}
</div>
</DemoPopover>
</>
);
return (
<div
className="chat-demo chat-session-demo"
data-chat-session-demo={rich ? "rich" : "plain"}
>
<p className="sr-only" role="status">
Host: {state.runtime.status}; model: {state.model}; queue revision:{" "}
{state.queue.revision}.
</p>
<ChatAuthoritativeQueue
projection={state.queue}
capabilities={capabilities.queue}
targetTurnId={state.runtime.activeTurnId}
onMutation={demo.mutate}
onProjection={demo.applyProjection}
renderDocumentEditor={(props) => <QueueDocumentEditor {...props} />}
/>
<Composer
compact
addMenu={addMenu}
attachLabel="Add files and more"
className="chat-composer-ghost"
key={mount}
ref={editor}
value={value}
onDocumentChange={setValue}
scope={scope}
draftKey="demo-draft"
host={demo.host}
runtime={state.runtime}
policy={{ runningIntent: intent }}
options={{
model: state.model,
effort: state.effort,
approval: state.approval,
}}
draftAdapter={demo.draftAdapter}
attachmentOptions={demo.attachmentOptions}
providers={providers}
onProviderInvoke={demo.invoke}
onStop={demo.stop}
context={
<Chat.ComposerContext>
<Chat.ComposerContextItem icon={<DemoIcon name="reference" />}>
demo-repository
</Chat.ComposerContextItem>
<Chat.ComposerContextEnd>
<Chat.ComposerConnection state="connected" />
</Chat.ComposerContextEnd>
</Chat.ComposerContext>
}
allowAttachmentOnly
label={rich ? "Rich demo message" : "Semantic demo message"}
>
<ComposerSettings
variant="menu"
groups={menuGroups}
scopeKey={scope.conversationId}
revision={state.settingsRevision}
settings={[
{
id: "approval",
label: "Approval mode",
value: state.approval,
choices: approvals.map(([value, label, description]) => ({
value,
label,
description,
tone: value === "full" ? ("warning" as const) : undefined,
})),
},
{
id: "model",
label: "Model",
value: state.model,
choices: models.map(([value, label]) => ({ value, label })),
},
{
id: "effort",
label: "Reasoning effort",
value: state.effort,
ordered: true,
defaultValue: "medium",
choices: efforts.map((value, index) => ({
value,
label: effortLabels[index],
})),
},
]}
onRequest={demo.requestSetting}
onAcknowledged={demo.acknowledgeSetting}
/>
</Composer>
</div>
);
}
export function SemanticComposerPreview() {
return <SessionDemo rich={false} />;
}
export function RichComposerPreview() {
return <SessionDemo rich />;
}
/** Focused Core 1.21.1 composition; settings still require host acknowledgment. */
export function CompactComposerPreview() {
const [demo] = useState(() => {
const host = createDemoHost();
host.setFailPreparation(false);
return host;
});
const state = useSyncExternalStore(
demo.subscribe,
demo.getSnapshot,
demo.getSnapshot,
);
const [rich, setRich] = useState(true);
const [value, setValue] = useState<ComposerDocumentUpdate>({
document: {
schemaVersion: 1,
content: [{ type: "text", text: "Review the latest changes." }],
},
revision: 0,
origin: "replace",
originId: "compact-initial",
});
const Composer = rich ? RichChatComposer : ChatSessionComposer;
return (
<div className="chat-demo chat-session-demo" data-chat-compact-demo>
<Composer
compact
attachLabel="Add files and more"
addMenu={
<>
<DemoPopover label="Composer help" icon="help">
<div className="popover-body">
<p>
Cmd/Ctrl+Enter sends; Enter adds a line. Add files with +;
images become thumbnails after preparation. Type / to choose
skills or commands, or @ for repository references.
</p>
<p>
Choose a model and reasoning effort from the model menu.
Switch editors from Add. Stop and follow-up submission are
independent.
</p>
<p>
This in-memory demo applies model choices only after the host
acknowledges them.
</p>
</div>
</DemoPopover>
<label className="chat-composer-menu-field">
<span>
<input
type="checkbox"
className="checkbox checkbox-sm"
checked={rich}
onChange={(event) => setRich(event.currentTarget.checked)}
/>{" "}
Use rich editor
</span>
</label>
</>
}
className="chat-composer-ghost"
value={value}
onDocumentChange={setValue}
scope={scope}
draftKey="compact-demo"
host={demo.host}
runtime={state.runtime}
attachmentOptions={demo.attachmentOptions}
providers={providers}
onProviderInvoke={demo.invoke}
options={{
model: state.model,
effort: state.effort,
approval: state.approval,
}}
onStop={demo.stop}
context={
<Chat.ComposerContext>
<Chat.ComposerContextItem icon={<DemoIcon name="reference" />}>
demo-repository
</Chat.ComposerContextItem>
<Chat.ComposerContextEnd>
<Chat.ComposerConnection state="connected" />
</Chat.ComposerContextEnd>
</Chat.ComposerContext>
}
allowAttachmentOnly
label="Compact demo message"
>
<ComposerSettings
variant="menu"
groups={menuGroups}
scopeKey={scope.conversationId}
revision={state.settingsRevision}
settings={[
{
id: "approval",
label: "Approval mode",
value: state.approval,
choices: approvals.map(([value, label, description]) => ({
value,
label,
description,
tone: value === "full" ? ("warning" as const) : undefined,
})),
},
{
id: "model",
label: "Model",
value: state.model,
choices: models.map(([value, label]) => ({ value, label })),
},
{
id: "effort",
label: "Reasoning effort",
value: state.effort,
ordered: true,
defaultValue: "medium",
choices: efforts.map((value, index) => ({
value,
label: effortLabels[index],
})),
},
]}
onRequest={demo.requestSetting}
onAcknowledged={demo.acknowledgeSetting}
/>
</Composer>
<p className="sr-only" role="status" aria-label="Compact host state">
Host: {state.runtime.status}; model: {state.model}; waiting messages:{" "}
{state.queue.items.length}.
{state.events.at(-1) ? ` ${state.events.at(-1)}` : ""}
</p>
</div>
);
}
Worked · 2 tool calls · 0 failed
Reasoning
Review source Done
The answer stays visible when activity is closed.
Agent Answers and Activity
Native work disclosures leave the final agent answer visible. Tool counts are illustrative; this preview performs no external work.
Source
import React, { useId, useRef, useState } from "react";
import { Chat } from "@duskmoon-dev/components/chat";
export function AgentActivityPreview() {
return (
<div data-chat-agent-demo style={{ width: "min(42rem, 100%)" }}>
<Chat.Agent>
<Chat.Work>
<Chat.WorkSummary>Worked · 2 tool calls · 0 failed</Chat.WorkSummary>
<Chat.WorkBody>
<Chat.Reasoning>
<summary>Reasoning</summary>
<div className="chat-reasoning-body">
Compare the source contract before checking behavior.
</div>
</Chat.Reasoning>
<Chat.Tool status="success">
<Chat.ToolHeader>
Review source <Chat.ToolStatus>Done</Chat.ToolStatus>
</Chat.ToolHeader>
<Chat.ToolResult>Markup reviewed.</Chat.ToolResult>
</Chat.Tool>
</Chat.WorkBody>
</Chat.Work>
<Chat.Content className="markdown-body">
<p>The answer stays visible when activity is closed.</p>
</Chat.Content>
</Chat.Agent>
<Chat.Agent>
<Chat.Content streaming>Progress without an avatar</Chat.Content>
</Chat.Agent>
</div>
);
}
const initialMessage =
"Review the chat view.\nKeep the waiting queue.\nSupport immediate steer.\nPreserve message order.\nKeep multiline text.\nCheck keyboard focus.\nCheck narrow screens.\nShare the results.";
export function CollapsibleMessagePreview() {
const [message, setMessage] = useState(initialMessage);
const id = useId();
return (
<div
data-chat-collapse-demo
style={{ width: "min(42rem, 100%)", display: "grid", gap: "1rem" }}
>
<label htmlFor={id}>Sent message text (edit to remeasure)</label>
<textarea
id={id}
className="textarea"
value={message}
rows={3}
onChange={(event) => setMessage(event.currentTarget.value)}
/>
<Chat placement="end">
<Chat.Bubble color="primary" collapsible>
{message}
</Chat.Bubble>
</Chat>
</div>
);
}
function QueueIcon({
action,
}: {
action: "send" | "steer" | "complete" | "reject" | "reset";
}) {
const paths = {
send: "m5 12 7-7 7 7M12 5v14",
steer: "m15 4 5 5-5 5M20 9h-9a6 6 0 0 0-6 6v4",
complete: "m5 12 4 4L19 6",
reject: "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM6 6l12 12",
reset: "M3 11a9 9 0 1 1 2.6 7.4M3 4v7h7",
};
return (
<svg
width="18"
height="18"
style={{ flexShrink: 0 }}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
>
<path d={paths[action]} />
</svg>
);
}
/** Local simulation only. Applications await their transport before changing the queue. */
export function WaitingQueuePreview() {
const inputId = useId();
const inputRef = useRef<HTMLTextAreaElement>(null);
const serial = useRef(2);
const [draft, setDraft] = useState("");
const [active, setActive] = useState(true);
const [turns, setTurns] = useState(1);
const [rejectNext, setRejectNext] = useState(false);
const [queue, setQueue] = useState([
{ id: "queued-1", text: "Also include the accessibility checks." },
{ id: "queued-2", text: "Check narrow screens too." },
]);
const [sent, setSent] = useState<{ id: string; text: string }[]>([]);
const [status, setStatus] = useState(
"Reply in progress. 2 messages waiting.",
);
function accepted() {
if (!rejectNext) return true;
setRejectNext(false);
setStatus(
"Admission rejected. The draft and waiting messages are preserved; retry the action.",
);
return false;
}
function admit(steer = false) {
if (!draft.trim() || (steer && !active) || !accepted()) return;
const item = { id: `message-${++serial.current}`, text: draft };
if (active && !steer) {
setQueue((current) => [...current, item]);
setStatus(`Message queued. ${queue.length + 1} messages waiting.`);
} else {
setSent((current) => [...current, item]);
if (!steer) {
setActive(true);
setTurns((current) => current + 1);
}
setStatus(
steer
? `Draft steered into the current reply. ${queue.length} messages waiting.`
: "Message sent. Reply started.",
);
}
setDraft("");
}
function consume(id: string, steer: boolean) {
const item = queue.find((entry) => entry.id === id);
if (!item || (steer && !accepted())) return;
setQueue((current) => current.filter((entry) => entry.id !== id));
if (steer) setSent((current) => [...current, item]);
setStatus(
`${steer ? "Message steered into the current reply" : "Waiting message removed"}. ${queue.length - 1} messages waiting.`,
);
inputRef.current?.focus();
}
function complete() {
const next = queue[0];
if (next && !accepted()) return;
if (next) {
setQueue((current) => current.slice(1));
setSent((current) => [...current, next]);
setTurns((current) => current + 1);
setStatus(
`Reply completed; oldest waiting message dispatched. ${queue.length - 1} messages waiting.`,
);
} else {
setActive(false);
setStatus("Reply completed. No messages waiting.");
}
}
return (
<div
data-chat-queue-demo
data-reply-count={turns}
style={{ width: "min(42rem, 100%)", display: "grid", gap: "1rem" }}
>
{sent.map((item) => (
<Chat key={item.id} placement="end">
<Chat.Bubble color="primary" collapsible>
{item.text}
</Chat.Bubble>
</Chat>
))}
<Chat.Agent>
<Chat.Content streaming={active}>
{active ? "Simulated reply in progress" : "Simulated reply complete"}
</Chat.Content>
</Chat.Agent>
<Chat.InputArea>
<Chat.Queue
items={queue}
steerDisabled={!active}
onSteer={(id) => consume(id, true)}
onRemove={(id) => consume(id, false)}
/>
<Chat.ComposerForm
ghost
onSubmit={(event) => {
event.preventDefault();
admit();
}}
>
<label className="sr-only" htmlFor={inputId}>
Queue demo message
</label>
<Chat.ComposerInput
ref={inputRef}
id={inputId}
name="message"
value={draft}
rows={3}
placeholder="Message the agent…"
onChange={(event) => setDraft(event.currentTarget.value)}
onKeyDown={(event) => {
if (
event.nativeEvent.isComposing ||
event.keyCode === 229 ||
event.key !== "Enter" ||
event.shiftKey ||
event.altKey
)
return;
event.preventDefault();
if (event.ctrlKey || event.metaKey) admit(true);
else event.currentTarget.form?.requestSubmit();
}}
/>
<Chat.ComposerActions>
<button
className="btn btn-primary btn-sm btn-circle btn-icon btn-icon-sm"
type="submit"
disabled={!draft.trim()}
aria-label={active ? "Queue message" : "Send message"}
title={active ? "Queue message (Enter)" : "Send message (Enter)"}
aria-keyshortcuts="Enter"
>
<QueueIcon action="send" />
</button>
<button
className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
type="button"
disabled={!active || !draft.trim()}
aria-label="Steer current message"
title="Steer current message (Ctrl/⌘+Enter)"
aria-keyshortcuts="Control+Enter Meta+Enter"
onClick={() => admit(true)}
>
<QueueIcon action="steer" />
</button>
</Chat.ComposerActions>
</Chat.ComposerForm>
</Chat.InputArea>
<p role="status" aria-atomic="true">
{status}
</p>
<div style={{ display: "flex", gap: "0.5rem", flexWrap: "wrap" }}>
<button
className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
type="button"
disabled={!active}
aria-label="Complete response"
title="Complete response"
onClick={complete}
>
<QueueIcon action="complete" />
</button>
<button
className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
type="button"
aria-label="Reject next admission"
title="Reject next admission"
aria-pressed={rejectNext}
onClick={() => setRejectNext(!rejectNext)}
>
<QueueIcon action="reject" />
</button>
<button
className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
type="button"
aria-label="Start fresh"
title="Start fresh"
onClick={() => {
setActive(false);
setQueue([]);
setSent([]);
setDraft("");
setTurns(0);
setRejectNext(false);
setStatus("Idle. No messages waiting.");
inputRef.current?.focus();
}}
>
<QueueIcon action="reset" />
</button>
</div>
</div>
);
}
Collapsible Sent Messages
Messages above six rendered lines expand with an accessible native button. Edit the text or resize to remeasure; short messages need no toggle.
Source
import React, { useId, useRef, useState } from "react";
import { Chat } from "@duskmoon-dev/components/chat";
export function AgentActivityPreview() {
return (
<div data-chat-agent-demo style={{ width: "min(42rem, 100%)" }}>
<Chat.Agent>
<Chat.Work>
<Chat.WorkSummary>Worked · 2 tool calls · 0 failed</Chat.WorkSummary>
<Chat.WorkBody>
<Chat.Reasoning>
<summary>Reasoning</summary>
<div className="chat-reasoning-body">
Compare the source contract before checking behavior.
</div>
</Chat.Reasoning>
<Chat.Tool status="success">
<Chat.ToolHeader>
Review source <Chat.ToolStatus>Done</Chat.ToolStatus>
</Chat.ToolHeader>
<Chat.ToolResult>Markup reviewed.</Chat.ToolResult>
</Chat.Tool>
</Chat.WorkBody>
</Chat.Work>
<Chat.Content className="markdown-body">
<p>The answer stays visible when activity is closed.</p>
</Chat.Content>
</Chat.Agent>
<Chat.Agent>
<Chat.Content streaming>Progress without an avatar</Chat.Content>
</Chat.Agent>
</div>
);
}
const initialMessage =
"Review the chat view.\nKeep the waiting queue.\nSupport immediate steer.\nPreserve message order.\nKeep multiline text.\nCheck keyboard focus.\nCheck narrow screens.\nShare the results.";
export function CollapsibleMessagePreview() {
const [message, setMessage] = useState(initialMessage);
const id = useId();
return (
<div
data-chat-collapse-demo
style={{ width: "min(42rem, 100%)", display: "grid", gap: "1rem" }}
>
<label htmlFor={id}>Sent message text (edit to remeasure)</label>
<textarea
id={id}
className="textarea"
value={message}
rows={3}
onChange={(event) => setMessage(event.currentTarget.value)}
/>
<Chat placement="end">
<Chat.Bubble color="primary" collapsible>
{message}
</Chat.Bubble>
</Chat>
</div>
);
}
function QueueIcon({
action,
}: {
action: "send" | "steer" | "complete" | "reject" | "reset";
}) {
const paths = {
send: "m5 12 7-7 7 7M12 5v14",
steer: "m15 4 5 5-5 5M20 9h-9a6 6 0 0 0-6 6v4",
complete: "m5 12 4 4L19 6",
reject: "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM6 6l12 12",
reset: "M3 11a9 9 0 1 1 2.6 7.4M3 4v7h7",
};
return (
<svg
width="18"
height="18"
style={{ flexShrink: 0 }}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
>
<path d={paths[action]} />
</svg>
);
}
/** Local simulation only. Applications await their transport before changing the queue. */
export function WaitingQueuePreview() {
const inputId = useId();
const inputRef = useRef<HTMLTextAreaElement>(null);
const serial = useRef(2);
const [draft, setDraft] = useState("");
const [active, setActive] = useState(true);
const [turns, setTurns] = useState(1);
const [rejectNext, setRejectNext] = useState(false);
const [queue, setQueue] = useState([
{ id: "queued-1", text: "Also include the accessibility checks." },
{ id: "queued-2", text: "Check narrow screens too." },
]);
const [sent, setSent] = useState<{ id: string; text: string }[]>([]);
const [status, setStatus] = useState(
"Reply in progress. 2 messages waiting.",
);
function accepted() {
if (!rejectNext) return true;
setRejectNext(false);
setStatus(
"Admission rejected. The draft and waiting messages are preserved; retry the action.",
);
return false;
}
function admit(steer = false) {
if (!draft.trim() || (steer && !active) || !accepted()) return;
const item = { id: `message-${++serial.current}`, text: draft };
if (active && !steer) {
setQueue((current) => [...current, item]);
setStatus(`Message queued. ${queue.length + 1} messages waiting.`);
} else {
setSent((current) => [...current, item]);
if (!steer) {
setActive(true);
setTurns((current) => current + 1);
}
setStatus(
steer
? `Draft steered into the current reply. ${queue.length} messages waiting.`
: "Message sent. Reply started.",
);
}
setDraft("");
}
function consume(id: string, steer: boolean) {
const item = queue.find((entry) => entry.id === id);
if (!item || (steer && !accepted())) return;
setQueue((current) => current.filter((entry) => entry.id !== id));
if (steer) setSent((current) => [...current, item]);
setStatus(
`${steer ? "Message steered into the current reply" : "Waiting message removed"}. ${queue.length - 1} messages waiting.`,
);
inputRef.current?.focus();
}
function complete() {
const next = queue[0];
if (next && !accepted()) return;
if (next) {
setQueue((current) => current.slice(1));
setSent((current) => [...current, next]);
setTurns((current) => current + 1);
setStatus(
`Reply completed; oldest waiting message dispatched. ${queue.length - 1} messages waiting.`,
);
} else {
setActive(false);
setStatus("Reply completed. No messages waiting.");
}
}
return (
<div
data-chat-queue-demo
data-reply-count={turns}
style={{ width: "min(42rem, 100%)", display: "grid", gap: "1rem" }}
>
{sent.map((item) => (
<Chat key={item.id} placement="end">
<Chat.Bubble color="primary" collapsible>
{item.text}
</Chat.Bubble>
</Chat>
))}
<Chat.Agent>
<Chat.Content streaming={active}>
{active ? "Simulated reply in progress" : "Simulated reply complete"}
</Chat.Content>
</Chat.Agent>
<Chat.InputArea>
<Chat.Queue
items={queue}
steerDisabled={!active}
onSteer={(id) => consume(id, true)}
onRemove={(id) => consume(id, false)}
/>
<Chat.ComposerForm
ghost
onSubmit={(event) => {
event.preventDefault();
admit();
}}
>
<label className="sr-only" htmlFor={inputId}>
Queue demo message
</label>
<Chat.ComposerInput
ref={inputRef}
id={inputId}
name="message"
value={draft}
rows={3}
placeholder="Message the agent…"
onChange={(event) => setDraft(event.currentTarget.value)}
onKeyDown={(event) => {
if (
event.nativeEvent.isComposing ||
event.keyCode === 229 ||
event.key !== "Enter" ||
event.shiftKey ||
event.altKey
)
return;
event.preventDefault();
if (event.ctrlKey || event.metaKey) admit(true);
else event.currentTarget.form?.requestSubmit();
}}
/>
<Chat.ComposerActions>
<button
className="btn btn-primary btn-sm btn-circle btn-icon btn-icon-sm"
type="submit"
disabled={!draft.trim()}
aria-label={active ? "Queue message" : "Send message"}
title={active ? "Queue message (Enter)" : "Send message (Enter)"}
aria-keyshortcuts="Enter"
>
<QueueIcon action="send" />
</button>
<button
className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
type="button"
disabled={!active || !draft.trim()}
aria-label="Steer current message"
title="Steer current message (Ctrl/⌘+Enter)"
aria-keyshortcuts="Control+Enter Meta+Enter"
onClick={() => admit(true)}
>
<QueueIcon action="steer" />
</button>
</Chat.ComposerActions>
</Chat.ComposerForm>
</Chat.InputArea>
<p role="status" aria-atomic="true">
{status}
</p>
<div style={{ display: "flex", gap: "0.5rem", flexWrap: "wrap" }}>
<button
className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
type="button"
disabled={!active}
aria-label="Complete response"
title="Complete response"
onClick={complete}
>
<QueueIcon action="complete" />
</button>
<button
className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
type="button"
aria-label="Reject next admission"
title="Reject next admission"
aria-pressed={rejectNext}
onClick={() => setRejectNext(!rejectNext)}
>
<QueueIcon action="reject" />
</button>
<button
className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
type="button"
aria-label="Start fresh"
title="Start fresh"
onClick={() => {
setActive(false);
setQueue([]);
setSent([]);
setDraft("");
setTurns(0);
setRejectNext(false);
setStatus("Idle. No messages waiting.");
inputRef.current?.focus();
}}
>
<QueueIcon action="reset" />
</button>
</div>
</div>
);
}
Waiting messages
2 queued- #1Also include the accessibility checks.
- #2Check narrow screens too.
Reply in progress. 2 messages waiting.
Waiting Queue and Steer
Application-owned local simulation: Enter sends or queues, Shift+Enter adds a newline, and Ctrl/⌘+Enter steers into the current reply. Complete response dispatches the oldest waiting item; rejection preserves drafts/messages. No backend or generated answers.
Source
import React, { useId, useRef, useState } from "react";
import { Chat } from "@duskmoon-dev/components/chat";
export function AgentActivityPreview() {
return (
<div data-chat-agent-demo style={{ width: "min(42rem, 100%)" }}>
<Chat.Agent>
<Chat.Work>
<Chat.WorkSummary>Worked · 2 tool calls · 0 failed</Chat.WorkSummary>
<Chat.WorkBody>
<Chat.Reasoning>
<summary>Reasoning</summary>
<div className="chat-reasoning-body">
Compare the source contract before checking behavior.
</div>
</Chat.Reasoning>
<Chat.Tool status="success">
<Chat.ToolHeader>
Review source <Chat.ToolStatus>Done</Chat.ToolStatus>
</Chat.ToolHeader>
<Chat.ToolResult>Markup reviewed.</Chat.ToolResult>
</Chat.Tool>
</Chat.WorkBody>
</Chat.Work>
<Chat.Content className="markdown-body">
<p>The answer stays visible when activity is closed.</p>
</Chat.Content>
</Chat.Agent>
<Chat.Agent>
<Chat.Content streaming>Progress without an avatar</Chat.Content>
</Chat.Agent>
</div>
);
}
const initialMessage =
"Review the chat view.\nKeep the waiting queue.\nSupport immediate steer.\nPreserve message order.\nKeep multiline text.\nCheck keyboard focus.\nCheck narrow screens.\nShare the results.";
export function CollapsibleMessagePreview() {
const [message, setMessage] = useState(initialMessage);
const id = useId();
return (
<div
data-chat-collapse-demo
style={{ width: "min(42rem, 100%)", display: "grid", gap: "1rem" }}
>
<label htmlFor={id}>Sent message text (edit to remeasure)</label>
<textarea
id={id}
className="textarea"
value={message}
rows={3}
onChange={(event) => setMessage(event.currentTarget.value)}
/>
<Chat placement="end">
<Chat.Bubble color="primary" collapsible>
{message}
</Chat.Bubble>
</Chat>
</div>
);
}
function QueueIcon({
action,
}: {
action: "send" | "steer" | "complete" | "reject" | "reset";
}) {
const paths = {
send: "m5 12 7-7 7 7M12 5v14",
steer: "m15 4 5 5-5 5M20 9h-9a6 6 0 0 0-6 6v4",
complete: "m5 12 4 4L19 6",
reject: "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM6 6l12 12",
reset: "M3 11a9 9 0 1 1 2.6 7.4M3 4v7h7",
};
return (
<svg
width="18"
height="18"
style={{ flexShrink: 0 }}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
>
<path d={paths[action]} />
</svg>
);
}
/** Local simulation only. Applications await their transport before changing the queue. */
export function WaitingQueuePreview() {
const inputId = useId();
const inputRef = useRef<HTMLTextAreaElement>(null);
const serial = useRef(2);
const [draft, setDraft] = useState("");
const [active, setActive] = useState(true);
const [turns, setTurns] = useState(1);
const [rejectNext, setRejectNext] = useState(false);
const [queue, setQueue] = useState([
{ id: "queued-1", text: "Also include the accessibility checks." },
{ id: "queued-2", text: "Check narrow screens too." },
]);
const [sent, setSent] = useState<{ id: string; text: string }[]>([]);
const [status, setStatus] = useState(
"Reply in progress. 2 messages waiting.",
);
function accepted() {
if (!rejectNext) return true;
setRejectNext(false);
setStatus(
"Admission rejected. The draft and waiting messages are preserved; retry the action.",
);
return false;
}
function admit(steer = false) {
if (!draft.trim() || (steer && !active) || !accepted()) return;
const item = { id: `message-${++serial.current}`, text: draft };
if (active && !steer) {
setQueue((current) => [...current, item]);
setStatus(`Message queued. ${queue.length + 1} messages waiting.`);
} else {
setSent((current) => [...current, item]);
if (!steer) {
setActive(true);
setTurns((current) => current + 1);
}
setStatus(
steer
? `Draft steered into the current reply. ${queue.length} messages waiting.`
: "Message sent. Reply started.",
);
}
setDraft("");
}
function consume(id: string, steer: boolean) {
const item = queue.find((entry) => entry.id === id);
if (!item || (steer && !accepted())) return;
setQueue((current) => current.filter((entry) => entry.id !== id));
if (steer) setSent((current) => [...current, item]);
setStatus(
`${steer ? "Message steered into the current reply" : "Waiting message removed"}. ${queue.length - 1} messages waiting.`,
);
inputRef.current?.focus();
}
function complete() {
const next = queue[0];
if (next && !accepted()) return;
if (next) {
setQueue((current) => current.slice(1));
setSent((current) => [...current, next]);
setTurns((current) => current + 1);
setStatus(
`Reply completed; oldest waiting message dispatched. ${queue.length - 1} messages waiting.`,
);
} else {
setActive(false);
setStatus("Reply completed. No messages waiting.");
}
}
return (
<div
data-chat-queue-demo
data-reply-count={turns}
style={{ width: "min(42rem, 100%)", display: "grid", gap: "1rem" }}
>
{sent.map((item) => (
<Chat key={item.id} placement="end">
<Chat.Bubble color="primary" collapsible>
{item.text}
</Chat.Bubble>
</Chat>
))}
<Chat.Agent>
<Chat.Content streaming={active}>
{active ? "Simulated reply in progress" : "Simulated reply complete"}
</Chat.Content>
</Chat.Agent>
<Chat.InputArea>
<Chat.Queue
items={queue}
steerDisabled={!active}
onSteer={(id) => consume(id, true)}
onRemove={(id) => consume(id, false)}
/>
<Chat.ComposerForm
ghost
onSubmit={(event) => {
event.preventDefault();
admit();
}}
>
<label className="sr-only" htmlFor={inputId}>
Queue demo message
</label>
<Chat.ComposerInput
ref={inputRef}
id={inputId}
name="message"
value={draft}
rows={3}
placeholder="Message the agent…"
onChange={(event) => setDraft(event.currentTarget.value)}
onKeyDown={(event) => {
if (
event.nativeEvent.isComposing ||
event.keyCode === 229 ||
event.key !== "Enter" ||
event.shiftKey ||
event.altKey
)
return;
event.preventDefault();
if (event.ctrlKey || event.metaKey) admit(true);
else event.currentTarget.form?.requestSubmit();
}}
/>
<Chat.ComposerActions>
<button
className="btn btn-primary btn-sm btn-circle btn-icon btn-icon-sm"
type="submit"
disabled={!draft.trim()}
aria-label={active ? "Queue message" : "Send message"}
title={active ? "Queue message (Enter)" : "Send message (Enter)"}
aria-keyshortcuts="Enter"
>
<QueueIcon action="send" />
</button>
<button
className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
type="button"
disabled={!active || !draft.trim()}
aria-label="Steer current message"
title="Steer current message (Ctrl/⌘+Enter)"
aria-keyshortcuts="Control+Enter Meta+Enter"
onClick={() => admit(true)}
>
<QueueIcon action="steer" />
</button>
</Chat.ComposerActions>
</Chat.ComposerForm>
</Chat.InputArea>
<p role="status" aria-atomic="true">
{status}
</p>
<div style={{ display: "flex", gap: "0.5rem", flexWrap: "wrap" }}>
<button
className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
type="button"
disabled={!active}
aria-label="Complete response"
title="Complete response"
onClick={complete}
>
<QueueIcon action="complete" />
</button>
<button
className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
type="button"
aria-label="Reject next admission"
title="Reject next admission"
aria-pressed={rejectNext}
onClick={() => setRejectNext(!rejectNext)}
>
<QueueIcon action="reject" />
</button>
<button
className="btn btn-ghost btn-sm btn-circle btn-icon btn-icon-sm"
type="button"
aria-label="Start fresh"
title="Start fresh"
onClick={() => {
setActive(false);
setQueue([]);
setSent([]);
setDraft("");
setTurns(0);
setRejectNext(false);
setStatus("Idle. No messages waiting.");
inputRef.current?.focus();
}}
>
<QueueIcon action="reset" />
</button>
</div>
</div>
);
}
Messages are queued locally in this example.
Composer, Attachments, and Completion
A controlled multiline composer with image/file previews, application-supplied command and skill completion, local asynchronous admission, and independent Stop. Cmd/Ctrl+Enter sends; Enter adds a line. Draft persistence, remote candidates, file validation/upload, and follow-up policy belong to your application. This example allows attachment-only messages and follow-ups during a reply.
Source
import "@duskmoon-dev/components/styles.css";
import { useState } from "react";
import { Chat } from "@duskmoon-dev/components/chat";
export function ComposerChatPreview() {
const [value, setValue] = useState("");
const [files, setFiles] = useState<File[]>([]);
const [generating, setGenerating] = useState(false);
const [messages, setMessages] = useState<string[]>([]);
const [error, setError] = useState("");
const commands = [
{ id: "help", label: "/help", description: "Show available commands" },
{ id: "review", label: "/review", description: "Use the review skill" },
];
const query = value.match(/\/[^\s/]*$/)?.[0];
const items = query
? commands.filter((item) => item.label.startsWith(query))
: [];
return (
<div
className="chat-demo"
data-chat-composer-demo
style={{ width: "min(42rem, 100%)", display: "grid", gap: "1rem" }}
>
{messages.map((message, index) => (
<Chat key={index} placement="end">
<Chat.Bubble color="primary">{message}</Chat.Bubble>
</Chat>
))}
<Chat.Composer
value={value}
onValueChange={setValue}
attachments={files}
onAttachmentsChange={(next) => {
setFiles(next);
setError(
next.some((file) => file.size > 2 * 1024 * 1024)
? "Choose files smaller than 2 MiB for this example."
: "",
);
}}
allowAttachmentOnly
generating={generating}
onStop={() => setGenerating(false)}
error={error || undefined}
onSubmit={async (submission) => {
if (submission.files.some((file) => file.size > 2 * 1024 * 1024)) {
setError("Choose files smaller than 2 MiB for this example.");
return false;
}
await new Promise((resolve) => setTimeout(resolve, 200));
setMessages((current) => [
...current,
[
submission.value,
...submission.files.map((file) => `Attached: ${file.name}`),
]
.filter(Boolean)
.join(" · "),
]);
setGenerating(true);
return true;
}}
completion={{
label: "Commands and skills",
items,
onSelect: (item, context) => {
const before = context.value.slice(0, context.selectionStart);
setValue(
before.replace(/\/[^\s/]*$/, `${item.label} `) +
context.value.slice(context.selectionEnd),
);
},
}}
textareaProps={{
"aria-label": "Message",
placeholder: "Write a message or type / for commands and skills",
}}
/>
<p role="status">
{generating
? "Reply in progress. You can send a follow-up or stop."
: "Messages are queued locally in this example."}
</p>
</div>
);
}
Basic Chat
An unboxed agent answer and a rounded user bubble with optional avatars, headers, and footers.
Source
import "@duskmoon-dev/components/styles.css";
import * as DmComponents from "@duskmoon-dev/components";
const Chat = DmComponents.Chat;
const Avatar = DmComponents.Avatar;
function ChatAvatar({ name, color }: { name: string; color?: string }) {
return <Chat.Avatar><Avatar size="sm" fallback={name} className={color} /></Chat.Avatar>;
}
export function BasicChatPreview() {
return (
<div className="chat-demo" style={{ width: "min(42rem, 100%)", display: "flex", flexDirection: "column", gap: "1rem" }}>
<Chat.Agent>
<ChatAvatar name="AI" color="avatar-primary" />
<Chat.Header>Assistant - 2:15 PM</Chat.Header>
<Chat.Content>How can I help you today? Read the <a href="/components/chat">Chat guide</a> for longer messages and links.</Chat.Content>
<Chat.Footer>Delivered</Chat.Footer>
</Chat.Agent>
<Chat placement="end">
<ChatAvatar name="GA" />
<Chat.Header>You - 2:16 PM</Chat.Header>
<Chat.Bubble color="primary">Show me a compact chat transcript.</Chat.Bubble>
<Chat.Footer>Sent</Chat.Footer>
</Chat>
</div>
);
}
Scroll-Driven Chat Indicators
Eight assistant replies pair with in-panel navigation ticks; user turns stay in the transcript without ticks.
Source
import "@duskmoon-dev/components/styles.css";
import React, { useId } from "react";
import * as DmComponents from "@duskmoon-dev/components";
const Chat = DmComponents.Chat;
const Avatar = DmComponents.Avatar;
function ChatAvatar({ name, color }: { name: string; color?: string }) {
return <Chat.Avatar><Avatar size="sm" fallback={name} className={color} /></Chat.Avatar>;
}
const scrollReplies = [
"Welcome back. The left ticks mark each assistant reply — scroll or click a tick to jump to that response.",
"Each agent row exposes a named view timeline. The parent raises timeline scope so indicators can follow visible replies.",
"No. Ticks only navigate to an agent response. User turns remain in the transcript without ticks.",
"Indicators brighten as their paired assistant message enters the panel and fade as it leaves.",
"Hash navigation scrolls the document. These buttons scroll only this conversation panel.",
"The handler aligns the agent row with the top of the panel, allowing for its scroll margin.",
"This longer answer gives the transcript enough height to scroll while the sticky indicator rail stays visible beside the message column. Long links, such as the DuskMoon component documentation, wrap inside a message instead of widening the panel.",
"Done. Click the last dash to return to this assistant response without moving the page behind the panel.",
] as const;
const scrollQuestions = [
"Can the rail follow assistant replies?",
"Should user messages get ticks?",
"What about animation range?",
"Why avoid hash links?",
"Can ticks land on the reply start?",
"Add one more long answer.",
"Great — take me to the last reply.",
] as const;
const scrollTimelines = [1, 2, 3, 4, 5, 6, 7, 8] as const;
export function ScrollDrivenChatPreview() {
const transcriptId = useId();
const replyIds = scrollTimelines.map((timeline) => `${transcriptId}-reply-${timeline}`);
return (
<Chat.Scroll className="chat-demo" style={{ width: "min(48rem, 100%)", height: "22rem" }} aria-label="Example chat transcript">
<Chat.ScrollTrack aria-label="Assistant replies">
{scrollTimelines.map((timeline, index) => <Chat.ScrollIndicator key={timeline} timeline={timeline} targetId={replyIds[index]} />)}
</Chat.ScrollTrack>
<Chat.ScrollBody>
{scrollTimelines.map((timeline, index) => (
<React.Fragment key={timeline}>
<Chat.Agent id={replyIds[index]} timeline={timeline}>
<ChatAvatar name="AI" color="avatar-primary" />
<Chat.Header>Assistant - 2:{String(index).padStart(2, "0")} PM</Chat.Header>
<Chat.Content>{scrollReplies[index]}</Chat.Content>
</Chat.Agent>
{index < scrollQuestions.length && (
<Chat placement="end">
<ChatAvatar name="GA" />
<Chat.Header>You - 2:{String(index + 1).padStart(2, "0")} PM</Chat.Header>
<Chat.Bubble color="primary">{scrollQuestions[index]}</Chat.Bubble>
</Chat>
)}
</React.Fragment>
))}
</Chat.ScrollBody>
</Chat.Scroll>
);
}
Bubble Colors
Default, semantic soft colors, and a filled primary bubble.
Source
import "@duskmoon-dev/components/styles.css";
import * as DmComponents from "@duskmoon-dev/components";
const Chat = DmComponents.Chat;
export function BubbleColorsPreview() {
const colors = ["primary", "secondary", "tertiary", "info", "success", "warning", "error"] as const;
return (
<div className="chat-demo" style={{ width: "min(42rem, 100%)", display: "flex", flexDirection: "column", gap: "0.75rem" }}>
<Chat placement="end"><Chat.Bubble>Default bubble</Chat.Bubble></Chat>
{colors.map((color) => <Chat placement="end" key={color}><Chat.Bubble color={color}>{color} bubble</Chat.Bubble></Chat>)}
<Chat placement="end"><Chat.Bubble color="primary" filled>Filled primary bubble</Chat.Bubble></Chat>
</div>
);
}
RTL Bubble Alignment
Right-to-left start and end rows with Arabic labels and bubbles.
Source
import "@duskmoon-dev/components/styles.css";
import * as DmComponents from "@duskmoon-dev/components";
const Chat = DmComponents.Chat;
const Avatar = DmComponents.Avatar;
function ChatAvatar({ name, color }: { name: string; color?: string }) {
return <Chat.Avatar><Avatar size="sm" fallback={name} className={color} /></Chat.Avatar>;
}
export function RtlBubblePreview() {
return (
<div className="chat-demo" dir="rtl" lang="ar" style={{ width: "min(42rem, 100%)", display: "flex", flexDirection: "column", gap: "1rem" }}>
<Chat.Agent><ChatAvatar name="AI" color="avatar-primary" /><Chat.Header>المساعد</Chat.Header><Chat.Content>كيف يمكنني مساعدتك اليوم؟</Chat.Content></Chat.Agent>
<Chat placement="end"><ChatAvatar name="GA" /><Chat.Header>أنت</Chat.Header><Chat.Bubble color="primary">أرني مثالاً للمحادثة.</Chat.Bubble></Chat>
</div>
);
}
Bubble Sizes
Extra small through large bubble sizes.
Source
import "@duskmoon-dev/components/styles.css";
import * as DmComponents from "@duskmoon-dev/components";
const Chat = DmComponents.Chat;
export function BubbleSizesPreview() {
const sizes = [["xs", "Extra small transcript bubble"], ["sm", "Small dense chat bubble"], ["md", "Medium default chat bubble"], ["lg", "Large accessible chat bubble"]] as const;
return (
<div className="chat-demo" style={{ width: "min(42rem, 100%)", display: "flex", flexDirection: "column", gap: "0.75rem" }}>
{sizes.map(([size, label]) => <Chat placement="end" key={size}><Chat.Bubble size={size}>{label}</Chat.Bubble></Chat>)}
</div>
);
}
Working · 2 tool calls · 0 failed
Thinking (3s)
get_weatherRunning...
{"city":"Tokyo"}get_weatherDone
{"city":"Tokyo"}{"temperature":"18 C","condition":"cloudy"}Reasoning, Tool Call, and Streaming
Reasoning with a running tool, a completed call and result, and streaming final content inside one bubble.
Source
import "@duskmoon-dev/components/styles.css";
import * as DmComponents from "@duskmoon-dev/components";
const Chat = DmComponents.Chat;
const Avatar = DmComponents.Avatar;
function ChatAvatar({ name, color }: { name: string; color?: string }) {
return <Chat.Avatar><Avatar size="sm" fallback={name} className={color} /></Chat.Avatar>;
}
function CodePane({ title, children }: { title: "Call" | "Result"; children: string }) {
return (
<div className="code-block code-block-compact">
<div className="code-header"><span className="code-title">{title}</span><span className="code-language">json</span></div>
<div className="code-content"><pre tabIndex={0} aria-label={`${title} JSON payload`}><code>{children}</code></pre></div>
</div>
);
}
export function LlmChatPreview() {
return (
<div className="chat-demo" style={{ width: "min(48rem, 100%)", display: "flex", flexDirection: "column", gap: "1rem" }}>
<Chat.Agent aria-live="polite">
<ChatAvatar name="AI" color="avatar-info" />
<Chat.Header>Assistant - 2:18 PM</Chat.Header>
<Chat.Work open><Chat.WorkSummary>Working · 2 tool calls · 0 failed</Chat.WorkSummary><Chat.WorkBody>
<Chat.Reasoning open>
<summary>Thinking (3s)</summary>
<div className="chat-reasoning-body">
<div>I should call the weather tool, then summarize the result in one sentence.</div>
<Chat.Tool status="running" open>
<Chat.ToolHeader><span>get_weather</span><Chat.ToolStatus>Running...</Chat.ToolStatus></Chat.ToolHeader>
<Chat.ToolCall><CodePane title="Call">{'{"city":"Tokyo"}'}</CodePane></Chat.ToolCall>
</Chat.Tool>
<div>Tool returned cloudy at 18 C. Drafting the final answer.</div>
</div>
</Chat.Reasoning>
<Chat.Tool status="success" open>
<Chat.ToolHeader><span>get_weather</span><Chat.ToolStatus>Done</Chat.ToolStatus></Chat.ToolHeader>
<Chat.ToolCall><CodePane title="Call">{'{"city":"Tokyo"}'}</CodePane></Chat.ToolCall>
<Chat.ToolResult><CodePane title="Result">{'{"temperature":"18 C","condition":"cloudy"}'}</CodePane></Chat.ToolResult>
</Chat.Tool>
</Chat.WorkBody></Chat.Work><Chat.Content streaming>It is 18 C and cloudy in Tokyo right now.</Chat.Content>
<Chat.Footer>Streaming</Chat.Footer>
</Chat.Agent>
</div>
);
}
Typing and Streaming
First-token typing and an active streaming reply.
Source
import "@duskmoon-dev/components/styles.css";
import * as DmComponents from "@duskmoon-dev/components";
const Chat = DmComponents.Chat;
const Avatar = DmComponents.Avatar;
function ChatAvatar({ name, color }: { name: string; color?: string }) {
return <Chat.Avatar><Avatar size="sm" fallback={name} className={color} /></Chat.Avatar>;
}
export function LiveStatesPreview() {
return (
<div className="chat-demo" style={{ width: "min(42rem, 100%)", display: "flex", flexDirection: "column", gap: "1rem" }}>
<Chat.Agent><ChatAvatar name="AI" color="avatar-secondary" /><Chat.Content><Chat.Typing /></Chat.Content></Chat.Agent>
<Chat.Agent><ChatAvatar name="AI" color="avatar-secondary" /><Chat.Content streaming>Generating a response</Chat.Content></Chat.Agent>
</div>
);
}
Token Metrics and Message Actions
Edit, Stop, Retry, and Copy appear on row hover or focus; touch devices keep them visible, with local outcomes alongside status and token metrics.
Source
import "@duskmoon-dev/components/styles.css";
import React, { useId, useState } from "react";
import * as DmComponents from "@duskmoon-dev/components";
const Chat = DmComponents.Chat;
const Avatar = DmComponents.Avatar;
const Tooltip = DmComponents.Tooltip;
function ChatAvatar({ name, color }: { name: string; color?: string }) {
return <Chat.Avatar><Avatar size="sm" fallback={name} className={color} /></Chat.Avatar>;
}
function Action({ label, onClick, children }: {
label: string;
onClick: () => void;
children: React.ReactNode;
}) {
return (
<Tooltip title={label}>
<button type="button" className="btn btn-ghost btn-xs btn-square" aria-label={label} onClick={onClick}>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" focusable="false">
{children}
</svg>
</button>
</Tooltip>
);
}
export function MessageActionsPreview() {
const editId = useId();
const [question, setQuestion] = useState("Summarize the deployment checks.");
const [draft, setDraft] = useState(question);
const [editing, setEditing] = useState(false);
const [generating, setGenerating] = useState(true);
const [revision, setRevision] = useState(0);
const [feedback, setFeedback] = useState("");
const answer = revision === 0 ? "The build completed and all deployment smoke tests passed." : `Revision ${revision}: the build and smoke tests passed.`;
async function copyAnswer() {
try {
await navigator.clipboard.writeText(answer);
setFeedback("Deployment summary copied.");
} catch {
setFeedback("Copy failed. Select the summary to copy it.");
}
}
return (
<div className="chat-demo" style={{ width: "min(42rem, 100%)", display: "flex", flexDirection: "column", gap: "1rem" }}>
<Chat placement="end">
<ChatAvatar name="GA" /><Chat.Header>You</Chat.Header>
<Chat.Bubble color="primary">{question}</Chat.Bubble>
<Chat.Status><Chat.StatusItem>Sent</Chat.StatusItem><Chat.StatusItem><Chat.StatusValue>12</Chat.StatusValue> tokens</Chat.StatusItem></Chat.Status>
<Chat.Actions hover>
<Action label="Edit your deployment question" onClick={() => { setDraft(question); setEditing(true); }}><path d="m16 3 5 5-12 12H4v-5Z" /><path d="m14 5 5 5" /></Action>
</Chat.Actions>
{editing && <form onSubmit={(event) => { event.preventDefault(); setQuestion(draft); setEditing(false); setFeedback("Question updated."); }}>
<label htmlFor={editId}>Edit question</label>
<input id={editId} className="input" value={draft} onChange={(event) => setDraft(event.target.value)} />
<button type="submit" className="btn btn-primary btn-xs">Save</button>
</form>}
</Chat>
<Chat.Agent>
<ChatAvatar name="AI" color="avatar-secondary" /><Chat.Header>Assistant · {generating ? "Generating" : "Stopped"}</Chat.Header>
<Chat.Content streaming={generating}>{generating ? "Checking the build and smoke-test results" : "Generation stopped."}</Chat.Content>
<Chat.Status><Chat.StatusItem>{generating ? "Generating" : "Stopped"}</Chat.StatusItem><Chat.StatusItem><Chat.StatusValue>42</Chat.StatusValue> token/s</Chat.StatusItem><Chat.StatusItem><Chat.StatusValue>256</Chat.StatusValue> tokens</Chat.StatusItem></Chat.Status>
{generating && <Chat.Actions hover><Action label="Stop generating the deployment summary" onClick={() => { setGenerating(false); setFeedback("Generation stopped."); }}><rect x="5" y="5" width="14" height="14" rx="2" /></Action></Chat.Actions>}
</Chat.Agent>
<Chat.Agent>
<ChatAvatar name="AI" color="avatar-primary" /><Chat.Header>Assistant · Completed</Chat.Header>
<Chat.Content>{answer}</Chat.Content>
<Chat.Status><Chat.StatusItem>Completed</Chat.StatusItem><Chat.StatusItem><Chat.StatusValue>42</Chat.StatusValue> token/s</Chat.StatusItem><Chat.StatusItem><Chat.StatusValue>1,248</Chat.StatusValue> tokens</Chat.StatusItem></Chat.Status>
<Chat.Actions hover>
<Action label="Retry the deployment summary" onClick={() => { setRevision((current) => current + 1); setFeedback("Summary regenerated locally."); }}><path d="M3 11a9 9 0 1 1 2.6 7.4" /><path d="M3 4v7h7" /></Action>
<Action label="Copy the deployment summary" onClick={() => { void copyAnswer(); }}><rect x="8" y="8" width="13" height="13" rx="2" /><path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3" /></Action>
</Chat.Actions>
</Chat.Agent>
<p role="status">{feedback}</p>
</div>
);
}
search_docsPending
run_queryRunning...
get_profileDone
deploy_previewFailed
Tool Statuses
Pending, running, successful, and failed tool headers.
Source
import "@duskmoon-dev/components/styles.css";
import * as DmComponents from "@duskmoon-dev/components";
const Chat = DmComponents.Chat;
export function ToolStatusesPreview() {
const tools = [["pending", "search_docs", "Pending"], ["running", "run_query", "Running..."], ["success", "get_profile", "Done"], ["error", "deploy_preview", "Failed"]] as const;
return (
<div className="chat-demo" style={{ width: "min(42rem, 100%)", display: "flex", flexDirection: "column", gap: "0.75rem" }}>
{tools.map(([status, name, label]) => <Chat.Tool key={status} status={status} open><Chat.ToolHeader><span>{name}</span><Chat.ToolStatus>{label}</Chat.ToolStatus></Chat.ToolHeader></Chat.Tool>)}
</div>
);
}
Summary: the deployment is ready.
- Build completed
- Smoke test passed
Markdown Agent Content
Unboxed agent answer with Markdown typography.
Source
import "@duskmoon-dev/components/styles.css";
import * as DmComponents from "@duskmoon-dev/components";
const Chat = DmComponents.Chat;
const Avatar = DmComponents.Avatar;
function ChatAvatar({ name, color }: { name: string; color?: string }) {
return <Chat.Avatar><Avatar size="sm" fallback={name} className={color} /></Chat.Avatar>;
}
export function MarkdownChatPreview() {
return (
<div className="chat-demo" style={{ width: "min(42rem, 100%)" }}>
<Chat.Agent><ChatAvatar name="AI" color="avatar-tertiary" /><Chat.Content><div className="markdown-body"><p><strong>Summary:</strong> the deployment is ready.</p><ul><li>Build completed</li><li>Smoke test passed</li></ul></div></Chat.Content></Chat.Agent>
</div>
);
}
API
The API reference below lists every parsed exported type or interface for Chat. Start with `placement`, `timeline`, `hover`, `targetId` for common usage.
packages/components/src/components/chat/Chat.types.tsScenarios: packages/components/src/components/chat/Chat.test.tsx| Prop | Type | Required | Description |
|---|---|---|---|
placement | ChatPlacement | No | Position the turn at the start or end of the conversation row. |
timeline | ChatTimeline | No | Pair an assistant row with a scroll indicator (slots 1–24). |
| Prop | Type | Required | Description |
|---|---|---|---|
hover | boolean | No | Reveal actions on message hover or keyboard focus. |
| Prop | Type | Required | Description |
|---|---|---|---|
targetId | string | Yes | targetId configures Chat. |
timeline | ChatTimeline | Yes | timeline configures Chat. |
| Prop | Type | Required | Description |
|---|---|---|---|
color | ChatBubbleColor | No | Apply a semantic DuskMoon color to the bubble. |
size | ChatBubbleSize | No | Control the bubble padding and font size. @default "md" |
filled | boolean | No | Use the saturated form of the selected color. |
streaming | boolean | No | Show the live streaming caret after the bubble content. |
collapsible | boolean | No | Collapse sent user messages exceeding six rendered lines. |
expanded | boolean | No | expanded configures Chat. |
defaultExpanded | boolean | No | defaultExpanded configures Chat. |
onExpandedChange | (expanded: boolean) => void | No | onExpandedChange configures Chat. |
| Prop | Type | Required | Description |
|---|---|---|---|
streaming | boolean | No | streaming configures Chat. |
| Prop | Type | Required | Description |
|---|---|---|---|
color | ChatComposerColor | No | color configures Chat. |
ghost | boolean | No | ghost configures Chat. |
| Prop | Type | Required | Description |
|---|---|---|---|
id | string | Yes | id configures Chat. |
text | string | Yes | text configures Chat. |
attachment | { src: string; alt: string } | No | attachment configures Chat. |
| Prop | Type | Required | Description |
|---|---|---|---|
items | readonly ChatQueueItem[] | Yes | items configures Chat. |
activeId | string | No | Stable identity of the next message; defaults to the first item. |
pendingIds | readonly string[] | No | The application owns pending state and removes messages after acknowledgment. |
steerDisabled | boolean | No | steerDisabled configures Chat. |
renderItemActions | ( | No | Optional authoritative controls; legacy Steer/Remove remain the default. |
item | ChatQueueItem, | Yes | item configures Chat. |
index | number, | Yes | index configures Chat. |
pending | boolean, | Yes | pending configures Chat. |
renderItemContent | (item: ChatQueueItem, index: number) => ReactNode | No | renderItemContent configures Chat. |
onSteer | (id: string) => void | Yes | onSteer configures Chat. |
onRemove | (id: string) => void | Yes | onRemove configures Chat. |
label | string | No | Accessible queue name. @default "Waiting messages" |
| Prop | Type | Required | Description |
|---|---|---|---|
status | ChatToolState | No | Reflect the current tool-call state. |
| Prop | Type | Required | Description |
|---|---|---|---|
value | string | Yes | value configures Chat. |
files | File[] | Yes | files configures Chat. |
| Prop | Type | Required | Description |
|---|---|---|---|
id | string | Yes | id configures Chat. |
label | string | Yes | label configures Chat. |
icon | ReactNode | No | Optional presentation; never part of the submitted document. |
sourceLabel | string | No | sourceLabel configures Chat. |
description | ReactNode | No | description configures Chat. |
disabled | boolean | No | disabled configures Chat. |
group | string | No | group configures Chat. |
| Prop | Type | Required | Description |
|---|---|---|---|
value | string | Yes | value configures Chat. |
selectionStart | number | Yes | selectionStart configures Chat. |
selectionEnd | number | Yes | selectionEnd configures Chat. |
| Prop | Type | Required | Description |
|---|---|---|---|
items | readonly ChatComposerCompletion[] | Yes | items configures Chat. |
onSelect | ( | Yes | onSelect configures Chat. |
item | ChatComposerCompletion, | Yes | item configures Chat. |
context | ChatComposerCompletionContext, | Yes | context configures Chat. |
label | string | No | label configures Chat. |
| Prop | Type | Required | Description |
|---|---|---|---|
submit | () => void | Yes | submit configures Chat. |
submitting | boolean | Yes | submitting configures Chat. |
canSubmit | boolean | Yes | canSubmit configures Chat. |
disabled | boolean | Yes | disabled configures Chat. |
generating | boolean | Yes | generating configures Chat. |
openAttachments | () => void | Yes | openAttachments configures Chat. |
| Prop | Type | Required | Description |
|---|---|---|---|
remove | () => void | Yes | remove configures Chat. |
disabled | boolean | Yes | disabled configures Chat. |
| Prop | Type | Required | Description |
|---|---|---|---|
value | string | Yes | value configures Chat. |
scope | ComposerScope | No | Isolate pending admission and completion state when changing contexts. |
onValueChange | (value: string) => void | Yes | onValueChange configures Chat. |
onSubmit | ( | Yes | Return false to reject admission and retain the draft. |
snapshot | ChatComposerSubmission, | Yes | snapshot configures Chat. |
attachments | File[] | No | attachments configures Chat. |
onAttachmentsChange | (files: File[]) => void | No | Enables the native file picker and attachment removal controls. |
accept | string | No | accept configures Chat. |
attachmentPolicy | ComposerAttachmentIntakePolicy | No | Shared validation for picker, pasted files, and dropped files. |
onAttachmentRejected | ( | No | onAttachmentRejected configures Chat. |
rejected | readonly ComposerAttachmentRejection[], | Yes | rejected configures Chat. |
multiple | boolean | No | @default true |
allowAttachmentOnly | boolean | No | Permit a draft containing only files. @default false |
compact | boolean | No | Compact Add menu, one send/stop action and ready-image strip. @default false |
addMenu | ReactNode | No | Additional actions in the compact Add menu. |
context | ReactNode | No | Attached context bar, rendered first inside the composer. |
disabled | boolean | No | disabled configures Chat. |
busy | boolean | No | Gates submission while keeping the draft editable. |
generating | boolean | No | Shows Stop when onStop is supplied; does not prevent submission. |
canSubmit | boolean | No | Application-controlled admission, including follow-ups. @default true |
onStop | () => void | No | onStop configures Chat. |
error | ReactNode | No | error configures Chat. |
onSubmitError | (error: unknown) => void | No | onSubmitError configures Chat. |
clearOnSubmit | boolean | No | Clear unchanged admitted text and only admitted file entries. @default true |
completion | ChatComposerCompletionConfig | No | completion configures Chat. |
minRows | number | No | @default 1 |
maxRows | number | No | @default 6 |
textareaProps | Omit< | No | textareaProps configures Chat. |
attachLabel | string | No | attachLabel configures Chat. |
sendLabel | string | No | sendLabel configures Chat. |
stopLabel | string | No | stopLabel configures Chat. |
renderAttachment | ( | No | renderAttachment configures Chat. |
file | File, | Yes | file configures Chat. |
context | ChatComposerAttachmentContext, | Yes | context configures Chat. |
children | ReactNode | ((context: ChatComposerActionContext) => ReactNode) | No | Extra application actions rendered alongside Attach, Stop, and Send. |
Type definition
"start" | "end"Type definition
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24Type definition
| "primary" | "secondary" | "tertiary" | "accent" | "neutral" | "base" | "info" | "success" | "warning" | "error"Type definition
"xs" | "sm" | "md" | "lg"Type definition
"pending" | "running" | "success" | "error"Type definition
ComponentProps<"div">Type definition
ComponentProps<"div">Type definition
ComponentProps<"div">Type definition
ComponentProps<"div">Type definition
ComponentProps<"span">Type definition
ComponentProps<"span">Type definition
ComponentProps<"div">Type definition
ComponentProps<"div">Type definition
ComponentProps<"div">Type definition
Omit<ChatProps, "placement">Type definition
ComponentProps<"details">Type definition
ComponentProps<"summary">Type definition
ComponentProps<"div">Type definition
ComponentProps<"div">Type definition
| "primary" | "secondary" | "tertiary" | "info" | "success" | "warning" | "error"Type definition
ComponentProps<"textarea">Type definition
ComponentProps<"div">Type definition
ComponentProps<"kbd">Type definition
ComponentProps<"details">Type definition
ComponentProps<"summary">Type definition
ComponentProps<"span">Type definition
ComponentProps<"div">Type definition
ComponentProps<"div">Type definition
Omit<ComponentProps<"span">, "children">Type definition
ChatPartComponent<HTMLDivElement, ChatProps> & { Composer: ChatPartComponent<HTMLDivElement, ChatComposerProps>