diff --git a/README.md b/README.md index fe568d3..5bef157 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,16 @@ Any mode: Typing: `enter` sends. While the agent is running, `enter` steers it (the message reaches it mid-run) and `alt+enter` queues the message for after the run, as in T3 Code. With an approval pending, a typed message declines it with your feedback. `shift+enter` adds a newline (it needs a terminal with the kitty keyboard protocol); so does ending the line with `\` and pressing `enter`. The box grows up to 8 lines. `ctrl+g` opens the message in `$VISUAL` or `$EDITOR` (falling back to `vi`); save and quit to bring it back. +As in T3 Code's message box, typing a trigger opens a list of suggestions above the box: + +| Trigger | Suggests | Inserts | +| --- | --- | --- | +| `/` | `/model`, then the provider's commands (only at the start of the message) and skills | `/command`, or `$skill` for a skill; `/model` opens the model picker | +| `$` | the provider's skills | `$skill` | +| `@` | threads, then files and folders in the thread's worktree or project | a markdown link to the file, or a link to the thread (sent along with the message, as T3 does) | + +`↑`/`↓` or `ctrl+n`/`ctrl+p` move, `tab` or `enter` chooses, a click chooses, and `esc` closes the list. Links show as raw markdown in the box; T3 shows them as chips. `#` (pull requests) isn't supported yet. + Navigation: | Key | Action | @@ -134,4 +144,4 @@ Type errors after a bump point at the protocol changes to adapt to. ## Not yet supported -Editing queued messages, plan follow-ups, attachments, forking threads, and reviewing or commenting on diffs. Use the T3 Code app for those. +Editing queued messages, `#` pull request mentions, plan follow-ups, attachments, forking threads, and reviewing or commenting on diffs. Use the T3 Code app for those. diff --git a/src/client/session.ts b/src/client/session.ts index dc6c143..536fc85 100644 --- a/src/client/session.ts +++ b/src/client/session.ts @@ -21,6 +21,8 @@ import { type ScheduledTaskId, type ServerConfig, type ModelSelection, + type OrchestrationMessageContext, + type ProjectEntry, type RuntimeMode, type TerminalAttachStreamEvent, type TerminalSummary, @@ -373,7 +375,8 @@ export class T3Session { * "steer" (into the active run) or "queue" (after it). See resolveComposerDispatchMode. */ /** `modelSelection` switches the thread's model (and options) with this message, as the web composer does. */ - sendMessage(threadId: ThreadId, text: string, mode: ComposerDispatchMode = "auto", modelSelection?: ModelSelection): Promise { + /** `context` carries the records for thread mentions in the text. */ + sendMessage(threadId: ThreadId, text: string, mode: ComposerDispatchMode = "auto", modelSelection?: ModelSelection, context?: OrchestrationMessageContext): Promise { const commandId = newCommandId(); return this.dispatch({ type: "message.dispatch", @@ -382,6 +385,7 @@ export class T3Session { messageId: MessageId.make(commandId), text, attachments: [], + ...(context ? { context } : {}), ...(modelSelection ? { modelSelection } : {}), ...(mode === "queue" ? { dispatchMode: { type: "queue_after_active" } } : { dispatchMode: { type: "start_immediately" }, deliveryIntent: mode }), createdBy: "user", @@ -421,15 +425,21 @@ export class T3Session { * Creates a thread and sends its first message in one call, as the web app does when a * draft is first sent. Resolves with the new thread's id. */ - async launchThread(input: Omit & { readonly text: string }): Promise { - const { text, ...rest } = input; + async launchThread(input: Omit & { readonly text: string; readonly context?: OrchestrationMessageContext | undefined }): Promise { + const { text, context, ...rest } = input; const commandId = newCommandId(); const result = await Effect.runPromise( - this.requireConnection().rpc[ORCHESTRATION_V2_WS_METHODS.launchThread]({ ...rest, commandId, initialMessage: { messageId: MessageId.make(commandId), text, attachments: [] } }), + this.requireConnection().rpc[ORCHESTRATION_V2_WS_METHODS.launchThread]({ ...rest, commandId, initialMessage: { messageId: MessageId.make(commandId), text, ...(context ? { context } : {}), attachments: [] } }), ); return result.threadId; } + /** Files and folders under `cwd` matching `query`, as the composer's @ menu searches them. */ + async searchEntries(cwd: string, query: string, limit: number): Promise { + const result = await Effect.runPromise(this.requireConnection().rpc[WS_METHODS.projectsSearchEntries]({ cwd, query, limit })); + return result.entries; + } + /** Whether `cwd` is a repository, and its default branch (else the current one), for a new worktree's base. */ async defaultRef(cwd: string): Promise<{ readonly isRepo: boolean; readonly ref: VcsRef | null }> { const result = await Effect.runPromise(this.requireConnection().rpc[WS_METHODS.vcsListRefs]({ cwd, refKind: "local" })); diff --git a/src/model/composerMenu.ts b/src/model/composerMenu.ts new file mode 100644 index 0000000..afbf944 --- /dev/null +++ b/src/model/composerMenu.ts @@ -0,0 +1,205 @@ +import type { EnvironmentId, OrchestrationMessageContext, OrchestrationV2ShellSnapshot, ProjectEntry, ServerProvider, ServerProviderSkill, ThreadContextRecord, ThreadId } from "@t3tools/contracts"; +import { resolveProviderSkillsForCwd, resolveProviderSlashCommandsForCwd } from "@t3tools/client-runtime/providerSkills"; +import { getProviderSkillsForSlashMenu, getProviderSlashCommandsForSlashMenu } from "@t3tools/client-runtime/providerSkills"; +import { collectComposerContextReferences, formatComposerContextReference, threadContextRecord } from "@t3tools/shared/composerContextReferences"; +import { detectComposerTrigger, replaceTextRange, serializeComposerFileLink, type ComposerTrigger } from "@t3tools/shared/composerTrigger"; +import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills"; +import { foldSearchQuery, scoreThreadSearch } from "@t3tools/shared/paletteSearch"; +import { insertRankedSearchResult, normalizeSearchQuery, scoreQueryMatch } from "@t3tools/shared/searchRanking"; +import * as DateTime from "effect/DateTime"; + +import { scoreProviderSkill, searchProviderSkills } from "../../vendor/t3code/apps/web/src/providerSkillSearch.ts"; + +export type { ComposerTrigger }; + +/** + * A suggestion for the trigger under the cursor, as the web composer's menu offers: `/` for + * commands, `$` for skills, `@` for files and threads. Choosing one swaps the trigger for + * `replacement`; `/model` opens the model picker instead. + */ +export interface ComposerItem { + readonly id: string; + readonly label: string; + readonly description: string; + readonly replacement: string | null; + /** A thread mention's record, sent with the message. */ + readonly record?: ThreadContextRecord; + readonly action?: "model"; +} + +/** As the web's limits: five threads, eighty paths. */ +const THREAD_LIMIT = 5; +export const PATH_SEARCH_LIMIT = 80; + +/** The trigger the cursor sits in, or null. `/model` is a command here, as tui3 has no model-name search. */ +export function composerTrigger(text: string, cursor: number): ComposerTrigger | null { + const trigger = detectComposerTrigger(text, cursor); + if (trigger?.kind === "slash-model") return { ...trigger, kind: "slash-command", query: "model" }; + return trigger; +} + +/** + * `/` suggestions: `/model`, then the provider's commands and skills. Providers only expand + * commands at the start of a message, so elsewhere only skills show; `/compact` only when it is + * the whole message, as the web shows it. + */ +export function slashItems(input: { readonly provider: ServerProvider | undefined; readonly cwd: string | null; readonly text: string; readonly trigger: ComposerTrigger }): ComposerItem[] { + const { provider, trigger, text } = input; + const atStart = text.slice(0, trigger.rangeStart).trim() === ""; + const alone = atStart && text.slice(trigger.rangeEnd).trim() === ""; + const skills = provider ? getProviderSkillsForSlashMenu(resolveProviderSkillsForCwd(provider, input.cwd), true) : []; + const commands = provider ? getProviderSlashCommandsForSlashMenu(resolveProviderSlashCommandsForCwd(provider, input.cwd), skills) : []; + const candidates: SlashCandidate[] = [ + { item: { id: "slash:model", label: "/model", description: "Switch response model for this thread", replacement: null, action: "model" }, name: "model", tier: 0 }, + ...(atStart ? commands : []) + .filter((command) => command.name !== "compact" || alone) + .map((command) => ({ + item: { id: `command:${command.name}`, label: `/${command.name}`, description: command.description ?? command.input?.hint ?? "Run provider command", replacement: `/${command.name} ` }, + name: command.name, + tier: 1, + })), + ...skills.map((skill) => ({ + item: { id: `skill:${skill.name}`, label: `/skill:${skill.name}`, description: skillDescription(skill, ""), replacement: `$${skill.name} ` }, + name: skill.name, + tier: 2, + skill, + })), + ]; + return searchSlash(candidates, trigger.query); +} + +/** `$` suggestions: the provider's skills, ranked as the web ranks them. */ +export function skillItems(provider: ServerProvider | undefined, cwd: string | null, query: string): ComposerItem[] { + if (!provider) return []; + return searchProviderSkills(resolveProviderSkillsForCwd(provider, cwd), query).map((skill) => ({ + id: `skill:${skill.name}`, + label: formatProviderSkillDisplayName(skill), + description: skillDescription(skill, "Run provider skill"), + replacement: `$${skill.name} `, + })); +} + +/** `@` thread suggestions: other top-level threads, ranked like the palette. Needs a query, as the web does. */ +export function threadItems(input: { readonly snapshot: OrchestrationV2ShellSnapshot | null; readonly environmentId: EnvironmentId | null; readonly excludeThreadId: ThreadId | null; readonly query: string; readonly now?: number }): ComposerItem[] { + const query = foldSearchQuery(input.query); + const { snapshot, environmentId } = input; + if (!query || !snapshot || !environmentId) return []; + const now = input.now ?? Date.now(); + const projects = new Map(snapshot.projects.map((project) => [project.id, project.title])); + return snapshot.threads + .filter((thread) => thread.id !== input.excludeThreadId && thread.archivedAt === null && thread.deletedAt === null && thread.lineage.relationshipToParent !== "subagent") + .map((thread) => ({ + thread, + match: scoreThreadSearch( + query, + { + id: thread.id, + title: thread.title, + branch: thread.branch, + projectTitle: projects.get(thread.projectId) ?? null, + pullRequests: (thread.pullRequests ?? []).map((pr) => ({ number: pr.number, title: pr.snapshot?.title ?? null, references: [pr.url] })), + activityAt: DateTime.toEpochMillis(thread.latestUserMessageAt ?? thread.updatedAt), + opens: thread.opens ?? null, + }, + now, + { picks: false }, + ), + })) + .filter((candidate) => candidate.match !== null) + .sort((a, b) => b.match!.score - a.match!.score) + .slice(0, THREAD_LIMIT) + .map(({ thread }) => { + const record = threadContextRecord({ environmentId, threadId: thread.id }, thread.title || "New thread"); + return { id: `thread:${thread.id}`, label: thread.title || "New thread", description: "Thread", replacement: `${formatComposerContextReference(record)} `, record }; + }); +} + +/** `@` path suggestions from the server's search, inserted as the web inserts them: a markdown link. */ +export function pathItems(entries: readonly ProjectEntry[]): ComposerItem[] { + return entries.map((entry) => { + const slash = entry.path.lastIndexOf("/"); + return { + id: `path:${entry.kind}:${entry.path}`, + label: `${entry.path.slice(slash + 1)}${entry.kind === "directory" ? "/" : ""}`, + description: slash > 0 ? entry.path.slice(0, slash) : "", + replacement: `${serializeComposerFileLink(entry.path)} `, + }; + }); +} + +/** The text with the trigger replaced; a trailing space swallows one already there, as the web does. */ +export function applyComposerItem(text: string, trigger: ComposerTrigger, replacement: string): { text: string; cursor: number } { + const end = replacement.endsWith(" ") && text[trigger.rangeEnd] === " " ? trigger.rangeEnd + 1 : trigger.rangeEnd; + return replaceTextRange(text, trigger.rangeStart, end, replacement); +} + +/** The records for the thread mentions still in the text, as the message's context. */ +export function messageContext(text: string, records: ReadonlyMap): OrchestrationMessageContext | undefined { + const referenced = new Set(collectComposerContextReferences(text).map((occurrence) => occurrence.contextId as string)); + const kept = [...records.values()].filter((record) => referenced.has(record.contextId)); + return kept.length > 0 ? { version: 1, records: kept } : undefined; +} + +function skillDescription(skill: ServerProviderSkill, fallback: string): string { + return skill.shortDescription ?? skill.description ?? (skill.scope ? `${skill.scope} skill` : fallback); +} + +interface SlashCandidate { + readonly item: ComposerItem; + readonly name: string; + readonly tier: number; + readonly skill?: ServerProviderSkill; +} + +/** The web's slash ranking (composerSlashCommandSearch): name first, then description; `skill:` narrows to skills. */ +function searchSlash(candidates: readonly SlashCandidate[], rawQuery: string): ComposerItem[] { + const query = normalizeSearchQuery(rawQuery, { trimLeadingPattern: /^\/+/ }); + if (!query) return candidates.map((candidate) => candidate.item); + const ranked: { item: ComposerItem; score: number; tieBreaker: string }[] = []; + for (const candidate of candidates) { + const score = scoreSlash(candidate, query); + if (score === null) continue; + insertRankedSearchResult(ranked, { item: candidate.item, score, tieBreaker: `${candidate.tier}\u0000${candidate.name}` }, Number.POSITIVE_INFINITY); + } + return ranked.map((entry) => entry.item); +} + +function scoreSlash(candidate: SlashCandidate, query: string): number | null { + if (candidate.skill) { + if (query === "skill") return 0; + const skillQuery = query.startsWith("skill:") ? query.slice("skill:".length) : query; + const skillScore = skillQuery ? scoreProviderSkill(candidate.skill, skillQuery) : 0; + if (skillScore !== null) return skillScore; + return "skill".startsWith(query) ? Number.MAX_SAFE_INTEGER : null; + } + const scores = [ + scoreQueryMatch({ value: candidate.name.toLowerCase(), query, exactBase: 0, prefixBase: 2, boundaryBase: 4, includesBase: 6, fuzzyBase: 100, boundaryMarkers: ["-", "_", "/"] }), + scoreQueryMatch({ value: candidate.item.description.toLowerCase(), query, exactBase: 20, prefixBase: 22, boundaryBase: 24, includesBase: 26 }), + ].filter((score): score is number => score !== null); + return scores.length > 0 ? Math.min(...scores) : null; +} + +/** + * The textarea's cursor is in display columns (a wide character counts two); these convert + * between it and string indices. + */ +export function indexAtCursor(text: string, row: number, col: number): number { + const lines = text.split("\n"); + let index = 0; + for (let line = 0; line < row && line < lines.length; line++) index += lines[line]!.length + 1; + let width = 0; + for (const { segment } of graphemes.segment(lines[row] ?? "")) { + if (width >= col) break; + width += Bun.stringWidth(segment); + index += segment.length; + } + return index; +} + +export function cursorAtIndex(text: string, index: number): { row: number; col: number } { + const before = text.slice(0, index); + const lines = before.split("\n"); + return { row: lines.length - 1, col: Bun.stringWidth(lines[lines.length - 1] ?? "") }; +} + +const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" }); diff --git a/src/ui/App.tsx b/src/ui/App.tsx index b657acb..8390b11 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -13,8 +13,10 @@ import { DEFAULT_TERMINAL_ID, type DiscoveredLocalServer, type ModelSelection, t import { homedir } from "node:os"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import type { OrchestrationMessageContext, ProjectEntry, ThreadContextRecord } from "@t3tools/contracts"; import type { FeedState, ServerConfigState, ShellState, T3Session, ThreadState, VcsState } from "../client/session.ts"; import { createAlerts, type Alert } from "../model/alerts.ts"; +import { applyComposerItem, composerTrigger, cursorAtIndex, indexAtCursor, messageContext, PATH_SEARCH_LIMIT, pathItems, skillItems, slashItems, threadItems, type ComposerItem } from "../model/composerMenu.ts"; import { draftDefaults, lockedProviderInstance, modelSummary, optionDescriptors, optionValue, optionValueLabel, providerName, RUNTIME_MODES, sameSelection, selectableProviders, withModel, withOption, type DraftThread } from "../model/models.ts"; import { configPath, cycleConfig, saveConfig, type Tui3Config } from "../config.ts"; import { detailsActions, detailsCwd, RUNTIME_MODE_LABELS, threadDetails, type DetailsAction, type GitAction } from "../model/details.ts"; @@ -22,6 +24,7 @@ import { paletteEntries, paletteGroups, pickerGroups, type PaletteCommand, type import { serverSettingLines, settingRows } from "../model/settings.ts"; import { buildTimeline, type Timeline } from "../model/timeline.ts"; import { threadRows, type Section } from "../model/threads.ts"; +import { ComposerMenu } from "./ComposerMenu.tsx"; import { ConfirmBar, type Confirmation } from "./ConfirmBar.tsx"; import { DetailsPanel } from "./DetailsPanel.tsx"; import { DiffView, type DiffState } from "./DiffView.tsx"; @@ -111,6 +114,14 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C const [flash, setFlash] = useState<{ text: string; bad?: boolean } | null>(null); const [composerLines, setComposerLines] = useState(1); const [composerEmpty, setComposerEmpty] = useState(true); + /** The composer's text and cursor (a string index), for the / $ @ menu. */ + const [composerState, setComposerState] = useState({ text: "", cursor: 0 }); + const [menuIndex, setMenuIndex] = useState(0); + /** The trigger esc closed the menu for; typing on reopens it. */ + const [menuDismissed, setMenuDismissed] = useState(null); + const [pathResults, setPathResults] = useState<{ key: string; entries: readonly ProjectEntry[] } | null>(null); + /** Thread mentions per composer, sent as the message's context. */ + const mentions = useRef(new Map>()); const [questionDrafts, setQuestionDrafts] = useState>(new Map()); const [now, setNow] = useState(Date.now()); const scrollRef = useRef(null); @@ -157,6 +168,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C const selectedIndex = rows.findIndex((row) => row.thread.id === threadId); const threadRow = allRows.find((row) => row.thread.id === threadId); const threadShell = threadRow?.thread ?? shell.snapshot?.threads.find((thread) => thread.id === threadId) ?? (threadId ? familyShells.get(threadId) : undefined); + const composerKey: string = draft ? DRAFT_KEY : (threadId ?? ""); // Pin the initial selection to a thread, or it would follow whatever sorts first. useEffect(() => { if (selectedId === undefined && rows[0]) setSelectedId(rows[0].thread.id); @@ -562,7 +574,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C }); }; const toggleWorkspace = () => draft && setDraft({ ...draft, envMode: draft.envMode === "local" ? "worktree" : "local" }); - const launchDraft = (text: string) => { + const launchDraft = (text: string, context?: OrchestrationMessageContext) => { if (!draft || !draftProject) return; const launching = draft; const project = draftProject; @@ -583,6 +595,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C interactionMode: "default", workspaceStrategy, text, + context, }); })().then( (id) => { @@ -662,6 +675,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C const clearComposer = () => { composerRef.current?.setText(""); if (threadId) drafts.current.delete(threadId); + mentions.current.delete(composerKey); setComposerLines(1); setComposerEmpty(true); }; @@ -707,10 +721,11 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C return; } const text = raw.trim(); + const context = messageContext(text, mentions.current.get(composerKey) ?? new Map()); if (draft) { if (!text) return; clearComposer(); - return launchDraft(text); + return launchDraft(text, context); } if (!threadId) return; if (pendingInput && questionDraft) { @@ -725,7 +740,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C if (pendingApproval) { // As in the web composer: the message declines the request and redirects the agent. if (pendingApproval.supportsFeedback) return run("Declined with feedback", () => session.respond(threadId, pendingApproval.requestId, "decline", text)); - return run("Declined and redirected", () => session.sendMessage(threadId, text, "steer")); + return run("Declined and redirected", () => session.sendMessage(threadId, text, "steer", undefined, context)); } const dispatchMode = resolveComposerDispatchMode({ running: working, alternateModifier: alternate, activeTurnDefault: config.followUpBehavior }); const pendingModel = pendingModels.get(threadId); @@ -736,7 +751,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C return next; }); } - run(dispatchMode === "queue" ? "Queued" : dispatchMode === "steer" ? "Steered" : "Sent", () => session.sendMessage(threadId, text, dispatchMode, pendingModel)); + run(dispatchMode === "queue" ? "Queued" : dispatchMode === "steer" ? "Steered" : "Sent", () => session.sendMessage(threadId, text, dispatchMode, pendingModel, context)); }; const loadEarlier = () => { @@ -828,7 +843,89 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C return false; }; + // The / $ @ menu: the web composer's suggestions for the trigger under the cursor. + const composerCwd = draft ? (draftProject?.workspaceRoot ?? null) : (threadShell?.worktreePath ?? project?.workspaceRoot ?? null); + const composerProvider = currentModel ? providerConfig?.providers.find((candidate) => candidate.instanceId === currentModel.instanceId) : undefined; + const trigger = mode === "input" && (threadId || draft) ? composerTrigger(composerState.text, composerState.cursor) : null; + const triggerKey = trigger ? `${composerKey}:${trigger.kind}:${trigger.rangeStart}:${trigger.query}` : null; + const pathKey = trigger?.kind === "path" && trigger.query.trim() && composerCwd ? `${composerCwd}\u0000${trigger.query.trim()}` : null; + useEffect(() => { + if (!pathKey) return; + const [cwd, query] = pathKey.split("\u0000") as [string, string]; + // Debounced as the web's path search is. + const timer = setTimeout(() => { + session.searchEntries(cwd, query, PATH_SEARCH_LIMIT).then( + (entries) => setPathResults({ key: pathKey, entries }), + () => setPathResults({ key: pathKey, entries: [] }), + ); + }, 120); + return () => clearTimeout(timer); + }, [session, pathKey]); + const menu = ((): { items: ComposerItem[]; empty: string; loading: boolean } | null => { + if (!trigger || triggerKey === menuDismissed) return null; + switch (trigger.kind) { + case "slash-command": + case "slash-model": + return { items: slashItems({ provider: composerProvider, cwd: composerCwd, text: composerState.text, trigger }), empty: "No matching command.", loading: false }; + case "skill": + return { items: skillItems(composerProvider, composerCwd, trigger.query), empty: "No skills found. Try / to browse provider commands.", loading: false }; + case "path": { + if (!trigger.query.trim()) return { items: [], empty: "Type to search files, folders and threads.", loading: false }; + const threads = threadItems({ snapshot: shell.snapshot, environmentId: providerConfig?.environment.environmentId ?? null, excludeThreadId: draft ? null : (threadId ?? null), query: trigger.query, now }); + const fresh = pathResults?.key === pathKey; + return { items: [...threads, ...(fresh ? pathItems(pathResults.entries) : [])], empty: fresh ? "No matching files or folders." : "Searching…", loading: !fresh }; + } + default: + return null; + } + })(); + const menuOpen = menu !== null; + const menuSelected = menu ? Math.min(menuIndex, Math.max(0, menu.items.length - 1)) : 0; + useEffect(() => setMenuIndex(0), [triggerKey]); + // A different composer (another thread, or the draft) mounts with its own text. + useEffect(() => { + const timer = setTimeout(syncComposerState, 0); + return () => clearTimeout(timer); + // eslint-disable-next-line react-hooks/exhaustive-deps -- syncComposerState reads the ref. + }, [composerKey]); + const syncComposerState = () => { + const composer = composerRef.current; + if (!composer) return; + const text = composer.plainText; + const { row, col } = composer.logicalCursor; + setComposerState({ text, cursor: indexAtCursor(text, row, col) }); + }; + const chooseMenuItem = (item: ComposerItem | undefined) => { + const composer = composerRef.current; + if (!item || !trigger || !composer) return; + const next = applyComposerItem(composerState.text, trigger, item.replacement ?? ""); + composer.setText(next.text); + const at = cursorAtIndex(next.text, next.cursor); + composer.setCursor(at.row, at.col); + if (item.record) { + const records = mentions.current.get(composerKey) ?? new Map(); + records.set(item.record.contextId, item.record); + mentions.current.set(composerKey, records); + } + syncComposerState(); + setComposerLines(composerLineCount(composer)); + if (item.action === "model") openModelPicker(); + }; + /** Keys the menu takes while it's open; the rest go to the message box. */ + const menuKey = (key: KeyEvent): boolean => { + if (!menu) return false; + if (key.name === "escape") return setMenuDismissed(triggerKey), true; + // Enter waits for a search in flight rather than sending the half-typed mention. + if (menu.loading && key.name === "return") return true; + if (menu.items.length === 0) return false; + if (key.name === "down" || (key.ctrl && key.name === "n")) return setMenuIndex(Math.min(menu.items.length - 1, menuSelected + 1)), true; + if (key.name === "up" || (key.ctrl && key.name === "p")) return setMenuIndex(Math.max(0, menuSelected - 1)), true; + if (key.name === "tab" || (key.name === "return" && !key.shift && !key.meta)) return chooseMenuItem(menu.items[menuSelected]), true; + return false; + }; + useKeyboard((key) => { + if (mode === "input" && menuKey(key)) return key.preventDefault(); if (mode === "picker") { if (key.ctrl && key.name === "c") return quit(); if (key.name === "escape") { @@ -1019,7 +1116,6 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C : "Steer the agent (alt+enter to queue instead)" : "Ask anything"; // The model with its options, then the mode when it isn't full access; click or m to change. - const composerKey: string = draft ? DRAFT_KEY : (threadId ?? ""); const pendingModel = !draft && threadShell ? pendingModels.get(threadShell.id) : undefined; const footer = currentModel && runtimeMode @@ -1136,6 +1232,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C }} /> ) : null} + {menu ? chooseMenuItem(menu.items[index])} /> : null} {threadId || draft ? ( submit()} + onCursorChange={syncComposerState} onContentChange={() => { + syncComposerState(); const composer = composerRef.current; const text = composer?.plainText ?? ""; if (text) drafts.current.set(composerKey, text); else drafts.current.delete(composerKey); // Wrapped lines count too, so a long paragraph grows the box. - // The wrapped count can lag a programmatic newline, so hard lines are a floor. - setComposerLines(Math.max(text.split("\n").length, composer?.virtualLineCount ?? 1)); + setComposerLines(composer ? composerLineCount(composer) : 1); setComposerEmpty(text.trim() === ""); }} /> @@ -1185,6 +1283,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C {flash ? ( {flash.text} + ) : menuOpen ? ( + ↑/↓ move · tab or enter choose · esc close ) : ( {hints(mode, { draft: draft !== null, config, approval: Boolean(pendingApproval), question: Boolean(pendingInput), working, attached, diff: diff !== null, parent: parent !== undefined })} )} @@ -1257,6 +1357,16 @@ function hints( const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error)); +/** + * The composer's height in lines, wrapped lines included. The wrapped count can lag a + * programmatic change, so the hard lines, each wrapped at the box's width, are a floor. + */ +function composerLineCount(composer: TextareaRenderable): number { + const width = Math.max(1, composer.width); + const estimate = composer.plainText.split("\n").reduce((lines, line) => lines + Math.max(1, Math.ceil(Bun.stringWidth(line) / width)), 0); + return Math.max(estimate, composer.virtualLineCount); +} + function firstLine(text: string): string { const line = (text.trim().split("\n")[0] ?? "").replace(/\s+/g, " "); return line.length > 100 ? `${line.slice(0, 99)}…` : line; diff --git a/src/ui/ComposerMenu.tsx b/src/ui/ComposerMenu.tsx new file mode 100644 index 0000000..899f83e --- /dev/null +++ b/src/ui/ComposerMenu.tsx @@ -0,0 +1,40 @@ +import type { ComposerItem } from "../model/composerMenu.ts"; +import { colors } from "./theme.ts"; + +const MAX_ROWS = 8; + +/** + * The web composer's / $ @ menu, just above the message box: ↑/↓ or ctrl+n/p move, tab or + * enter chooses, a click chooses, esc closes. + */ +export function ComposerMenu(props: { readonly items: readonly ComposerItem[]; readonly selected: number; readonly empty: string; readonly width: number; readonly onPick: (index: number) => void }) { + const { items, selected } = props; + const start = Math.max(0, Math.min(selected - Math.floor(MAX_ROWS / 2), items.length - MAX_ROWS)); + const inner = Math.max(10, props.width - 4); + return ( + + {items.length === 0 ? ( + + {props.empty} + + ) : ( + items.slice(start, start + MAX_ROWS).map((item, offset) => { + const index = start + offset; + const label = truncate(item.label, Math.floor(inner * 0.5)); + return ( + props.onPick(index)}> + {label} + {` ${truncate(item.description, inner - label.length - 2)}`} + + ); + }) + )} + {items.length > MAX_ROWS ? {`${selected + 1} of ${items.length}`} : null} + + ); +} + +function truncate(text: string, width: number): string { + const single = text.replace(/\s+/g, " "); + return single.length > width ? `${single.slice(0, Math.max(0, width - 1))}…` : single; +} diff --git a/test/composerMenu.test.ts b/test/composerMenu.test.ts new file mode 100644 index 0000000..d644148 --- /dev/null +++ b/test/composerMenu.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, test } from "bun:test"; +import { EnvironmentId, OrchestrationV2Command, ThreadId, type OrchestrationV2ShellSnapshot, type ServerProvider } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; + +import { T3Session } from "../src/client/session.ts"; +import { applyComposerItem, composerTrigger, cursorAtIndex, indexAtCursor, messageContext, pathItems, skillItems, slashItems, threadItems } from "../src/model/composerMenu.ts"; + +const provider = { + instanceId: "claude", + slashCommands: [{ name: "review", description: "Review the diff" }, { name: "compact", description: "Compact the conversation" }], + skills: [ + { name: "deploy", description: "Ship it", path: "/s/deploy", enabled: true }, + { name: "hidden", path: "/s/hidden", enabled: true, userInvocable: false }, + { name: "off", path: "/s/off", enabled: false }, + ], +} as unknown as ServerProvider; + +function slash(text: string, cursor = text.length) { + const trigger = composerTrigger(text, cursor)!; + return slashItems({ provider, cwd: null, text, trigger }).map((item) => item.label); +} + +describe("composer menu", () => { + test("finds the trigger under the cursor, as the web composer does", () => { + expect(composerTrigger("/rev", 4)).toMatchObject({ kind: "slash-command", query: "rev", rangeStart: 0 }); + expect(composerTrigger("look at @src/ap", 15)).toMatchObject({ kind: "path", query: "src/ap", rangeStart: 8 }); + expect(composerTrigger("use $dep", 8)).toMatchObject({ kind: "skill", query: "dep" }); + expect(composerTrigger("costs $5", 8)).toBeNull(); + expect(composerTrigger("see /usr/lib", 12)).toBeNull(); + expect(composerTrigger("/model", 6)).toMatchObject({ kind: "slash-command", query: "model" }); + }); + + test("offers provider commands only at the start, and /compact only alone", () => { + expect(slash("/")).toEqual(["/model", "/review", "/compact", "/skill:deploy"]); + expect(slash("/ then more", 1)).toEqual(["/model", "/review", "/skill:deploy"]); + expect(slash("text /")).toEqual(["/model", "/skill:deploy"]); + expect(slash("/rev")[0]).toBe("/review"); + }); + + test("skills leave out disabled and agent-only ones and insert $name", () => { + const items = skillItems(provider, null, ""); + expect(items.map((item) => item.replacement)).toEqual(["$deploy "]); + }); + + test("replacing swallows a following space and puts the cursor after it", () => { + const text = "run $dep now"; + const trigger = composerTrigger(text, 8)!; + expect(applyComposerItem(text, trigger, "$deploy ")).toEqual({ text: "run $deploy now", cursor: 12 }); + }); + + test("paths insert the web's file link", () => { + const [item] = pathItems([{ path: "src/ui/App (old).tsx", kind: "file" }]); + expect(item).toMatchObject({ label: "App (old).tsx", description: "src/ui", replacement: "[App (old).tsx](src/ui/App%20%28old%29.tsx) " }); + }); + + test("a thread mention sends its record while its link stays in the text", async () => { + const snapshot = { + projects: [{ id: "p", title: "proj" }], + threads: [ + { id: "t1", projectId: "p", title: "Release supervisor", branch: null, archivedAt: null, deletedAt: null, lineage: { relationshipToParent: null }, updatedAt: "2026-11-01T00:00:00.000Z", latestUserMessageAt: null }, + { id: "t2", projectId: "p", title: "Release helper", branch: null, archivedAt: null, deletedAt: null, lineage: { relationshipToParent: "subagent" }, updatedAt: "2026-11-01T00:00:00.000Z", latestUserMessageAt: null }, + ], + } as unknown as OrchestrationV2ShellSnapshot; + const items = threadItems({ snapshot, environmentId: EnvironmentId.make("env-1"), excludeThreadId: null, query: "release" }); + expect(items.map((item) => item.label)).toEqual(["Release supervisor"]); + const record = items[0]!.record!; + const text = `compare with ${items[0]!.replacement}please`; + const records = new Map([[record.contextId as string, record]]); + const context = messageContext(text, records); + expect(context).toEqual({ version: 1, records: [record] }); + expect(messageContext("link removed", records)).toBeUndefined(); + + const session = new T3Session(); + const sent: unknown[] = []; + (session as unknown as { dispatch: (command: unknown) => Promise }).dispatch = async (command) => void sent.push(command); + await session.sendMessage(ThreadId.make("t9"), text, "auto", undefined, context); + expect(Schema.is(OrchestrationV2Command)(sent[0])).toBe(true); + expect(sent[0]).toMatchObject({ context: { records: [{ kind: "thread", threadId: "t1" }] } }); + }); + + test("cursor columns count wide characters twice", () => { + const text = "é😀ab\nx你y"; + expect(indexAtCursor(text, 0, 3)).toBe(3); // after the emoji + expect(indexAtCursor(text, 1, 3)).toBe(text.indexOf("y")); + expect(cursorAtIndex(text, text.indexOf("y"))).toEqual({ row: 1, col: 3 }); + }); +});