Skip to content

Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.

Show @mentions as chips with the agent's color and avatar (#109)

Diasf3ceb5ba1709
diff --git a/src/core/context.ts b/src/core/context.ts
index efda704..dc32693 100644
--- a/src/core/context.ts
+++ b/src/core/context.ts
@@ -2,6 +2,7 @@
// and a prompt with the conversation transcript. The CLI keeps no session
// between turns, so everything the agent knows comes from here.
import { L, lang, locale } from '../shared/lang'
+import { MENTION } from '../shared/mention-text'
import { CODE_SPANS, describeSchedule, PROJECTS_DIR, type Agent, type AgentApp, type Conversation, type Memory, type Message, type Routine, type Settings, type Skill } from '../shared/types'
import type { ToolDef } from './gateway'
import { osOf, shellCommand, systemName } from './platform'
@@ -393,7 +394,7 @@ export const LER_THREAD: ToolDef = {
// code are quoted content, not a call (CODE_SPANS): a prompt shown in a fenced block, say.
export function mentioned(text: string, agents: Agent[]): Agent[] {
const found: Agent[] = []
- for (const m of text.replace(CODE_SPANS, ' ').matchAll(/(^|[^\w@])@([a-z0-9][a-z0-9_-]{1,31})\b/gi)) {
+ for (const m of text.replace(CODE_SPANS, ' ').matchAll(MENTION)) {
const a = agents.find((x) => x.handle.toLowerCase() === m[2]!.toLowerCase())
if (a && !found.includes(a)) found.push(a)
}
diff --git a/src/renderer/src/components/Conversation.tsx b/src/renderer/src/components/Conversation.tsx
index eb7308f..5efe806 100644
--- a/src/renderer/src/components/Conversation.tsx
+++ b/src/renderer/src/components/Conversation.tsx
@@ -1,8 +1,8 @@
import { L, lang, locale } from '../../../shared/lang'
-import { CODE_SPANS } from '../../../shared/types'
-import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react'
-import Markdown, { defaultUrlTransform } from 'react-markdown'
+import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentProps, type ReactNode } from 'react'
+import Markdown, { defaultUrlTransform, type ExtraProps } from 'react-markdown'
import { LOCAL_LINK, remarkLocalPaths } from '../../../shared/path-text'
+import { remarkMentions, splitMentions } from '../../../shared/mention-text'
import { localLinkFor } from './LocalLink'
import remarkGfm from 'remark-gfm'
import { KeepInWiki, WikiChip, WikiLink, wikiLinks } from './Wiki'
@@ -51,7 +51,7 @@ import {
transcribe,
voiceStatus
} from '../store'
-import { AgentAvatar, Icon, MeAvatar, ago, duration, time, tokens, usd, useJustEnded } from './ui'
+import { AgentAvatar, Icon, MeAvatar, ago, ownColor, duration, time, tokens, usd, useJustEnded } from './ui'
import { canRecord, NoSound, record, type Recording } from '../voice'
import { useVoice, VoicePopover } from './VoiceSetup'
import { ArtifactCard, BrowserCard, ServiceCard, SidePanel } from './Panel'
@@ -299,7 +299,8 @@ export function MessageList({ messages: all, conversationId, empty, focus, threa
)
}
-const AGENT_PLUGINS = [remarkGfm, remarkLocalPaths]
+const AGENT_PLUGINS = [remarkGfm, remarkMentions, remarkLocalPaths]
+const PLAIN_PLUGINS = [remarkGfm, remarkMentions]
const keepLocalLinks = (url: string): string => (url.startsWith(LOCAL_LINK) ? url : defaultUrlTransform(url))
// `replies`: in a timeline with threads, the replies to this message (none yet: empty).
@@ -319,7 +320,7 @@ function MessageRow({ message, grouped, replies }: { message: Message; grouped:
)
// The same object between renders, or every link would start over.
- const agentMarkdown = useMemo(() => ({ pre: CodeBlock, a: localLinkFor(message.id) }), [message.id])
+ const agentMarkdown = useMemo(() => ({ pre: CodeBlock, a: localLinkFor(message.id), span: MentionSpan }), [message.id])
if (message.author.kind === 'system') {
return (
@@ -361,9 +362,9 @@ function MessageRow({ message, grouped, replies }: { message: Message; grouped:
{message.text ? (
<div className="md">
{agent && message.run?.status !== 'working' ? (
- <Markdown remarkPlugins={AGENT_PLUGINS} urlTransform={keepLocalLinks} components={agentMarkdown}>{highlightMentions(message.text)}</Markdown>
+ <Markdown remarkPlugins={AGENT_PLUGINS} urlTransform={keepLocalLinks} components={agentMarkdown}>{wikiLinks(message.text)}</Markdown>
) : (
- <Markdown remarkPlugins={[remarkGfm]} components={{ pre: CodeBlock, a: (p) => <WikiLink href={p.href}>{p.children}</WikiLink> }}>{highlightMentions(message.text)}</Markdown>
+ <Markdown remarkPlugins={PLAIN_PLUGINS} components={plainMarkdown}>{wikiLinks(message.text)}</Markdown>
)}
</div>
) : null}
@@ -460,7 +461,7 @@ function RoutineMessage({ message, replies }: { message: Message; replies?: Mess
</div>
)}
<div className="md">
- <Markdown remarkPlugins={[remarkGfm]} components={{ pre: CodeBlock, a: (p) => <WikiLink href={p.href}>{p.children}</WikiLink> }}>{highlightMentions(message.text)}</Markdown>
+ <Markdown remarkPlugins={PLAIN_PLUGINS} components={plainMarkdown}>{wikiLinks(message.text)}</Markdown>
</div>
{replies && <ThreadLink message={message} replies={replies} />}
</div>
@@ -827,18 +828,24 @@ function QuestionCard({ question, answered }: { question: string; answered: bool
)
}
-// A @handle in code is not bolded (CODE_SPANS, the core's rule too): the box shows and copies the real text.
-const boldMentions = (t: string): string => t.replace(/(^|\s)@([a-z0-9_-]{2,32})/gi, '$1**@$2**')
-const highlightMentions = (text: string): string => {
- text = wikiLinks(text)
- let out = ''
- let last = 0
- for (const m of text.matchAll(CODE_SPANS)) {
- out += boldMentions(text.slice(last, m.index)) + m[0]
- last = m.index! + m[0].length
- }
- return out + boldMentions(text.slice(last))
+// What remarkMentions marked: an agent's @handle becomes its chip, which opens its profile. A handle
+// no agent has stays as it was written, in bold, as any @ always was.
+function MentionSpan({ node: _, ...props }: ComponentProps<'span'> & ExtraProps): ReactNode {
+ const handle = (props as Record<string, unknown>)['data-mention']
+ if (typeof handle !== 'string') return <span {...props} />
+ return <Mention handle={handle} />
}
+function Mention({ handle }: { handle: string }): ReactNode {
+ const agent = useStore((s) => s.agents.find((a) => a.handle.toLowerCase() === handle.toLowerCase()))
+ if (!agent) return <strong>@{handle}</strong>
+ return (
+ <button className={`mention c-${agent.color}`} style={ownColor(agent)} title={agent.role ? `${agent.name} · ${agent.role}` : agent.name} onClick={() => navigate({ kind: 'agent', id: agent.id })}>
+ <AgentAvatar agent={agent} size={16} />
+ <span>@{agent.handle}</span>
+ </button>
+ )
+}
+const plainMarkdown = { pre: CodeBlock, a: (p: { href?: string; children?: ReactNode }) => <WikiLink href={p.href}>{p.children}</WikiLink>, span: MentionSpan }
// Now, every second while `on`: the clock of a reply at work.
function useNow(on: boolean): number {
@@ -1404,6 +1411,8 @@ function RecordingClock({ since }: { since: number }): ReactNode {
)
}
+const TYPE = ['font-family', 'font-size', 'font-weight', 'line-height', 'letter-spacing', 'word-spacing', 'tab-size', 'text-transform', 'text-indent', 'padding']
+
// `threadId`: it answers in the thread that message started, not in the conversation.
export function Composer({ conversationId, threadId, members, placeholder }: { conversationId: string; threadId?: string; members: Agent[]; placeholder: string }): ReactNode {
const key = threadId ?? conversationId // the draft's
@@ -1417,7 +1426,9 @@ export function Composer({ conversationId, threadId, members, placeholder }: { c
const [mention, setMention] = useState<{ query: string; start: number } | null>(null)
const [active, setActive] = useState(0)
const ref = useRef<HTMLTextAreaElement>(null)
+ const mirror = useRef<HTMLDivElement>(null)
const platform = useStore((s) => s.platform)
+ const agents = useStore((s) => s.agents)
const allAgents = useStore((s) => s.agents.filter(isTeam))
const isDm = useStore((s) => s.conversations.find((c) => c.id === conversationId)?.kind === 'dm')
// Replies at work and questions asked here: in this thread, or outside threads.
@@ -1496,12 +1507,52 @@ export function Composer({ conversationId, threadId, members, placeholder }: { c
}
}, [inThread])
- useLayoutEffect(() => {
+ // The field grows with its text, up to a point; on a narrower window the same text takes more lines.
+ const fit = (): void => {
const el = ref.current
if (!el) return
el.style.height = 'auto'
el.style.height = `${Math.min(el.scrollHeight, 220)}px`
- }, [text])
+ followField()
+ }
+ useLayoutEffect(fit, [text])
+ useEffect(() => {
+ const el = ref.current
+ if (!el) return
+ let width = el.clientWidth
+ const watch = new ResizeObserver(() => {
+ if (el.clientWidth === width) return // only a new width changes the lines; fit's own height doesn't
+ width = el.clientWidth
+ fit()
+ })
+ watch.observe(el)
+ return () => watch.disconnect()
+ }, [])
+
+ // The text shows from a copy behind the field, where an agent's @handle wears its color; the field
+ // on top keeps the caret and the selection. The copy takes the field's type as computed (a phone
+ // gets 16 px, and a field doesn't inherit letter spacing), its width (a scrollbar takes some) and
+ // its size and its scroll, so both break the lines in the same places and scroll as far.
+ const followField = (): void => {
+ const el = ref.current
+ const m = mirror.current
+ if (!el || !m) return
+ const field = getComputedStyle(el)
+ for (const p of TYPE) m.style.setProperty(p, field.getPropertyValue(p))
+ m.style.width = `${el.clientWidth}px`
+ m.style.height = `${el.clientHeight}px`
+ m.scrollTop = el.scrollTop
+ }
+ const painted = splitMentions(text).map((p, i) => {
+ const a = 'handle' in p ? agents.find((x) => x.handle.toLowerCase() === p.handle.toLowerCase()) : undefined
+ return a ? (
+ <mark key={i} className={`c-${a.color}`} style={ownColor(a)}>
+ {p.text}
+ </mark>
+ ) : (
+ p.text
+ )
+ })
const options = mention
? members.filter((a) => a.handle.startsWith(mention.query.toLowerCase()) || a.name.toLowerCase().startsWith(mention.query.toLowerCase()))
@@ -1609,40 +1660,47 @@ export function Composer({ conversationId, threadId, members, placeholder }: { c
))}
</div>
)}
- <textarea
- ref={ref}
- rows={1}
- value={text}
- placeholder={asker ? L(`Responder a ${asker}`, `Reply to ${asker}`) : placeholder}
- onChange={(e) => {
- setText(e.target.value)
- updateMention(e.target.value, e.target.selectionStart)
- }}
- onPaste={(e) => {
- const files = [...e.clipboardData.files].filter((f) => f.type.startsWith('image/'))
- if (!files.length) return
- e.preventDefault()
- void addFiles(files)
- }}
- onKeyDown={(e) => {
- if (e.code === 'Space' && (platform === 'mac' ? e.altKey : e.ctrlKey) && canRecord()) {
- e.preventDefault()
- if (!e.repeat) voiceControls.press()
- return
- }
- if (e.key === 'Escape' && voice !== 'idle') return voiceControls.cancel()
- if (mention && options.length > 0) {
- if (e.key === 'ArrowDown') return (e.preventDefault(), setActive((active + 1) % options.length))
- if (e.key === 'ArrowUp') return (e.preventDefault(), setActive((active - 1 + options.length) % options.length))
- if (e.key === 'Enter' || e.key === 'Tab') return (e.preventDefault(), pick(options[active]!))
- if (e.key === 'Escape') return setMention(null)
- }
- if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
+ <div className="composer__field">
+ <div ref={mirror} className="composer__mirror" aria-hidden>
+ {painted}
+ {'\n'}
+ </div>
+ <textarea
+ ref={ref}
+ rows={1}
+ onScroll={followField}
+ value={text}
+ placeholder={asker ? L(`Responder a ${asker}`, `Reply to ${asker}`) : placeholder}
+ onChange={(e) => {
+ setText(e.target.value)
+ updateMention(e.target.value, e.target.selectionStart)
+ }}
+ onPaste={(e) => {
+ const files = [...e.clipboardData.files].filter((f) => f.type.startsWith('image/'))
+ if (!files.length) return
e.preventDefault()
- submit()
- }
- }}
- />
+ void addFiles(files)
+ }}
+ onKeyDown={(e) => {
+ if (e.code === 'Space' && (platform === 'mac' ? e.altKey : e.ctrlKey) && canRecord()) {
+ e.preventDefault()
+ if (!e.repeat) voiceControls.press()
+ return
+ }
+ if (e.key === 'Escape' && voice !== 'idle') return voiceControls.cancel()
+ if (mention && options.length > 0) {
+ if (e.key === 'ArrowDown') return (e.preventDefault(), setActive((active + 1) % options.length))
+ if (e.key === 'ArrowUp') return (e.preventDefault(), setActive((active - 1 + options.length) % options.length))
+ if (e.key === 'Enter' || e.key === 'Tab') return (e.preventDefault(), pick(options[active]!))
+ if (e.key === 'Escape') return setMention(null)
+ }
+ if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
+ e.preventDefault()
+ submit()
+ }
+ }}
+ />
+ </div>
<div className="composer__bar">
<VoiceButton controls={voiceControls} state={voice} />
<button className="icon-btn" title={L('Anexar imagem (ou arraste e solte, ou cole)', 'Attach an image (or drag and drop, or paste)')} onClick={() => picker.current?.click()}>
diff --git a/src/renderer/src/styles.css b/src/renderer/src/styles.css
index 363a483..faad712 100644
--- a/src/renderer/src/styles.css
+++ b/src/renderer/src/styles.css
@@ -1125,6 +1125,26 @@ h3 {
.md a {
color: var(--accent);
}
+/* An agent's @handle in a message: its chip, in its color, that opens its profile. */
+/* Inline, not flex: its text then sits on the line's baseline, like the words around it. */
+.mention {
+ display: inline;
+ white-space: nowrap;
+ padding: 2px 5px 2px 2px;
+ border-radius: 999px;
+ font: inherit;
+ font-weight: 600;
+ color: color-mix(in srgb, var(--agent, var(--accent)) 75%, var(--text));
+ background: color-mix(in srgb, var(--agent, var(--accent)) 14%, transparent);
+ transition: var(--transition-ui);
+}
+.mention:hover {
+ background: color-mix(in srgb, var(--agent, var(--accent)) 24%, transparent);
+}
+.mention .avatar {
+ vertical-align: middle;
+ margin-right: 4px;
+}
/* A long link or word breaks instead of pushing the message out of the conversation. */
.md {
max-width: 100%;
@@ -1485,6 +1505,35 @@ h3 {
.composer textarea:focus {
box-shadow: none;
}
+/* The field's text is drawn by the copy behind it (Composer), so a @handle can take its agent's color.
+ Both lay out the same: the copy takes the field's size, padding and type from the script. */
+.composer__field {
+ position: relative;
+}
+.composer__field textarea {
+ position: relative;
+ color: transparent;
+ caret-color: var(--text);
+}
+.composer__field textarea::placeholder {
+ color: var(--text-3);
+}
+.composer__mirror {
+ position: absolute;
+ top: 0;
+ left: 0;
+ overflow: hidden;
+ white-space: pre-wrap;
+ overflow-wrap: break-word;
+ color: var(--text);
+ pointer-events: none;
+}
+.composer__mirror mark {
+ color: color-mix(in srgb, var(--agent, var(--accent)) 75%, var(--text));
+ background: color-mix(in srgb, var(--agent, var(--accent)) 16%, transparent);
+ box-shadow: 0 0 0 2px color-mix(in srgb, var(--agent, var(--accent)) 16%, transparent);
+ border-radius: 3px;
+}
.composer__bar {
display: flex;
align-items: center;
diff --git a/src/shared/mention-text.ts b/src/shared/mention-text.ts
new file mode 100644
index 0000000..d507dd5
--- /dev/null
+++ b/src/shared/mention-text.ts
@@ -0,0 +1,61 @@
+// Finding @handles in a message. The same rule the core uses to call an agent (`mentioned`), so what
+// looks like a mention on screen is what calls someone. Whether a handle is an agent is up to the caller.
+import { CODE_SPANS } from './types'
+
+export const MENTION = /(^|[^\w@])@([a-z0-9][a-z0-9_-]{1,31})\b/gi
+
+export type MentionPart = { text: string } | { handle: string; text: string }
+
+function splitPlain(text: string, parts: MentionPart[]): void {
+ let last = 0
+ for (const m of text.matchAll(MENTION)) {
+ const at = m.index + m[1]!.length
+ if (at > last) parts.push({ text: text.slice(last, at) })
+ parts.push({ handle: m[2]!, text: `@${m[2]}` })
+ last = at + m[2]!.length + 1
+ }
+ if (last < text.length) parts.push({ text: text.slice(last) })
+}
+
+// Handles inside code are quoted content, not a call (CODE_SPANS): they stay text, as in the core.
+export function splitMentions(text: string): MentionPart[] {
+ const parts: MentionPart[] = []
+ let last = 0
+ for (const m of text.matchAll(CODE_SPANS)) {
+ splitPlain(text.slice(last, m.index), parts)
+ parts.push({ text: m[0] })
+ last = m.index + m[0].length
+ }
+ splitPlain(text.slice(last), parts)
+ return parts
+}
+
+interface Node {
+ type: string
+ value?: string
+ children?: Node[]
+ data?: { hName?: string; hProperties?: Record<string, string>; hChildren?: Node[] }
+}
+
+// A remark plugin: each @handle in a message's text becomes a <span data-mention="handle">, for the
+// renderer to show as the agent's chip (or as plain text, when no agent has that handle). Code and
+// links stay as they are.
+export function remarkMentions(): (tree: Node) => void {
+ const mention = (handle: string, text: string): Node => ({ type: 'mention', data: { hName: 'span', hProperties: { dataMention: handle }, hChildren: [{ type: 'text', value: text }] } })
+ const walk = (node: Node): void => {
+ if (!node.children) return
+ const next: Node[] = []
+ for (const child of node.children) {
+ if (child.type === 'text' && child.value?.includes('@')) {
+ const parts: MentionPart[] = []
+ splitPlain(child.value, parts)
+ for (const p of parts) next.push('handle' in p ? mention(p.handle, p.text) : { type: 'text', value: p.text })
+ } else {
+ if (child.type !== 'link' && child.type !== 'code' && child.type !== 'inlineCode') walk(child)
+ next.push(child)
+ }
+ }
+ node.children = next
+ }
+ return walk
+}
diff --git a/test/mention-text.test.ts b/test/mention-text.test.ts
new file mode 100644
index 0000000..71170f8
--- /dev/null
+++ b/test/mention-text.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest'
+import { remarkMentions, splitMentions } from '../src/shared/mention-text'
+
+describe('finding mentions in text', () => {
+ it('splits @handles out, keeping the text around them', () => {
+ expect(splitMentions('oi @ana, vê com @bruno-dev.')).toEqual([{ text: 'oi ' }, { handle: 'ana', text: '@ana' }, { text: ', vê com ' }, { handle: 'bruno-dev', text: '@bruno-dev' }, { text: '.' }])
+ })
+ it('leaves out emails, double @ and handles in code', () => {
+ const handles = (t: string): string[] => splitMentions(t).flatMap((p) => ('handle' in p ? [p.handle] : []))
+ expect(handles('mande pra [email protected] e @@ana')).toEqual([])
+ expect(handles('rode `@ana faça` e\n```\n@bruno\n```\ndepois @caio')).toEqual(['caio'])
+ })
+ it('gives back the whole text', () => {
+ const text = 'a `@b` @c\n```\n@d\n```\n@e!'
+ expect(splitMentions(text).map((p) => p.text).join('')).toBe(text)
+ })
+})
+
+describe('the remark plugin', () => {
+ it('turns @handles in text into spans the renderer reads, and leaves code and links alone', () => {
+ const tree = {
+ type: 'root',
+ children: [
+ {
+ type: 'paragraph',
+ children: [
+ { type: 'text', value: 'oi @ana e ' },
+ { type: 'inlineCode', value: '@bruno' },
+ { type: 'link', url: 'x', children: [{ type: 'text', value: '@caio' }] },
+ { type: 'strong', children: [{ type: 'text', value: '@duda' }] }
+ ]
+ }
+ ]
+ }
+ remarkMentions()(tree)
+ const json = JSON.stringify(tree)
+ expect(json.match(/"dataMention":"[^"]+"/g)).toEqual(['"dataMention":"ana"', '"dataMention":"duda"'])
+ expect(json).toContain('"value":"@bruno"')
+ expect(json).toContain('"value":"@caio"')
+ })
+})