Merge branch 'main' into fix/1892-container-queries
ci/woodpecker/pr/quality Pipeline was successful
Quality / check (pull_request) Successful in 10m46s

This commit is contained in:
sam committed 2026-11-12 12:14:54 +00:00
commit af02cbe832
30 files changed
+1266 -94

No files matched your search

+1 -1
View File
@@ -96,7 +96,7 @@ watch(() => accounts.status?.user, (user) => {
<SidebarProvider class="bg-[var(--workspace)]">
<a href="#main-content" class="sr-only focus:not-sr-only focus:fixed focus:top-2 focus:left-4 focus:z-[60] focus:rounded-md focus:bg-card focus:px-3 focus:py-2">Skip to main content</a>
<AppSidebar :hidden="hidden" />
<SidebarInset class="min-w-0 bg-[var(--workspace)]" :class="workflowsPage && 'max-md:h-dvh'">
<SidebarInset class="min-w-0 bg-[var(--workspace)] md:ml-[var(--chat-pin-l,0px)] md:mr-[var(--chat-pin-r,0px)]" :class="workflowsPage && 'max-md:h-dvh'">
<header class="bg-card border-border-strong sticky top-0 z-30 flex h-14 shrink-0 items-center gap-2 border-b px-3 shadow-[var(--shadow-sm)] sm:px-4">
<SidebarTrigger class="-ml-1 md:hidden" />
<Brand />
+60 -17
View File
@@ -7,15 +7,24 @@ import { Clock, Mic, Pencil, X } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { Textarea } from "@/components/ui/textarea";
import { applyCommand, isExactCommand } from "./commands";
import { isExactCommand, replaceToken } from "./commands";
import ChatSlashPalette from "./ChatSlashPalette.vue";
import {
closeCommandMenu,
commandMatches,
commandSelection,
commandSpecs,
addTaskTag,
clearPageTag,
pageTag,
composerText,
editQueued,
menuTrigger,
removeTaskTag,
retryTasks,
taskForKey,
taskLoadError,
taskTags,
isCommandMenuOpen,
isSending,
moveCommandSelection,
@@ -110,21 +119,27 @@ function onInput(event: Event): void {
}
function choose(index: number): void {
const spec = commandMatches.value[index];
const item = commandMatches.value[index];
const input = field.value?.$el;
if (!spec || !input) return;
// Completing the command replaces the token the caret sits in, which is
// decided by the same rule that found the matches.
const { text, cursor } = applyCommand(
input.value,
input.selectionStart ?? input.value.length,
spec.command,
);
composerText.value = text;
if (!item || !input) return;
const caret = input.selectionStart ?? input.value.length;
// Completing replaces the token the caret sits in, which is decided by the
// same rule that found the matches. A task leaves no text behind: it becomes
// a tag above the field.
let edit: { text: string; cursor: number };
if (menuTrigger.value === "#") {
const task = taskForKey(item.key);
if (!task) return;
addTaskTag(task);
edit = replaceToken(input.value, caret, "");
} else {
edit = replaceToken(input.value, caret, item.label);
}
composerText.value = edit.text;
closeCommandMenu();
void nextTick(() => {
input.focus();
input.setSelectionRange(cursor, cursor);
input.setSelectionRange(edit.cursor, edit.cursor);
});
}
@@ -132,12 +147,13 @@ function onKeydown(event: KeyboardEvent): void {
// Safari may end composition before delivering its confirming Enter.
if (event.key === "Enter" && (event.isComposing || event.keyCode === 229)) return;
const plain = !event.shiftKey && !event.ctrlKey && !event.metaKey;
if (isCommandMenuOpen.value && commandMatches.value.length) {
if (isCommandMenuOpen.value) {
// A command typed in full is sent rather than completed, so Enter never
// re-enters the command the palette was offering.
if (
event.key === "Enter" &&
plain &&
menuTrigger.value === "/" &&
isExactCommand(commandSpecs.value, composerText.value)
) {
event.preventDefault();
@@ -155,7 +171,10 @@ function onKeydown(event: KeyboardEvent): void {
moveCommandSelection(-1);
return;
}
if (event.key === "Enter" && plain) {
if (
commandMatches.value.length &&
((event.key === "Enter" && plain) || (event.key === "Tab" && !event.shiftKey))
) {
event.preventDefault();
choose(commandSelection.value);
return;
@@ -202,6 +221,27 @@ function onKeydown(event: KeyboardEvent): void {
</Tooltip>
</li>
</ul>
<ul v-if="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
:class="
cn(
@@ -218,18 +258,21 @@ function onKeydown(event: KeyboardEvent): void {
aria-label="Message Archie"
role="combobox"
aria-controls="slash-palette"
:aria-expanded="isCommandMenuOpen && commandMatches.length ? 'true' : 'false'"
:aria-expanded="isCommandMenuOpen ? 'true' : 'false'"
:aria-activedescendant="isCommandMenuOpen && commandMatches.length ? `slash-palette-option-${commandSelection}` : undefined"
class="max-h-40 min-h-11 flex-1 resize-none rounded-none border-0 bg-transparent! px-0 py-1 text-label shadow-none focus-visible:ring-0"
class="max-h-40 min-h-11 flex-1 resize-none rounded-none border-0 bg-transparent! px-0 py-1 text-label pointer-coarse:text-base shadow-none focus-visible:ring-0"
@input="onInput"
@keydown="onKeydown"
/>
<ChatSlashPalette
v-if="isCommandMenuOpen && commandMatches.length"
v-if="isCommandMenuOpen"
:matches="commandMatches"
:selection="commandSelection"
:label="menuTrigger === '#' ? 'Tasks' : 'Commands'"
:error="menuTrigger === '#' ? taskLoadError : ''"
@choose="choose"
@retry="retryTasks"
/>
<!-- Centred on the field's first line, then kept at the bottom as it grows. -->
+197 -7
View File
@@ -1,13 +1,18 @@
<script setup lang="ts">
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { ChevronDown, ChevronUp } from "@lucide/vue";
import { nextTick, onMounted, onUnmounted, ref, watch } from "vue";
import { useEventListener, useMediaQuery, useStorage, useWindowSize } from "@vueuse/core";
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { useLiveResource } from "@/stores/session";
import { cn } from "@/lib/utils";
import ChatBar from "./ChatBar.vue";
import ChatComposer from "./ChatComposer.vue";
import ChatTranscript from "./ChatTranscript.vue";
import { composerText, escapeOwnedByLayer, isSending, useChat } from "./state";
import { composerText, escapeOwnedByLayer, isSending, reloadTranscript, useChat } from "./state";
import { setDockOpen, unseenCount } from "./unseen";
/**
* Chat is a bar docked at the bottom of every page, not a route: the operator
@@ -19,6 +24,14 @@ import { composerText, escapeOwnedByLayer, isSending, useChat } from "./state";
* the conversation opens above it. Hiding the conversation leaves the bar. It is
* deliberately not a modal: no scrim, no scroll lock, no focus trap.
*
* On a desktop-width screen the expanded conversation can be pinned to the left
* or right edge, where the page reflows beside it instead of sitting under it.
* Dragging the header to an edge pins it; dragging it away, or double-clicking
* the header, unpins it. The side and width are remembered per browser.
*
* On a phone the bar rides above the on-screen keyboard, which iOS does not
* resize the page for, and swiping down on the conversation header hides it.
*
* 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
* containing block for `position: fixed`, so a bar nested inside would anchor to
@@ -26,7 +39,41 @@ import { composerText, escapeOwnedByLayer, isSending, useChat } from "./state";
*/
useChat();
// A task this conversation started reports its outcome into it. The dock stays
// mounted while collapsed, so a reply that lands then is still read and counted.
useLiveResource("chat", () => void reloadTranscript());
const expanded = ref(false);
watch(expanded, setDockOpen, { immediate: true });
const MIN_WIDTH = 320;
const EDGE = 64;
type Side = "left" | "right";
const saved = useStorage<{ side: Side | null; width: number }>(
"archie.chat.dock",
{ side: null, width: 420 },
localStorage,
{ mergeDefaults: true },
);
const desktop = useMediaQuery("(min-width: 768px)");
const { width: viewport } = useWindowSize();
const width = computed(() =>
Math.round(Math.min(Math.max(saved.value.width, MIN_WIDTH), Math.max(MIN_WIDTH, Math.min(720, viewport.value - 480)))),
);
const side = computed(() => (desktop.value && expanded.value ? saved.value.side : null));
// 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);
function followViewport(): void {
const vv = window.visualViewport;
keyboard.value = vv ? Math.max(0, Math.round(window.innerHeight - vv.height - vv.offsetTop)) : 0;
visibleHeight.value = vv ? vv.height : window.innerHeight;
}
useEventListener(() => window.visualViewport, ["resize", "scroll"], followViewport);
const phoneBottom = computed(() =>
keyboard.value > 0 ? `${keyboard.value + 8}px` : "max(0.5rem, env(safe-area-inset-bottom))",
);
const composer = ref<InstanceType<typeof ChatComposer> | null>(null);
// Nothing outside the dock closes it: every navigation control is outside it,
@@ -72,6 +119,101 @@ onUnmounted(() => {
document.documentElement.style.removeProperty("--chat-dock-clear");
});
// The page makes room for a pinned dock through these two variables.
watch([side, width], ([s, w]) => {
const root = document.documentElement.style;
root.setProperty("--chat-pin-l", s === "left" ? `${w}px` : "0px");
root.setProperty("--chat-pin-r", s === "right" ? `${w}px` : "0px");
}, { immediate: true });
onUnmounted(() => {
document.documentElement.style.removeProperty("--chat-pin-l");
document.documentElement.style.removeProperty("--chat-pin-r");
});
function edgeAt(x: number): Side | null {
if (x <= EDGE) return "left";
if (x >= window.innerWidth - EDGE) return "right";
return null;
}
// Pointer travel before a press on the header becomes a drag, so a click or a
// double-click on it never moves the dock.
const INTERACTIVE = "button, a, input, select, textarea, [role=combobox]";
const DRAG_START = 4;
const offset = ref<{ x: number; y: number } | null>(null);
const target = ref<Side | null>(null);
function startDrag(event: PointerEvent): void {
if (event.button !== 0 || (event.target as HTMLElement).closest(INTERACTIVE)) return;
if (!desktop.value) return startSwipe(event);
const grip = event.currentTarget as HTMLElement;
const { clientX: x0, clientY: y0 } = event;
grip.setPointerCapture(event.pointerId);
const move = (e: PointerEvent): void => {
const dx = e.clientX - x0;
const dy = e.clientY - y0;
if (!offset.value && Math.hypot(dx, dy) < DRAG_START) return;
offset.value = { x: dx, y: dy };
target.value = edgeAt(e.clientX);
};
const end = (e: PointerEvent): void => {
grip.removeEventListener("pointermove", move);
grip.removeEventListener("pointerup", end);
grip.removeEventListener("pointercancel", end);
if (offset.value && e.type === "pointerup") saved.value.side = edgeAt(e.clientX);
offset.value = null;
target.value = null;
};
grip.addEventListener("pointermove", move);
grip.addEventListener("pointerup", end);
grip.addEventListener("pointercancel", end);
}
// A downward flick on the header hides the conversation. It must be mostly
// vertical so a sideways slip does not collapse it.
const SWIPE = 48;
function startSwipe(event: PointerEvent): void {
const grip = event.currentTarget as HTMLElement;
const { clientX: x0, clientY: y0 } = event;
const end = (e: PointerEvent): void => {
grip.removeEventListener("pointerup", end);
grip.removeEventListener("pointercancel", end);
const dy = e.clientY - y0;
if (e.type === "pointerup" && dy >= SWIPE && dy > Math.abs(e.clientX - x0) * 1.5) {
// The keyboard is for the composer, which is no longer in front of it.
(document.activeElement as HTMLElement | null)?.blur();
expanded.value = false;
}
};
grip.addEventListener("pointerup", end);
grip.addEventListener("pointercancel", end);
}
function togglePin(event: MouseEvent): void {
if (!desktop.value || (event.target as HTMLElement).closest(INTERACTIVE)) return;
saved.value.side = saved.value.side ? null : "right";
}
function resize(event: PointerEvent): void {
const handle = event.currentTarget as HTMLElement;
handle.setPointerCapture(event.pointerId);
const move = (e: PointerEvent): void => {
saved.value.width = side.value === "right" ? window.innerWidth - e.clientX : e.clientX;
};
const end = (): void => {
handle.removeEventListener("pointermove", move);
handle.removeEventListener("pointerup", end);
handle.removeEventListener("pointercancel", end);
};
handle.addEventListener("pointermove", move);
handle.addEventListener("pointerup", end);
handle.addEventListener("pointercancel", end);
}
function resizeByKey(event: KeyboardEvent): void {
const grow = event.key === (side.value === "right" ? "ArrowLeft" : "ArrowRight");
const shrink = event.key === (side.value === "right" ? "ArrowRight" : "ArrowLeft");
if (!grow && !shrink) return;
event.preventDefault();
saved.value.width = width.value + (grow ? 16 : -16);
}
function usePrompt(text: string): void {
composerText.value = text;
composer.value?.focus();
@@ -79,13 +221,54 @@ function usePrompt(text: string): void {
</script>
<template>
<div class="pointer-events-none fixed inset-x-0 bottom-4 z-40 flex justify-center px-3 max-md:bottom-2">
<div
v-if="target"
aria-hidden="true"
:class="cn('pointer-events-none fixed inset-y-0 z-40 border-primary/40 bg-primary/10', target === 'left' ? 'left-0 border-r-2' : 'right-0 border-l-2')"
:style="{ width: `${width}px` }"
/>
<div
:class="cn(
'pointer-events-none fixed z-40',
side ? cn('inset-y-0', side === 'left' ? 'left-0' : 'right-0') : 'inset-x-0 bottom-4 flex justify-center px-3',
)"
:style="side ? { width: `${width}px` } : desktop ? undefined : { bottom: phoneBottom }"
>
<aside
ref="dock"
aria-label="Chat with Archie"
class="pointer-events-auto flex w-full max-w-xl flex-col rounded-lg border border-border-strong bg-popover shadow-[var(--shadow-md)]"
:class="cn(
'touch-hit pointer-events-auto relative flex flex-col border-border-strong bg-popover shadow-[var(--shadow-md)]',
side
? cn('h-full w-full', side === 'left' ? 'border-r' : 'border-l')
: 'w-full max-w-xl rounded-lg border',
offset && 'z-50 opacity-90',
)"
:style="offset ? { transform: `translate(${offset.x}px, ${offset.y}px)` } : undefined"
>
<ChatBar v-if="expanded">
<div
v-if="side"
role="separator"
aria-orientation="vertical"
aria-label="Resize chat"
tabindex="0"
:aria-valuenow="width"
:aria-valuemin="MIN_WIDTH"
class="absolute inset-y-0 z-10 w-1.5 cursor-col-resize hover:bg-primary/30 focus-visible:bg-primary/30 focus-visible:outline-none"
:class="side === 'left' ? '-right-0.5' : '-left-0.5'"
@pointerdown.prevent="resize"
@keydown="resizeByKey"
/>
<div
v-if="expanded"
:class="desktop ? 'cursor-grab select-none active:cursor-grabbing' : 'touch-none'"
@pointerdown="startDrag"
@dblclick="togglePin"
>
<div class="flex justify-center pt-1.5" aria-hidden="true">
<span class="h-1 w-8 rounded-full bg-border-strong" />
</div>
<ChatBar>
<Tooltip>
<TooltipTrigger as-child>
<Button
@@ -101,7 +284,12 @@ function usePrompt(text: string): void {
<TooltipContent>Hide conversation</TooltipContent>
</Tooltip>
</ChatBar>
<div v-if="expanded" class="flex h-[min(28rem,55dvh)] min-h-0 flex-col">
</div>
<div
v-if="expanded"
:class="cn('flex min-h-0 flex-col', side ? 'flex-1' : 'h-[min(28rem,55dvh)]')"
:style="side || desktop ? undefined : { height: `min(28rem, ${Math.round(visibleHeight * 0.55)}px)` }"
>
<ChatTranscript @prompt="usePrompt" />
</div>
<div @focusin="expanded = true">
@@ -112,10 +300,12 @@ function usePrompt(text: string): void {
<Button
variant="ghost"
size="icon-sm"
aria-label="Show conversation"
:class="cn(unseenCount && 'w-auto gap-1 px-2')"
:aria-label="unseenCount ? `Show conversation, ${unseenCount} new` : 'Show conversation'"
@click="expanded = true"
>
<ChevronUp />
<Badge v-if="unseenCount" variant="default" aria-hidden="true">{{ unseenCount }}</Badge>
</Button>
</TooltipTrigger>
<TooltipContent>Show conversation</TooltipContent>
+2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import ChatTaskRef from "./ChatTaskRef.vue";
import type { ChatInline } from "./markdown";
/** One inline run: the spans of a paragraph, a heading or a table cell. */
@@ -29,6 +30,7 @@ defineProps<{ inline: ChatInline[] }>();
class="text-link underline-offset-4 hover:underline"
>{{ span.text }}</a
>
<ChatTaskRef v-else-if="span.kind === 'taskref'" :id="span.id" />
<em v-else-if="span.kind === 'em'">{{ span.text }}</em>
<template v-else>{{ span.text }}</template>
</template>
+45
View File
@@ -0,0 +1,45 @@
<script setup lang="ts">
import { ArrowDownIcon } from "@lucide/vue";
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
import { MessageScrollerButton, useMessageScrollerScrollable } from "@/components/ui/message-scroller";
import { setAtEnd, unseenCount } from "./unseen";
/**
* The scroller's jump-to-latest button. It reads where the reader is for the
* unseen count and says how many replies are waiting below.
*
* The scroller measures on the frames after it mounts, and until then it
* reports "not scrollable", which would look like the end. The reader counts
* as at the end only once it has measured.
*/
const scrollable = useMessageScrollerScrollable();
const measured = ref(false);
let frame = 0;
onMounted(() => {
frame = requestAnimationFrame(() => {
frame = requestAnimationFrame(() => {
measured.value = true;
});
});
});
onUnmounted(() => {
cancelAnimationFrame(frame);
setAtEnd(false);
});
watch(
() => measured.value && !scrollable.value.end,
(end) => setAtEnd(end),
{ immediate: true },
);
const label = computed(() => `${unseenCount.value} new ${unseenCount.value === 1 ? "reply" : "replies"}`);
</script>
<template>
<MessageScrollerButton :size="unseenCount ? 'sm' : 'icon-sm'" :class="unseenCount ? 'gap-1.5 whitespace-nowrap' : undefined">
<ArrowDownIcon />
<template v-if="unseenCount">{{ label }}</template>
<span v-else class="sr-only">Scroll to end</span>
</MessageScrollerButton>
</template>
+35
View File
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import {
Copy,
Ellipsis,
GitBranch,
Pencil,
@@ -9,6 +10,7 @@ import {
Undo2,
} from "@lucide/vue";
import { ref } from "vue";
import { toast } from "vue-sonner";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
@@ -28,6 +30,7 @@ import { Input } from "@/components/ui/input";
import ChatSettings from "./ChatSettings.vue";
import {
currentSession,
messages,
runSessionCommand,
useEscapeLayer,
} from "./state";
@@ -51,6 +54,31 @@ function run(command: string): void {
void runSessionCommand(command);
}
// Reply text is already Markdown, so the transcript is the messages under a
// heading per speaker. Empty turns (tool-only replies) have nothing to paste.
async function copyMarkdown(): Promise<void> {
open.value = false;
const text = messages.value
.map((m) => {
const body = (m.text ?? m.Text ?? "").trim();
if (!body) return "";
return `### ${(m.from ?? m.From) === "web" ? "You" : "Archie"}\n\n${body}`;
})
.filter(Boolean)
.join("\n\n");
if (!text) {
toast.error("Nothing to copy");
return;
}
try {
await navigator.clipboard.writeText(text);
} catch (err) {
toast.error(`Not copied: ${(err as Error).message || "clipboard unavailable"}`);
return;
}
toast.success("Copied as Markdown");
}
// Rename and branch ask for a value in a labelled dialog, not window.prompt.
const promptOpen = ref(false);
const promptCommand = ref("");
@@ -124,6 +152,13 @@ function submitPrompt(): void {
@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
>
<Separator class="my-1" />
</template>
<ChatSettings />
+21 -11
View File
@@ -2,15 +2,21 @@
import { nextTick, ref, watch } from "vue";
import { commandScrollTop } from "./command-scroll";
import type { ChatCommandSpec } from "./state";
import { Button } from "@/components/ui/button";
import type { Completion } from "./commands";
/**
* The slash palette: the commands the server accepts, floating above the
* composer. It is the only command surface -- there is no second list anywhere
* in the panel -- so the arrow keys and the pointer both land here.
* The composer palette, floating above it: the commands the server accepts
* after `/`, the tasks that can be attached after `#`. The arrow keys and the
* pointer both land here. A failed read shows in place of the rows.
*/
const props = defineProps<{ matches: ChatCommandSpec[]; selection: number }>();
const emit = defineEmits<{ choose: [index: number] }>();
const props = defineProps<{
matches: Completion[];
selection: number;
label: string;
error?: string;
}>();
const emit = defineEmits<{ choose: [index: number]; retry: [] }>();
const menu = ref<HTMLElement | null>(null);
@@ -41,12 +47,16 @@ watch(
ref="menu"
id="slash-palette"
role="listbox"
aria-label="Commands"
:aria-label="label"
class="absolute inset-x-3 bottom-[calc(100%-0.25rem)] z-30 grid max-h-72 gap-0.5 overflow-auto rounded-lg border border-border-strong bg-popover p-1.5 shadow-md"
>
<div v-if="error" role="alert" class="flex items-center justify-between gap-2 px-2.5 py-2 text-danger">
<span class="truncate">{{ error }}</span>
<Button variant="outline" size="sm" @mousedown.prevent @click="emit('retry')">Retry</Button>
</div>
<button
v-for="(spec, index) in matches"
:key="spec.command"
v-for="(item, index) in matches"
:key="item.key"
type="button"
role="option"
:id="`slash-palette-option-${index}`"
@@ -55,8 +65,8 @@ watch(
@mousedown.prevent
@click="emit('choose', index)"
>
<code class="truncate text-foreground">{{ spec.command }}</code>
<span class="truncate">{{ spec.description || spec.usage || "" }}</span>
<code class="truncate text-foreground">{{ item.label }}</code>
<span class="truncate">{{ item.detail }}</span>
</button>
</div>
</template>
+59
View File
@@ -0,0 +1,59 @@
<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>
+2 -7
View File
@@ -4,18 +4,17 @@ import { computed } from "vue";
import { Button } from "@/components/ui/button";
import {
MessageScroller,
MessageScrollerButton,
MessageScrollerContent,
MessageScrollerItem,
MessageScrollerProvider,
MessageScrollerViewport,
} from "@/components/ui/message-scroller";
import { useLiveResource } from "@/stores/session";
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 {
@@ -27,7 +26,6 @@ import {
sessionError,
streamingTurn,
type ChatMessage,
reloadTranscript,
} from "./state";
/**
@@ -78,9 +76,6 @@ const rows = computed(() => {
},
];
});
// A task this conversation started reports its outcome into it.
useLiveResource("chat", () => void reloadTranscript());
</script>
<template>
@@ -141,7 +136,7 @@ useLiveResource("chat", () => void reloadTranscript());
</MessageScrollerContent>
</MessageScrollerViewport>
<MessageScrollerButton />
<ChatJumpButton />
</MessageScroller>
</MessageScrollerProvider>
</template>
+61 -25
View File
@@ -1,54 +1,90 @@
import type { ChatCommandSpec } from "./state";
import type { ChatCommandSpec, TaskRef } from "./state";
/**
* The slash palette's arithmetic, kept out of the composer so it is decided in
* one place rather than reconstructed from DOM positions twice.
* The composer palette's arithmetic, kept out of the composer so it is decided
* in one place rather than reconstructed from DOM positions twice. Two
* triggers share it: `/` completes a command, `#` picks a task.
*/
/** The command token the caret sits in: a slash word at the start or after a space. */
const OPEN_TOKEN = /(?:^|\s)\/([^\s]*)$/;
const ANY_TOKEN = /(?:^|\s)\/[^\s]*$/;
export type Trigger = "/" | "#";
/** One row of the palette: what is shown, and the key that identifies it. */
export interface Completion {
key: string;
label: string;
detail: string;
}
/** The trigger word the caret sits in: at the start or after whitespace. */
const OPEN_TOKEN = /(?:^|\s)([/#])([^\s]*)$/;
/** How many matches the palette will show at once. */
const MAX_MATCHES = 8;
/**
* matchesFor returns the commands worth offering for the text before the
* caret, matched on the command and its description together so a word from
* either finds it.
*/
export function matchesFor(
specs: ChatCommandSpec[],
/** detectTrigger returns the trigger and the text typed after it, if any. */
export function detectTrigger(
value: string,
caret: number,
): ChatCommandSpec[] {
): { trigger: Trigger; query: string } | null {
const match = value.slice(0, caret).match(OPEN_TOKEN);
if (!match) return [];
const query = match[1].toLowerCase();
if (!match) return null;
return { trigger: match[1] as Trigger, query: match[2].toLowerCase() };
}
/** Commands matched on the command and its description together. */
export function commandCompletions(
specs: ChatCommandSpec[],
query: string,
): Completion[] {
return specs
.filter((spec) =>
`${spec.command} ${spec.description ?? ""}`.toLowerCase().includes(query),
)
.slice(0, MAX_MATCHES);
.slice(0, MAX_MATCHES)
.map((spec) => ({
key: spec.command,
label: spec.command,
detail: spec.description || spec.usage || "",
}));
}
/** Tasks matched on id and title, so `#12` and a title word both find one. */
export function taskCompletions(tasks: TaskRef[], query: string): Completion[] {
return tasks
.filter((task) =>
`${task.id} ${task.title ?? ""}`.toLowerCase().includes(query),
)
.slice(0, MAX_MATCHES)
.map((task) => ({
key: String(task.id),
label: `#${task.id}`,
detail: task.title ?? "",
}));
}
/**
* applyCommand replaces the token being completed with the chosen command and
* returns the cursor position just after it, ready for the next word.
* replaceToken swaps the trigger word the caret sits in for `insert` and
* returns the caret just after it. A space follows the insert unless one
* already does, so completing mid-sentence never doubles it. An empty insert
* removes the token.
*/
export function applyCommand(
export function replaceToken(
value: string,
caret: number,
command: string,
insert: string,
): { text: string; cursor: number } {
const before = value.slice(0, caret);
const after = value.slice(caret);
const start = before.search(ANY_TOKEN);
const start = before.search(/(?:^|\s)[/#][^\s]*$/);
const tokenStart =
start < 0 ? before.length : start + (before[start] === " " ? 1 : 0);
start < 0 ? before.length : start + (/\s/.test(before[start]) ? 1 : 0);
const head = before.slice(0, tokenStart);
const gap = insert === "" || /^\s/.test(after) ? "" : " ";
// Removing the token must not leave the words either side of it two spaces apart.
const tail = insert === "" && /\s$/.test(head) ? after.replace(/^[ \t]/, "") : after;
return {
text: `${before.slice(0, tokenStart)}${command} ${after}`,
cursor: tokenStart + command.length + 1,
text: `${head}${insert}${gap}${tail}`,
cursor: tokenStart + insert.length + gap.length,
};
}
+20 -2
View File
@@ -15,6 +15,7 @@ export type ChatInline =
| { kind: "del"; text: string }
| { kind: "code"; text: string }
| { kind: "link"; text: string; href: string }
| { kind: "taskref"; id: number }
| { kind: "image"; alt: string; src: string };
/** One block of the document. Lists carry their items as inline runs. */
@@ -27,6 +28,23 @@ export type ChatBlock =
const INLINE =
/(!\[[^\]]*\]\((?:https?:\/\/[^\s)]+|data:image\/[^\s)]+|\/[^\s)]+)\)|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\((?:https?:\/\/[^\s)]+|\/[^\s)]+)\)|\*[^*]+\*|_[^_]+_)/g;
// 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;
// plainText splits a run of plain text around its task references.
function plainText(text: string): ChatInline[] {
const out: ChatInline[] = [];
let cursor = 0;
for (const match of text.matchAll(TASK_REF)) {
if (match.index > cursor)
out.push({ kind: "text", text: text.slice(cursor, match.index) });
out.push({ kind: "taskref", id: Number(match[1]) });
cursor = match.index + match[0].length;
}
if (cursor < text.length) out.push({ kind: "text", text: text.slice(cursor) });
return out;
}
// inlineMarkdown returns the children of one line: plain text and the element
// each matched span becomes, in order.
function inlineMarkdown(text: string): ChatInline[] {
@@ -34,7 +52,7 @@ function inlineMarkdown(text: string): ChatInline[] {
let cursor = 0;
for (const match of String(text).matchAll(INLINE)) {
if (match.index > cursor)
children.push({ kind: "text", text: text.slice(cursor, match.index) });
children.push(...plainText(text.slice(cursor, match.index)));
const value = match[0];
if (value.startsWith("![")) {
const img = value.match(/^!\[([^\]]*)\]\((.+)\)$/);
@@ -57,7 +75,7 @@ function inlineMarkdown(text: string): ChatInline[] {
cursor = match.index + value.length;
}
if (cursor < text.length)
children.push({ kind: "text", text: text.slice(cursor) });
children.push(...plainText(text.slice(cursor)));
return children;
}
+150 -17
View File
@@ -1,9 +1,10 @@
import { computed, onMounted, onUnmounted, ref, watch, type Ref } from "vue";
import { api } from "@/lib/api";
import { router } from "@/router";
import { randomUUID } from "@/lib/uuid";
import { channelID } from "./channel";
import { matchesFor } from "./commands";
import { commandCompletions, detectTrigger, taskCompletions, type Completion, type Trigger } from "./commands";
import {
resolveTurn,
retryChatTurn,
@@ -35,6 +36,13 @@ export interface ChatCommandSpec {
description?: string;
}
/** A task the operator can attach to a message as context. */
export interface TaskRef {
id: number | string;
title?: string;
status?: string;
}
/**
* A tool the assistant called. A live frame names the tool in `tool` and
* carries its outcome in `text`; a recorded turn uses `name` and `summary`.
@@ -203,6 +211,40 @@ export const composerText = computed({
drafts.value = { ...drafts.value, [currentSession.value]: value };
},
});
const tagDrafts = ref<Record<string, TaskRef[]>>({});
/** The tasks attached to the unsent message; each conversation keeps its own. */
export const taskTags = computed(() => tagDrafts.value[currentSession.value] ?? []);
export function addTaskTag(task: TaskRef): void {
if (taskTags.value.some((tag) => tag.id === task.id)) return;
tagDrafts.value = { ...tagDrafts.value, [currentSession.value]: [...taskTags.value, task] };
}
export function removeTaskTag(id: TaskRef["id"]): void {
tagDrafts.value = {
...tagDrafts.value,
[currentSession.value]: taskTags.value.filter((tag) => tag.id !== id),
};
}
function clearDraft(): void {
composerText.value = "";
removeAllTags();
}
function removeAllTags(): void {
tagDrafts.value = { ...tagDrafts.value, [currentSession.value]: [] };
}
/** The message as sent: the typed text, then the tasks it is about. */
function withTaskContext(text: string): string {
if (!taskTags.value.length) return text;
const refs = taskTags.value
.map((task) => `#${task.id}${task.title ? ` ${task.title}` : ""}`)
.join("; ");
return `${text}\n\nContext, tasks: ${refs}`;
}
export const statusText = ref("Ready");
export const isSending = ref(false);
export const isLoadingSession = ref(false);
@@ -215,7 +257,11 @@ export const selectorData = ref<ChatSelectorData>({});
export const selectedModel = ref("");
export const commandSpecs = ref<ChatCommandSpec[]>([]);
export const commandMatches = ref<ChatCommandSpec[]>([]);
export const commandMatches = ref<Completion[]>([]);
/** Which trigger the open menu was opened by. */
export const menuTrigger = ref<Trigger>("/");
/** Why the task list could not be read; shown in the menu, with a retry. */
export const taskLoadError = ref("");
export const commandSelection = ref(0);
export const isCommandMenuOpen = ref(false);
@@ -290,7 +336,7 @@ async function sendCommand(
channel_id: channelID(),
source_id: randomUUID(),
text,
page: currentPage(),
page: sentPage(),
});
if (!response.body) throw new Error("the chat stream returned no body");
const reader = response.body.getReader();
@@ -509,17 +555,71 @@ export function editQueued(index: number): void {
composerText.value = composerText.value.trim() ? `${composerText.value}\n${text}` : text;
}
/** Opens the palette for the slash word the caret sits in, or closes it. */
let taskChoices: TaskRef[] = [];
let loadGeneration = 0;
let lastInput = { value: "", caret: 0 };
async function loadTasks(): Promise<void> {
const generation = ++loadGeneration;
try {
const page = await api.taskPage<TaskRef>({ limit: 100 });
if (generation !== loadGeneration) return;
taskChoices = page.tasks;
taskLoadError.value = "";
} catch (err) {
if (generation !== loadGeneration) return;
taskLoadError.value = (err as Error).message || "Could not load tasks";
}
renderMenu();
}
/** Reads the task list again after a failure, for the menu's Retry. */
export function retryTasks(): void {
taskLoadError.value = "";
void loadTasks();
}
/** Opens the palette for the trigger word the caret sits in, or closes it. */
export function syncCommandMenu(value: string, caret: number): void {
const matches = matchesFor(commandSpecs.value, value, caret);
if (matches.length) {
commandMatches.value = matches;
commandSelection.value = 0;
isCommandMenuOpen.value = true;
lastInput = { value, caret };
// The list is read when # is first typed, so it is never older than the
// moment the operator reached for it.
if (
detectTrigger(value, caret)?.trigger === "#" &&
(!isCommandMenuOpen.value || menuTrigger.value !== "#")
) {
taskLoadError.value = "";
void loadTasks();
}
renderMenu();
}
function renderMenu(): void {
const found = detectTrigger(lastInput.value, lastInput.caret);
let matches: Completion[] = [];
if (found?.trigger === "/") {
matches = commandCompletions(commandSpecs.value, found.query);
} else if (found?.trigger === "#") {
matches = taskCompletions(taskChoices, found.query);
}
const showsError = found?.trigger === "#" && !!taskLoadError.value;
if (!found || (!matches.length && !showsError)) {
isCommandMenuOpen.value = false;
commandMatches.value = [];
return;
}
isCommandMenuOpen.value = false;
commandMatches.value = [];
if (!isCommandMenuOpen.value || menuTrigger.value !== found.trigger) {
commandSelection.value = 0;
}
menuTrigger.value = found.trigger;
commandMatches.value = matches;
commandSelection.value = Math.min(commandSelection.value, Math.max(matches.length - 1, 0));
isCommandMenuOpen.value = true;
}
/** The task a menu row stands for. */
export function taskForKey(key: string): TaskRef | undefined {
return taskChoices.find((task) => String(task.id) === key);
}
export function closeCommandMenu(): void {
@@ -532,9 +632,39 @@ export function moveCommandSelection(delta: number): void {
commandSelection.value = (commandSelection.value + delta + length) % length;
}
/** The page the operator asked from, so an answer can be about what they saw. */
/** The page the operator is on, without the hash the server never sees. */
function currentPage(): string {
return location.pathname + location.search || "/";
return router.currentRoute.value.fullPath.split("#")[0] || "/";
}
// The page whose tag the operator removed. Navigating elsewhere shows the tag
// again, so the dismissal never outlives the page it was made on.
const clearedPage = ref("");
watch(currentPage, () => {
clearedPage.value = "";
});
/** What the next message is about, named for the tag above the composer. */
export const pageTag = computed(() => {
const page = currentPage();
if (page === clearedPage.value) return null;
const route = router.currentRoute.value;
const label =
route.name === "task-detail"
? `Task #${route.params.id}`
: typeof route.meta.label === "string"
? route.meta.label
: page;
return { page, label };
});
export function clearPageTag(): void {
clearedPage.value = currentPage();
}
/** The page sent with a message: the tag's page, or none once it is cleared. */
function sentPage(): string | undefined {
return pageTag.value?.page;
}
export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
@@ -542,8 +672,11 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
// detaches the turn, so its writes stop landing.
const epoch = sessionEpoch;
const explicitText = retryOpts?.textOverride;
const typed = explicitText !== undefined ? explicitText : composerText.value;
const rawValue =
explicitText !== undefined ? explicitText : composerText.value;
explicitText === undefined && !retryOpts?.turn && typed.trim()
? withTaskContext(typed.trim())
: typed;
const { text, turn, isRetry } = resolveTurn(retryOpts, rawValue);
if (!text) return;
if (isSending.value) {
@@ -555,7 +688,7 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
return;
}
queuedMessages.value = [...queuedMessages.value, text];
if (explicitText === undefined) composerText.value = "";
if (explicitText === undefined) clearDraft();
closeCommandMenu();
return;
}
@@ -567,7 +700,7 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
if (!isRetry) {
messages.value = [...messages.value, { from: "web", text }];
// A queued or command send must not clear what is being typed.
if (explicitText === undefined) composerText.value = "";
if (explicitText === undefined) clearDraft();
}
// A bare /model offers its choices as buttons, as Telegram does; with an
@@ -629,7 +762,7 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
channel_id: channelID(),
source_id: turn.sourceID,
text: turn.text,
page: currentPage(),
page: sentPage(),
voice: turn.voice,
},
{ signal: ctrl.signal },
+50
View File
@@ -0,0 +1,50 @@
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;
}
+47
View File
@@ -0,0 +1,47 @@
import { computed, ref, watch } from "vue";
import { isLoadingSession, messages, type ChatMessage } from "./state";
/**
* Counts the replies the operator has not seen. A reply is seen once the
* conversation is open and scrolled to its end; one that lands before that,
* such as a finished task'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
* locally without an id and a later reload returns it with one, and that must
* not count twice.
*/
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 viewing = computed(() => dockOpen.value && atEnd.value);
export const unseenCount = computed(() => Math.max(0, total.value - seen.value));
// Opening or switching a conversation loads it, which is not news; a reload
// that drops a message must also lower the mark so the next reply still counts.
watch(
[total, viewing, isLoadingSession],
([count, watching, loading], [, , wasLoading]) => {
if (watching || loading || wasLoading || count < seen.value) seen.value = count;
},
{ immediate: true },
);
/** The dock reports whether the conversation is open above the composer. */
export function setDockOpen(open: boolean): void {
dockOpen.value = open;
}
/** The scroller's jump button reports whether the reader is at the end. */
export function setAtEnd(end: boolean): void {
atEnd.value = end;
}
+16
View File
@@ -351,3 +351,19 @@
transition-duration: 0.01ms !important;
}
}
/* Widens a control's tap area to 44px on a phone without changing how it looks
or what space it takes. Apply it to a container of buttons. */
@utility touch-hit {
@media (max-width: 767px) {
& button:not(.absolute) {
position: relative;
}
& button::after {
content: "";
position: absolute;
inset-block: min(0px, calc((100% - 44px) / 2));
inset-inline: min(0px, calc((100% - 44px) / 2));
}
}
}