The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): offer Bot Mode agent handles in the composer @ autocomplete
Teknium1a74e7fb43f8
diff --git a/apps/desktop/src/app/chat/composer/contrib.ts b/apps/desktop/src/app/chat/composer/contrib.tsindex 94d19457a58..ab4f205bb2f 100644--- a/apps/desktop/src/app/chat/composer/contrib.ts+++ b/apps/desktop/src/app/chat/composer/contrib.ts@@ -36,7 +36,8 @@ export const COMPOSER_AREAS = {actions: 'composer.actions',middleware: 'composer.middleware',attachments: 'composer.attachments',- microActions: 'composer.microActions'+ microActions: 'composer.microActions',+ atCompletions: 'composer.atCompletions'} as constexport interface ComposerDraft {@@ -50,6 +51,27 @@ export interface ComposerMiddleware {handler: (draft: ComposerDraft) => ComposerDraft | null | Promise<ComposerDraft | null>}+/** One row a `composer.atCompletions` source offers for the current query. */+export interface ComposerAtCompletionItem {+ /** Text inserted into the draft when picked (e.g. `@researcher`). */+ insert: string+ /** Row label; defaults to `insert`. */+ display?: string+ /** Secondary line (e.g. "Bot · Homelab"). */+ meta?: string+ /** Icon slug understood by the completion popover; defaults to 'simple'. */+ icon?: string+}++/** Payload of a `composer.atCompletions` data contribution — an extra source+ * merged into the composer's `@` popover ABOVE the path/reference results.+ * `query` is the text typed after `@` (no leading `@`). Sources must be+ * fast and synchronous-ish (called per keystroke after the debounce); slow+ * lookups belong behind the source's own cache. */+export interface ComposerAtCompletionSource {+ provide: (query: string) => ComposerAtCompletionItem[]+}+export interface ComposerAttachmentContext {insertText: (text: string) => void}diff --git a/apps/desktop/src/app/chat/composer/hooks/use-at-completions-contrib.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-at-completions-contrib.test.tsxnew file mode 100644index 00000000000..7333677ff6b--- /dev/null+++ b/apps/desktop/src/app/chat/composer/hooks/use-at-completions-contrib.test.tsx@@ -0,0 +1,109 @@+/**+ * `composer.atCompletions` contributions merge into the `@` popover ahead of+ * the gateway's path results (#88060 — Bot Mode agent handles). Covers: rows+ * appear, prefix filtering is delegated to the source, contributed rows lead,+ * and a throwing source is isolated instead of killing the popover.+ */+import { act, renderHook } from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'++import { COMPOSER_AREAS, type ComposerAtCompletionSource } from '@/app/chat/composer/contrib'+import { registry } from '@/contrib/registry'+import { queryClient } from '@/lib/query-client'++import { useAtCompletions } from './use-at-completions'++const disposers: Array<() => void> = []++function addSource(id: string, provide: ComposerAtCompletionSource['provide']) {+ disposers.push(+ registry.register({+ id,+ area: COMPOSER_AREAS.atCompletions,+ data: { provide } satisfies ComposerAtCompletionSource+ })+ )+}++function gatewayStub() {+ return {+ request: vi.fn(async () => ({+ items: [{ text: '@file:src/research-notes.md', display: 'research-notes.md', meta: 'file' }]+ }))+ }+}++/** Drive the adapter like the popover does: search, let the debounce and+ * fetch settle, then read the settled items from a second search call+ * (the adapter returns the currently-held rows synchronously). */+async function searchAndRead(+ result: { current: { adapter: { search?: (q: string) => readonly { label: string }[] } } },+ q: string+): Promise<string[]> {+ act(() => {+ result.current.adapter.search?.(q)+ })+ await act(async () => {+ await vi.advanceTimersByTimeAsync(300)+ })++ let rows: readonly { label: string }[] = []+ act(() => {+ rows = result.current.adapter.search?.(q) || []+ })++ return rows.map(r => r.label)+}++afterEach(() => {+ disposers.splice(0).forEach(d => d())+ queryClient.clear()+ vi.useRealTimers()+})++describe('contributed @ completion sources', () => {+ it('merges contributed rows ahead of gateway path results', async () => {+ vi.useFakeTimers()+ addSource('bots', q =>+ 'researcher'.startsWith(q) ? [{ insert: '@researcher', meta: 'Bot · Researcher' }] : []+ )++ const { result } = renderHook(() =>+ useAtCompletions({ gateway: gatewayStub() as never, sessionId: 's1', cwd: '/repo' })+ )++ const rows = await searchAndRead(result, 'rese')+ expect(rows[0]).toBe('@researcher')+ expect(rows.some(l => l.includes('research-notes.md'))).toBe(true)+ })++ it('drops rows when the query does not match the source filter', async () => {+ vi.useFakeTimers()+ addSource('bots', q =>+ 'researcher'.startsWith(q) ? [{ insert: '@researcher', meta: 'Bot' }] : []+ )++ const { result } = renderHook(() =>+ useAtCompletions({ gateway: gatewayStub() as never, sessionId: 's1', cwd: '/repo' })+ )++ const rows = await searchAndRead(result, 'zzz')+ expect(rows).not.toContain('@researcher')+ })++ it('isolates a throwing source instead of killing the popover', async () => {+ vi.useFakeTimers()+ addSource('broken', () => {+ throw new Error('boom')+ })+ addSource('bots', () => [{ insert: '@researcher' }])++ const { result } = renderHook(() =>+ useAtCompletions({ gateway: gatewayStub() as never, sessionId: 's1', cwd: '/repo' })+ )++ const rows = await searchAndRead(result, 'rese')+ expect(rows[0]).toBe('@researcher')+ expect(rows.length).toBeGreaterThan(1)+ })+})diff --git a/apps/desktop/src/app/chat/composer/hooks/use-at-completions.ts b/apps/desktop/src/app/chat/composer/hooks/use-at-completions.tsindex 1f8a12df336..33bc2f3c87f 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-at-completions.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-at-completions.ts@@ -2,10 +2,14 @@ import type { Unstable_TriggerAdapter, Unstable_TriggerItem } from '@assistant-uimport { useCallback } from 'react'import { refChipLabel } from '@/components/assistant-ui/directive-text'+import { useContributions } from '@/contrib/react/use-contributions'import type { HermesGateway } from '@/hermes'import { cachedPathCompletion, hasCachedPathCompletion } from '@/lib/slash-completion-cache'import { normalize } from '@/lib/text'+import type { ComposerAtCompletionSource } from '../contrib'+import { COMPOSER_AREAS } from '../contrib'+import type { CompletionEntry, CompletionPayload } from './use-live-completion-adapter'import { useLiveCompletionAdapter } from './use-live-completion-adapter'@@ -82,7 +86,9 @@ function classify(entry: CompletionEntry): {}}-/** Live `@` completions backed by the gateway's `complete.path` RPC. */+/** Live `@` completions backed by the gateway's `complete.path` RPC, with+ * contributed sources (composer.atCompletions — e.g. Bot Mode agent handles)+ * merged ahead of the path results. */export function useAtCompletions(options: {gateway: HermesGateway | nullsessionId: string | null@@ -91,6 +97,45 @@ export function useAtCompletions(options: {const { gateway, sessionId, cwd } = optionsconst enabled = Boolean(gateway)+ const contributed = useContributions(COMPOSER_AREAS.atCompletions)++ // Contributed rows for the query, mapped into the gateway entry shape so+ // one classify/toItem path renders every row. Provider errors are isolated:+ // a throwing source drops ITS rows, never the popover.+ const contributedEntries = useCallback(+ (query: string): CompletionEntry[] => {+ const out: CompletionEntry[] = []++ for (const contribution of contributed) {+ const source = contribution.data as ComposerAtCompletionSource | undefined++ if (!source || typeof source.provide !== 'function') {+ continue+ }++ try {+ for (const item of source.provide(query) || []) {+ if (!item || typeof item.insert !== 'string' || !item.insert) {+ continue+ }++ out.push({+ text: item.insert,+ display: item.display || item.insert,+ meta: item.meta || '',+ icon: item.icon || ''+ } as CompletionEntry)+ }+ } catch {+ /* a broken source must not take down @ completions */+ }+ }++ return out+ },+ [contributed]+ )+// Cache key: the completion depends on the query AND the directory it's// resolved against, so a cwd or session change can't serve another tree's// listing.@@ -99,9 +144,10 @@ export function useAtCompletions(options: {const fetcher = useCallback(async (query: string): Promise<CompletionPayload> => {const starters = starterEntries(query)+ const extras = contributedEntries(query)if (!gateway) {- return { items: starters, query }+ return { items: [...extras, ...starters], query }}const word = REF_STARTERS.has(query) ? `@${query}:` : `@${query}`@@ -126,13 +172,14 @@ export function useAtCompletions(options: {)const items = result.items ?? []+ const base = items.length > 0 ? items : starters- return { items: items.length > 0 ? items : starters, query }+ return { items: [...extras, ...base], query }} catch {- return { items: starters, query }+ return { items: [...extras, ...starters], query }}},- [cacheKey, gateway, sessionId, cwd]+ [cacheKey, contributedEntries, gateway, sessionId, cwd])const toItem = useCallback((entry: CompletionEntry, index: number): Unstable_TriggerItem => {diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.js b/apps/desktop/src/plugins/hermes-bots/plugin.jsindex 6a94eeade07..5ffc635fd7d 100644--- a/apps/desktop/src/plugins/hermes-bots/plugin.js+++ b/apps/desktop/src/plugins/hermes-bots/plugin.js@@ -6658,6 +6658,54 @@ export default {pluginCtx = ctxstartFaceClock()+ // @-mention autocomplete: typing "@rese…" in ANY composer offers the+ // roster's handles (issue #88060). Reads the roster straight from the+ // query cache — useRoster keeps it ≤5s stale and the popover must answer+ // synchronously per keystroke. Multi-source rosters contribute their+ // precomputed @name-device handles via botHandle. The active profile is+ // excluded (a bot doesn't @ itself); 'default' surfaces as @hermes.+ ctx.register({+ id: 'mention-completions',+ area: COMPOSER_AREAS.atCompletions,+ data: {+ provide: query => {+ const roster = queryClient.getQueryData(ROSTER_KEY)+ const profiles = Array.isArray(roster?.profiles) ? roster.profiles : []++ if (!profiles.length) {+ return []+ }++ const active = (host.state.profile.get() || 'default').trim() || 'default'+ const q = (query || '').toLowerCase()+ const items = []++ for (const profile of profiles) {+ if (!profile?.name || profile.name === active) {+ continue+ }++ const handle = botHandle(profile.name, profile)++ if (q && !handle.toLowerCase().startsWith(q)) {+ continue+ }++ const display = displayName(profile, $botMeta.get()[profile.name])+ const source = profile.connectionLabel ? ` · ${profile.connectionLabel}` : ''++ items.push({+ insert: `@${handle}`,+ display: `@${handle}`,+ meta: `Bot · ${display}${source}`+ })+ }++ return items.slice(0, 8)+ }+ }+ })+// Keyframes for the pet bob — injected because plugin classes aren't in// the app's precompiled CSS. Idempotent across hot reloads.if (!document.getElementById('hermes-bots-keyframes')) {diff --git a/apps/desktop/src/plugins/hermes-bots/tests/mention-completions.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/mention-completions.test.mjsnew file mode 100644index 00000000000..dd9c8c65172--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/tests/mention-completions.test.mjs@@ -0,0 +1,110 @@+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'+import test from 'node:test'+import vm from 'node:vm'++// The mention-completions source (#88060): typing @ offers roster handles.+// Extract the registered provide() by running plugin registration with a+// stubbed ctx/queryClient and exercising the captured contribution.++const source = readFileSync(new URL('../plugin.js', import.meta.url), 'utf8')++function loadProvide({ roster, active = 'default', meta = {} } = {}) {+ const registrations = []+ const atom = value => {+ let current = value++ return { get: () => current, set: next => (current = next), listen: () => () => undefined }+ }+ const jsx = (type, props = {}) => ({ type, props })+ const context = {+ atom,+ jsx,+ jsxs: jsx,+ useQuery: () => ({}),+ useValue: v => (v?.get ? v.get() : v),+ useState: v => [v, () => undefined],+ setTimeout,+ clearTimeout,+ performance,+ window: {+ setTimeout,+ clearTimeout,+ performance,+ requestAnimationFrame: () => 0,+ cancelAnimationFrame: () => undefined,+ addEventListener: () => undefined,+ removeEventListener: () => undefined+ },+ document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },+ queryClient: {+ getQueryData: () => roster,+ invalidateQueries: () => undefined,+ setQueryData: () => undefined+ },+ host: {+ state: { profile: { get: () => active, listen: () => () => undefined }, gateway: { get: () => null, listen: () => () => undefined } },+ request: async () => ({}),+ onEvent: () => () => undefined+ },+ COMPOSER_AREAS: { middleware: 'composer.middleware', atCompletions: 'composer.atCompletions' },+ sdk: new Proxy({}, { get: () => undefined })+ }+ const code = source+ .replace(/^import \* as sdk from '@hermes\/plugin-sdk'\r?\n/m, '')+ .replace(/^import\s+\{[\s\S]*?\}\s+from '@hermes\/plugin-sdk'\r?\n/m, '')+ .replace(/^import .* from 'react'\r?\n/m, '')+ .replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')+ .replace('export default {', 'globalThis.plugin = {')+ .concat('\nglobalThis.__botMeta = $botMeta;')+ vm.runInNewContext(code, context)+ context.__botMeta.set(meta)++ const ctx = {+ register: c => registrations.push(c),+ storage: { get: async () => undefined, set: async () => undefined }+ }++ try {+ context.plugin.register(ctx)+ } catch {+ /* registration walks UI surfaces the stub doesn't fully model — the+ contributions registered before any throw are what we assert on */+ }++ const contribution = registrations.find(c => c.area === 'composer.atCompletions')+ assert.ok(contribution, 'mention-completions contribution registered')++ return contribution.data.provide+}++const ROSTER = {+ profiles: [+ { name: 'default' },+ { name: 'researcher' },+ { name: 'writer', connectionLabel: 'Homelab', handle: 'writer-homelab' }+ ]+}++test('offers roster handles for a matching prefix, excluding the active profile', () => {+ const provide = loadProvide({ roster: ROSTER, active: 'researcher' })+ const all = provide('')+ const inserts = all.map(i => i.insert)++ assert.ok(inserts.includes('@hermes'), 'default surfaces as @hermes')+ assert.ok(inserts.includes('@writer-homelab'), 'multi-source handle used')+ assert.ok(!inserts.includes('@researcher'), 'active profile excluded')+})++test('prefix-filters against the handle', () => {+ const provide = loadProvide({ roster: ROSTER, active: 'default' })++ assert.deepStrictEqual([...provide('wri').map(i => i.insert)], ['@writer-homelab'])+ assert.strictEqual(provide('zzz').length, 0)+})++test('empty roster cache yields no rows (never throws)', () => {+ const provide = loadProvide({ roster: undefined })++ assert.strictEqual(provide('a').length, 0)+})diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.tsindex 032a58bd4d4..3be5a2c2d18 100644--- a/apps/desktop/src/sdk/index.ts+++ b/apps/desktop/src/sdk/index.ts@@ -425,7 +425,7 @@ export const host = {// Every contribution surface, plugin-reachable: register keybinds, palette// commands, routes, themes, panes, composer extensions, and bar items with// the same area ids + payload types core uses.-export { COMPOSER_AREAS, type ComposerAttachmentProvider, type ComposerMiddleware } from '@/app/chat/composer/contrib'+export { COMPOSER_AREAS, type ComposerAtCompletionItem, type ComposerAtCompletionSource, type ComposerAttachmentProvider, type ComposerMiddleware } from '@/app/chat/composer/contrib'// -- ui: the design language --------------------------------------------------