refactor(ui/chat): remove chat features the server never sends

The dashboard talks only to the modules/chat API, which sends no slash
commands, model list, voice support, attachments or any question other
than an approval, so the UI built on those could never appear:

- the slash command menu, Retry, Undo, Branch and Preview compression in
  the More menu, and the /model, /update and /new handling
- the model picker, the update card and the api.update* calls
- voice recording and the task tags nothing ever added
- the questionnaire, picker and clarify cards, and the "Always this
  session" answer, so components/ui/questionnaire loses its last user
- channel.ts, command-scroll.ts and turn.ts, which nothing imported
- the old dock-storage migration and the second capitalised spelling of
  message and tool fields

Tasks are gone from the binary too, so chat links and prompts speak of
runs: the #N task-link step in the markdown renderer goes, since an agent
already links pages through dashboard_navigate.

state.ts keeps the shared state and actions; types.ts, stream.ts,
transcript.ts, escape.ts and dock-window.ts hold the types, the stream
reader, turn-to-message building, Escape layers and the dock's pointer
and keyboard handling. ChatDock.vue drops from 560 lines to 307.
This commit is contained in:
sam committed 2026-11-26 01:59:26 +11:00
1 parent 8c9c19efb0
commit eb7d852567
60 files changed
+988 -4532

No files matched your search

