feat(webui): port the dashboard (Phases 3-5)

Every page from the deleted Preact dashboard, rebuilt in Vue 3 + shadcn-vue.
The navigation restructure landed earlier on this branch; this is the surfaces
behind it, and the two are now one app.

Dashboard, Tasks (list and detail), Configuration split six ways, Logs,
Inspector, Mappings, Bindings, Workflows, Skills, Curators, Channels, chat.

Components, not files: docs/prds/dashboard-port-brief.md requires one
component, one job, one file, with shared state in a module beside it. So a
page file composes and holds nothing, and a shape repeated across panes becomes
its own component (LogRow, PageHeader, PanelLoading, WorkflowBar).

Behaviour that had to survive, because each was a fix:

- Live activity's detail is clamped to one line with the payload on the title.
  Unclamped, one row made the dashboard 7,481px tall.
- Each health card takes its own height. Equalising left a mostly-empty box
  taking a quarter of the first screen once setup was done.
- Tasks: `tab`/`attempt` live in the query string and are written with
  router.replace, so a tab click adds no history entry and does not remount.
  The list's deep-link reveal honours prefers-reduced-motion.
- LOG_LEVELS is a wire contract (the server matches that CSV server-side), used
  unchanged by both log panes.
- The chat panel's Phase 5 list: a FAB that is the only toggle, a morph whose
  scale, radius and position interpolate together, no scrim, no close button,
  Escape returning focus to the launcher, Stop only while streaming.
- Unconfigured is not broken. A 501 on /api/version or the log stream renders
  what is true ("Not configured on this deployment") rather than blank, and a
  read-only Configuration says so instead of offering controls that cannot work.

Three things the port decided rather than carried:

- Button gains an `attention` variant and Badge the five status tones, in the
  project's own cva. The pill's dot did not come across: the Badge's shape is
  the affordance, and the same tone now covers a trend indicator.
- The icon module is not ported. Its name-to-glyph lookup is the pattern
  shadcn-vue's rules call out as wrong, so icons come from @lucide/vue at the
  call site. The five bespoke glyphs have no consumer yet and become components
  if a page draws them.
- The theme control left the topbar for /system/appearance, per the approved
  navigation design. ThemeToggle.vue and Placeholder.vue are deleted rather
  than orphaned: every route now resolves to a real page.

