Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(chat): put plugin chips in the typing line

rubenluetke10-beepa59aedc5c0c3
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx b/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx
index d936f40c29..edf2c7d1dd 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
ArrowUp,
Bot,
@@ -32,10 +32,9 @@ import { ComposerTypeahead } from "@/components/agentchat/ComposerTypeahead";
import { ChatAttachmentStrip } from "@/components/agentchat/ChatAttachmentStrip";
import { DictationStatus } from "@/components/agentchat/DictationStatus";
import { ComposerAddMenu } from "@/components/agentchat/ComposerAddMenu";
-import { ToolChoiceChips } from "@/components/agentchat/ToolChoiceChips";
+import { ComposerChipField, type ComposerChipFieldHandle } from "@/components/agentchat/ComposerChipField";
import type { ToolChoice } from "@/components/agentchat/toolChoices";
import { GigiMark } from "@/components/GigiMark";
-import { useAutoGrowTextarea } from "@/hooks/useAutoGrowTextarea";
import { fill, useT } from "@/i18n";
import { cn } from "@/lib/utils";
@@ -83,9 +82,16 @@ import { cn } from "@/lib/utils";
export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {
const t = useT();
const [value, setValueState] = useState("");
- const textareaRef = useAutoGrowTextarea(value);
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
+ const fieldRef = useRef<ComposerChipFieldHandle>(null);
const setValue = useCallback(
- (next: string | ((current: string) => string)) => setValueState(next),
+ (next: string | ((current: string) => string)) => {
+ setValueState((current) => {
+ const text = typeof next === "function" ? next(current) : next;
+ fieldRef.current?.setText(text);
+ return text;
+ });
+ },
[],
);
const connected = useEventStore((s) => s.connected);
@@ -173,7 +179,7 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {
provider: draft.provider,
cwd: draft.cwd,
triggers,
- });
+ }, fieldRef);
const running = runningTurn(timeline) !== null;
@@ -187,6 +193,7 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {
if (files.analyzing > 0) return; // a file still being read would be sent without its contents
if (dictating) stopDictation();
setValueState("");
+ fieldRef.current?.clear();
setAttachError("");
const attached = files.attachments;
files.clear();
@@ -207,18 +214,6 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {
}
}
- function onKeyDown(ev: KeyboardEvent<HTMLTextAreaElement>) {
- // Watches for a Ctrl+V the embedded browser may never answer; does nothing
- // in a real browser, where the box pastes on its own.
- pasteRescue.onKeyDown(ev);
- // An open list owns the arrows, Enter, Tab and Escape.
- if (typeahead.onKeyDown(ev)) return;
- if (ev.key === "Enter" && !ev.shiftKey) {
- ev.preventDefault();
- void onSend();
- }
- }
-
async function onPickFolder() {
try {
const path = await pickAgentChatFolder(draft.cwd || undefined);
@@ -470,10 +465,6 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {
{/* The blue variant of this strip lived here; a running microphone is a
live state, not the accent, so it now shares the one green strip. */}
<DictationStatus onStop={stopDictation} />
- <ToolChoiceChips
- items={selectedTools}
- onRemove={(id) => setSelectedTools((rows) => rows.filter((row) => row.id !== id))}
- />
<ChatAttachmentStrip
attachments={files.attachments}
analyzing={files.analyzing}
@@ -489,29 +480,26 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {
onHover={typeahead.setActiveIndex}
onPick={typeahead.pick}
/>
- <textarea
- ref={textareaRef}
- data-jarvis-chat-input=""
+ <ComposerChipField
+ ref={fieldRef}
+ placeholder={placeholder}
+ disabled={!connected}
autoFocus={autoFocus}
- value={value}
- onChange={(e) => setValueState(e.target.value)}
- onKeyDown={onKeyDown}
- onSelect={typeahead.refresh}
- onClick={typeahead.refresh}
- onBlur={typeahead.blur}
- aria-expanded={typeahead.open || undefined}
- aria-autocomplete={triggers.length ? "list" : undefined}
- onPaste={(e) => {
+ onSubmit={() => void onSend()}
+ onDraftChange={(draft) => {
+ setValueState(draft.text);
+ setSelectedTools(draft.choices);
+ }}
+ onKeyDown={(ev) => {
+ pasteRescue.onKeyDown(ev);
+ if (typeahead.onKeyDown(ev)) return true;
+ return false;
+ }}
+ onPasteFiles={(e) => {
pasteRescue.onPaste();
files.onPaste(e);
}}
- placeholder={placeholder}
- disabled={!connected}
- rows={2}
- // Grows with the text up to half the window (useAutoGrowTextarea), so
- // a message is read whole while it is written; past the cap the box
- // scrolls rather than pushing the picks and Send out of reach.
- className="max-h-[50vh] w-full resize-none bg-transparent px-1 py-1 text-reading text-foreground scrollbar-jarvis placeholder:text-muted-foreground focus-visible:outline-none disabled:opacity-50"
+ className="max-h-[50vh] text-reading scrollbar-jarvis"
/>
<div className="flex flex-wrap items-center gap-1">
{surface === "jarvis" && (
@@ -524,6 +512,7 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {
stance={draft.permissionMode}
selected={selectedTools}
onChange={setSelectedTools}
+ onInsert={(row) => fieldRef.current?.insertChip(row)}
onAttach={() => fileInputRef.current?.click()}
onFolder={() => void onPickFolder()}
onConnect={(row) =>
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx
index 7814f4c966..0ebfd9b69c 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx
@@ -23,7 +23,7 @@ import {
} from "lucide-react";
import { LiveCore } from "@/components/LiveCore";
-import { ToolChoiceChips } from "./ToolChoiceChips";
+import { MessageWithChips } from "./ToolChoiceChips";
import { ProviderLogo } from "@/components/providers/ProviderLogo";
import { formatThoughtDuration } from "@/components/home/TurnSteps";
import { agentToolView, formatTokens, outputTokens } from "@/components/agentchat/toolView";
@@ -113,8 +113,7 @@ export function AgentTimeline({
data-message-id={item.id}
>
<div className="jarvis-user-bubble max-w-[85%] rounded-lg px-4 py-3 text-reading">
- {item.text && <div className="whitespace-pre-wrap">{item.text}</div>}
- <ToolChoiceChips items={item.toolChoices ?? []} />
+ <MessageWithChips text={item.text} choices={item.toolChoices ?? []} />
{item.attachments.length > 0 && (
<div
data-testid="agent-message-attachments"
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ComposerAddMenu.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ComposerAddMenu.tsx
index a32cb58a6f..6b211db71d 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/ComposerAddMenu.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/ComposerAddMenu.tsx
@@ -22,6 +22,7 @@ export function ComposerAddMenu({
stance,
selected,
onChange,
+ onInsert,
onAttach,
onFolder,
onConnect,
@@ -34,6 +35,7 @@ export function ComposerAddMenu({
stance: string;
selected: ToolChoice[];
onChange: (items: ToolChoice[]) => void;
+ onInsert?: (row: ToolChoice) => void;
onAttach: () => void;
onFolder: () => void;
onConnect: (row: ToolChoice) => void;
@@ -328,6 +330,11 @@ export function ComposerAddMenu({
onConnect(row);
return;
}
+ if (onInsert) {
+ onInsert(row);
+ if (!picked) onChange([...selected, row]);
+ return;
+ }
onChange(
picked ? selected.filter((s) => s.id !== row.id) : [...selected, row],
);
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ComposerChipField.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ComposerChipField.test.tsx
new file mode 100644
index 0000000000..979646719a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/ComposerChipField.test.tsx
@@ -0,0 +1,38 @@
+import { createRef } from "react";
+import { describe, expect, it } from "vitest";
+import { render, screen } from "@testing-library/react";
+
+import { ComposerChipField, type ComposerChipFieldHandle } from "./ComposerChipField";
+import type { ToolChoice } from "./toolChoices";
+
+const gmail: ToolChoice = {
+ id: "plugin:gmail",
+ label: "Gmail",
+ brand: "gmail",
+ category: "plugins",
+ group: "Gmail",
+ description: "Mail",
+ available: true,
+ tool_names: ["gmail"],
+ skill: "",
+};
+
+describe("ComposerChipField", () => {
+ it("puts a plugin chip in the sentence at the caret", () => {
+ const handle = createRef<ComposerChipFieldHandle>();
+ render(
+ <ComposerChipField
+ ref={handle}
+ placeholder="Message"
+ onSubmit={() => {}}
+ onDraftChange={() => {}}
+ />,
+ );
+ handle.current?.hydrate("I am now", []);
+ handle.current?.hydrate("I am @gmail now", [gmail]);
+ const field = screen.getByTestId("composer-chip-field");
+ expect(field.querySelector('[data-brand="gmail"]')?.textContent).toContain("Gmail");
+ expect(handle.current?.getDraft().text).toContain("@gmail");
+ expect(handle.current?.getDraft().choices.map((row) => row.id)).toEqual(["plugin:gmail"]);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ComposerChipField.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ComposerChipField.tsx
new file mode 100644
index 0000000000..b7c4c50397
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/ComposerChipField.tsx
@@ -0,0 +1,290 @@
+import {
+ forwardRef,
+ useEffect,
+ useImperativeHandle,
+ useRef,
+ type ClipboardEvent,
+ type FormEvent,
+ type KeyboardEvent,
+} from "react";
+
+import { cn } from "@/lib/utils";
+import { choiceLookup, choiceToken } from "./composerChips";
+import type { ToolChoice } from "./toolChoices";
+import { toolIdentity, toolIdentityStyle } from "./toolIdentity";
+import "./toolIdentity.css";
+
+export interface ComposerDraft {
+ text: string;
+ choices: ToolChoice[];
+ caret: number;
+}
+
+export interface ComposerChipFieldHandle {
+ insertChip: (row: ToolChoice) => void;
+ insertText: (text: string) => void;
+ hydrate: (text: string, choices?: ToolChoice[]) => void;
+ getDraft: () => ComposerDraft;
+ clear: () => void;
+ focus: () => void;
+ setText: (text: string) => void;
+}
+
+function readChoice(node: HTMLElement): ToolChoice | null {
+ const raw = node.dataset.choice;
+ if (!raw) return null;
+ try {
+ return JSON.parse(decodeURIComponent(raw)) as ToolChoice;
+ } catch {
+ return null;
+ }
+}
+
+function createChipEl(row: ToolChoice): HTMLSpanElement {
+ const identity = toolIdentity(row);
+ const el = document.createElement("span");
+ el.contentEditable = "false";
+ el.className = "tool-identity tool-choice-chip";
+ el.dataset.inline = "true";
+ el.dataset.toolChip = "true";
+ el.dataset.toolId = row.id;
+ el.dataset.brand = identity.key ?? row.category;
+ el.dataset.choice = encodeURIComponent(JSON.stringify(row));
+ el.title = row.description || row.label;
+ Object.assign(el.style, toolIdentityStyle(row));
+
+ const icon = document.createElement("span");
+ icon.className = "tool-choice-icon";
+ icon.style.width = "16px";
+ icon.style.height = "16px";
+ icon.setAttribute("aria-hidden", "true");
+ if (identity.logo && identity.mark === "mono") {
+ const mask = document.createElement("span");
+ mask.className = "tool-choice-mask";
+ mask.style.setProperty("--tool-logo", `url("${identity.logo}")`);
+ icon.appendChild(mask);
+ } else if (identity.logo) {
+ const img = document.createElement("img");
+ img.src = identity.logo;
+ img.alt = "";
+ icon.appendChild(img);
+ }
+ const label = document.createElement("span");
+ label.textContent = row.label;
+ el.append(icon, label);
+ return el;
+}
+
+function serialize(root: HTMLElement): ComposerDraft {
+ const choices: ToolChoice[] = [];
+ let text = "";
+ const sel = root.ownerDocument.getSelection();
+ let caret = 0;
+ let seenCaret = false;
+
+ const walk = (node: Node) => {
+ if (!seenCaret && sel && sel.anchorNode === node) {
+ caret = text.length + (node.nodeType === Node.TEXT_NODE ? sel.anchorOffset : 0);
+ seenCaret = true;
+ }
+ if (node.nodeType === Node.TEXT_NODE) {
+ text += node.textContent ?? "";
+ return;
+ }
+ if (node.nodeType !== Node.ELEMENT_NODE) return;
+ const el = node as HTMLElement;
+ if (el.dataset.toolChip) {
+ const row = readChoice(el);
+ if (row) {
+ const token = `${choiceToken(row)}`;
+ if (!seenCaret && sel && el.contains(sel.anchorNode)) {
+ caret = text.length + token.length;
+ seenCaret = true;
+ }
+ text += token;
+ choices.push(row);
+ }
+ return;
+ }
+ if (el.tagName === "BR") {
+ text += "\n";
+ return;
+ }
+ if (el.tagName === "DIV" || el.tagName === "P") {
+ if (text && !text.endsWith("\n")) text += "\n";
+ }
+ for (const child of Array.from(node.childNodes)) walk(child);
+ };
+ for (const child of Array.from(root.childNodes)) walk(child);
+ if (!seenCaret) caret = text.length;
+ return { text, choices, caret };
+}
+
+function caretRange(root: HTMLElement): Range {
+ const sel = root.ownerDocument.getSelection();
+ if (sel && sel.rangeCount && root.contains(sel.anchorNode)) {
+ return sel.getRangeAt(0);
+ }
+ const range = root.ownerDocument.createRange();
+ range.selectNodeContents(root);
+ range.collapse(false);
+ return range;
+}
+
+function placeAfter(node: Node) {
+ const range = node.ownerDocument!.createRange();
+ range.setStartAfter(node);
+ range.collapse(true);
+ const sel = node.ownerDocument!.getSelection();
+ sel?.removeAllRanges();
+ sel?.addRange(range);
+}
+
+function hydrateRoot(root: HTMLElement, text: string, choices: ToolChoice[] = []) {
+ root.innerHTML = "";
+ const tags = choiceLookup(choices);
+ const chunks = text.split(/(@[^\s@]+)/g);
+ const doc = root.ownerDocument;
+ for (const chunk of chunks) {
+ if (!chunk) continue;
+ const name = chunk.startsWith("@") ? chunk.slice(1).toLowerCase() : "";
+ const row = name ? tags.get(name) : undefined;
+ if (row) root.appendChild(createChipEl(row));
+ else root.appendChild(doc.createTextNode(chunk));
+ }
+}
+
+export const ComposerChipField = forwardRef<
+ ComposerChipFieldHandle,
+ {
+ placeholder: string;
+ disabled?: boolean;
+ autoFocus?: boolean;
+ onSubmit: () => void;
+ onDraftChange: (draft: ComposerDraft) => void;
+ onKeyDown?: (event: KeyboardEvent<HTMLDivElement>) => boolean | void;
+ onPasteFiles?: (event: ClipboardEvent<HTMLElement>) => void;
+ className?: string;
+ }
+>(function ComposerChipField(
+ { placeholder, disabled, autoFocus, onSubmit, onDraftChange, onKeyDown: onKeyDownProp, onPasteFiles, className },
+ ref,
+) {
+ const elRef = useRef<HTMLDivElement>(null);
+
+ const emit = () => {
+ const root = elRef.current;
+ if (!root) return;
+ onDraftChange(serialize(root));
+ };
+
+ const insertNode = (node: Node, afterSpace = true) => {
+ const root = elRef.current;
+ if (!root) return;
+ root.focus();
+ const range = caretRange(root);
+ range.deleteContents();
+ range.insertNode(node);
+ if (afterSpace) {
+ const space = root.ownerDocument.createTextNode(" ");
+ node.parentNode?.insertBefore(space, node.nextSibling);
+ placeAfter(space);
+ } else {
+ placeAfter(node);
+ }
+ emit();
+ };
+
+ useImperativeHandle(ref, () => ({
+ insertChip(row) {
+ insertNode(createChipEl(row));
+ },
+ insertText(text) {
+ insertNode(elRef.current!.ownerDocument.createTextNode(text), false);
+ },
+ hydrate(text, choices = []) {
+ const root = elRef.current;
+ if (!root) return;
+ hydrateRoot(root, text, choices);
+ emit();
+ root.focus();
+ },
+ getDraft() {
+ return elRef.current ? serialize(elRef.current) : { text: "", choices: [], caret: 0 };
+ },
+ clear() {
+ const root = elRef.current;
+ if (!root) return;
+ root.innerHTML = "";
+ emit();
+ },
+ focus() {
+ elRef.current?.focus();
+ },
+ setText(text) {
+ const root = elRef.current;
+ if (!root) return;
+ root.textContent = text;
+ emit();
+ },
+ }));
+
+ useEffect(() => {
+ if (autoFocus) elRef.current?.focus();
+ }, [autoFocus]);
+
+ useEffect(() => {
+ const root = elRef.current;
+ if (!root) return;
+ const onSel = () => {
+ const sel = root.ownerDocument.getSelection();
+ if (sel?.anchorNode && root.contains(sel.anchorNode)) emit();
+ };
+ root.ownerDocument.addEventListener("selectionchange", onSel);
+ return () => root.ownerDocument.removeEventListener("selectionchange", onSel);
+ }, []);
+
+ function onInput(_ev: FormEvent<HTMLDivElement>) {
+ emit();
+ }
+
+ function onKeyDown(ev: KeyboardEvent<HTMLDivElement>) {
+ if (onKeyDownProp?.(ev)) return;
+ if (ev.defaultPrevented) return;
+ if (ev.key === "Enter" && !ev.shiftKey) {
+ ev.preventDefault();
+ onSubmit();
+ }
+ }
+
+ function onPaste(ev: ClipboardEvent<HTMLElement>) {
+ onPasteFiles?.(ev);
+ if (ev.defaultPrevented) return;
+ const text = ev.clipboardData.getData("text/plain");
+ if (!text) return;
+ ev.preventDefault();
+ insertNode(ev.currentTarget.ownerDocument.createTextNode(text), false);
+ }
+
+ return (
+ <div
+ ref={elRef}
+ role="textbox"
+ aria-multiline="true"
+ aria-placeholder={placeholder}
+ aria-disabled={disabled || undefined}
+ contentEditable={!disabled}
+ data-placeholder={placeholder}
+ data-testid="composer-chip-field"
+ data-jarvis-chat-input=""
+ suppressContentEditableWarning
+ onInput={onInput}
+ onKeyDown={onKeyDown}
+ onPaste={onPaste}
+ className={cn(
+ "composer-chip-field min-h-[32px] flex-1 bg-transparent px-1 py-1.5 text-sm leading-relaxed text-foreground outline-none",
+ className,
+ )}
+ />
+ );
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ToolChoiceChips.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ToolChoiceChips.tsx
index 17568e0284..5219283a06 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/ToolChoiceChips.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/ToolChoiceChips.tsx
@@ -1,7 +1,8 @@
-import { useState, type CSSProperties } from "react";
+import { Fragment, useState, type CSSProperties } from "react";
import { X } from "lucide-react";
import { useT } from "@/i18n";
import type { ToolChoice } from "./toolChoices";
+import { splitMessageChips } from "./composerChips";
import { toolIdentity, toolIdentityStyle } from "./toolIdentity";
import "./toolIdentity.css";
@@ -32,6 +33,39 @@ export function ToolChoiceIcon({ row, size = 20 }: { row: ToolChoice; size?: num
);
}
+export function ToolChoiceChip({
+ row,
+ onRemove,
+}: {
+ row: ToolChoice;
+ onRemove?: (id: string) => void;
+}) {
+ const t = useT();
+ return (
+ <span
+ className="tool-identity tool-choice-chip"
+ style={toolIdentityStyle(row)}
+ data-brand={toolIdentity(row).key ?? row.category}
+ data-tool-id={row.id}
+ data-editable={Boolean(onRemove)}
+ title={row.description || row.label}
+ >
+ <ToolChoiceIcon row={row} size={16} />
+ <span className="truncate">{row.label}</span>
+ {onRemove && (
+ <button
+ type="button"
+ onClick={() => onRemove(row.id)}
+ aria-label={`${t("chat_tools.remove")} ${row.label}`}
+ className="ml-0.5 inline-flex h-5 w-5 items-center justify-center rounded focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-current"
+ >
+ <X className="h-3 w-3" aria-hidden />
+ </button>
+ )}
+ </span>
+ );
+}
+
export function ToolChoiceChips({
items,
onRemove,
@@ -39,7 +73,6 @@ export function ToolChoiceChips({
items: ToolChoice[];
onRemove?: (id: string) => void;
}) {
- const t = useT();
if (!items.length) return null;
return (
<div
@@ -47,30 +80,26 @@ export function ToolChoiceChips({
data-editable={Boolean(onRemove)}
data-testid="tool-choice-chips"
>
- {items.map((row) => (
- <span
- key={row.id}
- className="tool-identity tool-choice-chip"
- style={toolIdentityStyle(row)}
- data-brand={toolIdentity(row).key ?? row.category}
- data-tool-id={row.id}
- data-editable={Boolean(onRemove)}
- title={row.description || row.label}
- >
- <ToolChoiceIcon row={row} size={16} />
- <span className="truncate">{row.label}</span>
- {onRemove && (
- <button
- type="button"
- onClick={() => onRemove(row.id)}
- aria-label={`${t("chat_tools.remove")} ${row.label}`}
- className="ml-0.5 inline-flex h-5 w-5 items-center justify-center rounded focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-current"
- >
- <X className="h-3 w-3" aria-hidden />
- </button>
- )}
- </span>
+ {items.map((row, index) => (
+ <ToolChoiceChip key={`${row.id}:${index}`} row={row} onRemove={onRemove} />
))}
</div>
);
}
+
+/** A stored sentence with `@gmail` tags drawn as brand pills in the same line. */
+export function MessageWithChips({ text, choices }: { text: string; choices: ToolChoice[] }) {
+ const parts = splitMessageChips(text, choices);
+ if (!parts.length) return null;
+ return (
+ <span data-testid="tool-choice-chips" data-editable="false" className="whitespace-pre-wrap">
+ {parts.map((part, index) =>
+ part.type === "text" ? (
+ <Fragment key={index}>{part.text}</Fragment>
+ ) : (
+ <ToolChoiceChip key={`${part.row.id}:${index}`} row={part.row} />
+ ),
+ )}
+ </span>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/composerChips.test.ts b/jarvis/ui/web/frontend/src/components/agentchat/composerChips.test.ts
new file mode 100644
index 0000000000..71c5428b33
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/composerChips.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from "vitest";
+
+import { choiceTag, choiceToken, splitMessageChips } from "./composerChips";
+import type { ToolChoice } from "./toolChoices";
+
+const gmail: ToolChoice = {
+ id: "plugin:gmail",
+ label: "Gmail",
+ brand: "gmail",
+ category: "plugins",
+ group: "Gmail",
+ description: "Mail",
+ available: true,
+ tool_names: ["gmail"],
+ skill: "",
+};
+
+describe("composer chips", () => {
+ it("tags a plugin as @gmail", () => {
+ expect(choiceTag(gmail)).toBe("gmail");
+ expect(choiceToken(gmail)).toBe("@gmail");
+ });
+
+ it("keeps chips in the sentence, not in a row of their own", () => {
+ const parts = splitMessageChips("I am @gmail now", [gmail]);
+ expect(parts).toEqual([
+ { type: "text", text: "I am " },
+ { type: "chip", row: gmail },
+ { type: "text", text: " now" },
+ ]);
+ });
+
+ it("still shows a chip after old messages that stored it separately", () => {
+ const parts = splitMessageChips("Find that email", [gmail]);
+ expect(parts[0]).toEqual({ type: "text", text: "Find that email" });
+ expect(parts[1]).toEqual({ type: "chip", row: gmail });
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/composerChips.ts b/jarvis/ui/web/frontend/src/components/agentchat/composerChips.ts
new file mode 100644
index 0000000000..67d766bf57
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/composerChips.ts
@@ -0,0 +1,55 @@
+/** Inline plugin chips in the composer: `@gmail` in the sent text, a brand pill on screen. */
+
+import type { ToolChoice } from "./toolChoices";
+
+const CHIP_RE = /(@[^\s@]+)/g;
+
+export function choiceTag(row: ToolChoice): string {
+ const raw = row.brand || row.id.replace(/^(plugin|mcp|cli|skill|core):/i, "");
+ return raw.replace(/_/g, "-").toLowerCase();
+}
+
+export function choiceToken(row: ToolChoice): string {
+ return `@${choiceTag(row)}`;
+}
+
+export function choiceLookup(choices: readonly ToolChoice[]): Map<string, ToolChoice> {
+ const tags = new Map<string, ToolChoice>();
+ for (const row of choices) {
+ tags.set(choiceTag(row), row);
+ const rest = row.id.replace(/^(plugin|mcp|cli|skill|core):/i, "").toLowerCase();
+ tags.set(rest.replace(/_/g, "-"), row);
+ tags.set(rest.replace(/-/g, "_"), row);
+ if (row.brand) tags.set(row.brand.toLowerCase().replace(/_/g, "-"), row);
+ }
+ return tags;
+}
+
+/** Split a stored message into text runs and the chips those `@tags` name. */
+export function splitMessageChips(
+ text: string,
+ choices: readonly ToolChoice[],
+): Array<{ type: "text"; text: string } | { type: "chip"; row: ToolChoice }> {
+ if (!text) {
+ return choices.length ? choices.map((row) => ({ type: "chip" as const, row })) : [];
+ }
+ const tags = choiceLookup(choices);
+ const used = new Set<ToolChoice>();
+ const parts: Array<{ type: "text"; text: string } | { type: "chip"; row: ToolChoice }> = [];
+ const chunks = text.split(CHIP_RE);
+ for (const chunk of chunks) {
+ if (!chunk) continue;
+ const name = chunk.startsWith("@") ? chunk.slice(1).toLowerCase() : "";
+ const row = name ? tags.get(name) : undefined;
+ if (row) {
+ parts.push({ type: "chip", row });
+ used.add(row);
+ } else {
+ parts.push({ type: "text", text: chunk });
+ }
+ }
+ for (const row of choices) {
+ if (!used.has(row)) parts.push({ type: "chip", row });
+ }
+ return parts;
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.css b/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.css
index f7cfe7552e..adfcc3b00a 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.css
+++ b/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.css
@@ -34,6 +34,27 @@
background: var(--tool-wash);
box-shadow: inset 0 0 0 1px var(--tool-wash);
}
+.composer-chip-field {
+ white-space: pre-wrap;
+ word-break: break-word;
+}
+.composer-chip-field:empty::before,
+.composer-chip-field:not(:focus):has(> br:only-child)::before {
+ content: attr(data-placeholder);
+ color: hsl(var(--muted-foreground));
+ pointer-events: none;
+}
+.composer-chip-field .tool-choice-chip,
+.tool-choice-chip[data-inline="true"] {
+ display: inline-flex;
+ vertical-align: middle;
+ margin: 0 0.12em;
+ padding: 1px 8px 1px 6px;
+ border-radius: 999px;
+ background: var(--tool-wash);
+ box-shadow: inset 0 0 0 1px var(--tool-wash);
+ max-width: 14rem;
+}
.tool-choice-chip button {
color: inherit;
opacity: 0.65;
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.test.tsx
index 69b8bfffb2..59ea60cd3a 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.test.tsx
@@ -112,7 +112,7 @@ describe("tool visual identities", () => {
const chips = screen.getByTestId("tool-choice-chips");
expect(chips.dataset.editable).toBe("false");
expect(chips.querySelector('[data-brand="gmail"]')).not.toBeNull();
- expect(chips.previousElementSibling?.textContent).toBe("Find that email");
+ expect(chips.textContent).toContain("Find that email");
expect(chips.querySelector("button")).toBeNull();
});
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/useComposerTypeahead.ts b/jarvis/ui/web/frontend/src/components/agentchat/useComposerTypeahead.ts
index 7d45eb3609..65f1a9ae11 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/useComposerTypeahead.ts
+++ b/jarvis/ui/web/frontend/src/components/agentchat/useComposerTypeahead.ts
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent, type RefObject } from "react";
+import type { ComposerChipFieldHandle } from "@/components/agentchat/ComposerChipField";
import { fetchTypeahead, type AgentChatSurface } from "@/lib/agentChatApi";
import {
activeToken,
@@ -25,7 +26,7 @@ export interface ComposerTypeahead {
/** Re-read the caret; call after any change, click or arrow key in the box. */
refresh: () => void;
/** Returns true when the key was the list's — the caller must then stop. */
- onKeyDown: (ev: KeyboardEvent<HTMLTextAreaElement>) => boolean;
+ onKeyDown: (ev: KeyboardEvent<HTMLElement>) => boolean;
pick: (item: TypeaheadItem) => void;
/** Escape: hide the list for this token until the token changes. */
close: () => void;
@@ -56,6 +57,7 @@ export function useComposerTypeahead(
value: string,
setValue: (next: string) => void,
seat: Seat,
+ fieldRef?: RefObject<ComposerChipFieldHandle | null>,
): ComposerTypeahead {
const [token, setToken] = useState<ActiveToken | null>(null);
const [rawItems, setRawItems] = useState<TypeaheadItem[]>([]);
@@ -68,12 +70,15 @@ export function useComposerTypeahead(
seatRef.current = seat;
const refresh = useCallback(() => {
+ const draft = fieldRef?.current?.getDraft();
const box = textareaRef.current;
- if (!box) {
+ const text = draft?.text ?? box?.value;
+ if (text == null) {
setToken(null);
return;
}
- const next = activeToken(box.value, box.selectionStart ?? box.value.length, seatRef.current.triggers);
+ const caret = draft?.caret ?? box?.selectionStart ?? text.length;
+ const next = activeToken(text, caret, seatRef.current.triggers);
if (next && dismissedStart.current === next.start) {
setToken(null);
return;
@@ -84,7 +89,7 @@ export function useComposerTypeahead(
? prev
: next,
);
- }, [textareaRef]);
+ }, [textareaRef, fieldRef]);
// The value can change under the box without a key (dictation, a paste
// rescue, a pick); the caret is read afterwards so the token follows.
@@ -173,28 +178,31 @@ export function useComposerTypeahead(
const pick = useCallback(
(item: TypeaheadItem) => {
const box = textareaRef.current;
+ const field = fieldRef?.current;
if (!token) return;
- const applied = applyPick(box ? box.value : value, token, item);
+ const applied = applyPick(field?.getDraft().text ?? box?.value ?? value, token, item);
setValue(applied.text);
+ if (field) field.hydrate(applied.text, field.getDraft().choices);
dismissedStart.current = null;
setToken(null);
- // The caret lands after what was inserted, once React has painted the new value.
window.requestAnimationFrame(() => {
const el = textareaRef.current;
- if (!el) return;
- el.focus();
- el.setSelectionRange(applied.caret, applied.caret);
- // A folder keeps the list open on its contents; refresh reads the caret.
+ if (el) {
+ el.focus();
+ el.setSelectionRange(applied.caret, applied.caret);
+ } else {
+ field?.focus();
+ }
if (item.kind === "folder") refresh();
});
},
- [token, textareaRef, value, setValue, refresh],
+ [token, textareaRef, fieldRef, value, setValue, refresh],
);
const open = Boolean(token) && (loading || items.length > 0 || query.length > 0);
const onKeyDown = useCallback(
- (ev: KeyboardEvent<HTMLTextAreaElement>): boolean => {
+ (ev: KeyboardEvent<HTMLElement>): boolean => {
if (!token || !open) return false;
switch (ev.key) {
case "ArrowDown":
diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
index cbd6090ca9..f6d20aee89 100644
--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
@@ -20,14 +20,16 @@ import { InternalMessageBubble } from "@/components/agentchat/InternalMessageBub
* the voice runs on the realtime tier (`[brain.realtime]`), which no text
* runner can drive. The header says so while voice is showing.
*/
-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { Brain, ChevronRight, MessageSquare, Mic, Paperclip, Plus, RotateCcw, Send, Square } from "lucide-react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { AgentChatStoreProvider, useAgentChat } from "@/components/agentchat/AgentChatStoreContext";
import { ChatAttachmentStrip } from "@/components/agentchat/ChatAttachmentStrip";
-import { ToolChoiceChips } from "@/components/agentchat/ToolChoiceChips";
+import { ComposerChipField, type ComposerChipFieldHandle } from "@/components/agentchat/ComposerChipField";
+import { MessageWithChips } from "@/components/agentchat/ToolChoiceChips";
+import { choiceToken } from "@/components/agentchat/composerChips";
import { useChatAttachments } from "@/components/agentchat/useChatAttachments";
import { DictationStatus } from "@/components/agentchat/DictationStatus";
import { useComposerDictation } from "@/components/agentchat/useComposerDictation";
@@ -52,7 +54,7 @@ import { AgentSwatch } from "../AgentSwatch";
import { useResolveProposal, useSocietyCapabilities, type SocietyAgent } from "../data";
import { MentionPicker } from "./MentionPicker";
import { AgentModelPicker } from "./AgentModelPicker";
-import { mentionChoice, messageChoices, withoutChoiceTokens } from "./mentionChoices";
+import { mentionChoice, messageChoices } from "./mentionChoices";
import {
buildMentionCatalog,
filterMentions,
@@ -809,12 +811,11 @@ function visibleUserText(text: string): string {
export function UserBubble({ item }: { item: UserItem }) {
const choices = messageChoices(item);
- const text = withoutChoiceTokens(visibleUserText(item.text), choices);
+ const text = visibleUserText(item.text);
return (
<div className="flex max-w-[85%] flex-col items-end gap-1 self-end">
- <div className="whitespace-pre-wrap rounded-2xl rounded-br-md bg-secondary px-3.5 py-2 text-sm leading-relaxed text-foreground">
- {text}
- <ToolChoiceChips items={choices} />
+ <div className="rounded-2xl rounded-br-md bg-secondary px-3.5 py-2 text-sm leading-relaxed text-foreground">
+ <MessageWithChips text={text} choices={choices} />
</div>
{item.attachments.length > 0 ? (
<div className="flex flex-wrap justify-end gap-1">
@@ -1103,19 +1104,15 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, s
const [activeIndex, setActiveIndex] = useState(0);
const [selectedTools, setSelectedTools] = useState<MentionItem[]>([]);
useEffect(() => { setSelectedTools([]); }, [sessionId, agent.agentId]);
- const textarea = useRef<HTMLTextAreaElement>(null);
+ const fieldRef = useRef<ComposerChipFieldHandle>(null);
const composerRef = useRef<HTMLDivElement>(null);
const fileInput = useRef<HTMLInputElement>(null);
const attachments = useChatAttachments({ sessionId, cwd, provider, surface }, (message) => setProblem(message));
- const dictation = useComposerDictation(value, setValue);
-
- const resize = useCallback(() => {
- const el = textarea.current;
- if (!el) return;
- el.style.height = "0px";
- el.style.height = `${Math.min(el.scrollHeight, 180)}px`;
- }, []);
- useEffect(resize, [value, resize]);
+ const dictation = useComposerDictation(value, (next) => {
+ const text = typeof next === "function" ? next(value) : next;
+ setValue(text);
+ fieldRef.current?.setText(text);
+ });
// "@" completes teammates AND the capability catalog — plugins, MCP
// servers, CLIs, skills, Jarvis tools — on every agent card, including
@@ -1137,32 +1134,35 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, s
if (activeIndex >= matches.length) setActiveIndex(Math.max(0, matches.length - 1));
}, [matches.length, activeIndex]);
- const onChange = (next: string, caret: number) => {
- setValue(next);
- setMention(mentionToken(next, caret));
+ const onDraftChange = (draft: { text: string; caret: number }) => {
+ setValue(draft.text);
+ setMention(mentionToken(draft.text, draft.caret));
};
const insertMention = (item: MentionItem) => {
- if (!mention) return;
- const el = textarea.current;
- const caret = el?.selectionStart ?? value.length;
- const inserted = item.agent ? `@${item.value} ` : "";
- if (!item.agent) setSelectedTools((items) => items.some((row) => row.key === item.key) ? items : [...items, item]);
- const next = `${value.slice(0, mention.start)}${inserted}${value.slice(caret)}`;
- setValue(next);
+ const field = fieldRef.current;
+ const draft = field?.getDraft();
+ const start = mention?.start ?? draft?.caret ?? value.length;
+ const caret = draft?.caret ?? value.length;
+ const before = (draft?.text ?? value).slice(0, start);
+ const after = (draft?.text ?? value).slice(caret);
+ if (item.agent) {
+ const next = `${before}@${item.value} ${after}`;
+ field?.hydrate(next, draft?.choices ?? []);
+ } else {
+ const row = mentionChoice(item);
+ const next = `${before}${choiceToken(row)} ${after}`;
+ field?.hydrate(next, [...(draft?.choices ?? []), row]);
+ setSelectedTools((items) => (items.some((row) => row.key === item.key) ? items : [...items, item]));
+ }
setMention(null);
- requestAnimationFrame(() => {
- if (!el) return;
- el.focus();
- const at = mention.start + inserted.length;
- el.setSelectionRange(at, at);
- });
};
const submit = async () => {
- const draftText = value.trim();
+ const draft = fieldRef.current?.getDraft();
+ const draftText = (draft?.text ?? value).trim();
const selected = selectedTools;
- const text = [draftText, ...selected.map((row) => `@${row.value}`)].filter(Boolean).join(" ");
+ const text = draftText;
if (!text || busy || modelSaving) return;
const named = mentionsInText(text, catalog);
const lines = named.agents.map(
@@ -1171,6 +1171,7 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, s
if (named.pinIds.length > 0) lines.push(`${TOOL_PIN_MARK} ${named.pinIds.join(", ")}]`);
const hint = lines.join("\n");
setValue("");
+ fieldRef.current?.clear();
setMention(null);
setProblem(null);
try {
@@ -1179,6 +1180,7 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, s
attachments.clear();
} catch (err) {
setValue(draftText);
+ fieldRef.current?.hydrate(draftText, draft?.choices ?? []);
setSelectedTools(selected);
setProblem(err instanceof Error ? err.message : String(err));
}
@@ -1190,10 +1192,6 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, s
<div className="shrink-0 border-t border-border px-3 pb-3 pt-2">
{problem ? <p className="mb-1 px-1 text-xs text-destructive">{problem}</p> : null}
<div className={CHAT_MEASURE}>
- <div className="mb-1.5">
- <ToolChoiceChips items={selectedTools.map(mentionChoice)}
- onRemove={(id) => setSelectedTools((items) => items.filter((row) => row.key !== id))} />
- </div>
<ChatAttachmentStrip attachments={attachments.attachments} analyzing={attachments.analyzing} onRemove={attachments.remove} />
</div>
<DictationStatus onStop={dictation.stop} className={cn(CHAT_MEASURE, "mb-1.5")} />
@@ -1232,12 +1230,8 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, s
<div className="absolute bottom-full left-0 z-20 mb-1 w-52 overflow-hidden rounded-lg border border-border bg-popover py-1 shadow-float">
<button type="button" onClick={() => {
setPlusOpen(false);
- const caret = textarea.current?.selectionStart ?? value.length;
- const prefix = value.slice(0, caret);
- const token = `${prefix && !/\s$/.test(prefix) ? " " : ""}@`;
- const next = prefix + token + value.slice(caret);
- onChange(next, caret + token.length);
- requestAnimationFrame(() => { textarea.current?.focus(); textarea.current?.setSelectionRange(caret + token.length, caret + token.length); });
+ fieldRef.current?.insertText("@");
+ fieldRef.current?.focus();
}} className="flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs text-foreground hover:bg-secondary">
<Plus className="h-3.5 w-3.5" aria-hidden />{t("chat_tools.all")}
</button>
@@ -1277,46 +1271,42 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, s
}}
/>
</div>
- <textarea
- ref={textarea}
- value={value}
- rows={1}
+ <ComposerChipField
+ ref={fieldRef}
placeholder={t("society.chat.placeholder").replace("{0}", agent.name)}
- onChange={(e) => onChange(e.target.value, e.target.selectionStart ?? e.target.value.length)}
- onPaste={attachments.onPaste}
+ disabled={busy}
+ onSubmit={() => void submit()}
+ onDraftChange={onDraftChange}
+ onPasteFiles={attachments.onPaste}
onKeyDown={(e) => {
- if (pickerOpen) {
- if (e.key === "ArrowDown") {
- e.preventDefault();
- if (matches.length) setActiveIndex((i) => (i + 1) % matches.length);
- return;
- }
- if (e.key === "ArrowUp") {
- e.preventDefault();
- if (matches.length) setActiveIndex((i) => (i - 1 + matches.length) % matches.length);
- return;
- }
- if (e.key === "Escape") {
- e.preventDefault();
- setMention(null);
- return;
- }
- if (e.key === "Tab" || (e.key === "Enter" && !e.shiftKey)) {
- const item = matches[activeIndex] ?? matches[0];
- if (item) {
- e.preventDefault();
- insertMention(item);
- return;
- }
- if (e.key === "Tab") return;
- }
+ if (!pickerOpen) return false;
+ if (e.key === "ArrowDown") {
+ e.preventDefault();
+ if (matches.length) setActiveIndex((i) => (i + 1) % matches.length);
+ return true;
}
- if (e.key === "Enter" && !e.shiftKey) {
+ if (e.key === "ArrowUp") {
e.preventDefault();
- void submit();
+ if (matches.length) setActiveIndex((i) => (i - 1 + matches.length) % matches.length);
+ return true;
+ }
+ if (e.key === "Escape") {
+ e.preventDefault();
+ setMention(null);
+ return true;
+ }
+ if (e.key === "Tab" || (e.key === "Enter" && !e.shiftKey)) {
+ const item = matches[activeIndex] ?? matches[0];
+ if (item) {
+ e.preventDefault();
+ insertMention(item);
+ return true;
+ }
+ if (e.key === "Tab") return true;
}
+ return false;
}}
- className="max-h-[180px] min-h-[32px] flex-1 resize-none bg-transparent px-1 py-1.5 text-sm leading-relaxed text-foreground placeholder:text-muted-foreground focus:outline-none"
+ className="max-h-[180px]"
/>
<button
type="button"
diff --git a/jarvis/ui/web/frontend/src/components/society/chat/mentionChoices.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/mentionChoices.test.tsx
index a4f229ad8d..445a633a56 100644
--- a/jarvis/ui/web/frontend/src/components/society/chat/mentionChoices.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/chat/mentionChoices.test.tsx
@@ -59,11 +59,8 @@ it("uses Add to select a real branded chip and preserves the existing pin protoc
fireEvent.click(screen.getByRole("button", { name: "society.chat.more" }));
fireEvent.click(screen.getByRole("button", { name: "chat_tools.all" }));
fireEvent.click(await screen.findByRole("option", { name: /@\s*gmail/ }));
- const chips = screen.getByTestId("tool-choice-chips");
- expect(chips.querySelector('[data-brand="gmail"] img')).not.toBeNull();
const input = screen.getByRole("textbox");
- expect((input as HTMLTextAreaElement).value).toBe("");
- fireEvent.change(input, { target: { value: "Check unread mail" } });
+ expect(input.querySelector('[data-brand="gmail"] img')).not.toBeNull();
fireEvent.click(screen.getByRole("button", { name: "society.chat.send" }));
await waitFor(() => expect(send).toHaveBeenCalledOnce());
const text = String(send.mock.calls[0][0]);
@@ -77,8 +74,8 @@ it("uses Add to select a real branded chip and preserves the existing pin protoc
it("reconstructs branded tags from an existing saved agent-card message", () => {
const text = "Read this @gmail\n\n[tools: plugin:gmail]";
render(<UserBubble item={{ type: "user", id: "m1", tsMs: 1, text, attachments: [] }} />);
- expect(screen.getByText("Read this")).toBeTruthy();
- expect(screen.queryByText(/@gmail/)).toBeNull();
+ expect(screen.getByTestId("tool-choice-chips").textContent).toContain("Read this");
+ expect(screen.queryByText("@gmail")).toBeNull();
expect(
screen.getByTestId("tool-choice-chips").querySelector('[data-brand="gmail"]'),
).not.toBeNull();