Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat: add at agent parser
Gusef6daf4cbc9a
diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex f8821ab63..708524448 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -170,6 +170,8 @@ export {// Utilsexport { parseEmailHandle, toAlookAddress, isValidHandle } from "./utils/email";+export { parsePromptMentions } from "./utils/prompt-parser";+export type { PromptAgent, PromptMention, ParseResult } from "./utils/prompt-parser";export { isValidToken, isValidEmail } from "./utils/validation";export { isOnline, formatStatus } from "./utils/status";export { isUniqueConstraintError } from "./utils/db-errors";diff --git a/src/shared/src/utils/prompt-parser.ts b/src/shared/src/utils/prompt-parser.tsnew file mode 100644index 000000000..0f8de13f0--- /dev/null+++ b/src/shared/src/utils/prompt-parser.ts@@ -0,0 +1,91 @@+import { toAlookAddress } from "./email"++export interface PromptAgent {+ name: string+ emailHandle: string | null+ description: string+}++export interface PromptMention {+ name: string+ email: string | null+ description: string+}++export interface ParseResult {+ enrichedPrompt: string+ mentions: PromptMention[]+}++function isTrigger(prompt: string, atIndex: number): boolean {+ if (atIndex === 0) return true+ const prev = prompt.charCodeAt(atIndex - 1)+ // Valid trigger if preceded by a non-alphanumeric/non-underscore character+ if ((prev >= 48 && prev <= 57) || (prev >= 65 && prev <= 90) || (prev >= 97 && prev <= 122) || prev === 95) return false+ return true+}++function isBoundary(prompt: string, endIndex: number): boolean {+ if (endIndex >= prompt.length) return true+ const next = prompt.charCodeAt(endIndex)+ if ((next >= 48 && next <= 57) || (next >= 65 && next <= 90) || (next >= 97 && next <= 122) || next === 95) return false+ return true+}++export function parsePromptMentions(prompt: string, agents: PromptAgent[]): ParseResult {+ if (!prompt || agents.length === 0) return { enrichedPrompt: prompt, mentions: [] }++ const sorted = agents.slice().sort((a, b) => b.name.length - a.name.length)+ const mentions: PromptMention[] = []++ interface Match {+ start: number+ end: number+ agent: PromptAgent+ }++ const matches: Match[] = []++ for (let i = 0; i < prompt.length; i++) {+ if (prompt[i] !== "@") continue+ if (!isTrigger(prompt, i)) continue++ const afterAt = i + 1+ for (const agent of sorted) {+ const nameEnd = afterAt + agent.name.length+ if (nameEnd > prompt.length) continue+ const slice = prompt.slice(afterAt, nameEnd)+ if (slice.toLowerCase() !== agent.name.toLowerCase()) continue+ if (!isBoundary(prompt, nameEnd)) continue++ // Check this match doesn't overlap with a previously found match+ const overlaps = matches.some(m => i >= m.start && i < m.end)+ if (overlaps) break++ matches.push({ start: i, end: nameEnd, agent })+ break+ }+ }++ // Process from end to start to preserve offsets+ let result = prompt+ for (let i = matches.length - 1; i >= 0; i--) {+ const m = matches[i]+ const mention: PromptMention = {+ name: m.agent.name,+ email: m.agent.emailHandle ? toAlookAddress(m.agent.emailHandle) : null,+ description: m.agent.description,+ }+ mentions.unshift(mention)++ if (m.agent.emailHandle) {+ const replacement = `@${m.agent.name} (${toAlookAddress(m.agent.emailHandle)})`+ result = result.slice(0, m.start) + replacement + result.slice(m.end)+ } else {+ // Preserve canonical casing even without email+ result = result.slice(0, m.start) + `@${m.agent.name}` + result.slice(m.end)+ }+ }++ return { enrichedPrompt: result, mentions }+}diff --git a/src/shared/test/utils/prompt-parser.test.ts b/src/shared/test/utils/prompt-parser.test.tsnew file mode 100644index 000000000..d22ef8a22--- /dev/null+++ b/src/shared/test/utils/prompt-parser.test.ts@@ -0,0 +1,126 @@+import { describe, it, expect } from "vitest"+import { parsePromptMentions } from "../../src/utils/prompt-parser"++const bot = (name: string, emailHandle: string | null = null, description = "") => ({+ name,+ emailHandle,+ description,+})++describe("parsePromptMentions", () => {+ it("enriches a single mention with email", () => {+ const result = parsePromptMentions("Hey @TestBot do this", [bot("TestBot", "testbot")])+ expect(result.enrichedPrompt).toBe("Hey @TestBot ([email protected]) do this")+ expect(result.mentions).toHaveLength(1)+ expect(result.mentions[0]).toEqual({ name: "TestBot", email: "[email protected]", description: "" })+ })++ it("enriches multiple mentions", () => {+ const result = parsePromptMentions("@Alpha and @Beta please coordinate", [+ bot("Alpha", "alpha"),+ bot("Beta", "beta"),+ ])+ expect(result.enrichedPrompt).toBe("@Alpha ([email protected]) and @Beta ([email protected]) please coordinate")+ expect(result.mentions).toHaveLength(2)+ })++ it("leaves mention without email handle unchanged", () => {+ const result = parsePromptMentions("Ask @NoEmail about it", [bot("NoEmail")])+ expect(result.enrichedPrompt).toBe("Ask @NoEmail about it")+ expect(result.mentions).toHaveLength(1)+ expect(result.mentions[0].email).toBeNull()+ })++ it("does not match email addresses", () => {+ const result = parsePromptMentions("send to [email protected]", [bot("example", "ex")])+ expect(result.enrichedPrompt).toBe("send to [email protected]")+ expect(result.mentions).toHaveLength(0)+ })++ it("does not match mid-word @ with agent name", () => {+ const result = parsePromptMentions("email@TestBot", [bot("TestBot", "testbot")])+ expect(result.enrichedPrompt).toBe("email@TestBot")+ expect(result.mentions).toHaveLength(0)+ })++ it("does not match unknown agents", () => {+ const result = parsePromptMentions("@UnknownAgent hi", [bot("TestBot", "testbot")])+ expect(result.enrichedPrompt).toBe("@UnknownAgent hi")+ expect(result.mentions).toHaveLength(0)+ })++ it("matches case-insensitively and preserves canonical name", () => {+ const result = parsePromptMentions("hey @testbot", [bot("TestBot", "testbot")])+ expect(result.enrichedPrompt).toBe("hey @TestBot ([email protected])")+ expect(result.mentions).toHaveLength(1)+ })++ it("prefers longest match (greedy)", () => {+ const result = parsePromptMentions("@SalesBot", [bot("Sales", "sales"), bot("SalesBot", "salesbot")])+ expect(result.enrichedPrompt).toBe("@SalesBot ([email protected])")+ expect(result.mentions).toHaveLength(1)+ expect(result.mentions[0].name).toBe("SalesBot")+ })++ it("matches mention at start of string", () => {+ const result = parsePromptMentions("@Bot do this", [bot("Bot", "bot")])+ expect(result.enrichedPrompt).toBe("@Bot ([email protected]) do this")+ expect(result.mentions).toHaveLength(1)+ })++ it("matches mention after newline", () => {+ const result = parsePromptMentions("line one\n@Bot do this", [bot("Bot", "bot")])+ expect(result.enrichedPrompt).toBe("line one\n@Bot ([email protected]) do this")+ expect(result.mentions).toHaveLength(1)+ })++ it("matches agent name with spaces", () => {+ const result = parsePromptMentions("Hey @Marketing Bot do this", [bot("Marketing Bot", "marketing-bot")])+ expect(result.enrichedPrompt).toBe("Hey @Marketing Bot ([email protected]) do this")+ expect(result.mentions).toHaveLength(1)+ })++ it("does not match without @ prefix", () => {+ const result = parsePromptMentions("Hey Marketing Bot do this", [bot("Marketing Bot", "marketing-bot")])+ expect(result.enrichedPrompt).toBe("Hey Marketing Bot do this")+ expect(result.mentions).toHaveLength(0)+ })++ it("returns unchanged prompt with empty agent list", () => {+ const result = parsePromptMentions("Hey @Bot", [])+ expect(result.enrichedPrompt).toBe("Hey @Bot")+ expect(result.mentions).toHaveLength(0)+ })++ it("enriches duplicate mentions of same agent", () => {+ const result = parsePromptMentions("@Bot do this and @Bot do that", [bot("Bot", "bot")])+ expect(result.enrichedPrompt).toBe("@Bot ([email protected]) do this and @Bot ([email protected]) do that")+ expect(result.mentions).toHaveLength(2)+ })++ it("handles adjacent mentions: @Bot1@Bot2", () => {+ const result = parsePromptMentions("@Bot1@Bot2", [bot("Bot1", "bot1"), bot("Bot2", "bot2")])+ // @Bot1 matches (followed by @, a non-alphanumeric char)+ // @Bot2 does NOT match (@ preceded by '1', an alphanumeric)+ expect(result.enrichedPrompt).toBe("@Bot1 ([email protected])@Bot2")+ expect(result.mentions).toHaveLength(1)+ expect(result.mentions[0].name).toBe("Bot1")+ })++ it("matches agent name with special characters (parentheses)", () => {+ const result = parsePromptMentions("Hey @Bot (v2) do this", [bot("Bot (v2)", "bot-v2")])+ expect(result.enrichedPrompt).toBe("Hey @Bot (v2) ([email protected]) do this")+ expect(result.mentions).toHaveLength(1)+ })++ it("includes description in mention when present", () => {+ const result = parsePromptMentions("@Helper", [bot("Helper", "helper", "A helpful bot")])+ expect(result.mentions[0].description).toBe("A helpful bot")+ })++ it("handles @ after punctuation (parentheses, quotes)", () => {+ const result = parsePromptMentions('(@Bot) and "@Bot"', [bot("Bot", "bot")])+ expect(result.enrichedPrompt).toBe('(@Bot ([email protected])) and "@Bot ([email protected])"')+ expect(result.mentions).toHaveLength(2)+ })+})diff --git a/src/web/src/app/api/agents/[id]/whitelist/route.test.ts b/src/web/src/app/api/agents/[id]/whitelist/route.test.tsindex 3ce0b2c11..aa96182ac 100644--- a/src/web/src/app/api/agents/[id]/whitelist/route.test.ts+++ b/src/web/src/app/api/agents/[id]/whitelist/route.test.ts@@ -29,8 +29,13 @@ vi.mock("@alook/shared", () => ({},AddWhitelistRequestSchema: {parse(data: unknown) {- const { z } = require("zod");- return z.object({ email: z.string().email() }).parse(data);+ const d = data as Record<string, unknown>;+ if (!d || typeof d !== "object" || typeof d.email !== "string" || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d.email)) {+ const err = new Error("validation");+ (err as any).issues = [{ path: ["email"], message: "Invalid email" }];+ throw err;+ }+ return { email: String(d.email) };},},}));diff --git a/src/web/src/app/api/conversations/[id]/buffered-messages/route.ts b/src/web/src/app/api/conversations/[id]/buffered-messages/route.tsindex 76eae37cb..bf9478f37 100644--- a/src/web/src/app/api/conversations/[id]/buffered-messages/route.ts+++ b/src/web/src/app/api/conversations/[id]/buffered-messages/route.ts@@ -3,6 +3,7 @@ import { getCloudflareContext } from "@opennextjs/cloudflare";import {queries,CreateBufferedMessageRequestSchema,+ parsePromptMentions,} from "@alook/shared";import { getDb } from "@/lib/db";import { nanoid } from "nanoid";@@ -119,9 +120,20 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {artifactIds.push(artifactId);}+ let enrichedContent = content;+ if (content.includes("@")) {+ try {+ const agentList = await queries.agent.listAgents(db, ws.workspaceId, ctx.userId);+ const { enrichedPrompt } = parsePromptMentions(content, agentList);+ enrichedContent = enrichedPrompt;+ } catch {+ // Fail-open: pass content through unmodified+ }+ }+const message = await queries.message.createBufferedMessage(db, {conversationId: id,- content,+ content: enrichedContent,attachmentIds: artifactIds.length > 0 ? JSON.stringify(artifactIds) : null,});diff --git a/src/web/src/app/api/conversations/[id]/messages/route.ts b/src/web/src/app/api/conversations/[id]/messages/route.tsindex 7f8fb9314..892c21321 100644--- a/src/web/src/app/api/conversations/[id]/messages/route.ts+++ b/src/web/src/app/api/conversations/[id]/messages/route.ts@@ -1,6 +1,6 @@import { NextRequest } from "next/server";import { getCloudflareContext } from "@opennextjs/cloudflare"-import { queries, TASK_TYPES, buildContextKey, CreateMessageRequestSchema } from "@alook/shared"+import { queries, TASK_TYPES, buildContextKey, CreateMessageRequestSchema, parsePromptMentions } from "@alook/shared"import { getDb } from "@/lib/db"import { nanoid } from "nanoid";import { withAuth } from "@/lib/middleware/auth";@@ -155,18 +155,49 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {// Auto-title: conditional WHERE title = '' ensures only the first message sets itqueries.conversation.updateConversationTitle(db, id, truncateTitle(content)).catch(() => {});+ let enrichedContent = content;+ let mentionContext: Record<string, unknown> | undefined;+ if (content.includes("@")) {+ try {+ const agentList = await queries.agent.listAgents(db, ws.workspaceId, ctx.userId);+ const { enrichedPrompt, mentions } = parsePromptMentions(content, agentList);+ enrichedContent = enrichedPrompt;+ if (mentions.length > 0) {+ const seen = new Set<string>();+ const uniqueMentions = mentions.filter(m => {+ if (seen.has(m.name)) return false;+ seen.add(m.name);+ return true;+ });+ mentionContext = {+ mentioned_agents: uniqueMentions.map(m => ({+ name: m.name,+ email: m.email,+ ...(m.description ? { description: m.description } : {}),+ })),+ };+ }+ } catch {+ // Fail-open: if agent query fails, pass content through unmodified+ }+ }+const contextKey = buildContextKey(TASK_TYPES.USER_DM_MESSAGE, { conversationId: id });+ const taskContext: Record<string, unknown> = {+ ...(artifactIds.length > 0 ? { attachment_ids: artifactIds } : {}),+ ...mentionContext,+ };const taskService = new TaskService(db);try {const task = await taskService.enqueueTask(conversation.agentId,id,ws.workspaceId,- content,+ enrichedContent,TASK_TYPES.USER_DM_MESSAGE,{contextKey,- context: artifactIds.length > 0 ? { attachment_ids: artifactIds } : undefined,+ context: Object.keys(taskContext).length > 0 ? taskContext : undefined,},);broadcastToUser(ctx.userId, { type: "task.updated", taskId: task.id, agentId: task.agentId, status: "queued" }).catch(() => {});diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.cssindex 0071e6867..eacbc32d9 100644--- a/src/web/src/app/globals.css+++ b/src/web/src/app/globals.css@@ -922,6 +922,23 @@.markdown strong { font-weight: 600; }.markdown em { font-style: italic; }+/* Textarea mention backdrop */+.caret-foreground {+ caret-color: var(--foreground);+}++/* Mention highlight — underline + italic */+.mention-highlight {+ text-decoration: underline;+ text-decoration-color: var(--foreground);+ text-underline-offset: 2px;+ text-decoration-thickness: 1.5px;+ font-style: italic;+}+.markdown-user .mention-highlight {+ text-decoration-color: var(--primary-foreground);+}+/* User bubble markdown — inherit text color from primary-foreground parent */.markdown-user,.markdown-user code:not(pre code) {diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsxindex e91973a0e..4aa5b2f35 100644--- a/src/web/src/components/agent-chat/agent-chat-view.tsx+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx@@ -30,6 +30,9 @@ import { Skeleton } from "@/components/ui/skeleton";import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";import { ArrowUp, Box, FileText, Loader2, Mail, Mic, Paperclip, RotateCcw, Square, X } from "lucide-react";import { useSpeechRecognition } from "@/hooks/use-speech-recognition";+import { useMentionPopup } from "@/hooks/use-mention-popup";+import { MentionPopup } from "@/components/agent-chat/mention-popup";+import { highlightMentions } from "@/lib/highlight-mentions";import { ArtifactSheet, formatSize } from "@/components/agent-chat/artifact-sheet";import { isPreviewable, getArtifactUrl } from "@/components/artifact-content-renderer";import {@@ -46,6 +49,13 @@ import { FollowUpBuffer } from "@/components/agent-chat/follow-up-buffer";const MESSAGE_LIMIT = 20;const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB+const MENTION_ALLOWED_TAGS = { mention: [] as string[] };+const MENTION_LITERAL_TAGS = ["mention"];+const MentionHighlight = ({ children }: { children?: React.ReactNode }) => (+ <span className="mention-highlight">{children}</span>+);+const MENTION_COMPONENTS = { mention: MentionHighlight };+/** Sort messages by (created_at, id) ascending — guarantees chronological order. */export function sortMessages(msgs: Message[]): Message[] {return msgs.slice().sort((a, b) => {@@ -184,6 +194,7 @@ export function AgentChatView() {const [selectedArtifact, setSelectedArtifact] = useState<Artifact | null>(null);const [pendingFiles, setPendingFiles] = useState<File[]>([]);const [bufferedMessages, setBufferedMessages] = useState<Message[]>([]);+ const [caretIndex, setCaretIndex] = useState<number | null>(null);const pendingFilesMapRef = useRef<Map<string, File[]>>(new Map());@@ -217,6 +228,16 @@ export function AgentChatView() {const fileInputRef = useRef<HTMLInputElement>(null);const textareaRef = useRef<HTMLTextAreaElement>(null);+ const otherAgents = useMemo(() => agents.filter(a => a.id !== agentId), [agents, agentId]);++ const mentionPopup = useMentionPopup({+ input,+ caretIndex,+ textareaRef,+ agents: otherAgents,+ onInputChange: setInput,+ });+useEffect(() => {const key = `chat-draft:${agentId}`;if (input) {@@ -821,6 +842,7 @@ export function AgentChatView() {};const handleKeyDown = (e: React.KeyboardEvent) => {+ if (mentionPopup.handleMentionKeyDown(e)) return;if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {e.preventDefault();handleSend();@@ -970,7 +992,7 @@ export function AgentChatView() {<div className="absolute inset-0 rounded-lg animate-pulse pointer-events-none" style={{ boxShadow: "0 0 0 2px var(--bubble-glow)" }} />)}<div className="markdown markdown-user">- <Streamdown controls={{ code: { copy: true, download: false }, table: { copy: false, download: false, fullscreen: false } }} linkSafety={{ enabled: false }}>{msg.content}</Streamdown>+ <Streamdown controls={{ code: { copy: true, download: false }, table: { copy: false, download: false, fullscreen: false } }} linkSafety={{ enabled: false }} allowedTags={MENTION_ALLOWED_TAGS} literalTagContent={MENTION_LITERAL_TAGS} components={MENTION_COMPONENTS}>{highlightMentions(msg.content, agents)}</Streamdown></div>{msg.attachment_ids && msg.attachment_ids.length > 0 && (<AttachmentChips attachmentIds={msg.attachment_ids} artifacts={artifacts} onArtifactClick={handleArtifactClick} />@@ -984,7 +1006,7 @@ export function AgentChatView() {})() : !hasTaskStream ? (<div className="flex justify-start" {...(msg.task_id ? { "data-task-id": msg.task_id } : {})}><div className="markdown max-w-full min-w-0 px-1 py-1 text-base text-foreground">- <Streamdown controls={{ code: { copy: true, download: false }, table: { copy: true, download: false, fullscreen: true } }} linkSafety={{ enabled: false }}>{msg.content}</Streamdown>+ <Streamdown controls={{ code: { copy: true, download: false }, table: { copy: true, download: false, fullscreen: true } }} linkSafety={{ enabled: false }} allowedTags={MENTION_ALLOWED_TAGS} literalTagContent={MENTION_LITERAL_TAGS} components={MENTION_COMPONENTS}>{highlightMentions(msg.content, agents)}</Streamdown></div></div>) : null}@@ -1036,20 +1058,51 @@ export function AgentChatView() {<p className="text-sm text-muted-foreground font-medium">Drop files here</p></div>)}- <textarea- ref={textareaRef}- value={input}- onChange={(e) => setInput(e.target.value)}- onKeyDown={handleKeyDown}- placeholder={isTaskActive ? "Type a follow-up..." : "Type a message..."}- rows={1}- disabled={sending}- className={cn(- "field-sizing-content w-full resize-none bg-transparent px-3.5 pt-2.5 text-base outline-none",- "placeholder:text-muted-foreground disabled:cursor-not-allowed",- "min-h-[38px] max-h-[200px] thin-scrollbar"- )}+ <MentionPopup+ isOpen={mentionPopup.isOpen}+ agents={mentionPopup.filteredAgents}+ selectedIndex={mentionPopup.selectedIndex}+ onSelect={mentionPopup.selectAgent}+ anchorPos={mentionPopup.anchorPos}/>+ <div className="relative">+ <div+ aria-hidden+ className="mention-backdrop absolute inset-0 px-3.5 pt-2.5 text-base whitespace-pre-wrap break-words pointer-events-none overflow-hidden"+ dangerouslySetInnerHTML={{+ __html: input+ ? highlightMentions(+ input.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"),+ agents,+ )+ .replace(/<mention>/g, '<span class="mention-highlight">')+ .replace(/<\/mention>/g, "</span>")+ : "",+ }}+ />+ <textarea+ ref={textareaRef}+ value={input}+ onChange={(e) => { setInput(e.target.value); setCaretIndex(e.target.selectionStart); }}+ onKeyDown={handleKeyDown}+ onKeyUp={(e) => setCaretIndex((e.target as HTMLTextAreaElement).selectionStart)}+ onClick={(e) => setCaretIndex((e.target as HTMLTextAreaElement).selectionStart)}+ onSelect={(e) => setCaretIndex((e.target as HTMLTextAreaElement).selectionStart)}+ onScroll={(e) => {+ const backdrop = (e.target as HTMLTextAreaElement).previousElementSibling;+ if (backdrop) backdrop.scrollTop = (e.target as HTMLTextAreaElement).scrollTop;+ }}+ placeholder={isTaskActive ? "Type a follow-up..." : "Type a message..."}+ rows={1}+ disabled={sending}+ className={cn(+ "relative field-sizing-content w-full resize-none bg-transparent px-3.5 pt-2.5 text-base outline-none",+ "placeholder:text-muted-foreground disabled:cursor-not-allowed",+ "min-h-[38px] max-h-[200px] thin-scrollbar",+ "caret-foreground text-transparent"+ )}+ />+ </div>{/* Pending file pills */}{pendingFiles.length > 0 && (diff --git a/src/web/src/components/agent-chat/mention-popup.tsx b/src/web/src/components/agent-chat/mention-popup.tsxnew file mode 100644index 000000000..b3337671a--- /dev/null+++ b/src/web/src/components/agent-chat/mention-popup.tsx@@ -0,0 +1,58 @@+import React, { useRef, useEffect } from "react"+import type { Agent } from "@alook/shared"+import { cn } from "@/lib/utils"++interface MentionPopupProps {+ isOpen: boolean+ agents: Agent[]+ selectedIndex: number+ onSelect: (agent: Agent) => void+ anchorPos: { top: number; left: number }+}++export function MentionPopup({ isOpen, agents, selectedIndex, onSelect, anchorPos }: MentionPopupProps) {+ const listRef = useRef<HTMLDivElement>(null)++ useEffect(() => {+ if (!listRef.current) return+ const selected = listRef.current.children[selectedIndex] as HTMLElement | undefined+ selected?.scrollIntoView({ block: "nearest" })+ }, [selectedIndex])++ if (!isOpen || agents.length === 0) return null++ return (+ <div+ className="absolute z-50 w-64 rounded-lg border border-border bg-popover text-popover-foreground shadow-md transition-opacity duration-150"+ style={{+ top: anchorPos.top - 4,+ left: anchorPos.left,+ transform: "translateY(-100%)",+ }}+ >+ <div ref={listRef} className="max-h-[200px] overflow-y-auto py-1 thin-scrollbar">+ {agents.map((agent, i) => (+ <button+ key={agent.id}+ type="button"+ className={cn(+ "flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm transition-colors",+ i === selectedIndex ? "bg-accent text-accent-foreground" : "hover:bg-accent/50",+ )}+ onMouseDown={(e) => {+ e.preventDefault()+ onSelect(agent)+ }}+ >+ <span className="truncate font-medium">{agent.name}</span>+ {agent.email_handle && (+ <span className="truncate text-xs text-muted-foreground">+ {agent.email_handle}@alook.ai+ </span>+ )}+ </button>+ ))}+ </div>+ </div>+ )+}diff --git a/src/web/src/hooks/use-mention-popup.ts b/src/web/src/hooks/use-mention-popup.tsnew file mode 100644index 000000000..2723f54eb--- /dev/null+++ b/src/web/src/hooks/use-mention-popup.ts@@ -0,0 +1,190 @@+import { useState, useCallback, useMemo, useRef, useEffect } from "react"+import type { Agent } from "@alook/shared"++export interface MentionPopupState {+ isOpen: boolean+ query: string+ selectedIndex: number+ anchorPos: { top: number; left: number }+ filteredAgents: Agent[]+ handleMentionKeyDown: (e: React.KeyboardEvent) => boolean+ selectAgent: (agent: Agent) => void+}++interface UseMentionPopupParams {+ input: string+ caretIndex: number | null+ textareaRef: React.RefObject<HTMLTextAreaElement | null>+ agents: Agent[]+ onInputChange: (value: string) => void+}++function isTriggerChar(ch: number): boolean {+ if ((ch >= 48 && ch <= 57) || (ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122) || ch === 95) return false+ return true+}++function findMentionTrigger(input: string, caretIndex: number): { start: number; query: string } | null {+ let i = caretIndex - 1+ while (i >= 0) {+ const ch = input.charCodeAt(i)+ if (ch === 64) { // '@'+ if (i === 0 || isTriggerChar(input.charCodeAt(i - 1))) {+ return { start: i, query: input.slice(i + 1, caretIndex) }+ }+ return null+ }+ if (ch === 10 || ch === 13) return null // newline breaks the scan+ i--+ }+ return null+}++function getCaretCoordinates(textarea: HTMLTextAreaElement, position: number): { top: number; left: number } {+ const mirror = document.createElement("div")+ const style = window.getComputedStyle(textarea)++ const props = [+ "fontFamily", "fontSize", "fontWeight", "fontStyle", "letterSpacing",+ "textTransform", "wordSpacing", "textIndent", "lineHeight",+ "paddingTop", "paddingRight", "paddingBottom", "paddingLeft",+ "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth",+ "boxSizing", "whiteSpace", "wordWrap", "overflowWrap",+ ] as const++ mirror.style.position = "absolute"+ mirror.style.top = "-9999px"+ mirror.style.left = "-9999px"+ mirror.style.visibility = "hidden"+ mirror.style.overflow = "hidden"+ mirror.style.width = `${textarea.offsetWidth}px`++ for (const prop of props) {+ (mirror.style as unknown as Record<string, string>)[prop] = style.getPropertyValue(+ prop.replace(/([A-Z])/g, "-$1").toLowerCase()+ )+ }++ const textBefore = textarea.value.slice(0, position)+ mirror.textContent = textBefore+ const marker = document.createElement("span")+ marker.textContent = ""+ mirror.appendChild(marker)++ document.body.appendChild(mirror)+ const top = marker.offsetTop - textarea.scrollTop+ const left = marker.offsetLeft+ document.body.removeChild(mirror)++ return { top, left }+}++export function useMentionPopup({+ input,+ caretIndex,+ textareaRef,+ agents,+ onInputChange,+}: UseMentionPopupParams): MentionPopupState {+ const [isOpen, setIsOpen] = useState(false)+ const [query, setQuery] = useState("")+ const [selectedIndex, setSelectedIndex] = useState(0)+ const [anchorPos, setAnchorPos] = useState({ top: 0, left: 0 })+ const triggerStartRef = useRef<number | null>(null)++ const filteredAgents = useMemo(() => {+ if (!isOpen) return []+ if (!query) return agents.slice(0, 20)+ const q = query.toLowerCase()+ const startsWith: Agent[] = []+ const includes: Agent[] = []+ for (const a of agents) {+ const name = a.name.toLowerCase()+ if (name.startsWith(q)) startsWith.push(a)+ else if (name.includes(q)) includes.push(a)+ }+ return [...startsWith, ...includes]+ }, [isOpen, query, agents])++ useEffect(() => {+ setSelectedIndex(0)+ }, [filteredAgents.length, query])++ useEffect(() => {+ if (caretIndex === null) {+ setIsOpen(false)+ return+ }++ const trigger = findMentionTrigger(input, caretIndex)+ if (trigger) {+ triggerStartRef.current = trigger.start+ setQuery(trigger.query)+ setIsOpen(true)++ if (textareaRef.current) {+ const coords = getCaretCoordinates(textareaRef.current, trigger.start)+ setAnchorPos(coords)+ }+ } else {+ setIsOpen(false)+ triggerStartRef.current = null+ }+ }, [input, caretIndex, textareaRef])++ const selectAgent = useCallback((agent: Agent) => {+ if (caretIndex === null || triggerStartRef.current === null) return++ const before = input.slice(0, triggerStartRef.current)+ const after = input.slice(caretIndex)+ const newInput = `${before}@${agent.name} ${after}`+ onInputChange(newInput)+ setIsOpen(false)++ const newCaretPos = before.length + 1 + agent.name.length + 1+ requestAnimationFrame(() => {+ const ta = textareaRef.current+ if (ta) {+ ta.focus()+ ta.setSelectionRange(newCaretPos, newCaretPos)+ }+ })+ }, [input, caretIndex, textareaRef, onInputChange])++ const handleMentionKeyDown = useCallback((e: React.KeyboardEvent): boolean => {+ if (!isOpen || filteredAgents.length === 0) return false+ if (e.nativeEvent.isComposing) return false++ if (e.key === "ArrowDown") {+ e.preventDefault()+ setSelectedIndex(i => (i + 1) % filteredAgents.length)+ return true+ }+ if (e.key === "ArrowUp") {+ e.preventDefault()+ setSelectedIndex(i => (i - 1 + filteredAgents.length) % filteredAgents.length)+ return true+ }+ if (e.key === "Enter") {+ e.preventDefault()+ selectAgent(filteredAgents[selectedIndex])+ return true+ }+ if (e.key === "Escape") {+ e.preventDefault()+ setIsOpen(false)+ return true+ }+ return false+ }, [isOpen, filteredAgents, selectedIndex, selectAgent])++ return {+ isOpen,+ query,+ selectedIndex,+ anchorPos,+ filteredAgents,+ handleMentionKeyDown,+ selectAgent,+ }+}diff --git a/src/web/src/lib/highlight-mentions.test.ts b/src/web/src/lib/highlight-mentions.test.tsnew file mode 100644index 000000000..792e6007d--- /dev/null+++ b/src/web/src/lib/highlight-mentions.test.ts@@ -0,0 +1,58 @@+import { describe, it, expect } from "vitest"+import { highlightMentions } from "./highlight-mentions"+import type { Agent } from "@alook/shared"++const agent = (name: string, email_handle: string | null = null): Agent => ({+ id: `ag_${name.toLowerCase()}`,+ workspace_id: "ws_1",+ runtime_id: "rt_1",+ name,+ description: "",+ instructions: "",+ runtime_mode: "daemon",+ runtime_config: {},+ status: "active",+ max_concurrent_tasks: 1,+ email_handle,+ visibility: "public",+ owner_id: null,+ created_at: "2024-01-01T00:00:00Z",+ updated_at: "2024-01-01T00:00:00Z",+})++describe("highlightMentions", () => {+ it("wraps basic @AgentName", () => {+ const result = highlightMentions("Hey @TestBot do this", [agent("TestBot", "testbot")])+ expect(result).toBe("Hey @<mention>TestBot</mention> do this")+ })++ it("wraps only name portion of enriched form", () => {+ const result = highlightMentions("Hey @TestBot ([email protected]) do this", [agent("TestBot", "testbot")])+ expect(result).toBe("Hey @<mention>TestBot</mention> ([email protected]) do this")+ })++ it("leaves non-matching @ as plain text", () => {+ const result = highlightMentions("send to [email protected]", [agent("TestBot")])+ expect(result).toBe("send to [email protected]")+ })++ it("wraps multiple mentions", () => {+ const result = highlightMentions("@Alpha and @Beta", [agent("Alpha", "alpha"), agent("Beta", "beta")])+ expect(result).toBe("@<mention>Alpha</mention> and @<mention>Beta</mention>")+ })++ it("does not wrap unknown agent names", () => {+ const result = highlightMentions("Hey @Unknown", [agent("TestBot")])+ expect(result).toBe("Hey @Unknown")+ })++ it("returns unchanged with no @ symbols", () => {+ const result = highlightMentions("Hello world", [agent("TestBot")])+ expect(result).toBe("Hello world")+ })++ it("returns unchanged with empty agents", () => {+ const result = highlightMentions("Hey @TestBot", [])+ expect(result).toBe("Hey @TestBot")+ })+})diff --git a/src/web/src/lib/highlight-mentions.ts b/src/web/src/lib/highlight-mentions.tsnew file mode 100644index 000000000..dc1728d98--- /dev/null+++ b/src/web/src/lib/highlight-mentions.ts@@ -0,0 +1,70 @@+import type { Agent } from "@alook/shared"++function isTrigger(text: string, atIndex: number): boolean {+ if (atIndex === 0) return true+ const prev = text.charCodeAt(atIndex - 1)+ if ((prev >= 48 && prev <= 57) || (prev >= 65 && prev <= 90) || (prev >= 97 && prev <= 122) || prev === 95) return false+ return true+}++function isBoundary(text: string, endIndex: number): boolean {+ if (endIndex >= text.length) return true+ const next = text.charCodeAt(endIndex)+ if ((next >= 48 && next <= 57) || (next >= 65 && next <= 90) || (next >= 97 && next <= 122) || next === 95) return false+ return true+}++export function highlightMentions(content: string, agents: Agent[]): string {+ if (!content || agents.length === 0 || !content.includes("@")) return content++ const sorted = agents.slice().sort((a, b) => b.name.length - a.name.length)++ interface Match {+ start: number+ end: number+ name: string+ }++ const matches: Match[] = []++ for (let i = 0; i < content.length; i++) {+ if (content[i] !== "@") continue+ if (!isTrigger(content, i)) continue++ const afterAt = i + 1+ for (const agent of sorted) {+ const nameEnd = afterAt + agent.name.length+ if (nameEnd > content.length) continue+ const slice = content.slice(afterAt, nameEnd)+ if (slice.toLowerCase() !== agent.name.toLowerCase()) continue++ // Check if this is the enriched form: @AgentName ([email protected])+ let matchEnd = nameEnd+ const afterName = content.slice(nameEnd)+ const enrichedMatch = afterName.match(/^ \([a-zA-Z0-9-]+@alook\.ai\)/)+ if (enrichedMatch) {+ matchEnd = nameEnd + enrichedMatch[0].length+ }++ if (!enrichedMatch && !isBoundary(content, nameEnd)) continue+ if (enrichedMatch && !isBoundary(content, matchEnd)) continue++ const overlaps = matches.some(m => i >= m.start && i < m.end)+ if (overlaps) break++ // Only wrap the @Name part in <mention>, leave the (email) outside+ matches.push({ start: i, end: nameEnd, name: agent.name })+ break+ }+ }++ // Process from end to start+ let result = content+ for (let i = matches.length - 1; i >= 0; i--) {+ const m = matches[i]+ const name = result.slice(m.start + 1, m.end)+ result = result.slice(0, m.start) + `@<mention>${name}</mention>` + result.slice(m.end)+ }++ return result+}