feat(ui): attach tasks to a chat message with # (#1861)

This commit is contained in:
sam committed 2026-11-12 22:43:41 +11:00
1 parent 37ea698a28
commit b234a85090
5 files changed
+287 -66

No files matched your search

+42 -1
View File
@@ -1,5 +1,5 @@
// The chat composer: IME confirmation never submits the draft, Shift+Enter
// inserts a newline, and ordinary Enter submits and clears.
// inserts a newline, ordinary Enter submits and clears, and # attaches a task.
const assert = require('node:assert/strict');
module.exports = async ({ page, go, shot }) => {
@@ -24,5 +24,46 @@ module.exports = async ({ page, go, shot }) => {
await composer.press('Enter');
assert.equal((await request).postDataJSON().text, 'Ordinary Enter submits');
assert.equal(await composer.inputValue(), '');
let failTasks = true;
await page.route('**/api/tasks?*', async route => {
if (failTasks) return route.fulfill({ status: 500, contentType: 'text/plain', body: 'task store down' });
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify([
{ id: 1861, title: "Chat composer: '#' context dropdown", status: 'running' },
{ id: 1842, title: 'Retry stalled task runs', status: 'done' },
]),
});
});
const tasksPalette = page.getByRole('listbox', { name: 'Tasks' });
await composer.fill('Look at #');
await tasksPalette.getByRole('alert').waitFor();
assert.equal(await tasksPalette.getByRole('option').count(), 0);
failTasks = false;
await tasksPalette.getByRole('button', { name: 'Retry' }).click();
await tasksPalette.getByRole('option').first().waitFor();
assert.equal(await tasksPalette.getByRole('option').count(), 2);
await composer.press('Escape');
await tasksPalette.waitFor({ state: 'hidden' });
await composer.fill('Look at #184 now');
await composer.evaluate(el => el.setSelectionRange(12, 12));
await composer.dispatchEvent('input');
await tasksPalette.getByRole('option').first().waitFor();
assert.equal(await tasksPalette.getByRole('option').count(), 1);
await composer.press('Tab');
await tasksPalette.waitFor({ state: 'hidden' });
assert.equal(await composer.inputValue(), 'Look at now');
await page.getByRole('list', { name: 'Attached tasks' }).getByText('#1842').waitFor();
const tagged = page.waitForRequest('**/api/chat/stream');
await composer.press('Enter');
const text = (await tagged).postDataJSON().text;
assert.ok(text.startsWith('Look at now') && text.includes('#1842 Retry stalled task runs'), text);
assert.equal(await page.getByRole('list', { name: 'Attached tasks' }).count(), 0);
await shot('chat-composition');
};
+48 -16
View File
@@ -7,15 +7,22 @@ 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,
composerText,
editQueued,
menuTrigger,
removeTaskTag,
retryTasks,
taskForKey,
taskLoadError,
taskTags,
isCommandMenuOpen,
isSending,
moveCommandSelection,
@@ -110,21 +117,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 +145,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 +169,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 +219,18 @@ function onKeydown(event: KeyboardEvent): void {
</Tooltip>
</li>
</ul>
<ul v-if="taskTags.length" aria-label="Attached tasks" class="mb-2 flex flex-wrap gap-1">
<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,7 +247,7 @@ 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"
@input="onInput"
@@ -226,10 +255,13 @@ function onKeydown(event: KeyboardEvent): void {
/>
<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. -->
+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>
+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,
};
}
+115 -13
View File
@@ -3,7 +3,7 @@ import { computed, onMounted, onUnmounted, ref, watch, type Ref } from "vue";
import { api } from "@/lib/api";
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 +35,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 +210,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 +256,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);
@@ -509,17 +554,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 {
@@ -542,8 +641,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 +657,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 +669,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