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"
>
+
+ {{ error }}
+
+
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