+19 -52
View File
@@ -3,74 +3,41 @@ import { ShieldQuestion } from "@lucide/vue";
import { ref } from "vue";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Item, ItemActions, ItemContent, ItemDescription, ItemMedia, ItemTitle } from "@/components/ui/item";
import { ReadError } from "@/components/ui/read-error";
import ChatQuestionnaire from "./ChatQuestionnaire.vue";
import { answerAsk, askError, askErrorID, type ChatAsk } from "./state";
import { errors } from "@/copy/errors";
import { describeError } from "@/lib/api";
import { answerAsk } from "./state";
import type { ChatAsk } from "./types";
const props = defineProps<{ ask: ChatAsk }>();
const reply = ref("");
// The last answer tried, so a failed send can be retried from the error.
const lastAnswer = ref("");
const error = ref("");
// The last answer tried, so a failed answer can be retried from the error.
let lastAnswer = false;
async function answer(value: string): Promise<boolean> {
lastAnswer.value = value;
return answerAsk(value, props.ask);
}
async function sendReply(): Promise<void> {
const text = reply.value.trim();
if (!text) return;
// The answer stays filled in until the server accepts it.
if (await answer(text)) reply.value = "";
}
function retry(): void {
if (lastAnswer.value) void answer(lastAnswer.value);
async function answer(approve: boolean): Promise<void> {
lastAnswer = approve;
try {
await answerAsk(props.ask, approve);
error.value = "";
} catch (err) {
error.value = describeError(err, errors.chat.ask.answer);
}
}
</script>
<template>
<ReadError v-if="askError && askErrorID === ask.id" :message="askError" retry-label="Retry answer" class="mt-2" @retry="retry" />
<ChatQuestionnaire v-if="ask.kind === 'questionnaire'" :ask="ask" :send="answer" />
<Item v-else-if="ask.kind === 'approval'" variant="outline" size="sm" class="mt-2" role="group" :aria-label="ask.prompt">
<ReadError v-if="error" :message="error" retry-label="Retry answer" class="mt-2" @retry="answer(lastAnswer)" />
<Item variant="outline" size="sm" class="mt-2" role="group" :aria-label="ask.prompt">
<ItemMedia variant="icon"><ShieldQuestion /></ItemMedia>
<ItemContent>
<ItemTitle>Allow {{ ask.prompt }}?</ItemTitle>
<ItemDescription v-if="ask.detail" class="font-mono text-caption break-all">{{ ask.detail }}</ItemDescription>
</ItemContent>
<ItemActions class="flex-wrap">
<Button size="sm" variant="outline" @click="answer('deny')">Deny</Button>
<Button v-if="ask.via !== 'approvals'" size="sm" variant="outline" @click="answer('always')">Always this session</Button>
<Button size="sm" @click="answer('approve')">Approve</Button>
<Button size="sm" variant="outline" @click="answer(false)">Deny</Button>
<Button size="sm" @click="answer(true)">Approve</Button>
</ItemActions>
</Item>
<div v-else class="mt-2 rounded-lg border border-border bg-card p-3 text-label" role="group" :aria-label="ask.prompt">
<template v-if="ask.kind === 'picker'">
<p class="font-medium">{{ ask.prompt }}</p>
<div class="mt-3 flex flex-wrap gap-2">
<Button v-for="choice in ask.choices" :key="choice.id" size="sm" variant="outline" @click="answer(choice.id)">
{{ choice.label }}
</Button>
</div>
</template>
<template v-else>
<p class="font-medium">{{ ask.prompt }}</p>
<div v-if="ask.choices?.length" class="mt-3 flex flex-wrap gap-2">
<Button v-for="choice in ask.choices" :key="choice.id" size="sm" variant="outline" @click="answer(choice.label)">
{{ choice.label }}
</Button>
</div>
<form class="mt-3 flex gap-2" @submit.prevent="sendReply">
<Input v-model="reply" class="flex-1" placeholder="Your answer" aria-label="Your answer" />
<Button type="submit" size="sm" :disabled="!reply.trim()">Send</Button>
</form>
</template>
</div>
</template>
-31
View File
@@ -1,31 +0,0 @@
<script setup lang="ts">
import { Paperclip } from "@lucide/vue";
import { mediaDetail, mediaLabel } from "./attachment";
import type { ChatMedia } from "./state";
/**
* One attachment a message carried, as the transcript shows it.
*
* The bytes are gone by design: they are turn-scoped and stripped before the
* record is stored, so this is a labelled chip rather than a preview. It
* links out only when the attachment itself carried a URL; a platform file id
* is deliberately never rendered, because it is a handle rather than an
* address and a chip that 404s is worse than no chip.
*/
defineProps<{ attachment: ChatMedia }>();
</script>
<template>
<component
:is="attachment.url ? 'a' : 'span'"
:href="attachment.url"
:target="attachment.url ? '_blank' : undefined"
:rel="attachment.url ? 'noopener noreferrer' : undefined"
:title="mediaDetail(attachment)"
class="inline-flex max-w-full items-center gap-1.5 rounded-md border border-border bg-muted px-2.5 py-1 text-caption font-medium text-fg-muted"
>
<Paperclip aria-hidden="true" class="size-3.5 shrink-0" />
<span class="truncate">{{ mediaLabel(attachment) }}</span>
</component>
</template>
+3 -2
View File
@@ -1,13 +1,14 @@
<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 { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import ChatSessionActions from "./ChatSessionActions.vue";
import ChatSessionList from "./ChatSessionList.vue";
import { sessionTitle } from "./session";
import { currentSession, newChat, sessions, useEscapeLayer } from "./state";
import { useEscapeLayer } from "./escape";
import { currentSession, newChat, sessions } from "./state";
/**
* One row for everything that is not the conversation: the drawer of
+4 -14
View File
@@ -1,17 +1,16 @@
<script setup lang="ts">
import { Alert, AlertDescription } from "@/components/ui/alert";
import { computed } from "vue";
import { Alert, AlertDescription } from "@/components/ui/alert";
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 ChatAttachment from "./ChatAttachment.vue";
import { Trace } from "@/components/ui/trace";
import ChatMarkdown from "./ChatMarkdown.vue";
import ChatThinking from "./ChatThinking.vue";
import ChatToolCall from "./ChatToolCall.vue";
import ChatToolGroup from "./ChatToolGroup.vue";
import type { ChatMedia, ChatToolCall as ToolCall } from "./state";
import type { ChatToolCall as ToolCall } from "./types";
/**
* One message, from either side of the conversation. There is no speaker
@@ -24,8 +23,6 @@ const props = withDefaults(
defineProps<{
text: string;
tools?: ToolCall[];
/** Attachments the message carried, which have no bytes left to render. */
media?: ChatMedia[];
assistant?: boolean;
/** The turn is still arriving: a tool call with no outcome is running. */
streaming?: boolean;
@@ -36,7 +33,7 @@ const props = withDefaults(
/** The text says why the turn failed rather than answering. */
error?: boolean;
}>(),
{ tools: () => [], media: () => [], assistant: false, streaming: false, reasoning: "", thinkingPending: false },
{ tools: () => [], assistant: false, streaming: false, reasoning: "", thinkingPending: false },
);
// The reply in the order it happened: text up to each call's offset, then the
@@ -73,13 +70,6 @@ const segments = computed(() => {
<MessageContent>
<Bubble :variant="assistant ? 'muted' : 'tinted'" class="max-w-[min(78ch,92%)]">
<BubbleContent class="[overflow-wrap:anywhere]">
<div v-if="media.length" class="mb-2 flex flex-wrap gap-1.5">
<ChatAttachment
v-for="(attachment, i) in media"
:key="i"
:attachment="attachment"
/>
</div>
<template v-if="assistant">
<ChatThinking
v-if="reasoning || thinkingPending"
-23
View File
@@ -1,23 +0,0 @@
<script setup lang="ts">
import { computed } from "vue";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { selectorData, setModel } from "./state";
defineProps<{ choose: "model" }>();
const options = computed(() => selectorData.value.models ?? []);
</script>
<template>
<div class="text-label">
<p class="text-label font-medium">Choose a model</p>
<p v-if="!options.length" class="mt-1 text-fg-muted">None configured.</p>
<Select v-else :model-value="selectorData.active_model" class="mt-2" @update:model-value="(v) => void setModel(String(v))">
<SelectTrigger class="w-full font-mono" aria-label="Model"><SelectValue placeholder="Choose a model" /></SelectTrigger>
<SelectContent>
<SelectItem v-for="option in options" :key="option" :value="option" class="font-mono">{{ option }}</SelectItem>
</SelectContent>
</Select>
</div>
</template>
+22 -153
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { Clock, Mic, Pencil, X } from "@lucide/vue";
import { Clock, Pencil, X } from "@lucide/vue";
import {
createTokenInputController,
TokenInput,
@@ -17,19 +17,16 @@ import {
TriggerMenuItem,
TriggerMenuList,
} from "@ui-sdk/vue/trigger-menu";
import { computed, nextTick, onMounted, ref, watch } from "vue";
import { nextTick, onMounted, watch } from "vue";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { errors } from "@/copy/errors";
import { api, describeError, type WorkflowVersion } from "@/lib/api";
import { api, type WorkflowVersion } from "@/lib/api";
import { cn } from "@/lib/utils";
import { useSessionStore } from "@/stores/session";
import ChatSuggestions from "./ChatSuggestions.vue";
import { serializePromptValue } from "./prompt-tokens";
import {
clearPageTag,
commandSpecs,
composerText,
editQueued,
isSending,
@@ -38,67 +35,19 @@ import {
placeholderHint,
queuedMessages,
removeQueued,
removeTaskTag,
selectorData,
sendMessage,
sendVoice,
stopTurn,
taskTags,
type TaskRef,
} from "./state";
const props = defineProps<{ open: boolean; flat?: boolean }>();
defineProps<{ flat?: boolean }>();
const session = useSessionStore();
const prompt = createTokenInputController();
const canRecord = computed(
() => !!selectorData.value.voice_available && typeof MediaRecorder !== "undefined" && !!navigator.mediaDevices?.getUserMedia,
);
const recording = ref(false);
const recordError = ref("");
let recorder: MediaRecorder | null = null;
async function toggleRecording(): Promise<void> {
if (recorder) {
recorder.stop();
return;
}
recordError.value = "";
let stream: MediaStream;
try {
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
} catch (err) {
recordError.value = errors.chat.composer.microphoneUnavailable(describeError(err, errors.common.unknown));
return;
}
const chunks: Blob[] = [];
recorder = new MediaRecorder(stream);
recorder.ondataavailable = (e) => chunks.push(e.data);
recorder.onstop = () => {
stream.getTracks().forEach((t) => t.stop());
const clip = new Blob(chunks, { type: recorder?.mimeType || "audio/webm" });
recorder = null;
recording.value = false;
if (clip.size) void sendVoice(clip);
};
recorder.start();
recording.value = true;
}
function focus(): void {
prompt.focus({ at: "end" });
}
defineExpose({ focus });
watch(
() => props.open,
(open) => {
if (open) void nextTick(focus);
},
);
// The composer takes focus back when a turn ends.
watch(isSending, (sending, wasSending) => {
if (wasSending && !sending) void nextTick(focus);
});
@@ -127,29 +76,12 @@ onMounted(() => {
watch(composerText, syncControllerFromText);
function onSubmit(): void {
if (!composerText.value.trim()) return;
void sendMessage();
function submit(): void {
if (composerText.value.trim()) void sendMessage();
}
type MenuEntry = TriggerMenuDataItem & { detail?: string };
async function searchTasks(query: string): Promise<MenuEntry[]> {
if (session.sections?.tasks === false) return [];
const list = await api.tasks<TaskRef[] | { tasks?: TaskRef[] }>();
const rows = Array.isArray(list) ? list : (list.tasks ?? []);
const q = query.trim().toLowerCase();
return rows
.filter((task) => `${task.id} ${task.title ?? ""}`.toLowerCase().includes(q))
.slice(0, 8)
.map((task) => ({
value: String(task.id),
label: `#${task.id}`,
keywords: task.title ? [task.title] : [],
detail: task.title ?? "",
}));
}
async function searchWorkflows(query: string): Promise<MenuEntry[]> {
const list = await api.workflowList();
const q = query.trim().toLowerCase();
@@ -164,48 +96,7 @@ async function searchWorkflows(query: string): Promise<MenuEntry[]> {
}));
}
function searchCommands(query: string): MenuEntry[] {
const q = query.trim().toLowerCase();
return commandSpecs.value
.filter((spec) => `${spec.command} ${spec.description ?? ""}`.toLowerCase().includes(q))
.slice(0, 8)
.map((spec) => ({
value: spec.command,
label: spec.command,
keywords: spec.description ? [spec.description] : [],
detail: spec.description || spec.usage || "",
}));
}
const triggers = computed<TriggerDefinition[]>(() => [
{
char: "/",
boundary: "start",
type: "command",
items: searchCommands,
},
{
char: "@",
type: "workflow",
items: searchWorkflows,
},
...(session.sections?.tasks !== false
? [
{
char: "#",
type: "task",
items: searchTasks,
} satisfies TriggerDefinition,
]
: []),
]);
function menuHeading(trigger: string | null): string {
if (trigger === "/") return "Commands";
if (trigger === "#") return "Tasks";
if (trigger === "@") return "Workflows";
return "Suggestions";
}
const triggers: TriggerDefinition[] = [{ char: "@", type: "workflow", items: searchWorkflows }];
</script>
<template>
@@ -236,29 +127,17 @@ function menuHeading(trigger: string | null): string {
</Tooltip>
</li>
</ul>
<ul v-if="!flat && (pageTag || taskTags.length)" 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>
<li
v-for="tag in taskTags"
:key="tag.id"
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">#{{ tag.id }}{{ tag.title ? ` ${tag.title}` : "" }}</span>
<Button variant="ghost" size="icon" class="size-5" :aria-label="`Remove task ${tag.id}`" @click="removeTaskTag(tag.id)"
><X
/></Button>
</li>
</ul>
<div
v-if="!flat && pageTag"
class="mb-2 flex w-fit 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>
</div>
<ChatSuggestions v-if="!flat && messages.length" />
<TokenInput :controller="prompt" submit-shortcut="enter" @value-change="onValueChange" @submit="onSubmit">
<TokenInput :controller="prompt" submit-shortcut="enter" @value-change="onValueChange" @submit="submit">
<div
:class="
cn(
@@ -273,7 +152,7 @@ function menuHeading(trigger: string | null): string {
<TokenInputEditor
aria-label="Message Archie"
:placeholder="placeholderHint || 'Message Archie (@ workflow, # task, / command)'"
:placeholder="placeholderHint || 'Message Archie (@ workflow)'"
:class="
cn(
'max-h-40 min-w-0 flex-1 overflow-y-auto bg-transparent text-label pointer-coarse:text-base outline-none',
@@ -285,21 +164,11 @@ function menuHeading(trigger: string | null): string {
<div :class="cn('flex flex-none items-center gap-2', !flat && 'mb-1.5')">
<slot name="actions" />
<Button v-if="isSending" variant="outline" size="sm" @click="stopTurn">Stop</Button>
<Button
v-if="canRecord && !composerText.trim()"
size="sm"
:variant="recording ? 'destructive' : 'outline'"
:disabled="isSending && !recording"
:aria-label="recording ? 'Stop recording and send' : 'Record a voice message'"
@click="toggleRecording"
><Mic data-icon="inline-start" />{{ recording ? "Send" : "" }}</Button
>
<p v-if="recordError" class="px-1 text-caption text-danger" role="alert">{{ recordError }}</p>
<Button
size="sm"
:variant="composerText.trim() ? 'default' : 'secondary'"
:disabled="!composerText.trim()"
@click="sendMessage()"
@click="submit"
>{{ isSending ? "Queue" : "Send" }}</Button
>
</div>
@@ -313,7 +182,7 @@ function menuHeading(trigger: string | null): string {
>
<TriggerMenuList v-slot="{ state }" class="max-h-60 overflow-auto">
<div class="px-2 py-1 text-caption font-medium text-fg-muted">
{{ menuHeading(state.trigger) }}
Workflows
</div>
<TriggerMenuEmpty class="px-2 py-2 text-label text-fg-muted">No matches</TriggerMenuEmpty>
<TriggerMenuItem
@@ -334,7 +203,7 @@ function menuHeading(trigger: string | null): string {
<TokenInputToken
class="mx-0.5 inline-flex items-center gap-1 rounded-sm border border-primary/25 bg-primary/10 px-1.5 py-0.5 align-baseline text-caption font-medium text-primary"
>
<span>{{ token.type === "workflow" ? `@${token.label}` : token.label }}</span>
<span>@{{ token.label }}</span>
<TokenInputTokenRemove
:aria-label="`Remove ${token.label}`"
class="cursor-pointer rounded-sm text-fg-muted hover:text-foreground"
+66 -349
View File
@@ -1,8 +1,7 @@
<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 { createReusableTemplate, useEventListener } from "@vueuse/core";
import { computed, ref, watch } from "vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
@@ -13,38 +12,16 @@ import {
DropdownMenuRadioItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useLiveResource } from "@/stores/session";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { useLiveResource } from "@/stores/session";
import ChatBar from "./ChatBar.vue";
import ChatComposer from "./ChatComposer.vue";
import ChatTranscript from "./ChatTranscript.vue";
import {
DOCK_STORAGE_KEY,
DRAG_START,
MAX_W,
MIN_H,
MIN_W,
RESIZE_DIRS,
SWIPE,
barPlacement,
fitRect,
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, reloadTranscript, useChat, useEscapeLayer } from "./state";
import { MIN_H, MIN_W, RESIZE_DIRS, handleOrientation, handleValue, type DockMode, type ResizeDir } from "./ChatDockLayout";
import { useDockWindow } from "./dock-window";
import { escapeOwnedByLayer, useEscapeLayer } from "./escape";
import { dockExpanded, isSending, reloadTranscript, useChat } from "./state";
import { setDockOpen, unseenCount } from "./unseen";
/**
@@ -65,8 +42,7 @@ import { setDockOpen, unseenCount } from "./unseen";
* 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.
* width, height) is stored per browser.
*
* On a phone-width screen the dock stays the full-width bottom bar: it rides
* above the on-screen keyboard, which iOS does not resize the page for, and
@@ -74,8 +50,7 @@ import { setDockOpen, unseenCount } from "./unseen";
* exist below the desktop breakpoint.
*
* The collapsed bar's show button carries the count of replies that landed
* while it was closed, and a task this conversation started reports its
* outcome into the transcript while the dock stays mounted.
* while it was closed.
*
* It stays mounted, so the session and any turn in flight survive a navigation.
* It is mounted outside the app shell: `.shell`'s backdrop-filter makes it a
@@ -84,147 +59,60 @@ import { setDockOpen, unseenCount } from "./unseen";
*/
useChat();
// A task this conversation started reports its outcome into it. The dock stays
// An action approved after its turn ended reports its outcome here. The dock stays
// mounted while collapsed, so a reply that lands then is still read and counted.
useLiveResource("chat", () => void reloadTranscript());
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 };
}
return fitRect(layout.value, 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 => {
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 {
// Ctrl+/ toggles the dock; Escape collapses it. A focused control that
// handled Escape itself (the composer's menu, the topbar search) calls
// preventDefault, and an open popover inside the dock owns Escape, so
// dismissing either never collapses the dock too.
useEventListener(document, "keydown", (event: KeyboardEvent) => {
if (event.defaultPrevented) return;
if ((event.ctrlKey || event.metaKey) && event.key === "/") {
event.preventDefault();
expanded.value = !expanded.value;
} else if (event.key === "Escape" && expanded.value && !escapeOwnedByLayer()) {
expanded.value = false;
}
}
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),
);
const header = ref<HTMLElement | null>(null);
const bar = ref<HTMLElement | null>(null);
const {
desktop,
vw,
vh,
mode,
pinned,
pinW,
pinMax,
winRect,
wrapStyle,
visibleHeight,
dragging,
resizing,
snapTarget,
setMode,
togglePin,
moveByKey,
resizeByKey,
resizePinByKey,
} = useDockWindow({ dock, header, bar }, expanded);
// 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 [DefineMoveHandle, MoveHandle] = createReusableTemplate();
const MODES: { mode: DockMode; label: string; icon: typeof PanelLeft }[] = [
{ mode: "left", label: "Left", icon: PanelLeft },
@@ -233,29 +121,6 @@ const MODES: { mode: DockMode; label: string; icon: typeof PanelLeft }[] = [
];
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"], [role="textbox"], [contenteditable="true"], [contenteditable=""]') ||
!!target.closest("[data-move-handle]")
);
}
function onBarFocusIn(event: FocusEvent): void {
const target = event.target as HTMLElement | null;
@@ -263,102 +128,6 @@ function onBarFocusIn(event: FocusEvent): void {
expanded.value = true;
}
// 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: resizeOrigin(), 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;
if (!expanded.value) {
const nextX = Math.min(Math.max(drag.origin.x + dx, INSET), Math.max(INSET, vw.value - drag.origin.w - INSET));
layout.value = { ...layout.value, mode: "float", x: nextX };
return;
}
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 = snapEdge(e.clientX, vw.value);
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",
@@ -379,47 +148,29 @@ const DIR_LABEL: Record<ResizeDir, string> = {
se: "bottom right",
sw: "bottom left",
};
// Only the expanded floating window resizes; the minimised bar is move-only.
// Only the expanded floating window resizes; the collapsed bar only moves.
const visibleDirs = computed<ResizeDir[]>(() => (expanded.value ? [...RESIZE_DIRS] : []));
// 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>
<DefineMoveHandle>
<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>
</DefineMoveHandle>
<div
v-if="snapTarget"
aria-hidden="true"
@@ -460,7 +211,7 @@ function onPinKey(event: KeyboardEvent): void {
: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)"
@keydown="resizeByKey(dir, $event)"
/>
</template>
<div
@@ -475,7 +226,7 @@ function onPinKey(event: KeyboardEvent): void {
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"
@keydown="resizePinByKey"
/>
<div
v-if="expanded"
@@ -484,24 +235,7 @@ function onPinKey(event: KeyboardEvent): void {
@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" #start><MoveHandle /></template>
<template v-if="desktop" #actions>
<DropdownMenu v-model:open="positionOpen">
<!-- No Tooltip around the trigger: nested in TooltipTrigger the menu
@@ -546,25 +280,8 @@ function onPinKey(event: KeyboardEvent): void {
<ChatTranscript />
</div>
<div ref="bar" class="touch-none" @focusin="onBarFocusIn">
<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>
<ChatComposer :flat="!expanded">
<template v-if="!expanded && desktop" #start><MoveHandle /></template>
<template v-if="!expanded" #actions>
<Tooltip>
<TooltipTrigger as-child>
-44
View File
@@ -22,7 +22,6 @@ export interface DockLayout extends Rect {
}
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;
@@ -51,11 +50,6 @@ export function defaultLayout(vw: number, vh: number): DockLayout {
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)));
@@ -148,44 +142,6 @@ 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;
}
-2
View File
@@ -3,7 +3,6 @@ import type { Element, ElementContent } from "hast";
import { computed, h, type VNodeChild } from "vue";
import CodeView from "@/base/CodeView.vue";
import ChatTaskRef from "./ChatTaskRef.vue";
import { parseMarkdown } from "./markdown";
/**
@@ -56,7 +55,6 @@ function codeBlock(pre: Element): VNodeChild {
function render(node: ElementContent, key: number): VNodeChild {
if (node.type === "text") return node.value;
if (node.type !== "element") return null;
if (node.tagName === "task-ref") return h(ChatTaskRef, { key, id: Number(node.properties.id) });
if (node.tagName === "pre") return codeBlock(node);
const { className, ...attrs } = node.properties;
-90
View File
@@ -1,90 +0,0 @@
<script setup lang="ts">
import { computed } from "vue";
import {
Questionnaire,
QuestionnaireActions,
QuestionnaireChoice,
QuestionnaireChoices,
QuestionnaireDescription,
QuestionnaireError,
QuestionnaireInput,
QuestionnaireItem,
QuestionnaireNext,
QuestionnairePrevious,
QuestionnaireProgress,
QuestionnaireSkip,
QuestionnaireSubmit,
QuestionnaireTitle,
} from "@/components/ui/questionnaire";
import type { ChatAsk } from "./state";
/**
* Several questions from one turn, answered in a single reply. The answers go
* back as a JSON object of question name to the list of values given, the shape
* the server checks against the questions it asked. The card owns answerAsk so
* a failed submit is recorded for the card's retry.
*/
const props = defineProps<{ ask: ChatAsk; send: (answer: string) => Promise<boolean> }>();
const questions = computed(() => props.ask.questions ?? []);
const items = computed(() =>
questions.value.map((q) => ({
name: q.name,
required: q.required,
choices: (q.choices ?? []).map((c) => ({ value: c.value })),
})),
);
const last = computed(() => questions.value.length <= 1);
function submit(event: Event): void {
event.preventDefault();
const form = new FormData(event.target as HTMLFormElement);
const answers: Record<string, string[]> = {};
for (const q of questions.value) {
const values = form.getAll(q.name).map(String).filter((v) => v.trim());
if (values.length) answers[q.name] = values;
}
void props.send(JSON.stringify(answers));
}
</script>
<template>
<Questionnaire
class="mt-2 min-w-72"
:default-item="questions[0]?.name"
:items="items"
shortcuts="letters"
@submit="submit"
>
<QuestionnaireProgress v-if="!last" />
<QuestionnaireItem
v-for="q in questions"
:key="q.name"
:name="q.name"
:required="q.required"
:multiple="q.multiple"
>
<QuestionnaireTitle>{{ q.title }}</QuestionnaireTitle>
<QuestionnaireDescription v-if="q.description">{{ q.description }}</QuestionnaireDescription>
<QuestionnaireChoices>
<QuestionnaireChoice v-for="c in q.choices ?? []" :key="c.value" :value="c.value">
<span class="font-medium">{{ c.label || c.value }}</span>
<span v-if="c.description" class="text-muted-foreground">{{ c.description }}</span>
</QuestionnaireChoice>
<QuestionnaireInput
v-if="q.allow_other || !q.choices?.length"
:aria-label="q.title"
:placeholder="q.choices?.length ? 'Something else…' : 'Your answer'"
/>
</QuestionnaireChoices>
<QuestionnaireError />
</QuestionnaireItem>
<QuestionnaireActions>
<QuestionnairePrevious v-if="!last" />
<QuestionnaireSkip />
<QuestionnaireNext v-if="!last">Next</QuestionnaireNext>
<QuestionnaireSubmit>Send</QuestionnaireSubmit>
</QuestionnaireActions>
</Questionnaire>
</template>
+53 -145
View File
@@ -1,77 +1,41 @@
<script setup lang="ts">
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import {
Copy,
Ellipsis,
GitBranch,
Pencil,
RotateCw,
Shrink,
Trash2,
Undo2,
} from "@lucide/vue";
import { ref } from "vue";
import { Copy, Ellipsis, Pencil, Trash2 } from "@lucide/vue";
import { computed, 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 { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Separator } from "@/components/ui/separator";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { errors } from "@/copy/errors";
import { describeError } from "@/lib/api";
import ChatSettings from "./ChatSettings.vue";
import {
currentSession,
deleteSession,
hasCommand,
messages,
renameSession,
runSessionCommand,
useEscapeLayer,
} from "./state";
import { useEscapeLayer } from "./escape";
import { currentSession, deleteSession, messages, modelError, renameSession, statusText } from "./state";
/**
* The menu behind the bar's one "more" button: 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), then the model it runs on.
*
* 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.
* The bar's "More" menu: actions on the open conversation, then the chat's
* status and any reason no model can answer.
*/
const open = ref(false);
const renameOpen = ref(false);
const confirmDelete = ref(false);
// Each layer owns Escape while open, so closing it leaves the dock open.
useEscapeLayer(open);
useEscapeLayer(renameOpen);
useEscapeLayer(confirmDelete);
function run(command: string): void {
open.value = false;
void runSessionCommand(command);
}
const title = ref("");
const status = computed(() => (statusText.value === "Ready" ? "" : statusText.value));
// 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.
// heading per speaker. Tool-only replies have no text to copy.
async function copyMarkdown(): Promise<void> {
open.value = false;
const text = messages.value
.map((m) => {
const body = (m.text ?? m.Text ?? "").trim();
if (!body) return "";
return `### ${(m.from ?? m.From) === "web" ? "You" : "Archie"}\n\n${body}`;
})
.filter(Boolean)
.filter((m) => m.text.trim())
.map((m) => `### ${m.from === "web" ? "You" : "Archie"}\n\n${m.text.trim()}`)
.join("\n\n");
if (!text) {
toast.error(errors.chat.session.nothingToCopy);
@@ -86,35 +50,23 @@ async function copyMarkdown(): Promise<void> {
toast.success("Copied as Markdown");
}
// Rename and branch ask for a value in a labelled dialog, not window.prompt.
const promptOpen = ref(false);
// The dialog owns Escape while open, so closing it leaves the dock open.
useEscapeLayer(promptOpen);
const promptCommand = ref("");
const promptMessage = ref("");
const promptValue = ref("");
function prompt(command: string, message: string): void {
function askRename(): void {
open.value = false;
promptCommand.value = command;
promptMessage.value = message;
promptValue.value = "";
promptOpen.value = true;
title.value = "";
renameOpen.value = true;
}
function submitPrompt(): void {
const value = promptValue.value.trim();
promptOpen.value = false;
if (!value) return;
// Renaming is the chat API's own; other prompts are server commands.
if (promptCommand.value === "/title") void renameSession(value);
else void runSessionCommand(`${promptCommand.value} ${value}`);
function submitRename(): void {
const value = title.value.trim();
renameOpen.value = false;
if (value) void renameSession(value);
}
const confirmDelete = ref(false);
useEscapeLayer(confirmDelete);
function askDelete(): void {
open.value = false;
confirmDelete.value = true;
}
function remove(): void {
confirmDelete.value = false;
void deleteSession();
@@ -122,7 +74,7 @@ function remove(): void {
</script>
<template>
<Popover v-model:open="open">
<Popover v-if="currentSession || status || modelError" 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
@@ -131,12 +83,7 @@ function remove(): void {
<Tooltip>
<TooltipTrigger as-child>
<PopoverTrigger as-child>
<Button
variant="ghost"
size="icon-sm"
class="flex-none"
aria-label="More"
>
<Button variant="ghost" size="icon-sm" class="flex-none" aria-label="More">
<Ellipsis />
</Button>
</PopoverTrigger>
@@ -146,75 +93,36 @@ function remove(): void {
</PopoverAnchor>
<PopoverContent align="end" class="grid w-64 gap-0.5 p-1">
<template v-if="currentSession">
<Button
v-if="hasCommand('/retry')"
variant="ghost"
size="sm"
class="justify-start"
@click="run('/retry')"
><RotateCw data-icon="inline-start" />Retry</Button
>
<Button
v-if="hasCommand('/undo')"
variant="ghost"
size="sm"
class="justify-start"
@click="run('/undo')"
><Undo2 data-icon="inline-start" />Undo</Button
>
<Button
variant="ghost"
size="sm"
class="justify-start"
@click="prompt('/title', 'Session title')"
><Pencil data-icon="inline-start" />Rename</Button
>
<Button
v-if="hasCommand('/branch')"
variant="ghost"
size="sm"
class="justify-start"
@click="prompt('/branch', 'Branch name (optional)')"
><GitBranch data-icon="inline-start" />Branch</Button
>
<Button
v-if="hasCommand('/compress')"
variant="ghost"
size="sm"
class="justify-start"
@click="run('/compress --preview')"
><Shrink data-icon="inline-start" />Preview compression</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="askDelete"
><Trash2 data-icon="inline-start" />Delete</Button
>
<Separator class="my-1" />
<Button variant="ghost" size="sm" class="justify-start" @click="askRename">
<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="askDelete">
<Trash2 data-icon="inline-start" />Delete
</Button>
</template>
<template v-if="status || modelError">
<Separator v-if="currentSession" class="my-1" />
<div class="grid gap-1 p-1">
<span v-if="status" class="text-caption text-fg-subtle">{{ status }}</span>
<span v-if="modelError" class="text-caption text-destructive">{{ modelError }}</span>
</div>
</template>
<ChatSettings />
</PopoverContent>
</Popover>
<Dialog :open="promptOpen" @update:open="(v: boolean) => (promptOpen = v)">
<Dialog v-model:open="renameOpen">
<DialogContent>
<DialogHeader><DialogTitle>{{ promptMessage }}</DialogTitle></DialogHeader>
<Input v-model="promptValue" :aria-label="promptMessage" @keydown.enter.prevent="submitPrompt" />
<DialogHeader><DialogTitle>Session title</DialogTitle></DialogHeader>
<Input v-model="title" aria-label="Session title" @keydown.enter.prevent="submitRename" />
<DialogFooter>
<Button variant="ghost" @click="promptOpen = false">Cancel</Button>
<Button :disabled="!promptValue.trim()" @click="submitPrompt">OK</Button>
<Button variant="ghost" @click="renameOpen = false">Cancel</Button>
<Button :disabled="!title.trim()" @click="submitRename">OK</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog :open="confirmDelete" @update:open="(v: boolean) => (confirmDelete = v)">
<Dialog v-model:open="confirmDelete">
<DialogContent>
<DialogHeader><DialogTitle>Delete this conversation?</DialogTitle></DialogHeader>
<DialogFooter>
+2 -2
View File
@@ -1,9 +1,9 @@
<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 { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { sessionTitle } from "./session";
import { currentSession, newChat, selectSession, sessions } from "./state";
@@ -20,7 +20,7 @@ const nav = ref<HTMLElement | null>(null);
onMounted(() => nav.value?.focus());
function choose(id: string): void {
selectSession(id);
void selectSession(id);
emit("close");
}
-71
View File
@@ -1,71 +0,0 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { selectedModel, selectorData, setModel, statusText } from "./state";
/**
* The chat's own settings: what the panel is doing right now, and the model it
* runs on. A model id already names its provider, so there is one control. It
* sits in the session menu.
*
* 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 modelValue = computed(() => selectedModel.value || DEFAULT);
// reka-ui mounts every item of a closed Select to find the selected label, so a
// catalogue of hundreds of models stalled the menu that holds this control.
// The items mount only while the list is open and the label is written here.
const listOpen = ref(false);
const label = computed(() => (selectedModel.value ? selectedModel.value : "Default"));
// The server groups models by provider; one flat list stands in when it does not.
const groups = computed(() => {
const grouped = selectorData.value.models_by_provider || {};
const entries = Object.entries(grouped).filter(([, models]) => models.length);
return entries.length
? entries
: [["", selectorData.value.models || []] as [string, string[]]];
});
// The model is chosen here only when the server offers a choice.
const choosable = computed(() => groups.value.some(([, models]) => models.length));
</script>
<template>
<div class="grid gap-1 p-1">
<span v-if="statusText !== 'Ready'" class="text-caption text-fg-subtle">{{ statusText }}</span>
<span v-if="selectorData.model_error" class="text-caption text-destructive">{{ selectorData.model_error }}</span>
<Select
v-if="choosable"
v-model:open="listOpen"
:model-value="modelValue"
@update:model-value="setModel($event === DEFAULT ? '' : String($event ?? ''))"
>
<SelectTrigger size="sm" class="w-full" aria-label="Model">
<SelectValue>{{ label }}</SelectValue>
</SelectTrigger>
<SelectContent>
<template v-if="listOpen">
<SelectItem :value="DEFAULT">Default</SelectItem>
<SelectGroup v-for="[provider, models] in groups" :key="provider">
<SelectLabel v-if="provider">{{ provider }}</SelectLabel>
<SelectItem v-for="model in models" :key="model" :value="model">{{ model }}</SelectItem>
</SelectGroup>
</template>
</SelectContent>
</Select>
</div>
</template>
+4 -5
View File
@@ -10,10 +10,9 @@ 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 a chat model is configured. A click
* sends the prompt as its own message (sendMessage's textOverride path sends at
* once while no turn runs) rather than filling the field, and resting on one
* previews it as the composer's placeholder.
* chips that scrolls sideways. A click sends the prompt as its own message
* and leaves the composer as typed; hovering or focusing one previews it as
* the composer's placeholder.
*/
defineProps<{ list?: boolean }>();
@@ -28,7 +27,7 @@ const prompts = computed(() => {
function send(prompt: string): void {
placeholderHint.value = "";
void sendMessage({ textOverride: prompt });
void sendMessage({ text: prompt });
}
function preview(prompt: string): void {
placeholderHint.value = prompt;
-59
View File
@@ -1,59 +0,0 @@
<script setup lang="ts">
import { onBeforeUnmount, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { revealTaskRow, taskExists } from "./task-ref";
/**
* A #N in a reply. It becomes a link only once the tasks API confirms the
* task exists, so an issue number or a stray count stays plain text. On the
* Tasks page, where the row is already listed, it scrolls there instead of
* leaving the page.
*/
const props = defineProps<{ id: number }>();
const route = useRoute();
const exists = ref(false);
// A streaming reply shows #1 before #12; the short wait skips the partial one.
let timer = 0;
watch(
() => props.id,
(id) => {
exists.value = false;
window.clearTimeout(timer);
timer = window.setTimeout(async () => {
const found = await taskExists(id);
if (id === props.id) exists.value = found === true;
}, 250);
},
{ immediate: true },
);
onBeforeUnmount(() => window.clearTimeout(timer));
function onClick(event: MouseEvent, navigate: (e: MouseEvent) => void) {
if (route.path === "/tasks" && revealTaskRow(props.id)) {
event.preventDefault();
return;
}
navigate(event);
}
</script>
<template>
<RouterLink
v-if="exists"
v-slot="{ href, navigate }"
:to="`/tasks/${id}`"
custom
>
<a
:href="href"
:title="`Task ${id}`"
class="rounded bg-primary-soft px-1 py-0.5 font-mono text-[0.9em] text-link hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
@click="onClick($event, navigate)"
>#{{ id }}</a
>
</RouterLink>
<template v-else>#{{ id }}</template>
</template>
+30 -57
View File
@@ -1,10 +1,10 @@
<script setup lang="ts">
import { Spinner } from "@/components/ui/spinner";
import { CircleCheck, CircleX } from "@lucide/vue";
import { createReusableTemplate } from "@vueuse/core";
import { computed } from "vue";
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block";
import { duration as formatDuration } from "@/lib/format";
import { Spinner } from "@/components/ui/spinner";
import {
TraceCollapsible,
TraceCollapsibleContent,
@@ -13,49 +13,29 @@ import {
TraceLine,
TraceTitle,
} from "@/components/ui/trace";
import { duration as formatDuration } from "@/lib/format";
import ChatNavChip from "./ChatNavChip.vue";
import type { ChatToolCall } from "./state";
import type { ChatToolCall } from "./types";
/**
* 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.
* One tool call: its name and main argument, with the full parameters and
* output folded away. It is evidence for the reply around it, so it stays dim
* unless the call failed. A failed call opens by default.
*/
const props = defineProps<{
tool: ChatToolCall;
/** The turn is still arriving, so a call with no outcome yet is running. */
/** The turn is still arriving, so a call with no output 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),
);
const [DefineLine, Line] = createReusableTemplate();
// 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 parameters = computed(() => props.tool.parameters ?? "");
const failed = computed(() => !!props.tool.failed);
const running = computed(() => !props.tool.text && !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.
// The line shows the call's main value, such as "git diff --stat" rather than
// its JSON: the first string argument, else the arguments as key: value pairs.
const argument = computed(() => {
try {
const args: unknown = JSON.parse(parameters.value);
@@ -72,39 +52,32 @@ const argument = computed(() => {
return parameters.value.split("\n", 1)[0];
});
const detail = computed(() =>
[parameters.value && `> ${parameters.value}`, outcome.value].filter(Boolean).join("\n\n"),
[parameters.value && `> ${parameters.value}`, props.tool.text].filter(Boolean).join("\n\n"),
);
</script>
<template>
<DefineLine>
<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">{{ tool.name || "tool" }}</span>
<TraceTitle class="font-mono text-caption">{{ argument }}</TraceTitle>
<span v-if="duration" class="shrink-0 text-caption tabular-nums">{{ duration }}</span>
</TraceLine>
</DefineLine>
<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>
<TraceCollapsibleTrigger><Line /></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>
<Line v-else />
</template>
+3 -5
View File
@@ -11,7 +11,7 @@ import {
TraceTitle,
} from "@/components/ui/trace";
import ChatToolCall from "./ChatToolCall.vue";
import type { ChatToolCall as ToolCall } from "./state";
import type { ChatToolCall as ToolCall } from "./types";
/**
* A run of consecutive tool calls as one line, opened to the individual
@@ -19,10 +19,8 @@ import type { ChatToolCall as ToolCall } from "./state";
*/
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"}`);
const anyFailed = computed(() => props.tools.some((tool) => tool.failed));
const title = computed(() => `${props.tools.length} tool calls`);
</script>
<template>
+35 -78
View File
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { computed } from "vue";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import {
MessageScroller,
@@ -9,14 +10,11 @@ import {
MessageScrollerProvider,
MessageScrollerViewport,
} from "@/components/ui/message-scroller";
import { Skeleton } from "@/components/ui/skeleton";
import ChatAskCard from "./ChatAskCard.vue";
import ChatBubble from "./ChatBubble.vue";
import ChatChooseCard from "./ChatChooseCard.vue";
import ChatUpdateCard from "./ChatUpdateCard.vue";
import ChatEmptyState from "./ChatEmptyState.vue";
import ChatJumpButton from "./ChatJumpButton.vue";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Skeleton } from "@/components/ui/skeleton";
import {
currentSession,
isLoadingSession,
@@ -25,73 +23,43 @@ import {
sendMessage,
sessionError,
streamingTurn,
type ChatMessage,
} from "./state";
/**
* The conversation: the messages so far, the turn still arriving, and what the
* panel says before either exists.
* The conversation: the messages so far and the turn still arriving.
*
* The scroller follows the tail, and stops following the moment the reader
* scrolls up rather than yanking them back on every streamed token. A watcher
* that set scrollTop by hand would have no "reader scrolled away" state and no
* way back down, so MessageScroller owns this.
* MessageScroller follows the tail and stops following as soon as the reader
* scrolls up, so streamed tokens never pull them back down.
*/
function parts(message: ChatMessage, index: number) {
const from = message.from ?? message.From ?? "";
// Anything this browser's composer did not send is Archie's answer.
return {
id: message.message_id || message.MessageID || `m${index}`,
text: message.text ?? message.Text ?? "",
tools: message.tool_calls || message.ToolCalls || [],
// Attachments have no bytes left to render -- the record kept their
// metadata only -- so the bubble labels them.
media: message.media || [],
assistant: from !== "web",
update: message.update,
choose: message.choose,
error: !!message.error,
approvals: message.approvals || [],
};
}
const bubbles = computed(() => messages.value.map(parts));
// The live turn is the row the finished message will take, under the same id:
// the scroller sees one row grow and settle, not one leave and another arrive.
const rows = computed(() => {
const finished = messages.value.map((message, index) => ({
id: message.message_id || `m${index}`,
text: message.text,
tools: message.tool_calls ?? [],
assistant: message.from !== "web",
error: !!message.error,
approvals: message.approvals ?? [],
live: false,
reasoning: "",
thinkingPending: false,
}));
const turn = streamingTurn.value;
if (!turn) {
return bubbles.value.map((bubble) => ({
...bubble,
live: false,
reasoning: "",
thinkingPending: false,
}));
}
if (!turn) return finished;
// The live turn takes the id the finished message will have, so the scroller
// sees one row grow and settle instead of one row leaving and another arriving.
return [
...bubbles.value.map((bubble) => ({
...bubble,
live: false,
reasoning: "",
thinkingPending: false,
})),
...finished,
{
id: `m${bubbles.value.length}`,
id: `m${finished.length}`,
text: turn.text || "…",
tools: turn.tools,
media: [],
assistant: true,
update: undefined,
choose: undefined,
error: turn.isError,
approvals: turn.approvals || [],
approvals: turn.approvals,
live: true,
reasoning: turn.reasoning ?? "",
// Nothing said and nothing reasoned yet: the turn may still be thinking,
// so the row shows the pending thinking trace. Once the answer's text
// arrives without any reasoning, the trace is not rendered at all.
thinkingPending: !turn.text && !(turn.reasoning ?? ""),
reasoning: turn.reasoning,
// Nothing said or reasoned yet: the turn may still be thinking.
thinkingPending: !turn.text && !turn.reasoning,
},
];
});
@@ -102,21 +70,18 @@ const rows = computed(() => {
<MessageScroller class="min-h-0 flex-1">
<MessageScrollerViewport>
<MessageScrollerContent class="gap-4 p-4">
<template v-if="isLoadingSession && !bubbles.length">
<template v-if="isLoadingSession && !messages.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 && !bubbles.length"
class="flex flex-col items-center gap-3 p-4"
>
<div v-else-if="sessionError && !messages.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="!bubbles.length && !streamingTurn" />
<ChatEmptyState v-else-if="!rows.length" />
<template v-else>
<MessageScrollerItem
@@ -128,7 +93,6 @@ const rows = computed(() => {
<ChatBubble
:text="row.text"
:tools="row.tools"
:media="row.media"
:assistant="row.assistant"
:streaming="row.live"
:reasoning="row.reasoning"
@@ -136,20 +100,13 @@ const rows = computed(() => {
:error="row.error"
>
<ChatAskCard v-for="ask in row.approvals" :key="ask.id" :ask="ask" />
<template v-if="row.live && streamingTurn">
<Button
v-if="streamingTurn.isError && streamingTurn.turn"
variant="outline"
size="sm"
class="mt-2"
@click="sendMessage({ turn: streamingTurn.turn })"
>Retry</Button>
<ChatAskCard v-if="streamingTurn.ask" :ask="streamingTurn.ask" />
</template>
<template v-else>
<ChatUpdateCard v-if="row.update" :update="row.update" />
<ChatChooseCard v-if="row.choose" :choose="row.choose" />
</template>
<Button
v-if="row.live && streamingTurn?.isError && streamingTurn.retryText"
variant="outline"
size="sm"
class="mt-2"
@click="sendMessage({ retry: streamingTurn.retryText })"
>Retry</Button>
</ChatBubble>
</MessageScrollerItem>
</template>
-71
View File
@@ -1,71 +0,0 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import { Button } from "@/components/ui/button";
import { errors } from "@/copy/errors";
import { api, describeError } from "@/lib/api";
import type { ChatUpdate } from "./state";
const props = defineProps<{ update: ChatUpdate }>();
interface Component {
Label?: string;
ID?: string;
Installed?: string;
Available?: string;
Changelog?: string;
}
const available = computed(() => (props.update.available ?? []) as Component[]);
const state = ref<"idle" | "installing" | "deferred" | "done" | "failed">("idle");
const result = ref("");
async function install() {
state.value = "installing";
try {
const out = await api.updateInstall<{ result?: { installed?: Record<string, string> } }>(props.update.snapshot);
const installed = out.result?.installed;
result.value = installed
? Object.entries(installed).map(([id, v]) => `${id} → ${v}`).join(", ") + ". Archie restarts to apply it."
: "Update finished.";
state.value = "done";
} catch (err) {
result.value = describeError(err, errors.common.unknown);
state.value = "failed";
}
}
async function later() {
try {
await api.updateDefer(props.update.snapshot);
state.value = "deferred";
} catch (err) {
result.value = describeError(err, errors.common.unknown);
state.value = "failed";
}
}
</script>
<template>
<div class="text-label">
<p v-if="!available.length">Up to date</p>
<template v-else>
<p class="font-medium">An update is available</p>
<ul class="mt-1 space-y-0.5">
<li v-for="c in available" :key="c.ID">
{{ c.Label || c.ID }}: <span class="font-mono">{{ c.Installed || "?" }} → {{ c.Available }}</span>
<a v-if="c.Changelog" :href="c.Changelog" target="_blank" rel="noopener" class="ml-1 text-caption underline">changes</a>
</li>
</ul>
<div v-if="state === 'idle' || state === 'failed'" class="mt-3 flex gap-2">
<Button v-if="update.can_install" size="sm" @click="install">Install</Button>
<Button size="sm" variant="ghost" @click="later">Not now</Button>
</div>
<p v-else-if="state === 'installing'" class="mt-2 text-fg-muted">Installing…</p>
<p v-else-if="state === 'deferred'" class="mt-2 text-fg-muted">Skipped until a newer release.</p>
<p v-else-if="state === 'done'" class="mt-2 text-ok">{{ result }}</p>
<p v-else class="mt-2 text-danger">{{ result }}</p>
<p v-if="state === 'idle' && !update.can_install" class="mt-2 text-caption text-fg-muted">No install script on this host.</p>
</template>
</div>
</template>
-50
View File
@@ -1,50 +0,0 @@
import type { ChatMedia } from "./state";
/**
* How a transcript renders an attachment whose bytes it does not have.
*
* The bytes are turn-scoped and never reach a browser, so the label stands in
* for the file. It reuses the placeholder vocabulary the channels already
* write into a message's text (`[photo]`, `[document: report.pdf]`, see the
* notes in `internal/channels/telegram/inboundmedia.go`), so the same
* attachment reads the same whether its metadata survived persistence or only
* the note in its text did.
*/
export function mediaLabel(attachment: ChatMedia): string {
switch (attachment.type) {
case "image":
return "[photo]";
case "video":
return "[video]";
case "audio":
return "[audio]";
case "document":
return attachment.file_name
? `[document: ${attachment.file_name}]`
: "[document]";
default:
return `[${attachment.type || "attachment"}]`;
}
}
/**
* The metadata behind the label, for the chip's tooltip: mime type, file name,
* size, dimensions and duration, in the order a reader asks about them.
*
* It reports only what the record actually carried, so an unknown size reads
* as absent rather than as zero, and it never names the platform file id: a
* handle is not information about the file.
*/
export function mediaDetail(attachment: ChatMedia): string {
const parts: string[] = [];
if (attachment.mime_type) parts.push(attachment.mime_type);
if (attachment.file_name) parts.push(attachment.file_name);
if (attachment.file_size !== undefined) {
parts.push(`${attachment.file_size} bytes`);
}
if (attachment.width && attachment.height) {
parts.push(`${attachment.width}×${attachment.height}`);
}
if (attachment.duration !== undefined) parts.push(`${attachment.duration} s`);
return parts.join(" · ");
}
-24
View File
@@ -1,24 +0,0 @@
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 {
// Storage can be blocked (private mode, policy): fall back to a per-load id
// rather than throwing a DOMException on every send.
let id: string | null = null;
try {
id = localStorage.getItem(CHANNEL_KEY);
if (!id) {
id = randomUUID();
localStorage.setItem(CHANNEL_KEY, id);
}
} catch {
id = id ?? randomUUID();
}
return id;
}
-41
View File
@@ -1,41 +0,0 @@
// 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;
}
+313
View File
@@ -0,0 +1,313 @@
import {
useDraggable,
useEventListener,
useMediaQuery,
usePointerSwipe,
useResizeObserver,
useStorage,
useWindowSize,
} from "@vueuse/core";
import { computed, nextTick, onUnmounted, ref, watch, type Ref } from "vue";
import {
DOCK_STORAGE_KEY,
DRAG_START,
INSET,
MAX_W,
SWIPE,
barPlacement,
fitRect,
keyboardCover,
keyStep,
normalizeLayout,
phoneBarBottom,
pinnedWidth,
resizeRect,
snapEdge,
type DockLayout,
type DockMode,
type Rect,
type ResizeDir,
} from "./ChatDockLayout";
interface DockElements {
/** The dock itself: the target of every drag and resize. */
dock: Ref<HTMLElement | null>;
/** The conversation header, which drags the expanded window. */
header: Ref<HTMLElement | null>;
/** The composer bar, which drags the collapsed dock. */
bar: Ref<HTMLElement | null>;
}
const NOT_A_DRAG_SURFACE =
'button, a, input, select, textarea, [role="combobox"], [role="separator"], [role="textbox"], [contenteditable="true"], [contenteditable=""]';
/** The horizontal and vertical step an arrow key asks for. */
function arrowDelta(event: KeyboardEvent): { dx: number; dy: number } {
const step = keyStep(event.shiftKey);
return {
dx: event.key === "ArrowRight" ? step : event.key === "ArrowLeft" ? -step : 0,
dy: event.key === "ArrowDown" ? step : event.key === "ArrowUp" ? -step : 0,
};
}
/**
* The chat dock's window behaviour. On a desktop-width screen the dock floats
* or pins to a side: pointer drags move it, eight handles resize it, arrow keys
* do both, and dragging near a side edge offers the pinned split. On a phone
* it is a full-width bottom bar that rides above the on-screen keyboard and
* hides when its header is swiped down. The layout is stored per browser, and
* the page reads the dock's footprint from CSS variables on the root element.
*/
export function useDockWindow({ dock, header, bar }: DockElements, expanded: Ref<boolean>) {
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(() => pinnedWidth(MAX_W, vw.value));
function floatAt(rect: Rect): void {
layout.value = { ...layout.value, mode: "float", x: rect.x, y: rect.y, w: rect.w, h: rect.h };
}
// The rendered rectangle: 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 };
}
return fitRect(layout.value, vw.value, vh.value);
});
// Fixed elements stay anchored to the layout viewport, so the dock offsets
// by the part the on-screen keyboard covers to stay above it.
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);
useEventListener(() => window.visualViewport, ["resize", "scroll"], () => {
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;
});
const wrapStyle = computed((): Record<string, string> => {
if (!desktop.value) return { bottom: phoneBarBottom(keyboard.value) };
const rect = winRect.value;
if (pinned.value) {
return { left: `${rect.x}px`, top: "0px", width: `${rect.w}px`, height: `${rect.h}px` };
}
if (expanded.value) {
// A tablet's on-screen keyboard covers the bottom of the layout
// viewport; keep the window, and its composer, 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 placed = barPlacement(rect, mode.value, vw.value);
return { left: `${placed.x}px`, bottom: `${placed.bottom + keyboard.value}px`, width: `${placed.w}px` };
});
// 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. Only a bar in the
// bottom quarter of the screen reserves room.
const root = document.documentElement.style;
function reserve(): void {
if (expanded.value || !dock.value) return;
const rect = dock.value.getBoundingClientRect();
const clear = rect.bottom >= window.innerHeight * 0.75 ? Math.ceil(window.innerHeight - rect.top) : 0;
root.setProperty("--chat-dock-clear", `${clear}px`);
}
useResizeObserver(dock, reserve);
useEventListener(window, "resize", reserve);
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],
() => {
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(() => {
root.removeProperty("--chat-dock-clear");
root.removeProperty("--chat-pin-l");
root.removeProperty("--chat-pin-r");
});
// The header drags the open window and the bar drags the collapsed 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(NOT_A_DRAG_SURFACE) || !!target.closest("[data-move-handle]");
}
// The rectangle a drag or resize starts from. Collapsed, the bar can sit at
// an edge rather than at the stored x, so its rendered x and width are the
// origin; otherwise the first move would make it jump.
function dragOrigin(): Rect {
const rect = winRect.value;
if (expanded.value || !dock.value) return rect;
const shown = dock.value.getBoundingClientRect();
return { ...rect, x: shown.left, w: shown.width };
}
function applyResize(origin: Rect, dir: ResizeDir, dx: number, dy: number): void {
floatAt(resizeRect(origin, dir, dx, dy, vw.value, vh.value));
}
const dragging = ref(false);
const resizing = ref(false);
const snapTarget = ref<"left" | "right" | null>(null);
// A press becomes a drag only after DRAG_START pixels of travel, so a click
// or double-click on a drag surface never moves the dock.
let drag: { origin: Rect; x0: number; y0: number; moved: boolean } | null = null;
useDraggable(dock, {
disabled: () => !desktop.value,
onStart: (_, e) => {
if (!e.isPrimary || !onDragSurface(e.target as HTMLElement)) return false;
drag = { origin: dragOrigin(), x0: e.clientX, y0: e.clientY, moved: false };
},
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;
if (!expanded.value) {
const x = Math.min(Math.max(drag.origin.x + dx, INSET), Math.max(INSET, vw.value - drag.origin.w - INSET));
layout.value = { ...layout.value, mode: "float", x };
return;
}
floatAt(fitRect({ ...drag.origin, x: drag.origin.x + dx, y: drag.origin.y + dy }, vw.value, vh.value));
snapTarget.value = snapEdge(e.clientX, vw.value);
},
onEnd: (_, e) => {
if (drag?.moved && e.type === "pointerup" && snapTarget.value) {
layout.value = { ...layout.value, mode: snapTarget.value };
}
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 would compound 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 handle = (e.target as HTMLElement).closest<HTMLElement>("[data-resize]");
const dir = handle?.dataset.resize as ResizeDir | "pin" | undefined;
if (!e.isPrimary || !dir) return false;
resize = { dir, origin: dragOrigin(), 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: pinnedWidth(resize.w0 + (mode.value === "left" ? dx : -dx), vw.value) };
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
// swipe hides the conversation.
usePointerSwipe(header, {
threshold: SWIPE,
onSwipeEnd: (e, direction) => {
if (desktop.value || e.type !== "pointerup" || direction !== "down") return;
// The keyboard serves the composer, which is no longer in front of it.
(document.activeElement as HTMLElement | null)?.blur();
expanded.value = false;
},
});
function setMode(next: DockMode): void {
if (!desktop.value) return;
layout.value = { ...layout.value, mode: next };
expanded.value = true;
}
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 { dx, dy } = arrowDelta(event);
const rect = winRect.value;
floatAt(fitRect({ ...rect, x: rect.x + dx, y: rect.y + dy }, vw.value, vh.value));
}
function resizeByKey(dir: ResizeDir, event: KeyboardEvent): void {
if (!desktop.value || !event.key.startsWith("Arrow")) return;
event.preventDefault();
const { dx, dy } = arrowDelta(event);
applyResize(dragOrigin(), dir, dx, dy);
}
function resizePinByKey(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: pinnedWidth(layout.value.w + (grow ? 16 : -16), vw.value) };
}
return {
desktop,
vw,
vh,
mode,
pinned,
pinW,
pinMax,
winRect,
wrapStyle,
visibleHeight,
dragging,
resizing,
snapTarget,
setMode,
togglePin,
moveByKey,
resizeByKey,
resizePinByKey,
};
}
+22
View File
@@ -0,0 +1,22 @@
import { onUnmounted, ref, watch, type Ref } from "vue";
/**
* How many layers inside the dock currently own Escape: an open popover,
* dialog or drawer. The dock collapses on Escape only when none is open, so
* dismissing a menu does not also hide the conversation behind it.
*/
const openLayers = ref(0);
/** Registers a toggleable layer inside the dock 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;
}
+6 -27
View File
@@ -7,13 +7,10 @@ import { unified } from "unified";
/**
* Model-written Markdown (GitHub flavoured) parsed into an HTML syntax tree
* that ChatMarkdown renders as Vue nodes. Raw HTML in the source is dropped,
* links and images keep only safe URLs, and a #N outside code and links
* becomes a `task-ref` element.
* and links and images keep only safe URLs.
*/
const processor = unified().use(remarkParse).use(remarkGfm).use(remarkRehype);
// A #N the model wrote about a task. Not part of a word, entity or path.
const TASK_REF = /(?<![\w&#/])#(\d{1,9})(?!\w)/g;
const SAFE_HREF = /^(?:https?:\/\/|\/(?!\/)|#)/i;
// Images render only from same-origin paths and inline data: a remote image
// URL is a data-exfil sink, and /\ or // makes the browser treat the rest as
@@ -22,24 +19,23 @@ const SAFE_SRC = /^(?:\/(?![/\\])|data:image\/)/i;
export function parseMarkdown(text: string | null | undefined): Root {
const tree = processor.runSync(processor.parse(text ?? "")) as Root;
tree.children = clean(tree.children, false) as RootContent[];
tree.children = clean(tree.children) as RootContent[];
return tree;
}
function clean(nodes: Array<RootContent | ElementContent>, literal: boolean): ElementContent[] {
function clean(nodes: Array<RootContent | ElementContent>): ElementContent[] {
const out: ElementContent[] = [];
for (const node of nodes) {
if (node.type === "text") {
out.push(...(literal ? [node] : taskRefs(node.value)));
out.push(node);
} else if (node.type === "element") {
const kept = safeElement(node);
if (!kept) continue;
if (kept !== node) {
out.push(...clean(kept.children, literal));
out.push(...clean(kept.children));
continue;
}
const inner = literal || ["a", "code", "pre"].includes(node.tagName);
node.children = clean(node.children, inner);
node.children = clean(node.children);
out.push(node);
}
}
@@ -57,20 +53,3 @@ function safeElement(node: Element): Element | null {
}
return node;
}
function taskRefs(text: string): ElementContent[] {
const out: ElementContent[] = [];
let cursor = 0;
for (const match of text.matchAll(TASK_REF)) {
if (match.index > cursor) out.push({ type: "text", value: text.slice(cursor, match.index) });
out.push({
type: "element",
tagName: "task-ref",
properties: { id: match[1] },
children: [],
});
cursor = match.index + match[0].length;
}
if (cursor < text.length) out.push({ type: "text", value: text.slice(cursor) });
return out;
}
+3 -10
View File
@@ -1,16 +1,9 @@
import type { TokenInputValue } from "@ui-sdk/core/token-input";
/**
* Serializes a TokenInputValue into the plain text sent in a chat turn.
* Commands keep their slash label, tasks emit `#<id>`, and workflows emit `@<name>`.
* Serializes a TokenInputValue into the plain text sent in a chat turn. The
* only token is a workflow, sent as `@<name>`.
*/
export function serializePromptValue(value: TokenInputValue): string {
return value
.map((segment) => {
if (typeof segment === "string") return segment;
if (segment.type === "task") return `#${segment.value}`;
if (segment.type === "workflow") return `@${segment.label}`;
return segment.label;
})
.join("");
return value.map((segment) => (typeof segment === "string" ? segment : `@${segment.label}`)).join("");
}
+3 -5
View File
@@ -1,6 +1,5 @@
import { useAppearanceStore } from "../stores/appearance";
import type { ChatSession } from "./state";
import { useAppearanceStore } from "@/stores/appearance";
import type { ChatSession } from "./types";
// One formatter per zone, cached: the zone chosen under Appearance is applied
// here like Timestamp applies it, not the browser's zone.
@@ -22,8 +21,7 @@ function started(zone: string): Intl.DateTimeFormat {
// 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 || session.branch_name;
if (named) return named;
if (session.title) return session.title;
return session.created_at
? started(useAppearanceStore().timeZone).format(new Date(session.created_at))
: "New chat";
+207 -724
View File
File diff suppressed because it is too large. Load diff
+54
View File
@@ -0,0 +1,54 @@
import { errors } from "@/copy/errors";
import { api } from "@/lib/api";
import type { ChatToolCall } from "./types";
/**
* One `data: {...}` frame of a turn's event stream. A `tool` frame carries a
* ChatToolCall, a `navigate` frame its path and label, and an `approval` frame
* the held action.
*/
export interface ChatStreamFrame extends ChatToolCall {
seq?: number;
type?: string;
request_id?: string;
action?: string;
summary?: string;
}
const TERMINAL = new Set(["done", "error", "cancelled"]);
/**
* Reads a turn's recorded events from the server-sent stream until it ends,
* passing each frame to onFrame. Resolves with the terminal frame: done, error
* or cancelled. A stream that closes before a terminal frame is a failure.
*/
export async function readTurn(
turnID: string,
signal: AbortSignal | undefined,
onFrame: (frame: ChatStreamFrame) => void,
onBytes: () => void = () => {},
): Promise<ChatStreamFrame> {
const response = await api.chatTurnEvents(turnID, 0, { signal });
if (!response.body) throw new Error(errors.chat.stream.noBody);
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
for (;;) {
const { value, done } = await reader.read();
if (!done) onBytes();
buffer += decoder.decode(value ?? new Uint8Array(), { stream: !done });
const chunks = buffer.split("\n\n");
buffer = chunks.pop() ?? "";
for (const chunk of chunks) {
const line = chunk.split("\n").find((part) => part.startsWith("data: "));
if (!line) continue;
const frame = JSON.parse(line.slice(6)) as ChatStreamFrame;
onFrame(frame);
if (frame.type && TERMINAL.has(frame.type)) {
await reader.cancel().catch(() => {});
return frame;
}
}
if (done) throw new Error(errors.chat.stream.endedEarly);
}
}
+19 -23
View File
@@ -1,7 +1,6 @@
/**
* The suggested prompts shown beside the chat composer, keyed off the page
* the operator is on. The page identity is the same one the composer's page
* tag uses: the route's name, with the task id on a task detail page.
* the operator is on, chosen by the route's name.
*
* Prompts are questions an operator would actually ask on that page, not
* demonstrations of the feature.
@@ -17,22 +16,22 @@ export interface SuggestionRoute {
/** The pages that get their own prompt set. */
export type SuggestionPage =
| "task"
| "tasks"
| "run"
| "runs"
| "events"
| "workflows"
| "schedules"
| "settings"
| "default";
/** Which prompt set a route gets, by route name like the page tag's. */
/** Which prompt set a route gets, by route name. */
export function suggestionPage(route: SuggestionRoute): SuggestionPage {
const name = typeof route.name === "string" ? route.name : "";
switch (name) {
case "task-detail":
return "task";
case "tasks":
return "tasks";
case "run":
return "run";
case "runs":
return "runs";
case "events":
return "events";
case "workflows":
@@ -51,23 +50,20 @@ export function suggestionPage(route: SuggestionRoute): SuggestionPage {
return "default";
}
/** The prompts for a route; a task page names the task it is open on. */
/** The prompts for a route. */
export function suggestionsForRoute(route: SuggestionRoute): string[] {
switch (suggestionPage(route)) {
case "task": {
const id = route.params?.id;
const ref = id === undefined || id === "" ? "this task" : `task #${String(id)}`;
case "run":
return [
`What is ${ref} doing right now?`,
`Summarise what ${ref} did`,
`Which files did ${ref} change?`,
"What is this run doing right now?",
"Summarise what this run did",
"Why is this run waiting?",
];
}
case "tasks":
case "runs":
return [
"Which tasks are waiting on me?",
"Which runs are waiting on an approval?",
"What failed in the last hour?",
"Show tasks that need review",
"Which runs are still going?",
];
case "events":
return [
@@ -90,13 +86,13 @@ export function suggestionsForRoute(route: SuggestionRoute): string[] {
case "settings":
return [
"Which model is Archie using right now?",
"How do I connect a new repository?",
"Which connectors are set up?",
"Show recent access decisions",
];
default:
return [
"Summarise active tasks",
"Show running agents",
"Summarise today's runs",
"What is waiting on me?",
"Check system status",
];
}
-50
View File
@@ -1,50 +0,0 @@
import { api, ApiError } from "@/lib/api";
const FOUND_TTL_MS = 10 * 60_000;
const MISSING_TTL_MS = 30_000;
const lookups = new Map<number, { at: number; found: boolean }>();
const inflight = new Map<number, Promise<boolean | null>>();
/**
* Whether task `id` exists, asked of the tasks API. Answers are kept briefly
* so a reply that re-renders every frame asks once. A task that was missing a
* moment ago may have been created since, so that answer expires quickly. A
* failed lookup is null and is not kept: the reference stays plain text.
*/
export function taskExists(id: number): Promise<boolean | null> {
const known = lookups.get(id);
if (known && Date.now() - known.at < (known.found ? FOUND_TTL_MS : MISSING_TTL_MS))
return Promise.resolve(known.found);
let pending = inflight.get(id);
if (!pending) {
pending = api
.task(String(id))
.then(() => true)
.catch((err) => (err instanceof ApiError && err.status === 404 ? false : null))
.then((found) => {
if (found !== null) lookups.set(id, { at: Date.now(), found });
inflight.delete(id);
return found;
});
inflight.set(id, pending);
}
return pending;
}
const HIGHLIGHT = ["bg-primary-soft", "motion-safe:transition-colors", "motion-safe:duration-700"];
/**
* Scrolls to task `id`'s row when the page lists it and marks it once.
* Returns false when no such row is on screen.
*/
export function revealTaskRow(id: number): boolean {
const row = document.querySelector<HTMLElement>(`tr[data-row-key="${id}"]`);
if (!row) return false;
const still = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
row.scrollIntoView({ block: "center", behavior: still ? "auto" : "smooth" });
row.classList.add(...HIGHLIGHT);
window.setTimeout(() => row.classList.remove("bg-primary-soft"), 1600);
window.setTimeout(() => row.classList.remove(...HIGHLIGHT), 2400);
return true;
}
+48
View File
@@ -0,0 +1,48 @@
import { errors } from "@/copy/errors";
import type { ChatTurnRecord } from "@/lib/api";
import type { ChatAsk, ChatMessage, ChatToolCall } from "./types";
/** The turns as the transcript shows them: each message, then its reply. */
export function transcriptOf(turns: ChatTurnRecord[]): ChatMessage[] {
return turns.flatMap((turn): ChatMessage[] => [promptOf(turn), replyOf(turn)]);
}
export function promptOf(turn: ChatTurnRecord): ChatMessage {
return { from: "web", text: turn.text, message_id: `${turn.id}:in` };
}
function replyOf(turn: ChatTurnRecord): ChatMessage {
const end = Array.from(turn.reply).length;
const settled = new Map(turn.actions.map((a) => [a.request_id, a]));
const tools: ChatToolCall[] = [
...turn.tool_calls,
// Opened pages and answered approvals carry no offset, so they follow the reply.
...turn.navigate.map((n) => ({ ...n, text_offset: end })),
...turn.approvals.flatMap((a) => {
const done = settled.get(a.request_id);
if (!done) return [];
return [{
name: a.action,
text: done.result ? `${done.state}: ${done.result}` : done.state,
failed: !["approved", "running", "succeeded"].includes(done.state),
text_offset: end,
}];
}),
];
const message: ChatMessage = {
from: "assistant",
message_id: `${turn.id}:out`,
text: turn.reply,
tool_calls: tools,
approvals: turn.approvals.filter((a) => !settled.has(a.request_id)).map(askOf),
};
if (turn.state === "failed") {
return { ...message, text: turn.reply || turn.error || errors.chat.turn.failed, error: !turn.reply };
}
if (turn.state === "cancelled") return { ...message, text: turn.reply || "Stopped before replying." };
return message;
}
export function askOf(a: { request_id?: string; action?: string; summary?: string }): ChatAsk {
return { id: a.request_id ?? "", prompt: a.action ?? "", detail: a.summary };
}
-52
View File
@@ -1,52 +0,0 @@
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;
/** A recorded clip, base64, transcribed by the server. */
voice?: { data: string; mime_type: string };
}
function newChatTurn(text: string, voice?: ChatTurn["voice"]): ChatTurn {
return { text, sourceID: randomUUID(), voice };
}
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;
voice?: ChatTurn["voice"];
/** A turn the server already has: follow its stream instead of sending. */
follow?: string;
}
// 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, retry?.voice);
return { text, turn, isRetry };
}
+57
View File
@@ -0,0 +1,57 @@
/** One web conversation, as GET /api/chat/sessions lists it. */
export interface ChatSession {
session_id: string;
title?: string;
created_at?: string;
}
/**
* A tool the assistant called, or a page it opened. A recorded turn and a live
* `tool` frame carry the same fields; a `navigate` frame carries only `path`
* and `label` and renders as a link instead of a tool line.
*/
export interface ChatToolCall {
name?: string;
parameters?: string;
/** The tool's output, or its error when `failed` is set. */
text?: string;
failed?: boolean;
duration_ms?: number;
/** Runes of reply text before the call: where in the reply it happened. */
text_offset?: number;
path?: string;
label?: string;
}
/** An action a turn held for approval. */
export interface ChatAsk {
id: string;
prompt: string;
detail?: string;
}
/** One message in the transcript, from either side. */
export interface ChatMessage {
from: "web" | "assistant";
text: string;
message_id?: string;
tool_calls?: ChatToolCall[];
/** A reply standing in for a turn that failed; the bubble shows it as an error. */
error?: boolean;
/** Actions the turn held for approval that nobody has answered yet. */
approvals?: ChatAsk[];
}
/** A turn in flight: what it shows so far, and the text to resend if it fails. */
export interface StreamingTurn {
text: string;
tools: ChatToolCall[];
/** The model's thinking so far, streamed on `reasoning` frames. */
reasoning: string;
approvals: ChatAsk[];
/** The text sent, for Retry; absent when the turn cannot be retried. */
retryText?: string;
isError: boolean;
/** The operator stopped the turn; it is finished, not in flight. */
stopped: boolean;
}
+3 -8
View File
@@ -1,11 +1,11 @@
import { computed, ref, watch } from "vue";
import { isLoadingSession, messages, type ChatMessage } from "./state";
import { isLoadingSession, messages } 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 finished task's outcome while the dock is collapsed or the reader
* such as an approved action's outcome while the dock is collapsed or the reader
* is scrolled up, adds to the count until then.
*
* It counts replies by position, not by id: a streamed reply is appended
@@ -16,12 +16,7 @@ const dockOpen = ref(false);
const atEnd = ref(false);
const seen = ref(0);
function isReply(message: ChatMessage): boolean {
// Cards the operator's own command produced are not something Archie said.
return (message.from ?? message.From ?? "") !== "web" && !message.update && !message.choose;
}
const total = computed(() => messages.value.filter(isReply).length);
const total = computed(() => messages.value.filter((message) => message.from !== "web").length);
const viewing = computed(() => dockOpen.value && atEnd.value);
export const unseenCount = computed(() => Math.max(0, total.value - seen.value));
@@ -1,453 +0,0 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import type {
ItemRegistration,
QuestionnaireItemDefinition,
QuestionnaireShortcutMode,
} from './useQuestionnaire'
import { cn } from '@/lib/utils'
import { computed, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue'
import {
compareDocumentOrder,
createQuestionnaireCollection,
getInitialItemName,
getShortcutFromKey,
isAnswerFilled,
isRadioTarget,
isTextEntryTarget,
provideQuestionnaireRootContext,
} from './useQuestionnaire'
const props = withDefaults(defineProps<{
class?: HTMLAttributes['class']
/** Item shown first. Ignored when `item` is provided. */
defaultItem?: string
/** Controlled active item. Use with `v-model:item`. */
item?: string
/** Declares the item order, and the choice order shortcuts are assigned in. */
items?: readonly QuestionnaireItemDefinition[]
/** Set to `false` to run native constraint validation on answered items. */
noValidate?: boolean
/** Assigns a keyboard shortcut to every choice. */
shortcuts?: QuestionnaireShortcutMode
}>(), {
noValidate: true,
})
const emits = defineEmits<{
'reset': [event: Event]
'submit': [event: Event]
'update:item': [item: string]
}>()
interface PendingFocus {
name: string
target: 'invalid' | 'item'
}
const rootElement = ref<HTMLFormElement | null>(null)
const registrations = shallowRef<ItemRegistration[]>([])
const domVersion = ref(0)
const pendingFocus = shallowRef<PendingFocus | null>(null)
const collection = computed(() => createQuestionnaireCollection(props.items))
const uncontrolledItem = ref<string | null>(
getInitialItemName(collection.value, props.defaultItem),
)
const controlled = computed(() => props.item !== undefined)
const activeItemName = computed(() => (controlled.value ? props.item! : uncontrolledItem.value))
const shortcuts = computed(() => props.shortcuts ?? null)
const nativeValidation = computed(() => props.noValidate === false)
let previousActiveItemName = activeItemName.value
const runtimeItems = computed(() => {
// Re-sort whenever items are added to or removed from the DOM.
void domVersion.value
return registrations.value
.filter(registration => !registration.isDisabled())
.sort((first, second) => compareDocumentOrder(first.element, second.element))
})
const runtimeItemByName = computed(
() => new Map(runtimeItems.value.map(runtimeItem => [runtimeItem.name, runtimeItem])),
)
/** `items` is authoritative when provided, so items can be declared before they render. */
const logicalItems = computed<readonly { name: string }[]>(
() => collection.value?.enabledItems ?? runtimeItems.value,
)
const currentIndex = computed(
() => logicalItems.value.findIndex(logicalItem => logicalItem.name === activeItemName.value),
)
const activeItem = computed(() => {
if (currentIndex.value < 0 || !activeItemName.value) {
return null
}
return runtimeItemByName.value.get(activeItemName.value) ?? null
})
const activeDefinition = computed(() =>
activeItemName.value ? collection.value?.itemByName.get(activeItemName.value) : undefined,
)
const activeItemRequired = computed(() => {
if (currentIndex.value < 0) {
return null
}
return activeDefinition.value
? Boolean(activeDefinition.value.required)
: (activeItem.value?.isRequired() ?? false)
})
const activeItemStatus = computed(() => {
if (currentIndex.value < 0) {
return null
}
return activeItem.value?.status() ?? (activeItemName.value ? 'unanswered' : null)
})
const orderedRegistrations = computed(() => {
if (!collection.value) {
return runtimeItems.value
}
return collection.value.enabledItems.flatMap((definition) => {
const registration = runtimeItemByName.value.get(definition.name)
return registration ? [registration] : []
})
})
const total = computed(() => logicalItems.value.length)
const current = computed(() => (currentIndex.value < 0 ? 0 : currentIndex.value + 1))
const first = computed(() => total.value > 0 && currentIndex.value === 0)
const last = computed(() => total.value > 0 && currentIndex.value === total.value - 1)
function setItem(nextItem: string, focusTarget: PendingFocus['target'] = 'item') {
if (nextItem === activeItemName.value) {
return
}
pendingFocus.value = { name: nextItem, target: focusTarget }
if (!controlled.value) {
uncontrolledItem.value = nextItem
}
emits('update:item', nextItem)
}
function registerItem(registration: ItemRegistration) {
registrations.value = [
...registrations.value.filter(
current => current.element !== registration.element && current.name !== registration.name,
),
registration,
]
return () => {
registrations.value = registrations.value.filter(current => current !== registration)
}
}
function setItemAt(index: number, focusTarget: PendingFocus['target'] = 'item') {
const nextItem = logicalItems.value[index]
if (nextItem) {
setItem(nextItem.name, focusTarget)
}
}
function goPrevious() {
if (currentIndex.value <= 0) {
return
}
setItemAt(currentIndex.value - 1)
}
function goNext() {
if (!activeItem.value || currentIndex.value >= total.value - 1) {
return
}
if (!activeItem.value.validate()) {
activeItem.value.focusInvalid()
return
}
setItemAt(currentIndex.value + 1)
}
function confirmCurrent() {
if (!activeItem.value) {
return
}
if (!activeItem.value.validate()) {
activeItem.value.focusInvalid()
return
}
if (last.value) {
rootElement.value?.requestSubmit()
return
}
setItemAt(currentIndex.value + 1)
}
function skipCurrent() {
if (!activeItem.value || activeItem.value.isRequired()) {
return
}
activeItem.value.skip()
if (!last.value) {
setItemAt(currentIndex.value + 1)
return
}
queueMicrotask(() => {
rootElement.value?.requestSubmit()
})
}
function handleReset(event: Event) {
emits('reset', event)
if (event.defaultPrevented) {
return
}
for (const registration of registrations.value) {
registration.reset()
}
const resetItemName = collection.value
? getInitialItemName(collection.value, props.defaultItem)
: (runtimeItems.value.find(registration => registration.name === props.defaultItem)?.name
?? runtimeItems.value[0]?.name)
if (resetItemName) {
setItem(resetItemName)
}
}
function handleSubmit(event: Event) {
const firstInvalidItem = orderedRegistrations.value.find(registration => !registration.validate())
if (firstInvalidItem) {
event.preventDefault()
setItem(firstInvalidItem.name, 'invalid')
if (firstInvalidItem.name === activeItemName.value) {
firstInvalidItem.focusInvalid()
pendingFocus.value = null
}
return
}
emits('submit', event)
}
function handleKeydown(event: KeyboardEvent) {
if (
event.defaultPrevented
|| event.isComposing
|| event.keyCode === 229
|| !activeItem.value
|| !(event.target instanceof Element)
) {
return
}
if (event.key === 'Enter' && (event.metaKey || event.ctrlKey) && !event.altKey && !event.shiftKey) {
event.preventDefault()
if (!event.repeat) {
confirmCurrent()
}
return
}
if (event.metaKey || event.ctrlKey || event.altKey) {
return
}
if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
const moved = activeItem.value.moveAnswerFocus(
event.target,
event.key === 'ArrowDown' ? 'next' : 'previous',
)
if (moved) {
event.preventDefault()
return
}
}
if (
(event.key === 'ArrowLeft' || event.key === 'ArrowRight')
&& !isTextEntryTarget(event.target)
&& !isRadioTarget(event.target)
) {
event.preventDefault()
if (event.repeat) {
return
}
if (event.key === 'ArrowLeft') {
goPrevious()
}
else if (activeItem.value.status() !== 'unanswered') {
goNext()
}
return
}
if (event.key === 'Enter') {
const answer = activeItem.value.getAnswerByElement(event.target)
if (!answer) {
return
}
event.preventDefault()
if (!event.repeat && isAnswerFilled(answer)) {
confirmCurrent()
}
return
}
if (!shortcuts.value || isTextEntryTarget(event.target)) {
return
}
const shortcut = getShortcutFromKey(event.key, shortcuts.value)
const answer = shortcut ? activeItem.value.getAnswerByShortcut(shortcut) : null
if (!answer) {
return
}
event.preventDefault()
if (event.repeat) {
return
}
answer.element.focus()
if (answer.type === 'choice') {
answer.element.click()
}
}
watch(
() => [activeItemName.value, currentIndex.value, total.value, activeItem.value] as const,
() => {
if (total.value === 0) {
return
}
if (currentIndex.value < 0) {
const firstItem = logicalItems.value[0]
if (!firstItem) {
return
}
if (!controlled.value && activeItemName.value === null) {
uncontrolledItem.value = firstItem.name
return
}
setItem(firstItem.name)
return
}
const focus = pendingFocus.value
const activeItemChanged = previousActiveItemName !== activeItemName.value
previousActiveItemName = activeItemName.value
if (!focus || focus.name !== activeItemName.value) {
if (controlled.value && activeItemChanged) {
pendingFocus.value = null
activeItem.value?.focus()
}
return
}
if (focus.target === 'invalid') {
activeItem.value?.focusInvalid()
}
else {
activeItem.value?.focus()
}
pendingFocus.value = null
},
{ flush: 'post', immediate: true },
)
let observer: MutationObserver | null = null
onMounted(() => {
if (!rootElement.value || typeof MutationObserver === 'undefined') {
return
}
observer = new MutationObserver(() => {
domVersion.value += 1
})
observer.observe(rootElement.value, { childList: true, subtree: true })
})
onBeforeUnmount(() => {
observer?.disconnect()
observer = null
})
provideQuestionnaireRootContext({
activeItem,
activeItemName,
activeItemRequired,
activeItemStatus,
current,
domVersion,
first,
goNext,
goPrevious,
itemDefinitionByName: computed(() => collection.value?.itemByName ?? null),
last,
nativeValidation,
registerItem,
shortcuts,
skipCurrent,
total,
})
</script>
<template>
<form
ref="rootElement"
data-slot="questionnaire"
:data-shortcuts="shortcuts ?? undefined"
:novalidate="props.noValidate"
:class="cn('gap-4 flex w-full min-w-0 flex-col', props.class)"
@keydown="handleKeydown"
@reset="handleReset"
@submit="handleSubmit"
>
<slot :current="current" :first="first" :last="last" :total="total" />
</form>
</template>
@@ -1,26 +0,0 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
const props = withDefaults(defineProps<PrimitiveProps & {
class?: HTMLAttributes['class']
}>(), {
as: 'div',
})
</script>
<template>
<Primitive
data-slot="questionnaire-actions"
:as="props.as"
:as-child="props.asChild"
:class="cn(
'gap-2 sm:min-h-8 grid min-h-11 w-full grid-cols-[minmax(0,1fr)_auto_auto] items-center',
props.class,
)"
>
<slot />
</Primitive>
</template>
@@ -1,198 +0,0 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { CheckIcon } from '@lucide/vue'
import { cn } from '@/lib/utils'
import { computed, onBeforeUnmount, ref, useId, watch } from 'vue'
import { getAnswerKeyShortcuts, injectQuestionnaireItemContext } from './useQuestionnaire'
const props = withDefaults(defineProps<{
/** Controlled checked state. Use with `v-model:checked`. */
checked?: boolean
class?: HTMLAttributes['class']
/** Checks the choice on mount and after a native form reset. */
defaultChecked?: boolean
disabled?: boolean
/** Submitted as the answer of the parent item. */
value: string
}>(), {
// `undefined` keeps the choice uncontrolled. Without this default, Vue casts
// the absent boolean prop to `false` and every choice looks controlled.
checked: undefined,
defaultChecked: false,
disabled: false,
})
const emits = defineEmits<{
'change': [event: Event]
'update:checked': [checked: boolean]
}>()
const item = injectQuestionnaireItemContext()
const answerId = useId()
const inputElement = ref<HTMLInputElement | null>(null)
const initialDefaultChecked = props.defaultChecked
const controlled = computed(() => props.checked !== undefined)
const disabled = computed(() => item.disabled.value || props.disabled)
const selected = computed(() => item.selectedAnswerIds.value.includes(answerId))
const checked = computed(() => {
if (!controlled.value) {
return selected.value
}
// A skipped item clears every answer, including controlled ones.
return item.status.value === 'skipped' ? false : props.checked!
})
const type = computed(() => (item.multiple.value ? 'checkbox' : 'radio'))
const shortcut = computed(() =>
item.shortcutByChoiceValue.value?.get(props.value)
?? item.shortcutByAnswerId.value.get(answerId)
?? null)
function syncCheckedElement() {
if (inputElement.value && inputElement.value.checked !== checked.value) {
inputElement.value.checked = checked.value
}
}
function handleChange(event: Event) {
emits('change', event)
if (event.defaultPrevented) {
syncCheckedElement()
return
}
const nextChecked = (event.target as HTMLInputElement).checked
emits('update:checked', nextChecked)
if (!controlled.value) {
item.setAnswerSelectionFromInteraction(answerId, nextChecked)
return
}
// Re-selecting the same controlled choice has to clear the skipped state.
if (item.status.value === 'skipped' && props.checked === nextChecked) {
item.setAnswerSelectionFromInteraction(answerId, props.checked)
}
// Checking a radio clears its siblings, so the whole group has to re-sync in
// case the host keeps the previous answer.
item.requestControlSync()
}
const unregisterSelection = item.registerAnswerSelection(answerId, initialDefaultChecked)
let unregisterControl: (() => void) | null = null
watch([inputElement, disabled, () => props.disabled, () => props.value], ([element]) => {
unregisterControl?.()
unregisterControl = null
if (!element) {
return
}
unregisterControl = item.registerAnswerControl({
disabled: disabled.value,
element,
id: answerId,
ownDisabled: props.disabled,
type: 'choice',
value: props.value,
})
}, { flush: 'post' })
watch(() => props.defaultChecked, (defaultChecked) => {
item.setAnswerDefault(answerId, defaultChecked)
})
watch([() => props.checked, item.resetVersion], () => {
if (controlled.value) {
item.syncControlledAnswerSelection(answerId, props.checked!)
}
}, { immediate: true })
watch(item.controlSyncVersion, syncCheckedElement, { flush: 'post' })
watch([checked, inputElement, () => props.defaultChecked, item.resetVersion], () => {
if (!inputElement.value) {
return
}
// Keep the native reset target aligned with the questionnaire owned default,
// including controlled choices whose `checked` prop stays authoritative.
inputElement.value.defaultChecked = controlled.value ? props.checked! : props.defaultChecked
syncCheckedElement()
}, { flush: 'post' })
onBeforeUnmount(() => {
unregisterControl?.()
unregisterControl = null
unregisterSelection()
})
</script>
<template>
<label
data-slot="questionnaire-choice"
:data-checked="checked ? '' : undefined"
:data-disabled="disabled ? '' : undefined"
:data-invalid="item.invalid.value ? '' : undefined"
:data-shortcut="shortcut ?? undefined"
:data-type="type"
:data-unchecked="checked ? undefined : ''"
:class="cn(
'border-input dark:bg-input/20 hover:bg-muted/50 data-checked:border-primary/40 data-checked:bg-muted dark:data-checked:bg-muted data-invalid:border-destructive has-[>input:focus-visible]:border-ring has-[>input:focus-visible]:ring-ring gap-2.5 rounded-lg border bg-card px-3 py-2.5 text-label has-[>input:focus-visible]:ring-3 group/questionnaire-choice relative flex min-h-11 cursor-pointer items-start text-start transition-colors outline-none select-none',
'data-disabled:pointer-events-none data-disabled:cursor-not-allowed data-disabled:opacity-50',
props.class,
)"
>
<input
:id="answerId"
ref="inputElement"
data-slot="questionnaire-choice-input"
class="absolute inset-0 z-10 size-full cursor-pointer opacity-0"
:aria-invalid="item.invalid.value || undefined"
:aria-keyshortcuts="getAnswerKeyShortcuts(shortcut, !disabled && checked)"
:checked="checked"
:data-checked="checked ? '' : undefined"
:data-unchecked="checked ? undefined : ''"
:disabled="disabled"
:name="item.status.value === 'skipped' ? undefined : item.name.value"
:required="item.required.value && !item.multiple.value && !item.hasInputAnswer.value"
:type="type"
:value="props.value"
@change="handleChange"
>
<span
aria-hidden="true"
data-slot="questionnaire-choice-indicator"
class="border-input dark:bg-input/30 group-data-checked/questionnaire-choice:bg-primary dark:group-data-checked/questionnaire-choice:bg-primary group-data-checked/questionnaire-choice:text-primary-foreground group-data-checked/questionnaire-choice:border-primary size-4 translate-y-[--spacing(0.45)] group-has-data-[slot=questionnaire-choice-description]/questionnaire-choice:translate-y-0.5 rounded-[4px] pointer-events-none relative flex shrink-0 items-center justify-center border group-data-[type=radio]/questionnaire-choice:rounded-full"
>
<span
data-slot="questionnaire-choice-indicator-dot"
class="bg-primary-foreground size-2 hidden rounded-full group-data-[type=checkbox]/questionnaire-choice:hidden group-data-checked/questionnaire-choice:block"
/>
<CheckIcon data-slot="questionnaire-choice-indicator-check" class="size-3.5 hidden group-data-[type=radio]/questionnaire-choice:hidden group-data-checked/questionnaire-choice:block" />
</span>
<span
data-slot="questionnaire-choice-label"
class="gap-0.5 flex min-w-0 flex-1 flex-col leading-snug"
>
<slot :checked="checked" :disabled="disabled" :shortcut="shortcut" :type="type" />
</span>
<span
v-if="shortcut"
aria-hidden="true"
data-slot="questionnaire-choice-shortcut"
class="border-input bg-background text-muted-foreground size-5 translate-y-[--spacing(0.45)] group-has-data-[slot=questionnaire-choice-description]/questionnaire-choice:translate-y-0.5 items-center justify-center rounded-md border font-mono text-micro font-medium leading-none pointer-events-none ms-auto hidden shrink-0 group-data-[shortcut]/questionnaire-choice:inline-flex"
>
{{ shortcut }}
</span>
</label>
</template>
@@ -1,27 +0,0 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
import { injectQuestionnaireItemContext } from './useQuestionnaire'
const props = withDefaults(defineProps<PrimitiveProps & {
class?: HTMLAttributes['class']
}>(), {
as: 'div',
})
const item = injectQuestionnaireItemContext()
</script>
<template>
<Primitive
data-slot="questionnaire-choices"
:as="props.as"
:as-child="props.asChild"
:data-shortcuts="item.shortcuts.value ?? undefined"
:class="cn('gap-2 group/questionnaire-choices grid min-w-0', props.class)"
>
<slot :shortcuts="item.shortcuts.value" />
</Primitive>
</template>
@@ -1,59 +0,0 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { ComponentPublicInstance, HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
import { onBeforeUnmount, onMounted, ref, useId } from 'vue'
import { injectQuestionnaireItemContext } from './useQuestionnaire'
const props = withDefaults(defineProps<PrimitiveProps & {
class?: HTMLAttributes['class']
id?: string
}>(), {
as: 'p',
})
const item = injectQuestionnaireItemContext()
const primitiveRef = ref<ComponentPublicInstance | null>(null)
const fallbackId = props.id ?? useId()
const descriptionId = ref(fallbackId)
let unregisterDescription = item.registerDescription(descriptionId.value)
onMounted(() => {
// With `as-child` the rendered child can bring its own id, for example a
// DialogDescription. Adopt it so both descriptions point at one element.
const element = primitiveRef.value?.$el as HTMLElement | undefined
const renderedId = element?.id
if (!renderedId) {
if (element) {
element.id = fallbackId
}
return
}
if (renderedId !== descriptionId.value) {
unregisterDescription()
descriptionId.value = renderedId
unregisterDescription = item.registerDescription(renderedId)
}
})
onBeforeUnmount(() => unregisterDescription())
</script>
<template>
<Primitive
v-bind="props.asChild ? {} : { id: descriptionId }"
ref="primitiveRef"
data-slot="questionnaire-description"
:as="props.as"
:as-child="props.asChild"
:class="cn('text-label text-pretty text-muted-foreground', props.class)"
>
<slot />
</Primitive>
</template>
@@ -1,44 +0,0 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
import { computed, onBeforeUnmount, useId } from 'vue'
import { injectQuestionnaireItemContext } from './useQuestionnaire'
const props = withDefaults(defineProps<PrimitiveProps & {
class?: HTMLAttributes['class']
id?: string
}>(), {
as: 'p',
})
const item = injectQuestionnaireItemContext()
const errorId = props.id ?? useId()
const unregisterError = item.registerError(errorId)
const fallback = computed(() =>
item.required.value
? 'Choose an answer to continue.'
: 'Choose an answer or skip this question.')
onBeforeUnmount(unregisterError)
</script>
<template>
<Primitive
:id="errorId"
data-slot="questionnaire-error"
:as="props.as"
:as-child="props.asChild"
:data-invalid="item.invalid.value ? '' : undefined"
:hidden="!item.invalid.value"
:role="item.invalid.value ? 'alert' : undefined"
:class="cn('mt-2 text-label text-destructive', props.class)"
>
<slot :invalid="item.invalid.value">
{{ fallback }}
</slot>
</Primitive>
</template>
@@ -1,160 +0,0 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import type { QuestionnaireInputType } from './useQuestionnaire'
import { cn } from '@/lib/utils'
import { computed, nextTick, onBeforeUnmount, ref, useId, watch } from 'vue'
import {
getAnswerKeyShortcuts,
hasInputValue,
injectQuestionnaireItemContext,
} from './useQuestionnaire'
defineOptions({
// The wrapper is the root element, so attributes have to reach the input.
inheritAttrs: false,
})
const props = withDefaults(defineProps<{
class?: HTMLAttributes['class']
/** Fills the answer on mount and after a native form reset. */
defaultValue?: string | number
disabled?: boolean
/** Controlled value. Use with `v-model`. */
modelValue?: string | number
type?: QuestionnaireInputType
}>(), {
disabled: false,
type: 'text',
})
const emits = defineEmits<{
'update:modelValue': [value: string]
}>()
const item = injectQuestionnaireItemContext()
const answerId = useId()
const inputElement = ref<HTMLInputElement | null>(null)
const initialDefaultFilled = hasInputValue(props.defaultValue)
const uncontrolledValue = ref(String(props.defaultValue ?? ''))
const controlled = computed(() => props.modelValue !== undefined)
const defaultFilled = computed(() => hasInputValue(props.defaultValue))
const disabled = computed(() => item.disabled.value || props.disabled)
// Vue re-applies `value` on every render, so the input always renders the value
// the questionnaire owns instead of an undefined binding that would clear it.
const value = computed(() =>
controlled.value ? String(props.modelValue ?? '') : uncontrolledValue.value)
const filled = computed(() => hasInputValue(value.value))
const selected = computed(() => item.selectedAnswerIds.value.includes(answerId))
function syncValueElement() {
if (inputElement.value && inputElement.value.value !== value.value) {
inputElement.value.value = value.value
}
}
function handleInput(event: Event) {
const nextValue = (event.target as HTMLInputElement).value
emits('update:modelValue', nextValue)
if (controlled.value) {
// The host owns the value, so restore whatever it kept.
nextTick(syncValueElement)
return
}
uncontrolledValue.value = nextValue
item.setAnswerSelectionFromInteraction(answerId, hasInputValue(nextValue))
}
const unregisterSelection = item.registerAnswerSelection(answerId, initialDefaultFilled)
let unregisterControl: (() => void) | null = null
watch([inputElement, disabled, () => props.disabled], ([element]) => {
unregisterControl?.()
unregisterControl = null
if (!element) {
return
}
unregisterControl = item.registerAnswerControl({
disabled: disabled.value,
element,
id: answerId,
ownDisabled: props.disabled,
type: 'input',
value: '',
})
}, { flush: 'post' })
watch(defaultFilled, (nextDefaultFilled) => {
item.setAnswerDefault(answerId, nextDefaultFilled)
})
// Watching the value as well as `filled` lets a host update clear the skipped
// state even when the answer stays filled.
watch([value, filled], () => {
if (controlled.value) {
item.syncControlledAnswerSelection(answerId, filled.value)
}
}, { immediate: true })
watch(item.resetVersion, () => {
if (!controlled.value) {
uncontrolledValue.value = String(props.defaultValue ?? '')
}
})
watch([value, inputElement], () => {
if (!inputElement.value) {
return
}
// A native form reset restores `defaultValue`, so keep it in sync with the
// value the questionnaire owns.
inputElement.value.defaultValue = String(
(controlled.value ? props.modelValue : props.defaultValue) ?? '',
)
}, { flush: 'post' })
onBeforeUnmount(() => {
unregisterControl?.()
unregisterControl = null
unregisterSelection()
})
</script>
<template>
<div
data-slot="questionnaire-input-wrapper"
class="w-full group/questionnaire-input relative min-w-0"
>
<input
v-bind="$attrs"
:id="answerId"
ref="inputElement"
data-slot="questionnaire-input"
:aria-invalid="item.invalid.value || undefined"
:aria-keyshortcuts="getAnswerKeyShortcuts(null, !disabled && filled && selected)"
:data-disabled="disabled ? '' : undefined"
:data-empty="filled ? undefined : ''"
:data-filled="filled ? '' : undefined"
:data-invalid="item.invalid.value ? '' : undefined"
:disabled="disabled"
:form="selected ? undefined : ''"
:name="selected ? item.name.value : undefined"
:type="props.type"
:value="value"
:class="cn(
'dark:bg-input/30 border-input focus-visible:border-ring focus-visible:ring-ring aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:aria-invalid:border-destructive/50 disabled:bg-input/50 dark:disabled:bg-input/80 h-8 rounded-lg border bg-card px-2.5 py-1 text-title focus-visible:ring-3 aria-invalid:ring-3 md:text-label min-h-11 w-full min-w-0 transition-[color,box-shadow,background-color] outline-none disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 sm:min-h-0',
'selection:bg-primary selection:text-primary-foreground placeholder:text-muted-foreground',
props.class,
)"
@input="handleInput"
>
</div>
</template>
@@ -1,467 +0,0 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import type { AnswerControlRegistration, QuestionnaireItemStatus } from './useQuestionnaire'
import { cn } from '@/lib/utils'
import { computed, onBeforeUnmount, ref, shallowRef, useAttrs, watch } from 'vue'
import {
compareDocumentOrder,
getShortcutByChoiceValue,
getShortcutKeys,
injectQuestionnaireRootContext,
isAnswerFilled,
isEmptyNavigableInput,
isRadioTarget,
isTextEntryTarget,
provideQuestionnaireItemContext,
} from './useQuestionnaire'
defineOptions({
inheritAttrs: false,
})
const props = withDefaults(defineProps<{
class?: HTMLAttributes['class']
/** Excludes the item from the questionnaire without unmounting it. */
disabled?: boolean
/** Marks the item invalid from outside, for example after schema validation. */
invalid?: boolean
/** Renders choices as checkboxes and keeps every selected answer. */
multiple?: boolean
/** Submitted under this name, and used to activate the item. */
name: string
/** Requires an answer before the questionnaire can continue. */
required?: boolean
}>(), {
disabled: false,
invalid: false,
multiple: false,
required: false,
})
const emits = defineEmits<{
'update:status': [status: QuestionnaireItemStatus]
}>()
const attrs = useAttrs()
const root = injectQuestionnaireRootContext()
const itemElement = ref<HTMLFieldSetElement | null>(null)
const answerControls = shallowRef<AnswerControlRegistration[]>([])
const selectedAnswerIds = ref<string[]>([])
const validationAttempted = ref(false)
const skipped = ref(false)
const resetVersion = ref(0)
const controlSyncVersion = ref(0)
const descriptionIds = ref<string[]>([])
const errorIds = ref<string[]>([])
const titleIds = ref<string[]>([])
let defaultSelectedAnswerIds: string[] = []
const active = computed(() => !props.disabled && root.activeItemName.value === props.name)
const orderedAnswerControls = computed(() => {
// Re-sort whenever answers are added to or removed from the DOM.
void root.domVersion.value
return [...answerControls.value].sort((first, second) =>
compareDocumentOrder(first.element, second.element))
})
const answers = computed(() => orderedAnswerControls.value.filter(answer => !answer.disabled))
const answered = computed(() =>
answers.value.some(answer => selectedAnswerIds.value.includes(answer.id)))
const status = computed<QuestionnaireItemStatus>(() => {
if (skipped.value) {
return 'skipped'
}
return answered.value ? 'answered' : 'unanswered'
})
const intentionallySkipped = computed(() => status.value === 'skipped' && !props.required)
const valid = computed(() =>
props.disabled
|| intentionallySkipped.value
|| (!props.invalid && status.value === 'answered'))
const invalid = computed(() =>
!props.disabled
&& !intentionallySkipped.value
&& (props.invalid || (validationAttempted.value && !valid.value)))
const hasInputAnswer = computed(() => answers.value.some(answer => answer.type === 'input'))
const itemDefinition = computed(() => root.itemDefinitionByName.value?.get(props.name))
const shortcutByChoiceValue = computed(() =>
root.itemDefinitionByName.value
? getShortcutByChoiceValue(itemDefinition.value, root.shortcuts.value)
: null)
const shortcutByAnswerId = computed(() => {
// Choice values from `items` take precedence, so shortcuts stay stable.
if (shortcutByChoiceValue.value) {
return new Map<string, string>()
}
const keys = getShortcutKeys(root.shortcuts.value)
const shortcutAnswers = answers.value.filter(answer => answer.type === 'choice')
return new Map(
shortcutAnswers
.slice(0, keys.length)
.flatMap((answer, index) => (keys[index] ? [[answer.id, keys[index]!] as const] : [])),
)
})
// Only set when the title does not render as the legend, which already names
// the fieldset on its own.
const labelledBy = computed(() =>
[...titleIds.value, attrs['aria-labelledby']].filter(Boolean).join(' ') || undefined)
const describedBy = computed(() =>
[...descriptionIds.value, ...(invalid.value ? errorIds.value : []), attrs['aria-describedby']]
.filter(Boolean)
.join(' ') || undefined)
const keyShortcuts = computed(() =>
[
attrs['aria-keyshortcuts'],
active.value ? 'Meta+Enter Control+Enter' : undefined,
active.value && answers.value.length ? 'ArrowUp ArrowDown' : undefined,
active.value && !root.first.value ? 'ArrowLeft' : undefined,
active.value && !root.last.value && status.value !== 'unanswered' ? 'ArrowRight' : undefined,
]
.filter(Boolean)
.join(' ') || undefined)
function updateAnswerSelected(answerId: string, selected: boolean) {
if (!selected) {
selectedAnswerIds.value = selectedAnswerIds.value.filter(current => current !== answerId)
return
}
if (!props.multiple) {
selectedAnswerIds.value = [answerId]
return
}
if (!selectedAnswerIds.value.includes(answerId)) {
selectedAnswerIds.value = [...selectedAnswerIds.value, answerId]
}
}
function setAnswerSelectionFromInteraction(answerId: string, selected: boolean) {
skipped.value = false
updateAnswerSelected(answerId, selected)
}
function syncControlledAnswerSelection(answerId: string, selected: boolean) {
if (selected) {
skipped.value = false
}
updateAnswerSelected(answerId, selected)
}
function registerAnswerSelection(answerId: string, defaultSelected: boolean) {
if (defaultSelected) {
defaultSelectedAnswerIds = [
...defaultSelectedAnswerIds.filter(current => current !== answerId),
answerId,
]
if (!props.multiple) {
if (!selectedAnswerIds.value.length) {
selectedAnswerIds.value = [answerId]
}
}
else if (!selectedAnswerIds.value.includes(answerId)) {
selectedAnswerIds.value = [...selectedAnswerIds.value, answerId]
}
}
return () => {
defaultSelectedAnswerIds = defaultSelectedAnswerIds.filter(current => current !== answerId)
selectedAnswerIds.value = selectedAnswerIds.value.filter(current => current !== answerId)
}
}
function setAnswerDefault(answerId: string, defaultSelected: boolean) {
if (defaultSelected) {
if (!defaultSelectedAnswerIds.includes(answerId)) {
defaultSelectedAnswerIds = [...defaultSelectedAnswerIds, answerId]
}
return
}
defaultSelectedAnswerIds = defaultSelectedAnswerIds.filter(current => current !== answerId)
}
/**
* Selecting a controlled choice clears the native checked state of the other
* choices in the group, so every control re-syncs after an interaction the host
* may have rejected.
*/
function requestControlSync() {
controlSyncVersion.value += 1
}
function registerAnswerControl(registration: AnswerControlRegistration) {
answerControls.value = [
...answerControls.value.filter(
current => current.element !== registration.element && current.id !== registration.id,
),
registration,
]
return () => {
answerControls.value = answerControls.value.filter(current => current !== registration)
}
}
function registerDescription(descriptionId: string) {
if (!descriptionIds.value.includes(descriptionId)) {
descriptionIds.value = [...descriptionIds.value, descriptionId]
}
return () => {
descriptionIds.value = descriptionIds.value.filter(current => current !== descriptionId)
}
}
function registerTitle(titleId: string) {
if (!titleIds.value.includes(titleId)) {
titleIds.value = [...titleIds.value, titleId]
}
return () => {
titleIds.value = titleIds.value.filter(current => current !== titleId)
}
}
function registerError(errorId: string) {
if (!errorIds.value.includes(errorId)) {
errorIds.value = [...errorIds.value, errorId]
}
return () => {
errorIds.value = errorIds.value.filter(current => current !== errorId)
}
}
function validate() {
validationAttempted.value = true
if (!valid.value) {
return false
}
if (!root.nativeValidation.value) {
return true
}
const invalidAnswer = answers.value.find(
answer =>
isAnswerFilled(answer) && answer.element.willValidate && !answer.element.validity.valid,
)
if (!invalidAnswer) {
return true
}
invalidAnswer.element.focus()
invalidAnswer.element.reportValidity()
return false
}
function focus() {
itemElement.value?.focus()
}
function focusInvalid() {
const selectedInput = itemElement.value?.querySelector<HTMLInputElement>(
'input[data-filled][name]:not(:disabled)',
)
const firstControl = itemElement.value?.querySelector<HTMLElement>(
'input:not([type=hidden]):not(:disabled), textarea:not(:disabled)',
)
;(selectedInput ?? firstControl ?? itemElement.value)?.focus()
}
function reset() {
validationAttempted.value = false
skipped.value = false
selectedAnswerIds.value = props.multiple
? [...defaultSelectedAnswerIds]
: defaultSelectedAnswerIds.slice(0, 1)
resetVersion.value += 1
}
function skip() {
if (props.required) {
return
}
selectedAnswerIds.value = []
skipped.value = true
}
function getAnswerByElement(element: Element) {
return answers.value.find(answer => answer.element === element) ?? null
}
function getAnswerByShortcut(shortcut: string) {
if (shortcutByChoiceValue.value) {
const choiceValue = Array.from(shortcutByChoiceValue.value.entries()).find(
([, choiceShortcut]) => choiceShortcut === shortcut,
)?.[0]
return (
answers.value.find(answer => answer.type === 'choice' && answer.value === choiceValue) ?? null
)
}
const answerId = Array.from(shortcutByAnswerId.value.entries()).find(
([, answerShortcut]) => answerShortcut === shortcut,
)?.[0]
return answers.value.find(answer => answer.id === answerId) ?? null
}
function moveAnswerFocus(currentElement: Element, direction: 'next' | 'previous') {
const currentIndex = answers.value.findIndex(answer => answer.element === currentElement)
const currentAnswer = currentIndex < 0 ? null : (answers.value[currentIndex] ?? null)
if (
!answers.value.length
|| (isTextEntryTarget(currentElement) && !isEmptyNavigableInput(currentAnswer))
|| (currentIndex < 0 && currentElement !== itemElement.value)
) {
return false
}
const nextAnswer
= currentIndex < 0
? (answers.value.find(isAnswerFilled)
?? (direction === 'next' ? answers.value[0] : answers.value[answers.value.length - 1]))
: answers.value[
(currentIndex + (direction === 'next' ? 1 : -1) + answers.value.length)
% answers.value.length
]
if (!nextAnswer || nextAnswer.element === currentElement) {
return false
}
// Radio groups already move focus with the arrow keys.
if (
currentIndex >= 0
&& isRadioTarget(currentElement)
&& isRadioTarget(nextAnswer.element)
) {
return false
}
nextAnswer.element.focus()
if (nextAnswer.type === 'choice' && isRadioTarget(nextAnswer.element)) {
nextAnswer.element.click()
}
return true
}
watch(status, (nextStatus) => {
emits('update:status', nextStatus)
})
watch(() => props.multiple, (multiple, wasMultiple) => {
if (!wasMultiple || multiple) {
return
}
const selectedAnswer = answers.value.find(answer => selectedAnswerIds.value.includes(answer.id))
selectedAnswerIds.value = selectedAnswer ? [selectedAnswer.id] : []
})
let unregisterItem: (() => void) | null = null
watch([itemElement, () => props.name], ([element, name]) => {
unregisterItem?.()
unregisterItem = null
if (!element) {
return
}
unregisterItem = root.registerItem({
element,
focus,
focusInvalid,
getAnswerByElement,
getAnswerByShortcut,
getChoices: () =>
orderedAnswerControls.value.flatMap(answer =>
answer.type === 'choice' ? [{ disabled: answer.ownDisabled, value: answer.value }] : []),
isDisabled: () => props.disabled,
isRequired: () => props.required,
moveAnswerFocus,
name,
reset,
skip,
status: () => status.value,
validate,
})
}, { flush: 'post' })
onBeforeUnmount(() => {
unregisterItem?.()
unregisterItem = null
})
provideQuestionnaireItemContext({
active,
controlSyncVersion,
disabled: computed(() => props.disabled),
hasInputAnswer,
invalid,
multiple: computed(() => props.multiple),
name: computed(() => props.name),
registerAnswerControl,
registerAnswerSelection,
registerDescription,
registerError,
registerTitle,
requestControlSync,
required: computed(() => props.required),
resetVersion,
selectedAnswerIds,
setAnswerDefault,
setAnswerSelectionFromInteraction,
shortcutByAnswerId,
shortcutByChoiceValue,
shortcuts: root.shortcuts,
status,
syncControlledAnswerSelection,
})
</script>
<template>
<fieldset
v-bind="attrs"
ref="itemElement"
data-slot="questionnaire-item"
:aria-describedby="describedBy"
:aria-invalid="invalid || undefined"
:aria-keyshortcuts="keyShortcuts"
:aria-labelledby="labelledBy"
:data-active="active ? '' : undefined"
:data-disabled="props.disabled ? '' : undefined"
:data-invalid="invalid ? '' : undefined"
:data-multiple="props.multiple ? '' : undefined"
:data-required="props.required ? '' : undefined"
:data-status="status"
:disabled="props.disabled"
:hidden="!active"
:inert="!active"
tabindex="-1"
:class="cn('flex flex-col gap-4 min-w-0 border-0 p-0 outline-none', props.class)"
>
<slot :active="active" :invalid="invalid" :status="status" />
</fieldset>
</template>
@@ -1,77 +0,0 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import type { ButtonVariants } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
import { computed } from 'vue'
import { buttonVariants } from '@/components/ui/button'
import { injectQuestionnaireRootContext } from './useQuestionnaire'
const props = withDefaults(defineProps<PrimitiveProps & {
class?: HTMLAttributes['class']
disabled?: boolean
size?: ButtonVariants['size']
variant?: ButtonVariants['variant']
}>(), {
as: 'button',
disabled: false,
size: 'default',
variant: 'default',
})
const emits = defineEmits<{
click: [event: MouseEvent]
}>()
const root = injectQuestionnaireRootContext()
const visible = computed(() => root.total.value > 1 && !root.last.value)
const shortcut = computed(() => (visible.value && !props.disabled ? 'Enter' : null))
function handleClick(event: MouseEvent) {
emits('click', event)
// `disabled` does not block clicks once `as` or `as-child` renders something
// other than a button.
if (props.disabled) {
event.preventDefault()
return
}
if (!event.defaultPrevented) {
root.goNext()
}
}
</script>
<template>
<Primitive
data-slot="questionnaire-next"
type="button"
:aria-hidden="!visible || undefined"
:aria-disabled="props.disabled || undefined"
:aria-keyshortcuts="shortcut ?? undefined"
:as="props.as"
:as-child="props.asChild"
:data-disabled="props.disabled ? '' : undefined"
:data-hidden="visible ? undefined : ''"
:data-shortcut="shortcut ?? undefined"
:data-size="props.size"
:data-status="root.activeItemStatus.value ?? undefined"
:data-variant="props.variant"
:data-visible="visible ? '' : undefined"
:disabled="props.disabled"
:hidden="!visible"
:inert="!visible"
:tabindex="visible ? undefined : -1"
:class="cn(
buttonVariants({ size: props.size, variant: props.variant }),
'col-start-3 row-start-1 min-h-11 justify-self-end sm:min-h-0',
props.class,
)"
@click="handleClick"
>
<slot>Next</slot>
</Primitive>
</template>
@@ -1,74 +0,0 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import type { ButtonVariants } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
import { computed } from 'vue'
import { buttonVariants } from '@/components/ui/button'
import { injectQuestionnaireRootContext } from './useQuestionnaire'
const props = withDefaults(defineProps<PrimitiveProps & {
class?: HTMLAttributes['class']
disabled?: boolean
size?: ButtonVariants['size']
variant?: ButtonVariants['variant']
}>(), {
as: 'button',
disabled: false,
size: 'default',
variant: 'outline',
})
const emits = defineEmits<{
click: [event: MouseEvent]
}>()
const root = injectQuestionnaireRootContext()
const visible = computed(() => root.total.value > 1 && !root.first.value)
function handleClick(event: MouseEvent) {
emits('click', event)
// `disabled` does not block clicks once `as` or `as-child` renders something
// other than a button.
if (props.disabled) {
event.preventDefault()
return
}
if (!event.defaultPrevented) {
root.goPrevious()
}
}
</script>
<template>
<Primitive
data-slot="questionnaire-previous"
type="button"
:aria-hidden="!visible || undefined"
:aria-disabled="props.disabled || undefined"
:as="props.as"
:as-child="props.asChild"
:data-disabled="props.disabled ? '' : undefined"
:data-hidden="visible ? undefined : ''"
:data-size="props.size"
:data-status="root.activeItemStatus.value ?? undefined"
:data-variant="props.variant"
:data-visible="visible ? '' : undefined"
:disabled="props.disabled"
:hidden="!visible"
:inert="!visible"
:tabindex="visible ? undefined : -1"
:class="cn(
buttonVariants({ size: props.size, variant: props.variant }),
'col-start-1 row-start-1 min-h-11 justify-self-start sm:min-h-0',
props.class,
)"
@click="handleClick"
>
<slot>Previous</slot>
</Primitive>
</template>
@@ -1,51 +0,0 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
import { computed } from 'vue'
import { injectQuestionnaireRootContext } from './useQuestionnaire'
const props = withDefaults(defineProps<PrimitiveProps & {
class?: HTMLAttributes['class']
}>(), {
as: 'div',
})
const root = injectQuestionnaireRootContext()
const label = computed(() =>
root.total.value ? `Question ${root.current.value} of ${root.total.value}` : undefined)
</script>
<template>
<Primitive
aria-label="Questionnaire progress"
aria-live="polite"
data-slot="questionnaire-progress"
role="progressbar"
:aria-valuemax="root.total.value || undefined"
:aria-valuemin="root.total.value ? 1 : undefined"
:aria-valuenow="root.total.value ? root.current.value : undefined"
:aria-valuetext="label"
:as="props.as"
:as-child="props.asChild"
:data-current="root.current.value"
:data-first="root.first.value ? '' : undefined"
:data-last="root.last.value ? '' : undefined"
:data-total="root.total.value"
:class="cn(
'text-caption min-h-[1lh] w-fit min-w-[14ch] font-medium text-muted-foreground tabular-nums',
props.class,
)"
>
<slot
:current="root.current.value"
:first="root.first.value"
:last="root.last.value"
:total="root.total.value"
>
{{ label }}
</slot>
</Primitive>
</template>
@@ -1,74 +0,0 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import type { ButtonVariants } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
import { computed } from 'vue'
import { buttonVariants } from '@/components/ui/button'
import { injectQuestionnaireRootContext } from './useQuestionnaire'
const props = withDefaults(defineProps<PrimitiveProps & {
class?: HTMLAttributes['class']
disabled?: boolean
size?: ButtonVariants['size']
variant?: ButtonVariants['variant']
}>(), {
as: 'button',
disabled: false,
size: 'default',
variant: 'outline',
})
const emits = defineEmits<{
click: [event: MouseEvent]
}>()
const root = injectQuestionnaireRootContext()
const visible = computed(() => root.activeItemRequired.value === false)
function handleClick(event: MouseEvent) {
emits('click', event)
// `disabled` does not block clicks once `as` or `as-child` renders something
// other than a button.
if (props.disabled) {
event.preventDefault()
return
}
if (!event.defaultPrevented) {
root.skipCurrent()
}
}
</script>
<template>
<Primitive
data-slot="questionnaire-skip"
type="button"
:aria-hidden="!visible || undefined"
:aria-disabled="props.disabled || undefined"
:as="props.as"
:as-child="props.asChild"
:data-disabled="props.disabled ? '' : undefined"
:data-hidden="visible ? undefined : ''"
:data-size="props.size"
:data-status="root.activeItemStatus.value ?? undefined"
:data-variant="props.variant"
:data-visible="visible ? '' : undefined"
:disabled="props.disabled"
:hidden="!visible"
:inert="!visible"
:tabindex="visible ? undefined : -1"
:class="cn(
buttonVariants({ size: props.size, variant: props.variant }),
'col-start-2 row-start-1 min-h-11 justify-self-end sm:min-h-0',
props.class,
)"
@click="handleClick"
>
<slot>Skip</slot>
</Primitive>
</template>
@@ -1,57 +0,0 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import type { ButtonVariants } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
import { computed } from 'vue'
import { buttonVariants } from '@/components/ui/button'
import { injectQuestionnaireRootContext } from './useQuestionnaire'
const props = withDefaults(defineProps<PrimitiveProps & {
class?: HTMLAttributes['class']
disabled?: boolean
size?: ButtonVariants['size']
variant?: ButtonVariants['variant']
}>(), {
as: 'button',
disabled: false,
size: 'default',
variant: 'default',
})
const root = injectQuestionnaireRootContext()
const visible = computed(() => root.total.value > 0 && root.last.value)
const shortcut = computed(() => (visible.value && !props.disabled ? 'Enter' : null))
</script>
<template>
<Primitive
data-slot="questionnaire-submit"
type="submit"
:aria-hidden="!visible || undefined"
:aria-disabled="props.disabled || undefined"
:aria-keyshortcuts="shortcut ?? undefined"
:as="props.as"
:as-child="props.asChild"
:data-disabled="props.disabled ? '' : undefined"
:data-hidden="visible ? undefined : ''"
:data-shortcut="shortcut ?? undefined"
:data-size="props.size"
:data-status="root.activeItemStatus.value ?? undefined"
:data-variant="props.variant"
:data-visible="visible ? '' : undefined"
:disabled="props.disabled"
:hidden="!visible"
:inert="!visible"
:tabindex="visible ? undefined : -1"
:class="cn(
buttonVariants({ size: props.size, variant: props.variant }),
'col-start-3 row-start-1 min-h-11 justify-self-end sm:min-h-0',
props.class,
)"
>
<slot>Submit</slot>
</Primitive>
</template>
@@ -1,53 +0,0 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { ComponentPublicInstance, HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
import { onBeforeUnmount, onMounted, ref, useId } from 'vue'
import { injectQuestionnaireItemContext } from './useQuestionnaire'
const props = withDefaults(defineProps<PrimitiveProps & {
class?: HTMLAttributes['class']
id?: string
}>(), {
as: 'legend',
})
const item = injectQuestionnaireItemContext()
const primitiveRef = ref<ComponentPublicInstance | null>(null)
const fallbackId = props.id ?? useId()
let unregisterTitle: (() => void) | null = null
onMounted(() => {
const element = primitiveRef.value?.$el as HTMLElement | undefined
// A legend already names the fieldset. Anything else, for example a
// DialogTitle rendered through `as-child`, has to name it explicitly.
if (!element || element.tagName === 'LEGEND') {
return
}
if (!element.id) {
element.id = fallbackId
}
unregisterTitle = item.registerTitle(element.id)
})
onBeforeUnmount(() => unregisterTitle?.())
</script>
<template>
<Primitive
v-bind="props.id ? { id: props.id } : {}"
ref="primitiveRef"
data-slot="questionnaire-title"
:as="props.as"
:as-child="props.asChild"
:class="cn('text-title leading-snug font-medium [&:not(:has(~[data-slot=questionnaire-description]))]:mb-4 text-pretty', props.class)"
>
<slot />
</Primitive>
</template>
@@ -1,15 +0,0 @@
export { default as Questionnaire } from './Questionnaire.vue'
export { default as QuestionnaireActions } from './QuestionnaireActions.vue'
export { default as QuestionnaireChoice } from './QuestionnaireChoice.vue'
export { default as QuestionnaireChoices } from './QuestionnaireChoices.vue'
export { default as QuestionnaireDescription } from './QuestionnaireDescription.vue'
export { default as QuestionnaireError } from './QuestionnaireError.vue'
export { default as QuestionnaireInput } from './QuestionnaireInput.vue'
export { default as QuestionnaireItem } from './QuestionnaireItem.vue'
export { default as QuestionnaireNext } from './QuestionnaireNext.vue'
export { default as QuestionnairePrevious } from './QuestionnairePrevious.vue'
export { default as QuestionnaireProgress } from './QuestionnaireProgress.vue'
export { default as QuestionnaireSkip } from './QuestionnaireSkip.vue'
export { default as QuestionnaireSubmit } from './QuestionnaireSubmit.vue'
export { default as QuestionnaireTitle } from './QuestionnaireTitle.vue'
@@ -1,271 +0,0 @@
import type { ComputedRef, Ref } from 'vue'
import { createContext } from 'reka-ui'
export type QuestionnaireItemStatus = 'unanswered' | 'answered' | 'skipped'
export type QuestionnaireShortcutMode = 'letters' | 'numbers'
export type QuestionnaireInputType
= | 'date'
| 'datetime-local'
| 'email'
| 'month'
| 'number'
| 'password'
| 'search'
| 'tel'
| 'text'
| 'time'
| 'url'
| 'week'
interface QuestionnaireChoiceDefinition {
disabled?: boolean
value: string
}
export interface QuestionnaireItemDefinition {
choices?: readonly QuestionnaireChoiceDefinition[]
disabled?: boolean
name: string
required?: boolean
}
interface ChoiceRegistration {
disabled: boolean
value: string
}
export interface AnswerControlRegistration {
disabled: boolean
element: HTMLInputElement
id: string
ownDisabled: boolean
type: 'choice' | 'input'
value: string
}
export interface ItemRegistration {
element: HTMLFieldSetElement
focus: () => void
focusInvalid: () => void
getAnswerByElement: (element: Element) => AnswerControlRegistration | null
getAnswerByShortcut: (shortcut: string) => AnswerControlRegistration | null
getChoices: () => ChoiceRegistration[]
isDisabled: () => boolean
isRequired: () => boolean
moveAnswerFocus: (element: Element, direction: 'next' | 'previous') => boolean
name: string
reset: () => void
skip: () => void
status: () => QuestionnaireItemStatus
validate: () => boolean
}
export interface QuestionnaireRootContext {
activeItem: ComputedRef<ItemRegistration | null>
activeItemName: ComputedRef<string | null>
activeItemRequired: ComputedRef<boolean | null>
activeItemStatus: ComputedRef<QuestionnaireItemStatus | null>
current: ComputedRef<number>
domVersion: Ref<number>
first: ComputedRef<boolean>
goNext: () => void
goPrevious: () => void
itemDefinitionByName: ComputedRef<Map<string, QuestionnaireItemDefinition> | null>
last: ComputedRef<boolean>
nativeValidation: ComputedRef<boolean>
registerItem: (registration: ItemRegistration) => () => void
shortcuts: ComputedRef<QuestionnaireShortcutMode | null>
skipCurrent: () => void
total: ComputedRef<number>
}
export interface QuestionnaireItemContext {
active: ComputedRef<boolean>
/** Bumped after a controlled answer interaction so every control re-syncs. */
controlSyncVersion: Ref<number>
disabled: ComputedRef<boolean>
hasInputAnswer: ComputedRef<boolean>
invalid: ComputedRef<boolean>
multiple: ComputedRef<boolean>
name: ComputedRef<string>
registerAnswerControl: (registration: AnswerControlRegistration) => () => void
registerAnswerSelection: (answerId: string, defaultSelected: boolean) => () => void
registerDescription: (descriptionId: string) => () => void
registerError: (errorId: string) => () => void
/** Only used when the title does not render as the fieldset legend. */
registerTitle: (titleId: string) => () => void
requestControlSync: () => void
required: ComputedRef<boolean>
resetVersion: Ref<number>
selectedAnswerIds: Ref<string[]>
setAnswerDefault: (answerId: string, defaultSelected: boolean) => void
setAnswerSelectionFromInteraction: (answerId: string, selected: boolean) => void
shortcutByAnswerId: ComputedRef<Map<string, string>>
shortcutByChoiceValue: ComputedRef<Map<string, string> | null>
shortcuts: ComputedRef<QuestionnaireShortcutMode | null>
status: ComputedRef<QuestionnaireItemStatus>
syncControlledAnswerSelection: (answerId: string, selected: boolean) => void
}
export const [injectQuestionnaireRootContext, provideQuestionnaireRootContext]
= createContext<QuestionnaireRootContext>('Questionnaire')
export const [injectQuestionnaireItemContext, provideQuestionnaireItemContext]
= createContext<QuestionnaireItemContext>('QuestionnaireItem')
export function hasInputValue(value: unknown) {
if (Array.isArray(value)) {
return value.some(item => String(item).trim().length > 0)
}
return value !== undefined && value !== null && String(value).trim().length > 0
}
export function getShortcutKeys(shortcuts: QuestionnaireShortcutMode | null) {
if (shortcuts === 'letters') {
return Array.from({ length: 26 }, (_, index) => String.fromCharCode(65 + index))
}
if (shortcuts === 'numbers') {
return Array.from({ length: 9 }, (_, index) => String(index + 1))
}
return []
}
export function getShortcutFromKey(key: string, shortcuts: QuestionnaireShortcutMode) {
const normalizedKey = shortcuts === 'letters' ? key.toUpperCase() : key
return getShortcutKeys(shortcuts).includes(normalizedKey) ? normalizedKey : null
}
export function getAnswerKeyShortcuts(shortcut: string | null, filled: boolean) {
return [shortcut, filled ? 'Enter' : null].filter(Boolean).join(' ') || undefined
}
export function isAnswerFilled(answer: AnswerControlRegistration) {
if (answer.type === 'choice') {
return answer.element.checked
}
return answer.element.hasAttribute('name') && hasInputValue(answer.element.value)
}
export function isEmptyNavigableInput(answer: AnswerControlRegistration | null) {
return (
answer?.type === 'input'
&& ['email', 'password', 'search', 'tel', 'text', 'url'].includes(answer.element.type)
&& !hasInputValue(answer.element.value)
)
}
export function isTextEntryTarget(element: Element) {
if (element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement) {
return true
}
if (element instanceof HTMLInputElement) {
return !['button', 'checkbox', 'radio', 'reset', 'submit'].includes(element.type)
}
return element instanceof HTMLElement && element.isContentEditable
}
export function isRadioTarget(element: Element) {
return element instanceof HTMLInputElement && element.type === 'radio'
}
/**
* Sort registrations by the position of their element in the document, so that
* navigation always follows the rendered order instead of the mount order.
*/
export function compareDocumentOrder(first: Element, second: Element) {
if (first === second) {
return 0
}
const position = first.compareDocumentPosition(second)
if (position & Node.DOCUMENT_POSITION_FOLLOWING) {
return -1
}
if (position & Node.DOCUMENT_POSITION_PRECEDING) {
return 1
}
return 0
}
export interface QuestionnaireCollection {
enabledItems: QuestionnaireItemDefinition[]
itemByName: Map<string, QuestionnaireItemDefinition>
items: readonly QuestionnaireItemDefinition[]
}
export function createQuestionnaireCollection(
items: readonly QuestionnaireItemDefinition[] | undefined,
): QuestionnaireCollection | null {
if (items === undefined) {
return null
}
return {
enabledItems: items.filter(item => !item.disabled),
itemByName: new Map(items.map(item => [item.name, item])),
items,
}
}
export function getInitialItemName(
collection: QuestionnaireCollection | null,
defaultItem: string | undefined,
) {
if (!collection) {
return defaultItem ?? null
}
const defaultDefinition = defaultItem ? collection.itemByName.get(defaultItem) : undefined
if (defaultDefinition && !defaultDefinition.disabled) {
return defaultDefinition.name
}
return collection.enabledItems[0]?.name ?? null
}
/**
* Map every enabled choice of an item definition to a keyboard shortcut, so
* that shortcuts stay stable regardless of how choices are rendered.
*/
export function getShortcutByChoiceValue(
item: QuestionnaireItemDefinition | undefined,
shortcuts: QuestionnaireShortcutMode | null,
) {
const shortcutByChoiceValue = new Map<string, string>()
if (!item || !shortcuts) {
return shortcutByChoiceValue
}
const keys = getShortcutKeys(shortcuts)
let shortcutIndex = 0
for (const choice of item.choices ?? []) {
if (choice.disabled) {
continue
}
const shortcut = keys[shortcutIndex]
if (!shortcut) {
break
}
shortcutByChoiceValue.set(choice.value, shortcut)
shortcutIndex += 1
}
return shortcutByChoiceValue
}
+1 -12
View File
@@ -3,28 +3,17 @@
export const chat = {
ask: {
answer: "Could not send the answer",
unsupported: "This question can't be answered here",
},
composer: {
microphoneUnavailable: (detail: string) => `Microphone unavailable: ${detail}`,
},
session: {
unavailable: "Chat unavailable",
loadMessages: "Could not load session messages",
refreshList: (detail: string) => `Could not refresh the session list: ${detail}`,
command: "Session action failed",
rename: "Could not rename the conversation",
delete: "Could not delete the conversation",
model: (detail: string) => `Model update failed: ${detail}`,
nothingToCopy: "Nothing to copy",
copyFailed: (detail: string) => `Not copied: ${detail}`,
clipboardUnavailable: "clipboard unavailable",
},
tasks: {
load: "Could not load tasks",
},
update: {
check: (detail: string) => `Could not check for updates: ${detail}`,
},
turn: {
// The server sends a sentence the reader can act on; this is for a failure
// that never reached it, such as a dropped connection.
+1 -1
View File
@@ -1,5 +1,5 @@
// Every failure message the dashboard writes itself, by feature. Call sites
// dot-walk it, e.g. errors.chat.composer.microphoneUnavailable, so the copy is
// dot-walk it, e.g. errors.chat.turn.stop, so the copy is
// changed here and nowhere else.
import { accounts } from "./accounts.ts";
import { alerts } from "./alerts.ts";
-12
View File
@@ -586,19 +586,7 @@ export const api = {
taskLogDownloadURL: (id: string, attempt?: number | null) =>
`/api/tasks/${encodeURIComponent(id)}/logs/download` +
(attempt == null ? "" : `?attempt=${attempt}`),
// Versions + updates. The install's synchronous phase (clone + build +
// install) legitimately runs for minutes; its timeout is therefore minutes,
// not the 15s default, and the watchdog owns everything after the restart.
version: <T = unknown>() => request<T>("/api/version"),
updateSnapshot: <T = unknown>() => request<T>("/api/chat/update"),
updateDefer: (snapshot: unknown) =>
request("/api/chat/update/defer", { method: "POST", body: { snapshot } }),
updateInstall: <T = unknown>(snapshot: unknown) =>
request<T>("/api/chat/update/install", {
method: "POST",
body: { snapshot },
timeoutMs: 15 * 60_000,
}),
captures: <T = unknown>(limit?: number) =>
request<T>("/api/captures" + qs({ limit })),
eventTypes: <T = unknown>() => request<T>("/api/event-types"),
-35
View File
@@ -1,35 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import { mediaDetail, mediaLabel, type ChatMedia } from "../src/chat/attachment.ts";
test("an attachment is labelled in the channel's own placeholder vocabulary", () => {
const cases: Array<[ChatMedia, string]> = [
[{ type: "image", mime_type: "image/jpeg" }, "[photo]"],
[{ type: "video" }, "[video]"],
[{ type: "audio" }, "[audio]"],
[{ type: "document", file_name: "report.pdf" }, "[document: report.pdf]"],
[{ type: "document" }, "[document]"],
[{ type: "sticker" }, "[sticker]"],
[{ type: "" }, "[attachment]"],
];
for (const [attachment, want] of cases) {
assert.equal(mediaLabel(attachment), want, JSON.stringify(attachment));
}
});
test("the detail names the metadata that survived persistence", () => {
assert.equal(
mediaDetail({
type: "image",
mime_type: "image/jpeg",
file_name: "beach.jpg",
file_size: 2024,
width: 1280,
height: 960,
}),
"image/jpeg · beach.jpg · 2024 bytes · 1280×960",
);
assert.equal(mediaDetail({ type: "audio", duration: 12 }), "12 s");
assert.equal(mediaDetail({ type: "document" }), "");
});
+1 -66
View File
@@ -2,8 +2,6 @@ import assert from "node:assert/strict";
import test from "node:test";
import {
DOCK_STORAGE_KEY,
LEGACY_DOCK_STORAGE_KEY,
MAX_W,
MIN_H,
MIN_W,
@@ -14,35 +12,15 @@ import {
handleValue,
keyboardCover,
keyStep,
legacyLayout,
migrateDockStorage,
normalizeLayout,
phoneBarBottom,
pinnedWidth,
resizeRect,
snapEdge,
windowWidth,
type DockLayout,
type ResizeDir,
type StorageLike,
} from "../src/chat/ChatDockLayout.ts";
class MemoryStorage implements StorageLike {
readonly values = new Map<string, string>();
getItem(key: string): string | null {
return this.values.get(key) ?? null;
}
setItem(key: string, value: string): void {
this.values.set(key, value);
}
removeItem(key: string): void {
this.values.delete(key);
}
}
const VW = 1280;
const VH = 800;
@@ -149,45 +127,11 @@ test("the minimised bar docks at the bottom of the screen on the pinned side", (
assert.deepEqual(barPlacement({ ...rect, x: 0, w: 320 }, "float", 500), { x: 8, bottom: 8, w: 484 });
});
test("the old edge-pin preference migrates into the new key and is removed", () => {
const cases: Array<[string | null, DockLayout | null]> = [
['{"side":"right","width":500}', { mode: "right", x: 772, y: 216, w: 500, h: 560 }],
['{"side":"left","width":300}', { mode: "left", x: 816, y: 216, w: 320, h: 560 }],
['{"side":null,"width":380}', { mode: "float", x: 816, y: 216, w: 380, h: 560 }],
["not json", defaultLayout(VW, VH)],
[null, null],
];
for (const [legacy, want] of cases) {
const storage = new MemoryStorage();
if (legacy !== null) storage.setItem(LEGACY_DOCK_STORAGE_KEY, legacy);
migrateDockStorage(storage, VW, VH);
assert.equal(storage.getItem(LEGACY_DOCK_STORAGE_KEY), null, "legacy key removed");
if (want === null) {
assert.equal(storage.getItem(DOCK_STORAGE_KEY), null);
} else {
assert.deepEqual(JSON.parse(storage.getItem(DOCK_STORAGE_KEY) ?? "null"), want, legacy ?? "");
}
}
});
test("an existing new-key layout wins and still retires the legacy key", () => {
const storage = new MemoryStorage();
const kept: DockLayout = { mode: "float", x: 40, y: 40, w: 360, h: 420 };
storage.setItem(DOCK_STORAGE_KEY, JSON.stringify(kept));
storage.setItem(LEGACY_DOCK_STORAGE_KEY, '{"side":"left","width":900}');
migrateDockStorage(storage, VW, VH);
assert.deepEqual(JSON.parse(storage.getItem(DOCK_STORAGE_KEY) ?? "null"), kept);
assert.equal(storage.getItem(LEGACY_DOCK_STORAGE_KEY), null);
});
test("legacy pin and float widths are clamped to what the viewport allows", () => {
test("the pinned width is clamped to what the viewport allows", () => {
assert.equal(pinnedWidth(500, VW), 500);
assert.equal(pinnedWidth(9999, VW), 720);
assert.equal(pinnedWidth(100, VW), MIN_W);
assert.equal(pinnedWidth(700, 900), 420); // vw - 480 caps below MAX_W
assert.equal(windowWidth(440, VW), 440);
assert.equal(windowWidth(9999, VW), 720);
assert.equal(windowWidth(440, 400), 384);
});
test("keyboard steps and handle metadata follow the contract", () => {
@@ -205,15 +149,6 @@ test("keyboard steps and handle metadata follow the contract", () => {
assert.equal(handleOrientation("s"), "horizontal");
});
test("legacyLayout maps only the known fields of the old preference", () => {
assert.deepEqual(legacyLayout({ side: "left", width: 420 }), { mode: "left", w: 420 });
assert.deepEqual(legacyLayout({ side: "right" }), { mode: "right" });
assert.deepEqual(legacyLayout({ side: null, width: 420 }), { mode: "float", w: 420 });
assert.deepEqual(legacyLayout({ side: "up", width: "wide" }), { mode: "float" });
assert.equal(legacyLayout(null), null);
assert.equal(legacyLayout("right"), null);
});
test("the on-screen keyboard's cover of the layout viewport is measured, never negative", () => {
const cases: Array<[{ height: number; offsetTop: number } | null, number]> = [
[null, 0],
+2 -7
View File
@@ -15,9 +15,8 @@ function elements(tree: Root | Element, tag: string): Element[] {
return found;
}
// Guards the chat renderer against script URLs and against #N task links
// appearing inside code or existing links.
test("parseMarkdown keeps only safe URLs and links task references in prose", () => {
// Guards the chat renderer against script URLs and remote images.
test("parseMarkdown keeps only safe URLs", () => {
const cases = [
{ md: "[x](javascript:alert(1))", tag: "a", count: 0 },
{ md: "[x](https://example.com)", tag: "a", count: 1 },
@@ -35,10 +34,6 @@ test("parseMarkdown keeps only safe URLs and links task references in prose", ()
// Allowed controls: same-origin root-relative path and inline data image.
{ md: "![x](/img/chart.png)", tag: "img", count: 1 },
{ md: "<script>alert(1)</script>", tag: "script", count: 0 },
{ md: "See #12 and #13.", tag: "task-ref", count: 2 },
{ md: "`#12` and [#13](https://example.com)", tag: "task-ref", count: 0 },
{ md: "```\n#12\n```", tag: "task-ref", count: 0 },
{ md: "issue#12 and a/#12", tag: "task-ref", count: 0 },
];
for (const { md, tag, count } of cases) {
assert.equal(elements(parseMarkdown(md), tag).length, count, md);
+2 -12
View File
@@ -9,8 +9,8 @@ import {
// One route per page the prompts distinguish, in the shape the page tag reads.
const pages: Array<[SuggestionRoute, string]> = [
[{ name: "task-detail", path: "/tasks/42", params: { id: "42" } }, "task"],
[{ name: "tasks", path: "/tasks" }, "tasks"],
[{ name: "run", path: "/runs/0b7f", params: { id: "0b7f" } }, "run"],
[{ name: "runs", path: "/runs" }, "runs"],
[{ name: "events", path: "/events" }, "events"],
[{ name: "workflows", path: "/workflows" }, "workflows"],
[{ name: "schedules", path: "/schedules" }, "schedules"],
@@ -59,16 +59,6 @@ test("every route yields distinct, well-formed prompts", () => {
}
});
test("a task page names the task it is open on", () => {
const withId = suggestionsForRoute({ name: "task-detail", path: "/tasks/42", params: { id: "42" } });
assert.ok(withId.some((prompt) => prompt.includes("#42")));
assert.ok(withId.every((prompt) => !prompt.includes("undefined")));
const withoutId = suggestionsForRoute({ name: "task-detail", path: "/tasks" });
assert.ok(withoutId.some((prompt) => prompt.includes("this task")));
assert.ok(withoutId.every((prompt) => !prompt.includes("#")));
});
test("settings is recognised by flag, by name and by path alike", () => {
const byFlag = suggestionsForRoute({ name: "system-status", path: "/settings/status", meta: { settings: true } });
const byName = suggestionsForRoute({ name: "settings-plugins", path: "/settings/plugins" });
+3 -3
View File
@@ -77,7 +77,7 @@ test("reasoning frames accumulate on the live turn as its thinking", async () =>
{ type: "reasoning", text: "the request" },
{ type: "error", text: "provider exploded" },
]);
await state.sendMessage({ textOverride: "hello" });
await state.sendMessage({ text: "hello" });
const turn = state.streamingTurn.value;
assert.ok(turn, "the failed turn stays on the panel");
assert.equal(turn.isError, true);
@@ -90,7 +90,7 @@ test("reasoning never leaks into the reply text", async () => {
{ type: "delta", text: "Hello" },
{ type: "done", text: "Hello" },
]);
await state.sendMessage({ textOverride: "hi" });
await state.sendMessage({ text: "hi" });
assert.equal(state.streamingTurn.value, null);
const last = state.messages.value.at(-1);
assert.equal(last?.from, "assistant");
@@ -99,7 +99,7 @@ test("reasoning never leaks into the reply text", async () => {
test("a turn without reasoning frames completes normally", async () => {
stubApi([{ type: "delta", text: "Hi" }, { type: "done", text: "Hi" }]);
await state.sendMessage({ textOverride: "hey" });
await state.sendMessage({ text: "hey" });
assert.equal(state.streamingTurn.value, null);
assert.equal(state.messages.value.at(-1)?.text, "Hi");
assert.equal(state.statusText.value, "Ready");
+2 -11
View File
@@ -7,17 +7,8 @@ test("serializePromptValue maps text and tokens into the chat wire format", () =
const cases = [
[["Review the retry policy"], "Review the retry policy"],
[
[
"Check ",
{ id: "1", type: "task", value: "42", label: "#42" },
" in ",
{ id: "2", type: "workflow", value: "wf-1", label: "Event triage" },
],
"Check #42 in @Event triage",
],
[
[{ id: "3", type: "command", value: "/help", label: "/help" }, " schedules"],
"/help schedules",
["Check ", { id: "1", type: "workflow", value: "wf-1", label: "Event triage" }, " runs"],
"Check @Event triage runs",
],
] as const;