diff --git a/e2e/checks/chat-composer.cjs b/e2e/checks/chat-composer.cjs index eecd42165..c3bda1cab 100644 --- a/e2e/checks/chat-composer.cjs +++ b/e2e/checks/chat-composer.cjs @@ -1,10 +1,11 @@ // 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 }) => { +module.exports = async ({ page, go, shot, tolerate }) => { + tolerate(/api\/tasks/); await go('/events'); - const composer = page.getByRole('textbox', { name: 'Message Archie', exact: true }); + const composer = page.getByRole('combobox', { name: 'Message Archie', exact: true }); await composer.waitFor(); await composer.fill('Composition in progress'); const sent = []; @@ -24,5 +25,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'); }; diff --git a/ui/src/chat/ChatComposer.vue b/ui/src/chat/ChatComposer.vue index 2aba045a8..4bc20724c 100644 --- a/ui/src/chat/ChatComposer.vue +++ b/ui/src/chat/ChatComposer.vue @@ -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 { +
diff --git a/ui/src/chat/ChatSlashPalette.vue b/ui/src/chat/ChatSlashPalette.vue index 86a5d37a6..724902697 100644 --- a/ui/src/chat/ChatSlashPalette.vue +++ b/ui/src/chat/ChatSlashPalette.vue @@ -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(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" > +
diff --git a/ui/src/chat/commands.ts b/ui/src/chat/commands.ts index 1e5524fc6..559059a5a 100644 --- a/ui/src/chat/commands.ts +++ b/ui/src/chat/commands.ts @@ -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, }; } diff --git a/ui/src/chat/state.ts b/ui/src/chat/state.ts index 017a5a0c1..c50ec2f82 100644 --- a/ui/src/chat/state.ts +++ b/ui/src/chat/state.ts @@ -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>({}); +/** 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({}); export const selectedModel = ref(""); export const commandSpecs = ref([]); -export const commandMatches = ref([]); +export const commandMatches = ref([]); +/** Which trigger the open menu was opened by. */ +export const menuTrigger = ref("/"); +/** 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 { + const generation = ++loadGeneration; + try { + const page = await api.taskPage({ 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 { // 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 { 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 { 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