feat(ui): make the composer the chat with Archie (#2018)

The composer is the chat again: the old dashboard's chat, copied from
ui/src/chat and moved onto the chat module's API. It is the full /composer
page and a dock on every other page, with the session list, session menu,
left, right and floating positions and a full-screen sheet at phone width.
A message carries the page it was asked from and the page's suggested
prompts; a reply streams its thinking, tool calls and text, Stop cancels it,
and a message sent meanwhile is queued by the server. Workflow notifications
and approval requests show in the conversation as cards, and an approval is
answered only with its card's Approve or Deny.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
samandCopilot committed 2026-11-19 19:43:21 +11:00
1 parent cbfcd43018
commit 5642058fd0
34 files changed
+3723 -329

No files matched your search

+57 -36
View File
@@ -1,16 +1,23 @@
<script setup lang="ts">
import { ref } from "vue";
import { RouterLink, RouterView } from "vue-router";
import { ref, watch } from "vue";
import { RouterLink, RouterView, useRoute } from "vue-router";
import { Toaster } from "vue-sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Section } from "@/components/ui/section";
import { TooltipProvider } from "@/components/ui/tooltip";
import { clearToken, invalidTokenMessage, isValidToken, setToken, token } from "./api";
import ChatDock from "./chat/ChatDock.vue";
import ChatTopbarButton from "./chat/ChatTopbarButton.vue";
import { unauthorized } from "./chat/state";
/**
* The shell: the admin token gate, then the composer and runs. The token is
* the bootstrap credential until identities exist.
* The shell: the admin token gate, then the pages, with the chat docked to
* every page but the composer, which is the chat itself. The token is the
* bootstrap credential until identities exist.
*/
const route = useRoute();
const savedToken = token();
const invalidSavedToken = savedToken !== "" && !isValidToken(savedToken);
if (invalidSavedToken) clearToken();
@@ -34,39 +41,53 @@ function signOut() {
clearToken();
signedIn.value = false;
}
watch(unauthorized, (refused) => {
if (!refused) return;
unauthorized.value = false;
signOut();
});
</script>
<template>
<div class="mx-auto flex min-h-dvh max-w-4xl flex-col gap-4 p-4">
<header class="flex items-center gap-4">
<span class="text-title font-semibold">Archie</span>
<nav v-if="signedIn" class="flex flex-1 flex-wrap items-center gap-x-3 gap-y-1 text-label">
<RouterLink to="/composer" active-class="text-foreground" class="text-muted-foreground">Composer</RouterLink>
<RouterLink to="/runs" active-class="text-foreground" class="text-muted-foreground">Runs</RouterLink>
<RouterLink to="/unmatched" active-class="text-foreground" class="text-muted-foreground">Unmatched</RouterLink>
<RouterLink to="/events" active-class="text-foreground" class="text-muted-foreground">Events</RouterLink>
<RouterLink to="/classes" active-class="text-foreground" class="text-muted-foreground">Classes</RouterLink>
<RouterLink to="/people" active-class="text-foreground" class="text-muted-foreground">People</RouterLink>
<RouterLink to="/controls" active-class="text-foreground" class="text-muted-foreground">Controls</RouterLink>
<RouterLink to="/extensions" active-class="text-foreground" class="text-muted-foreground">Extensions</RouterLink>
<RouterLink to="/sources" active-class="text-foreground" class="text-muted-foreground">Sources</RouterLink>
<RouterLink to="/triggers" active-class="text-foreground" class="text-muted-foreground">Triggers</RouterLink>
<RouterLink to="/credentials" active-class="text-foreground" class="text-muted-foreground">Credentials</RouterLink>
<RouterLink to="/settings" active-class="text-foreground" class="text-muted-foreground">Settings</RouterLink>
<Button variant="ghost" size="xs" class="ml-auto" @click="signOut">Sign out</Button>
</nav>
</header>
<form v-if="!signedIn" class="max-w-md" @submit.prevent="signIn">
<Section title="Admin token">
<div class="flex gap-2">
<Input v-model="draft" type="password" autocomplete="off" aria-label="Admin token" />
<Button type="submit">Sign in</Button>
</div>
<p v-if="signInError" role="alert" class="mt-2 text-label text-destructive">{{ signInError }}</p>
</Section>
</form>
<RouterView v-else v-slot="{ Component }">
<component :is="Component" @unauthorized="signOut" />
</RouterView>
</div>
<TooltipProvider :delay-duration="350">
<div class="mx-auto flex min-h-dvh max-w-4xl flex-col gap-4 p-4 [padding-left:max(1rem,var(--chat-pin-l,0px))] [padding-right:max(1rem,var(--chat-pin-r,0px))]">
<header class="flex items-center gap-4">
<span class="text-title font-semibold">Archie</span>
<nav v-if="signedIn" class="flex flex-1 flex-wrap items-center gap-x-3 gap-y-1 text-label">
<RouterLink to="/composer" active-class="text-foreground" class="text-muted-foreground">Composer</RouterLink>
<RouterLink to="/runs" active-class="text-foreground" class="text-muted-foreground">Runs</RouterLink>
<RouterLink to="/unmatched" active-class="text-foreground" class="text-muted-foreground">Unmatched</RouterLink>
<RouterLink to="/events" active-class="text-foreground" class="text-muted-foreground">Events</RouterLink>
<RouterLink to="/classes" active-class="text-foreground" class="text-muted-foreground">Classes</RouterLink>
<RouterLink to="/people" active-class="text-foreground" class="text-muted-foreground">People</RouterLink>
<RouterLink to="/controls" active-class="text-foreground" class="text-muted-foreground">Controls</RouterLink>
<RouterLink to="/extensions" active-class="text-foreground" class="text-muted-foreground">Extensions</RouterLink>
<RouterLink to="/sources" active-class="text-foreground" class="text-muted-foreground">Sources</RouterLink>
<RouterLink to="/triggers" active-class="text-foreground" class="text-muted-foreground">Triggers</RouterLink>
<RouterLink to="/credentials" active-class="text-foreground" class="text-muted-foreground">Credentials</RouterLink>
<RouterLink to="/settings" active-class="text-foreground" class="text-muted-foreground">Settings</RouterLink>
<span class="ml-auto flex items-center gap-1">
<ChatTopbarButton v-if="route.name !== 'composer'" />
<Button variant="ghost" size="xs" @click="signOut">Sign out</Button>
</span>
</nav>
</header>
<form v-if="!signedIn" class="max-w-md" @submit.prevent="signIn">
<Section title="Admin token">
<div class="flex gap-2">
<Input v-model="draft" type="password" autocomplete="off" aria-label="Admin token" />
<Button type="submit">Sign in</Button>
</div>
<p v-if="signInError" role="alert" class="mt-2 text-label text-destructive">{{ signInError }}</p>
</Section>
</form>
<RouterView v-else v-slot="{ Component }">
<component :is="Component" @unauthorized="signOut" />
</RouterView>
<div aria-hidden="true" class="h-[var(--chat-dock-clear,0px)] flex-none" />
</div>
<ChatDock v-if="signedIn && route.name !== 'composer'" />
<Toaster position="bottom-right" rich-colors close-button />
</TooltipProvider>
</template>
+17 -279
View File
@@ -1,287 +1,25 @@
<script setup lang="ts">
import { ArrowDownToLine, ArrowUpRight, ChevronDown, ClipboardCheck, Inbox, Radio, ShieldAlert } from "@lucide/vue";
import { nextTick, onBeforeUnmount, onMounted, ref } from "vue";
import { RouterLink } from "vue-router";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardAction, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { Empty, EmptyHeader, EmptyMedia, EmptyTitle } from "@/components/ui/empty";
import { Item, ItemActions, ItemContent, ItemMedia, ItemTitle } from "@/components/ui/item";
import { ReadError } from "@/components/ui/read-error";
import { Section } from "@/components/ui/section";
import { Spinner } from "@/components/ui/spinner";
import { Timestamp } from "@/components/ui/timestamp";
import {
answerApproval, composerStream, latestMessages, messagesAfter, pendingApprovals, type Message,
type PendingApproval, Unauthorized,
} from "./api";
import ChatBar from "./chat/ChatBar.vue";
import ChatComposer from "./chat/ChatComposer.vue";
import ChatPending from "./chat/ChatPending.vue";
import ChatTranscript from "./chat/ChatTranscript.vue";
import { useChat } from "./chat/state";
/**
* The stream sends sequence numbers, not message bodies. Fetch messages
* after the last loaded sequence number to catch up after reconnecting.
* The composer: the chat with Archie at full size, the same conversation the
* dock shows on every other page.
*/
const emit = defineEmits<{ unauthorized: [] }>();
const messages = ref<Message[]>([]);
const approvals = ref<PendingApproval[]>([]);
const approvalReadFailed = ref(false);
const loading = ref(true);
const error = ref("");
const answering = ref<string | null>(null);
const activity = ref<HTMLElement | null>(null);
const atLatest = ref(true);
const controller = new AbortController();
let approvalRead = 0;
let following = false;
const activityKinds = {
notification: { icon: Radio, label: "Workflow update" },
approval_request: { icon: ShieldAlert, label: "Approval requested" },
approval_answer: { icon: ClipboardCheck, label: "Decision recorded" },
} satisfies Record<Message["kind"], { icon: typeof Radio; label: string }>;
async function loadApprovals() {
const read = ++approvalRead;
try {
const pending = await pendingApprovals(controller.signal);
if (read !== approvalRead || controller.signal.aborted) return;
approvals.value = pending;
approvalReadFailed.value = false;
} catch (err) {
if (read !== approvalRead || controller.signal.aborted) return;
if (err instanceof Unauthorized) fail(err);
else approvalReadFailed.value = true;
}
}
async function answer(request: PendingApproval, approved: boolean) {
if (answering.value) return;
answering.value = request.id;
try {
await answerApproval(request.id, approved);
++approvalRead;
approvals.value = approvals.value.filter(({ id }) => id !== request.id);
await loadApprovals();
} catch (err) {
fail(err);
} finally {
answering.value = null;
}
}
const cursor = () => messages.value.at(-1)?.seq ?? 0;
function updateReadingPosition() {
const view = activity.value;
if (view) atLatest.value = view.scrollHeight - view.clientHeight - view.scrollTop <= 2;
}
async function updateAfterDisclosure() {
await nextTick();
updateReadingPosition();
}
function showLatest(focus = false) {
const view = activity.value;
if (!view) return;
view.scrollTop = view.scrollHeight;
if (focus) view.focus({ preventScroll: true });
updateReadingPosition();
}
async function load() {
loading.value = true;
error.value = "";
try {
const [latest] = await Promise.all([latestMessages(controller.signal), loadApprovals()]);
messages.value = latest;
} catch (err) {
fail(err);
} finally {
loading.value = false;
}
await nextTick();
showLatest();
if (!following && !error.value && !controller.signal.aborted) {
following = true;
void follow();
}
}
async function catchUp(through?: number) {
do {
const more = await messagesAfter(cursor(), controller.signal);
if (more.length === 0) break;
updateReadingPosition();
messages.value.push(...more);
await nextTick();
if (atLatest.value) showLatest();
else updateReadingPosition();
} while (through === undefined || cursor() < through);
await loadApprovals();
}
async function follow() {
let backoff = 1000;
while (!controller.signal.aborted) {
try {
for await (const seq of composerStream(controller.signal, catchUp)) {
backoff = 1000;
if (seq > cursor()) await catchUp(seq);
}
} catch (err) {
if (controller.signal.aborted) return;
if (err instanceof Unauthorized) return fail(err);
}
await new Promise((resolve) => setTimeout(resolve, backoff));
backoff = Math.min(backoff * 2, 30000);
}
}
function fail(err: unknown) {
if (controller.signal.aborted) return;
if (err instanceof Unauthorized) emit("unauthorized");
error.value = err instanceof Error ? err.message : String(err);
}
onMounted(load);
onBeforeUnmount(() => controller.abort());
useChat();
</script>
<template>
<div class="flex min-w-0 flex-col gap-4">
<Spinner v-if="loading" />
<ReadError v-else-if="error" :message="error" retry-label="Retry" @retry="load" />
<template v-else>
<Section v-if="approvals.length || approvalReadFailed" title="Action required" class="mb-0 ring-warn/40">
<template #action>
<Badge v-if="approvals.length" variant="warn" class="tabular-nums">
{{ approvals.length }} awaiting approval
</Badge>
</template>
<ReadError v-if="approvalReadFailed" message="Couldn't load pending approvals." retry-label="Retry" @retry="loadApprovals" />
<ul v-else class="flex max-h-[24dvh] flex-col gap-2 overflow-y-auto p-1">
<Item v-for="request in approvals" :key="request.id" as="li" variant="outline" class="items-start">
<ItemMedia variant="icon" class="mt-1 text-warn">
<ShieldAlert aria-hidden="true" />
</ItemMedia>
<Collapsible v-slot="{ open }" class="min-w-0 flex-1">
<ItemTitle class="w-auto break-words">{{ request.action }}</ItemTitle>
<div class="flex flex-wrap items-center justify-between gap-2">
<span class="text-caption text-muted-foreground">
Respond by <Timestamp :at="request.step_deadline || request.deadline" absolute />
</span>
<CollapsibleTrigger as-child>
<Button
variant="outline"
size="sm"
:aria-label="`${open ? 'Hide' : 'Review'} approval for ${request.action}`"
>
{{ open ? "Hide approval" : "Review approval" }}
<ChevronDown :class="open && 'rotate-180'" aria-hidden="true" data-icon="inline-end" />
</Button>
</CollapsibleTrigger>
</div>
<CollapsibleContent class="mt-3 border-t pt-3">
<p class="whitespace-pre-wrap break-words leading-relaxed">{{ request.summary }}</p>
<ItemActions class="mt-3 flex-wrap">
<Button size="sm" :disabled="answering !== null" @click="answer(request, true)">Approve</Button>
<Button variant="outline" size="sm" :disabled="answering !== null" @click="answer(request, false)">Deny</Button>
<Button
v-if="request.run_id && request.run_id !== '00000000-0000-0000-0000-000000000000'"
variant="link"
size="sm"
as-child
>
<RouterLink
:to="{ name: 'run', params: { id: request.run_id } }"
:aria-label="`View run for ${request.action} (${request.run_id})`"
>View run <ArrowUpRight aria-hidden="true" data-icon="inline-end" /></RouterLink>
</Button>
</ItemActions>
</CollapsibleContent>
</Collapsible>
</Item>
</ul>
</Section>
<Card class="gap-0 pb-0">
<CardHeader class="mb-3">
<CardTitle id="composer-activity">Recent activity</CardTitle>
<CardDescription v-if="messages.length" id="composer-activity-scope">Earlier activity is not shown.</CardDescription>
<CardAction v-if="!atLatest && messages.length">
<Button size="sm" variant="outline" @click="showLatest(true)">
<ArrowDownToLine aria-hidden="true" data-icon="inline-start" /> Jump to latest
</Button>
</CardAction>
</CardHeader>
<Empty v-if="messages.length === 0">
<EmptyHeader>
<EmptyMedia variant="icon"><Inbox aria-hidden="true" /></EmptyMedia>
<EmptyTitle>No messages yet</EmptyTitle>
</EmptyHeader>
</Empty>
<div
v-else
ref="activity"
role="region"
aria-labelledby="composer-activity"
aria-describedby="composer-activity-scope"
tabindex="0"
class="max-h-[44dvh] overflow-y-auto border-t focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring sm:max-h-[55dvh]"
@scroll.passive="updateReadingPosition"
>
<ol class="divide-y divide-border">
<Item v-for="m in messages" :key="m.id" as="li" class="flex-nowrap items-start gap-3 rounded-none border-0 px-4 py-2">
<ItemMedia variant="icon" class="mt-1 text-muted-foreground">
<component :is="activityKinds[m.kind].icon" aria-hidden="true" />
</ItemMedia>
<ItemContent class="min-w-0">
<div class="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">
<ItemTitle class="min-w-0 break-words">
<span class="sr-only">{{ activityKinds[m.kind].label }}: </span>{{ m.title }}
</ItemTitle>
<Timestamp :at="m.created_at" class="text-caption text-muted-foreground" />
</div>
<Collapsible v-if="m.body || m.attempts?.length || m.run_id" v-slot="{ open }" @update:open="updateAfterDisclosure">
<ItemActions class="-ml-2 flex-wrap">
<CollapsibleTrigger v-if="m.body || m.attempts?.length" as-child>
<Button variant="ghost" size="xs" :aria-label="`${open ? 'Hide' : 'View'} details for ${m.title}`">
{{ open ? "Hide details" : "View details" }}
<ChevronDown :class="open && 'rotate-180'" aria-hidden="true" data-icon="inline-end" />
</Button>
</CollapsibleTrigger>
<Button v-if="m.run_id" variant="link" size="xs" as-child>
<RouterLink
:to="{ name: 'run', params: { id: m.run_id } }"
:aria-label="`View run for ${m.title} (${m.run_id})`"
>View run <ArrowUpRight aria-hidden="true" data-icon="inline-end" /></RouterLink>
</Button>
</ItemActions>
<CollapsibleContent v-if="m.body || m.attempts?.length" class="mt-2 rounded-lg bg-muted/50 p-3">
<p v-if="m.body" class="whitespace-pre-wrap break-words leading-relaxed">{{ m.body }}</p>
<details v-if="m.attempts?.length" :class="m.body && 'mt-2'" class="text-caption" @toggle="updateReadingPosition">
<summary class="cursor-pointer font-medium">Delivery attempts</summary>
<ul class="mt-2 flex flex-col gap-2">
<li v-for="a in m.attempts" :key="`${a.channel}:${a.attempt}`" class="flex flex-wrap items-center gap-2">
<span class="font-medium">{{ a.channel }}</span>
<span class="text-muted-foreground">Attempt {{ a.attempt }}</span>
<Badge :variant="a.ok ? 'secondary' : 'danger'">{{ a.ok ? "Delivered" : "Failed" }}</Badge>
<span class="tabular-nums text-muted-foreground">{{ a.duration_ms }} ms</span>
<Timestamp :at="a.at" />
<span v-if="a.response" class="font-mono break-all">{{ a.response }}</span>
<span v-if="a.error" class="text-destructive break-all">{{ a.error }}</span>
</li>
</ul>
</details>
</CollapsibleContent>
</Collapsible>
</ItemContent>
</Item>
</ol>
</div>
</Card>
</template>
</div>
<section
aria-label="Chat with Archie"
class="flex h-[calc(100dvh-6rem)] min-h-96 min-w-0 flex-col rounded-lg border border-border-strong bg-popover"
>
<ChatBar />
<ChatTranscript />
<ChatPending />
<ChatComposer :open="true" />
</section>
</template>
+117
View File
@@ -688,3 +688,120 @@ export async function* composerStream(signal: AbortSignal, onConnected?: () => P
reader.releaseLock();
}
}
/** One conversation, as GET /api/chat/sessions lists it. */
export interface ChatSession {
session_id: string;
title: string;
created_at: string;
updated_at: string;
}
export interface ChatSessions {
sessions: ChatSession[];
active_model: string;
model_error?: string;
}
/** A tool the agent called and what came of it. */
export interface ChatToolCall {
id: string;
name: string;
parameters: string;
text: string;
failed?: boolean;
duration_ms: number;
text_offset: number;
}
/** An action judgement held and put to people. */
export interface ChatApproval {
request_id: string;
action: string;
summary: string;
level: string;
deadline: string;
}
/** What became of a held action once its approval was answered. */
export interface ChatActionDone {
request_id: string;
state: "succeeded" | "failed" | "unknown" | "denied" | "expired";
result?: string;
}
export interface ChatNavigation {
path: string;
label: string;
}
/** One message and Archie's reply, with what the turn did. */
export interface ChatTurn {
id: string;
session_id: string;
seq: number;
state: "queued" | "running" | "succeeded" | "failed" | "cancelled";
text: string;
page?: string;
page_label?: string;
reply: string;
reasoning?: string;
error?: string;
tool_calls: ChatToolCall[];
approvals: ChatApproval[];
actions: ChatActionDone[];
navigate: ChatNavigation[];
created_at: string;
finished_at?: string;
}
/** One recorded event of a turn, as its stream sends it. */
export type ChatEvent = { seq: number } & (
| { type: "reasoning" | "delta" | "done" | "error" | "cancelled"; text: string }
| ({ type: "tool" } & ChatToolCall)
| ({ type: "navigate" } & ChatNavigation)
| ({ type: "approval" } & ChatApproval)
| ({ type: "action" } & ChatActionDone)
);
const sessionPath = (id: string) => `/api/chat/sessions/${encodeURIComponent(id)}`;
const turnPath = (id: string) => `/api/chat/turns/${encodeURIComponent(id)}`;
export const chatSessions = (signal?: AbortSignal) => get<ChatSessions>("/api/chat/sessions", signal);
export const createChatSession = () => send<ChatSession>("POST", "/api/chat/sessions");
export const renameChatSession = (id: string, title: string) => send<ChatSession>("PATCH", sessionPath(id), { title });
export const deleteChatSession = (id: string) => send<void>("DELETE", sessionPath(id));
export const chatTurns = (id: string, signal?: AbortSignal) => get<ChatTurn[]>(`${sessionPath(id)}/turns`, signal);
export const chatTurn = (id: string, signal?: AbortSignal) => get<ChatTurn>(turnPath(id), signal);
export const sendChatTurn = (sessionID: string, text: string, page?: { page: string; page_label: string }) =>
send<ChatTurn>("POST", `${sessionPath(sessionID)}/turns`, { text, ...page });
export const cancelChatTurn = (id: string) => send<ChatTurn>("POST", `${turnPath(id)}/cancel`);
/**
* Yields a turn's recorded events after the cursor until the turn ends. The
* stream ends after a done, error or cancelled event; a dropped connection
* ends it early, and the caller reconnects from the last seq it saw.
*/
export async function* chatTurnEvents(id: string, after: number, signal: AbortSignal): AsyncGenerator<ChatEvent> {
const res = await request(`${turnPath(id)}/events?after=${after}`, signal);
if (!res.body) return;
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
let buffered = "";
try {
for (;;) {
const { value, done } = await reader.read();
if (done) return;
buffered += value;
let end: number;
while ((end = buffered.indexOf("\n\n")) >= 0) {
const frame = buffered.slice(0, end);
buffered = buffered.slice(end + 2);
const data = frame.split("\n").find((line) => line.startsWith("data: "));
if (data) yield JSON.parse(data.slice(6)) as ChatEvent;
}
}
} finally {
void reader.cancel().catch(() => undefined);
reader.releaseLock();
}
}
+94
View File
@@ -0,0 +1,94 @@
<script setup lang="ts">
import { ArrowUpRight, MessageSquare, ShieldAlert } from "@lucide/vue";
import { computed, onMounted, ref } from "vue";
import { RouterLink } from "vue-router";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Item, ItemActions, ItemContent, ItemDescription, ItemMedia, ItemTitle } from "@/components/ui/item";
import { Timestamp } from "@/components/ui/timestamp";
import type { ChatActionDone } from "../api";
import { answer, approvals, conversationOf, currentSession, selectSession } from "./state";
/**
* An action judgement held for a person, with Approve and Deny while it waits.
* This card is the only way to answer it from the chat: a reply in the
* conversation is never an approval. Once answered it says what became of the
* action.
*/
const props = defineProps<{
requestId: string;
action: string;
summary: string;
/** The run that asked, when a run did rather than this conversation. */
runId?: string;
outcome?: ChatActionDone;
}>();
// Resolved before a link shows, so a card never offers a run that isn't one.
const origin = ref<{ session: string | null } | null>(null);
onMounted(async () => {
if (props.runId) origin.value = { session: await conversationOf(props.runId) };
});
const pending = computed(() => approvals.value.find((a) => a.id === props.requestId));
const answering = ref(false);
const error = ref("");
const outcomeLabel: Record<ChatActionDone["state"], string> = {
succeeded: "Ran",
failed: "Didn't run",
unknown: "Outcome unknown",
denied: "Denied",
expired: "Expired",
};
async function decide(approved: boolean): Promise<void> {
if (answering.value) return;
answering.value = true;
error.value = "";
try {
await answer(props.requestId, approved);
} catch (err) {
error.value = err instanceof Error ? err.message : String(err);
} finally {
answering.value = false;
}
}
</script>
<template>
<Item variant="outline" size="sm" class="mt-2 items-start" role="group" :aria-label="`Approval for ${action}`">
<ItemMedia variant="icon" class="text-warn"><ShieldAlert aria-hidden="true" /></ItemMedia>
<ItemContent class="min-w-0">
<ItemTitle class="w-auto break-words">{{ action }}</ItemTitle>
<ItemDescription class="line-clamp-none whitespace-pre-wrap break-words">{{ summary }}</ItemDescription>
<span v-if="pending" class="text-caption text-muted-foreground">
Respond by <Timestamp :at="pending.step_deadline || pending.deadline" absolute />
</span>
<p v-if="outcome?.result" class="mt-1 whitespace-pre-wrap break-words font-mono text-caption">{{ outcome.result }}</p>
<p v-if="error" role="alert" class="text-caption text-destructive">{{ error }}</p>
<ItemActions class="mt-1 flex-wrap justify-start">
<template v-if="pending">
<Button size="sm" :disabled="answering" @click="decide(true)">Approve</Button>
<Button size="sm" variant="outline" :disabled="answering" @click="decide(false)">Deny</Button>
</template>
<Badge v-else-if="outcome" :variant="outcome.state === 'succeeded' ? 'secondary' : 'warn'">{{ outcomeLabel[outcome.state] }}</Badge>
<Badge v-else variant="secondary">Answered</Badge>
<Button
v-if="origin?.session && origin.session !== currentSession"
variant="link"
size="sm"
@click="selectSession(origin.session)"
>
<MessageSquare aria-hidden="true" data-icon="inline-start" />Open conversation
</Button>
<Button v-else-if="runId && origin && !origin.session" variant="link" size="sm" as-child>
<RouterLink :to="{ name: 'run', params: { id: runId } }" :aria-label="`View run for ${action}`"
>View run <ArrowUpRight aria-hidden="true" data-icon="inline-end"
/></RouterLink>
</Button>
</ItemActions>
</ItemContent>
</Item>
</template>
+59
View File
@@ -0,0 +1,59 @@
<script setup lang="ts">
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Menu, SquarePen } from "@lucide/vue";
import { computed, ref } from "vue";
import { Button } from "@/components/ui/button";
import ChatSessionActions from "./ChatSessionActions.vue";
import ChatSessionList from "./ChatSessionList.vue";
import { sessionTitle } from "./session";
import { currentSession, newChat, sessions, useEscapeLayer } from "./state";
/**
* One row for everything that is not the conversation: the drawer of
* conversations, which one is open, and icon controls on the right. The dock
* fills the slots: `start` before the drawer button, `actions` before the more
* menu, and `end` last.
*/
const drawer = ref(false);
useEscapeLayer(drawer);
const title = computed(() => {
const open = sessions.value.find((s) => s.session_id === currentSession.value);
return open ? sessionTitle(open) : "New chat";
});
</script>
<template>
<div class="flex items-center gap-0.5 px-2 py-1.5">
<slot name="start" />
<Tooltip>
<TooltipTrigger as-child>
<Button
variant="ghost"
size="icon-sm"
class="flex-none"
aria-label="Conversations"
:aria-expanded="drawer"
@click="drawer = true"
>
<Menu />
</Button>
</TooltipTrigger>
<TooltipContent>Conversations</TooltipContent>
</Tooltip>
<span class="min-w-0 flex-1 truncate px-1 text-label font-medium" :title="title">{{ title }}</span>
<Tooltip>
<TooltipTrigger as-child>
<Button variant="ghost" size="icon-sm" class="flex-none" aria-label="New chat" @click="newChat">
<SquarePen />
</Button>
</TooltipTrigger>
<TooltipContent>New chat</TooltipContent>
</Tooltip>
<slot name="actions" />
<ChatSessionActions />
<slot name="end" />
<ChatSessionList v-if="drawer" @close="drawer = false" />
</div>
</template>
+118
View File
@@ -0,0 +1,118 @@
<script setup lang="ts">
import { Alert, AlertDescription } from "@/components/ui/alert";
import { computed } from "vue";
import { Bubble, BubbleContent } from "@/components/ui/bubble";
import { Trace } from "@/components/ui/trace";
import { CodeBlockCopyButton } from "@/components/ui/code-block";
import { Message, MessageContent, MessageFooter } from "@/components/ui/message";
import ChatMarkdown from "./ChatMarkdown.vue";
import ChatThinking from "./ChatThinking.vue";
import ChatToolCall from "./ChatToolCall.vue";
import ChatToolGroup from "./ChatToolGroup.vue";
import type { ChatToolCall as ToolCall } from "./state";
/**
* One message, from either side of the conversation. There is no speaker
* label: which side of the panel it sits on, and its fill, are what say who is
* talking. A trailing action arrives through the slot, so the retry the
* transcript offers belongs to the bubble rather than beside it. A finished
* reply carries a copy action beneath it.
*/
const props = withDefaults(
defineProps<{
text: string;
tools?: ToolCall[];
/** The page the operator asked from. */
page?: string;
assistant?: boolean;
/** The turn is still arriving: a tool call with no outcome is running. */
streaming?: boolean;
/** The live turn's thinking so far, rendered as a collapsible trace. */
reasoning?: string;
/** The live turn is still arriving and has not reasoned yet. */
thinkingPending?: boolean;
/** The text says why the turn failed rather than answering. */
error?: boolean;
}>(),
{ tools: () => [], page: "", assistant: false, streaming: false, reasoning: "", thinkingPending: false },
);
// The reply in the order it happened: text up to each call's offset, then the
// call. Consecutive calls at one point fold into one line; a navigation chip
// is an action for the operator, so it always stands alone. A call recorded
// without an offset sits at the start.
type Segment = { text: string } | { tools: ToolCall[] };
const segments = computed(() => {
const chars = Array.from(props.text);
const out: Segment[] = [];
let at = 0;
let open = false;
for (const tool of props.tools) {
const offset = Math.min(Math.max(tool.text_offset ?? 0, at), chars.length);
if (offset > at) {
out.push({ text: chars.slice(at, offset).join("") });
at = offset;
open = false;
}
const last = out[out.length - 1];
if (!tool.path && open && last && "tools" in last) last.tools.push(tool);
else {
out.push({ tools: [tool] });
open = !tool.path;
}
}
if (at < chars.length) out.push({ text: chars.slice(at).join("") });
return out;
});
</script>
<template>
<Message :align="assistant ? 'start' : 'end'">
<MessageContent>
<Bubble :variant="assistant ? 'muted' : 'tinted'" class="max-w-[min(78ch,92%)]">
<BubbleContent class="[overflow-wrap:anywhere]">
<template v-if="assistant">
<ChatThinking
v-if="reasoning || thinkingPending"
:text="reasoning"
:pending="thinkingPending"
:collapsed="!streaming"
/>
<template v-if="error">
<Trace v-if="tools.length" class="mb-2">
<ChatToolGroup v-if="tools.length > 1" :tools="tools" :streaming="false" />
<ChatToolCall v-else :tool="tools[0]" :streaming="false" />
</Trace>
<Alert variant="destructive" class="text-label"><AlertDescription>{{ text }}</AlertDescription></Alert>
</template>
<template v-for="(segment, i) in segments" v-else :key="i">
<ChatMarkdown v-if="'text' in segment" :text="segment.text" />
<Trace v-else class="my-2">
<ChatToolGroup
v-if="segment.tools.length > 1"
:tools="segment.tools"
:streaming="streaming && i === segments.length - 1"
/>
<ChatToolCall
v-else
:tool="segment.tools[0]"
:streaming="streaming && i === segments.length - 1"
/>
</Trace>
</template>
</template>
<div v-else class="whitespace-pre-wrap">{{ text }}</div>
<p v-if="!assistant && page" class="mt-1 text-caption opacity-70">{{ page }}</p>
<slot />
</BubbleContent>
</Bubble>
<MessageFooter
v-if="assistant && !streaming && text"
class="px-0 transition-opacity focus-within:opacity-100 [@media(hover:hover)]:opacity-0 [@media(hover:hover)]:group-hover/message:opacity-100"
>
<CodeBlockCopyButton :value="text" />
</MessageFooter>
</MessageContent>
</Message>
</template>
+241
View File
@@ -0,0 +1,241 @@
<script setup lang="ts">
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { nextTick, ref, watch } from "vue";
import { Clock, Pencil, X } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { Textarea } from "@/components/ui/textarea";
import { isExactCommand, replaceToken } from "./commands";
import ChatSlashPalette from "./ChatSlashPalette.vue";
import ChatSuggestions from "./ChatSuggestions.vue";
import {
closeCommandMenu,
commandMatches,
commandSelection,
commandSpecs,
clearPageTag,
pageTag,
placeholderHint,
messages,
composerText,
editQueued,
menuTrigger,
isCommandMenuOpen,
isSending,
moveCommandSelection,
queuedMessages,
removeQueued,
sendMessage,
stopTurn,
syncCommandMenu,
} from "./state";
/**
* The composer: the text, the palette that completes a slash command, and the
* actions. It stays writeable while a turn is in flight: a message sent then
* waits behind it (Queue), and Stop is an addition to the row, never a
* replacement for Send.
*
* The textarea is stripped back to bare text inside the shell that carries the
* border and the fill. It grows with what is typed and stops at `max-h-40`, so
* a long draft scrolls rather than eating the transcript above it.
*/
// Flat drops the field's own border and fill when the card around it already
// draws them, so the collapsed dock reads as one surface rather than a box in a box.
const props = defineProps<{ open: boolean; flat?: boolean }>();
const field = ref<{ $el: HTMLTextAreaElement } | null>(null);
function focus(): void {
field.value?.$el?.focus();
}
defineExpose({ focus });
// The panel stays mounted so the session survives navigation, so opening it is
// a prop change rather than a mount: focus the composer on that edge.
watch(
() => props.open,
(open) => {
if (open) void nextTick(focus);
},
);
// A finished turn leaves the caret in the composer, where the next message is
// typed, rather than on the button that sent the last one.
watch(isSending, (sending, wasSending) => {
if (wasSending && !sending) void nextTick(focus);
});
function onInput(event: Event): void {
const input = event.target as HTMLTextAreaElement;
composerText.value = input.value;
syncCommandMenu(input.value, input.selectionStart ?? input.value.length);
}
function choose(index: number): void {
const item = commandMatches.value[index];
const input = field.value?.$el;
if (!item || !input) return;
const caret = input.selectionStart ?? input.value.length;
// Completing replaces the token the caret sits in, which is decided by the
// same rule that found the matches.
const edit = replaceToken(input.value, caret, item.label);
composerText.value = edit.text;
closeCommandMenu();
void nextTick(() => {
input.focus();
input.setSelectionRange(edit.cursor, edit.cursor);
});
}
function onKeydown(event: KeyboardEvent): void {
// Safari may end composition before delivering its confirming Enter.
if (event.key === "Enter" && (event.isComposing || event.keyCode === 229)) return;
const plain = !event.shiftKey && !event.ctrlKey && !event.metaKey;
if (isCommandMenuOpen.value) {
// A command typed in full is sent rather than completed, so Enter never
// re-enters the command the palette was offering.
if (
event.key === "Enter" &&
plain &&
menuTrigger.value === "/" &&
isExactCommand(commandSpecs.value, composerText.value)
) {
event.preventDefault();
closeCommandMenu();
void sendMessage();
return;
}
if (event.key === "ArrowDown") {
event.preventDefault();
moveCommandSelection(1);
return;
}
if (event.key === "ArrowUp") {
event.preventDefault();
moveCommandSelection(-1);
return;
}
if (
commandMatches.value.length &&
((event.key === "Enter" && plain) || (event.key === "Tab" && !event.shiftKey))
) {
event.preventDefault();
choose(commandSelection.value);
return;
}
if (event.key === "Escape") {
// Consumed here: dismissing the palette must not also close the panel.
event.preventDefault();
closeCommandMenu();
return;
}
}
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
void sendMessage();
}
}
</script>
<template>
<div :class="flat ? 'p-2' : 'border-t p-3'">
<ul v-if="queuedMessages.length" aria-label="Queued messages" class="mb-2 flex flex-col gap-1">
<li
v-for="(queued, index) in queuedMessages"
:key="index"
class="flex items-center gap-1 rounded-md border border-dashed border-border px-2 py-1 text-label text-fg-muted"
>
<Clock class="size-3.5 flex-none" aria-hidden="true" />
<span class="min-w-0 flex-1 truncate">{{ queued }}</span>
<Tooltip>
<TooltipTrigger as-child>
<Button variant="ghost" size="icon" class="size-7" aria-label="Edit queued message" @click="editQueued(index)"
><Pencil
/></Button>
</TooltipTrigger>
<TooltipContent>Edit</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger as-child>
<Button variant="ghost" size="icon" class="size-7" aria-label="Remove queued message" @click="removeQueued(index)"
><X
/></Button>
</TooltipTrigger>
<TooltipContent>Remove</TooltipContent>
</Tooltip>
</li>
</ul>
<ul v-if="!flat && pageTag" aria-label="Message context" class="mb-2 flex flex-wrap gap-1">
<li
v-if="pageTag"
class="flex max-w-full items-center gap-1 rounded-md border border-border bg-muted px-2 py-0.5 text-label"
>
<span class="truncate">{{ pageTag.label }}</span>
<Button variant="ghost" size="icon" class="size-5" aria-label="Remove page context" @click="clearPageTag"
><X
/></Button>
</li>
</ul>
<!-- An empty conversation lists the prompts itself; once it has messages
they sit beside the field so they stay reachable without scrolling up.
The minimised bar is the field alone; the page context still goes with
the message. -->
<ChatSuggestions v-if="!flat && messages.length" />
<div
:class="
cn(
'relative flex gap-2 rounded-xl border transition-colors duration-200',
// Minimised, the field is one line: the controls centre on it.
flat ? 'items-center border-transparent px-2 py-1.5' : 'items-end border-border-strong bg-muted px-3 py-2.5',
)
"
>
<div v-if="$slots.start" :class="cn('flex flex-none items-center', !flat && 'mb-1.5')">
<slot name="start" />
</div>
<Textarea
ref="field"
:model-value="composerText"
rows="1"
:placeholder="placeholderHint || 'Message Archie'"
aria-label="Message Archie"
role="combobox"
aria-controls="slash-palette"
:aria-expanded="isCommandMenuOpen ? 'true' : 'false'"
:aria-activedescendant="isCommandMenuOpen && commandMatches.length ? `slash-palette-option-${commandSelection}` : undefined"
:class="cn('max-h-40 flex-1 resize-none rounded-none border-0 bg-transparent! px-0 text-label pointer-coarse:text-base shadow-none focus-visible:ring-0', flat ? 'min-h-10 py-2.5 text-base leading-5' : 'min-h-11 py-1')"
@input="onInput"
@keydown="onKeydown"
/>
<ChatSlashPalette
v-if="isCommandMenuOpen"
:matches="commandMatches"
:selection="commandSelection"
label="Commands"
@choose="choose"
/>
<!-- Centred on the field's first line, then kept at the bottom as it grows. -->
<div :class="cn('flex flex-none items-center gap-2', !flat && 'mb-1.5')">
<slot name="actions" />
<!-- Only while a turn is arriving: a Stop with nothing to stop is a
button that lies about what the panel is doing. -->
<Button v-if="isSending" variant="outline" size="sm" @click="stopTurn"
>Stop</Button
>
<Button
size="sm"
:variant="composerText.trim() ? 'default' : 'secondary'"
:disabled="!composerText.trim()"
@click="sendMessage()"
>{{ isSending ? "Queue" : "Send" }}</Button
>
</div>
</div>
</div>
</template>
+579
View File
@@ -0,0 +1,579 @@
<script setup lang="ts">
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { ChevronDown, ChevronUp, GripVertical, PanelLeft, PanelRight, PictureInPicture2 } from "@lucide/vue";
import { useDraggable, useEventListener, useMediaQuery, usePointerSwipe, useStorage, useWindowSize } from "@vueuse/core";
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { cn } from "@/lib/utils";
import ChatBar from "./ChatBar.vue";
import ChatComposer from "./ChatComposer.vue";
import ChatPending from "./ChatPending.vue";
import ChatTranscript from "./ChatTranscript.vue";
import {
DOCK_STORAGE_KEY,
DRAG_START,
MAX_W,
MIN_H,
MIN_W,
RESIZE_DIRS,
SWIPE,
barPlacement,
fitRect,
BAR_W,
INSET,
handleOrientation,
handleValue,
keyboardCover,
keyStep,
migrateDockStorage,
normalizeLayout,
phoneBarBottom,
pinnedWidth,
resizeRect,
snapEdge,
type DockLayout,
type DockMode,
type Rect,
type ResizeDir,
} from "./ChatDockLayout";
import { dockExpanded, escapeOwnedByLayer, isSending, useChat, useEscapeLayer } from "./state";
import { setDockOpen, unseenCount } from "./unseen";
/**
* Chat is a window docked to every page, not a route: the operator asks Archie
* about the page they are already on, so navigating must not reset it, and it
* must not replace the work that prompted the question. The agent is told
* which page that is.
*
* It is the composer alone until the operator focuses it or a turn starts, then
* the conversation opens above it. Hiding the conversation leaves the bar where
* it was. It is deliberately not a modal: no scrim, no scroll lock, no focus
* trap.
*
* On a desktop-width screen the expanded conversation is a free-floating
* window: the header drags it anywhere, all eight edges and corners resize it
* (pointer and keyboard), and dragging near a side edge shows the pinned
* split, committing on release. The header's position menu picks Left, Float
* or Right outright; pinned, the page reflows beside the dock instead of
* sitting under it. Ctrl+/ toggles the window, Escape collapses it, and the
* collapsed bar stays where it was and drags too. The layout (mode, x, y,
* width, height) is remembered per browser under "archie.chat.dock.v2", which
* replaces the old edge-pin preference.
*
* On a phone-width screen the collapsed dock is the full-width bottom bar and
* the open conversation a full-screen sheet; both ride above the on-screen
* keyboard, which iOS does not resize the page for, and swiping down on the
* conversation header hides it. No float or resize handles
* exist below the desktop breakpoint.
*
* The collapsed bar's show button carries the count of replies and run cards
* that landed while it was closed.
*
* It stays mounted, so the session and any turn in flight survive a navigation.
* It is mounted outside the page container, so `position: fixed` anchors to the
* viewport. The composer page is the same chat full size, so the dock steps
* aside there.
*/
useChat();
const expanded = dockExpanded;
watch(expanded, setDockOpen, { immediate: true });
// The old edge-pin preference moves into the new key before useStorage reads it.
migrateDockStorage(localStorage, window.innerWidth, window.innerHeight);
const stored = useStorage<DockLayout>(
DOCK_STORAGE_KEY,
normalizeLayout(null, window.innerWidth, window.innerHeight),
localStorage,
);
const desktop = useMediaQuery("(min-width: 768px)");
const { width: vw, height: vh } = useWindowSize();
const layout = computed<DockLayout>({
get: () => normalizeLayout(stored.value, vw.value, vh.value),
set: (value) => {
stored.value = value;
},
});
const mode = computed<DockMode>(() => (desktop.value ? layout.value.mode : "float"));
const pinned = computed(() => desktop.value && expanded.value && mode.value !== "float");
const pinW = computed(() => pinnedWidth(layout.value.w, vw.value));
const pinMax = computed(() => Math.max(MIN_W, Math.min(MAX_W, vw.value - 480)));
// The rendered rectangle of the window: full-height at an edge when pinned, the
// clamped stored rectangle when floating.
const winRect = computed<Rect>(() => {
if (!desktop.value) return { x: 0, y: 0, w: vw.value, h: vh.value };
if (pinned.value) {
return { x: mode.value === "left" ? 0 : vw.value - pinW.value, y: 0, w: pinW.value, h: vh.value };
}
// Opening the window never narrows it below the minimised bar.
const minW = Math.min(BAR_W, vw.value - INSET * 2);
return fitRect({ ...layout.value, w: Math.max(layout.value.w, minW) }, vw.value, vh.value);
});
// The part of the layout viewport the on-screen keyboard covers, and the height
// left above it. Fixed elements stay anchored to the layout viewport, so without
// this the bar sits under the keyboard.
const keyboard = ref(0);
const visibleHeight = ref(window.innerHeight);
// How far the browser has panned the page up to show the focused input.
const visibleTop = ref(0);
function followViewport(): void {
const vv = window.visualViewport;
keyboard.value = keyboardCover(window.innerHeight, vv);
visibleHeight.value = vv ? vv.height : window.innerHeight;
visibleTop.value = vv ? Math.max(0, Math.round(vv.offsetTop)) : 0;
}
useEventListener(() => window.visualViewport, ["resize", "scroll"], followViewport);
const phoneBottom = computed(() => phoneBarBottom(keyboard.value));
const wrapStyle = computed<Record<string, string> | undefined>((): Record<string, string> | undefined => {
// On a phone the open conversation is a full-screen sheet over the part of
// the screen the keyboard leaves.
if (!desktop.value && expanded.value) return { top: `${visibleTop.value}px`, height: `${visibleHeight.value}px` };
if (!desktop.value) return { bottom: phoneBottom.value };
if (pinned.value) {
return { left: `${winRect.value.x}px`, top: "0px", width: `${pinW.value}px`, height: `${vh.value}px` };
}
const rect = winRect.value;
if (expanded.value) {
// A tablet's on-screen keyboard covers the layout viewport's bottom; keep
// the window, and so its composer, in the part left above it.
const fit = keyboard.value > 0 ? fitRect(rect, vw.value, visibleHeight.value) : rect;
const top = keyboard.value > 0 ? fit.y + visibleTop.value : fit.y;
return { left: `${fit.x}px`, top: `${top}px`, width: `${fit.w}px`, height: `${fit.h}px` };
}
const bar = barPlacement(rect, mode.value, vw.value);
return { left: `${bar.x}px`, bottom: `${bar.bottom + keyboard.value}px`, width: `${bar.w}px` };
});
// Nothing outside the dock closes it: every navigation control is outside it,
// so a click-outside dismissal turned navigation into a collapse and read as a
// lost conversation. Hide, swipe down, Escape and Ctrl+/ are the only ways to
// collapse.
watch(isSending, (sending) => {
if (sending) expanded.value = true;
});
function onKeydown(event: KeyboardEvent): void {
// A focused control (the composer dismissing its palette, or the topbar
// search) already handled Escape via preventDefault; collapsing too would
// make that menu impossible to dismiss on its own. A popover portalled out
// of the bar owns Escape by being open, which the flag reports.
if (event.defaultPrevented || event.key !== "Escape" || escapeOwnedByLayer()) return;
expanded.value = false;
}
watch(expanded, (open) => {
if (open) document.addEventListener("keydown", onKeydown);
else document.removeEventListener("keydown", onKeydown);
});
onUnmounted(() => document.removeEventListener("keydown", onKeydown));
function onGlobalKeydown(event: KeyboardEvent): void {
if (event.defaultPrevented) return;
if ((event.ctrlKey || event.metaKey) && event.key === "/") {
event.preventDefault();
expanded.value = !expanded.value;
}
}
onMounted(() => document.addEventListener("keydown", onGlobalKeydown));
onUnmounted(() => document.removeEventListener("keydown", onGlobalKeydown));
// The page reserves the collapsed dock's height, read from the rendered bar so
// the last line of any page can scroll clear of it. A bar floating clear of the
// bottom of the screen reserves nothing.
const dock = ref<HTMLElement | null>(null);
let observer: ResizeObserver | null = null;
function reserve(): void {
if (expanded.value || !dock.value) return;
const rect = dock.value.getBoundingClientRect();
// Only a bar sitting in the bottom quarter of the screen needs the page to
// reserve room under it; one floating higher up does not.
const clear = rect.bottom >= window.innerHeight * 0.75 ? Math.ceil(window.innerHeight - rect.top) : 0;
document.documentElement.style.setProperty("--chat-dock-clear", `${clear}px`);
}
onMounted(() => {
observer = new ResizeObserver(reserve);
if (dock.value) observer.observe(dock.value);
window.addEventListener("resize", reserve);
});
onUnmounted(() => {
observer?.disconnect();
window.removeEventListener("resize", reserve);
document.documentElement.style.removeProperty("--chat-dock-clear");
});
watch([expanded, desktop, () => layout.value.x, () => layout.value.y, () => layout.value.w, mode], () =>
nextTick(reserve),
);
// The page makes room for a pinned dock through these two variables.
watch([pinned, mode, pinW], () => {
const root = document.documentElement.style;
root.setProperty("--chat-pin-l", pinned.value && mode.value === "left" ? `${pinW.value}px` : "0px");
root.setProperty("--chat-pin-r", pinned.value && mode.value === "right" ? `${pinW.value}px` : "0px");
}, { immediate: true });
onUnmounted(() => {
document.documentElement.style.removeProperty("--chat-pin-l");
document.documentElement.style.removeProperty("--chat-pin-r");
});
const MODES: { mode: DockMode; label: string; icon: typeof PanelLeft }[] = [
{ mode: "left", label: "Left", icon: PanelLeft },
{ mode: "float", label: "Float", icon: PictureInPicture2 },
{ mode: "right", label: "Right", icon: PanelRight },
];
const positionOpen = ref(false);
useEscapeLayer(positionOpen);
function setMode(next: DockMode): void {
if (!desktop.value) return;
layout.value = { ...layout.value, mode: next };
expanded.value = true;
}
const dragging = ref(false);
const snapTarget = ref<"left" | "right" | null>(null);
// A resize follows the pointer directly; the position transition would lag it.
const resizing = ref(false);
const header = ref<HTMLElement | null>(null);
const bar = ref<HTMLElement | null>(null);
// The header drags the open window and the bar drags the minimised one. The
// controls inside them keep their own presses, except the move handle.
function onDragSurface(target: HTMLElement): boolean {
const surface = expanded.value ? header.value : bar.value;
if (!surface?.contains(target)) return false;
return !target.closest("button, a, input, select, textarea, [role=combobox], [role=separator]") || !!target.closest("[data-move-handle]");
}
// Pointer travel before a press becomes a drag, so a click or a double-click
// on a drag surface never moves the dock.
let drag: { origin: Rect; x0: number; y0: number; moved: boolean; snap: "left" | "right" | null } | null = null;
useDraggable(dock, {
disabled: () => !desktop.value,
onStart: (_, e) => {
if (!e.isPrimary || !onDragSurface(e.target as HTMLElement)) return false;
drag = { origin: { ...winRect.value }, x0: e.clientX, y0: e.clientY, moved: false, snap: null };
},
onMove: (_, e) => {
if (!drag) return;
const dx = e.clientX - drag.x0;
const dy = e.clientY - drag.y0;
if (!drag.moved && Math.hypot(dx, dy) < DRAG_START) return;
drag.moved = true;
dragging.value = true;
const next = fitRect({ ...drag.origin, x: drag.origin.x + dx, y: drag.origin.y + dy }, vw.value, vh.value);
layout.value = { ...layout.value, mode: "float", x: next.x, y: next.y, w: next.w, h: next.h };
drag.snap = expanded.value ? snapEdge(e.clientX, vw.value) : null;
snapTarget.value = drag.snap;
},
onEnd: (_, e) => {
if (drag?.moved && e.type === "pointerup" && drag.snap) layout.value = { ...layout.value, mode: drag.snap };
drag = null;
dragging.value = false;
snapTarget.value = null;
},
});
// Every resize handle, the pinned divider included, carries data-resize. The
// delta is measured from the press and applied to the rectangle as it was then;
// applying it to the live rectangle compounded every move.
let resize: { dir: ResizeDir | "pin"; origin: Rect; w0: number; x0: number; y0: number } | null = null;
useDraggable(dock, {
disabled: () => !desktop.value,
preventDefault: true,
onStart: (_, e) => {
const dir = (e.target as HTMLElement).closest<HTMLElement>("[data-resize]")?.dataset.resize as ResizeDir | "pin" | undefined;
if (!e.isPrimary || !dir) return false;
resize = { dir, origin: resizeOrigin(), w0: pinW.value, x0: e.clientX, y0: e.clientY };
resizing.value = true;
},
onMove: (_, e) => {
if (!resize) return;
const dx = e.clientX - resize.x0;
if (resize.dir === "pin") {
layout.value = { ...layout.value, w: clampWidth(resize.w0 + (mode.value === "left" ? dx : -dx)) };
return;
}
applyResize(resize.origin, resize.dir, dx, e.clientY - resize.y0);
},
onEnd: () => {
resize = null;
resizing.value = false;
},
});
// On a phone the header is a swipe surface, not a drag surface: a downward
// flick hides the conversation.
usePointerSwipe(header, {
threshold: SWIPE,
onSwipeEnd: (e, direction) => {
if (desktop.value || e.type !== "pointerup" || direction !== "down") return;
// The keyboard is for the composer, which is no longer in front of it.
(document.activeElement as HTMLElement | null)?.blur();
expanded.value = false;
},
});
function togglePin(event: MouseEvent): void {
if (!desktop.value || !onDragSurface(event.target as HTMLElement)) return;
layout.value = { ...layout.value, mode: mode.value === "float" ? "right" : "float" };
}
function moveByKey(event: KeyboardEvent): void {
if (!desktop.value || !event.key.startsWith("Arrow")) return;
event.preventDefault();
const step = keyStep(event.shiftKey);
const rect = winRect.value;
const next = fitRect(
{
...rect,
x: rect.x + (event.key === "ArrowRight" ? step : event.key === "ArrowLeft" ? -step : 0),
y: rect.y + (event.key === "ArrowDown" ? step : event.key === "ArrowUp" ? -step : 0),
},
vw.value,
vh.value,
);
layout.value = { ...layout.value, mode: "float", x: next.x, y: next.y, w: next.w, h: next.h };
}
const HANDLE_CLASS: Record<ResizeDir, string> = {
n: "top-[-3px] left-3.5 right-3.5 h-2 cursor-ns-resize",
s: "bottom-[-3px] left-3.5 right-3.5 h-2 cursor-ns-resize",
e: "right-[-3px] top-3.5 bottom-3.5 w-2 cursor-ew-resize",
w: "left-[-3px] top-3.5 bottom-3.5 w-2 cursor-ew-resize",
ne: "top-0 right-0 size-3.5 cursor-nesw-resize",
nw: "top-0 left-0 size-3.5 cursor-nwse-resize",
se: "bottom-0 right-0 size-4 cursor-nwse-resize",
sw: "bottom-0 left-0 size-4 cursor-nesw-resize",
};
const DIR_LABEL: Record<ResizeDir, string> = {
n: "top",
s: "bottom",
e: "right",
w: "left",
ne: "top right",
nw: "top left",
se: "bottom right",
sw: "bottom left",
};
// The minimised bar keeps its height, so only its width edges resize it.
const visibleDirs = computed<ResizeDir[]>(() => (expanded.value ? [...RESIZE_DIRS] : ["e", "w"]));
// The rectangle a resize starts from. Minimised, the bar can sit at an edge
// rather than at the stored x, so its rendered x and width are the origin, or
// the first move would jump it.
function resizeOrigin(): Rect {
const rect = winRect.value;
if (expanded.value || !dock.value) return rect;
const bar = dock.value.getBoundingClientRect();
return { ...rect, x: bar.left, w: bar.width };
}
function applyResize(origin: Rect, dir: ResizeDir, dx: number, dy: number): void {
const rect = resizeRect(origin, dir, dx, dy, vw.value, vh.value);
layout.value = { ...layout.value, mode: "float", x: rect.x, y: rect.y, w: rect.w, h: rect.h };
}
function onHandleKey(dir: ResizeDir, event: KeyboardEvent): void {
if (!desktop.value || !event.key.startsWith("Arrow")) return;
event.preventDefault();
const step = keyStep(event.shiftKey);
const dx = event.key === "ArrowRight" ? step : event.key === "ArrowLeft" ? -step : 0;
const dy = event.key === "ArrowDown" ? step : event.key === "ArrowUp" ? -step : 0;
applyResize(resizeOrigin(), dir, dx, dy);
}
function clampWidth(w: number): number {
return Math.min(Math.max(w, MIN_W), pinMax.value);
}
function onPinKey(event: KeyboardEvent): void {
if (!desktop.value) return;
const grow = event.key === (mode.value === "right" ? "ArrowLeft" : "ArrowRight");
const shrink = event.key === (mode.value === "right" ? "ArrowRight" : "ArrowLeft");
if (!grow && !shrink) return;
event.preventDefault();
layout.value = { ...layout.value, w: clampWidth(layout.value.w + (grow ? 16 : -16)) };
}
</script>
<template>
<div
v-if="snapTarget"
aria-hidden="true"
:class="cn('pointer-events-none fixed inset-y-0 z-40 border-primary/40 bg-primary/10', snapTarget === 'left' ? 'left-0 border-r-2' : 'right-0 border-l-2')"
:style="{ width: `${pinW}px` }"
/>
<div
:class="cn(
'pointer-events-none fixed z-40 transition-[left,top,bottom,width,height] duration-200 ease-out motion-reduce:transition-none',
(dragging || resizing) && 'transition-none',
!desktop && !expanded && 'inset-x-0 bottom-4 flex justify-center px-3 max-md:bottom-2',
!desktop && expanded && 'inset-x-0 flex',
// Docked, minimising hides the dock; the topbar button and Ctrl+/ bring
// it back. It stays mounted so the session and a turn in flight survive.
desktop && mode !== 'float' && !expanded && 'hidden',
)"
:style="wrapStyle"
>
<aside
ref="dock"
aria-label="Chat with Archie"
:class="cn(
'touch-hit pointer-events-auto relative flex flex-col border-border-strong bg-popover shadow-[var(--shadow-md)]',
desktop ? cn('w-full', pinned || expanded ? 'h-full' : '', pinned ? (mode === 'left' ? 'border-r' : 'border-l') : 'rounded-lg border') : expanded ? 'h-full w-full' : 'w-full max-w-xl rounded-lg border',
dragging && 'z-50 opacity-90',
)"
>
<template v-if="desktop && !pinned">
<div
v-for="dir in visibleDirs"
:key="dir"
role="separator"
tabindex="0"
aria-label="Resize chat"
:title="`Resize from the ${DIR_LABEL[dir]} edge. Arrow keys resize; Shift changes faster.`"
:aria-orientation="handleOrientation(dir)"
:aria-valuenow="handleValue(dir, winRect)"
:aria-valuemin="dir === 'n' || dir === 's' ? MIN_H : MIN_W"
:aria-valuemax="dir === 'n' || dir === 's' ? vh : vw"
:data-resize="dir"
:class="cn('absolute z-10 touch-none hover:bg-primary/30 focus-visible:bg-primary/50', HANDLE_CLASS[dir])"
@keydown="onHandleKey(dir, $event)"
/>
</template>
<div
v-if="desktop && pinned"
role="separator"
aria-orientation="vertical"
aria-label="Resize chat"
tabindex="0"
:aria-valuenow="pinW"
:aria-valuemin="MIN_W"
:aria-valuemax="pinMax"
data-resize="pin"
class="absolute inset-y-0 z-10 w-1.5 cursor-col-resize touch-none hover:bg-primary/30 focus-visible:bg-primary/50"
:class="mode === 'left' ? '-right-0.5' : '-left-0.5'"
@keydown="onPinKey"
/>
<div
v-if="expanded"
ref="header"
:class="cn('touch-none', desktop && 'cursor-grab select-none active:cursor-grabbing')"
@dblclick="togglePin"
>
<ChatBar>
<template v-if="desktop" #start>
<Tooltip>
<TooltipTrigger as-child>
<Button
variant="ghost"
size="icon-sm"
class="flex-none cursor-grab touch-none active:cursor-grabbing"
data-move-handle
aria-label="Move chat"
title="Drag to move. Arrow keys move; Shift moves further."
@keydown="moveByKey"
>
<GripVertical />
</Button>
</TooltipTrigger>
<TooltipContent>Move chat</TooltipContent>
</Tooltip>
</template>
<template v-if="desktop" #actions>
<DropdownMenu v-model:open="positionOpen">
<!-- No Tooltip around the trigger: nested in TooltipTrigger the menu
loses its anchor and opens off-screen, as MoreMenu found. -->
<DropdownMenuTrigger as-child>
<Button variant="ghost" size="icon-sm" class="flex-none" aria-label="Chat position" title="Position">
<component :is="MODES.find((m) => m.mode === mode)?.icon ?? PictureInPicture2" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" class="min-w-36">
<DropdownMenuRadioGroup :model-value="mode" @update:model-value="setMode($event as DockMode)">
<DropdownMenuRadioItem v-for="m in MODES" :key="m.mode" :value="m.mode">
<component :is="m.icon" />{{ m.label }}
</DropdownMenuRadioItem>
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
</template>
<template #end>
<Tooltip>
<TooltipTrigger as-child>
<Button
variant="ghost"
size="icon-sm"
class="flex-none"
aria-label="Hide conversation"
@click="expanded = false"
>
<ChevronDown />
</Button>
</TooltipTrigger>
<TooltipContent>Hide conversation</TooltipContent>
</Tooltip>
</template>
</ChatBar>
</div>
<div
v-if="expanded"
class="flex min-h-0 flex-1 flex-col"
>
<ChatTranscript />
<ChatPending />
</div>
<div ref="bar" class="touch-none" @focusin="expanded = true">
<ChatComposer :open="false" :flat="!expanded">
<template v-if="!expanded && desktop" #start>
<Tooltip>
<TooltipTrigger as-child>
<Button
variant="ghost"
size="icon-sm"
class="cursor-grab touch-none active:cursor-grabbing"
data-move-handle
aria-label="Move chat"
title="Drag to move. Arrow keys move; Shift moves further."
@keydown="moveByKey"
>
<GripVertical />
</Button>
</TooltipTrigger>
<TooltipContent>Move chat</TooltipContent>
</Tooltip>
</template>
<template v-if="!expanded" #actions>
<Tooltip>
<TooltipTrigger as-child>
<Button
variant="ghost"
size="icon-sm"
:class="cn(unseenCount && 'w-auto gap-1 px-2')"
:aria-label="unseenCount ? `Show conversation, ${unseenCount} new` : 'Show conversation'"
@click="expanded = true"
>
<ChevronUp />
<Badge v-if="unseenCount" variant="default" aria-hidden="true">{{ unseenCount }}</Badge>
</Button>
</TooltipTrigger>
<TooltipContent>Show conversation</TooltipContent>
</Tooltip>
</template>
</ChatComposer>
</div>
</aside>
</div>
</template>
+197
View File
@@ -0,0 +1,197 @@
/**
* Geometry and persistence for the chat dock window. The dock floats freely on
* desktop-width screens: the header drags it anywhere, eight edges and corners
* resize it, and dragging near a side edge offers the pinned split, which
* reflows the page. On phone-width screens it stays a full-width bottom bar,
* riding above the on-screen keyboard. Pure functions live here so the
* placement rules are testable without a DOM; ChatDock.vue owns the pointer
* and keyboard events.
*/
export type DockMode = "left" | "float" | "right";
export interface Rect {
x: number;
y: number;
w: number;
h: number;
}
export interface DockLayout extends Rect {
mode: DockMode;
}
export const DOCK_STORAGE_KEY = "archie.chat.dock.v2";
export const LEGACY_DOCK_STORAGE_KEY = "archie.chat.dock";
export const MIN_W = 320;
export const MIN_H = 280;
export const MAX_W = 720;
/** The minimised bar is at least this wide, screen permitting. */
export const BAR_W = 640;
/** Margin kept between a floating window and the viewport edge. */
export const INSET = 8;
/** Pointer distance from a side edge that offers the snap preview. */
const EDGE = 64;
/** Pointer travel before a press on a drag surface becomes a drag. */
export const DRAG_START = 4;
const KEY_STEP = 10;
const KEY_STEP_FAST = 40;
export const RESIZE_DIRS = ["n", "s", "e", "w", "ne", "nw", "se", "sw"] as const;
export type ResizeDir = (typeof RESIZE_DIRS)[number];
function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), Math.max(min, max));
}
export function defaultLayout(vw: number, vh: number): DockLayout {
const w = Math.min(440, Math.max(MIN_W, vw - INSET * 2));
const h = Math.min(560, Math.max(MIN_H, vh - INSET * 2));
return { mode: "float", x: Math.max(INSET, vw - w - 24), y: Math.max(INSET, vh - h - 24), w, h };
}
/** Largest width a floating window may take in this viewport. */
export function windowWidth(w: number, vw: number): number {
return clamp(w, MIN_W, Math.max(MIN_W, Math.min(MAX_W, vw - INSET * 2)));
}
/** Largest width the pinned split may take, leaving the page room to reflow. */
export function pinnedWidth(w: number, vw: number): number {
return clamp(w, MIN_W, Math.max(MIN_W, Math.min(MAX_W, vw - 480)));
}
/** Clamp a rectangle into the viewport, keeping its size within the minimums. */
export function fitRect<T extends Rect>(rect: T, vw: number, vh: number, inset = INSET): T {
const availW = Math.max(1, vw - inset * 2);
const availH = Math.max(1, vh - inset * 2);
const w = clamp(rect.w, Math.min(MIN_W, availW), Math.min(MAX_W, availW));
const h = clamp(rect.h, Math.min(MIN_H, availH), availH);
return {
...rect,
x: clamp(rect.x, inset, vw - w - inset),
y: clamp(rect.y, inset, vh - h - inset),
w,
h,
};
}
/** Validate a stored value, filling any missing field from the defaults. */
export function normalizeLayout(raw: unknown, vw: number, vh: number): DockLayout {
const d = defaultLayout(vw, vh);
if (!raw || typeof raw !== "object") return d;
const o = raw as Partial<Record<keyof DockLayout, unknown>>;
const mode: DockMode = o.mode === "left" || o.mode === "right" || o.mode === "float" ? o.mode : "float";
const num = (value: unknown, fallback: number): number =>
typeof value === "number" && Number.isFinite(value) ? value : fallback;
return fitRect(
{ mode, x: num(o.x, d.x), y: num(o.y, d.y), w: num(o.w, d.w), h: num(o.h, d.h) },
vw,
vh,
);
}
/** Resize a rectangle from one of the eight edges/corners by a pointer delta. */
export function resizeRect(origin: Rect, dir: ResizeDir, dx: number, dy: number, vw: number, vh: number): Rect {
const rect = { ...origin };
const minW = Math.min(MIN_W, Math.max(1, vw - INSET * 2));
const minH = Math.min(MIN_H, Math.max(1, vh - INSET * 2));
if (dir.includes("e")) rect.w = clamp(origin.w + dx, minW, Math.max(minW, vw - origin.x - INSET));
if (dir.includes("s")) rect.h = clamp(origin.h + dy, minH, Math.max(minH, vh - origin.y - INSET));
if (dir.includes("w")) {
rect.x = clamp(origin.x + dx, INSET, origin.x + origin.w - minW);
rect.w = origin.x + origin.w - rect.x;
}
if (dir.includes("n")) {
rect.y = clamp(origin.y + dy, INSET, origin.y + origin.h - minH);
rect.h = origin.y + origin.h - rect.y;
}
return rect;
}
/** The pinned side a pointer near an edge would commit to on release. */
export function snapEdge(pointerX: number, vw: number, edge = EDGE): "left" | "right" | null {
if (pointerX <= edge) return "left";
if (pointerX >= vw - edge) return "right";
return null;
}
/**
* Where the minimised bar sits: docked at the bottom of the screen, under the
* window's horizontal position or on the side the mode pins to. Returned as a
* bottom offset so the bar's own height never has to be known here.
*/
export function barPlacement(rect: Rect, mode: DockMode, vw: number): { x: number; bottom: number; w: number } {
const w = Math.max(rect.w, Math.min(BAR_W, vw - INSET * 2));
const x = mode === "left" ? 0 : mode === "right" ? Math.max(0, vw - w) : clamp(rect.x, INSET, Math.max(INSET, vw - w - INSET));
return { x, bottom: INSET, w };
}
/** Pointer travel down on the header that hides the conversation on a phone. */
export const SWIPE = 48;
/**
* How much of the layout viewport the on-screen keyboard covers, 0 when there
* is none. Fixed elements stay anchored to the layout viewport, so the phone
* bar offsets by this to ride above the keyboard.
*/
export function keyboardCover(innerHeight: number, vv: { height: number; offsetTop: number } | null): number {
return vv ? Math.max(0, Math.round(innerHeight - vv.height - vv.offsetTop)) : 0;
}
/** The phone bar's bottom offset: above the keyboard while one is up, else the safe area. */
export function phoneBarBottom(keyboard: number): string {
return keyboard > 0 ? `${keyboard + 8}px` : "max(0.5rem, env(safe-area-inset-bottom))";
}
/** The old { side, width } dock preference, as a partial new layout. */
export function legacyLayout(raw: unknown): Partial<DockLayout> | null {
if (!raw || typeof raw !== "object") return null;
const o = raw as Record<string, unknown>;
const partial: Partial<DockLayout> = { mode: o.side === "left" || o.side === "right" ? o.side : "float" };
if (typeof o.width === "number" && Number.isFinite(o.width)) partial.w = o.width;
return partial;
}
export interface StorageLike {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
removeItem(key: string): void;
}
/**
* Move the old "archie.chat.dock" preference into the new key (the side becomes
* the mode, the width the window width) and drop the old key either way: the
* new key deliberately replaces it.
*/
export function migrateDockStorage(storage: StorageLike, vw: number, vh: number): void {
try {
const legacy = storage.getItem(LEGACY_DOCK_STORAGE_KEY);
if (storage.getItem(DOCK_STORAGE_KEY) === null && legacy !== null) {
let parsed: unknown = null;
try {
parsed = JSON.parse(legacy);
} catch {
parsed = null;
}
storage.setItem(DOCK_STORAGE_KEY, JSON.stringify(normalizeLayout(legacyLayout(parsed) ?? {}, vw, vh)));
}
if (legacy !== null) storage.removeItem(LEGACY_DOCK_STORAGE_KEY);
} catch {
// Unwritable storage leaves the dock at its defaults for this visit.
}
}
export function keyStep(fast: boolean): number {
return fast ? KEY_STEP_FAST : KEY_STEP;
}
/** The separator orientation announced for a resize handle. */
export function handleOrientation(dir: ResizeDir): "horizontal" | "vertical" {
return dir === "e" || dir === "w" ? "vertical" : "horizontal";
}
/** The size a resize handle announces: its height on the north/south edges, else its width. */
export function handleValue(dir: ResizeDir, rect: Rect): number {
return dir === "n" || dir === "s" ? Math.round(rect.h) : Math.round(rect.w);
}
+32
View File
@@ -0,0 +1,32 @@
<script setup lang="ts">
import { RouterLink } from "vue-router";
import Logo from "@/components/topbar/Logo.vue";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import ChatSuggestions from "./ChatSuggestions.vue";
import { chatModelReady } from "./state";
/**
* What the panel opens on before there is a conversation: the mark, a greeting
* and the prompts for this page. Once the conversation has messages the
* prompts move beside the composer.
*/
</script>
<template>
<div class="w-full self-center justify-self-center px-1 py-6">
<div aria-hidden="true" class="mb-4 flex justify-center">
<Logo :open="false" class="text-[4rem]!" />
</div>
<h2 class="mb-5 text-center text-xl font-semibold tracking-tight">How can I help?</h2>
<ChatSuggestions v-if="chatModelReady" list />
<Alert v-else class="text-label">
<AlertDescription class="flex flex-wrap items-center justify-between gap-2">
No agent model is set.
<Button as-child variant="outline" size="sm"><RouterLink to="/settings" class="no-underline">Choose a model</RouterLink></Button>
</AlertDescription>
</Alert>
</div>
</template>
+35
View File
@@ -0,0 +1,35 @@
<script setup lang="ts">
import type { ChatInline } from "./markdown";
/** One inline run: the spans of a paragraph, a heading or a table cell. */
defineProps<{ inline: ChatInline[] }>();
</script>
<template>
<template v-for="(span, i) in inline" :key="i">
<img
v-if="span.kind === 'image'"
:src="span.src"
:alt="span.alt"
loading="lazy"
class="my-1 block max-h-96 max-w-full cursor-pointer rounded-md border border-border bg-card object-contain"
/>
<del v-else-if="span.kind === 'del'">{{ span.text }}</del>
<strong v-else-if="span.kind === 'strong'">{{ span.text }}</strong>
<code
v-else-if="span.kind === 'code'"
class="rounded bg-foreground/10 px-1 py-0.5 font-mono text-[0.9em]"
>{{ span.text }}</code
>
<a
v-else-if="span.kind === 'link'"
:href="span.href"
target="_blank"
rel="noreferrer"
class="text-link underline-offset-4 hover:underline"
>{{ span.text }}</a
>
<em v-else-if="span.kind === 'em'">{{ span.text }}</em>
<template v-else>{{ span.text }}</template>
</template>
</template>
+45
View File
@@ -0,0 +1,45 @@
<script setup lang="ts">
import { ArrowDownIcon } from "@lucide/vue";
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
import { MessageScrollerButton, useMessageScrollerScrollable } from "@/components/ui/message-scroller";
import { setAtEnd, unseenCount } from "./unseen";
/**
* The scroller's jump-to-latest button. It reads where the reader is for the
* unseen count and says how many replies are waiting below.
*
* The scroller measures on the frames after it mounts, and until then it
* reports "not scrollable", which would look like the end. The reader counts
* as at the end only once it has measured.
*/
const scrollable = useMessageScrollerScrollable();
const measured = ref(false);
let frame = 0;
onMounted(() => {
frame = requestAnimationFrame(() => {
frame = requestAnimationFrame(() => {
measured.value = true;
});
});
});
onUnmounted(() => {
cancelAnimationFrame(frame);
setAtEnd(false);
});
watch(
() => measured.value && !scrollable.value.end,
(end) => setAtEnd(end),
{ immediate: true },
);
const label = computed(() => `${unseenCount.value} new ${unseenCount.value === 1 ? "reply" : "replies"}`);
</script>
<template>
<MessageScrollerButton :size="unseenCount ? 'sm' : 'icon-sm'" :class="unseenCount ? 'gap-1.5 whitespace-nowrap' : undefined">
<ArrowDownIcon />
<template v-if="unseenCount">{{ label }}</template>
<span v-else class="sr-only">Scroll to end</span>
</MessageScrollerButton>
</template>
+100
View File
@@ -0,0 +1,100 @@
<script setup lang="ts">
import { computed } from "vue";
import CodeView from "@/base/CodeView.vue";
import ChatInline from "./ChatInline.vue";
import { parseMarkdown } from "./markdown";
/**
* A reply rendered as semantic HTML: headings, lists, quotes, fenced code,
* tables, inline emphasis. The parse is a computed, so a reply that grows a
* token at a time re-renders from the text it now has rather than accumulating
* markup.
*/
const props = defineProps<{ text: string }>();
const blocks = computed(() => parseMarkdown(props.text));
</script>
<template>
<div class="[overflow-wrap:anywhere]">
<template v-for="(block, i) in blocks" :key="i">
<CodeView v-if="block.kind === 'pre'" :code="block.code" :lang="block.lang" class="my-2" />
<table
v-else-if="block.kind === 'table'"
class="my-3 w-full border-collapse text-[0.92em]"
>
<thead>
<tr>
<th
v-for="(cell, c) in block.head"
:key="c"
class="border border-border bg-muted px-2 py-1.5 text-left font-semibold"
>
<ChatInline :inline="cell" />
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, r) in block.rows" :key="r">
<td
v-for="(cell, c) in row"
:key="c"
class="border border-border px-2 py-1.5 text-left"
>
<ChatInline :inline="cell" />
</td>
</tr>
</tbody>
</table>
<blockquote
v-else-if="block.kind === 'blockquote'"
class="my-2 border-l-[3px] border-primary pl-3 text-fg-muted"
>
<ChatInline :inline="block.inline" />
</blockquote>
<h1
v-else-if="block.kind === 'h1'"
class="mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]"
>
<ChatInline :inline="block.inline" />
</h1>
<h2
v-else-if="block.kind === 'h2'"
class="mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]"
>
<ChatInline :inline="block.inline" />
</h2>
<h3
v-else-if="block.kind === 'h3'"
class="mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]"
>
<ChatInline :inline="block.inline" />
</h3>
<ul
v-else-if="block.kind === 'ul'"
class="my-2.5 flex list-disc flex-col gap-1 pl-5"
>
<li v-for="(item, n) in block.items" :key="n">
<ChatInline :inline="item" />
</li>
</ul>
<ol
v-else-if="block.kind === 'ol'"
class="my-2.5 flex list-decimal flex-col gap-1 pl-5"
>
<li v-for="(item, n) in block.items" :key="n">
<ChatInline :inline="item" />
</li>
</ol>
<p v-else-if="block.kind === 'p'" class="mb-2.5 last:mb-0">
<ChatInline :inline="block.inline" />
</p>
</template>
</div>
</template>
+26
View File
@@ -0,0 +1,26 @@
<script setup lang="ts">
import { ArrowUpRight } from "@lucide/vue";
/**
* A dashboard_navigate result: a clickable chip that routes the operator to a
* dashboard page. It is an action, not evidence, so it is styled as a button
* rather than a muted log line, and it visibly invites a click. It is the only
* clickable navigation surface in the transcript.
*
* A RouterLink rather than a `#/path` anchor: history routing means the server
* stores bare paths, and an anchor would reload the whole app to change one
* segment.
*/
defineProps<{ path: string; label?: string }>();
</script>
<template>
<RouterLink
:to="path"
:title="`Go to ${label || path}`"
class="inline-flex max-w-full items-center gap-1.5 rounded-md border border-primary/45 bg-primary-soft px-2.5 py-1 text-caption font-semibold text-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
>
<ArrowUpRight aria-hidden="true" class="size-3.5 shrink-0" />
<span class="truncate">{{ label || path }}</span>
</RouterLink>
</template>
+82
View File
@@ -0,0 +1,82 @@
<script setup lang="ts">
import { ArrowUpRight, ChevronDown, ClipboardCheck, MessageSquare, Radio } from "@lucide/vue";
import { onMounted, ref } from "vue";
import { RouterLink } from "vue-router";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { Item, ItemActions, ItemContent, ItemMedia, ItemTitle } from "@/components/ui/item";
import { Timestamp } from "@/components/ui/timestamp";
import type { Message } from "../api";
import ChatApprovalCard from "./ChatApprovalCard.vue";
import { conversationOf, selectSession } from "./state";
/**
* A message from a run in the conversation: a notification, an approval
* request with its Approve and Deny, or the answer one got. A request a
* conversation asked links back to that conversation rather than to a run.
*/
const props = defineProps<{ notice: Message }>();
const askedBy = ref<{ session: string } | null>(null);
const resolved = ref(false);
onMounted(async () => {
if (props.notice.run_id) {
const session = await conversationOf(props.notice.run_id);
askedBy.value = session ? { session } : null;
}
resolved.value = true;
});
const icons = { notification: Radio, approval_request: Radio, approval_answer: ClipboardCheck };
</script>
<template>
<ChatApprovalCard
v-if="notice.kind === 'approval_request' && notice.request_id"
:request-id="notice.request_id"
:action="notice.title"
:summary="notice.body"
:run-id="notice.run_id"
/>
<Item v-else variant="outline" size="sm" class="items-start" role="group" :aria-label="notice.title">
<ItemMedia variant="icon" class="mt-0.5 text-muted-foreground"><component :is="icons[notice.kind]" aria-hidden="true" /></ItemMedia>
<ItemContent class="min-w-0">
<div class="flex flex-wrap items-baseline justify-between gap-x-3">
<ItemTitle class="w-auto min-w-0 break-words">{{ notice.title }}</ItemTitle>
<Timestamp :at="notice.created_at" class="text-caption text-muted-foreground" />
</div>
<Collapsible v-if="notice.body || notice.attempts?.length" v-slot="{ open }">
<CollapsibleTrigger as-child>
<Button variant="ghost" size="xs" class="-ml-2" :aria-label="`${open ? 'Hide' : 'View'} details for ${notice.title}`">
{{ open ? "Hide details" : "View details" }}
<ChevronDown :class="open && 'rotate-180'" aria-hidden="true" data-icon="inline-end" />
</Button>
</CollapsibleTrigger>
<CollapsibleContent class="mt-1 rounded-lg bg-muted/50 p-3">
<p v-if="notice.body" class="whitespace-pre-wrap break-words leading-relaxed">{{ notice.body }}</p>
<ul v-if="notice.attempts?.length" class="mt-2 flex flex-col gap-1 text-caption">
<li v-for="a in notice.attempts" :key="`${a.channel}:${a.attempt}`" class="flex flex-wrap items-center gap-2">
<span class="font-medium">{{ a.channel }}</span>
<span class="text-muted-foreground">Attempt {{ a.attempt }}</span>
<Badge :variant="a.ok ? 'secondary' : 'danger'">{{ a.ok ? "Delivered" : "Failed" }}</Badge>
<span v-if="a.error" class="break-all text-destructive">{{ a.error }}</span>
</li>
</ul>
</CollapsibleContent>
</Collapsible>
</ItemContent>
<ItemActions v-if="notice.run_id && resolved">
<Button v-if="askedBy" variant="link" size="sm" @click="selectSession(askedBy.session)">
<MessageSquare aria-hidden="true" data-icon="inline-start" />Open conversation
</Button>
<Button v-else variant="link" size="sm" as-child>
<RouterLink :to="{ name: 'run', params: { id: notice.run_id } }" :aria-label="`View run for ${notice.title}`"
>View run <ArrowUpRight aria-hidden="true" data-icon="inline-end"
/></RouterLink>
</Button>
</ItemActions>
</Item>
</template>
+38
View File
@@ -0,0 +1,38 @@
<script setup lang="ts">
import { ChevronDown, ShieldAlert } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { ReadError } from "@/components/ui/read-error";
import ChatApprovalCard from "./ChatApprovalCard.vue";
import { approvalReadFailed, loadApprovals, otherApprovals } from "./state";
/**
* Approvals waiting for an answer that the open conversation doesn't show,
* such as one a run asked before this conversation began, so none is out of
* reach from the chat.
*/
</script>
<template>
<ReadError v-if="approvalReadFailed" class="mx-3 mt-2" message="Couldn't load pending approvals." retry-label="Retry" @retry="loadApprovals" />
<Collapsible v-else-if="otherApprovals.length" v-slot="{ open }" class="border-t px-3 pt-2">
<CollapsibleTrigger as-child>
<Button variant="ghost" size="sm" class="w-full justify-start text-warn">
<ShieldAlert aria-hidden="true" data-icon="inline-start" />
{{ otherApprovals.length }} awaiting approval
<ChevronDown :class="['ml-auto', open && 'rotate-180']" aria-hidden="true" />
</Button>
</CollapsibleTrigger>
<CollapsibleContent class="flex max-h-[30dvh] flex-col overflow-y-auto pb-1">
<ChatApprovalCard
v-for="request in otherApprovals"
:key="request.id"
:request-id="request.id"
:action="request.action"
:summary="request.summary"
:run-id="request.run_id"
/>
</CollapsibleContent>
</Collapsible>
</template>
+159
View File
@@ -0,0 +1,159 @@
<script setup lang="ts">
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Copy, Ellipsis, Pencil, RotateCw, Trash2 } from "@lucide/vue";
import { ref } from "vue";
import { toast } from "vue-sonner";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import {
Popover,
PopoverAnchor,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import ChatSettings from "./ChatSettings.vue";
import { currentSession, deleteSession, messages, renameSession, retryLast, useEscapeLayer } from "./state";
/**
* The menu behind the bar's one "more" button: what acts on the conversation
* itself rather than on what is being said (send the last message again,
* rename, copy or delete the conversation), then the model it runs on. Each
* is also a slash command. The popover closes as the action goes, because its
* outcome shows in the transcript, not in the menu.
*/
const open = ref(false);
useEscapeLayer(open);
function retry(): void {
open.value = false;
void retryLast();
}
// Reply text is already Markdown, so the transcript is the messages under a
// heading per speaker. Empty turns (tool-only replies) have nothing to paste.
async function copyMarkdown(): Promise<void> {
open.value = false;
const text = messages.value
.map((m) => {
const body = m.notice ? `${m.notice.title}\n\n${m.notice.body}`.trim() : m.text.trim();
if (!body) return "";
return `### ${m.from === "web" ? "You" : "Archie"}\n\n${body}`;
})
.filter(Boolean)
.join("\n\n");
if (!text) {
toast.error("Nothing to copy yet.");
return;
}
try {
await navigator.clipboard.writeText(text);
} catch (err) {
toast.error(`Couldn't copy: ${err instanceof Error ? err.message : "the clipboard is unavailable"}`);
return;
}
toast.success("Copied as Markdown");
}
// Rename asks for the title in a labelled dialog, not window.prompt; delete
// asks to confirm, since it can't be undone.
const promptOpen = ref(false);
const confirmOpen = ref(false);
// A dialog owns Escape while open, so closing it leaves the dock open.
useEscapeLayer(promptOpen);
useEscapeLayer(confirmOpen);
const promptValue = ref("");
function rename(): void {
open.value = false;
promptValue.value = "";
promptOpen.value = true;
}
function submitPrompt(): void {
const value = promptValue.value.trim();
promptOpen.value = false;
if (value) void renameSession(value);
}
function confirmDelete(): void {
open.value = false;
confirmOpen.value = true;
}
function remove(): void {
confirmOpen.value = false;
void deleteSession();
}
</script>
<template>
<Popover v-model:open="open">
<!-- The anchor sits outside the tooltip chain on purpose: nested inside
TooltipTrigger, the popper anchor ref resolves to a component object
rather than the button, the content is never positioned, and the menu
stays parked off-screen. -->
<PopoverAnchor as-child>
<Tooltip>
<TooltipTrigger as-child>
<PopoverTrigger as-child>
<Button
variant="ghost"
size="icon-sm"
class="flex-none"
aria-label="More"
>
<Ellipsis />
</Button>
</PopoverTrigger>
</TooltipTrigger>
<TooltipContent>More</TooltipContent>
</Tooltip>
</PopoverAnchor>
<PopoverContent align="end" class="grid w-64 gap-0.5 p-1">
<template v-if="currentSession">
<Button variant="ghost" size="sm" class="justify-start" @click="retry"
><RotateCw data-icon="inline-start" />Retry</Button
>
<Button variant="ghost" size="sm" class="justify-start" @click="rename"
><Pencil data-icon="inline-start" />Rename</Button
>
<Button
variant="ghost"
size="sm"
class="justify-start"
@click="copyMarkdown"
><Copy data-icon="inline-start" />Copy as Markdown</Button
>
<Button variant="ghost" size="sm" class="justify-start text-destructive" @click="confirmDelete"
><Trash2 data-icon="inline-start" />Delete</Button
>
<Separator class="my-1" />
</template>
<ChatSettings />
</PopoverContent>
</Popover>
<Dialog :open="promptOpen" @update:open="(v: boolean) => (promptOpen = v)">
<DialogContent>
<DialogHeader><DialogTitle>Rename conversation</DialogTitle></DialogHeader>
<Input v-model="promptValue" aria-label="Title" maxlength="120" @keydown.enter.prevent="submitPrompt" />
<DialogFooter>
<Button variant="ghost" @click="promptOpen = false">Cancel</Button>
<Button :disabled="!promptValue.trim()" @click="submitPrompt">Rename</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog :open="confirmOpen" @update:open="(v: boolean) => (confirmOpen = v)">
<DialogContent>
<DialogHeader><DialogTitle>Delete this conversation?</DialogTitle></DialogHeader>
<DialogFooter>
<Button variant="ghost" @click="confirmOpen = false">Cancel</Button>
<Button variant="destructive" @click="remove">Delete</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</template>
+70
View File
@@ -0,0 +1,70 @@
<script setup lang="ts">
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Check, History, SquarePen, X } from "@lucide/vue";
import { onMounted, ref } from "vue";
import { Button } from "@/components/ui/button";
import { sessionTitle } from "./session";
import { currentSession, newChat, selectSession, sessions } from "./state";
/**
* The conversation drawer the bar's menu button opens over the panel: a new
* conversation first, then every conversation to switch to. It covers the
* panel rather than dropping down, so long titles get the panel's width.
*/
const emit = defineEmits<{ close: [] }>();
// Focus moves into the drawer, so Escape and Tab act on it straight away. The
// drawer itself takes it, not its first button, whose tooltip would open.
const nav = ref<HTMLElement | null>(null);
onMounted(() => nav.value?.focus());
function choose(id: string): void {
selectSession(id);
emit("close");
}
function start(): void {
newChat();
emit("close");
}
</script>
<template>
<nav
ref="nav"
tabindex="-1"
aria-label="Conversations"
class="outline-none absolute inset-0 z-20 flex flex-col gap-0.5 overflow-y-auto rounded-[inherit] bg-popover p-2"
@pointerdown.stop
@dblclick.stop
@keydown.esc.stop.prevent="emit('close')"
>
<Tooltip>
<TooltipTrigger as-child>
<Button variant="ghost" size="icon-sm" class="mb-1" aria-label="Close conversations" @click="emit('close')">
<X />
</Button>
</TooltipTrigger>
<TooltipContent>Close</TooltipContent>
</Tooltip>
<Button variant="ghost" size="sm" class="justify-start" @click="start">
<SquarePen data-icon="inline-start" />New chat
</Button>
<div class="mt-2 flex items-center gap-2 px-2 py-1 text-caption text-fg-muted">
<History class="size-3.5" aria-hidden="true" />Chats
</div>
<Button
v-for="session in sessions"
:key="session.session_id"
variant="ghost"
size="sm"
class="justify-start pl-7 font-normal"
:aria-current="session.session_id === currentSession ? 'true' : undefined"
@click="choose(session.session_id)"
>
<span class="min-w-0 flex-1 truncate text-left">{{ sessionTitle(session) }}</span>
<Check v-if="session.session_id === currentSession" class="flex-none" aria-hidden="true" />
</Button>
</nav>
</template>
+21
View File
@@ -0,0 +1,21 @@
<script setup lang="ts">
import { RouterLink } from "vue-router";
import { Button } from "@/components/ui/button";
import { activeModel, modelError, statusText } from "./state";
/**
* What the panel is doing right now and the model that answers. The model is
* the organisation's agent model, set in Settings like every agent's.
*/
</script>
<template>
<div class="grid gap-1 p-1 text-label">
<span v-if="statusText !== 'Ready'" class="text-caption text-fg-subtle">{{ statusText }}</span>
<div class="flex items-center justify-between gap-2">
<span class="min-w-0 truncate" :class="!activeModel && 'text-fg-muted'">{{ activeModel || modelError || "No agent model" }}</span>
<Button variant="link" size="sm" as-child><RouterLink to="/settings">Change</RouterLink></Button>
</div>
</div>
</template>
+71
View File
@@ -0,0 +1,71 @@
<script setup lang="ts">
import { nextTick, ref, watch } from "vue";
import { commandScrollTop } from "./command-scroll";
import { Button } from "@/components/ui/button";
import type { Completion } from "./commands";
/**
* The composer palette, floating above it: the commands after `/`. The arrow
* keys and the pointer both land here.
*/
const props = defineProps<{
matches: Completion[];
selection: number;
label: string;
error?: string;
}>();
const emit = defineEmits<{ choose: [index: number]; retry: [] }>();
const menu = ref<HTMLElement | null>(null);
// Arrow keys move the selection, and the list scrolls so the highlight stays
// visible once the matches run past the rows that fit. The arithmetic is
// command-scroll.ts's; this only applies what it returns. flush: 'post' so the
// option being measured is the one just selected, not the one leaving.
watch(
() => [props.selection, props.matches.length],
async () => {
await nextTick();
const el = menu.value;
const option = el?.children[props.selection] as HTMLElement | undefined;
if (!el || !option) return;
el.scrollTop = commandScrollTop({
scrollTop: el.scrollTop,
viewportHeight: el.clientHeight,
optionTop: option.offsetTop,
optionHeight: option.offsetHeight,
});
},
{ flush: "post" },
);
</script>
<template>
<div
ref="menu"
id="slash-palette"
role="listbox"
:aria-label="label"
class="absolute inset-x-3 bottom-[calc(100%-0.25rem)] z-30 grid max-h-72 gap-0.5 overflow-auto rounded-lg border border-border-strong bg-popover p-1.5 text-label shadow-md"
>
<div v-if="error" role="alert" class="flex items-center justify-between gap-2 px-2.5 py-2 text-danger">
<span class="truncate">{{ error }}</span>
<Button variant="outline" size="sm" @mousedown.prevent @click="emit('retry')">Retry</Button>
</div>
<button
v-for="(item, index) in matches"
:key="item.key"
type="button"
role="option"
:id="`slash-palette-option-${index}`"
:aria-selected="index === selection"
class="flex flex-col gap-0.5 rounded-md border border-transparent px-2.5 py-1.5 text-left text-fg-muted hover:bg-muted hover:text-foreground aria-selected:border-border aria-selected:bg-muted aria-selected:text-foreground"
@mousedown.prevent
@click="emit('choose', index)"
>
<code class="truncate text-foreground">{{ item.label }}</code>
<span v-if="item.detail" class="line-clamp-2 text-caption">{{ item.detail }}</span>
</button>
</div>
</template>
+93
View File
@@ -0,0 +1,93 @@
<script setup lang="ts">
import { MessageSquare } from "@lucide/vue";
import { computed, onUnmounted } from "vue";
import { useRoute } from "vue-router";
import { Button } from "@/components/ui/button";
import { chatModelReady, messages, placeholderHint, sendMessage } from "./state";
import { suggestionsForRoute } from "./suggestions";
/**
* The suggested prompts for the page the operator is on. The empty
* conversation lists them (`list`); beside the composer they are a row of
* chips that scrolls sideways. None show until an agent model is configured. A
* click sends the prompt as its own message rather than filling the field, and
* resting on one previews it as the composer's placeholder.
*/
defineProps<{ list?: boolean }>();
const route = useRoute();
// No model, no prompts: one sent now could only fail.
// A prompt already asked in this conversation is not suggested again.
const prompts = computed(() => {
if (!chatModelReady.value) return [];
const asked = new Set(messages.value.filter((m) => m.from === "web").map((m) => m.text.trim()));
return suggestionsForRoute(route).filter((p) => !asked.has(p));
});
function send(prompt: string): void {
placeholderHint.value = "";
void sendMessage({ textOverride: prompt });
}
function preview(prompt: string): void {
placeholderHint.value = prompt;
}
// A vertical wheel scrolls the row sideways; a trackpad's sideways swipe
// already does.
function scrollSideways(event: WheelEvent): void {
if (Math.abs(event.deltaY) <= Math.abs(event.deltaX)) return;
const row = event.currentTarget as HTMLElement;
if (row.scrollWidth <= row.clientWidth) return;
event.preventDefault();
row.scrollLeft += event.deltaY;
}
function clear(): void {
placeholderHint.value = "";
}
onUnmounted(clear);
</script>
<template>
<ul v-if="prompts.length && list" class="flex flex-col gap-1 text-left" aria-label="Suggested prompts">
<li v-for="prompt in prompts" :key="prompt">
<Button
variant="ghost"
class="h-auto w-full justify-start gap-3 py-1.5 whitespace-normal text-left font-normal"
@click="send(prompt)"
@pointerenter="preview(prompt)"
@pointerleave="clear"
@focus="preview(prompt)"
@blur="clear"
>
<span class="flex size-7 flex-none items-center justify-center rounded-md border" aria-hidden="true">
<MessageSquare class="size-3.5" />
</span>
{{ prompt }}
</Button>
</li>
</ul>
<!-- One row that scrolls sideways, so the prompts never push the
transcript up by more than a line. -->
<div
v-else-if="prompts.length"
class="-mx-3 mb-2 flex snap-x snap-mandatory scroll-px-3 gap-1.5 overflow-x-auto px-3 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
role="group"
aria-label="Suggested prompts"
@wheel="scrollSideways"
>
<Button
v-for="prompt in prompts"
:key="prompt"
variant="outline"
size="sm"
class="flex-none snap-start whitespace-nowrap"
@click="send(prompt)"
@pointerenter="preview(prompt)"
@pointerleave="clear"
@focus="preview(prompt)"
@blur="clear"
>
{{ prompt }}
</Button>
</div>
</template>
+50
View File
@@ -0,0 +1,50 @@
<script setup lang="ts">
import { BrainIcon } from "@lucide/vue";
import { Spinner } from "@/components/ui/spinner";
import {
Trace,
TraceCollapsible,
TraceCollapsibleContent,
TraceCollapsibleTrigger,
TraceIcon,
TraceLine,
TraceTitle,
} from "@/components/ui/trace";
/**
* The live turn's thinking: the model's reasoning as it streams, in the same
* collapsible trace a tool call uses. While the turn has not produced any
* reasoning yet, the icon spins and the title shimmers; once text arrives it
* streams into the open trace. A finished turn's thinking is folded away. A
* turn that never reasons renders nothing, which the caller decides by not
* mounting this at all.
*/
withDefaults(
defineProps<{
text?: string;
/** The turn is still arriving and has not reasoned yet. */
pending?: boolean;
/** A finished turn's thinking starts folded away. */
collapsed?: boolean;
}>(),
{ text: "", pending: false, collapsed: false },
);
</script>
<template>
<Trace class="my-2">
<TraceCollapsible :default-open="!collapsed">
<TraceCollapsibleTrigger>
<TraceLine :status="pending && !text ? 'running' : undefined">
<TraceIcon>
<Spinner v-if="pending && !text" />
<BrainIcon v-else />
</TraceIcon>
<TraceTitle>Thinking</TraceTitle>
</TraceLine>
</TraceCollapsibleTrigger>
<TraceCollapsibleContent v-if="text" class="whitespace-pre-wrap [overflow-wrap:anywhere]">{{ text }}</TraceCollapsibleContent>
</TraceCollapsible>
</Trace>
</template>
+110
View File
@@ -0,0 +1,110 @@
<script setup lang="ts">
import { Spinner } from "@/components/ui/spinner";
import { CircleCheck, CircleX } from "@lucide/vue";
import { computed } from "vue";
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block";
import { duration as formatDuration } from "@/lib/format";
import {
TraceCollapsible,
TraceCollapsibleContent,
TraceCollapsibleTrigger,
TraceIcon,
TraceLine,
TraceTitle,
} from "@/components/ui/trace";
import ChatNavChip from "./ChatNavChip.vue";
import type { ChatToolCall } from "./state";
/**
* One tool call: the name, and what came back once it is opened.
*
* A quiet line rather than the point of the reply: it is evidence for the
* answer under it, so it is dim, and a failed call is the only thing here that
* raises its voice. The parameters it was given and its outcome are folded away
* until asked for. Rendered inside a Trace, which an empty list never creates,
* so a turn that called no tools looks untouched.
*/
const props = defineProps<{
tool: ChatToolCall;
/** The turn is still arriving, so a call with no outcome yet is running. */
streaming?: boolean;
}>();
const name = computed(
() => props.tool.name || props.tool.Name || props.tool.tool || "tool",
);
const parameters = computed(
() => props.tool.parameters || props.tool.Parameters || "",
);
const failed = computed(() =>
Boolean(props.tool.err || props.tool.Err || props.tool.failed),
);
// A recorded turn reports its outcome in summary, a live frame in text, and a
// failure may only carry the error.
const outcome = computed(
() =>
props.tool.summary ||
props.tool.Summary ||
props.tool.text ||
props.tool.err ||
props.tool.Err ||
"",
);
const running = computed(() => !outcome.value && !failed.value && !!props.streaming);
const duration = computed(() => formatDuration(props.tool.duration_ms));
// The row shows the call's main value, as "git diff --stat" rather than its
// JSON: the first string argument, else its arguments as key: value pairs.
const argument = computed(() => {
try {
const args: unknown = JSON.parse(parameters.value);
if (args && typeof args === "object" && !Array.isArray(args)) {
const first = Object.values(args).find((v) => typeof v === "string" && v);
if (typeof first === "string") return first.split("\n", 1)[0];
return Object.entries(args)
.map(([key, value]) => `${key}: ${typeof value === "object" ? JSON.stringify(value) : value}`)
.join(", ");
}
} catch {
// Truncated or not JSON: show it as it came.
}
return parameters.value.split("\n", 1)[0];
});
const detail = computed(() =>
[parameters.value && `> ${parameters.value}`, outcome.value].filter(Boolean).join("\n\n"),
);
</script>
<template>
<ChatNavChip v-if="tool.path" :path="tool.path" :label="tool.label" />
<TraceCollapsible v-else-if="detail" :default-open="failed">
<TraceCollapsibleTrigger>
<TraceLine :status="failed ? 'error' : running ? 'running' : undefined">
<TraceIcon>
<CircleX v-if="failed" />
<Spinner v-else-if="running" />
<CircleCheck v-else class="text-ok" />
</TraceIcon>
<span class="font-mono text-foreground">{{ name }}</span>
<TraceTitle class="font-mono text-caption">{{ argument }}</TraceTitle>
<span v-if="duration" class="shrink-0 text-caption tabular-nums">{{ duration }}</span>
</TraceLine>
</TraceCollapsibleTrigger>
<TraceCollapsibleContent>
<CodeBlock size="sm">
<CodeBlockContent wrap class="max-h-64">{{ detail }}</CodeBlockContent>
</CodeBlock>
</TraceCollapsibleContent>
</TraceCollapsible>
<TraceLine v-else :status="failed ? 'error' : running ? 'running' : undefined">
<TraceIcon>
<CircleX v-if="failed" />
<Spinner v-else-if="running" />
<CircleCheck v-else class="text-ok" />
</TraceIcon>
<span class="font-mono text-foreground">{{ name }}</span>
<TraceTitle class="font-mono text-caption">{{ argument }}</TraceTitle>
<span v-if="duration" class="shrink-0 text-caption tabular-nums">{{ duration }}</span>
</TraceLine>
</template>
+47
View File
@@ -0,0 +1,47 @@
<script setup lang="ts">
import { Wrench } from "@lucide/vue";
import { computed } from "vue";
import {
TraceCollapsible,
TraceCollapsibleContent,
TraceCollapsibleTrigger,
TraceIcon,
TraceLine,
TraceTitle,
} from "@/components/ui/trace";
import ChatToolCall from "./ChatToolCall.vue";
import type { ChatToolCall as ToolCall } from "./state";
/**
* A run of consecutive tool calls as one line, opened to the individual
* calls. A failure anywhere in the run opens it.
*/
const props = defineProps<{ tools: ToolCall[]; streaming?: boolean }>();
const failed = (tool: ToolCall) => Boolean(tool.err || tool.Err || tool.failed);
const anyFailed = computed(() => props.tools.some(failed));
const title = computed(() => `${props.tools.length} tool call${props.tools.length === 1 ? "" : "s"}`);
</script>
<template>
<TraceCollapsible :default-open="anyFailed">
<TraceCollapsibleTrigger>
<TraceLine :status="anyFailed ? 'error' : undefined">
<TraceIcon><Wrench /></TraceIcon>
<TraceTitle class="truncate">{{ title }}</TraceTitle>
</TraceLine>
</TraceCollapsibleTrigger>
<TraceCollapsibleContent>
<div class="flex flex-col gap-1.5">
<ChatToolCall
v-for="(tool, i) in tools"
:key="i"
:tool="tool"
:streaming="streaming && i === tools.length - 1"
/>
</div>
</TraceCollapsibleContent>
</TraceCollapsible>
</template>
+42
View File
@@ -0,0 +1,42 @@
<script setup lang="ts">
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { MessageCircle } from "@lucide/vue";
import { computed } from "vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Kbd } from "@/components/ui/kbd";
import { dockExpanded } from "./state";
import { unseenCount } from "./unseen";
/**
* Opens and closes the chat dock from the topbar, so a dock that is minimised,
* or hidden because it is docked, is one click away without knowing Ctrl+/.
*/
const shortcut = navigator.platform.startsWith("Mac") ? "⌘/" : "Ctrl /";
const label = computed(() => {
const action = dockExpanded.value ? "Hide chat" : "Chat with Archie";
return unseenCount.value ? `${action}, ${unseenCount.value} new` : action;
});
</script>
<template>
<Tooltip>
<TooltipTrigger as-child>
<Button
variant="ghost"
size="icon"
class="relative"
:aria-label="label"
:aria-pressed="dockExpanded"
@click="dockExpanded = !dockExpanded"
>
<MessageCircle class="size-4" aria-hidden="true" />
<Badge v-if="unseenCount" class="absolute -top-0.5 -right-1.5 h-4 min-w-4 px-1 text-caption tabular-nums" aria-hidden="true">
{{ unseenCount }}
</Badge>
</Button>
</TooltipTrigger>
<TooltipContent>{{ dockExpanded ? "Hide chat" : "Chat with Archie" }} <Kbd>{{ shortcut }}</Kbd></TooltipContent>
</Tooltip>
</template>
+98
View File
@@ -0,0 +1,98 @@
<script setup lang="ts">
import { computed } from "vue";
import { Button } from "@/components/ui/button";
import {
MessageScroller,
MessageScrollerContent,
MessageScrollerItem,
MessageScrollerProvider,
MessageScrollerViewport,
} from "@/components/ui/message-scroller";
import ChatApprovalCard from "./ChatApprovalCard.vue";
import ChatBubble from "./ChatBubble.vue";
import ChatEmptyState from "./ChatEmptyState.vue";
import ChatJumpButton from "./ChatJumpButton.vue";
import ChatNoticeCard from "./ChatNoticeCard.vue";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Skeleton } from "@/components/ui/skeleton";
import { currentSession, isLoadingSession, messages, retryLast, selectSession, sessionError } from "./state";
/**
* The conversation: each message and its reply, the cards runs sent while it
* was open, and what the panel says before any exist.
*
* The scroller follows the tail, and stops following the moment the reader
* scrolls up rather than yanking them back on every streamed token.
*/
const rows = computed(() =>
messages.value.map((m) => ({
...m,
thinkingPending: !!m.live && !m.text && !m.reasoning && !m.tool_calls?.length,
})),
);
</script>
<template>
<MessageScrollerProvider auto-scroll default-scroll-position="last-anchor">
<MessageScroller class="min-h-0 flex-1">
<MessageScrollerViewport>
<MessageScrollerContent class="gap-4 p-4">
<template v-if="isLoadingSession && !rows.length">
<Skeleton class="h-14 w-3/5 self-end rounded-xl" />
<Skeleton class="h-24 w-4/5 rounded-xl" />
<Skeleton class="h-10 w-2/5 self-end rounded-xl" />
</template>
<div v-else-if="sessionError && !rows.length" class="flex flex-col items-center gap-3 p-4">
<Alert variant="destructive" class="max-w-md"><AlertDescription>{{ sessionError }}</AlertDescription></Alert>
<Button variant="outline" size="sm" @click="selectSession(currentSession)">Retry</Button>
</div>
<ChatEmptyState v-else-if="!rows.length" />
<template v-else>
<MessageScrollerItem
v-for="row in rows"
:key="row.key"
:message-id="row.key"
:scroll-anchor="row.from === 'web'"
>
<ChatNoticeCard v-if="row.notice" :notice="row.notice" />
<ChatBubble
v-else
:text="row.live && !row.text ? '…' : row.text"
:tools="row.tool_calls"
:page="row.page"
:assistant="row.from === 'assistant'"
:streaming="row.live"
:reasoning="row.reasoning"
:thinking-pending="row.thinkingPending"
:error="row.error"
>
<ChatApprovalCard
v-for="approval in row.approvals"
:key="approval.request_id"
:request-id="approval.request_id"
:action="approval.action"
:summary="approval.summary"
:outcome="approval.outcome"
/>
<Button
v-if="row.error && row.turn"
variant="outline"
size="sm"
class="mt-2"
@click="retryLast(row.turn)"
>Retry</Button>
</ChatBubble>
</MessageScrollerItem>
</template>
<Alert v-if="sessionError && rows.length" variant="destructive"><AlertDescription>{{ sessionError }}</AlertDescription></Alert>
</MessageScrollerContent>
</MessageScrollerViewport>
<ChatJumpButton />
</MessageScroller>
</MessageScrollerProvider>
</template>
+41
View File
@@ -0,0 +1,41 @@
// Keeping the arrow-key selection visible in the command palette.
//
// The palette caps its height and scrolls, so once the matches run past the
// visible rows the selection must scroll with the highlight. Browsers have
// scrollIntoView, but the decision is pure
// arithmetic and worth testing on its own, so the effect only applies what
// this returns.
/** The palette's scroll geometry and the selected option's position in it. */
export interface CommandScrollGeometry {
scrollTop: number;
viewportHeight: number;
optionTop: number;
optionHeight: number;
}
/**
* commandScrollTop returns the scrollTop that brings the selected option fully
* into view, or the current scrollTop when it is already visible. Mirrors
* `scrollIntoView({ block: "nearest" })`: it moves the minimum distance, and
* scrolls up for an option above the viewport, down for one below.
*/
export function commandScrollTop({
scrollTop,
viewportHeight,
optionTop,
optionHeight,
}: CommandScrollGeometry): number {
// An option taller than the viewport cannot be shown whole. Align its top,
// which holds the command itself; aligning the bottom would scroll the name
// out of sight and leave only the tail of its description.
if (optionHeight >= viewportHeight) return optionTop;
if (optionTop < scrollTop) return optionTop;
const optionBottom = optionTop + optionHeight;
const viewportBottom = scrollTop + viewportHeight;
if (optionBottom > viewportBottom) return optionBottom - viewportHeight;
return scrollTop;
}
+88
View File
@@ -0,0 +1,88 @@
import type { ChatCommandSpec } from "./state";
/**
* The composer palette's arithmetic, kept out of the composer so it is decided
* in one place rather than reconstructed from DOM positions twice. `/`
* completes a command.
*/
export type Trigger = "/";
/** One row of the palette: what is shown, and the key that identifies it. */
export interface Completion {
key: string;
label: string;
detail: string;
}
/** The trigger word the caret sits in: at the start or after whitespace. */
const OPEN_TOKEN = /(?:^|\s)([/])([^\s]*)$/;
/** How many matches the palette will show at once. */
const MAX_MATCHES = 8;
/** detectTrigger returns the trigger and the text typed after it, if any. */
export function detectTrigger(
value: string,
caret: number,
): { trigger: Trigger; query: string } | null {
const match = value.slice(0, caret).match(OPEN_TOKEN);
if (!match) return null;
return { trigger: match[1] as Trigger, query: match[2].toLowerCase() };
}
/** Commands matched on the command and its description together. */
export function commandCompletions(
specs: ChatCommandSpec[],
query: string,
): Completion[] {
return specs
.filter((spec) =>
`${spec.command} ${spec.description ?? ""}`.toLowerCase().includes(query),
)
.slice(0, MAX_MATCHES)
.map((spec) => ({
key: spec.command,
label: spec.command,
detail: spec.description || spec.usage || "",
}));
}
/**
* replaceToken swaps the trigger word the caret sits in for `insert` and
* returns the caret just after it. A space follows the insert unless one
* already does, so completing mid-sentence never doubles it. An empty insert
* removes the token.
*/
export function replaceToken(
value: string,
caret: number,
insert: string,
): { text: string; cursor: number } {
const before = value.slice(0, caret);
const after = value.slice(caret);
const start = before.search(/(?:^|\s)[/][^\s]*$/);
const tokenStart =
start < 0 ? before.length : start + (/\s/.test(before[start]) ? 1 : 0);
const head = before.slice(0, tokenStart);
const gap = insert === "" || /^\s/.test(after) ? "" : " ";
// Removing the token must not leave the words either side of it two spaces apart.
const tail = insert === "" && /\s$/.test(head) ? after.replace(/^[ \t]/, "") : after;
return {
text: `${head}${insert}${gap}${tail}`,
cursor: tokenStart + insert.length + gap.length,
};
}
/**
* isExactCommand reports whether the composer already holds a command and
* nothing else. Enter then sends it rather than completing it, so a command
* typed in full is never re-entered by the palette that was offering it.
*/
export function isExactCommand(
specs: ChatCommandSpec[],
value: string,
): boolean {
const trimmed = value.trim();
return specs.some((spec) => spec.command === trimmed);
}
+191
View File
@@ -0,0 +1,191 @@
/**
* Chat markdown.
*
* Telegram-style rich blocks -- headings, lists, quotes, fenced code, tables,
* inline emphasis/links/images -- parsed into a tree that ChatMarkdown renders
* as semantic HTML. The parse is separate from the render so a streamed reply
* can be re-rendered on every frame without re-deciding what the text means.
*/
/** One span of an inline run: what a paragraph's text breaks down into. */
export type ChatInline =
| { kind: "text"; text: string }
| { kind: "strong"; text: string }
| { kind: "em"; text: string }
| { kind: "del"; text: string }
| { kind: "code"; text: string }
| { kind: "link"; text: string; href: string }
| { kind: "image"; alt: string; src: string };
/** One block of the document. Lists carry their items as inline runs. */
export type ChatBlock =
| { kind: "p" | "h1" | "h2" | "h3" | "blockquote"; inline: ChatInline[] }
| { kind: "ul" | "ol"; items: ChatInline[][] }
| { kind: "pre"; code: string; lang: string }
| { kind: "table"; head: ChatInline[][]; rows: ChatInline[][][] };
const INLINE =
/(!\[[^\]]*\]\((?:https?:\/\/[^\s)]+|data:image\/[^\s)]+|\/[^\s)]+)\)|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\((?:https?:\/\/[^\s)]+|\/[^\s)]+)\)|\*[^*]+\*|_[^_]+_)/g;
function plainText(text: string): ChatInline[] {
return text ? [{ kind: "text", text }] : [];
}
// inlineMarkdown returns the children of one line: plain text and the element
// each matched span becomes, in order.
function inlineMarkdown(text: string): ChatInline[] {
const children: ChatInline[] = [];
let cursor = 0;
for (const match of String(text).matchAll(INLINE)) {
if (match.index > cursor)
children.push(...plainText(text.slice(cursor, match.index)));
const value = match[0];
if (value.startsWith("![")) {
const img = value.match(/^!\[([^\]]*)\]\((.+)\)$/);
if (img)
children.push({ kind: "image", alt: img[1] || "Image", src: img[2] });
} else if (value.startsWith("~~")) {
children.push({ kind: "del", text: value.slice(2, -2) });
} else if (value.startsWith("**") || value.startsWith("__")) {
children.push({ kind: "strong", text: value.slice(2, -2) });
} else if (value.startsWith("`")) {
children.push({ kind: "code", text: value.slice(1, -1) });
} else if (value.startsWith("[")) {
const link = value.match(
/^\[([^\]]+)\]\((https?:\/\/[^\s)]+|\/[^\s)]+)\)$/,
);
if (link) children.push({ kind: "link", text: link[1], href: link[2] });
} else {
children.push({ kind: "em", text: value.slice(1, -1) });
}
cursor = match.index + value.length;
}
if (cursor < text.length)
children.push(...plainText(text.slice(cursor)));
return children;
}
export function parseMarkdown(text: string | null | undefined): ChatBlock[] {
const blocks: ChatBlock[] = [];
const lines = String(text || "").split("\n");
let paragraph: string[] = [];
let list: { tag: "ul" | "ol"; items: string[] } | null = null;
let code: string[] | null = null;
let lang = "";
const flushParagraph = () => {
if (paragraph.length) {
blocks.push({ kind: "p", inline: inlineMarkdown(paragraph.join(" ")) });
paragraph = [];
}
};
const flushList = () => {
if (!list) return;
blocks.push({
kind: list.tag,
items: list.items.map((item) => inlineMarkdown(item)),
});
list = null;
};
for (let index = 0; index < lines.length; index++) {
const line = lines[index];
if (line.startsWith("```")) {
flushParagraph();
flushList();
if (code) {
blocks.push({ kind: "pre", code: code.join("\n"), lang });
code = null;
} else {
code = [];
lang = line.slice(3).trim().split(/\s/)[0];
}
continue;
}
if (code) {
code.push(line);
continue;
}
const headerCells = tableCells(line);
const separatorCells =
index + 1 < lines.length ? tableCells(lines[index + 1]) : null;
if (
headerCells &&
separatorCells &&
isTableSeparator(separatorCells) &&
headerCells.length === separatorCells.length
) {
flushParagraph();
flushList();
const rows: string[][] = [];
for (index += 2; index < lines.length; index++) {
const cells = tableCells(lines[index]);
if (!cells || cells.length !== headerCells.length) {
index--;
break;
}
rows.push(cells);
}
blocks.push({
kind: "table",
head: headerCells.map((cell) => inlineMarkdown(cell)),
rows: rows.map((row) => row.map((cell) => inlineMarkdown(cell))),
});
continue;
}
if (!line.trim()) {
flushParagraph();
flushList();
continue;
}
const heading = line.match(/^(#{1,3})\s+(.+)$/);
if (heading) {
flushParagraph();
flushList();
blocks.push({
kind: `h${heading[1].length}` as "h1" | "h2" | "h3",
inline: inlineMarkdown(heading[2]),
});
continue;
}
const bullet = line.match(/^\s*[-*]\s+(.+)$/);
const ordered = line.match(/^\s*\d+[.)]\s+(.+)$/);
if (bullet || ordered) {
flushParagraph();
const tag = ordered ? "ol" : "ul";
if (!list || list.tag !== tag) {
flushList();
list = { tag, items: [] };
}
list.items.push((bullet || ordered)![1]);
continue;
}
if (line.startsWith(">")) {
flushParagraph();
flushList();
blocks.push({
kind: "blockquote",
inline: inlineMarkdown(line.replace(/^>\s?/, "")),
});
continue;
}
paragraph.push(line);
}
flushParagraph();
flushList();
if (code) blocks.push({ kind: "pre", code: code.join("\n"), lang });
return blocks;
}
function tableCells(line: string): string[] | null {
const value = String(line || "").trim();
if (!value.includes("|")) return null;
const unwrapped = value.replace(/^\|/, "").replace(/\|$/, "");
const cells = unwrapped.split("|").map((cell) => cell.trim());
return cells.length > 1 && cells.every((cell) => cell !== "") ? cells : null;
}
function isTableSeparator(cells: string[]): boolean {
return cells.every((cell) => /^:?-{3,}:?$/.test(cell));
}
+30
View File
@@ -0,0 +1,30 @@
import { useAppearanceStore } from "@/stores/appearance";
import type { ChatSession } from "./state";
// One formatter per zone, cached: the zone chosen under Appearance is applied
// here like Timestamp applies it, not the browser's zone.
const startedCache = new Map<string, Intl.DateTimeFormat>();
function started(zone: string): Intl.DateTimeFormat {
const cached = startedCache.get(zone);
if (cached) return cached;
const format = new Intl.DateTimeFormat(undefined, {
month: "short",
day: "numeric",
hour: "numeric",
minute: "2-digit",
...(zone ? { timeZone: zone } : {}),
});
startedCache.set(zone, format);
return format;
}
// An untitled conversation is named by when it began, which tells two apart
// where a raw id cannot.
export function sessionTitle(session: ChatSession): string {
const named = session.title;
if (named) return named;
return session.created_at
? started(useAppearanceStore().timeZone).format(new Date(session.created_at))
: "New chat";
}
+677
View File
@@ -0,0 +1,677 @@
import { computed, onMounted, onUnmounted, ref, watch, type Ref } from "vue";
import router from "../router";
import {
answerApproval,
cancelChatTurn,
chatSessions,
chatTurn,
chatTurnEvents,
chatTurns,
composerStream,
createChatSession,
deleteChatSession,
latestMessages,
messagesAfter,
pendingApprovals,
renameChatSession,
sendChatTurn,
Unauthorized,
type ChatActionDone,
type ChatApproval,
type ChatSession,
type ChatTurn,
type Message,
type PendingApproval,
} from "../api";
import { commandCompletions, detectTrigger, type Completion, type Trigger } from "./commands";
/**
* The chat's shared state.
*
* The dock and the composer page are separate components and the dock survives
* a navigation, so the conversation lives in a module rather than in either
* one. Turns are the server's: a message is stored before it is shown as sent,
* a turn sent while another runs waits in the server's queue, and what a turn
* streams is recorded, so a reload follows a running turn from where it is.
* Notifications and approval requests from runs show in the conversation as
* cards; an approval is answered only through its card.
*/
export type { ChatSession };
/** One slash command the composer accepts. */
export interface ChatCommandSpec {
command: string;
usage?: string;
description?: string;
}
/**
* A tool the assistant called, or a page it offered: a navigation carries
* `path` and renders as a link rather than a tool line.
*/
export interface ChatToolCall {
id?: string;
name?: string;
tool?: string;
parameters?: string;
summary?: string;
text?: string;
failed?: boolean;
duration_ms?: number;
text_offset?: number;
path?: string;
label?: string;
Name?: string;
Parameters?: string;
Summary?: string;
Err?: string;
err?: string;
}
/** One row of the transcript: the operator's message, Archie's reply, or a card from a run. */
export interface ChatMessage {
key: string;
from: "web" | "assistant" | "notice";
text: string;
/** The page the message was asked from. */
page?: string;
tool_calls?: ChatToolCall[];
/** Actions judgement held during the turn, with what became of each. */
approvals?: (ChatApproval & { outcome?: ChatActionDone })[];
reasoning?: string;
/** The reply is still arriving. */
live?: boolean;
/** The turn waits behind another one in this conversation. */
queued?: boolean;
error?: boolean;
/** The turn this row belongs to, for a retry. */
turn?: ChatTurn;
notice?: Message;
}
export const sessions = ref<ChatSession[]>([]);
export const currentSession = ref("");
const turns = ref<ChatTurn[]>([]);
const notices = ref<Message[]>([]);
/** Approval requests waiting for an answer, from any run or conversation. */
export const approvals = ref<PendingApproval[]>([]);
export const approvalReadFailed = ref(false);
export const noticeError = ref("");
const drafts = ref<Record<string, string>>({});
/** Whether the chat dock shows the conversation; the dock, Ctrl+/ and the topbar button share it. */
export const dockExpanded = ref(false);
/** A suggested prompt the pointer or focus rests on, previewed as the composer placeholder. */
export const placeholderHint = ref("");
/** The unsent text of the open conversation; each conversation keeps its own. */
export const composerText = computed({
get: () => drafts.value[currentSession.value] ?? "",
set: (value: string) => {
drafts.value = { ...drafts.value, [currentSession.value]: value };
},
});
export const statusText = ref("Ready");
export const isLoadingSession = ref(false);
// A failed conversation load or send: shown in the transcript itself.
export const sessionError = ref("");
export const activeModel = ref("");
export const modelError = ref("");
/** Whether an agent model is configured, so a prompt sent now can be answered. */
export const chatModelReady = computed(() => !!activeModel.value);
/** The dashboard was refused: the shell signs the operator out. */
export const unauthorized = ref(false);
/** The commands the composer's palette offers. Each acts on the conversation through its API. */
export const commandSpecs = ref<ChatCommandSpec[]>([
{ command: "/new", description: "Start a new conversation" },
{ command: "/rename", usage: "/rename <title>", description: "Rename this conversation" },
{ command: "/retry", description: "Send the last message again" },
{ command: "/stop", description: "Stop the turn in progress" },
{ command: "/delete", description: "Delete this conversation" },
]);
export const commandMatches = ref<Completion[]>([]);
export const menuTrigger = ref<Trigger>("/");
export const commandSelection = ref(0);
export const isCommandMenuOpen = ref(false);
/**
* How many layers inside the panel currently own Escape -- an open popover, a
* select inside one. The panel's own Escape defers to them.
*/
const openLayers = ref(0);
/** Registers a toggleable layer inside the panel, for as long as it is mounted. */
export function useEscapeLayer(open: Ref<boolean>): void {
watch(open, (isOpen) => {
openLayers.value += isOpen ? 1 : -1;
});
onUnmounted(() => {
if (open.value) openLayers.value -= 1;
});
}
export function escapeOwnedByLayer(): boolean {
return openLayers.value > 0;
}
const unfinished = (t: ChatTurn) => t.state === "queued" || t.state === "running";
/** A turn of this conversation is waiting or running. */
export const isSending = computed(() => turns.value.some(unfinished));
/** The turns waiting behind the one running, oldest first. */
const queuedTurns = computed(() => {
return turns.value.filter(unfinished).slice(1);
});
export const queuedMessages = computed(() => queuedTurns.value.map((t) => t.text));
function fail(err: unknown, what: string): string {
if (err instanceof Unauthorized) unauthorized.value = true;
const reason = err instanceof Error ? err.message : String(err);
return `${what}: ${reason}`;
}
// The notifications shown in a conversation are those that arrived while it was
// the newest one: from its start until the next conversation began.
const sessionWindow = computed(() => {
const open = sessions.value.find((s) => s.session_id === currentSession.value);
if (!open) return null;
const later = sessions.value
.map((s) => s.created_at)
.filter((at) => at > open.created_at)
.sort();
return { from: open.created_at, to: later[0] };
});
const askedHere = computed(() => new Set(turns.value.flatMap((t) => t.approvals.map((a) => a.request_id))));
/** The transcript: each turn's message and reply, with the run cards that arrived meanwhile. */
export const messages = computed<ChatMessage[]>(() => {
const rows: (ChatMessage & { at: string })[] = [];
const waiting = new Set(queuedTurns.value.map((t) => t.id));
for (const turn of turns.value) {
// A message waiting behind another turn shows in the queue above the composer.
if (waiting.has(turn.id)) continue;
rows.push({ key: `${turn.id}:q`, at: turn.created_at, from: "web", text: turn.text, page: turn.page_label || turn.page, turn });
const outcomes = new Map(turn.actions.map((a) => [a.request_id, a]));
const failed = turn.state === "failed";
rows.push({
key: `${turn.id}:a`,
at: turn.created_at,
from: "assistant",
text: failed ? turn.error || "The turn failed." : turn.reply || (turn.state === "cancelled" ? "Stopped before replying." : ""),
tool_calls: [
...turn.tool_calls,
...turn.navigate.map((n) => ({ path: n.path, label: n.label, text_offset: Array.from(turn.reply).length })),
],
approvals: turn.approvals.map((a) => ({ ...a, outcome: outcomes.get(a.request_id) })),
reasoning: turn.reasoning,
live: unfinished(turn),
error: failed,
turn,
});
}
const window = sessionWindow.value;
if (window) {
for (const notice of notices.value) {
if (notice.created_at < window.from || (window.to && notice.created_at >= window.to)) continue;
if (notice.request_id && askedHere.value.has(notice.request_id)) continue;
rows.push({ key: `n${notice.id}`, at: notice.created_at, from: "notice", text: notice.title, notice });
}
}
// Stable: a turn's two rows keep their order.
return rows.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));
});
// Bumped on every conversation switch: a stream for an earlier conversation is
// detached and must not write into the one now open.
let sessionEpoch = 0;
let following: AbortController | null = null;
async function refreshSessions(): Promise<void> {
const data = await chatSessions();
sessions.value = data.sessions;
activeModel.value = data.active_model;
modelError.value = data.model_error ?? "";
if (!currentSession.value && data.sessions[0]) await selectSession(data.sessions[0].session_id);
}
export async function selectSession(id: string): Promise<void> {
if (!id) return;
sessionEpoch++;
following?.abort();
following = null;
currentSession.value = id;
turns.value = [];
isLoadingSession.value = true;
sessionError.value = "";
const epoch = sessionEpoch;
try {
const loaded = await chatTurns(id);
if (epoch !== sessionEpoch) return;
turns.value = loaded;
follow();
} catch (err) {
if (epoch === sessionEpoch) sessionError.value = fail(err, "Couldn't load the conversation");
} finally {
if (epoch === sessionEpoch) isLoadingSession.value = false;
}
}
/** Re-reads the open conversation, so actions settled after a turn ended show. */
export async function reloadTranscript(): Promise<void> {
const id = currentSession.value;
if (!id || isSending.value) return;
const epoch = sessionEpoch;
try {
const loaded = await chatTurns(id);
if (epoch === sessionEpoch && !isSending.value) turns.value = loaded;
} catch {
// The next composer event or reopening the conversation reads it again.
}
}
function replaceTurn(next: ChatTurn): void {
turns.value = turns.value.map((t) => (t.id === next.id ? next : t));
}
/**
* Follows the conversation's unfinished turns one at a time, oldest first,
* replaying each from its first event so a reload shows it whole. A dropped
* stream reconnects from the last event seen.
*/
function follow(): void {
if (following) return;
const ctrl = new AbortController();
following = ctrl;
const epoch = sessionEpoch;
void (async () => {
let backoff = 1000;
try {
for (;;) {
const next = turns.value.find(unfinished);
if (!next || ctrl.signal.aborted || epoch !== sessionEpoch) return;
try {
await followTurn(next, ctrl.signal);
backoff = 1000;
} catch (err) {
if (ctrl.signal.aborted) return;
if (err instanceof Unauthorized) {
unauthorized.value = true;
return;
}
await new Promise((resolve) => setTimeout(resolve, backoff));
backoff = Math.min(backoff * 2, 30000);
}
}
} finally {
if (following === ctrl) following = null;
if (epoch === sessionEpoch) statusText.value = "Ready";
void refreshSessions().catch(() => undefined);
}
})();
}
async function followTurn(start: ChatTurn, signal: AbortSignal): Promise<void> {
let turn: ChatTurn = { ...start, reply: "", reasoning: "", tool_calls: [], approvals: [], actions: [], navigate: [] };
let seq = 0;
// A turn read while queued may have started since.
let ended = false;
for await (const event of chatTurnEvents(start.id, seq, signal)) {
seq = event.seq;
switch (event.type) {
case "delta":
turn = { ...turn, state: "running", reply: turn.reply + event.text };
break;
case "reasoning":
turn = { ...turn, state: "running", reasoning: (turn.reasoning ?? "") + event.text };
break;
case "tool": {
const { seq: _seq, type: _type, ...tool } = event;
turn = { ...turn, state: "running", tool_calls: [...turn.tool_calls, tool] };
break;
}
case "navigate":
turn = { ...turn, navigate: [...turn.navigate, { path: event.path, label: event.label }] };
break;
case "approval": {
const { seq: _seq, type: _type, ...approval } = event;
turn = { ...turn, approvals: [...turn.approvals, approval] };
void loadApprovals();
break;
}
case "action": {
const { seq: _seq, type: _type, ...done } = event;
turn = { ...turn, actions: [...turn.actions, done] };
break;
}
case "done":
case "error":
case "cancelled":
ended = true;
break;
}
replaceTurn(turn);
statusText.value = "Thinking…";
}
if (!ended && !signal.aborted) {
// The stream closed before the turn ended: read where it stands and follow again.
replaceTurn(await chatTurn(start.id, signal));
throw new Error("the stream ended early");
}
replaceTurn(await chatTurn(start.id, signal));
}
/** Whether a page's context goes with the next message: the route the operator is on. */
function currentPage(): string {
return router.currentRoute.value.fullPath.split("#")[0] || "/";
}
// The page whose tag the operator removed. Navigating elsewhere shows the tag
// again, so the dismissal never outlives the page it was made on.
const clearedPage = ref("");
watch(currentPage, () => {
clearedPage.value = "";
});
/** What the next message is about, named for the tag above the composer. */
export const pageTag = computed(() => {
const route = router.currentRoute.value;
const page = currentPage();
if (page === clearedPage.value || route.name === "composer") return null;
const id = typeof route.params.id === "string" ? route.params.id : "";
const named = typeof route.meta.label === "string" ? route.meta.label : page;
return { page, label: id ? `${named} ${id.length > 12 ? id.slice(0, 8) : id}` : named };
});
export function clearPageTag(): void {
clearedPage.value = currentPage();
}
async function ensureSession(): Promise<string> {
if (currentSession.value) return currentSession.value;
const created = await createChatSession();
sessions.value = [created, ...sessions.value];
sessionEpoch++;
currentSession.value = created.session_id;
turns.value = [];
return created.session_id;
}
/**
* Sends the composer's text, or the given text, as a turn. The server stores it
* before answering; one sent while a turn runs waits behind it there.
*/
export async function sendMessage(opts?: { textOverride?: string }): Promise<void> {
const typed = opts?.textOverride ?? composerText.value;
const text = typed.trim();
if (!text) return;
closeCommandMenu();
if (text.startsWith("/") && (await runCommand(text))) {
if (opts?.textOverride === undefined) composerText.value = "";
return;
}
sessionError.value = "";
try {
const session = await ensureSession();
const tag = pageTag.value;
const turn = await sendChatTurn(session, text, tag ? { page: tag.page, page_label: tag.label } : undefined);
if (session !== currentSession.value) return;
if (opts?.textOverride === undefined) drafts.value = { ...drafts.value, [session]: "" };
turns.value = [...turns.value, turn];
dockExpanded.value = true;
statusText.value = "Thinking…";
follow();
} catch (err) {
sessionError.value = fail(err, "Couldn't send the message");
}
}
/** Runs a palette command; false when the text isn't one, so it goes as a message. */
async function runCommand(text: string): Promise<boolean> {
const [command, ...rest] = text.split(/\s+/);
const arg = rest.join(" ").trim();
switch (command) {
case "/new":
await newChat();
return true;
case "/rename":
if (arg) await renameSession(arg);
return true;
case "/retry":
await retryLast();
return true;
case "/stop":
stopTurn();
return true;
case "/delete":
await deleteSession();
return true;
}
return false;
}
export async function newChat(): Promise<void> {
sessionError.value = "";
try {
const created = await createChatSession();
sessions.value = [created, ...sessions.value];
await selectSession(created.session_id);
} catch (err) {
sessionError.value = fail(err, "Couldn't start a conversation");
}
}
export async function renameSession(title: string): Promise<void> {
const id = currentSession.value;
if (!id) return;
try {
const renamed = await renameChatSession(id, title);
sessions.value = sessions.value.map((s) => (s.session_id === id ? renamed : s));
} catch (err) {
sessionError.value = fail(err, "Couldn't rename the conversation");
}
}
export async function deleteSession(): Promise<void> {
const id = currentSession.value;
if (!id) return;
try {
await deleteChatSession(id);
sessions.value = sessions.value.filter((s) => s.session_id !== id);
currentSession.value = "";
turns.value = [];
if (sessions.value[0]) await selectSession(sessions.value[0].session_id);
} catch (err) {
sessionError.value = fail(err, "Couldn't delete the conversation");
}
}
/** Sends the last message of the conversation again, as a new turn. */
export async function retryLast(turn?: ChatTurn): Promise<void> {
const last = turn ?? turns.value.at(-1);
if (last) await sendMessage({ textOverride: last.text });
}
/** Stops the running turn, or the next queued one when none runs. */
export function stopTurn(): void {
const target = turns.value.find((t) => t.state === "running") ?? turns.value.find(unfinished);
if (!target) return;
statusText.value = "Stopping…";
void cancelChatTurn(target.id)
.then((t) => replaceTurn({ ...target, state: t.state }))
.catch((err) => {
sessionError.value = fail(err, "Couldn't stop the turn");
});
}
export function removeQueued(index: number): void {
const turn = queuedTurns.value[index];
if (!turn) return;
void cancelChatTurn(turn.id)
.then((t) => replaceTurn({ ...turn, state: t.state }))
.catch((err) => {
sessionError.value = fail(err, "Couldn't remove the queued message");
});
}
/** Moves a queued message back into the composer, after anything already typed. */
export function editQueued(index: number): void {
const turn = queuedTurns.value[index];
if (!turn) return;
removeQueued(index);
composerText.value = composerText.value.trim() ? `${composerText.value}\n${turn.text}` : turn.text;
}
let lastInput = { value: "", caret: 0 };
/** Opens the palette for the command the caret sits in, or closes it. */
export function syncCommandMenu(value: string, caret: number): void {
lastInput = { value, caret };
const found = detectTrigger(lastInput.value, lastInput.caret);
const matches = found?.trigger === "/" ? commandCompletions(commandSpecs.value, found.query) : [];
if (!found || !matches.length) {
isCommandMenuOpen.value = false;
commandMatches.value = [];
return;
}
if (!isCommandMenuOpen.value) commandSelection.value = 0;
menuTrigger.value = found.trigger;
commandMatches.value = matches;
commandSelection.value = Math.min(commandSelection.value, Math.max(matches.length - 1, 0));
isCommandMenuOpen.value = true;
}
export function closeCommandMenu(): void {
isCommandMenuOpen.value = false;
}
export function moveCommandSelection(delta: number): void {
const length = commandMatches.value.length;
if (!length) return;
commandSelection.value = (commandSelection.value + delta + length) % length;
}
let approvalRead = 0;
export async function loadApprovals(): Promise<void> {
const read = ++approvalRead;
try {
const pending = await pendingApprovals();
if (read !== approvalRead) return;
approvals.value = pending;
approvalReadFailed.value = false;
} catch (err) {
if (read !== approvalRead) return;
if (err instanceof Unauthorized) unauthorized.value = true;
approvalReadFailed.value = true;
}
}
/** Answers an approval request. A reply in the conversation never does. */
export async function answer(id: string, approved: boolean): Promise<void> {
await answerApproval(id, approved);
++approvalRead;
approvals.value = approvals.value.filter((a) => a.id !== id);
await loadApprovals();
}
let noticeStream: AbortController | null = null;
const noticeCursor = () => notices.value.at(-1)?.seq ?? 0;
async function catchUp(through?: number): Promise<void> {
do {
const more = await messagesAfter(noticeCursor(), noticeStream?.signal);
if (more.length === 0) break;
notices.value = [...notices.value, ...more];
} while (through === undefined || noticeCursor() < through);
await loadApprovals();
await reloadTranscript();
}
// Notifications and approval requests from runs, followed for as long as the
// chat is mounted. The stream sends positions, not messages; the messages
// after the last one held are read on each.
async function followNotices(ctrl: AbortController): Promise<void> {
try {
notices.value = await latestMessages(ctrl.signal);
noticeError.value = "";
} catch (err) {
if (ctrl.signal.aborted) return;
noticeError.value = fail(err, "Couldn't load notifications");
}
let backoff = 1000;
while (!ctrl.signal.aborted) {
try {
for await (const seq of composerStream(ctrl.signal, catchUp)) {
backoff = 1000;
if (seq > noticeCursor()) await catchUp(seq);
}
} catch (err) {
if (ctrl.signal.aborted) return;
if (err instanceof Unauthorized) {
unauthorized.value = true;
return;
}
}
await new Promise((resolve) => setTimeout(resolve, backoff));
backoff = Math.min(backoff * 2, 30000);
}
}
let mounts = 0;
/**
* Loads the conversations and follows run notifications for as long as a chat
* surface is mounted. The dock and the composer page share one state, so the
* first mount starts it and the last unmount stops it.
*/
export function useChat(): void {
onMounted(() => {
if (mounts++ > 0) return;
const reopen = currentSession.value;
refreshSessions()
.then(() => (reopen ? selectSession(reopen) : undefined))
.catch((err) => {
sessionError.value = fail(err, "Couldn't load conversations");
});
void loadApprovals();
noticeStream = new AbortController();
void followNotices(noticeStream);
});
onUnmounted(() => {
if (--mounts > 0) return;
noticeStream?.abort();
noticeStream = null;
following?.abort();
following = null;
});
}
/** Approval requests waiting for an answer that the open transcript doesn't show. */
export const otherApprovals = computed(() => {
const shown = new Set(
messages.value.flatMap((m) => [...(m.approvals ?? []).map((a) => a.request_id), m.notice?.request_id ?? ""]),
);
return approvals.value.filter((a) => !shown.has(a.id));
});
// A turn id is a run id to judgement and approvals: a card that names one
// links to the conversation it came from, or else to the run.
const origins = new Map<string, Promise<string | null>>();
/** The conversation a run id belongs to, or null when it is a workflow run. */
export function conversationOf(runID: string): Promise<string | null> {
let found = origins.get(runID);
if (!found) {
found = chatTurn(runID).then(
(t) => t.session_id,
() => null,
);
origins.set(runID, found);
}
return found;
}
+40
View File
@@ -0,0 +1,40 @@
/**
* The suggested prompts shown beside the chat composer, keyed off the page
* the operator is on: the route's name, as the page tag reads it.
*
* Prompts are questions an operator would actually ask on that page, not
* demonstrations of the feature.
*/
/** The route as the page tag reads it; only these fields are consulted. */
export interface SuggestionRoute {
name?: unknown;
params?: Record<string, unknown>;
}
/** The prompts for a route; a run page names the run it is open on. */
export function suggestionsForRoute(route: SuggestionRoute): string[] {
const name = typeof route.name === "string" ? route.name : "";
switch (name) {
case "run":
return ["What did this run do?", "Why did this run end the way it did?", "Which actions did this run propose?"];
case "runs":
return ["Which runs failed recently?", "Summarise recent runs", "Which approvals are waiting on me?"];
case "events":
case "unmatched":
return ["Which events arrived today?", "Why didn't my last event start a workflow?", "Which sources are sending events?"];
case "classes":
case "class":
return ["Which actions run without approval?", "Which classes lost autonomy recently?", "What is waiting for my approval?"];
case "extensions":
case "credentials":
case "sources":
case "triggers":
case "settings":
case "controls":
case "people":
return ["Which model is Archie using right now?", "How do I connect a new source?", "Which extensions are running?"];
default:
return ["Summarise recent runs", "Which approvals are waiting on me?", "What needs my attention?"];
}
}
+44
View File
@@ -0,0 +1,44 @@
import { computed, ref, watch } from "vue";
import { isLoadingSession, messages, type ChatMessage } from "./state";
/**
* Counts the replies the operator has not seen. A reply is seen once the
* conversation is open and scrolled to its end; one that lands before that,
* such as a run's notification while the dock is collapsed or the reader is
* scrolled up, adds to the count until then.
*
* It counts finished replies and run cards by position.
*/
const dockOpen = ref(false);
const atEnd = ref(false);
const seen = ref(0);
function isReply(message: ChatMessage): boolean {
return message.from !== "web" && !message.live;
}
const total = computed(() => messages.value.filter(isReply).length);
const viewing = computed(() => dockOpen.value && atEnd.value);
export const unseenCount = computed(() => Math.max(0, total.value - seen.value));
// Opening or switching a conversation loads it, which is not news; a reload
// that drops a message must also lower the mark so the next reply still counts.
watch(
[total, viewing, isLoadingSession],
([count, watching, loading], [, , wasLoading]) => {
if (watching || loading || wasLoading || count < seen.value) seen.value = count;
},
{ immediate: true },
);
/** The dock reports whether the conversation is open above the composer. */
export function setDockOpen(open: boolean): void {
dockOpen.value = open;
}
/** The scroller's jump button reports whether the reader is at the end. */
export function setAtEnd(end: boolean): void {
atEnd.value = end;
}
+14 -14
View File
@@ -4,19 +4,19 @@ export default createRouter({
history: createWebHistory(),
routes: [
{ path: "/", redirect: "/composer" },
{ path: "/composer", name: "composer", component: () => import("./ComposerView.vue") },
{ path: "/runs", name: "runs", component: () => import("./RunsView.vue") },
{ path: "/unmatched", name: "unmatched", component: () => import("./UnmatchedView.vue") },
{ path: "/classes", name: "classes", component: () => import("./ClassesView.vue") },
{ path: "/classes/:id", name: "class", component: () => import("./ClassView.vue"), props: true },
{ path: "/people", name: "people", component: () => import("./PeopleView.vue") },
{ path: "/controls", name: "controls", component: () => import("./ControlsView.vue") },
{ path: "/extensions", name: "extensions", component: () => import("./ExtensionsView.vue") },
{ path: "/sources", name: "sources", component: () => import("./SourcesView.vue") },
{ path: "/triggers", name: "triggers", component: () => import("./TriggersView.vue") },
{ path: "/events", name: "events", component: () => import("./EventsView.vue") },
{ path: "/credentials", name: "credentials", component: () => import("./CredentialsView.vue") },
{ path: "/settings", name: "settings", component: () => import("./SettingsView.vue") },
{ path: "/runs/:id", name: "run", component: () => import("./RunView.vue"), props: true },
{ path: "/composer", name: "composer", meta: { label: "Composer" }, component: () => import("./ComposerView.vue") },
{ path: "/runs", name: "runs", meta: { label: "Runs" }, component: () => import("./RunsView.vue") },
{ path: "/unmatched", name: "unmatched", meta: { label: "Unmatched" }, component: () => import("./UnmatchedView.vue") },
{ path: "/classes", name: "classes", meta: { label: "Classes" }, component: () => import("./ClassesView.vue") },
{ path: "/classes/:id", name: "class", meta: { label: "Class" }, component: () => import("./ClassView.vue"), props: true },
{ path: "/people", name: "people", meta: { label: "People" }, component: () => import("./PeopleView.vue") },
{ path: "/controls", name: "controls", meta: { label: "Controls" }, component: () => import("./ControlsView.vue") },
{ path: "/extensions", name: "extensions", meta: { label: "Extensions" }, component: () => import("./ExtensionsView.vue") },
{ path: "/sources", name: "sources", meta: { label: "Sources" }, component: () => import("./SourcesView.vue") },
{ path: "/triggers", name: "triggers", meta: { label: "Triggers" }, component: () => import("./TriggersView.vue") },
{ path: "/events", name: "events", meta: { label: "Events" }, component: () => import("./EventsView.vue") },
{ path: "/credentials", name: "credentials", meta: { label: "Credentials" }, component: () => import("./CredentialsView.vue") },
{ path: "/settings", name: "settings", meta: { label: "Settings" }, component: () => import("./SettingsView.vue") },
{ path: "/runs/:id", name: "run", meta: { label: "Run" }, component: () => import("./RunView.vue"), props: true },
],
});