Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat: @-agent / #-session mention composer (Lexical) (#536)

Call Whitecbbea8fec283
diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.py
index f5ee111d3..17277aac9 100644
--- a/core/system_prompt_injection.py
+++ b/core/system_prompt_injection.py
@@ -195,6 +195,13 @@ Rules:
- Use `vibe agent run --agent <agent-name> --session-id ... --message ...` only to continue that same Session. Reuse the current session id only with Agents whose `Backend` matches `{current_agent_backend}`; otherwise use `--create-session`.
- `--async` changes waiting behavior, not session identity: synchronous waits for the result; async runs in the background and is inspected later with `vibe runs`.
- Create or update Agents only when it captures a reusable role, reduces repeated prompting, or makes a long-running Harness more reliable.
+
+### Mentions in user messages
+On the Web chat the user composes with `@` / `#` autocomplete, which inserts stable references into their message text:
+- `@<agent-name>` points at that enabled Agent (see the table above). Act on it with `vibe agent run --agent <agent-name> ...`.
+- `#<session-id>` points at that Session. Resume it with `vibe agent run --session-id <session-id> ...`, or read its history with `vibe data query`.
+
+Treat these as the user pointing at that Agent or Session, and decide the action from context. Only the bracketed `@<...>` / `#<...>` forms are references; a bare `@` or `#` in prose is ordinary text.
"""
_SESSION_END_PROMPT = """\
diff --git a/docs/plans/composer-at-hash-mentions.md b/docs/plans/composer-at-hash-mentions.md
new file mode 100644
index 000000000..b5c493a3b
--- /dev/null
+++ b/docs/plans/composer-at-hash-mentions.md
@@ -0,0 +1,77 @@
+# Composer @-agent / #-session mentions
+
+## Background
+The Web chat composer is a plain `<textarea>`. We want IM-style autocomplete:
+`@` mentions an enabled **Agent**, `#` references any **Session** by title. On
+send, selections become stable text markers plus a structured sidecar; the
+current Agent reads the markers and acts via existing Harness commands.
+
+## Locked design (from product dialogue)
+- **Semantics = Model B.** Markers are *references* handed to the CURRENT agent;
+ no core re-routing. The agent acts via `vibe agent run --agent <name>` /
+ `--session-id <id>` / `vibe data query`.
+- **Markers (angle brackets):** `@<Agent Display Name>` (the `--agent` handle),
+ `#<session-id>` (the `--session-id` handle). Regex `/([@#])<([^>\n]+)>/g`.
+- **Double-write:** the message `text` keeps the markers; a sidecar
+ `content.references: [{kind:'agent',name,agent_id,backend} | {kind:'session',session_id,title}]`
+ rides in the existing `content` JSON blob (same home as attachments /
+ quick_replies → no schema migration).
+- **`#` scope:** ALL sessions machine-wide, EXCLUDE the current session; recent-N
+ by default, ≥2 chars → global title search.
+- **Surface:** Web composer only; multiple `@`/`#` per message; only
+ picker-selected items become markers (literal typed `@`/`#` stay plain text).
+- **Inline chips required** → composer input becomes contenteditable.
+- **Library:** Lexical + `lexical-beautiful-mentions` (MIT, multi-trigger,
+ custom menu/chip, node `data`, hook). Fallback = TipTap (same data contract).
+
+## Solution / architecture
+The data contract (markers + `content.references`) is library-agnostic.
+
+**Frontend**
+- `ui/src/lib/mentions.ts` — shared contract: `MentionReference` type, marker
+ regex, `referenceToMarker`, `linkifyMentions` (marker → markdown link with the
+ `avibe-mention:` scheme), `parseMentionHref`.
+- `ui/src/components/workbench/MentionEditor.tsx` — Lexical PlainText editor +
+ `BeautifulMentionsPlugin` (triggers `@`/`#`, async `onSearch`). Serializes the
+ editor to marker text + references via node traversal. cmdk-styled menu.
+ Replicates the textarea contract: Enter-to-send (shift/IME/soft-keyboard
+ aware), auto-grow, autofocus, placeholder, voice insert, clear, focus.
+- `Composer.tsx` — when `onSearchAgents`/`onSearchSessions` props are present,
+ render `<MentionEditor>` instead of `<textarea>` (Workbench home stays plain).
+- `ui/src/components/ui/markdown.tsx` — `a` map renders a `Badge` chip for the
+ `avibe-mention:` scheme; `urlTransform` passes that scheme through react-markdown's
+ sanitizer; new optional `references` prop pre-runs `linkifyMentions`.
+- `ChatPage.tsx` — supplies `onSearchAgents` (listVibeAgents enabled) +
+ `onSearchSessions` (listSessions, exclude current, ≥2 chars → title search);
+ threads `references` into `sendMessage` → `content.references`; `MessageRow`
+ passes `content.references` to `<Markdown>`.
+- `ApiContext.tsx` — `listSessions({ q })` title-search param.
+- i18n keys (`en`/`zh`).
+
+**Backend**
+- `storage/workbench_sessions_service.list_sessions` — add `query` (title
+ LIKE, case-insensitive) and `exclude_id`.
+- UI route `GET /api/sessions` — accept `q` + `exclude_id`.
+- `core/handlers/message_handler` — per-turn: expand `content.references` into a
+ compact context block prepended to the agent message (resolve by id: agent
+ enabled? desc; session exists? title + last_active + usable vibe commands).
+ Re-resolve live (don't trust the client snapshot for actions).
+
+## Todo
+- [ ] FE: mentions.ts contract + helpers
+- [ ] FE: MentionEditor (Lexical + beautiful-mentions)
+- [ ] FE: Composer integration (gated on mention props)
+- [ ] FE: markdown chip rendering + Badge + urlTransform
+- [ ] FE: ChatPage wiring + MessageRow references
+- [ ] FE: ApiContext title-search param + i18n + chip/editor CSS
+- [ ] BE: list_sessions query + exclude_id (+ route)
+- [ ] BE: per-turn reference context expansion (message_handler)
+- [ ] Tests: pytest (search + reference expansion); npm run build green
+- [ ] Codex self-review → non-draft PR → review watch
+- [ ] Hand-off: real-device iOS Safari + Chinese IME validation (human)
+
+## Evidence layers
+- unit: pytest for list_sessions search/exclude + reference-block builder.
+- contract: marker (de)serialization round-trip (vitest if present, else pure-fn check).
+- scenario: none new.
+- residual manual: iOS Safari + Chinese IME on the live composer (human).
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index 28529dc4e..4ef014e00 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -111,12 +111,16 @@ def list_sessions(
status: Optional[str] = None,
limit: int = 50,
before_id: Optional[str] = None,
+ title_query: Optional[str] = None,
) -> dict[str, Any]:
"""Return sessions for the workbench list. Cursor pagination via ``before_id``.
``status`` accepts ``active`` / ``archived`` (or omit for both). The
cursor is the row id; results are sorted by ``last_active_at DESC``
so the cursor row is "the last id you already saw".
+
+ ``title_query`` powers the chat composer ``#``-mention global search: a
+ case-insensitive title LIKE match (LIKE metacharacters escaped).
"""
query = select(agent_sessions)
@@ -124,6 +128,12 @@ def list_sessions(
query = query.where(agent_sessions.c.scope_id == scope_id)
if status is not None and status != "all":
query = query.where(agent_sessions.c.status == status)
+ if title_query:
+ # `#`-mention global search: case-insensitive title LIKE. Escape the LIKE
+ # metacharacters so a literal ``%`` / ``_`` in the query can't widen it.
+ like = title_query.strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
+ if like:
+ query = query.where(agent_sessions.c.title.ilike(f"%{like}%", escape="\\"))
if before_id is not None:
cursor_row = conn.execute(
select(agent_sessions.c.last_active_at, agent_sessions.c.created_at).where(agent_sessions.c.id == before_id)
diff --git a/tests/test_core_services_sessions.py b/tests/test_core_services_sessions.py
index c826fd049..d6737c3b5 100644
--- a/tests/test_core_services_sessions.py
+++ b/tests/test_core_services_sessions.py
@@ -171,6 +171,32 @@ def test_update_then_list_reflects_changes(isolated_state):
assert page["sessions"][0]["model"] == "claude-sonnet-4-6"
+def test_list_sessions_title_query_filters_by_title(isolated_state):
+ """``#``-mention search: case-insensitive title LIKE, escaping LIKE metachars."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_avibe_scope(conn)
+ sessions_service.create_session(
+ conn, scope_id=scope_id, agent_backend="claude", title="Review auth module"
+ )
+ sessions_service.create_session(
+ conn, scope_id=scope_id, agent_backend="claude", title="Deploy pipeline"
+ )
+ sessions_service.create_session(
+ conn, scope_id=scope_id, agent_backend="claude", title="100% coverage push"
+ )
+
+ with engine.connect() as conn:
+ hit = sessions_service.list_sessions(conn, title_query="AUTH")
+ miss = sessions_service.list_sessions(conn, title_query="nonexistent")
+ literal = sessions_service.list_sessions(conn, title_query="100%")
+
+ assert [s["title"] for s in hit["sessions"]] == ["Review auth module"]
+ assert miss["sessions"] == []
+ # The ``%`` is escaped, so it matches the literal "100%" title, not every row.
+ assert [s["title"] for s in literal["sessions"]] == ["100% coverage push"]
+
+
def test_archive_marks_session(isolated_state):
engine = create_sqlite_engine()
with engine.begin() as conn:
diff --git a/ui/package-lock.json b/ui/package-lock.json
index cd85522e1..49e2ddada 100644
--- a/ui/package-lock.json
+++ b/ui/package-lock.json
@@ -8,6 +8,7 @@
"name": "ui",
"version": "0.0.0",
"dependencies": {
+ "@lexical/react": "^0.45.0",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-popover": "^1.1.15",
@@ -23,6 +24,8 @@
"framer-motion": "^12.26.2",
"i18next": "^25.7.4",
"i18next-browser-languagedetector": "^8.2.0",
+ "lexical": "^0.45.0",
+ "lexical-beautiful-mentions": "^0.1.48",
"lucide-react": "^0.562.0",
"papaparse": "^5.5.3",
"qrcode.react": "^4.2.0",
@@ -963,31 +966,46 @@
}
},
"node_modules/@floating-ui/core": {
- "version": "1.7.3",
- "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.3.tgz",
- "integrity": "sha512-sGnvb5dmrJaKEZ+LDIpguvdX3bDlEllmv4/ClQ9awcmCZrlx5jQyyMWFM5kBI+EyNOCDDiKk8il0zeuX3Zlg/w==",
+ "version": "1.7.5",
+ "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.5.tgz",
+ "integrity": "sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==",
"license": "MIT",
"dependencies": {
- "@floating-ui/utils": "^0.2.10"
+ "@floating-ui/utils": "^0.2.11"
}
},
"node_modules/@floating-ui/dom": {
- "version": "1.7.4",
- "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.4.tgz",
- "integrity": "sha512-OOchDgh4F2CchOX94cRVqhvy7b3AFb+/rQXyswmzmGakRfkMgoWVjfnLWkRirfLEfuD4ysVW16eXzwt3jHIzKA==",
+ "version": "1.7.6",
+ "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.6.tgz",
+ "integrity": "sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ==",
"license": "MIT",
"dependencies": {
- "@floating-ui/core": "^1.7.3",
- "@floating-ui/utils": "^0.2.10"
+ "@floating-ui/core": "^1.7.5",
+ "@floating-ui/utils": "^0.2.11"
+ }
+ },
+ "node_modules/@floating-ui/react": {
+ "version": "0.27.19",
+ "resolved": "https://registry.npmjs.org/@floating-ui/react/-/react-0.27.19.tgz",
+ "integrity": "sha512-31B8h5mm8YxotlE7/AU/PhNAl8eWxAmjL/v2QOxroDNkTFLk3Uu82u63N3b6TXa4EGJeeZLVcd/9AlNlVqzeog==",
+ "license": "MIT",
+ "dependencies": {
+ "@floating-ui/react-dom": "^2.1.8",
+ "@floating-ui/utils": "^0.2.11",
+ "tabbable": "^6.0.0"
+ },
+ "peerDependencies": {
+ "react": ">=17.0.0",
+ "react-dom": ">=17.0.0"
}
},
"node_modules/@floating-ui/react-dom": {
- "version": "2.1.6",
- "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.6.tgz",
- "integrity": "sha512-4JX6rEatQEvlmgU80wZyq9RT96HZJa88q8hp0pBd+LrczeDI4o6uA2M+uvxngVHo4Ihr8uibXxH6+70zhAFrVw==",
+ "version": "2.1.8",
+ "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.8.tgz",
+ "integrity": "sha512-cC52bHwM/n/CxS87FH0yWdngEZrjdtLW/qVruo68qg+prK7ZQ4YGdut2GyDVpoGeAYe/h899rVeOVm6Oi40k2A==",
"license": "MIT",
"dependencies": {
- "@floating-ui/dom": "^1.7.4"
+ "@floating-ui/dom": "^1.7.6"
},
"peerDependencies": {
"react": ">=16.8.0",
@@ -995,9 +1013,9 @@
}
},
"node_modules/@floating-ui/utils": {
- "version": "0.2.10",
- "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.10.tgz",
- "integrity": "sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ==",
+ "version": "0.2.11",
+ "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.11.tgz",
+ "integrity": "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==",
"license": "MIT"
},
"node_modules/@humanfs/core": {
@@ -1102,6 +1120,315 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
+ "node_modules/@lexical/clipboard": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/clipboard/-/clipboard-0.45.0.tgz",
+ "integrity": "sha512-9oDu2SNj/EZGjpXJTruz74Ls3VzF2Q41v1QB7JnTq5lh24byvIOdgEpOFHtr/7WVHssfXCbMtgFb5tW8rMaZ2g==",
+ "license": "MIT",
+ "dependencies": {
+ "@lexical/extension": "0.45.0",
+ "@lexical/html": "0.45.0",
+ "@lexical/internal": "0.45.0",
+ "@lexical/list": "0.45.0",
+ "@lexical/selection": "0.45.0",
+ "@lexical/utils": "0.45.0",
+ "@types/trusted-types": "^2.0.7",
+ "lexical": "0.45.0"
+ }
+ },
+ "node_modules/@lexical/code-core": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/code-core/-/code-core-0.45.0.tgz",
+ "integrity": "sha512-zU3noYmfluSK38r0eBz3gHKzsgOksf9eHqoPIwXH6HovKCDo848HoW0i/hCRzRo9oPqydKikx0LIKUvWSaSNIw==",
+ "license": "MIT",
+ "dependencies": {
+ "@lexical/extension": "0.45.0",
+ "@lexical/html": "0.45.0",
+ "@lexical/internal": "0.45.0",
+ "lexical": "0.45.0"
+ }
+ },
+ "node_modules/@lexical/devtools-core": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/devtools-core/-/devtools-core-0.45.0.tgz",
+ "integrity": "sha512-XiVedKif5nWbNj2CeNy30kokfk/iYb7Db+B1Z18bnr/uzp6IzkxpX6I4GeZu4HVbQJhGMCAdq19tFpYwXOx4sw==",
+ "license": "MIT",
+ "dependencies": {
+ "@lexical/html": "0.45.0",
+ "@lexical/link": "0.45.0",
+ "@lexical/mark": "0.45.0",
+ "@lexical/table": "0.45.0",
+ "@lexical/utils": "0.45.0",
+ "lexical": "0.45.0"
+ },
+ "peerDependencies": {
+ "react": ">=17.x",
+ "react-dom": ">=17.x"
+ }
+ },
+ "node_modules/@lexical/dragon": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/dragon/-/dragon-0.45.0.tgz",
+ "integrity": "sha512-34k2/QuM8A9WVqVCtNGx1ySBWXxMVKejKH3VBWnXEb1NdrDa/N8jLpu0gOCLcrrDjMdUzs9uVgW0D4FRf1Lixg==",
+ "license": "MIT",
+ "dependencies": {
+ "@lexical/extension": "0.45.0",
+ "lexical": "0.45.0"
+ }
+ },
+ "node_modules/@lexical/extension": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/extension/-/extension-0.45.0.tgz",
+ "integrity": "sha512-oJs1Zvrsqh32zZmeCkTQi7R2WoVIvaQE265JFZ/VczWlsWRdkkWQbGZ6iOlBZ3AmtiNgHoBeB0gZSoRQtWEQyA==",
+ "license": "MIT",
+ "dependencies": {
+ "@lexical/internal": "0.45.0",
+ "@lexical/utils": "0.45.0",
+ "@preact/signals-core": "^1.14.1",
+ "lexical": "0.45.0"
+ }
+ },
+ "node_modules/@lexical/hashtag": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/hashtag/-/hashtag-0.45.0.tgz",
+ "integrity": "sha512-gFX4n+9RjOFVkNUkEcv3JeQT0LvZ8fiHWHrIkg1m3JbyloG6mKDlsSlO1qnIPUaAB4V62Tbnmfv3I0qp1UvNuw==",
+ "license": "MIT",
+ "dependencies": {
+ "@lexical/text": "0.45.0",
+ "@lexical/utils": "0.45.0",
+ "lexical": "0.45.0"
+ }
+ },
+ "node_modules/@lexical/history": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/history/-/history-0.45.0.tgz",
+ "integrity": "sha512-KihtI8485Wx7kyFCtKNKk/nO2jSibRa8iL0OiKPZsYWVAQF5vFG3J00epX8EkEpeCx8Zjmj+3eytY05HPNd2nA==",
+ "license": "MIT",
+ "dependencies": {
+ "@lexical/extension": "0.45.0",
+ "@lexical/utils": "0.45.0",
+ "lexical": "0.45.0"
+ }
+ },
+ "node_modules/@lexical/html": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/html/-/html-0.45.0.tgz",
+ "integrity": "sha512-eK215f25cnAcIzNB1iRltg8hbvkK5wyyXvKQUqhfG/9HaSSVBCPuCyXKZicjZllQNvbFINGHFhTIqSP56drFSw==",
+ "license": "MIT",
+ "dependencies": {
+ "@lexical/extension": "0.45.0",
+ "@lexical/internal": "0.45.0",
+ "@lexical/selection": "0.45.0",
+ "@lexical/utils": "0.45.0",
+ "lexical": "0.45.0"
+ }
+ },
+ "node_modules/@lexical/internal": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/internal/-/internal-0.45.0.tgz",
+ "integrity": "sha512-IhyzCdb1/xdpTtvK0xnqUXpaVRsD2KTZ6EMZpavm6dhKaglf1zorpdbH7r6Hjps6SRb4DCn/t7lac+GMdDFbXg==",
+ "license": "MIT"
+ },
+ "node_modules/@lexical/link": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/link/-/link-0.45.0.tgz",
+ "integrity": "sha512-9xpsRQ06IA4eVnx4OtFV0+Tmp2Etvh0dh9FTFd/LJYaqo2A0ZIuNUggueDZ0i2dhi8wWW8J08O7U0HxLcDWHAg==",
+ "license": "MIT",
+ "dependencies": {
+ "@lexical/extension": "0.45.0",
+ "@lexical/html": "0.45.0",
+ "@lexical/internal": "0.45.0",
+ "@lexical/utils": "0.45.0",
+ "lexical": "0.45.0"
+ }
+ },
+ "node_modules/@lexical/list": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/list/-/list-0.45.0.tgz",
+ "integrity": "sha512-Eyff9KVLu5mV4QSid2aw9uYmKDKgDYToAaagI9Sp3VgqTMmvRUQJ0w7sr4zq8/FRKSzrsf4V2FjvLAuQE7eBUQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@lexical/extension": "0.45.0",
+ "@lexical/html": "0.45.0",
+ "@lexical/internal": "0.45.0",
+ "@lexical/utils": "0.45.0",
+ "lexical": "0.45.0"
+ }
+ },
+ "node_modules/@lexical/mark": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/mark/-/mark-0.45.0.tgz",
+ "integrity": "sha512-PMyGmnF6koE5TKCDlGe1k1t1ZOefReyYaKtx6OY3Tf1AyyKII6zRGR+dANrgWzYliYO7j4mpKBK00ykOnuF3zA==",
+ "license": "MIT",
+ "dependencies": {
+ "@lexical/utils": "0.45.0",
+ "lexical": "0.45.0"
+ }
+ },
+ "node_modules/@lexical/markdown": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/markdown/-/markdown-0.45.0.tgz",
+ "integrity": "sha512-fl/UUwudBXGnz44kOS07ZRN0DMfOWNnVl7GSSNyz6zDo1cMD60URt7LjF51bAG2oL8i1eRDX4/GV+7vBcuoGzw==",
+ "license": "MIT",
+ "dependencies": {
+ "@lexical/code-core": "0.45.0",
+ "@lexical/internal": "0.45.0",
+ "@lexical/link": "0.45.0",
+ "@lexical/list": "0.45.0",
+ "@lexical/rich-text": "0.45.0",
+ "@lexical/selection": "0.45.0",
+ "@lexical/text": "0.45.0",
+ "@lexical/utils": "0.45.0",
+ "lexical": "0.45.0"
+ }
+ },
+ "node_modules/@lexical/overflow": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/overflow/-/overflow-0.45.0.tgz",
+ "integrity": "sha512-iw6Gc85phIGEjAFRDLiGOrnxK/EjyRlEfQHI7BeU0m+qHDCc94cThbeuaPTC7nnxHytFbRdtJIhoQvvcUR+PKA==",
+ "license": "MIT",
+ "dependencies": {
+ "lexical": "0.45.0"
+ }
+ },
+ "node_modules/@lexical/plain-text": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/plain-text/-/plain-text-0.45.0.tgz",
+ "integrity": "sha512-453bsKVk3oY5/ktp3A2zO2nFdXniU/zfD87eIcN50aXrIwvNm082GkfmBaDeVujk7fLgC2hG980xdcEH4xcG3w==",
+ "license": "MIT",
+ "dependencies": {
+ "@lexical/clipboard": "0.45.0",
+ "@lexical/dragon": "0.45.0",
+ "@lexical/extension": "0.45.0",
+ "@lexical/selection": "0.45.0",
+ "@lexical/utils": "0.45.0",
+ "lexical": "0.45.0"
+ }
+ },
+ "node_modules/@lexical/react": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/react/-/react-0.45.0.tgz",
+ "integrity": "sha512-LAaceAtcQpVMDvldhkrQC1MSawpj7aAm1CfGg6RbyQgTDDp2fKnP1gDhjQIef3lH8W2fYeXRe66EdzaFkoGHKA==",
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "@floating-ui/react": "^0.27.19",
+ "@lexical/devtools-core": "0.45.0",
+ "@lexical/dragon": "0.45.0",
+ "@lexical/extension": "0.45.0",
+ "@lexical/hashtag": "0.45.0",
+ "@lexical/history": "0.45.0",
+ "@lexical/internal": "0.45.0",
+ "@lexical/link": "0.45.0",
+ "@lexical/list": "0.45.0",
+ "@lexical/mark": "0.45.0",
+ "@lexical/markdown": "0.45.0",
+ "@lexical/overflow": "0.45.0",
+ "@lexical/plain-text": "0.45.0",
+ "@lexical/rich-text": "0.45.0",
+ "@lexical/table": "0.45.0",
+ "@lexical/text": "0.45.0",
+ "@lexical/utils": "0.45.0",
+ "@lexical/yjs": "0.45.0",
+ "lexical": "0.45.0",
+ "react-error-boundary": "^6.1.1"
+ },
+ "peerDependencies": {
+ "react": ">=17.x",
+ "react-dom": ">=17.x",
+ "yjs": ">=13.5.22"
+ },
+ "peerDependenciesMeta": {
+ "yjs": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@lexical/rich-text": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/rich-text/-/rich-text-0.45.0.tgz",
+ "integrity": "sha512-jd+jIsDirqILuUQiNUJAzZWynVZHuN1ekqYcydgDFaUXMFBQgVr3mBUieQzMw2IDAEk98txntu/mZQav4BryQQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@lexical/clipboard": "0.45.0",
+ "@lexical/dragon": "0.45.0",
+ "@lexical/extension": "0.45.0",
+ "@lexical/html": "0.45.0",
+ "@lexical/selection": "0.45.0",
+ "@lexical/utils": "0.45.0",
+ "lexical": "0.45.0"
+ }
+ },
+ "node_modules/@lexical/selection": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/selection/-/selection-0.45.0.tgz",
+ "integrity": "sha512-V2DYMhl84F1aZ24YpWMMqy9ikO7cVfD3G+GjMwrZnMt0JVnIghjPiYIEBb/OtqqA+mCbBwNhfpdK1RtF9HTbJA==",
+ "license": "MIT",
+ "dependencies": {
+ "@lexical/internal": "0.45.0",
+ "lexical": "0.45.0"
+ }
+ },
+ "node_modules/@lexical/table": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/table/-/table-0.45.0.tgz",
+ "integrity": "sha512-OXbwEg0DqkTdvqnu7z+/u8bgnDz2sjHHXCG3zGRhEzDgHcWoVQ18IciwMdse7dTTNfBIJMuGJcRoWPrHf9UlhQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@lexical/clipboard": "0.45.0",
+ "@lexical/extension": "0.45.0",
+ "@lexical/html": "0.45.0",
+ "@lexical/internal": "0.45.0",
+ "@lexical/utils": "0.45.0",
+ "lexical": "0.45.0"
+ }
+ },
+ "node_modules/@lexical/text": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/text/-/text-0.45.0.tgz",
+ "integrity": "sha512-ozI8fDsLTYAzEWXaBrGYZ0GnRbbIHi4IL99w5q06UfTQzBMYmF7WaccDP1krOOwwioPYQbiqZM7dh/41jsFELQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@lexical/internal": "0.45.0",
+ "lexical": "0.45.0"
+ }
+ },
+ "node_modules/@lexical/utils": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/utils/-/utils-0.45.0.tgz",
+ "integrity": "sha512-Fo5MMErqoPlUyTw1qVMZ9kE33ZjJF957KU683tsCrrlaVisVxpboL7BbAnxWTwCcIpAsfc6AUndJJ70M9NDMGg==",
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "@lexical/internal": "0.45.0",
+ "@lexical/selection": "0.45.0",
+ "lexical": "0.45.0"
+ }
+ },
+ "node_modules/@lexical/yjs": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/@lexical/yjs/-/yjs-0.45.0.tgz",
+ "integrity": "sha512-HYbOovvOavtF1S7C13l9g21s4MFLLd/o49qdn+/uGj23j4yjG556XBSrF0c3BREXDXSUr+RTbI6uiQ+L5Ofcmw==",
+ "license": "MIT",
+ "dependencies": {
+ "@lexical/internal": "0.45.0",
+ "@lexical/selection": "0.45.0",
+ "lexical": "0.45.0"
+ },
+ "peerDependencies": {
+ "yjs": ">=13.5.22"
+ }
+ },
+ "node_modules/@preact/signals-core": {
+ "version": "1.14.2",
+ "resolved": "https://registry.npmjs.org/@preact/signals-core/-/signals-core-1.14.2.tgz",
+ "integrity": "sha512-RZHdBj9ZF4n40Rp4jS052EHHjBWf96P9oNdXPfhQTovCuWY9iQn3Gq+gOTJSgBO9A/JBuPfMOWsSX/lIU9Pc/A==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/preact"
+ }
+ },
"node_modules/@radix-ui/primitive": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.3.tgz",
@@ -2582,6 +2909,12 @@
"@types/react": "^19.2.0"
}
},
+ "node_modules/@types/trusted-types": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
+ "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
+ "license": "MIT"
+ },
"node_modules/@types/unist": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",
@@ -4165,6 +4498,16 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/isomorphic.js": {
+ "version": "0.2.5",
+ "resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz",
+ "integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==",
+ "license": "MIT",
+ "funding": {
+ "type": "GitHub Sponsors ❤",
+ "url": "https://github.com/sponsors/dmonad"
+ }
+ },
"node_modules/jiti": {
"version": "2.6.1",
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.6.1.tgz",
@@ -4266,6 +4609,50 @@
"node": ">= 0.8.0"
}
},
+ "node_modules/lexical": {
+ "version": "0.45.0",
+ "resolved": "https://registry.npmjs.org/lexical/-/lexical-0.45.0.tgz",
+ "integrity": "sha512-z2M9C2ILPW7SopQE1aKbOFdZJbe3HvsrgWnJKveMDrSEvVjU9Hce4UpKVsAdkwY7TgY9RDuCV3+sfrGu0WkL+w==",
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "@lexical/internal": "0.45.0"
+ }
+ },
+ "node_modules/lexical-beautiful-mentions": {
+ "version": "0.1.48",
+ "resolved": "https://registry.npmjs.org/lexical-beautiful-mentions/-/lexical-beautiful-mentions-0.1.48.tgz",
+ "integrity": "sha512-ukiSAxMB9Hl88V19eT5uDSC7gDpeXKhgO6MEtmHKnj69VgwLVCKclIr2UO6yJs97QEw3cqJA5nM4j72obgXlmw==",
+ "license": "MIT",
+ "peerDependencies": {
+ "@lexical/react": ">=0.11.0",
+ "@lexical/utils": ">=0.11.0",
+ "lexical": ">=0.11.0",
+ "react": ">=17.x",
+ "react-dom": ">=17.x"
+ }
+ },
+ "node_modules/lib0": {
+ "version": "0.2.117",
+ "resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.117.tgz",
+ "integrity": "sha512-DeXj9X5xDCjgKLU/7RR+/HQEVzuuEUiwldwOGsHK/sfAfELGWEyTcf0x+uOvCvK3O2zPmZePXWL85vtia6GyZw==",
+ "license": "MIT",
+ "dependencies": {
+ "isomorphic.js": "^0.2.4"
+ },
+ "bin": {
+ "0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js",
+ "0gentesthtml": "bin/gentesthtml.js",
+ "0serve": "bin/0serve.js"
+ },
+ "engines": {
+ "node": ">=16"
+ },
+ "funding": {
+ "type": "GitHub Sponsors ❤",
+ "url": "https://github.com/sponsors/dmonad"
+ }
+ },
"node_modules/lightningcss": {
"version": "1.30.2",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.30.2.tgz",
@@ -5776,6 +6163,15 @@
"react": "^19.2.3"
}
},
+ "node_modules/react-error-boundary": {
+ "version": "6.1.2",
+ "resolved": "https://registry.npmjs.org/react-error-boundary/-/react-error-boundary-6.1.2.tgz",
+ "integrity": "sha512-3DpCr5HVdZ0caUjYE/kIHBEJN0mNP3ZCgf16c48uJ5TbWjorKVp+YG8W3XqlJ7vJAVNw6wNIImyPXmFydwmyng==",
+ "license": "MIT",
+ "peerDependencies": {
+ "react": "^18.0.0 || ^19.0.0"
+ }
+ },
"node_modules/react-i18next": {
"version": "16.5.3",
"resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-16.5.3.tgz",
@@ -6249,6 +6645,12 @@
"node": ">=8"
}
},
+ "node_modules/tabbable": {
+ "version": "6.4.0",
+ "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-6.4.0.tgz",
+ "integrity": "sha512-05PUHKSNE8ou2dwIxTngl4EzcnsCDZGJ/iCLtDflR/SHB/ny14rXc+qU5P4mG9JkusiV7EivzY9Mhm55AzAvCg==",
+ "license": "MIT"
+ },
"node_modules/tailwind-merge": {
"version": "3.4.0",
"resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.4.0.tgz",
@@ -6730,6 +7132,24 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/yjs": {
+ "version": "13.6.31",
+ "resolved": "https://registry.npmjs.org/yjs/-/yjs-13.6.31.tgz",
+ "integrity": "sha512-Eq+5BRfbeGyqGVrTJL3bEcr8gKkxPuyuoHmAwpk52fDb8kOVMrfVSTRPd6yiGgX5Fskb96qCRjzjbRjrL4YEnw==",
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "lib0": "^0.2.99"
+ },
+ "engines": {
+ "node": ">=16.0.0",
+ "npm": ">=8.0.0"
+ },
+ "funding": {
+ "type": "GitHub Sponsors ❤",
+ "url": "https://github.com/sponsors/dmonad"
+ }
+ },
"node_modules/yocto-queue": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
diff --git a/ui/package.json b/ui/package.json
index 1196f7fc9..7662a682c 100644
--- a/ui/package.json
+++ b/ui/package.json
@@ -11,6 +11,7 @@
"validate:theme": "node scripts/validate-theme.mjs"
},
"dependencies": {
+ "@lexical/react": "^0.45.0",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-popover": "^1.1.15",
@@ -26,6 +27,8 @@
"framer-motion": "^12.26.2",
"i18next": "^25.7.4",
"i18next-browser-languagedetector": "^8.2.0",
+ "lexical": "^0.45.0",
+ "lexical-beautiful-mentions": "^0.1.48",
"lucide-react": "^0.562.0",
"papaparse": "^5.5.3",
"qrcode.react": "^4.2.0",
diff --git a/ui/src/components/ui/markdown.tsx b/ui/src/components/ui/markdown.tsx
index a66b8691f..b7292438d 100644
--- a/ui/src/components/ui/markdown.tsx
+++ b/ui/src/components/ui/markdown.tsx
@@ -1,11 +1,18 @@
import * as React from 'react';
-import ReactMarkdown, { type Components } from 'react-markdown';
+import ReactMarkdown, { type Components, defaultUrlTransform } from 'react-markdown';
import remarkGfm from 'remark-gfm';
import remarkBreaks from 'remark-breaks';
+import { Badge } from '@/components/ui/badge';
import { ChatImage, LinkedImageProvider } from '@/components/ui/chat-image';
import { FileCard } from '@/components/ui/file-card';
import { isProxyMediaUrl, readMediaDims } from '@/lib/mediaProxy';
+import {
+ MENTION_LINK_SCHEME,
+ linkifyMentions,
+ parseMentionHref,
+ type MentionReference,
+} from '@/lib/mentions';
import { cn } from '@/lib/utils';
// Shared markdown renderer. react-markdown + remark-gfm (tables, strikethrough,
@@ -25,12 +32,21 @@ import { cn } from '@/lib/utils';
// echoes with its line breaks intact while still formatting explicit markdown;
// leave it off for authored markdown (agent replies) where wrapped lines must
// not sprout stray hard breaks.
+// Keep react-markdown's URL sanitizer from stripping our custom mention scheme
+// (it allows only http/https/mailto/tel/relative by default).
+function mentionUrlTransform(url: string): string {
+ return url.startsWith(`${MENTION_LINK_SCHEME}:`) ? url : defaultUrlTransform(url);
+}
+
export const Markdown: React.FC<{
content: string;
className?: string;
interactive?: boolean;
softBreaks?: boolean;
-}> = ({ content, className, interactive = true, softBreaks = false }) => {
+ /** Mention sidecar — when present, `@<name>` / `#<id>` markers in `content`
+ * render as inline chips (see lib/mentions). */
+ references?: MentionReference[];
+}> = ({ content, className, interactive = true, softBreaks = false, references }) => {
// Stable ``remarkPlugins`` + ``components`` identities across re-renders.
// ReactMarkdown keys its rendered tree on the component functions it is handed;
// the old inline object minted fresh functions every render, so ReactMarkdown
@@ -79,6 +95,20 @@ export const Markdown: React.FC<{
// clickable row (non-interactive).
a: ({ href, children }) => {
const url = href ? String(href) : '';
+ // @-agent / #-session mention chips (see lib/mentions). Rendered in both
+ // interactive and non-interactive contexts — a chip is a span, safe inside
+ // a clickable row, and never triggers a fetch or navigation.
+ const mention = parseMentionHref(url);
+ if (mention) {
+ return (
+ <Badge
+ variant={mention.kind === '@' ? 'success' : 'info'}
+ className="max-w-[18rem] truncate align-baseline font-medium"
+ >
+ {children}
+ </Badge>
+ );
+ }
if (interactive && url && isProxyMediaUrl(url)) {
return <FileCard href={url}>{children}</FileCard>;
}
@@ -105,10 +135,19 @@ export const Markdown: React.FC<{
[interactive],
);
+ // Mention markers are rewritten to `avibe-mention:` links BEFORE markdown sees
+ // them, and only when a sidecar is present — agent replies (no references) skip
+ // this so their code spans are never touched. The links render as chips via the
+ // `a` map.
+ const rendered = references && references.length ? linkifyMentions(content, references) : content;
return (
<div className={cn('vr-markdown', className)}>
- <ReactMarkdown remarkPlugins={remarkPlugins} components={components}>
- {content}
+ <ReactMarkdown
+ remarkPlugins={remarkPlugins}
+ components={components}
+ urlTransform={mentionUrlTransform}
+ >
+ {rendered}
</ReactMarkdown>
</div>
);
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index ba5d2b6dd..a853929d7 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -22,7 +22,8 @@ import { ImageViewerProvider } from '../ui/image-viewer';
import { FileViewerProvider } from '../ui/file-viewer';
import { Input } from '../ui/input';
import { Markdown } from '../ui/markdown';
-import { Composer, type ComposerAttachment, type ComposerHandle } from './Composer';
+import { Composer, type ComposerAttachment, type ComposerHandle, type ComposerProps } from './Composer';
+import type { MentionReference } from '../../lib/mentions';
import { QuickReplies } from './QuickReplies';
// While a turn is in flight, reconcile the working/Stop state against the
@@ -537,7 +538,12 @@ export const ChatPage: React.FC = () => {
}, [working, syncTurnState]);
const sendMessage = useCallback(
- async (text: string, attachments?: ComposerAttachment[], metadata?: Record<string, unknown>) => {
+ async (
+ text: string,
+ attachments?: ComposerAttachment[],
+ metadata?: Record<string, unknown>,
+ references?: MentionReference[],
+ ) => {
// NB: no ``working`` guard — sending WHILE a turn runs is the queue
// feature; the backend enqueues it (202) instead of refusing.
const ready = (attachments ?? []).filter((a) => a.status === 'ready');
@@ -550,27 +556,36 @@ export const ChatPage: React.FC = () => {
// stream — we don't hold the response open. ``apiFetch`` attaches the
// CSRF token that ``protect_mutating_ui_requests`` requires under
// remote-access mode (raw ``fetch`` would 403).
- const requestBody = {
- text,
- ...(ready.length > 0
+ const refs = references ?? [];
+ const content =
+ ready.length > 0 || refs.length > 0
? {
- content: {
- text,
- attachments: ready.map((a) => ({
- token: a.token,
- name: a.name,
- mime: a.mime,
- size: a.size,
- kind: a.kind,
- url: a.url,
- // Persist image pixel size when known so the box is reserved on
- // reload (undefined keys drop out of the JSON).
- width: a.width,
- height: a.height,
- })),
- },
+ text,
+ ...(ready.length > 0
+ ? {
+ attachments: ready.map((a) => ({
+ token: a.token,
+ name: a.name,
+ mime: a.mime,
+ size: a.size,
+ kind: a.kind,
+ url: a.url,
+ // Persist image pixel size when known so the box is reserved on
+ // reload (undefined keys drop out of the JSON).
+ width: a.width,
+ height: a.height,
+ })),
+ }
+ : {}),
+ // @-agent / #-session mention sidecar (see lib/mentions): the text
+ // keeps the `@<name>` / `#<id>` markers; this carries resolved ids +
+ // session titles for chip rendering and the backend reference block.
+ ...(refs.length > 0 ? { references: refs } : {}),
}
- : {}),
+ : undefined;
+ const requestBody = {
+ text,
+ ...(content ? { content } : {}),
// Quick-reply click: tag the user row with the agent message it answers
// so the locked/highlighted state can be derived on reload.
...(metadata ? { metadata } : {}),
@@ -622,6 +637,41 @@ export const ChatPage: React.FC = () => {
[sessionId, appendMessage, refreshQueue, markWorking],
);
+ // @ mention source: all enabled Agents, filtered client-side (the set is small
+ // and already loaded for this session via bootstrap).
+ const searchAgents = useCallback(
+ async (query: string) => {
+ const q = query.trim().toLowerCase();
+ return agents
+ .filter((a) => a.enabled)
+ // Names with the marker terminator (`>`) or a newline can't round-trip
+ // through @<name>, so they aren't mentionable.
+ .filter((a) => !/[>\n]/.test(a.name))
+ .filter((a) => !q || a.name.toLowerCase().includes(q))
+ .map((a) => ({ name: a.name, agent_id: a.id, backend: a.backend, description: a.description }));
+ },
+ [agents],
+ );
+
+ // # reference source: recent active sessions machine-wide (excluding the current
+ // one); ≥2 chars switches to a global title search via the server-side ``q``.
+ const searchSessions = useCallback(
+ async (query: string) => {
+ const q = query.trim();
+ const broad = q.length >= 2;
+ const res = await api.listSessions(
+ broad
+ ? { q, status: 'active', limit: 24, cache: false }
+ : { status: 'active', limit: 12, cache: true },
+ );
+ return res.sessions
+ .filter((s) => s.id !== sessionId)
+ .slice(0, broad ? 20 : 8)
+ .map((s) => ({ session_id: s.id, title: s.title }));
+ },
+ [api, sessionId],
+ );
+
// A quick-reply click sends the chosen label as a normal user turn, tagged with
// the agent message it answers so the group can lock + highlight the choice on
// reload (the answered state is derived from this metadata).
@@ -885,12 +935,14 @@ export const ChatPage: React.FC = () => {
<Compose
key={sessionId}
composerRef={composerRef}
- onSend={sendMessage}
+ onSend={(text, attachments, references) => sendMessage(text, attachments, undefined, references)}
onStop={stopMessage}
busy={working}
sessionId={sessionId ?? ''}
initialDraft={initialDraft}
onDraftChange={onDraftChange}
+ onSearchAgents={searchAgents}
+ onSearchSessions={searchSessions}
/>
</div>
</FileViewerProvider>
@@ -944,15 +996,17 @@ const QueueStrip: React.FC<{
interface ComposeProps {
composerRef: React.Ref<ComposerHandle>;
- onSend: (text: string, attachments?: ComposerAttachment[]) => void;
+ onSend: (text: string, attachments?: ComposerAttachment[], references?: MentionReference[]) => void;
onStop: () => void;
busy: boolean;
sessionId: string;
initialDraft: string | null;
onDraftChange: (text: string) => void;
+ onSearchAgents: ComposerProps['onSearchAgents'];
+ onSearchSessions: ComposerProps['onSearchSessions'];
}
-const Compose: React.FC<ComposeProps> = ({ composerRef, onSend, onStop, busy, sessionId, initialDraft, onDraftChange }) => (
+const Compose: React.FC<ComposeProps> = ({ composerRef, onSend, onStop, busy, sessionId, initialDraft, onDraftChange, onSearchAgents, onSearchSessions }) => (
// shrink-0 pins the bar at the bottom of the fixed-height chat container; the
// gradient fades the transcript out behind it (no opaque band / hard border)
// so the input sits close to the bottom edge. The input row is the shared
@@ -969,6 +1023,8 @@ const Compose: React.FC<ComposeProps> = ({ composerRef, onSend, onStop, busy, se
sessionId={sessionId}
initialDraft={initialDraft}
onDraftChange={onDraftChange}
+ onSearchAgents={onSearchAgents}
+ onSearchSessions={onSearchSessions}
autoFocus
/>
</div>
@@ -1451,7 +1507,12 @@ const MessageRow = memo(function MessageRow({ message, session, messageFontSize,
) : (
// Keep the user's own newlines visible (soft-break → <br>); agent/system
// replies are authored markdown and must not get stray hard breaks.
- <Markdown content={message.text} softBreaks={isUser} className="vr-markdown--inherit-size" />
+ <Markdown
+ content={message.text}
+ softBreaks={isUser}
+ references={(message.content as { references?: MentionReference[] } | null)?.references}
+ className="vr-markdown--inherit-size"
+ />
)
) : messageAttachments.length === 0 ? (
<div className="text-[13px] text-muted">—</div>
diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsx
index ef9435bc8..ebd0ee7cc 100644
--- a/ui/src/components/workbench/Composer.tsx
+++ b/ui/src/components/workbench/Composer.tsx
@@ -8,6 +8,13 @@ import { avibeFetch, primeCloudToken } from '../../lib/avibeFetch';
import { isSoftKeyboardOpen, isTouchCapableDevice } from '../../lib/softKeyboard';
import { cn } from '../../lib/utils';
import { Button } from '../ui/button';
+import {
+ MentionEditor,
+ type AgentSearchResult,
+ type MentionEditorHandle,
+ type SessionSearchResult,
+} from './MentionEditor';
+import type { MentionReference } from '../../lib/mentions';
export type ComposerAttachment = {
localId: string;
@@ -85,6 +92,7 @@ export interface ComposerProps {
onSend: (
text: string,
attachments?: ComposerAttachment[],
+ references?: MentionReference[],
) => boolean | void | Promise<boolean | void>;
/** A turn is running — the send button becomes a Stop button. */
busy?: boolean;
@@ -107,6 +115,11 @@ export interface ComposerProps {
* never pops the on-screen keyboard). The chat composer remounts per session,
* so this also covers opening / switching sessions. */
autoFocus?: boolean;
+ /** When BOTH are provided, the input upgrades to the rich mention editor:
+ * `@` autocompletes enabled Agents, `#` autocompletes Sessions. Leaving them
+ * unset keeps the plain textarea (e.g. the Workbench home). */
+ onSearchAgents?: (query: string) => Promise<AgentSearchResult[]>;
+ onSearchSessions?: (query: string) => Promise<SessionSearchResult[]>;
}
export interface ComposerHandle {
@@ -131,6 +144,8 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
className,
sessionId,
autoFocus = false,
+ onSearchAgents,
+ onSearchSessions,
}, ref) {
const { t } = useTranslation();
const [value, setValue] = useState('');
@@ -157,11 +172,21 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
// home composer leaves them off.
const mediaEnabled = Boolean(sessionId);
+ // Mentions upgrade the plain textarea to a Lexical editor (chat composer only,
+ // gated on the caller wiring both search sources). The editor owns the rich
+ // content; ``value`` mirrors its serialized marker text for the send/draft path
+ // and ``referencesRef`` holds the resolved sidecar for the send payload.
+ const useMentions = Boolean(onSearchAgents && onSearchSessions);
+ const mentionRef = useRef<MentionEditorHandle | null>(null);
+ const referencesRef = useRef<MentionReference[]>([]);
+
useEffect(() => {
- if (draftAppliedRef.current || initialDraft == null) return;
+ // The mention editor seeds itself from ``initialText`` and drives ``value``
+ // via onChange, so the textarea-path seeding is skipped there.
+ if (useMentions || draftAppliedRef.current || initialDraft == null) return;
draftAppliedRef.current = true;
if (initialDraft) setValue((cur) => (cur ? cur : initialDraft));
- }, [initialDraft]);
+ }, [initialDraft, useMentions]);
// Keep a ref of the latest value so the async voice-fill can append without a
// stale closure.
@@ -337,8 +362,12 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
if (!unmountedRef.current && text) {
// Append the transcript into the box (never auto-send) via the draft
// path so it persists if the user switches away before sending.
- const next = valueRef.current ? `${valueRef.current} ${text}` : text;
- update(next);
+ if (useMentions) {
+ mentionRef.current?.append(text);
+ } else {
+ const next = valueRef.current ? `${valueRef.current} ${text}` : text;
+ update(next);
+ }
}
} finally {
if (!unmountedRef.current) setTranscribing(false);
@@ -398,19 +427,29 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
if (!canSubmit || pendingRef.current) return;
const submitted = trimmed;
const sent = readyAttachments;
+ const sentRefs = referencesRef.current;
pendingRef.current = true;
// Clear optimistically so the box can't be re-submitted and a slow send can't
// wipe text typed in the meantime.
setValue('');
onDraftChange?.('');
setAttachments([]);
+ referencesRef.current = [];
+ if (useMentions) mentionRef.current?.clear();
try {
// If the caller reports the send couldn't start (home no-project nudge),
// restore the prompt + attachments for retry — unless the user typed anew.
- const started = await onSend(submitted, sent);
+ const started = await onSend(submitted, sent, useMentions ? sentRefs : undefined);
if (started === false) {
setValue((cur) => (cur ? cur : submitted));
setAttachments((cur) => (cur.length ? cur : sent));
+ if (useMentions && !valueRef.current.trim()) {
+ // Only restore when the user hasn't started a new draft during the
+ // in-flight send (mirrors the textarea path's keep-new-typing guard).
+ // Chips re-resolve when re-picked; the content is never lost.
+ referencesRef.current = sentRefs;
+ mentionRef.current?.setText(submitted);
+ }
}
} finally {
pendingRef.current = false;
@@ -514,24 +553,43 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
)}
</div>
)}
- <textarea
- ref={textareaRef}
- value={value}
- onChange={(e) => update(e.target.value)}
- onKeyDown={(e) => {
- // Enter sends, Shift+Enter newline — EXCEPT while the on-screen
- // keyboard is open (mobile), where Enter inserts a newline and Send is
- // the button. Hardware keyboards (no soft keyboard) keep Enter-to-send.
- // ``isComposing`` guards against submitting mid-IME composition (CJK).
- if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing && !isSoftKeyboardOpen()) {
- e.preventDefault();
- submit();
- }
- }}
- rows={1}
- placeholder={busy ? t('chat.compose.placeholderBusy') : placeholder ?? t('chat.compose.placeholder')}
- className="max-h-40 min-h-9 flex-1 resize-none bg-transparent py-2 text-[13px] leading-5 text-foreground outline-none placeholder:text-muted"
- />
+ {useMentions ? (
+ <MentionEditor
+ ref={mentionRef}
+ className="flex-1"
+ placeholder={busy ? t('chat.compose.placeholderBusy') : placeholder ?? t('chat.compose.placeholder')}
+ disabled={disabled}
+ autoFocus={autoFocus}
+ initialText={initialDraft}
+ onSearchAgents={onSearchAgents!}
+ onSearchSessions={onSearchSessions!}
+ onChange={(text, references) => {
+ setValue(text);
+ referencesRef.current = references;
+ onDraftChange?.(text);
+ }}
+ onSubmit={submit}
+ />
+ ) : (
+ <textarea
+ ref={textareaRef}
+ value={value}
+ onChange={(e) => update(e.target.value)}
+ onKeyDown={(e) => {
+ // Enter sends, Shift+Enter newline — EXCEPT while the on-screen
+ // keyboard is open (mobile), where Enter inserts a newline and Send is
+ // the button. Hardware keyboards (no soft keyboard) keep Enter-to-send.
+ // ``isComposing`` guards against submitting mid-IME composition (CJK).
+ if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing && !isSoftKeyboardOpen()) {
+ e.preventDefault();
+ submit();
+ }
+ }}
+ rows={1}
+ placeholder={busy ? t('chat.compose.placeholderBusy') : placeholder ?? t('chat.compose.placeholder')}
+ className="max-h-40 min-h-9 flex-1 resize-none bg-transparent py-2 text-[13px] leading-5 text-foreground outline-none placeholder:text-muted"
+ />
+ )}
{/* While recording, the left mic button is the Stop control (tap to
finish + transcribe); this trash button cancels/discards the clip —
same as ESC. Send stays greyed until recording ends. */}
diff --git a/ui/src/components/workbench/MentionEditor.tsx b/ui/src/components/workbench/MentionEditor.tsx
new file mode 100644
index 000000000..bc56795b6
--- /dev/null
+++ b/ui/src/components/workbench/MentionEditor.tsx
@@ -0,0 +1,376 @@
+import {
+ forwardRef,
+ useCallback,
+ useEffect,
+ useImperativeHandle,
+ useRef,
+ type Ref,
+} from 'react';
+import { LexicalComposer } from '@lexical/react/LexicalComposer';
+import { PlainTextPlugin } from '@lexical/react/LexicalPlainTextPlugin';
+import { ContentEditable } from '@lexical/react/LexicalContentEditable';
+import { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary';
+import { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin';
+import { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin';
+import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
+import {
+ $createParagraphNode,
+ $getRoot,
+ $isElementNode,
+ $isLineBreakNode,
+ $isTextNode,
+ COMMAND_PRIORITY_HIGH,
+ KEY_ENTER_COMMAND,
+ type EditorState,
+ type LexicalNode,
+} from 'lexical';
+import {
+ BeautifulMentionsPlugin,
+ BeautifulMentionNode,
+ $isBeautifulMentionNode,
+ type BeautifulMentionsItem,
+ type BeautifulMentionsMenuProps,
+ type BeautifulMentionsMenuItemProps,
+} from 'lexical-beautiful-mentions';
+
+import { isSoftKeyboardOpen, isTouchCapableDevice } from '../../lib/softKeyboard';
+import { cn } from '../../lib/utils';
+import { dedupeReferences, type MentionReference } from '../../lib/mentions';
+
+export type AgentSearchResult = {
+ name: string;
+ agent_id?: string | null;
+ backend?: string | null;
+ description?: string | null;
+};
+export type SessionSearchResult = { session_id: string; title?: string | null };
+
+export interface MentionEditorHandle {
+ focus: () => void;
+ clear: () => void;
+ /** Append free text at the end (voice transcript) without disturbing chips. */
+ append: (text: string) => void;
+ /** Replace the whole editor with plain text (restore on a failed send). */
+ setText: (text: string) => void;
+}
+
+export interface MentionEditorProps {
+ placeholder?: string;
+ disabled?: boolean;
+ autoFocus?: boolean;
+ /** Seed once (saved draft). Markers in the seed restore as plain text in v1. */
+ initialText?: string | null;
+ className?: string;
+ onChange: (text: string, references: MentionReference[]) => void;
+ onSubmit: () => void;
+ onSearchAgents: (query: string) => Promise<AgentSearchResult[]>;
+ onSearchSessions: (query: string) => Promise<SessionSearchResult[]>;
+}
+
+// Per-trigger chip classes — styled in index.css to read like a Badge
+// (success/mint for agents, info/cyan for sessions).
+// Chip styling for the mention nodes inside the editor — Tailwind utilities that
+// mirror Badge's success (agent) / info (session) variants.
+const MENTION_THEME = {
+ '@': 'rounded-full border border-mint/40 bg-mint-soft px-1.5 py-px font-medium text-mint',
+ '@Focused': 'ring-1 ring-mint/60',
+ '#': 'rounded-full border border-cyan/40 bg-cyan-soft px-1.5 py-px font-medium text-cyan',
+ '#Focused': 'ring-1 ring-cyan/60',
+};
+
+// Walk a Lexical node into our marker text, collecting references as it goes.
+function nodeToMarkerText(node: LexicalNode, refs: MentionReference[]): string {
+ if ($isBeautifulMentionNode(node)) {
+ const trigger = node.getTrigger();
+ const value = node.getValue();
+ const data = (node.getData() ?? {}) as Record<string, string | number | boolean | null>;
+ if (trigger === '@') {
+ // The marker terminates at the first `>`; a name containing `>` (or a
+ // newline) would serialize to an ambiguous `@<a>b>`. Such names can't be
+ // round-tripped, so fall back to plain text rather than a broken marker.
+ // (searchAgents also filters these out — this is defense in depth.)
+ if (/[>\n]/.test(value)) return `@${value}`;
+ refs.push({
+ kind: 'agent',
+ name: value,
+ agent_id: data.agentId != null ? String(data.agentId) : undefined,
+ backend: data.backend != null ? String(data.backend) : undefined,
+ });
+ return `@<${value}>`;
+ }
+ if (trigger === '#') {
+ const sessionId = data.sessionId != null ? String(data.sessionId) : value;
+ refs.push({ kind: 'session', session_id: sessionId, title: value });
+ return `#<${sessionId}>`;
+ }
+ return `${trigger}${value}`;
+ }
+ if ($isLineBreakNode(node)) return '\n';
+ if ($isTextNode(node)) return node.getTextContent();
+ if ($isElementNode(node)) {
+ return node
+ .getChildren()
+ .map((child) => nodeToMarkerText(child, refs))
+ .join('');
+ }
+ return '';
+}
+
+function serializeEditorState(state: EditorState): { text: string; references: MentionReference[] } {
+ return state.read(() => {
+ const refs: MentionReference[] = [];
+ const blocks = $getRoot()
+ .getChildren()
+ .map((block) => nodeToMarkerText(block, refs));
+ return { text: blocks.join('\n'), references: dedupeReferences(refs) };
+ });
+}
+
+// Enter submits — except Shift+Enter (newline), mid-IME composition (CJK), while
+// the on-screen keyboard is open (mobile: Enter = newline, send via button), or
+// while the mention menu is open (Enter picks the highlighted suggestion).
+function EnterSubmitPlugin({
+ onSubmit,
+ menuOpenRef,
+}: {
+ onSubmit: () => void;
+ menuOpenRef: React.MutableRefObject<boolean>;
+}) {
+ const [editor] = useLexicalComposerContext();
+ useEffect(
+ () =>
+ editor.registerCommand(
+ KEY_ENTER_COMMAND,
+ (event: KeyboardEvent | null) => {
+ if (!event || event.shiftKey) return false;
+ if (event.isComposing || event.keyCode === 229) return false;
+ if (menuOpenRef.current || isSoftKeyboardOpen()) return false;
+ event.preventDefault();
+ onSubmit();
+ return true;
+ },
+ COMMAND_PRIORITY_HIGH,
+ ),
+ [editor, onSubmit, menuOpenRef],
+ );
+ return null;
+}
+
+function EditablePlugin({ disabled }: { disabled: boolean }) {
+ const [editor] = useLexicalComposerContext();
+ useEffect(() => {
+ editor.setEditable(!disabled);
+ }, [editor, disabled]);
+ return null;
+}
+
+function BootstrapPlugin({
+ autoFocus,
+ initialText,
+ bridgeRef,
+}: {
+ autoFocus: boolean;
+ initialText?: string | null;
+ bridgeRef: Ref<MentionEditorHandle>;
+}) {
+ const [editor] = useLexicalComposerContext();
+ const seeded = useRef(false);
+
+ useImperativeHandle(
+ bridgeRef,
+ () => ({
+ focus: () => editor.focus(),
+ clear: () =>
+ editor.update(() => {
+ const root = $getRoot();
+ root.clear();
+ root.append($createParagraphNode());
+ }),
+ append: (text: string) =>
+ editor.update(() => {
+ const root = $getRoot();
+ const selection = root.selectEnd();
+ const prefix = root.getTextContent().length > 0 ? ' ' : '';
+ selection.insertText(`${prefix}${text}`);
+ }),
+ setText: (text: string) =>
+ editor.update(() => {
+ const root = $getRoot();
+ root.clear();
+ const paragraph = $createParagraphNode();
+ root.append(paragraph);
+ if (text) paragraph.selectStart().insertText(text);
+ }),
+ }),
+ [editor],
+ );
+
+ useEffect(() => {
+ if (seeded.current) return;
+ seeded.current = true;
+ const raw = initialText ?? '';
+ if (!raw.trim()) {
+ if (autoFocus && !isTouchCapableDevice()) editor.focus();
+ return;
+ }
+ editor.update(() => {
+ const root = $getRoot();
+ root.clear();
+ const paragraph = $createParagraphNode();
+ root.append(paragraph);
+ // v1: a restored draft seeds as plain text (markers render raw until
+ // re-picked); the content is lossless for sending. Insert the raw draft so
+ // intentional leading/trailing whitespace survives the round-trip.
+ paragraph.selectStart().insertText(raw);
+ });
+ if (autoFocus && !isTouchCapableDevice()) editor.focus();
+ // Only on mount.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ return null;
+}
+
+const MentionMenu = forwardRef<HTMLUListElement, BeautifulMentionsMenuProps>(
+ ({ loading: _loading, children, ...props }, ref) => (
+ <ul
+ ref={ref}
+ className="z-50 m-0 max-h-64 min-w-[15rem] list-none overflow-y-auto overflow-x-hidden rounded-md border border-border bg-panel p-1 text-text shadow-md"
+ {...props}
+ >
+ {children}
+ </ul>
+ ),
+);
+MentionMenu.displayName = 'MentionMenu';
+
+const MentionMenuItem = forwardRef<HTMLLIElement, BeautifulMentionsMenuItemProps>(
+ ({ selected, item, itemValue: _itemValue, label: _label, ...props }, ref) => {
+ const data = (item.data ?? {}) as Record<string, string | number | boolean | null>;
+ // Agents show their backend as a secondary hint; sessions show only the title.
+ const secondary = item.trigger === '@' && data.backend != null ? String(data.backend) : '';
+ return (
+ <li
+ ref={ref}
+ className={cn(
+ 'flex cursor-pointer select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none',
+ selected ? 'bg-accent/10 text-accent' : 'text-text',
+ )}
+ {...props}
+ >
+ <span className="shrink-0 text-muted">{item.trigger}</span>
+ <span className="truncate">{item.value}</span>
+ {secondary ? <span className="ml-auto shrink-0 text-xs text-muted">{secondary}</span> : null}
+ </li>
+ );
+ },
+);
+MentionMenuItem.displayName = 'MentionMenuItem';
+
+// A Lexical-backed text input with `@` (agent) / `#` (session) inline-chip
+// mentions. Owns only the editor; the surrounding composer shell (send button,
+// attachment chips, voice) stays in Composer.
+export const MentionEditor = forwardRef<MentionEditorHandle, MentionEditorProps>(function MentionEditor(
+ {
+ placeholder,
+ disabled = false,
+ autoFocus = false,
+ initialText = null,
+ className,
+ onChange,
+ onSubmit,
+ onSearchAgents,
+ onSearchSessions,
+ },
+ ref,
+) {
+ const menuOpenRef = useRef(false);
+
+ const handleChange = useCallback(
+ (state: EditorState) => {
+ const { text, references } = serializeEditorState(state);
+ onChange(text, references);
+ },
+ [onChange],
+ );
+
+ const onSearch = useCallback(
+ async (trigger: string, queryString?: string | null): Promise<BeautifulMentionsItem[]> => {
+ const query = (queryString ?? '').trim();
+ if (trigger === '@') {
+ const agents = await onSearchAgents(query);
+ return agents.map((a) => ({
+ value: a.name,
+ agentId: a.agent_id ?? null,
+ backend: a.backend ?? null,
+ }));
+ }
+ if (trigger === '#') {
+ const sessions = await onSearchSessions(query);
+ return sessions.map((s) => ({
+ value: s.title && s.title.trim() ? s.title : s.session_id,
+ sessionId: s.session_id,
+ }));
+ }
+ return [];
+ },
+ [onSearchAgents, onSearchSessions],
+ );
+
+ const initialConfig = useRef({
+ namespace: 'avibe-mention-composer',
+ theme: { beautifulMentions: MENTION_THEME },
+ nodes: [BeautifulMentionNode],
+ editable: !disabled,
+ onError: (error: Error) => {
+ // Surface in dev; never throw out of the editor and wipe the box.
+ console.error('[MentionEditor]', error);
+ },
+ }).current;
+
+ return (
+ <div className={cn('relative', className)}>
+ <LexicalComposer initialConfig={initialConfig}>
+ <PlainTextPlugin
+ contentEditable={
+ <ContentEditable
+ className="max-h-40 min-h-9 w-full overflow-y-auto whitespace-pre-wrap break-words bg-transparent py-2 text-[13px] leading-5 text-foreground outline-none"
+ aria-label={placeholder}
+ spellCheck
+ />
+ }
+ placeholder={
+ <div className="pointer-events-none absolute left-0 top-2 select-none text-[13px] leading-5 text-muted">
+ {placeholder}
+ </div>
+ }
+ ErrorBoundary={LexicalErrorBoundary}
+ />
+ <HistoryPlugin />
+ <OnChangePlugin onChange={handleChange} ignoreSelectionChange />
+ <BeautifulMentionsPlugin
+ triggers={['@', '#']}
+ onSearch={onSearch}
+ searchDelay={150}
+ menuItemLimit={8}
+ // Only Agents/Sessions returned by onSearch may become chips — no
+ // user-created (unresolved) mentions (the picker-selected-only contract).
+ creatable={false}
+ insertOnBlur={false}
+ menuComponent={MentionMenu}
+ menuItemComponent={MentionMenuItem}
+ menuAnchorClassName="z-50"
+ onMenuOpen={() => {
+ menuOpenRef.current = true;
+ }}
+ onMenuClose={() => {
+ menuOpenRef.current = false;
+ }}
+ />
+ <EnterSubmitPlugin onSubmit={onSubmit} menuOpenRef={menuOpenRef} />
+ <EditablePlugin disabled={disabled} />
+ <BootstrapPlugin autoFocus={autoFocus} initialText={initialText} bridgeRef={ref} />
+ </LexicalComposer>
+ </div>
+ );
+});
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 8bf27ecd8..dcef75596 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -172,7 +172,7 @@ export type ApiContextType = {
saveGlobalPrompts: (
payload: { content: string; backends: string[] },
) => Promise<{ ok: boolean; backends: GlobalPromptFile[] }>;
- listSessions: (params?: { projectId?: string; status?: 'active' | 'archived' | 'all'; limit?: number; beforeId?: string; cache?: boolean }) => Promise<{ sessions: WorkbenchSession[]; next_before_id: string | null }>;
+ listSessions: (params?: { projectId?: string; status?: 'active' | 'archived' | 'all'; limit?: number; beforeId?: string; q?: string; cache?: boolean }) => Promise<{ sessions: WorkbenchSession[]; next_before_id: string | null }>;
createSession: (payload: WorkbenchSessionCreate) => Promise<WorkbenchSession>;
getSession: (sessionId: string) => Promise<WorkbenchSession>;
getSessionBootstrap: (sessionId: string) => Promise<WorkbenchSessionBootstrap>;
@@ -1658,6 +1658,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
if (params?.status) search.set('status', params.status);
if (params?.limit) search.set('limit', String(params.limit));
if (params?.beforeId) search.set('before_id', params.beforeId);
+ if (params?.q) search.set('q', params.q);
const qs = search.toString();
const path = qs ? `/api/sessions?${qs}` : '/api/sessions';
return params?.cache === false ? getJson(path) : getCachedJson(path);
diff --git a/ui/src/lib/mentions.ts b/ui/src/lib/mentions.ts
new file mode 100644
index 000000000..9cceeef5f
--- /dev/null
+++ b/ui/src/lib/mentions.ts
@@ -0,0 +1,118 @@
+// Shared contract for @-agent / #-session mentions in the chat composer.
+//
+// Marker convention (the agent-facing, transport-stable form): `@<agent-name>`
+// and `#<session-id>` live inline in the message text. A structured sidecar in
+// `message.content.references` carries the resolved data (ids, session titles)
+// for faithful chip rendering and backend context — see docs/plans.
+//
+// Humans never read the raw markers (the bubble renders chips), so the format is
+// optimized for LLM legibility + robust parsing. The `<…>` form is excised from
+// the text BEFORE react-markdown sees it (we rewrite markers to mention links),
+// so it never collides with markdown's `<tag>` HTML handling.
+
+export type AgentReference = {
+ kind: 'agent';
+ /** Display name — the `vibe agent run --agent <name>` handle and the chip label. */
+ name: string;
+ agent_id?: string;
+ backend?: string;
+};
+
+export type SessionReference = {
+ kind: 'session';
+ /** Stable `vibe agent run --session-id <id>` handle; carried in the marker. */
+ session_id: string;
+ /** Snapshot of the title at send time — the chip label. */
+ title?: string | null;
+};
+
+export type MentionReference = AgentReference | SessionReference;
+
+export const MENTION_TRIGGERS = ['@', '#'] as const;
+export type MentionTrigger = (typeof MENTION_TRIGGERS)[number];
+
+// Matches `@<…>` / `#<…>`. Inner text excludes `>` and newlines: agent names with
+// `>` are disallowed (enforced at insert time) and session ids are token-safe.
+export const MENTION_MARKER_RE = /([@#])<([^>\n]+)>/g;
+
+/** The custom link scheme markers are rewritten to before markdown rendering. */
+export const MENTION_LINK_SCHEME = 'avibe-mention';
+
+/** The inline text marker for a reference. */
+export function referenceToMarker(ref: MentionReference): string {
+ return ref.kind === 'agent' ? `@<${ref.name}>` : `#<${ref.session_id}>`;
+}
+
+/** Dedupe references by (kind, id) so a marker repeated in the text yields one entry. */
+export function dedupeReferences(refs: MentionReference[]): MentionReference[] {
+ const seen = new Set<string>();
+ const out: MentionReference[] = [];
+ for (const ref of refs) {
+ const key = ref.kind === 'agent' ? `agent:${ref.name}` : `session:${ref.session_id}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push(ref);
+ }
+ return out;
+}
+
+function escapeMarkdownLabel(value: string): string {
+ return value.replace(/[\\\[\]]/g, (m) => `\\${m}`).replace(/\s*\n\s*/g, ' ');
+}
+
+/**
+ * Rewrite `@<…>` / `#<…>` markers in `text` into markdown links carrying the
+ * `avibe-mention:` scheme, so the shared `Markdown` renderer can show them as
+ * chips via its `a` component map. Session labels use the title from
+ * `references` when available, else the raw id.
+ */
+// Inline code spans and fenced code blocks — markers inside these must render
+// literally (e.g. `` `@<T>` ``), so linkify skips them.
+const CODE_SEGMENT_RE = /(```[\s\S]*?```|`[^`]*`)/g;
+
+export function linkifyMentions(text: string, references?: MentionReference[]): string {
+ const sessionTitles = new Map<string, string>();
+ for (const ref of references ?? []) {
+ if (ref.kind === 'session' && ref.title) sessionTitles.set(ref.session_id, ref.title);
+ }
+ const rewrite = (segment: string): string =>
+ segment.replace(MENTION_MARKER_RE, (_full, trigger: string, inner: string) => {
+ if (trigger === '@') {
+ const label = escapeMarkdownLabel(`@${inner}`);
+ return `[${label}](${MENTION_LINK_SCHEME}:agent:${encodeURIComponent(inner)})`;
+ }
+ const label = escapeMarkdownLabel(`#${sessionTitles.get(inner) || inner}`);
+ return `[${label}](${MENTION_LINK_SCHEME}:session:${encodeURIComponent(inner)})`;
+ });
+ // Split out code spans/blocks (the odd capture-group chunks) and rewrite markers
+ // only in the surrounding prose, so marker-shaped text inside code stays literal.
+ return text
+ .split(CODE_SEGMENT_RE)
+ .map((chunk) => (chunk.startsWith('`') ? chunk : rewrite(chunk)))
+ .join('');
+}
+
+/** Parse an `avibe-mention:<kind>:<value>` href back into its parts. */
+export function parseMentionHref(href: string): { kind: MentionTrigger; value: string } | null {
+ const prefix = `${MENTION_LINK_SCHEME}:`;
+ if (!href.startsWith(prefix)) return null;
+ const rest = href.slice(prefix.length);
+ const sep = rest.indexOf(':');
+ if (sep < 0) return null;
+ const kindStr = rest.slice(0, sep);
+ let value: string;
+ try {
+ value = decodeURIComponent(rest.slice(sep + 1));
+ } catch {
+ value = rest.slice(sep + 1);
+ }
+ if (kindStr === 'agent') return { kind: '@', value };
+ if (kindStr === 'session') return { kind: '#', value };
+ return null;
+}
+
+/** True when the text contains at least one mention marker. */
+export function hasMentionMarkers(text: string): boolean {
+ MENTION_MARKER_RE.lastIndex = 0;
+ return MENTION_MARKER_RE.test(text);
+}
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 7f666ebff..cefe4e7a6 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3513,6 +3513,8 @@ def sessions_list():
except (TypeError, ValueError):
limit = 50
before_id = request.args.get("before_id") or None
+ # ``q`` powers the chat composer ``#``-mention global title search.
+ title_query = request.args.get("q") or None
engine = _projects_engine()
with engine.connect() as conn:
@@ -3522,6 +3524,7 @@ def sessions_list():
status=status,
limit=limit,
before_id=before_id,
+ title_query=title_query,
)
return jsonify(result)