Skip to content

The agent that grows with you

feat(desktop): skill-match and connection-repair suggestion providers

Brooklyn Nicholsonc8cad1cc9efc
diff --git a/apps/desktop/src/app/chat/composer/focus.ts b/apps/desktop/src/app/chat/composer/focus.ts
index f1ea428c3c0..8cd961b7f96 100644
--- a/apps/desktop/src/app/chat/composer/focus.ts
+++ b/apps/desktop/src/app/chat/composer/focus.ts
@@ -19,7 +19,7 @@ import { RICH_INPUT_SLOT } from './rich-editor'
/** Composer routing key. The main chat is `'main'`, the edit composer
* `'edit'`; scoped composers (session tiles) use `'tile:<id>'`. */
export type ComposerTarget = 'edit' | 'main' | (string & {})
-export type ComposerInsertMode = 'block' | 'inline'
+export type ComposerInsertMode = 'block' | 'inline' | 'prefix'
export interface FocusDetail {
target: ComposerTarget
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts
index 4d5941c1a6c..ecfefb93b44 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts
@@ -1,6 +1,8 @@
// Register the built-in draft providers with the suggestion bus (side-effect
-// import — the bus itself is provider-agnostic).
+// import — the bus itself is provider-agnostic). The repair provider is
+// event-driven and registers through the gateway stream instead.
import '@/store/suggestion-providers/mcp'
+import '@/store/suggestion-providers/skill'
import { useAui, useAuiState, useComposerRuntime } from '@assistant-ui/react'
import { type RefObject, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
@@ -159,6 +161,16 @@ export function useComposerDraft({
return
}
+ // 'prefix' puts the value at the START of the draft — slash commands
+ // (the skill-suggestion pill) only route when they lead the message.
+ if (mode === 'prefix') {
+ const rest = draftRef.current.trimStart()
+
+ paintDraft(`${value} ${rest}`.trimEnd())
+
+ return
+ }
+
const base = mode === 'inline' ? draftRef.current.trimEnd() : draftRef.current
const sep = mode === 'inline' ? (base ? ' ' : '') : base && !base.endsWith('\n') ? '\n\n' : ''
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts
index 6d0e7f8cbf5..46b992a68d4 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts
@@ -67,6 +67,8 @@ import {
} from '@/store/session'
import { dropSessionState } from '@/store/session-states'
import { pruneDelegateFallbackSubagents, pruneFinishedSessionSubagents, upsertSubagent } from '@/store/subagents'
+import { reportMcpToolResult } from '@/store/suggestion-providers/repair'
+import { invalidateSkillSuggestionIndex } from '@/store/suggestion-providers/skill'
import { clearActiveSessionTodos } from '@/store/todos'
import { recordToolDiff } from '@/store/tool-diffs'
import { setSessionDraftingTool } from '@/store/tool-drafting'
@@ -885,9 +887,23 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
// The agent just created/deleted/renamed a skill, which adds or removes
// its `/name` command. Drop the composer's cached `/` list so the new
- // skill is offerable now rather than after the hour-long TTL.
+ // skill is offerable now rather than after the hour-long TTL — and the
+ // skill-suggestion provider's index with it.
if (payload?.name === 'skill_manage') {
invalidateSlashCompletions()
+ invalidateSkillSuggestionIndex()
+ }
+
+ // MCP tool outcomes feed the connection-repair suggestion provider:
+ // an auth/connection-shaped failure offers a reconnect pill; a later
+ // success against the same server withdraws it.
+ if (sessionId && typeof payload?.name === 'string' && payload.name.startsWith('mcp__')) {
+ reportMcpToolResult(
+ sessionId,
+ payload.name,
+ Boolean(payload.error),
+ [payload.error, payload.result].filter(part => typeof part === 'string').join(' ')
+ )
}
if (typeof payload?.inline_diff === 'string' && payload.inline_diff.trim()) {
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index 965200df601..713f75ab329 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -2142,6 +2142,21 @@ export const en: Translations = {
addedTip: 'Connected — its tools are ready in this chat',
connectFailed: server => `Could not connect ${server}`
},
+ skillSuggestions: {
+ label: skill => `Use skill: ${skill}`,
+ tip: skill => `You mentioned “${skill}” — click to lead with that skill`,
+ done: skill => `Added /${skill}`,
+ doneTip: 'The skill loads when you send'
+ },
+ repairSuggestions: {
+ label: server => `Reconnect ${server}`,
+ tip: server => `A ${server} call just failed with a connection error`,
+ working: server => `Reconnecting ${server}…`,
+ workingTip: 'Click to cancel',
+ done: server => `Reconnected ${server}`,
+ doneTip: 'Fresh credentials are live in this chat',
+ failed: server => `Could not reconnect ${server}`
+ },
snippets: {
codeReview: {
label: 'Code review',
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index 8752503ab9b..dbc82d1418c 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -1799,6 +1799,21 @@ export interface Translations {
addedTip: string
connectFailed: (server: string) => string
}
+ skillSuggestions: {
+ label: (skill: string) => string
+ tip: (skill: string) => string
+ done: (skill: string) => string
+ doneTip: string
+ }
+ repairSuggestions: {
+ label: (server: string) => string
+ tip: (server: string) => string
+ working: (server: string) => string
+ workingTip: string
+ done: (server: string) => string
+ doneTip: string
+ failed: (server: string) => string
+ }
}
statusStack: {
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index 347132690bd..687901141dc 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -2332,6 +2332,21 @@ export const zh: Translations = {
addedTip: '已连接 — 其工具已在此对话中可用',
connectFailed: server => `无法连接 ${server}`
},
+ skillSuggestions: {
+ label: skill => `使用技能: ${skill}`,
+ tip: skill => `你提到了“${skill}” — 点击以该技能开头`,
+ done: skill => `已添加 /${skill}`,
+ doneTip: '发送时将加载该技能'
+ },
+ repairSuggestions: {
+ label: server => `重新连接 ${server}`,
+ tip: server => `${server} 调用刚因连接错误失败`,
+ working: server => `正在重新连接 ${server}…`,
+ workingTip: '点击取消',
+ done: server => `已重新连接 ${server}`,
+ doneTip: '新凭据已在此对话中生效',
+ failed: server => `无法重新连接 ${server}`
+ },
snippets: {
codeReview: {
label: '代码审查',
diff --git a/apps/desktop/src/store/suggestion-providers/repair.test.ts b/apps/desktop/src/store/suggestion-providers/repair.test.ts
new file mode 100644
index 00000000000..e83f94dcf02
--- /dev/null
+++ b/apps/desktop/src/store/suggestion-providers/repair.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest'
+
+import { mcpServerFromToolName } from './repair'
+
+describe('mcpServerFromToolName', () => {
+ it('extracts the server from a namespaced MCP tool', () => {
+ expect(mcpServerFromToolName('mcp__figma__get_design_context')).toBe('figma')
+ expect(mcpServerFromToolName('mcp__browsermcp__browser_navigate')).toBe('browsermcp')
+ })
+
+ it('handles multi-underscore server names', () => {
+ expect(mcpServerFromToolName('mcp__comfy_cloud__generate')).toBe('comfy_cloud')
+ })
+
+ it('returns null for non-MCP tools', () => {
+ expect(mcpServerFromToolName('terminal')).toBeNull()
+ expect(mcpServerFromToolName('read_file')).toBeNull()
+ expect(mcpServerFromToolName('mcp_not_namespaced')).toBeNull()
+ })
+})
diff --git a/apps/desktop/src/store/suggestion-providers/repair.ts b/apps/desktop/src/store/suggestion-providers/repair.ts
new file mode 100644
index 00000000000..6a8d9478d98
--- /dev/null
+++ b/apps/desktop/src/store/suggestion-providers/repair.ts
@@ -0,0 +1,142 @@
+import { authMcpServer, cancelMcpOAuthFlow, getMcpOAuthFlow, listMcpServers } from '@/hermes'
+import { translateNow } from '@/i18n'
+import { completeMcpDesktopOAuth, McpOAuthCancelled } from '@/lib/mcp-dashboard-oauth'
+import { prettyName } from '@/lib/text'
+import { type ComposerSuggestion, offerSuggestions } from '@/store/composer-suggestions'
+import { $gateway } from '@/store/gateway'
+import { notifyError } from '@/store/notifications'
+
+/**
+ * Connection-repair event provider: an MCP tool call just failed with an
+ * auth/connection error, so offer to reconnect that server right where the
+ * user is about to type their next message. The highest-precision source on
+ * the bus — state-triggered by an actual failure in THIS session, never
+ * guessed from keywords.
+ *
+ * Fed by the gateway event stream (`reportMcpToolResult` from the
+ * tool.complete handler). The offer self-limits: a successful reconnect —
+ * or any later successful call to the same server — withdraws it.
+ */
+
+// Auth/connection shaped failure text from an MCP tool result. Deliberately
+// narrow: a tool erroring on its own semantics ("issue not found") must not
+// pill a reconnect. Matched against the error/result string.
+const REPAIR_RE = /\b(401|403|unauthorized|forbidden|token .*(expired|invalid)|oauth|authenticat\w+ (failed|required|expired)|connection (refused|closed|reset|failed)|server (unavailable|disconnected|not connected)|ECONNREFUSED)\b/i
+
+/** `mcp__figma__get_design_context` → `figma`; null for non-MCP tools. */
+export const mcpServerFromToolName = (toolName: string): string | null => {
+ const match = /^mcp__([^_]+(?:_[^_]+)*?)__/.exec(toolName)
+
+ return match ? match[1]! : null
+}
+
+const failed = new Map<string, Set<string>>()
+
+const keyFor = (sessionId: string | null | undefined): string => sessionId ?? ''
+
+async function reconnect(server: string, sessionId: string | null, cancelled: () => boolean): Promise<void> {
+ try {
+ await completeMcpDesktopOAuth({
+ serverName: server,
+ start: authMcpServer,
+ status: getMcpOAuthFlow,
+ cancelled,
+ cancel: cancelMcpOAuthFlow,
+ openExternal: url => window.hermesDesktop.openExternal(url)
+ })
+
+ // Fresh tokens reach the live session before the pill claims success.
+ await $gateway
+ .get()
+ ?.request('reload.mcp', { confirm: true, session_id: sessionId ?? undefined })
+ .catch(() => {})
+
+ clearMcpFailure(sessionId, server)
+ } catch (error) {
+ if (!(error instanceof McpOAuthCancelled)) {
+ notifyError(error, translateNow('composer.repairSuggestions.failed', prettyName(server)))
+ }
+
+ throw error
+ }
+}
+
+function toSuggestion(server: string, sessionId: string | null): ComposerSuggestion {
+ const copy = (key: string, ...args: unknown[]) => translateNow(`composer.repairSuggestions.${key}`, ...args)
+ const name = prettyName(server)
+
+ return {
+ brand: server,
+ doneLabel: copy('done', name),
+ doneTip: copy('doneTip'),
+ icon: 'plug',
+ id: server,
+ invoke: context => reconnect(server, sessionId, context.cancelled),
+ label: copy('label', name),
+ provider: 'repair',
+ tip: copy('tip', name),
+ workingLabel: copy('working', name),
+ workingTip: copy('workingTip')
+ }
+}
+
+function publish(sessionId: string | null | undefined): void {
+ const servers = [...(failed.get(keyFor(sessionId)) ?? [])]
+
+ offerSuggestions(
+ sessionId,
+ 'repair',
+ servers.map(server => toSuggestion(server, sessionId ?? null))
+ )
+}
+
+/**
+ * Called from the gateway tool.complete handler for every finished tool call.
+ * A failed MCP call with auth/connection-shaped output raises the offer for
+ * its server; a successful call to that server withdraws it (the connection
+ * evidently works again).
+ */
+export function reportMcpToolResult(
+ sessionId: string | null | undefined,
+ toolName: string,
+ isError: boolean,
+ resultText: string
+): void {
+ const server = mcpServerFromToolName(toolName)
+
+ if (!server) {
+ return
+ }
+
+ const key = keyFor(sessionId)
+ const sessionFailed = failed.get(key)
+
+ if (isError && REPAIR_RE.test(resultText)) {
+ // Only offer repair for servers that are actually configured — a failure
+ // from a just-removed server shouldn't pitch reconnecting it.
+ void listMcpServers()
+ .then(({ servers }) => {
+ if (!servers.some(entry => entry.name === server)) {
+ return
+ }
+
+ const next = failed.get(key) ?? new Set<string>()
+
+ next.add(server)
+ failed.set(key, next)
+ publish(sessionId)
+ })
+ .catch(() => {
+ // Can't verify the server exists — don't offer.
+ })
+ } else if (!isError && sessionFailed?.delete(server)) {
+ publish(sessionId)
+ }
+}
+
+/** Withdraw a server's repair offer (reconnected, or server removed). */
+export function clearMcpFailure(sessionId: string | null | undefined, server: string): void {
+ if (failed.get(keyFor(sessionId))?.delete(server)) {
+ publish(sessionId)
+ }
+}
diff --git a/apps/desktop/src/store/suggestion-providers/skill.ts b/apps/desktop/src/store/suggestion-providers/skill.ts
new file mode 100644
index 00000000000..f5a30278e28
--- /dev/null
+++ b/apps/desktop/src/store/suggestion-providers/skill.ts
@@ -0,0 +1,94 @@
+import { requestComposerFocus, requestComposerInsert } from '@/app/chat/composer/focus'
+import { getSkills } from '@/hermes'
+import { translateNow } from '@/i18n'
+import { type ComposerSuggestion, registerDraftProvider } from '@/store/composer-suggestions'
+
+/**
+ * Skill-match draft provider: the draft names a skill the user has, so offer
+ * to load it with the message. Highest value/annoyance ratio of the ranked
+ * sources — the skill index is local, the trigger is the user literally
+ * typing the skill's name, and the action is reversible (it edits the draft,
+ * nothing else).
+ *
+ * Invoke prefixes the draft with the skill's `/name` command; the pill then
+ * self-limits naturally: the next draft sample sees a leading slash and the
+ * provider stands down. Loading actually happens when the user sends —
+ * the pill never sends on their behalf.
+ */
+
+const SKILLS_TTL_MS = 5 * 60_000
+const MIN_NAME_LENGTH = 4
+
+interface SkillIndexEntry {
+ name: string
+ pattern: RegExp
+}
+
+let index: SkillIndexEntry[] | null = null
+let indexAt = 0
+
+/** Drop the cached skill index (skill_manage created/deleted a skill). */
+export function invalidateSkillSuggestionIndex(): void {
+ index = null
+ indexAt = 0
+}
+
+const escape = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+
+async function loadIndex(): Promise<SkillIndexEntry[]> {
+ if (index && Date.now() - indexAt < SKILLS_TTL_MS) {
+ return index
+ }
+
+ const skills = await getSkills()
+
+ index = skills
+ .filter(skill => skill.enabled && skill.name.length >= MIN_NAME_LENGTH)
+ .map(skill => ({
+ name: skill.name,
+ // Whole-word on unicode boundaries; hyphens/underscores inside a skill
+ // name ("pr-ready") are literal, so "pr-ready" matches but "already"
+ // never matches "read".
+ pattern: new RegExp(`(?<![\\p{L}\\p{N}])${escape(skill.name.toLowerCase())}(?![\\p{L}\\p{N}-])`, 'u')
+ }))
+ indexAt = Date.now()
+
+ return index
+}
+
+function toSuggestion(name: string): ComposerSuggestion {
+ const copy = (key: string, ...args: unknown[]) => translateNow(`composer.skillSuggestions.${key}`, ...args)
+
+ return {
+ doneLabel: copy('done', name),
+ doneTip: copy('doneTip'),
+ icon: 'zap',
+ id: name,
+ invoke: async () => {
+ // Prefix, don't replace: the user's words stay theirs. mode:'prefix'
+ // puts the command where slash routing expects it — line start.
+ requestComposerInsert(`/${name} `, { mode: 'prefix' })
+ requestComposerFocus()
+ },
+ label: copy('label', name),
+ provider: 'skill',
+ tip: copy('tip', name),
+ workingLabel: copy('label', name),
+ workingTip: copy('tip', name)
+ }
+}
+
+registerDraftProvider('skill', async ({ text }) => {
+ const trimmed = text.trimStart()
+
+ // Already a slash command (possibly ours from a previous click) — stand
+ // down instead of offering to double-prefix.
+ if (trimmed.startsWith('/')) {
+ return []
+ }
+
+ const haystack = text.toLowerCase()
+ const skills = await loadIndex()
+
+ return skills.filter(skill => skill.pattern.test(haystack)).map(skill => toSuggestion(skill.name))
+})