Show attachments and @ files as chips in the composer

Textarea extmarks make [image 1] and @src/ui/App.tsx atomic chips in the accent
colour; backspace deletes one whole, and deleting an attachment's chip removes it.
The sent text is unchanged: attachment chips are left out and @ files go as their
markdown links. The @ menu now edits in place so earlier chips survive.
This commit is contained in:
Callum Alpass committed 2026-11-03 03:25:42 +11:00
1 parent f18fc9c68d
commit ffade010a2
7 files changed
+300 -18

No files matched your search

+9 -2
View File
@@ -23,6 +23,8 @@ export interface ComposerItem {
readonly label: string;
readonly description: string;
readonly replacement: string | null;
/** What the composer shows in place of the replacement, as one chip; the replacement is still what's sent. */
readonly chip?: string;
/** A mention's record (a thread, or a pull request), sent with the message. */
readonly record?: ComposerContextRecord;
readonly action?: "model";
@@ -138,14 +140,19 @@ export function pathItems(entries: readonly ProjectEntry[]): ComposerItem[] {
label: `${entry.path.slice(slash + 1)}${entry.kind === "directory" ? "/" : ""}`,
description: slash > 0 ? entry.path.slice(0, slash) : "",
replacement: `${serializeComposerFileLink(entry.path)} `,
chip: `@${entry.path}${entry.kind === "directory" ? "/" : ""}`,
};
});
}
/** 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);
return replaceTextRange(text, trigger.rangeStart, composerItemEnd(text, trigger, replacement), replacement);
}
/** Where the text a choice replaces ends: the trigger's range, and a space the replacement brings its own of. */
export function composerItemEnd(text: string, trigger: ComposerTrigger, replacement: string): number {
return replacement.endsWith(" ") && text[trigger.rangeEnd] === " " ? trigger.rangeEnd + 1 : trigger.rangeEnd;
}
/** The records for the mentions (threads, pull requests) still in the text, as the message's context. */
+16 -11
View File
@@ -48,9 +48,10 @@ import { SettingsView } from "./SettingsView.tsx";
import { useWorkspace } from "./useWorkspace.ts";
import { usePullRequests } from "./usePullRequests.ts";
import { rendererClipboard, type Clipboard } from "./clipboard.ts";
import { composerText, useComposerChips } from "./useComposerChips.ts";
import { openInBrowser, screenTextAt } from "./links.ts";
import { desktopNotify, ring } from "./terminalOut.ts";
import { colors, statusColor } from "./theme.ts";
import { colors, statusColor, useMarkdownStyle } from "./theme.ts";
import { BAR, NO_BORDER } from "./edges.ts";
import { ThreadList } from "./ThreadList.tsx";
import { useTurns } from "./useTurns.ts";
@@ -114,6 +115,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
const attached = attachThreadId !== undefined;
const renderer = useRenderer();
const [clipboard] = useState(() => props.clipboard ?? rendererClipboard(renderer));
const markdownStyle = useMarkdownStyle();
const { width, height } = useTerminalDimensions();
const [shell, setShell] = useState<ShellState>(session.getShell());
// Any thread, listed or not: subagents open here too.
@@ -434,6 +436,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
confirm,
say,
});
const chips = useComposerChips({ composerRef, composerKey, pending: attach.pending, remove: attach.remove });
const usage = useUsageSummary(session, settingsIndex !== null && live);
const usageInfo = useMemo(() => usageLimits(serverConfig?.config ?? null, now), [serverConfig, now]);
const spendResetCredit = (credit: (typeof usageInfo.credits)[number]) =>
@@ -563,7 +566,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
const composer = composerRef.current;
if (!composer) return;
const key = composerKey;
const file = scratchFile(composer.plainText);
const file = scratchFile(composerText(composer));
showPane({
kind: "local",
id: `message:${file.path}`,
@@ -620,7 +623,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
const putMessage = (key: string, text: string) => {
const composer = composerRef.current;
if (key !== activeComposerKey.current || !composer) return void drafts.current.set(key, text);
composer.setText(text);
chips.replaceText(composer, text);
composer.gotoBufferEnd();
setComposerLines(composerLineCount(composer));
setComposerEmpty(text.trim() === "");
@@ -633,8 +636,8 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
const restoreMessage = (key: string, text: string, context: OrchestrationMessageContext | undefined, attachments: readonly ChatAttachment[]) => {
const composer = composerRef.current;
if (key === activeComposerKey.current && composer) {
if (composer.plainText.trim()) return;
composer.setText(text);
if (composerText(composer).trim()) return;
chips.replaceText(composer, text);
composer.gotoBufferEnd();
setComposerLines(composerLineCount(composer));
setComposerEmpty(text === "");
@@ -658,7 +661,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
};
const clearComposer = () => {
composerRef.current?.setText("");
if (composerRef.current) chips.replaceText(composerRef.current, "");
if (threadId) drafts.current.delete(threadId);
composerMenu.forget();
setComposerLines(1);
@@ -668,11 +671,11 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
/** Enter in the composer; `alternate` is alt+enter, which flips steer and queue. */
const submit = (alternate = false) => {
const composer = composerRef.current;
const raw = composer?.plainText ?? "";
const raw = composer ? composerText(composer) : "";
// A trailing backslash continues onto a new line, for terminals that can't send shift+enter.
if (!alternate && config.sendShortcut === "enter" && composer && raw.endsWith("\\")) {
composer.setText(raw.slice(0, -1));
composer.gotoBufferEnd();
composer.deleteCharBackward();
composer.newLine();
return;
}
@@ -727,10 +730,10 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
const turns = useTurns({ session, threadId, projection, timeline: current, config: providerConfig, cwd: panel.cwd, ignoreWhitespace: config.diffIgnoreWhitespace, enabled: draft === null, diff, setDiff, scrollRef, confirm, say,
showConversation: () => { setMode("nav"); setDetailsPrefState((value) => (width < MIN_CONVERSATION_WIDTH + DETAILS_WIDTH ? false : value)); },
restorePrompt: (id, text) => {
const previous = id === activeComposerKey.current ? composerRef.current?.plainText ?? "" : drafts.current.get(id) ?? "";
const previous = id === activeComposerKey.current && composerRef.current ? composerText(composerRef.current) : drafts.current.get(id) ?? "";
const next = text ? previous ? `${previous}\n\n${text}` : text : previous;
drafts.current.set(id, next);
if (id === activeComposerKey.current) { composerRef.current?.setText(next); setMode("input"); }
if (id === activeComposerKey.current && composerRef.current) { chips.replaceText(composerRef.current, next); setMode("input"); }
},
});
@@ -1334,6 +1337,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
focusedBackgroundColor={colors.element}
wrapMode="word"
keyBindings={[...COMPOSER_KEYS[config.sendShortcut]]}
syntaxStyle={markdownStyle}
onSubmit={() => submit()}
onPaste={(event: PasteEvent) => {
const text = decodePasteBytes(event.bytes);
@@ -1347,8 +1351,9 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
onCursorChange={composerMenu.sync}
onContentChange={() => {
composerMenu.sync();
chips.sync();
const composer = composerRef.current;
const text = composer?.plainText ?? "";
const text = composer ? composerText(composer) : "";
if (text) drafts.current.set(composerKey, text);
else drafts.current.delete(composerKey);
// Wrapped lines count too, so a long paragraph grows the box.
+2
View File
@@ -183,6 +183,8 @@ export function useMarkdownStyle(): SyntaxStyle {
"markup.quote": { fg: colors.muted, italic: true },
"markup.raw": { fg: colors.plan },
"markup.raw.block": { fg: colors.text },
// Attachments and mentions in the message box.
"extmark.chip": { fg: colors.accent, bg: colors.element },
}, owner);
markdownStyles.set(owner, style);
return style;
+135
View File
@@ -0,0 +1,135 @@
import type { Extmark, TextareaRenderable } from "@opentui/core";
import type { ChatAttachment } from "@t3tools/contracts";
import { useEffect, useRef, useState, type RefObject } from "react";
/** What a chip stands for: an attachment, which the sent text leaves out, or a mention, sent as `sent`. */
interface ChipData {
readonly attachmentId?: string;
readonly sent?: string;
}
/**
* Makes `start`–`end` of the composer (in its cursor offsets) one chip: drawn in the accent
* colour, stepped over by the cursor and deleted whole by backspace.
*/
export function markChip(composer: TextareaRenderable, start: number, end: number, data: ChipData): void {
const extmarks = composer.extmarks;
const typeId = extmarks.getTypeId("chip") ?? extmarks.registerType("chip");
const styleId = composer.syntaxStyle?.getStyleId("extmark.chip");
extmarks.create({ start, end, virtual: true, typeId, data, ...(styleId ? { styleId } : {}) });
}
/** Inserts `label` at the cursor as a chip, apart from the words either side. */
function insertChip(composer: TextareaRenderable, label: string, data: ChipData): void {
const before = composer.plainText[indexAtOffset(composer.plainText, composer.cursorOffset) - 1];
if (before && !/\s/.test(before)) composer.insertText(" ");
const start = composer.cursorOffset;
composer.insertText(label);
markChip(composer, start, composer.cursorOffset, data);
composer.insertText(" ");
}
function chipsOf(composer: TextareaRenderable): Extmark[] {
const typeId = composer.extmarks.getTypeId("chip");
return typeId === null ? [] : composer.extmarks.getAllForTypeId(typeId);
}
const attachmentChips = (composer: TextareaRenderable) => chipsOf(composer).filter((chip) => (chip.data as ChipData | undefined)?.attachmentId);
/** The index in `text` of a cursor offset, which counts columns, and one for each line break. */
function indexAtOffset(text: string, offset: number): number {
let column = 0;
let index = 0;
for (const char of text) {
if (column >= offset) break;
column += char === "\n" ? 1 : Bun.stringWidth(char);
index += char.length;
}
return index;
}
/** The composer's text as it is sent and kept as a draft: mentions as they're sent, attachments (and the space after each) left out. */
export function composerText(composer: TextareaRenderable): string {
const text = composer.plainText;
let kept = "";
let from = 0;
for (const chip of chipsOf(composer).sort((a, b) => a.start - b.start)) {
const data = (chip.data ?? {}) as ChipData;
const start = indexAtOffset(text, chip.start);
let end = indexAtOffset(text, chip.end);
if (data.attachmentId && text[end] === " ") end++;
kept += text.slice(from, start) + (data.sent ?? "");
from = end;
}
return kept + text.slice(from);
}
/**
* The composer's attachments as chips, `[image 1]` or `[report.pdf]`: each pending one gets a
* chip at the cursor, removing an attachment takes its chip out, and deleting a chip removes
* its attachment. Replace the text through `replaceText`, so the old chips going with the old
* text doesn't count as deleting them.
*/
export function useComposerChips(deps: {
readonly composerRef: RefObject<TextareaRenderable | null>;
readonly composerKey: string;
readonly pending: readonly ChatAttachment[];
readonly remove: (attachment: ChatAttachment) => void;
}) {
const { composerRef, composerKey, pending } = deps;
/** The attachments with a chip in the composer as it is now. */
const shown = useRef(new Set<string>());
/** Bumped when the text is replaced, so the chips go back in. */
const [replaced, setReplaced] = useState(0);
// A new composer, new attachments or new text: each needs its chips.
useEffect(() => {
const composer = composerRef.current;
if (!composer) return;
const chips = attachmentChips(composer);
const present = new Set(chips.map((chip) => (chip.data as ChipData).attachmentId));
for (const chip of chips) {
if (pending.some((attachment) => attachment.id === (chip.data as ChipData).attachmentId)) continue;
composer.extmarks.delete(chip.id);
removeRange(composer, chip.start, chip.end);
}
let images = 0;
for (const attachment of pending) {
if (attachment.type === "image") images++;
if (!present.has(attachment.id)) insertChip(composer, attachment.type === "image" ? `[image ${images}]` : `[${attachment.name}]`, { attachmentId: attachment.id });
}
shown.current = new Set(pending.map((attachment) => attachment.id));
}, [composerKey, pending, replaced]);
return {
/** The text changed: an attachment whose chip was deleted goes too. */
sync: () => {
const composer = composerRef.current;
if (!composer) return;
const present = new Set(attachmentChips(composer).map((chip) => (chip.data as ChipData).attachmentId));
for (const attachment of pending) {
if (!shown.current.has(attachment.id) || present.has(attachment.id)) continue;
shown.current.delete(attachment.id);
deps.remove(attachment);
}
},
/** Sets the composer's text, then puts the attachment chips back. */
replaceText: (composer: TextareaRenderable, text: string) => {
shown.current.clear();
composer.setText(text);
setReplaced((count) => count + 1);
},
};
}
/** Deletes the text between two cursor offsets, and the space after it, keeping the cursor where it was. */
function removeRange(composer: TextareaRenderable, start: number, end: number): void {
const cursor = composer.cursorOffset;
const stop = end + (composer.plainText[indexAtOffset(composer.plainText, end)] === " " ? 1 : 0);
composer.cursorOffset = start;
const from = composer.logicalCursor;
composer.cursorOffset = stop;
const to = composer.logicalCursor;
composer.deleteRange(from.row, from.col, to.row, to.col);
composer.cursorOffset = cursor >= stop ? cursor - (stop - start) : Math.min(cursor, start);
}
+13 -5
View File
@@ -3,8 +3,9 @@ import type { ComposerContextRecord, EnvironmentId, OrchestrationMessageContext,
import { useEffect, useRef, useState, type RefObject } from "react";
import type { T3Session } from "../client/session.ts";
import { applyComposerItem, composerTrigger, cursorAtIndex, indexAtCursor, messageContext, PATH_SEARCH_LIMIT, pathItems, skillItems, slashItems, threadItems, type ComposerItem } from "../model/composerMenu.ts";
import { composerItemEnd, composerTrigger, cursorAtIndex, indexAtCursor, messageContext, PATH_SEARCH_LIMIT, pathItems, skillItems, slashItems, threadItems, type ComposerItem } from "../model/composerMenu.ts";
import { keys, type Binding } from "../model/keymap.ts";
import { markChip } from "./useComposerChips.ts";
import { useComposerPullRequests } from "./usePullRequests.ts";
/**
@@ -96,10 +97,17 @@ export function useComposerMenu(deps: {
const choose = (item: ComposerItem | undefined) => {
const composer = composerRef.current;
if (!item || !trigger || !composer) return;
const next = applyComposerItem(state.text, trigger, item.replacement ?? "");
composer.setText(next.text);
const at = cursorAtIndex(next.text, next.cursor);
composer.setCursor(at.row, at.col);
// An edit in place rather than new text, which would take the chips already there with it.
const replacement = item.replacement ?? "";
const from = cursorAtIndex(state.text, trigger.rangeStart);
const to = cursorAtIndex(state.text, composerItemEnd(state.text, trigger, replacement));
composer.deleteRange(from.row, from.col, to.row, to.col);
composer.setCursor(from.row, from.col);
const sent = replacement.trimEnd();
const start = composer.cursorOffset;
composer.insertText(item.chip ?? sent);
if (item.chip) markChip(composer, start, composer.cursorOffset, { sent });
composer.insertText(replacement.slice(sent.length));
if (item.record) {
const records = mentions.current.get(composerKey) ?? new Map<string, ComposerContextRecord>();
records.set(item.record.contextId, item.record);