Also fixes the bundle freshness check failing on the first build after every
change. ui/dist is committed, so nothing ignores it and Tailwind's content
detection scanned it, making each build an input to the next.
This commit is contained in:
sam committed 2026-09-20 20:04:55 +10:00
1 parent 5fe25045d1
commit b9daa01b4b
276 files changed
+12888 -563

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
<script setup lang="ts">
import ChatSessionList from "./ChatSessionList.vue";
import ChatSettings from "./ChatSettings.vue";
/**
* One row for everything that is not the conversation: which conversation is
* open, and the controls that are consulted rather than used constantly.
*/
</script>
<template>
<div class="flex items-center gap-2 border-b px-3 py-2">
<ChatSessionList />
<ChatSettings />
</div>
</template>
+43
View File
@@ -0,0 +1,43 @@
<script setup lang="ts">
import { cn } from "@/lib/utils";
import ChatMarkdown from "./ChatMarkdown.vue";
import ChatToolCall from "./ChatToolCall.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.
*/
withDefaults(
defineProps<{
text: string;
tools?: ToolCall[];
assistant?: boolean;
/** The turn is still arriving: a tool call with no outcome is running. */
streaming?: boolean;
}>(),
{ tools: () => [], assistant: false, streaming: false },
);
</script>
<template>
<div class="flex" :class="assistant ? 'justify-start' : 'justify-end'">
<div
:class="
cn(
'max-w-[min(78ch,86%)] rounded-[0.85rem] px-4 py-3 leading-normal [overflow-wrap:anywhere]',
assistant ? 'bg-muted' : 'bg-primary/15',
)
"
>
<div v-if="assistant && tools.length" class="mb-2 grid gap-0.5 text-xs">
<ChatToolCall v-for="(tool, i) in tools" :key="i" :tool="tool" :streaming="streaming" />
</div>
<ChatMarkdown v-if="assistant" :text="text" />
<div v-else class="whitespace-pre-wrap">{{ text }}</div>
<slot />
</div>
</div>
</template>
+150
View File
@@ -0,0 +1,150 @@
<script setup lang="ts">
import { nextTick, ref, watch } from "vue";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { applyCommand, isExactCommand } from "./commands";
import ChatSlashPalette from "./ChatSlashPalette.vue";
import {
closeCommandMenu,
commandMatches,
commandSelection,
commandSpecs,
composerText,
isCommandMenuOpen,
isSending,
moveCommandSelection,
sendMessage,
stopTurn,
syncCommandMenu,
} from "./state";
/**
* The composer: the text, the palette that completes a slash command, and the
* two actions. It stays writeable and focused while a turn is in flight --
* stopping is not the only thing an operator may want to do next -- so 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: the field's own chrome would draw a second box inside
* the first. `bg-transparent!` beats the field's dark fill, which the dark
* variant would otherwise re-apply over the shell. It grows with what is typed
* and stops at `max-h-40`, so a long draft scrolls rather than eating the
* transcript above it.
*/
const props = defineProps<{ open: 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 spec = commandMatches.value[index];
const input = field.value?.$el;
if (!spec || !input) return;
// Completing the command replaces the token the caret sits in, which is
// decided by the same rule that found the matches.
const { text, cursor } = applyCommand(input.value, input.selectionStart ?? input.value.length, spec.command);
composerText.value = text;
closeCommandMenu();
void nextTick(() => {
input.focus();
input.setSelectionRange(cursor, cursor);
});
}
function onKeydown(event: KeyboardEvent): void {
const plain = !event.shiftKey && !event.ctrlKey && !event.metaKey;
if (isCommandMenuOpen.value && commandMatches.value.length) {
// 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 && 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 (event.key === "Enter" && plain) {
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="border-t p-3">
<div class="relative flex items-end gap-2 rounded-xl border border-border-strong bg-muted px-3 py-2.5">
<Textarea
ref="field"
:model-value="composerText"
rows="3"
placeholder="Message Archie, or type / for commands"
aria-label="Message Archie"
class="max-h-40 min-h-11 flex-1 resize-none border-0 bg-transparent! px-0 py-1 text-sm focus-visible:ring-0"
@input="onInput"
@keydown="onKeydown"
/>
<ChatSlashPalette
v-if="isCommandMenuOpen && commandMatches.length"
:matches="commandMatches"
:selection="commandSelection"
@choose="choose"
/>
<div class="flex flex-none items-center gap-2">
<!-- 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" :disabled="isSending || !composerText.trim()" @click="sendMessage()">Send</Button>
</div>
</div>
</div>
</template>
+35
View File
@@ -0,0 +1,35 @@
<script setup lang="ts">
/**
* What the panel opens on before there is a conversation: an invitation, and
* three prompts that fill the composer. The text is handed up rather than
* typed into the composer here, because the composer owns its own focus.
*/
const emit = defineEmits<{ prompt: [text: string] }>();
// Prompts an operator might actually ask, rather than demonstrations of the
// feature.
const PROMPTS = ["Summarise active tasks", "Show running agents", "Check system status"];
</script>
<template>
<div class="w-full self-center justify-self-center py-6 text-center">
<span
aria-hidden="true"
class="mx-auto mb-3 grid size-9 place-items-center rounded-xl border border-border-strong font-bold text-primary"
>A</span
>
<h2 class="text-lg font-semibold tracking-[-0.02em]">What are we working on?</h2>
<p class="mt-2 mb-4 text-sm text-fg-muted">Ask Archie anything, or start with one of these prompts.</p>
<div class="grid gap-2">
<button
v-for="prompt in PROMPTS"
:key="prompt"
type="button"
class="rounded-full border border-border bg-muted px-3 py-2 text-left text-sm text-fg-muted transition-colors hover:border-border-strong hover:text-foreground"
@click="emit('prompt', prompt)"
>
{{ prompt }}
</button>
</div>
</div>
</template>
+46
View File
@@ -0,0 +1,46 @@
<script setup lang="ts">
import { MessageCircle, X } from "@lucide/vue";
import { cn } from "@/lib/utils";
import { CHAT_PANEL_ID } from "./state";
/**
* The launcher: the one control that opens and closes the panel, which is why
* there is no close button inside it.
*
* Both glyphs are stacked and cross-faded, so the button keeps one size and the
* swap cannot reflow the dock. It stays visible while the panel is open -- and
* on a phone, where the panel becomes a sheet above it, that visibility is the
* only way out.
*/
defineProps<{ open: boolean }>();
const emit = defineEmits<{ toggle: [] }>();
// Stacked in one cell, so switching glyphs changes opacity and rotation rather
// than layout.
function glyph(visible: boolean): string {
return cn(
"col-start-1 row-start-1 grid place-items-center transition-[opacity,transform] duration-[140ms]",
visible ? "opacity-100" : "-rotate-45 scale-[0.7] opacity-0",
);
}
</script>
<template>
<button
type="button"
class="relative z-10 grid size-14 cursor-pointer place-items-center rounded-full bg-linear-to-br from-primary to-[var(--brand-alt)] text-primary-foreground shadow-[var(--shadow-md)] transition-[transform,box-shadow] duration-[140ms] hover:-translate-y-px hover:shadow-[0_12px_34px_var(--primary-soft)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:translate-y-0"
:aria-label="open ? 'Close chat' : 'Chat with Archie'"
:title="open ? 'Close chat' : 'Chat with Archie'"
:aria-expanded="open"
:aria-controls="CHAT_PANEL_ID"
@click="emit('toggle')"
>
<span aria-hidden="true" :class="glyph(!open)">
<MessageCircle :size="22" />
</span>
<span aria-hidden="true" :class="glyph(open)">
<X :size="22" />
</span>
</button>
</template>
+25
View File
@@ -0,0 +1,25 @@
<script setup lang="ts">
import { MessageCirclePlus } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { panelTitle } from "./session";
import { currentSession, newChat, sessions } from "./state";
/**
* The panel's head: which conversation is open, and the one action that always
* applies to it.
*
* There is no close button. The launcher stays visible while the panel is open
* and is the single control that opens and closes it, so a second one here
* would be a duplicate that can drift out of step.
*/
</script>
<template>
<div class="flex items-center justify-between gap-2 border-b px-4 py-3">
<strong class="truncate text-sm font-semibold">{{ panelTitle(sessions, currentSession) }}</strong>
<Button variant="ghost" size="icon-sm" class="flex-none" title="New chat" aria-label="New chat" @click="newChat">
<MessageCirclePlus />
</Button>
</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-primary 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>
+67
View File
@@ -0,0 +1,67 @@
<script setup lang="ts">
import { onUnmounted, ref, watch } from "vue";
import ChatFab from "./ChatFab.vue";
import ChatPanel from "./ChatPanel.vue";
import { escapeOwnedByLayer } from "./state";
/**
* Chat is a floating launcher and the panel it opens, not a route: the operator
* asks Archie about the page they are already on, so navigating must not close
* it and opening it must not replace the work that prompted the question.
*
* Deliberately not a modal: no scrim, no body scroll lock, no focus trap. The
* page stays readable, scrollable and clickable while the panel is open, which
* is what "ask about this page" requires.
*
* It hosts a single panel instance, so the session and its stream survive
* navigation rather than being rebuilt per page.
*
* This element is mounted outside the app shell: `.shell`'s backdrop-filter
* makes it a containing block for `position: fixed`, so a launcher nested
* inside it would anchor to the shell and ride off the bottom of a long page.
*/
const open = ref(false);
const fab = ref<{ $el: HTMLButtonElement } | null>(null);
function close(): void {
open.value = false;
// Focus goes back to the control that opened the panel; otherwise a keyboard
// user who dismisses it lands at the top of the document.
fab.value?.$el?.focus();
}
function toggle(): void {
if (open.value) close();
else open.value = true;
}
function onKeydown(event: KeyboardEvent): void {
// A focused control (the composer dismissing its palette, or the topbar
// search) already handled Escape via preventDefault; closing the panel too
// would make that menu impossible to dismiss on its own.
if (event.defaultPrevented || event.key !== "Escape") return;
// The same rule for a layer that owns Escape by being open rather than by
// holding focus: a popover portalled out of the panel listens on document
// too, and the panel registered its own handler first, so the flag is what
// keeps the innermost layer's dismissal from taking the panel with it.
if (escapeOwnedByLayer()) return;
close();
}
watch(open, (isOpen) => {
if (isOpen) document.addEventListener("keydown", onKeydown);
else document.removeEventListener("keydown", onKeydown);
});
onUnmounted(() => document.removeEventListener("keydown", onKeydown));
</script>
<template>
<div
class="fixed right-6 bottom-6 z-40 max-[720px]:right-4 max-[720px]:bottom-4"
>
<ChatPanel :open="open" />
<ChatFab ref="fab" :open="open" @toggle="toggle" />
</div>
</template>
+74
View File
@@ -0,0 +1,74 @@
<script setup lang="ts">
import { computed } from "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">
<pre
v-if="block.kind === 'pre'"
class="my-2 overflow-auto rounded-md border border-border bg-background/60 p-3"
><code class="font-mono text-[0.85em]">{{ block.code }}</code></pre>
<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-full border border-primary/45 bg-primary-soft px-2.5 py-1 text-xs font-semibold text-primary 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>
+88
View File
@@ -0,0 +1,88 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import ChatBar from "./ChatBar.vue";
import ChatComposer from "./ChatComposer.vue";
import ChatHeader from "./ChatHeader.vue";
import ChatSessionActions from "./ChatSessionActions.vue";
import ChatTranscript from "./ChatTranscript.vue";
import { CHAT_PANEL_ID, composerText, currentSession, useChat } from "./state";
/**
* The panel: the shape that grows out of the launcher, holding the
* conversation. It composes the head, the bar, the transcript and the composer,
* and owns nothing but the morph and the composer's focus.
*
* It stays mounted while closed, so the session and any turn in flight survive
* a navigation. `inert` is what keeps an invisible panel out of the tab order
* and out of the pointer's way.
*/
const props = defineProps<{ open: boolean }>();
useChat();
const composer = ref<InstanceType<typeof ChatComposer> | null>(null);
/**
* The panel's shape.
*
* Closed, it is collapsed to a small round shape sitting exactly over the
* button; open, it is the full panel beside it. Scaling from the bottom-right
* corner and translating by the launcher's own width is what makes the button
* appear to become the panel, rather than a panel merely fading in next to it:
* scale, border-radius and position interpolate together. The contents fade in
* separately, below, once the shape has arrived.
*
* On a phone the sheet rises from the launcher instead of opening beside it, so
* the closed shape travels down toward the button rather than sideways. Those
* two values (56px launcher, 0.75rem gap) are the dock's own geometry; the
* launcher and every offset here are built from them.
*/
const panelShape = computed(() =>
props.open
? "pointer-events-auto rounded-lg opacity-100 [transform:none] [transition:opacity_160ms_cubic-bezier(0.4,0,0.2,1),transform_260ms_cubic-bezier(0.22,1,0.36,1),border-radius_260ms_cubic-bezier(0.22,1,0.36,1)]"
: "pointer-events-none rounded-full opacity-0 [transform:translateX(calc(56px_+_0.75rem))_scale(0.16)] max-[720px]:[transform:translateY(calc(56px_+_0.75rem))_scale(0.16)] [transition:opacity_140ms_cubic-bezier(0.4,0,0.2,1),transform_200ms_cubic-bezier(0.4,0,1,1),border-radius_200ms_cubic-bezier(0.4,0,1,1)]",
);
// The contents follow the shape rather than stretching with it: they fade in
// once the panel is most of the way open, so the morph reads as a container
// opening instead of a page being scaled up.
const contentFade = computed(() =>
props.open
? "opacity-100 transition-opacity duration-[160ms] ease-linear delay-[120ms]"
: "opacity-0 transition-opacity duration-[120ms] ease-linear",
);
function usePrompt(text: string): void {
composerText.value = text;
composer.value?.focus();
}
</script>
<template>
<aside
:id="CHAT_PANEL_ID"
aria-label="Chat with Archie"
:aria-hidden="open ? undefined : 'true'"
class="pointer-events-none absolute bottom-0 right-[calc(56px_+_0.75rem)] h-[min(640px,calc(100vh_-_3rem))] w-[min(440px,calc(100vw_-_56px_-_0.75rem_-_3rem))] max-[720px]:fixed max-[720px]:bottom-[calc(1rem_+_56px_+_0.75rem)] max-[720px]:left-4 max-[720px]:right-4 max-[720px]:h-[min(72vh,calc(100vh_-_2rem_-_56px_-_0.75rem))] max-[720px]:w-auto"
>
<div
:class="
panelShape +
' h-full w-full overflow-hidden border bg-popover shadow-[var(--shadow-md)] origin-bottom-right'
"
:inert="open ? undefined : true"
>
<!-- The conversation takes the rest of the column: without `min-h-0` on
the transcript it sizes to its content instead, and the composer
floats above dead space. -->
<div :class="contentFade + ' flex h-full min-h-0 flex-col overflow-hidden'">
<ChatHeader />
<ChatBar />
<ChatSessionActions v-if="currentSession" />
<ChatTranscript @prompt="usePrompt" />
<ChatComposer ref="composer" :open="open" />
</div>
</div>
</aside>
</template>
+47
View File
@@ -0,0 +1,47 @@
<script setup lang="ts">
import { ref } from "vue";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { promptSessionCommand, runSessionCommand, useEscapeLayer } from "./state";
/**
* The commands that act on the conversation itself rather than on what is being
* said: retry the last turn, undo it, rename the conversation, branch it, or
* look at what compressing it would drop.
*
* Each one is the same command the server accepts from any other channel, so
* this is a set of buttons over the slash surface rather than a second way to
* do the work. The popover closes as the command goes, because its answer comes
* back into the transcript and the status line, not into the menu.
*/
const open = ref(false);
useEscapeLayer(open);
function run(command: string): void {
open.value = false;
void runSessionCommand(command);
}
function prompt(command: string, message: string): void {
open.value = false;
promptSessionCommand(command, message);
}
</script>
<template>
<div class="flex items-center border-b px-3 py-1.5 text-xs">
<Popover v-model:open="open">
<PopoverTrigger as-child>
<Button variant="ghost" size="xs" class="text-fg-muted">Session actions</Button>
</PopoverTrigger>
<PopoverContent align="start" class="flex w-[min(22rem,72vw)] flex-wrap gap-1.5">
<Button variant="outline" size="sm" @click="run('/retry')">Retry</Button>
<Button variant="outline" size="sm" @click="run('/undo')">Undo</Button>
<Button variant="outline" size="sm" @click="prompt('/title', 'Session title')">Rename</Button>
<Button variant="outline" size="sm" @click="prompt('/branch', 'Branch name (optional)')">Branch</Button>
<Button variant="outline" size="sm" @click="run('/compress --preview')">Preview compression</Button>
</PopoverContent>
</Popover>
</div>
</template>
+36
View File
@@ -0,0 +1,36 @@
<script setup lang="ts">
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { sessionTitle } from "./session";
import { currentSession, selectSession, sessions } from "./state";
/**
* Which conversation is open, and how to switch. A select rather than a list:
* the panel is small, and choosing between a handful of conversations is a
* control, not a place to be.
*
* reka-ui refuses an empty string as an item value -- it is how the component
* spells "nothing selected" -- and a session id is never empty, so the ids pass
* through unchanged.
*/
</script>
<template>
<div class="min-w-0 flex-1">
<Select
:model-value="currentSession"
:disabled="!sessions.length"
@update:model-value="selectSession(String($event))"
>
<SelectTrigger size="sm" class="w-full" aria-label="Conversation">
<SelectValue placeholder="No conversations yet" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem v-for="session in sessions" :key="session.session_id" :value="session.session_id">
{{ sessionTitle(session) }}
</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</div>
</template>
+108
View File
@@ -0,0 +1,108 @@
<script setup lang="ts">
import { Settings } from "@lucide/vue";
import { computed, ref } from "vue";
import { Button } from "@/components/ui/button";
import { Field, FieldLabel } from "@/components/ui/field";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import {
currentModels,
selectedModel,
selectedPersona,
selectedProvider,
selectorData,
setModel,
setPersona,
setProvider,
statusText,
useEscapeLayer,
} from "./state";
/**
* The chat's own settings, folded away: what the panel is doing right now, and
* the three selectors the server offers.
*
* A Popover rather than a disclosure menu: it closes on an outside pointerdown
* and on focus leaving it, which is what a control that opens over the
* transcript has to do. It portals out of the panel, so the panel's overflow
* cannot clip it.
*
* reka-ui refuses an empty string as an item value (that is how it spells
* "nothing selected") while the wire reads an absent value as "use the
* default", so the sentinel converts at this boundary and the state below keeps
* the empty string.
*/
const DEFAULT = "__default__";
const open = ref(false);
useEscapeLayer(open);
const personaValue = computed(() => selectedPersona.value || DEFAULT);
const providerValue = computed(() => selectedProvider.value || DEFAULT);
const modelValue = computed(() => selectedModel.value || DEFAULT);
function clear(value: unknown): string {
return value === DEFAULT ? "" : String(value ?? "");
}
</script>
<template>
<Popover v-model:open="open">
<PopoverTrigger as-child>
<Button variant="ghost" size="icon-sm" aria-label="Chat settings" title="Chat settings">
<Settings />
</Button>
</PopoverTrigger>
<PopoverContent align="end" class="grid w-64 gap-3">
<span class="text-xs text-fg-subtle">{{ statusText }}</span>
<Field class="gap-1">
<FieldLabel class="text-xs text-fg-muted">Personality</FieldLabel>
<Select :model-value="personaValue" @update:model-value="setPersona(clear($event))">
<SelectTrigger size="sm" class="w-full" aria-label="Personality">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem :value="DEFAULT">Default</SelectItem>
<SelectItem v-for="name in selectorData.personas || []" :key="name" :value="name">{{ name }}</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</Field>
<Field v-if="(selectorData.providers || []).length" class="gap-1">
<FieldLabel class="text-xs text-fg-muted">Provider</FieldLabel>
<Select :model-value="providerValue" @update:model-value="setProvider(clear($event))">
<SelectTrigger size="sm" class="w-full" aria-label="Provider">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem :value="DEFAULT">Default</SelectItem>
<SelectItem v-for="provider in selectorData.providers || []" :key="provider" :value="provider">
{{ provider }}
</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</Field>
<Field class="gap-1">
<FieldLabel class="text-xs text-fg-muted">Model</FieldLabel>
<Select :model-value="modelValue" @update:model-value="setModel(clear($event))">
<SelectTrigger size="sm" class="w-full" aria-label="Model">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem :value="DEFAULT">Default</SelectItem>
<SelectItem v-for="model in currentModels" :key="model" :value="model">{{ model }}</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</Field>
</PopoverContent>
</Popover>
</template>
+60
View File
@@ -0,0 +1,60 @@
<script setup lang="ts">
import { nextTick, ref, watch } from "vue";
import { commandScrollTop } from "./command-scroll";
import type { ChatCommandSpec } from "./state";
/**
* The slash palette: the commands the server accepts, floating above the
* composer. It is the only command surface -- there is no second list anywhere
* in the panel -- so the arrow keys and the pointer both land here.
*/
const props = defineProps<{ matches: ChatCommandSpec[]; selection: number }>();
const emit = defineEmits<{ choose: [index: number] }>();
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"
role="listbox"
aria-label="Commands"
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 shadow-md"
>
<button
v-for="(spec, index) in matches"
:key="spec.command"
type="button"
role="option"
:aria-selected="index === selection"
class="grid grid-cols-[minmax(8rem,14rem)_1fr] items-center gap-2.5 rounded-md border border-transparent px-2.5 py-2 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">{{ spec.command }}</code>
<span class="truncate">{{ spec.description || spec.usage || "" }}</span>
</button>
</div>
</template>
+46
View File
@@ -0,0 +1,46 @@
<script setup lang="ts">
import { Wrench } from "@lucide/vue";
import { computed } from "vue";
import { cn } from "@/lib/utils";
import ChatNavChip from "./ChatNavChip.vue";
import type { ChatToolCall } from "./state";
/**
* One tool call: the name, the parameters it was given, and what came back.
*
* A quiet log line rather than the point of the reply: it is evidence for the
* answer under it, so it is smaller and dimmer than the text it produced, and
* a failed call is the only thing here that raises its voice. An empty list
* renders nothing, 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. Which words stand in for silence depends on
// whether the turn is still going: "running…" is true mid-turn and a lie after.
const summary = computed(() => {
const reported = props.tool.summary || props.tool.Summary || props.tool.text || props.tool.err || props.tool.Err;
if (reported) return reported;
if (!props.streaming) return "done";
return failed.value ? "failed" : "running…";
});
</script>
<template>
<ChatNavChip v-if="tool.path" :path="tool.path" :label="tool.label" />
<div v-else class="flex items-baseline gap-1.5 [overflow-wrap:anywhere]">
<Wrench aria-hidden="true" class="size-3.5 shrink-0 self-center text-fg-subtle" />
<span class="font-semibold text-foreground">{{ name }}</span>
<code v-if="parameters" class="font-mono text-[0.95em] text-fg-subtle">{{ parameters }}</code>
<span :class="cn('text-fg-muted', failed && 'text-danger')">{{ summary }}</span>
</div>
</template>
+87
View File
@@ -0,0 +1,87 @@
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import ChatBubble from "./ChatBubble.vue";
import ChatEmptyState from "./ChatEmptyState.vue";
import { messages, sendMessage, streamingTurn, type ChatMessage } from "./state";
/**
* The conversation: the messages so far, the turn still arriving, and what the
* panel says before either exists. It scrolls itself to the newest line, so a
* streamed answer stays in view as it grows.
*/
const emit = defineEmits<{ prompt: [text: string] }>();
const scroller = ref<{ $el: HTMLElement } | null>(null);
function parts(message: ChatMessage) {
const from = message.from ?? message.From ?? "";
// Anything this browser's composer did not send is Archie's answer.
return {
text: message.text ?? message.Text ?? "",
tools: message.tool_calls || message.ToolCalls || [],
assistant: from !== "web",
};
}
const bubbles = computed(() => messages.value.map(parts));
// ScrollArea renders its own scrollable element, so the way to follow the tail
// is to reach into the component for it. Asking the wrapper instead would set
// scrollTop on a box that does not scroll.
function viewport(): HTMLElement | null {
return scroller.value?.$el?.querySelector<HTMLElement>('[data-slot="scroll-area-viewport"]') ?? null;
}
// Auto scroll to the bottom on a new message or a streamed token. flush: 'post'
// measures after the new content is in the DOM; measuring before that reads the
// height the transcript is about to replace.
watch(
[messages, streamingTurn],
() => {
const el = viewport();
if (el) el.scrollTop = el.scrollHeight;
},
{ flush: "post" },
);
</script>
<template>
<ScrollArea ref="scroller" class="min-h-0 flex-1">
<div class="grid content-start gap-4 p-4">
<ChatEmptyState v-if="!bubbles.length && !streamingTurn" @prompt="emit('prompt', $event)" />
<template v-else>
<ChatBubble
v-for="(bubble, i) in bubbles"
:key="i"
:text="bubble.text"
:tools="bubble.tools"
:assistant="bubble.assistant"
/>
<!-- The live turn is a bubble like any other, so what arrives is
rendered by the same rules as what was already there. -->
<ChatBubble
v-if="streamingTurn"
:text="streamingTurn.text || '…'"
:tools="streamingTurn.tools"
assistant
streaming
>
<Button
v-if="streamingTurn.isError && streamingTurn.turn"
variant="outline"
size="sm"
class="mt-2"
@click="sendMessage({ turn: streamingTurn.turn })"
>
Retry
</Button>
</ChatBubble>
</template>
</div>
</ScrollArea>
</template>
+17
View File
@@ -0,0 +1,17 @@
import { randomUUID } from "@/lib/uuid";
const CHANNEL_KEY = "archie.web.chat.channel";
/**
* The browser's chat identity. The server keys a conversation on the channel
* alone (the browser has no threading), so this is persisted: a reload rejoins
* the conversation instead of starting a second one beside it.
*/
export function channelID(): string {
let id = localStorage.getItem(CHANNEL_KEY);
if (!id) {
id = randomUUID();
localStorage.setItem(CHANNEL_KEY, id);
}
return id;
}
+52
View File
@@ -0,0 +1,52 @@
import type { ChatCommandSpec } from "./state";
/**
* The slash palette's arithmetic, kept out of the composer so it is decided in
* one place rather than reconstructed from DOM positions twice.
*/
/** The command token the caret sits in: a slash word at the start or after a space. */
const OPEN_TOKEN = /(?:^|\s)\/([^\s]*)$/;
const ANY_TOKEN = /(?:^|\s)\/[^\s]*$/;
/** How many matches the palette will show at once. */
const MAX_MATCHES = 8;
/**
* matchesFor returns the commands worth offering for the text before the
* caret, matched on the command and its description together so a word from
* either finds it.
*/
export function matchesFor(specs: ChatCommandSpec[], value: string, caret: number): ChatCommandSpec[] {
const match = value.slice(0, caret).match(OPEN_TOKEN);
if (!match) return [];
const query = match[1].toLowerCase();
return specs
.filter((spec) => `${spec.command} ${spec.description ?? ""}`.toLowerCase().includes(query))
.slice(0, MAX_MATCHES);
}
/**
* applyCommand replaces the token being completed with the chosen command and
* returns the cursor position just after it, ready for the next word.
*/
export function applyCommand(value: string, caret: number, command: string): { text: string; cursor: number } {
const before = value.slice(0, caret);
const after = value.slice(caret);
const start = before.search(ANY_TOKEN);
const tokenStart = start < 0 ? before.length : start + (before[start] === " " ? 1 : 0);
return {
text: `${before.slice(0, tokenStart)}${command} ${after}`,
cursor: tokenStart + command.length + 1,
};
}
/**
* 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);
}
+170
View File
@@ -0,0 +1,170 @@
/**
* 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 }
| { kind: "table"; head: ChatInline[][]; rows: ChatInline[][][] };
const INLINE =
/(!\[[^\]]*\]\((?:https?:\/\/[^\s)]+|data:image\/[^\s)]+|\/[^\s)]+)\)|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\((?:https?:\/\/[^\s)]+|\/[^\s)]+)\)|\*[^*]+\*|_[^_]+_)/g;
// 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({ kind: "text", text: 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({ kind: "text", text: 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;
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") });
code = null;
} else {
code = [];
}
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") });
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));
}
+16
View File
@@ -0,0 +1,16 @@
import type { ChatSession } from "./state";
export function sessionTitle(session: ChatSession): string {
return session.title || session.branch_name || `Conversation ${session.session_id.slice(0, 8)}`;
}
/**
* panelTitle names the launcher panel's header. The panel is small and the
* session switcher sits below it, so the header says which conversation is
* open rather than repeating the product name.
*/
export function panelTitle(sessions: ChatSession[], currentSession: string): string {
if (!currentSession) return "Archie";
const session = (sessions || []).find((item) => item.session_id === currentSession);
return session ? sessionTitle(session) : "Archie";
}
+462
View File
@@ -0,0 +1,462 @@
import { computed, onMounted, onUnmounted, ref, watch, type Ref } from "vue";
import { api } from "@/lib/api";
import { channelID } from "./channel";
import { matchesFor } from "./commands";
import { resolveTurn, retryChatTurn, type ChatTurn, type RetryOptions } from "./turn";
/**
* The chat panel's shared state.
*
* The launcher and the panel are separate components and the panel survives a
* navigation, so the conversation lives in a module rather than in either one.
* Everything the server answers with is read here; the components decide how it
* looks.
*/
/** One web conversation, as GET /api/chat/sessions lists it. */
export interface ChatSession {
session_id: string;
title?: string;
branch_name?: string;
}
/** One slash command the server will accept. */
export interface ChatCommandSpec {
command: string;
usage?: string;
description?: string;
}
/**
* A tool the assistant called. A live frame names the tool in `tool` and
* carries its outcome in `text`; a recorded turn uses `name` and `summary`.
*/
export interface ChatToolCall {
id?: string;
name?: string;
tool?: string;
parameters?: string;
summary?: string;
text?: string;
failed?: boolean;
/** A dashboard_navigate result: the page to route to, instead of a tool line. */
path?: string;
label?: string;
// The same view reaches the browser from more than one composition, so an
// outcome may arrive under either spelling. `err`/`Err` is also how a failed
// call reports itself: it is a result, not a missing one.
Name?: string;
Parameters?: string;
Summary?: string;
Err?: string;
err?: string;
}
/** One message in the transcript, from either side. */
export interface ChatMessage {
from?: string;
text?: string;
tool_calls?: ChatToolCall[];
// The same view reaches the browser from more than one composition, so both
// spellings are read rather than assuming one serialiser.
From?: string;
Text?: string;
ToolCalls?: ChatToolCall[];
message_id?: string;
MessageID?: string;
}
/** A turn in flight: what it is showing, and what to resend if it fails. */
export interface StreamingTurn {
text: string;
tools: ChatToolCall[];
isError: boolean;
turn?: ChatTurn;
isRetry: boolean;
}
/** Everything the selectors on the panel read, from one sessions read. */
export interface ChatSelectorData {
personas?: string[];
providers?: string[];
models?: string[];
models_by_provider?: Record<string, string[]>;
active_persona?: string;
active_personas?: Record<string, string>;
active_provider?: string;
active_model?: string;
commands?: Array<ChatCommandSpec | string>;
}
/**
* The id the launcher points its `aria-controls` at and the panel answers to.
* Both read it here so the pair cannot drift apart.
*/
export const CHAT_PANEL_ID = "chat-panel";
/**
* One `data: {...}` frame of the chat stream. The server always emits `text`,
* empty or not: the browser concatenates it, so a missing key would put the
* string "undefined" into the transcript on a turn whose reply is empty.
*/
interface ChatStreamFrame extends ChatToolCall {
type?: string;
text: string;
session_id?: string;
}
/** A turn that never settles must not hold the composer closed forever. */
const STREAM_TIMEOUT_MS = 120000;
export const sessions = ref<ChatSession[]>([]);
export const currentSession = ref("");
export const messages = ref<ChatMessage[]>([]);
export const composerText = ref("");
export const statusText = ref("Ready");
export const isSending = ref(false);
export const streamingTurn = ref<StreamingTurn | null>(null);
export const selectorData = ref<ChatSelectorData>({});
export const selectedPersona = ref("");
export const selectedProvider = ref("");
export const selectedModel = ref("");
export const commandSpecs = ref<ChatCommandSpec[]>([]);
export const commandMatches = ref<ChatCommandSpec[]>([]);
export const commandSelection = ref(0);
export const isCommandMenuOpen = ref(false);
export const currentModels = computed(() => {
const grouped = selectorData.value.models_by_provider || {};
const provider = selectedProvider.value;
return provider && grouped[provider] ? grouped[provider] : selectorData.value.models || [];
});
/**
* How many layers inside the panel currently own Escape -- an open popover, a
* select inside one.
*
* The panel's own Escape defers to them. Dismissing a menu must not also throw
* away the conversation the menu was opened over, and a layer that dismissed
* both would make the panel impossible to keep open while consulting it.
*/
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;
}
let activeController: AbortController | null = null;
// The send path holds a stream loop that outlives the click that started it; a
// module-level controller is what a Stop, or an unmount, aborts.
function abortActiveTurn(): void {
activeController?.abort();
}
export async function refreshSessions(): Promise<void> {
const data = await api.chatSessions<ChatSelectorData & { sessions?: ChatSession[] }>();
const sessionList = data.sessions || [];
sessions.value = sessionList;
selectorData.value = data;
selectedPersona.value = data.active_persona || "";
const providers = data.providers || [];
selectedProvider.value = data.active_provider || providers[0] || "";
selectedModel.value = data.active_model || "";
commandSpecs.value = (data.commands || []).map((item) =>
typeof item === "string" ? { command: item, usage: item, description: "" } : item,
);
if (!currentSession.value && sessionList[0]) {
// Vue's reactivity makes the assignment above readable here immediately, so
// the read that selects the first conversation needs no data threaded into
// it the way the Preact tree had to pass its own copy.
await selectSession(sessionList[0].session_id);
}
}
export async function selectSession(id: string): Promise<void> {
if (!id) return;
const data = selectorData.value;
currentSession.value = id;
messages.value = [];
streamingTurn.value = null;
selectedPersona.value = data.active_personas?.[id] || data.active_persona || "";
try {
// Resuming is the server's own command, so the transcript read below is of
// a conversation the server considers current rather than a stale one.
await api.chatMessage(channelID(), `/resume ${id}`);
const [msgs, turns] = await Promise.all([api.chatMessages<ChatMessage[]>(id), api.chatTurns<ChatTurnView[]>(id)]);
const byAssistantMessage = new Map<string, ChatTurnView>();
for (const turn of turns || []) {
const assistantID = turn.assistant_message_id || turn.AssistantMessageID;
if (assistantID) byAssistantMessage.set(assistantID, turn);
}
// Tool calls belong to the turn, not the message, so a reopened
// conversation gets its transcript back with the evidence in place.
messages.value = (msgs || []).map((message) => {
const messageID = message.message_id || message.MessageID;
const turn = messageID ? byAssistantMessage.get(messageID) : undefined;
return turn ? { ...message, tool_calls: turn.tool_calls || turn.ToolCalls || [] } : message;
});
} catch (err) {
statusText.value = (err as Error).message || "Could not load session messages";
}
}
/** One recorded turn, as GET /api/chat/sessions/{id}/turns returns it. */
interface ChatTurnView {
assistant_message_id?: string;
AssistantMessageID?: string;
tool_calls?: ChatToolCall[];
ToolCalls?: ChatToolCall[];
}
export async function runSessionCommand(command: string): Promise<void> {
if (!currentSession.value) return;
try {
statusText.value = "Working…";
const result = await api.chatMessage<{ session_id?: string; reply?: string }>(channelID(), command);
if (result.session_id) currentSession.value = result.session_id;
statusText.value = result.reply || "Session updated";
await refreshSessions();
if (result.session_id || currentSession.value) {
await selectSession(result.session_id || currentSession.value);
}
} catch (err) {
statusText.value = (err as Error).message || "Session action failed";
}
}
// Rename and branch take a value the server has no form for, so the browser's
// own prompt is the input: a modal built for two commands would be more UI than
// the two commands are worth.
export function promptSessionCommand(command: string, message: string): void {
const value = window.prompt(message);
if (value?.trim()) void runSessionCommand(`${command} ${value.trim()}`);
}
export function setPersona(name: string): void {
selectedPersona.value = name;
const session = currentSession.value;
if (!session || !name) return;
api
.chatPersona(session, name)
.then(() => {
const data = selectorData.value;
selectorData.value = {
...data,
active_personas: { ...(data.active_personas || {}), [session]: name },
};
statusText.value = `Personality: ${name}`;
})
.catch((err: Error) => {
statusText.value = err.message || "Failed to set personality";
});
}
export async function setProvider(provider: string): Promise<void> {
selectedProvider.value = provider;
if (!provider) return;
try {
const result = await api.chatMessage<{ reply?: string }>(channelID(), `/model --provider ${provider}`);
statusText.value = result.reply || "Provider updated";
await refreshSessions();
} catch (err) {
statusText.value = `Provider update failed: ${(err as Error).message || err}`;
}
}
export async function setModel(model: string): Promise<void> {
selectedModel.value = model;
if (!model) return;
try {
const result = await api.chatMessage<{ reply?: string }>(channelID(), `/model ${model}`);
statusText.value = result.reply || "Model updated";
await refreshSessions();
} catch (err) {
statusText.value = `Model update failed: ${(err as Error).message || err}`;
}
}
export function newChat(): void {
composerText.value = "/new";
void sendMessage({ textOverride: "/new" });
}
/** Opens the palette for the slash word the caret sits in, or closes it. */
export function syncCommandMenu(value: string, caret: number): void {
const matches = matchesFor(commandSpecs.value, value, caret);
if (matches.length) {
commandMatches.value = matches;
commandSelection.value = 0;
isCommandMenuOpen.value = true;
return;
}
isCommandMenuOpen.value = false;
commandMatches.value = [];
}
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;
}
/** The page the operator asked from, so an answer can be about what they saw. */
function currentPage(): string {
return location.pathname + location.search || "/";
}
export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
const explicitText = retryOpts?.textOverride;
const rawValue = explicitText !== undefined ? explicitText : composerText.value;
const { text, turn, isRetry } = resolveTurn(retryOpts, rawValue);
if (!text || isSending.value) return;
closeCommandMenu();
isSending.value = true;
statusText.value = isRetry ? "Retrying…" : "Thinking…";
if (!isRetry) {
messages.value = [...messages.value, { from: "web", text }];
composerText.value = "";
}
let activeTools: ChatToolCall[] = [];
streamingTurn.value = { text: "", tools: [], isError: false, turn, isRetry };
let streamedText = "";
let finished = false;
let timedOut = false;
let timeoutId: ReturnType<typeof setTimeout> | undefined;
try {
const controller = new AbortController();
activeController = controller;
timeoutId = setTimeout(() => {
timedOut = true;
controller.abort();
}, STREAM_TIMEOUT_MS);
const response = await api.chatStream(
{
channel_id: channelID(),
source_id: turn.sourceID,
text: turn.text,
page: currentPage(),
},
{ signal: controller.signal },
);
const body = response.body;
if (!body) throw new Error("the chat stream returned no body");
const reader = body.getReader();
const decoder = new TextDecoder();
let buffer = "";
// Drained to completion: the stream is read until the reader reports done,
// and a turn that ends without a `done` frame is a failed turn rather than
// a short one. Reading only some frames leaves the producer writing into a
// stream nobody collects.
for (;;) {
const { value, done } = await reader.read();
buffer += decoder.decode(value || new Uint8Array(), { stream: !done });
const frames = buffer.split("\n\n");
buffer = frames.pop() || "";
for (const frame of frames) {
const line = frame.split("\n").find((part) => part.startsWith("data: "));
if (!line) continue;
const event = JSON.parse(line.slice(6)) as ChatStreamFrame;
if (event.session_id) currentSession.value = event.session_id;
if (event.type === "delta") {
streamedText += event.text;
streamingTurn.value = streamingTurn.value ? { ...streamingTurn.value, text: streamedText } : null;
}
// A navigate result is appended to the same list as the tool calls: it
// is one more thing the turn did, and it renders as a chip rather than
// a tool line.
if (event.type === "tool" || event.type === "navigate") {
activeTools = [...activeTools, event];
streamingTurn.value = streamingTurn.value ? { ...streamingTurn.value, tools: activeTools } : null;
}
if (event.type === "done") {
finished = true;
if (!streamedText) streamedText = event.text || "";
}
if (event.type === "error") throw new Error(event.text);
}
if (done) break;
}
if (!finished) throw new Error("chat stream ended before completion");
messages.value = [...messages.value, { from: "assistant", text: streamedText, tool_calls: activeTools }];
streamingTurn.value = null;
statusText.value = "Ready";
await refreshSessions();
} catch (err) {
const failed = err as Error;
if (failed.name === "AbortError" && !timedOut) {
streamingTurn.value = { text: "Turn stopped.", tools: activeTools, isError: false, turn, isRetry };
statusText.value = "Stopped";
} else {
streamingTurn.value = {
text: `Unable to complete that turn: ${failed.message || failed}`,
tools: activeTools,
isError: true,
turn: turn ? retryChatTurn(turn) : undefined,
isRetry,
};
statusText.value = "Error — retry available";
}
} finally {
clearTimeout(timeoutId);
activeController = null;
isSending.value = false;
}
}
export function stopTurn(): void {
statusText.value = "Stopping…";
if (currentSession.value) {
void api.chatCancel(currentSession.value).catch(() => {});
}
abortActiveTurn();
}
/**
* Owns the first sessions read and the teardown of an in-flight turn for the
* panel's lifetime. The panel is mounted once beside the outlet and stays
* mounted while it is closed, so opening it is a prop change rather than a
* mount and the conversation survives a navigation.
*/
export function useChat(): void {
onMounted(() => {
refreshSessions().catch((err: Error) => {
statusText.value = err.message || "Chat unavailable";
});
});
onUnmounted(() => {
abortActiveTurn();
});
}
+42
View File
@@ -0,0 +1,42 @@
import { randomUUID } from "@/lib/uuid";
/**
* What a send puts on the wire: the text, and the source id the server keys
* the turn on so a retry of the same turn is recognisable as one.
*/
export interface ChatTurn {
text: string;
sourceID: string;
}
export function newChatTurn(text: string): ChatTurn {
return { text, sourceID: randomUUID() };
}
export function retryChatTurn(turn: ChatTurn): ChatTurn {
return { ...turn };
}
/** A retry descriptor as the transcript holds it, or nothing for a fresh send. */
export interface RetryOptions {
textOverride?: string;
turn?: ChatTurn;
}
// resolveTurn decides what to send: a real retry descriptor's original turn,
// or a fresh turn built from the composer text. `retry` is untrusted here --
// a DOM event handler bound as `el.onclick = sendMessage` (rather than
// `() => sendMessage()`) hands the click's MouseEvent to this function as
// `retry`, and a MouseEvent is truthy but has no `.turn`. Only an object
// carrying a `turn.text` string counts as a genuine retry; anything else
// (including no argument) falls back to the composer text instead of
// throwing on a missing property.
export function resolveTurn(
retry: RetryOptions | null | undefined,
composerValue: string,
): { text: string; turn: ChatTurn; isRetry: boolean } {
const isRetry = !!(retry && typeof retry === "object" && retry.turn && typeof retry.turn.text === "string");
const text = isRetry ? retry.turn!.text : composerValue.trim();
const turn = isRetry ? retryChatTurn(retry.turn!) : newChatTurn(text);
return { text, turn, isRetry };
}