Skip to content

The agent that grows with you

fix(desktop): remove every composer suggestion pill

Teknium833cfc607a2e
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 3c4f46e6b2b..f88f2267913 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,11 +1,3 @@
-// Register the built-in draft providers with the suggestion bus (side-effect
-// import — the bus itself is provider-agnostic). The repair provider is
-// event-driven and registers through the gateway stream instead.
-import '@/store/suggestion-providers/cron'
-import '@/store/suggestion-providers/github'
-import '@/store/suggestion-providers/mcp'
-import '@/store/suggestion-providers/skill'
-
import { useAui, useAuiState, useComposerRuntime } from '@assistant-ui/react'
import { SLASH_COMMAND_RE } from '@hermes/shared'
import { type RefObject, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
@@ -35,7 +27,6 @@ import {
import { isBrowsingHistory } from '@/store/composer-input-history'
import { $composerPopout } from '@/store/composer-popout'
import { migrateQueuedPrompts } from '@/store/composer-queue'
-import { clearDraftSuggestions, sampleComposerDraft } from '@/store/composer-suggestions'
import {
cloneAttachments,
@@ -222,7 +213,7 @@ export function useComposerDraft({
}
// 'prefix' puts the value at the START of the draft — slash commands
- // (the skill-suggestion pill) only route when they lead the message.
+ // only route when they lead the message.
if (mode === 'prefix') {
const rest = draftRef.current.trimStart()
@@ -459,9 +450,6 @@ export function useComposerDraft({
const sync = () => {
const text = composerRuntime.getState().text
draftRef.current = text
- // Composer suggestion pills for THIS session's draft (debounced +
- // change-gated in the bus — this is just a timer reset).
- sampleComposerDraft(sessionIdRef.current ?? null, text)
const editor = editorRef.current
@@ -615,12 +603,6 @@ export function useComposerDraft({
} else if (!isBrowsingHistory(sessionId)) {
stashAt(activeQueueSessionKey, latestText)
}
-
- // Withdraw the outgoing session's draft suggestions (and any pending
- // sample timer). The incoming session re-earns its own from the draft
- // restore above — without this a leaving session's "Add GitHub" pill
- // lingers in the map and re-appears stale on the way back.
- clearDraftSuggestions(sessionIdRef.current)
}
}, [activeQueueSessionKey]) // eslint-disable-line react-hooks/exhaustive-deps
diff --git a/apps/desktop/src/app/chat/composer/index.tsx b/apps/desktop/src/app/chat/composer/index.tsx
index 4fa9c95c9a4..aee9bf96c50 100644
--- a/apps/desktop/src/app/chat/composer/index.tsx
+++ b/apps/desktop/src/app/chat/composer/index.tsx
@@ -105,7 +105,6 @@ import { useComposerScope, useComposerSurfaceId } from './scope'
import { ComposerStatusStack } from './status-stack'
import { CodingStatusRow } from './status-stack/coding-row'
import { StatusDrawerContent, StatusDrawerToggle } from './status-stack/drawer'
-import { SuggestionPills } from './suggestion-pills'
import { extractClipboardImageBlobs, openDirectiveScope } from './text-utils'
import { ComposerTriggerPopover } from './trigger-popover'
import type { ChatBarProps } from './types'
@@ -1300,7 +1299,6 @@ export function ChatBar({
and share one left edge with it. */}
<div className={cn(composerFloatingStrip, 'px-[5px] pb-1.5 empty:hidden')}>
<ActionBadges sessionId={statusSessionId} />
- <SuggestionPills sessionId={statusSessionId} />
<PreparedImageRecovery
occupied={hasText || attachments.length > 0 || busy || disabled}
onRestore={(text, restored, id) => {
diff --git a/apps/desktop/src/app/chat/composer/suggestion-pills.test.tsx b/apps/desktop/src/app/chat/composer/suggestion-pills.test.tsx
deleted file mode 100644
index e8e46b32ba8..00000000000
--- a/apps/desktop/src/app/chat/composer/suggestion-pills.test.tsx
+++ /dev/null
@@ -1,183 +0,0 @@
-import { act, render } from '@testing-library/react'
-import { afterEach, describe, expect, it, vi } from 'vitest'
-
-import { $composerSuggestionsBySession, type ComposerSuggestion, offerSuggestions } from '@/store/composer-suggestions'
-
-import { SuggestionPills } from './suggestion-pills'
-
-/**
- * The pill strip owns phase; the bus owns existence. These cover the seam
- * between them — what has to happen to a pill's phase and its in-flight work
- * when the bus withdraws it, which is the normal way a suggestion ends.
- */
-
-interface Flow {
- resolve: () => void
- reject: (error: unknown) => void
- /** Latest value of the invoke context's `cancelled()` poll. */
- cancelled: () => boolean
-}
-
-function pill(id: string, provider = 'mcp'): { suggestion: ComposerSuggestion; flow: Flow } {
- const flow: Partial<Flow> = {}
-
- const suggestion: ComposerSuggestion = {
- doneLabel: `Added ${id}`,
- doneTip: 'done',
- id,
- invoke: context =>
- new Promise<void>((resolve, reject) => {
- flow.resolve = resolve
- flow.reject = reject
- flow.cancelled = context.cancelled
- }),
- label: `Add ${id}`,
- provider,
- tip: 'because',
- workingLabel: `Connecting ${id}…`,
- workingTip: 'cancel'
- }
-
- return { flow: flow as Flow, suggestion }
-}
-
-const labels = (container: HTMLElement) => [...container.querySelectorAll('button')].map(button => button.textContent)
-
-const click = async (container: HTMLElement) => {
- await act(async () => {
- container.querySelector('button')!.click()
- })
-}
-
-afterEach(() => {
- $composerSuggestionsBySession.set({})
-})
-
-describe('SuggestionPills', () => {
- it('narrates idle → working → done through one invoke', async () => {
- const { flow, suggestion } = pill('github')
- const { container } = render(<SuggestionPills sessionId="s1" />)
-
- act(() => offerSuggestions('s1', 'mcp', [suggestion]))
- expect(labels(container)).toEqual(['Add github'])
-
- await click(container)
- expect(labels(container)).toEqual(['Connecting github…'])
-
- await act(async () => flow.resolve())
- expect(labels(container)).toEqual(['Added github'])
- })
-
- it('re-offering a withdrawn key starts from idle, not a stale done', async () => {
- const first = pill('github')
- const { container } = render(<SuggestionPills sessionId="s1" />)
-
- act(() => offerSuggestions('s1', 'mcp', [first.suggestion]))
- await click(container)
- await act(async () => first.flow.resolve())
- expect(labels(container)).toEqual(['Added github'])
-
- // The provider withdraws (draft lost the trigger) and offers again later.
- act(() => offerSuggestions('s1', 'mcp', []))
- act(() => offerSuggestions('s1', 'mcp', [pill('github').suggestion]))
-
- expect(labels(container)).toEqual(['Add github'])
- })
-
- it('a fresh offer is clickable again after an earlier one completed', async () => {
- const first = pill('github')
- const second = pill('github')
- const { container } = render(<SuggestionPills sessionId="s1" />)
-
- act(() => offerSuggestions('s1', 'mcp', [first.suggestion]))
- await click(container)
- await act(async () => first.flow.resolve())
-
- act(() => offerSuggestions('s1', 'mcp', []))
- act(() => offerSuggestions('s1', 'mcp', [second.suggestion]))
- await click(container)
-
- // A stale `done` swallows the click (only idle invokes) — this is the
- // user-visible half of the phase leak.
- expect(labels(container)).toEqual(['Connecting github…'])
- })
-
- it('cancels the in-flight action when the pill is withdrawn mid-flight', async () => {
- const { flow, suggestion } = pill('github')
- const { container } = render(<SuggestionPills sessionId="s1" />)
-
- act(() => offerSuggestions('s1', 'mcp', [suggestion]))
- await click(container)
- expect(flow.cancelled()).toBe(false)
-
- // The pill is the only cancel affordance; losing it must abort the work.
- act(() => offerSuggestions('s1', 'mcp', []))
-
- expect(labels(container)).toEqual([])
- expect(flow.cancelled()).toBe(true)
- })
-
- it('cancels in-flight work when the strip unmounts', async () => {
- const { flow, suggestion } = pill('github')
- const { container, unmount } = render(<SuggestionPills sessionId="s1" />)
-
- act(() => offerSuggestions('s1', 'mcp', [suggestion]))
- await click(container)
-
- unmount()
-
- expect(flow.cancelled()).toBe(true)
- })
-
- it('does not carry phase across a session switch on one mounted composer', async () => {
- const { flow, suggestion } = pill('github')
- const { container, rerender } = render(<SuggestionPills sessionId="s1" />)
-
- act(() => offerSuggestions('s1', 'mcp', [suggestion]))
- await click(container)
- await act(async () => flow.resolve())
- expect(labels(container)).toEqual(['Added github'])
-
- act(() => offerSuggestions('s2', 'mcp', [pill('github').suggestion]))
- rerender(<SuggestionPills sessionId="s2" />)
-
- expect(labels(container)).toEqual(['Add github'])
- })
-
- it('returns to idle when the provider rejects, so it can be retried', async () => {
- const { flow, suggestion } = pill('github')
- const { container } = render(<SuggestionPills sessionId="s1" />)
-
- act(() => offerSuggestions('s1', 'mcp', [suggestion]))
- await click(container)
-
- await act(async () => flow.reject(new Error('nope')))
-
- expect(labels(container)).toEqual(['Add github'])
- })
-
- it('a second click on a working pill requests cancel', async () => {
- const { flow, suggestion } = pill('github')
- const { container } = render(<SuggestionPills sessionId="s1" />)
-
- act(() => offerSuggestions('s1', 'mcp', [suggestion]))
- await click(container)
- await click(container)
-
- expect(flow.cancelled()).toBe(true)
- expect(labels(container)).toEqual(['Connecting github…'])
- })
-
- it('invokes each pill independently when two are offered', async () => {
- const a = pill('github')
- const b = pill('linear')
- const invoke = vi.spyOn(b.suggestion, 'invoke')
- const { container } = render(<SuggestionPills sessionId="s1" />)
-
- act(() => offerSuggestions('s1', 'mcp', [a.suggestion, b.suggestion]))
- await click(container)
-
- expect(labels(container)).toEqual(['Connecting github…', 'Add linear'])
- expect(invoke).not.toHaveBeenCalled()
- })
-})
diff --git a/apps/desktop/src/app/chat/composer/suggestion-pills.tsx b/apps/desktop/src/app/chat/composer/suggestion-pills.tsx
deleted file mode 100644
index e4562ae057e..00000000000
--- a/apps/desktop/src/app/chat/composer/suggestion-pills.tsx
+++ /dev/null
@@ -1,159 +0,0 @@
-import { useEffect, useState } from 'react'
-
-import { composerFloatingPill } from '@/components/chat/composer-dock'
-import { Codicon } from '@/components/ui/codicon'
-import { Tip } from '@/components/ui/tooltip'
-import { triggerHaptic } from '@/lib/haptics'
-import { brandFor, brandGlyphStyle } from '@/lib/mcp-brands'
-import { useSessionSlice } from '@/lib/use-session-slice'
-import { cn } from '@/lib/utils'
-import { $composerSuggestionsBySession, markSuggestionInvoked, suggestionKey } from '@/store/composer-suggestions'
-
-/**
- * The composer suggestion strip — generic pills fed by the suggestion bus
- * (`store/composer-suggestions.ts`; the MCP connect pills of PR #85036 are
- * provider one of N). Renders beside the micro-action badges in the floating
- * lane above the composer, same pill treatment. Session-scoped like the
- * badges: each composer shows only the suggestions its own session earned.
- *
- * Every pill is a one-click action with a narrated lifecycle: label →
- * workingLabel (click again to request cancel) → doneLabel. The provider's
- * `invoke` owns the work, cancellation, rollback, and error toasts; this
- * component owns only the phase presentation.
- *
- * No dismiss affordance ON PURPOSE. Suggestions are self-limiting — a
- * provider withdraws its offer when the trigger condition stops holding —
- * so a close button would mostly collect accidental permanent opt-outs.
- * The escape hatch is simply not clicking.
- *
- * Same pointer-events rule as the micro-action pills: NEVER
- * `pointer-events-none` — the pop-out drag region sits behind this strip.
- */
-
-type PillPhase = 'done' | 'idle' | 'working'
-
-/**
- * Phase belongs to the pill the user is looking at, so it lives and dies with
- * that pill — the bus owns whether a suggestion exists, this owns only how far
- * along it is. Remounting per session enforces the half of that the strip
- * can't see: one composer stays mounted across a session switch, and phase
- * keys are `provider:id`, so without this "Added GitHub" in one chat renders
- * the next chat's genuine offer as already-done and inert.
- */
-export function SuggestionPills({ sessionId }: { sessionId: null | string }) {
- return <SessionSuggestionPills key={sessionId ?? ''} sessionId={sessionId} />
-}
-
-function SessionSuggestionPills({ sessionId }: { sessionId: null | string }) {
- const suggestions = useSessionSlice($composerSuggestionsBySession, sessionId)
- const [phases, setPhases] = useState<Record<string, PillPhase>>({})
- // Cancel flags outlive renders but never trigger them (poll-boundary abort).
- const [cancels] = useState(() => new Map<string, boolean>())
-
- const setPhase = (key: string, phase: PillPhase) => setPhases(current => ({ ...current, [key]: phase }))
-
- // A pill that leaves the strip takes its phase with it, and cancels whatever
- // it had in flight. Both halves matter:
- //
- // - Phase, because keys repeat. A provider withdraws and re-offers the same
- // `provider:id` constantly (the draft loses and regains the trigger word,
- // a connect fails and the word is still typed), and a `done` left on file
- // paints the fresh offer as "Added GitHub" — a pill that says it already
- // worked and ignores clicks, since only `idle` invokes.
- // - Cancellation, because a withdrawn pill is the user's ONLY cancel
- // affordance. Clicking a working pill sets this flag; once the pill is
- // gone nothing can, so an OAuth flow the user walked away from would poll
- // forever, hold the server's in-progress slot against a retry, and either
- // land a server they never confirmed or roll one back with no UI to say
- // so. Withdrawal aborts it at the next poll boundary and lets the
- // provider roll back.
- //
- // `suggestions` is reference-stable while the offered set is unchanged (the
- // bus preserves identity on no-op writes), so this runs on real churn only.
- useEffect(() => {
- const live = new Set(suggestions.map(suggestionKey))
-
- for (const key of cancels.keys()) {
- if (!live.has(key)) {
- cancels.set(key, true)
- }
- }
-
- setPhases(current => {
- const kept = Object.entries(current).filter(([key]) => live.has(key))
-
- return kept.length === Object.keys(current).length ? current : Object.fromEntries(kept)
- })
- }, [cancels, suggestions])
-
- // Unmount withdraws everything at once (composer closing, session switch
- // remounting this subtree) — same rule, same reason.
- useEffect(
- () => () => {
- for (const key of cancels.keys()) {
- cancels.set(key, true)
- }
- },
- [cancels]
- )
-
- return suggestions.map(suggestion => {
- const key = suggestionKey(suggestion)
- const brand = suggestion.brand ? brandFor(suggestion.brand) : null
- const phase = phases[key] ?? 'idle'
-
- const label =
- phase === 'working' ? suggestion.workingLabel : phase === 'done' ? suggestion.doneLabel : suggestion.label
-
- const tip = phase === 'working' ? suggestion.workingTip : phase === 'done' ? suggestion.doneTip : suggestion.tip
-
- const invoke = async () => {
- cancels.set(key, false)
- setPhase(key, 'working')
- triggerHaptic('selection')
- // Acting on a pill clears its ignored-count in the bus's declined
- // ledger — its later withdrawal is success, not a strike.
- markSuggestionInvoked(sessionId, key)
-
- try {
- await suggestion.invoke({ cancelled: () => cancels.get(key) === true, sessionId })
- triggerHaptic('submit')
- setPhase(key, 'done')
- } catch {
- // Provider owns error surfacing (and swallows its own cancels);
- // the pill just returns to idle so it can be tried again.
- setPhase(key, 'idle')
- } finally {
- cancels.delete(key)
- }
- }
-
- return (
- <Tip key={key} label={tip}>
- <button
- className={cn(composerFloatingPill, 'max-w-56', phase === 'done' && 'cursor-default')}
- onClick={() => {
- if (phase === 'working') {
- // Second click requests cancel (a stuck OAuth tab, etc.).
- cancels.set(key, true)
- } else if (phase === 'idle') {
- void invoke()
- }
- }}
- type="button"
- >
- {phase === 'working' ? (
- <Codicon className="shrink-0 opacity-70" name="loading" size="0.75rem" spinning />
- ) : phase === 'done' ? (
- <Codicon className="shrink-0 text-emerald-400" name="check" size="0.75rem" />
- ) : brand ? (
- <brand.Icon aria-hidden className="size-3 shrink-0" style={brandGlyphStyle(brand)} />
- ) : (
- <Codicon className="shrink-0 opacity-70" name={suggestion.icon ?? 'lightbulb'} size="0.75rem" />
- )}
- <span className="truncate">{label}</span>
- </button>
- </Tip>
- )
- })
-}
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools.ts
index 346267af733..1498670c86a 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools.ts
@@ -11,8 +11,6 @@ import { recordPreviewArtifact, reofferPreviewArtifact } from '@/store/preview-s
import { $sessionStates, storedSessionIdForRuntimeId } from '@/store/session-states'
import { setupBeatResult } from '@/store/setup-beat'
import { isTerminalSubagentCompletion, pruneDelegateFallbackSubagents, upsertSubagent } from '@/store/subagents'
-import { reportMcpToolResult } from '@/store/suggestion-providers/repair'
-import { invalidateSkillSuggestionIndex } from '@/store/suggestion-providers/skill'
import { restoreSessionTodosFromSnapshot } from '@/store/todos'
import { setSessionDraftingTool } from '@/store/tool-drafting'
import { clearSessionToolProgress, clearToolProgress, setToolProgress } from '@/store/tool-progress'
@@ -201,23 +199,9 @@ export function handleToolEvent(ctx: GatewayEventContext): boolean {
// 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 — and the
- // skill-suggestion provider's index with it.
+ // skill is offerable now rather than after the hour-long TTL.
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(' ')
- )
}
// A file-mutating tool just finished — nudge the git-mirroring surfaces
diff --git a/apps/desktop/src/components/assistant-ui/mcp-setup-tool.tsx b/apps/desktop/src/components/assistant-ui/mcp-setup-tool.tsx
index c2ef598bf96..90d19d9852a 100644
--- a/apps/desktop/src/components/assistant-ui/mcp-setup-tool.tsx
+++ b/apps/desktop/src/components/assistant-ui/mcp-setup-tool.tsx
@@ -34,7 +34,6 @@ import {
toolConnectionRequest
} from '@/store/connection-request'
import { notifyError } from '@/store/notifications'
-import { invalidateMcpSuggestionIndex } from '@/store/suggestion-providers/mcp'
import { selectMessageRunning } from './tool/fallback-model'
import { parseMaybeObject } from './tool/fallback-model/format'
@@ -318,11 +317,8 @@ function McpSetupRow({ action, onReissue, reissueBlocked, reissuing, request, ta
const verb = rowVerb(target, action)
const fields = target.requiredEnv
- // The composer's MCP suggestion index caches the configured servers; this row just changed them.
useEffect(() => {
if (target.state === 'connected') {
- invalidateMcpSuggestionIndex()
-
if (!target.discoveryError && target.tools.length > 0) {
setSetupOpen(false)
}
diff --git a/apps/desktop/src/i18n/de.ts b/apps/desktop/src/i18n/de.ts
index 2ce7934cf9c..e0e68eb8e79 100644
--- a/apps/desktop/src/i18n/de.ts
+++ b/apps/desktop/src/i18n/de.ts
@@ -3929,43 +3929,6 @@ export const deOverrides = {
snippetsDesc: 'Wählen Sie einen Start-Prompt, um ihn in den Composer einzufügen.',
dropFiles: 'Dateien zum Anhängen ablegen',
dropSession: 'Ablegen, um diesen Chat zu verlinken',
- mcpSuggestions: {
- label: server => `${server} hinzufügen`,
- tip: keyword => `Vorgeschlagen, weil Sie „${keyword}“ erwähnt haben – zum Verbinden klicken`,
- connecting: server => `${server} wird verbunden…`,
- cancelTip: 'Klicken zum Abbrechen',
- added: server => `${server} hinzugefügt`,
- addedTip: 'Verbunden — seine Tools sind in diesem Chat bereit',
- connectFailed: server => `${server} konnte nicht verbunden werden`
- },
- skillSuggestions: {
- label: skill => `Fähigkeit verwenden: ${skill}`,
- tip: skill => `Sie haben „${skill}“ erwähnt – klicken, um mit diesem Skill zu beginnen`,
- done: skill => `/skill hinzugefügt: ${skill}`,
- doneTip: 'Die Fähigkeit wird beim Senden geladen'
- },
- githubSuggestions: {
- label: 'GitHub einrichten',
- tip: 'GitHub funktioniert hier über die gh-CLI-Skills – klicken, um Ihr Konto zu verbinden',
- done: '/github-auth hinzugefügt',
- doneTip: 'Senden Sie die Nachricht, und der Agent führt Sie durch die GitHub-Anmeldung'
- },
- repairSuggestions: {
- label: server => `${server} erneut verbinden`,
- tip: server => `Ein ${server}-Aufruf ist gerade mit einem Verbindungsfehler fehlgeschlagen`,
- working: server => `${server} wird erneut verbunden…`,
- workingTip: 'Klicken zum Abbrechen',
- done: server => `${server} erneut verbunden`,
- doneTip: 'Frische Anmeldedaten sind in diesem Chat aktiv',
- failed: server => `${server} konnte nicht erneut verbunden werden`
- },
- cronSuggestions: {
- label: 'Dies planen',
- tip: phrase => `„${phrase}“ klingt wiederkehrend — führen Sie es stattdessen nach Zeitplan aus`,
- prefix: 'Als geplanten Job einrichten:',
- done: 'Für Planung markiert',
- doneTip: 'Senden Sie die Nachricht, und der Agent erstellt den Job'
- },
snippets: {
codeReview: {
label: 'Code-Review',
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index a628617d194..74f7c4f039c 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -3497,43 +3497,6 @@ export const en: Translations = {
snippetsDesc: 'Pick a starter prompt to drop into the composer.',
dropFiles: 'Drop files to attach',
dropSession: 'Drop to link this chat',
- mcpSuggestions: {
- label: server => `Add ${server}`,
- tip: keyword => `Suggested because you mentioned “${keyword}” — click to connect`,
- connecting: server => `Connecting ${server}…`,
- cancelTip: 'Click to cancel',
- added: server => `Added ${server}`,
- 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'
- },
- githubSuggestions: {
- label: 'Set up GitHub',
- tip: 'GitHub works through the gh CLI skills here — click to connect your account',
- done: 'Added /github-auth',
- doneTip: 'Send the message and the agent walks you through GitHub sign-in'
- },
- 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}`
- },
- cronSuggestions: {
- label: 'Schedule this',
- tip: phrase => `“${phrase}” sounds recurring — run it on a schedule instead`,
- prefix: 'Set this up as a scheduled job:',
- done: 'Marked for scheduling',
- doneTip: 'Send it and the agent creates the job'
- },
snippets: {
codeReview: {
label: 'Code review',
diff --git a/apps/desktop/src/i18n/es.ts b/apps/desktop/src/i18n/es.ts
index 29732ff0a15..3a74b2c4c21 100644
--- a/apps/desktop/src/i18n/es.ts
+++ b/apps/desktop/src/i18n/es.ts
@@ -3922,43 +3922,6 @@ export const esOverrides = {
snippetsDesc: 'Elige un prompt inicial para insertarlo en el compositor.',
dropFiles: 'Suelta archivos para adjuntarlos',
dropSession: 'Suelta para enlazar este chat',
- mcpSuggestions: {
- label: server => `Añadir ${server}`,
- tip: keyword => `Sugerido porque mencionaste "${keyword}" — haz clic para conectar`,
- connecting: server => `Conectando ${server}…`,
- cancelTip: 'Haz clic para cancelar',
- added: server => `${server} añadido`,
- addedTip: 'Conectado — sus herramientas están listas en este chat',
- connectFailed: server => `No se pudo conectar ${server}`
- },
- skillSuggestions: {
- label: skill => `Usar habilidad: ${skill}`,
- tip: skill => `Mencionaste "${skill}" — haz clic para empezar con esa habilidad`,
- done: skill => `Añadido /${skill}`,
- doneTip: 'La habilidad se carga cuando envíes'
- },
- githubSuggestions: {
- label: 'Configurar GitHub',
- tip: 'GitHub funciona aquí mediante las skills de la CLI gh: haz clic para conectar tu cuenta',
- done: 'Se añadió /github-auth',
- doneTip: 'Envía el mensaje y el agente te guiará para iniciar sesión en GitHub'
- },
- repairSuggestions: {
- label: server => `Reconectar ${server}`,
- tip: server => `Una llamada a ${server} acaba de fallar con un error de conexión`,
- working: server => `Reconectando ${server}…`,
- workingTip: 'Haz clic para cancelar',
- done: server => `${server} reconectado`,
- doneTip: 'Las credenciales nuevas están activas en este chat',
- failed: server => `No se pudo reconectar ${server}`
- },
- cronSuggestions: {
- label: 'Programar esto',
- tip: phrase => `"${phrase}" suena recurrente — ejecútalo con un horario en su lugar`,
- prefix: 'Configúralo como tarea programada:',
- done: 'Marcado para programar',
- doneTip: 'Envíalo y el agente creará la tarea'
- },
snippets: {
codeReview: {
label: 'Revisión de código',
diff --git a/apps/desktop/src/i18n/fr.ts b/apps/desktop/src/i18n/fr.ts
index 7fdbd2f46cb..a97f38da6e5 100644
--- a/apps/desktop/src/i18n/fr.ts
+++ b/apps/desktop/src/i18n/fr.ts
@@ -3937,43 +3937,6 @@ export const frOverrides = {
snippetsDesc: 'Choisissez une invite de démarrage à insérer dans le compositeur.',
dropFiles: 'Déposez des fichiers pour les attacher',
dropSession: 'Déposez pour lier cette conversation',
- mcpSuggestions: {
- label: server => `Ajouter ${server}`,
- tip: keyword => `Suggéré car vous avez mentionné « ${keyword} » — cliquez pour vous connecter`,
- connecting: server => `Connexion à ${server}…`,
- cancelTip: 'Cliquez pour annuler',
- added: server => `${server} ajouté`,
- addedTip: 'Connecté — ses outils sont prêts dans cette conversation',
- connectFailed: server => `Impossible de se connecter à ${server}`
- },
- skillSuggestions: {
- label: skill => `Utiliser le skill : ${skill}`,
- tip: skill => `Vous avez mentionné « ${skill} » — cliquez pour commencer avec ce skill`,
- done: skill => `/${skill} ajouté`,
- doneTip: "Le skill se charge lors de l'envoi"
- },
- githubSuggestions: {
- label: 'Configurer GitHub',
- tip: 'GitHub fonctionne ici grâce aux skills de la CLI gh ; cliquez pour connecter votre compte',
- done: 'Ajout de /github-auth',
- doneTip: "Envoyez le message et l'agent vous guidera dans la connexion à GitHub"
- },
- repairSuggestions: {
- label: server => `Reconnecter ${server}`,
- tip: server => `Un appel à ${server} vient d'échouer à cause d'une erreur de connexion`,
- working: server => `Reconnexion à ${server}…`,
- workingTip: 'Cliquez pour annuler',
- done: server => `${server} reconnecté`,
- doneTip: 'Les nouveaux identifiants sont actifs dans cette conversation',
- failed: server => `Impossible de reconnecter ${server}`
- },
- cronSuggestions: {
- label: 'Planifier ceci',
- tip: phrase => `« ${phrase} » semble récurrent — exécutez-le plutôt selon une planification`,
- prefix: 'Configurer ceci comme tâche planifiée :',
- done: 'Marqué pour planification',
- doneTip: "Envoyez-le pour que l'agent crée la tâche"
- },
snippets: {
codeReview: {
label: 'Revue de code',
diff --git a/apps/desktop/src/i18n/overlay-gaps.json b/apps/desktop/src/i18n/overlay-gaps.json
index aedf3dbd388..66d30fa9a82 100644
--- a/apps/desktop/src/i18n/overlay-gaps.json
+++ b/apps/desktop/src/i18n/overlay-gaps.json
@@ -360,38 +360,11 @@
"common.expand": ["ar"],
"common.formatJson": ["ar"],
"common.tryHint": ["ar"],
- "composer.cronSuggestions.done": ["ar","ja","zh-hant"],
- "composer.cronSuggestions.doneTip": ["ar","ja","zh-hant"],
- "composer.cronSuggestions.label": ["ar","ja","zh-hant"],
- "composer.cronSuggestions.prefix": ["ar","ja","zh-hant"],
- "composer.cronSuggestions.tip": ["ar","ja","zh-hant"],
- "composer.githubSuggestions.done": ["ar","ja","zh-hant"],
- "composer.githubSuggestions.doneTip": ["ar","ja","zh-hant"],
- "composer.githubSuggestions.label": ["ar","ja","zh-hant"],
- "composer.githubSuggestions.tip": ["ar","ja","zh-hant"],
"composer.hiddenQueued": ["ar","ja","ru","zh","zh-hant"],
- "composer.mcpSuggestions.added": ["ar","ja","zh-hant"],
- "composer.mcpSuggestions.addedTip": ["ar","ja","zh-hant"],
- "composer.mcpSuggestions.cancelTip": ["ar","ja","zh-hant"],
- "composer.mcpSuggestions.connectFailed": ["ar","ja","zh-hant"],
- "composer.mcpSuggestions.connecting": ["ar","ja","zh-hant"],
- "composer.mcpSuggestions.label": ["ar","ja","zh-hant"],
- "composer.mcpSuggestions.tip": ["ar","ja","zh-hant"],
"composer.queueResume": ["ar"],
"composer.queueResumeTip": ["ar"],
"composer.queuedPaused": ["ar"],
"composer.queuedTerminalSelectionExpiredBody": ["de","es","fr","ru"],
- "composer.repairSuggestions.done": ["ar","ja","zh-hant"],
- "composer.repairSuggestions.doneTip": ["ar","ja","zh-hant"],
- "composer.repairSuggestions.failed": ["ar","ja","zh-hant"],
- "composer.repairSuggestions.label": ["ar","ja","zh-hant"],
- "composer.repairSuggestions.tip": ["ar","ja","zh-hant"],
- "composer.repairSuggestions.working": ["ar","ja","zh-hant"],
- "composer.repairSuggestions.workingTip": ["ar","ja","zh-hant"],
- "composer.skillSuggestions.done": ["ar","ja","zh-hant"],
- "composer.skillSuggestions.doneTip": ["ar","ja","zh-hant"],
- "composer.skillSuggestions.label": ["ar","ja","zh-hant"],
- "composer.skillSuggestions.tip": ["ar","ja","zh-hant"],
"composer.speakReplies": ["ar"],
"composer.steer": ["ja","zh-hant"],
"composer.stopSpeakingReplies": ["ar"],
diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.ts
index 6287a50b334..b55df0fa3ef 100644
--- a/apps/desktop/src/i18n/ru.ts
+++ b/apps/desktop/src/i18n/ru.ts
@@ -2738,43 +2738,6 @@ export const ruOverrides = {
snippetsDesc: 'Выберите стартовый промпт, чтобы вставить в композер.',
dropFiles: 'Перетащите файлы, чтобы прикрепить',
dropSession: 'Перетащите, чтобы связать этот чат',
- mcpSuggestions: {
- label: server => `Добавить ${server}`,
- tip: keyword => `Предложено, потому что вы упомянули «${keyword}» — нажмите, чтобы подключить`,
- connecting: server => `Подключаем ${server}…`,
- cancelTip: 'Нажмите, чтобы отменить',
- added: server => `Добавлен ${server}`,
- addedTip: 'Подключено — его инструменты готовы в этом чате',
- connectFailed: server => `Не удалось подключить ${server}`
- },
- skillSuggestions: {
- label: skill => `Использовать навык: ${skill}`,
- tip: skill => `Вы упомянули «${skill}» — нажмите, чтобы начать с этого навыка`,
- done: skill => `Добавлено /${skill}`,
- doneTip: 'Навык загрузится при отправке'
- },
- githubSuggestions: {
- label: 'Настроить GitHub',
- tip: 'GitHub работает через навыки gh CLI здесь — нажмите, чтобы подключить аккаунт',
- done: 'Добавлено /github-auth',
- doneTip: 'Отправьте сообщение, и агент проведёт вас через вход в GitHub'
- },
- repairSuggestions: {
- label: server => `Переподключить ${server}`,
- tip: server => `Недавний вызов ${server} завершился ошибкой соединения`,
- working: server => `Переподключаем ${server}…`,
- workingTip: 'Нажмите, чтобы отменить',
- done: server => `Переподключено ${server}`,
- doneTip: 'Свежие учётные данные активны в этом чате',
- failed: server => `Не удалось переподключить ${server}`
- },
- cronSuggestions: {
- label: 'Запланировать это',
- tip: phrase => `«${phrase}» звучит как повторяющееся — запланируйте выполнение по расписанию`,
- prefix: 'Настроить это как запланированную задачу:',
- done: 'Отмечено для планирования',
- doneTip: 'Отправьте, и агент создаст задачу'
- },
snippets: {
codeReview: {
label: 'Рецензия кода',
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index 26481d57f51..8759f17cfb7 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -2983,43 +2983,6 @@ catalog: CatalogTranslations
snippets: Record<string, { label: string; description: string; text: string }>
dropFiles: string
dropSession: string
- mcpSuggestions: {
- label: (server: string) => string
- tip: (keyword: string) => string
- connecting: (server: string) => string
- cancelTip: string
- added: (server: string) => string
- addedTip: string
- connectFailed: (server: string) => string
- }
- skillSuggestions: {
- label: (skill: string) => string
- tip: (skill: string) => string
- done: (skill: string) => string
- doneTip: string
- }
- githubSuggestions: {
- label: string
- tip: string
- done: 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
- }
- cronSuggestions: {
- label: string
- tip: (phrase: string) => string
- prefix: string
- done: string
- doneTip: string
- }
}
statusStack: {
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index a24b0587a39..b84bf226769 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -3388,43 +3388,6 @@ export const zhOverrides = {
snippetsDesc: '选择一个起始提示词放入输入框。',
dropFiles: '拖放文件以附加',
dropSession: '拖放以链接此对话',
- mcpSuggestions: {
- label: server => `添加 ${server}`,
- tip: keyword => `因为你提到了“${keyword}”而推荐 — 点击连接`,
- connecting: server => `正在连接 ${server}…`,
- cancelTip: '点击取消',
- added: server => `已添加 ${server}`,
- addedTip: '已连接 — 其工具已在此对话中可用',
- connectFailed: server => `无法连接 ${server}`
- },
- skillSuggestions: {
- label: skill => `使用技能: ${skill}`,
- tip: skill => `你提到了“${skill}” — 点击以该技能开头`,
- done: skill => `已添加 /${skill}`,
- doneTip: '发送时将加载该技能'
- },
- githubSuggestions: {
- label: '设置 GitHub',
- tip: '这里通过 gh CLI 技能使用 GitHub — 点击连接你的账号',
- done: '已添加 /github-auth',
- doneTip: '发送消息后,agent 将引导你完成 GitHub 登录'
- },
- repairSuggestions: {
- label: server => `重新连接 ${server}`,
- tip: server => `${server} 调用刚因连接错误失败`,
- working: server => `正在重新连接 ${server}…`,
- workingTip: '点击取消',
- done: server => `已重新连接 ${server}`,
- doneTip: '新凭据已在此对话中生效',
- failed: server => `无法重新连接 ${server}`
- },
- cronSuggestions: {
- label: '定时执行',
- tip: phrase => `“${phrase}”听起来是周期性任务 — 可以按计划运行`,
- prefix: '将此设置为定时任务:',
- done: '已标记为定时任务',
- doneTip: '发送后由智能体创建任务'
- },
snippets: {
codeReview: {
label: '代码审查',
diff --git a/apps/desktop/src/store/composer-suggestions.test.ts b/apps/desktop/src/store/composer-suggestions.test.ts
deleted file mode 100644
index 9b3a22c65de..00000000000
--- a/apps/desktop/src/store/composer-suggestions.test.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import { describe, expect, it } from 'vitest'
-
-import {
- $composerSuggestionsBySession,
- type ComposerSuggestion,
- markSuggestionInvoked,
- offerSuggestions,
- suggestionKey
-} from './composer-suggestions'
-
-const suggestion = (id: string, provider = 'test'): ComposerSuggestion => ({
- doneLabel: 'done',
- doneTip: 'done',
- id,
- invoke: async () => {},
- label: id,
- provider,
- tip: 'because',
- workingLabel: 'working',
- workingTip: 'working'
-})
-
-const pillsFor = (sessionId: string) => ($composerSuggestionsBySession.get()[sessionId] ?? []).map(s => s.id)
-
-describe('composer suggestion bus', () => {
- it('publishes event offerings per session and withdraws on empty offer', () => {
- offerSuggestions('s1', 'test', [suggestion('a')])
-
- expect(pillsFor('s1')).toEqual(['a'])
- expect(pillsFor('s2')).toEqual([])
-
- offerSuggestions('s1', 'test', [])
-
- expect(pillsFor('s1')).toEqual([])
- })
-
- it('dedupes by provider-namespaced key across providers', () => {
- offerSuggestions('s4', 'p1', [suggestion('same', 'p1')])
- offerSuggestions('s4', 'p2', [suggestion('same', 'p2')])
-
- // Different providers, same id — distinct keys, both allowed.
- expect(pillsFor('s4')).toEqual(['same', 'same'])
-
- offerSuggestions('s4', 'p1', [])
- offerSuggestions('s4', 'p2', [])
- })
-
- it('quiets a suggestion after it is repeatedly withdrawn uninvoked', () => {
- // Three offer/withdraw cycles = three strikes.
- for (let i = 0; i < 3; i += 1) {
- offerSuggestions('s5', 'test', [suggestion('naggy')])
- offerSuggestions('s5', 'test', [])
- }
-
- offerSuggestions('s5', 'test', [suggestion('naggy')])
-
- expect(pillsFor('s5')).toEqual([])
-
- offerSuggestions('s5', 'test', [])
- })
-
- it('an invoked suggestion never accrues strikes', () => {
- for (let i = 0; i < 3; i += 1) {
- offerSuggestions('s6', 'test', [suggestion('used')])
- markSuggestionInvoked('s6', suggestionKey(suggestion('used')))
- offerSuggestions('s6', 'test', [])
- }
-
- offerSuggestions('s6', 'test', [suggestion('used')])
-
- expect(pillsFor('s6')).toEqual(['used'])
-
- offerSuggestions('s6', 'test', [])
- })
-
- it('replaces an offer whose rendered copy changed under the same key', () => {
- offerSuggestions('s7', 'test', [{ ...suggestion('linear'), tip: 'because you mentioned “linear”' }])
- offerSuggestions('s7', 'test', [{ ...suggestion('linear'), tip: 'because you pasted linear.app' }])
-
- // Same key, new trigger — the strip must paint the new reason, not the
- // first one it ever saw.
- expect(($composerSuggestionsBySession.get().s7 ?? []).map(s => s.tip)).toEqual(['because you pasted linear.app'])
-
- offerSuggestions('s7', 'test', [])
- })
-
- it('re-offering the same key swaps in the fresh invoke closure', async () => {
- const calls: string[] = []
-
- const offer = (tag: string) =>
- offerSuggestions('s8', 'test', [
- { ...suggestion('linear'), invoke: async () => void calls.push(tag), label: `Add linear ${tag}` }
- ])
-
- offer('first')
- offer('second')
-
- await ($composerSuggestionsBySession.get().s8 ?? [])[0]!.invoke({ cancelled: () => false, sessionId: 's8' })
-
- // A pinned first object means the pill runs work built for a draft the
- // user has since changed.
- expect(calls).toEqual(['second'])
-
- offerSuggestions('s8', 'test', [])
- })
-})
diff --git a/apps/desktop/src/store/composer-suggestions.ts b/apps/desktop/src/store/composer-suggestions.ts
deleted file mode 100644
index a241c3395ac..00000000000
--- a/apps/desktop/src/store/composer-suggestions.ts
+++ /dev/null
@@ -1,306 +0,0 @@
-import { atom } from 'nanostores'
-
-/**
- * The composer suggestion bus — a generic, session-scoped feed for the pill
- * strip above the composer (rendered by `composer/suggestion-pills.tsx`).
- *
- * Providers, not sources baked into the store: anything can offer a pill —
- * draft keywords (the MCP directory was the first), session state, tool
- * results, connection events. Two provider shapes:
- *
- * - **Draft providers** react to what the user is typing. Registered with
- * `registerDraftProvider`, they run inside the existing debounced draft
- * sampler (600ms, change-gated) and return suggestions for that session's
- * draft. Pure-ish: given a draft, they decide; the bus handles debounce,
- * session scoping, reference identity, and the cap.
- * - **Event providers** push and withdraw suggestions directly via
- * `offerSuggestion` / `withdrawSuggestion` from wherever their signal
- * lives (a store listener, a gateway event handler). The bus applies the
- * same session scoping and cap.
- *
- * The UX contract every suggestion signs (see PR #85036's pills):
- * session-scoped, capped at MAX_SUGGESTIONS with draft suggestions ranked
- * after event ones, self-limiting (a suggestion exists only while its
- * trigger condition holds — providers withdraw it, there is NO dismiss
- * affordance), and one-click: `invoke` runs the whole action with the pill
- * narrating idle → working → done. No suggestion may block or shift the
- * composer.
- */
-export interface ComposerSuggestion {
- /** Stable per-suggestion identity, unique within its provider
- * (e.g. the server name, the skill name). */
- id: string
- /** Provider that offered it; `${provider}:${id}` is the bus-wide key. */
- provider: string
- /** Pill label, already localized ("Add Atlassian"). */
- label: string
- /** Tooltip explaining WHY this is being suggested. */
- tip: string
- /** Brand identity for the glyph slot; falls back to `icon`. */
- brand?: string
- /** Codicon name when there is no brand glyph (default: lightbulb). */
- icon?: string
- /** Runs the whole action; the pill shows `workingLabel` while it's
- * in flight and `doneLabel` on success. Reject to return to idle
- * (provider surfaces its own error toast). */
- invoke: (context: { cancelled: () => boolean; sessionId: string | null }) => Promise<void>
- /** Label while `invoke` runs ("Connecting Atlassian…"). */
- workingLabel: string
- /** Tooltip while working; clicking a working pill requests cancel. */
- workingTip: string
- /** Label after `invoke` resolves ("Added Atlassian"). */
- doneLabel: string
- /** Tooltip once done. */
- doneTip: string
-}
-
-export const MAX_SUGGESTIONS = 2
-
-/** Bus-wide key: provider-namespaced so two providers can't collide. */
-export const suggestionKey = (suggestion: Pick<ComposerSuggestion, 'id' | 'provider'>): string =>
- `${suggestion.provider}:${suggestion.id}`
-
-/** Suggestions keyed by RUNTIME session id, exactly like
- * `$composerActionsBySession`: drafts are per-session state, so suggestions
- * derived from them are too. */
-export const $composerSuggestionsBySession = atom<Record<string, ComposerSuggestion[]>>({})
-
-const keyFor = (sessionId: string | null | undefined): string => sessionId ?? ''
-
-// Everything the pill actually paints. Compared field-by-field rather than by
-// key alone: a provider rebuilds its suggestion objects on every sample, so
-// key equality is true constantly, and treating that as "no change" pins the
-// FIRST object forever — the strip then paints a stale tip and, worse, calls a
-// stale `invoke` closure. Comparing the rendered copy keeps the cheap bail-out
-// for the common case (same draft, same match) while letting a genuinely
-// changed offer through.
-const RENDERED: readonly (keyof ComposerSuggestion)[] = [
- 'brand',
- 'doneLabel',
- 'doneTip',
- 'icon',
- 'label',
- 'tip',
- 'workingLabel',
- 'workingTip'
-]
-
-const sameSuggestions = (a: readonly ComposerSuggestion[], b: readonly ComposerSuggestion[]) =>
- a.length === b.length &&
- a.every((x, i) => {
- const y = b[i]!
-
- return suggestionKey(x) === suggestionKey(y) && RENDERED.every(field => x[field] === y[field])
- })
-
-function write(sessionId: string | null | undefined, suggestions: ComposerSuggestion[]): void {
- const key = keyFor(sessionId)
- const current = $composerSuggestionsBySession.get()
- const existing = current[key] ?? []
-
- // Unchanged sets keep their reference so the strip doesn't re-render.
- if (sameSuggestions(existing, suggestions)) {
- return
- }
-
- const next = { ...current }
-
- if (suggestions.length > 0) {
- next[key] = suggestions
- } else {
- delete next[key]
- }
-
- $composerSuggestionsBySession.set(next)
-}
-
-// ---------------------------------------------------------------------------
-// Providers
-// ---------------------------------------------------------------------------
-
-export interface DraftProviderContext {
- sessionId: string | null
- /** The draft text at sample time. */
- text: string
-}
-
-export type DraftProvider = (context: DraftProviderContext) => Promise<ComposerSuggestion[]>
-
-const draftProviders = new Map<string, DraftProvider>()
-
-/** Register a provider that derives suggestions from the draft. Runs inside
- * the composer's debounced sampler; results replace that provider's previous
- * offerings for the session. Returns an unregister fn (HMR hygiene). */
-export function registerDraftProvider(name: string, provider: DraftProvider): () => void {
- draftProviders.set(name, provider)
-
- return () => {
- draftProviders.delete(name)
- }
-}
-
-// Event-provider offerings, merged with draft results on every write.
-// Keyed session → provider → suggestions.
-const eventOfferings = new Map<string, Map<string, ComposerSuggestion[]>>()
-
-/** Offer suggestions from an event provider (session state, tool results,
- * connection events…). Replaces that provider's previous offerings for the
- * session; providers withdraw by offering []. */
-export function offerSuggestions(
- sessionId: string | null | undefined,
- provider: string,
- suggestions: ComposerSuggestion[]
-): void {
- const key = keyFor(sessionId)
- let providers = eventOfferings.get(key)
-
- if (!providers) {
- providers = new Map()
- eventOfferings.set(key, providers)
- }
-
- if (suggestions.length > 0) {
- providers.set(provider, suggestions)
- } else {
- providers.delete(provider)
- }
-
- publish(sessionId ?? null)
-}
-
-// Last draft-provider results per session, merged with event offerings.
-const draftOfferings = new Map<string, ComposerSuggestion[]>()
-
-// ---------------------------------------------------------------------------
-// Declined ledger (VS Code's hardest-won recommendation lesson: never keep
-// re-firing at someone who has seen the offer and not taken it)
-// ---------------------------------------------------------------------------
-
-// Times a suggestion key was WITHDRAWN without ever being invoked, per
-// session. A pill the user watched appear and let die N times is a declined
-// offer — stop making it for the rest of the session. Session-scoped and
-// in-memory on purpose: a fresh session is a fresh chance, and acting on a
-// pill clears its count.
-const IGNORED_LIMIT = 3
-const ignoredCounts = new Map<string, Map<string, number>>()
-const shown = new Map<string, Set<string>>()
-
-/** The pill strip marks a suggestion invoked so its withdrawal isn't
- * miscounted as the user ignoring it. */
-export function markSuggestionInvoked(sessionId: string | null | undefined, key: string): void {
- ignoredCounts.get(keyFor(sessionId))?.delete(key)
- shown.get(keyFor(sessionId))?.delete(key)
-}
-
-const quieted = (sessionKey: string, key: string): boolean =>
- (ignoredCounts.get(sessionKey)?.get(key) ?? 0) >= IGNORED_LIMIT
-
-// Suggestions visible in the last publish that vanish uninvoked get a strike.
-function recordWithdrawals(sessionKey: string, next: readonly ComposerSuggestion[]): void {
- const previous = shown.get(sessionKey)
-
- if (previous) {
- const surviving = new Set(next.map(suggestionKey))
-
- for (const key of previous) {
- if (!surviving.has(key)) {
- const counts = ignoredCounts.get(sessionKey) ?? new Map<string, number>()
-
- counts.set(key, (counts.get(key) ?? 0) + 1)
- ignoredCounts.set(sessionKey, counts)
- }
- }
- }
-
- shown.set(sessionKey, new Set(next.map(suggestionKey)))
-}
-
-/** Event offerings first (they carry session/tool state, stronger signal
- * than draft keywords), then draft matches, capped. */
-function publish(sessionId: string | null): void {
- const key = keyFor(sessionId)
- const event = [...(eventOfferings.get(key)?.values() ?? [])].flat()
- const draft = draftOfferings.get(key) ?? []
- const seen = new Set<string>()
- const merged: ComposerSuggestion[] = []
-
- for (const suggestion of [...event, ...draft]) {
- const k = suggestionKey(suggestion)
-
- if (!seen.has(k) && !quieted(key, k)) {
- seen.add(k)
- merged.push(suggestion)
- }
-
- if (merged.length >= MAX_SUGGESTIONS) {
- break
- }
- }
-
- recordWithdrawals(key, merged)
- write(sessionId, merged)
-}
-
-// ---------------------------------------------------------------------------
-// Draft sampling (the composer's runtime subscription feeds this)
-// ---------------------------------------------------------------------------
-
-const SAMPLE_DEBOUNCE_MS = 600
-
-// Per-session debounce/generation so a tile composer's sampling never stomps
-// the primary's (each session settles independently).
-const sampleTimers = new Map<string, number>()
-const sampleGenerations = new Map<string, number>()
-
-/**
- * Feed a session's draft snapshot to the draft providers. Called from that
- * composer's runtime subscription on every change, but internally debounced
- * and change-gated: the store only writes when the session's merged set
- * actually differs, so typing within a line costs nothing downstream.
- */
-export function sampleComposerDraft(sessionId: string | null | undefined, text: string): void {
- const key = keyFor(sessionId)
-
- window.clearTimeout(sampleTimers.get(key))
-
- const generation = (sampleGenerations.get(key) ?? 0) + 1
- sampleGenerations.set(key, generation)
-
- // Too short to mean anything — clear draft offerings without running providers.
- if (text.trim().length < 3) {
- draftOfferings.delete(key)
- publish(sessionId ?? null)
-
- return
- }
-
- sampleTimers.set(
- key,
- window.setTimeout(() => {
- void Promise.all(
- [...draftProviders.values()].map(provider =>
- provider({ sessionId: sessionId ?? null, text }).catch((): ComposerSuggestion[] => [])
- )
- ).then(results => {
- // A newer sample for THIS session superseded this one mid-flight.
- if (generation !== sampleGenerations.get(key)) {
- return
- }
-
- draftOfferings.set(key, results.flat())
- publish(sessionId ?? null)
- })
- }, SAMPLE_DEBOUNCE_MS)
- )
-}
-
-/** Drop a session's suggestions outright (composer unmount / session leave).
- * Draft offerings die with the draft; event offerings persist — their
- * providers own that lifecycle and withdraw on their own signal. */
-export function clearDraftSuggestions(sessionId: string | null | undefined): void {
- const key = keyFor(sessionId)
-
- window.clearTimeout(sampleTimers.get(key))
- draftOfferings.delete(key)
- publish(sessionId ?? null)
-}
diff --git a/apps/desktop/src/store/profile-remote-override.ts b/apps/desktop/src/store/profile-remote-override.ts
index 14a39175e42..d1557484798 100644
--- a/apps/desktop/src/store/profile-remote-override.ts
+++ b/apps/desktop/src/store/profile-remote-override.ts
@@ -91,9 +91,8 @@ export async function refreshProfileRemoteOverrides(names: string[]): Promise<vo
}
// The token-rotation failure shape: the remote host answered but refused the
-// credentials. Mirrors the auth-vocabulary used by suggestion-providers/repair
-// — connectivity failures (timeout, refused, DNS) stay generic so a down host
-// doesn't misread as a revoked token.
+// credentials. Connectivity failures (timeout, refused, DNS) stay generic so a
+// down host doesn't misread as a revoked token.
const AUTH_FAILURE_RE =
/\b(401|403|unauthorized|forbidden)\b|invalid[_ ]?token|token .*(expired|invalid|rejected)|authenticat\w+ (failed|required|expired)/i
diff --git a/apps/desktop/src/store/suggestion-providers/cron.test.ts b/apps/desktop/src/store/suggestion-providers/cron.test.ts
deleted file mode 100644
index e83292b68c5..00000000000
--- a/apps/desktop/src/store/suggestion-providers/cron.test.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { describe, expect, it } from 'vitest'
-
-import { matchRecurrence } from './cron'
-
-describe('matchRecurrence', () => {
- it.each([
- ['remind me every morning to check the board', 'every morning'],
- ['run this daily please', 'daily'],
- ['every 2 hours, poll the feed', 'every 2 hours'],
- ['each week send a summary', 'each week'],
- ['do it every friday', 'every friday'],
- ['nightly build report', 'nightly']
- ])('matches recurring phrasing: %s', (draft, phrase) => {
- expect(matchRecurrence(draft)?.toLowerCase()).toBe(phrase)
- })
-
- it.each([
- 'remind me to call mom tomorrow',
- 'this happens to everyone',
- 'the everyday struggle',
- 'weekly-report.pdf is attached',
- 'i read the Daily Prophet'
- ])('stays quiet on one-shots and lookalikes: %s', draft => {
- expect(matchRecurrence(draft)).toBeNull()
- })
-})
diff --git a/apps/desktop/src/store/suggestion-providers/cron.ts b/apps/desktop/src/store/suggestion-providers/cron.ts
deleted file mode 100644
index 17b420e23e3..00000000000
--- a/apps/desktop/src/store/suggestion-providers/cron.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import { requestComposerFocus, requestComposerInsert } from '@/app/chat/composer/focus'
-import { translateNow } from '@/i18n'
-import { registerDraftProvider } from '@/store/composer-suggestions'
-
-/**
- * Recurrence draft provider: the draft reads like a recurring task
- * ("remind me every morning…", "check this daily"), so offer to schedule it
- * as a cron job instead of a one-off message.
- *
- * Invoke prefixes the draft with an explicit scheduling instruction — the
- * agent owns parsing the schedule and creating the job (cronjob tool); the
- * pill only makes the intent unambiguous. Same reversible-edit contract as
- * the skill pill: it touches the draft, nothing else, and stands down once
- * the draft leads with the instruction it inserted.
- */
-
-// Recurrence phrasing, deliberately narrow (VS Code lesson: high-precision
-// triggers over statistical ones). Whole-word, unicode boundaries; hyphen
-// counts as a word character so "weekly-report.pdf" stays quiet.
-// - "every <hour|morning|day|week|weekday|month|monday…>" (+ "every 2 hours")
-// - "daily" / "weekly" / "monthly" / "nightly" / "hourly"
-// - "each morning/day/week/…"
-// - a bare "remind me" is NOT a trigger — one-shot reminders are fine as
-// normal messages.
-const RECURRENCE_RE =
- /(?<![\p{L}\p{N}-])(?:(?:every|each)\s+(?:\d+\s+)?(?:second|minute|hour|morning|afternoon|evening|night|day|weekday|week|month|monday|tuesday|wednesday|thursday|friday|saturday|sunday)s?|daily|weekly|monthly|nightly|hourly)(?![\p{L}\p{N}-])/giu
-
-// A bare frequency adverb immediately followed by a Capitalized word is a
-// proper noun ("the Daily Prophet", "Weekly Standup notes"), not a schedule.
-// Checked in code because the regex's `i` flag case-folds \p{Lu} inside the
-// pattern (making "please" read as capitalized).
-const ADVERB_RE = /^(daily|weekly|monthly|nightly|hourly)$/i
-
-/** Pure matcher, exported for tests: the recurrence phrase that fired, or
- * null. The pill tooltip shows it, same attribution rule as every source. */
-export function matchRecurrence(text: string): string | null {
- for (const match of text.matchAll(RECURRENCE_RE)) {
- const phrase = match[0]
-
- if (ADVERB_RE.test(phrase) && /^\s+\p{Lu}/u.test(text.slice(match.index + phrase.length))) {
- continue
- }
-
- return phrase
- }
-
- return null
-}
-
-registerDraftProvider('cron', async ({ text }) => {
- const copy = (key: string, ...args: unknown[]) => translateNow(`composer.cronSuggestions.${key}`, ...args)
- const trimmed = text.trimStart()
-
- // Already a slash command, or already carrying the instruction we insert —
- // stand down.
- if (trimmed.startsWith('/') || trimmed.toLowerCase().startsWith(copy('prefix').toLowerCase())) {
- return []
- }
-
- const phrase = matchRecurrence(text)
-
- if (!phrase) {
- return []
- }
-
- return [
- {
- doneLabel: copy('done'),
- doneTip: copy('doneTip'),
- icon: 'calendar',
- id: 'schedule',
- invoke: async () => {
- requestComposerInsert(copy('prefix'), { mode: 'prefix' })
- requestComposerFocus()
- },
- label: copy('label'),
- provider: 'cron',
- tip: copy('tip', phrase),
- workingLabel: copy('label'),
- workingTip: copy('tip', phrase)
- }
- ]
-})
diff --git a/apps/desktop/src/store/suggestion-providers/github.test.ts b/apps/desktop/src/store/suggestion-providers/github.test.ts
deleted file mode 100644
index 654db5d1390..00000000000
--- a/apps/desktop/src/store/suggestion-providers/github.test.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { describe, expect, it } from 'vitest'
-
-import { githubHit } from './github'
-
-describe('githubHit', () => {
- it('matches a completed whole-word github mention', () => {
- expect(githubHit('open a github issue for this')).toBe(true)
- expect(githubHit('check GitHub please')).toBe(true)
- })
-
- it('does not fire while the word is still under the caret', () => {
- expect(githubHit('let me check github')).toBe(false)
- })
-
- it('does not match inside other words', () => {
- expect(githubHit('mygithubby thing here')).toBe(false)
- })
-
- it('matches a pasted github.com link immediately', () => {
- expect(githubHit('review https://github.com/NousResearch/hermes-agent/pull/1')).toBe(true)
- expect(githubHit('see https://gist.github.com/foo/abc')).toBe(true)
- })
-
- it('does not match lookalike domains', () => {
- expect(githubHit('see https://notgithub.com/x more')).toBe(false)
- expect(githubHit('see https://github.com.evil.example/x more')).toBe(false)
- })
-})
diff --git a/apps/desktop/src/store/suggestion-providers/github.ts b/apps/desktop/src/store/suggestion-providers/github.ts
deleted file mode 100644
index 934f54a863d..00000000000
--- a/apps/desktop/src/store/suggestion-providers/github.ts
+++ /dev/null
@@ -1,116 +0,0 @@
-import { requestComposerFocus, requestComposerInsert } from '@/app/chat/composer/focus'
-import { getGhAuthStatus } from '@/hermes'
-import { translateNow } from '@/i18n'
-import { type ComposerSuggestion, registerDraftProvider } from '@/store/composer-suggestions'
-
-/**
- * GitHub draft provider — the deliberate NON-MCP integration path.
- *
- * GitHub has no entry in the MCP catalog and never gets a connect pill: its
- * hosted MCP requires a per-host OAuth app (generic Dynamic Client
- * Registration 404s at /register), and more importantly the bundled
- * github/* skills driving the `gh` CLI are a strictly more capable
- * integration (PRs, reviews, issues, releases, workflows) than the remote
- * MCP's tool surface. So when the draft signals GitHub intent, the right
- * offer is onboarding onto the skills:
- *
- * - `gh` already authenticated → no pill. The skills just work; suggesting
- * setup at an already-set-up user is noise.
- * - not authenticated (or gh missing) → offer the `github-auth` skill. The
- * invoke prefixes the draft with `/github-auth` (same reversible,
- * never-sends-on-your-behalf contract as the skill provider) and the
- * agent walks the user through `gh auth login` / install.
- *
- * The auth probe is served by `GET /api/git/gh-auth` (cached backend-side);
- * a probe failure (older backend, transient error) suggests nothing rather
- * than nagging.
- */
-
-const AUTH_TTL_MS = 5 * 60_000
-const SKILL_NAME = 'github-auth'
-
-let needsSetup: boolean | null = null
-let checkedAt = 0
-
-/** Drop the cached gh-auth probe (e.g. after the setup flow completes). */
-export function invalidateGithubSuggestionIndex(): void {
- needsSetup = null
- checkedAt = 0
-}
-
-// Whole-word "github" mention or a pasted github.com link. Same completed-
-// word discipline as the MCP provider: a keyword still under the caret is a
-// word in progress, not intent — but a pasted host counts immediately.
-const KEYWORD_RE = /(?<![\p{L}\p{N}])github(?![\p{L}\p{N}])(?=[\s\S])/iu
-const HOST_RE = /https?:\/\/([^\s/,)\]}"'<>]*@)?([\w.-]*\.)?github\.com(?=[/\s:,)\]}"'<>]|$)/i
-
-/** Pure matcher, exported for tests. */
-export function githubHit(text: string): boolean {
- if (HOST_RE.test(text)) {
- return true
- }
-
- // Keyword matching runs with URLs removed: "github" inside a pasted
- // lookalike domain (notgithub.com, github.com.evil.example) is the URL's
- // business, and the host matcher above already rejected it.
- const withoutUrls = text.replace(/https?:\/\/[^\s]+/gi, ' ')
- const match = KEYWORD_RE.exec(withoutUrls.toLowerCase())
-
- // Completed word: at least one character follows the mention.
- return match !== null && match.index + 'github'.length < withoutUrls.length
-}
-
-async function loadNeedsSetup(): Promise<boolean> {
- if (needsSetup !== null && Date.now() - checkedAt < AUTH_TTL_MS) {
- return needsSetup
- }
-
- const status = await getGhAuthStatus()
-
- needsSetup = !status.authenticated
- checkedAt = Date.now()
-
- return needsSetup
-}
-
-function toSuggestion(): ComposerSuggestion {
- const copy = (key: string, ...args: unknown[]) => translateNow(`composer.githubSuggestions.${key}`, ...args)
-
- return {
- brand: 'github',
- doneLabel: copy('done'),
- doneTip: copy('doneTip'),
- id: SKILL_NAME,
- invoke: async () => {
- // Prefix, don't replace — and never send. The agent takes over when
- // the user sends: the github-auth skill installs gh if needed and
- // runs the device-code OAuth flow.
- requestComposerInsert(`/${SKILL_NAME} `, { mode: 'prefix' })
- requestComposerFocus()
- },
- label: copy('label'),
- provider: 'github',
- tip: copy('tip'),
- workingLabel: copy('label'),
- workingTip: copy('tip')
- }
-}
-
-registerDraftProvider('github', async ({ text }) => {
- const trimmed = text.trimStart()
-
- // Already a slash command (possibly ours from a previous click).
- if (trimmed.startsWith('/')) {
- return []
- }
-
- if (!githubHit(text)) {
- return []
- }
-
- if (!(await loadNeedsSetup())) {
- return []
- }
-
- return [toSuggestion()]
-})
diff --git a/apps/desktop/src/store/suggestion-providers/mcp.test.ts b/apps/desktop/src/store/suggestion-providers/mcp.test.ts
deleted file mode 100644
index 767c7d59848..00000000000
--- a/apps/desktop/src/store/suggestion-providers/mcp.test.ts
+++ /dev/null
@@ -1,219 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest'
-
-import type { ComposerSuggestion } from '@/store/composer-suggestions'
-
-import { buildMcpSuggestionIndex, matchSuggestions } from './mcp'
-
-type DraftProvider = (context: { sessionId: string | null; text: string }) => Promise<ComposerSuggestion[]>
-
-const mocks = vi.hoisted(() => ({
- notify: vi.fn(),
- notifyError: vi.fn(),
- provider: null as DraftProvider | null,
- removeMcpServer: vi.fn(async () => {}),
- request: vi.fn()
-}))
-
-vi.mock('@/api/client', () => ({ capabilityScoped: () => undefined, setSessionOwnerResolver: () => {} }))
-vi.mock('@/hermes', () => ({
- addMcpServer: async () => {},
- setApiRequestProfile: () => {},
- getMcpCatalog: async () => ({
- entries: [
- {
- auth_type: 'oauth',
- name: 'hosted',
- suggest: { hosts: [], keywords: ['hosted'] },
- transport: 'http',
- url: 'https://mcp.example.test'
- }
- ]
- }),
- listMcpServers: async () => ({ servers: [] }),
- removeMcpServer: mocks.removeMcpServer
-}))
-vi.mock('@/lib/mcp-dashboard-oauth', () => ({
- completeMcpDesktopOAuth: async () => ({ tools: [] }),
- McpOAuthCancelled: class extends Error {}
-}))
-vi.mock('@/store/composer-suggestions', () => ({
- registerDraftProvider: (_name: string, provider: DraftProvider) => {
- mocks.provider = provider
- }
-}))
-vi.mock('@/store/gateway', () => ({ $gateway: { get: () => ({ request: mocks.request }) } }))
-vi.mock('@/store/notifications', () => ({ notify: mocks.notify, notifyError: mocks.notifyError }))
-
-describe('connect reads what reload.mcp did for the chat', () => {
- const connect = async () => {
- const [suggestion] = await mocks.provider!({ sessionId: 's1', text: 'use the hosted board ' })
-
- return suggestion!.invoke({ cancelled: () => false, sessionId: 's1' })
- }
-
- beforeEach(() => {
- mocks.notify.mockReset()
- mocks.notifyError.mockReset()
- mocks.request.mockReset()
- })
-
- it('claims success once the chat runs the new server', async () => {
- mocks.request.mockResolvedValue({ session: 'applied', status: 'reloaded' })
-
- await connect()
-
- expect(mocks.request).toHaveBeenCalledWith('reload.mcp', { confirm: true, session_id: 's1' })
- expect(mocks.notify).not.toHaveBeenCalled()
- expect(mocks.notifyError).not.toHaveBeenCalled()
- })
-
- it('does not claim the chat has the server while its turn defers the change', async () => {
- mocks.request.mockResolvedValue({ session: 'busy', status: 'reloaded' })
-
- await expect(connect()).rejects.toThrow()
-
- expect(mocks.notify).toHaveBeenCalledWith(expect.objectContaining({ message: expect.stringMatching(/busy/i) }))
- expect(mocks.notifyError).not.toHaveBeenCalled()
- })
-
- it('fails when the new server is among those that did not connect', async () => {
- mocks.request.mockResolvedValue({ session: 'applied', status: 'reloaded', unavailable: ['hosted'] })
-
- await expect(connect()).rejects.toThrow(/hosted/)
-
- expect(mocks.notifyError).toHaveBeenCalled()
- })
-
- it('fails when the reload is refused', async () => {
- mocks.request.mockRejectedValue(new Error('mcp_servers_unavailable: did not connect: hosted'))
-
- await expect(connect()).rejects.toThrow()
-
- expect(mocks.notifyError).toHaveBeenCalled()
- })
-
- it('succeeds beside another server that did not connect, and names it', async () => {
- mocks.request.mockResolvedValue({ session: 'applied', status: 'reloaded', unavailable: ['linear'] })
-
- await connect()
-
- expect(mocks.notify).toHaveBeenCalledWith(
- expect.objectContaining({ kind: 'warning', message: expect.stringContaining('linear') })
- )
- expect(mocks.notifyError).not.toHaveBeenCalled()
- })
-})
-
-it('does not send local-app or non-OAuth catalog suggestions through the hosted OAuth-only composer flow', () => {
- const hosted = {
- name: 'hosted',
- url: 'https://mcp.example.test',
- auth_type: 'oauth',
- transport: 'http',
- suggest: { keywords: ['hosted'], hosts: [] }
- }
-
- const editor = {
- ...hosted,
- name: 'editor',
- url: 'http://127.0.0.1:8000/mcp',
- auth_type: 'none',
- suggest: { ...hosted.suggest, requires_app: true }
- }
-
- const key = { ...hosted, name: 'key', auth_type: 'api_key' }
- const stdio = { ...hosted, name: 'stdio', url: null, transport: 'stdio' }
- expect(buildMcpSuggestionIndex([hosted, editor, key, stdio]).map(row => row.server)).toEqual([hosted.name])
-})
-
-const INDEX = [
- { keywords: ['linear', 'issue tracker', 'ticket'], server: 'linear' },
- { keywords: ['figma', 'design'], server: 'figma' },
- { keywords: ['unreal', 'ue5'], server: 'unreal-engine' }
-]
-
-describe('matchSuggestions', () => {
- it('matches a whole word and reports the keyword that hit', () => {
- expect(matchSuggestions('can you check the linear board', INDEX)).toEqual([{ keyword: 'linear', server: 'linear' }])
- })
-
- it('does not match inside other words', () => {
- // "linearly" must not suggest Linear — the classic false positive.
- expect(matchSuggestions('this scales linearly with input', INDEX)).toEqual([])
- })
-
- it('matches multi-word keywords as phrases', () => {
- expect(matchSuggestions('our issue tracker is a mess', INDEX)).toEqual([
- { keyword: 'issue tracker', server: 'linear' }
- ])
- })
-
- it('is case-insensitive against the draft', () => {
- expect(matchSuggestions('open FIGMA please', INDEX)).toEqual([{ keyword: 'figma', server: 'figma' }])
- })
-
- it('caps the number of suggestions', () => {
- const matches = matchSuggestions('linear ticket for the figma design in unreal', INDEX)
-
- expect(matches.length).toBeLessThanOrEqual(2)
- })
-
- it('one suggestion per server even when several keywords hit', () => {
- expect(matchSuggestions('a linear ticket', INDEX)).toEqual([{ keyword: 'linear', server: 'linear' }])
- })
-
- it('handles regex metacharacters in keywords safely', () => {
- const index = [{ keywords: ['c++'], server: 'cpp-tools' }]
-
- expect(matchSuggestions('help with c++ code', index)).toEqual([{ keyword: 'c++', server: 'cpp-tools' }])
- })
-
- it('matches a pasted vendor URL by host suffix', () => {
- const index = [{ hosts: ['atlassian.net'], keywords: ['jira'], server: 'atlassian' }]
-
- expect(matchSuggestions('look at https://yourco.atlassian.net/browse/ENG-123 pls', index)).toEqual([
- { keyword: 'atlassian.net', server: 'atlassian' }
- ])
- })
-
- it('host hit wins over keyword hit as the reported trigger', () => {
- const index = [{ hosts: ['linear.app'], keywords: ['linear'], server: 'linear' }]
-
- expect(matchSuggestions('linear ticket: https://linear.app/team/issue/ABC-1', index)).toEqual([
- { keyword: 'linear.app', server: 'linear' }
- ])
- })
-
- it('does not match a host suffix embedded in another domain', () => {
- const index = [{ hosts: ['linear.app'], keywords: [], server: 'linear' }]
-
- // evil-linear.app.example.com must not fire; nor must notlinear.app.
- expect(matchSuggestions('see https://linear.app.example.com/x', index)).toEqual([])
- expect(matchSuggestions('see https://notlinear.app/x', index)).toEqual([])
- })
-
- it('strips port and credentials before host comparison', () => {
- const index = [{ hosts: ['sentry.io'], keywords: [], server: 'sentry' }]
-
- expect(matchSuggestions('logs at https://[email protected]:443/issues', index)).toEqual([
- { keyword: 'sentry.io', server: 'sentry' }
- ])
- })
-
- it('a keyword still under the caret does not fire yet', () => {
- // The debounce elapses mid-thought; the word is only intent once
- // something follows it.
- expect(matchSuggestions('can you check linear', INDEX)).toEqual([])
- expect(matchSuggestions('can you check linear ', INDEX)).toEqual([{ keyword: 'linear', server: 'linear' }])
- expect(matchSuggestions('can you check linear?', INDEX)).toEqual([{ keyword: 'linear', server: 'linear' }])
- })
-
- it('a pasted URL fires even as the last thing in the draft', () => {
- // Pasting is a deliberate act — the completed-word guard is keyword-only.
- const index = [{ hosts: ['linear.app'], keywords: ['linear'], server: 'linear' }]
-
- expect(matchSuggestions('look at https://linear.app/team/issue/ABC-1', index)).toEqual([
- { keyword: 'linear.app', server: 'linear' }
- ])
- })
-})
diff --git a/apps/desktop/src/store/suggestion-providers/mcp.ts b/apps/desktop/src/store/suggestion-providers/mcp.ts
deleted file mode 100644
index 4b5ee9dbdae..00000000000
--- a/apps/desktop/src/store/suggestion-providers/mcp.ts
+++ /dev/null
@@ -1,253 +0,0 @@
-import { capabilityScoped } from '@/api/client'
-import { addMcpServer, getMcpCatalog, listMcpServers, removeMcpServer } from '@/hermes'
-import { translateNow } from '@/i18n'
-import { completeMcpDesktopOAuth, McpOAuthCancelled } from '@/lib/mcp-dashboard-oauth'
-import { McpReloadDeferred, reloadMcpFor } from '@/lib/mcp-reload'
-import { prettyName } from '@/lib/text'
-import { type ComposerSuggestion, registerDraftProvider } from '@/store/composer-suggestions'
-import { notifyError } from '@/store/notifications'
-import type { McpCatalogEntry } from '@/types/hermes'
-
-/**
- * The MCP draft provider — the suggestion bus's founding member (PR #85036).
- *
- * Matches the draft against the Nous-approved MCP catalog's `suggest`
- * metadata (`GET /api/mcp/catalog` — the same reviewed manifests behind
- * `hermes mcp catalog`), by whole-word keyword and pasted-link host suffix,
- * excluding servers already configured. The catalog is the single source of
- * truth for suggestible servers. A suggestion's invoke runs the whole
- * connect: validated config write → browser OAuth → live tool reload, with
- * rollback on cancel/failure so a decline never strands a half-configured
- * server.
- */
-
-const CONFIGURED_TTL_MS = 5 * 60_000
-const CATALOG_TTL_MS = 5 * 60_000
-
-// Names already present in mcp_servers config (enabled or not) — those need a
-// toggle/auth at most, not an "add this server" pill. Cached briefly; a miss
-// (older backend, transient error) suggests nothing rather than nagging.
-let configuredNames: Set<string> | null = null
-let configuredAt = 0
-
-interface SuggestibleServer {
- server: string
- keywords: string[]
- hosts?: string[]
- /** Streamable-HTTP/SSE endpoint written to config on invoke. */
- url: string
-}
-
-// Suggestible servers from the catalog (entries with `suggest` + an http url).
-let suggestible: SuggestibleServer[] | null = null
-let suggestibleAt = 0
-
-/** Drop the caches (profile switch / after an install). */
-export function invalidateMcpSuggestionIndex(): void {
- configuredNames = null
- configuredAt = 0
- suggestible = null
- suggestibleAt = 0
-}
-
-async function loadConfiguredNames(): Promise<Set<string>> {
- if (configuredNames && Date.now() - configuredAt < CONFIGURED_TTL_MS) {
- return configuredNames
- }
-
- const { servers } = await listMcpServers()
-
- configuredNames = new Set(servers.map(server => server.name))
- configuredAt = Date.now()
-
- return configuredNames
-}
-
-async function loadSuggestible(): Promise<SuggestibleServer[]> {
- if (suggestible && Date.now() - suggestibleAt < CATALOG_TTL_MS) {
- return suggestible
- }
-
- const { entries } = await getMcpCatalog()
-
- const fromCatalog = buildMcpSuggestionIndex(entries)
-
- suggestible = fromCatalog
- suggestibleAt = Date.now()
-
- return suggestible
-}
-
-/** This older composer path runs hosted OAuth. Local/setup-dependent tasks use manage_connections instead. */
-export function buildMcpSuggestionIndex(
- entries: readonly Pick<McpCatalogEntry, 'name' | 'url' | 'suggest' | 'auth_type' | 'transport'>[]
-): SuggestibleServer[] {
- return entries
- .filter(
- entry =>
- entry.transport === 'http' &&
- entry.auth_type === 'oauth' &&
- !entry.suggest?.requires_app &&
- entry.suggest &&
- entry.url &&
- (entry.suggest.keywords.length > 0 || entry.suggest.hosts.length > 0)
- )
- .map(entry => ({
- hosts: entry.suggest!.hosts,
- keywords: entry.suggest!.keywords,
- server: entry.name,
- url: entry.url!
- }))
-}
-
-interface KeywordEntry {
- server: string
- keywords: string[]
- /** Hostname suffixes ("atlassian.net") matched against URLs in the draft. */
- hosts?: string[]
-}
-
-// Hostnames of http(s) URLs in the draft. Loose on purpose — a draft is not
-// a document, so a trailing-punctuation host ("linear.app,") still counts.
-const URL_HOST_RE = /https?:\/\/([^\s/,)\]}"'<>]+)/gi
-
-const draftHosts = (text: string): string[] =>
- [...text.matchAll(URL_HOST_RE)].map(match => {
- const raw = match[1]!.toLowerCase()
- // Strip credentials and port: user@host:443 → host.
- const withoutCredentials = raw.slice(raw.lastIndexOf('@') + 1)
-
- return withoutCredentials.replace(/:\d+$/, '')
- })
-
-// Strict suffix-on-dot-boundary: "myorg.atlassian.net" matches "atlassian.net";
-// "notlinear.app" and "linear.app.example.com" do not match "linear.app".
-const hostMatches = (host: string, suffix: string): boolean => host === suffix || host.endsWith(`.${suffix}`)
-
-export interface McpMatch {
- server: string
- /** The keyword or host that matched, for the pill's tooltip. */
- keyword: string
-}
-
-const MAX_MATCHES = 2
-
-// Whole-word (unicode-aware) keyword hit that the user has FINISHED typing:
-// at least one character must follow the match (the lookahead already
-// guarantees it's a boundary). A hit still under the caret — "figma" as the
-// last thing typed, debounce elapsed mid-thought — is not intent yet, it's
-// eavesdropping on a word in progress; the pill waits for the space/period.
-const keywordHit = (haystack: string, candidate: string): boolean => {
- const pattern = new RegExp(
- `(?<![\\p{L}\\p{N}])${candidate.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\p{L}\\p{N}])`,
- 'gu'
- )
-
- for (const match of haystack.matchAll(pattern)) {
- if (match.index + match[0].length < haystack.length) {
- return true
- }
- }
-
- return false
-}
-
-/** Pure matcher, exported for tests: pasted-link host hits (the strongest
- * intent signal) and completed whole-word keyword hits against the draft,
- * capped at MAX_MATCHES. Host hits skip the completed-word guard — a paste
- * is a deliberate act, and the URL routinely ends the draft. */
-export function matchSuggestions(text: string, index: KeywordEntry[]): McpMatch[] {
- const haystack = text.toLowerCase()
- const hosts = draftHosts(text)
- const matches: McpMatch[] = []
-
- for (const entry of index) {
- // A pasted vendor link beats any keyword: report the host as the trigger.
- const host = entry.hosts?.find(suffix => hosts.some(candidate => hostMatches(candidate, suffix)))
-
- // Whole-word match so "linearly" doesn't suggest Linear. Suggest
- // keywords are lowercase; multi-word keywords match as phrases.
- const keyword = host ?? entry.keywords.find(candidate => keywordHit(haystack, candidate))
-
- if (keyword) {
- matches.push({ keyword, server: entry.server })
-
- if (matches.length >= MAX_MATCHES) {
- break
- }
- }
- }
-
- return matches
-}
-
-async function connect(known: SuggestibleServer, sessionId: string | null, cancelled: () => boolean): Promise<void> {
- const oauthScope = capabilityScoped()
-
- try {
- await addMcpServer({ name: known.server, url: known.url }, oauthScope)
-
- try {
- await completeMcpDesktopOAuth({
- serverName: known.server,
- profile: oauthScope,
- cancelled
- })
- } catch (error) {
- // Decline/failure means "no server" — roll back the config write
- // rather than stranding an unauthorized entry (authoritative-write
- // rule). Best-effort; the primary error wins.
- await removeMcpServer(known.server, oauthScope).catch(() => {})
- throw error
- }
-
- invalidateMcpSuggestionIndex()
- // The pill claims success only once the chat runs the server: not while a
- // turn defers the change, and not when the server did not connect.
- await reloadMcpFor(known.server, sessionId)
- } catch (error) {
- if (!(error instanceof McpOAuthCancelled || error instanceof McpReloadDeferred)) {
- notifyError(error, translateNow('composer.mcpSuggestions.connectFailed', prettyName(known.server)))
- }
-
- throw error
- }
-}
-
-function toSuggestion(match: McpMatch, known: SuggestibleServer, sessionId: string | null): ComposerSuggestion {
- const name = prettyName(match.server)
- const copy = (key: string, ...args: unknown[]) => translateNow(`composer.mcpSuggestions.${key}`, ...args)
-
- return {
- brand: match.server,
- doneLabel: copy('added', name),
- doneTip: copy('addedTip'),
- id: match.server,
- // The pill's session wins over the one captured at sample time: the reload
- // has to reach the session the user is actually looking at.
- invoke: context => connect(known, context.sessionId ?? sessionId, context.cancelled),
- label: copy('label', name),
- provider: 'mcp',
- tip: copy('tip', match.keyword),
- workingLabel: copy('connecting', name),
- workingTip: copy('cancelTip')
- }
-}
-
-registerDraftProvider('mcp', async ({ sessionId, text }) => {
- // Catalog unreachable — suggest nothing rather than mis-suggest.
- const index = await loadSuggestible()
- const candidates = matchSuggestions(text, index)
-
- // Fast path: no keyword hit at all → skip the servers fetch.
- if (candidates.length === 0) {
- return []
- }
-
- const configured = await loadConfiguredNames()
- const byName = new Map(index.map(entry => [entry.server, entry]))
-
- return candidates
- .filter(candidate => !configured.has(candidate.server))
- .map(match => toSuggestion(match, byName.get(match.server)!, sessionId))
-})
diff --git a/apps/desktop/src/store/suggestion-providers/repair.test.ts b/apps/desktop/src/store/suggestion-providers/repair.test.ts
deleted file mode 100644
index 610607e5225..00000000000
--- a/apps/desktop/src/store/suggestion-providers/repair.test.ts
+++ /dev/null
@@ -1,147 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest'
-
-import type { ComposerSuggestion } from '@/store/composer-suggestions'
-
-import { mcpServerFromToolName, REPAIR_RE, reportMcpToolResult } from './repair'
-
-const mocks = vi.hoisted(() => ({
- notify: vi.fn(),
- notifyError: vi.fn(),
- offers: [] as ComposerSuggestion[][],
- request: vi.fn()
-}))
-
-vi.mock('@/hermes', () => ({
- listMcpServers: async () => ({ servers: [{ name: 'figma' }] }),
- setApiRequestProfile: () => {}
-}))
-vi.mock('@/lib/mcp-dashboard-oauth', () => ({
- completeMcpDesktopOAuth: async () => ({ tools: [] }),
- McpOAuthCancelled: class extends Error {}
-}))
-vi.mock('@/store/composer-suggestions', () => ({
- offerSuggestions: (_sessionId: unknown, _provider: string, suggestions: ComposerSuggestion[]) => {
- mocks.offers.push(suggestions)
- }
-}))
-vi.mock('@/store/gateway', () => ({ $gateway: { get: () => ({ request: mocks.request }) } }))
-vi.mock('@/store/notifications', () => ({ notify: mocks.notify, notifyError: mocks.notifyError }))
-
-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()
- })
-})
-
-describe('REPAIR_RE', () => {
- it.each([
- 'HTTP 401 Unauthorized',
- 'token has expired, please re-authenticate',
- 'OAuth flow required',
- 'authentication failed for server',
- 'connection refused by remote host',
- 'ECONNREFUSED 127.0.0.1:3845',
- 'server disconnected before response'
- ])('flags auth/connection failures: %s', text => {
- expect(REPAIR_RE.test(text)).toBe(true)
- })
-
- it.each([
- 'issue PROJ-123 not found',
- 'no design nodes matched the query',
- 'rate limit exceeded, retry after 60s',
- 'invalid argument: node_id is required',
- 'permission denied editing this file'
- ])('ignores tool-semantics failures: %s', text => {
- expect(REPAIR_RE.test(text)).toBe(false)
- })
-})
-
-describe('reconnect reads what reload.mcp did for the chat', () => {
- let session = 0
-
- // A fresh chat with a failed figma call: the offer it raises.
- const offered = async (): Promise<{ sessionId: string; suggestion: ComposerSuggestion }> => {
- const sessionId = `s${++session}`
- reportMcpToolResult(sessionId, 'mcp__figma__get_design_context', true, 'HTTP 401 Unauthorized')
- await vi.waitFor(() => expect(mocks.offers.at(-1)).toHaveLength(1))
-
- return { sessionId, suggestion: mocks.offers.at(-1)![0]! }
- }
-
- const invoke = ({ sessionId, suggestion }: { sessionId: string; suggestion: ComposerSuggestion }) =>
- suggestion.invoke({ cancelled: () => false, sessionId })
-
- beforeEach(() => {
- mocks.offers.length = 0
- mocks.notify.mockReset()
- mocks.notifyError.mockReset()
- mocks.request.mockReset()
- })
-
- it('withdraws the offer once the chat runs the reconnected server', async () => {
- const pill = await offered()
- mocks.request.mockResolvedValue({ session: 'applied', status: 'reloaded' })
-
- await invoke(pill)
-
- expect(mocks.request).toHaveBeenCalledWith('reload.mcp', { confirm: true, session_id: pill.sessionId })
- expect(mocks.offers.at(-1)).toEqual([])
- })
-
- it('keeps the offer and says so when the chat is busy and the change is deferred', async () => {
- const pill = await offered()
- const before = mocks.offers.length
- mocks.request.mockResolvedValue({ session: 'busy', status: 'reloaded' })
-
- await expect(invoke(pill)).rejects.toThrow()
-
- expect(mocks.offers).toHaveLength(before)
- expect(mocks.notify).toHaveBeenCalledWith(expect.objectContaining({ message: expect.stringMatching(/busy/i) }))
- expect(mocks.notifyError).not.toHaveBeenCalled()
- })
-
- it('keeps the offer when the server still did not connect', async () => {
- const pill = await offered()
- const before = mocks.offers.length
- mocks.request.mockResolvedValue({ session: 'applied', status: 'reloaded', unavailable: ['figma'] })
-
- await expect(invoke(pill)).rejects.toThrow(/figma/)
-
- expect(mocks.offers).toHaveLength(before)
- expect(mocks.notifyError).toHaveBeenCalled()
- })
-
- it('keeps the offer when the reload itself is refused', async () => {
- const pill = await offered()
- const before = mocks.offers.length
- mocks.request.mockRejectedValue(new Error('mcp_servers_unavailable: did not connect: figma'))
-
- await expect(invoke(pill)).rejects.toThrow()
-
- expect(mocks.offers).toHaveLength(before)
- })
-
- it('withdraws its own offer but names another server that did not connect', async () => {
- const pill = await offered()
- mocks.request.mockResolvedValue({ session: 'unchanged', status: 'reloaded', unavailable: ['linear'] })
-
- await invoke(pill)
-
- expect(mocks.offers.at(-1)).toEqual([])
- expect(mocks.notify).toHaveBeenCalledWith(
- expect.objectContaining({ kind: 'warning', message: expect.stringContaining('linear') })
- )
- })
-})
diff --git a/apps/desktop/src/store/suggestion-providers/repair.ts b/apps/desktop/src/store/suggestion-providers/repair.ts
deleted file mode 100644
index c932448a5bd..00000000000
--- a/apps/desktop/src/store/suggestion-providers/repair.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-import { listMcpServers } from '@/hermes'
-import { translateNow } from '@/i18n'
-import { completeMcpDesktopOAuth, McpOAuthCancelled } from '@/lib/mcp-dashboard-oauth'
-import { McpReloadDeferred, reloadMcpFor } from '@/lib/mcp-reload'
-import { prettyName } from '@/lib/text'
-import { type ComposerSuggestion, offerSuggestions } from '@/store/composer-suggestions'
-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. Exported for
-// tests.
-export 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,
- cancelled
- })
-
- // The offer stays until the chat runs the reconnected server: a deferred
- // change or a server that still did not connect keeps it.
- await reloadMcpFor(server, sessionId)
- clearMcpFailure(sessionId, server)
- } catch (error) {
- if (!(error instanceof McpOAuthCancelled || error instanceof McpReloadDeferred)) {
- 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, context.sessionId ?? 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.test.ts b/apps/desktop/src/store/suggestion-providers/skill.test.ts
deleted file mode 100644
index 649567f4d32..00000000000
--- a/apps/desktop/src/store/suggestion-providers/skill.test.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-import { describe, expect, it } from 'vitest'
-
-import type { ChatMessage } from '@/lib/chat-messages'
-
-import { collidesWithWorkspace, skillHit, skillPattern, skillTouchedInMessages, stripSlashTokens } from './skill'
-
-// skillHit is the provider's real predicate: a whole-word match that the user
-// has finished typing (at least one character follows it).
-const hits = (name: string, draft: string) => skillHit(skillPattern(name), draft.toLowerCase())
-
-// Exercises the provider's real haystack sanitizer, not a copy of it.
-const hitsAfterSanitize = (name: string, draft: string) =>
- skillHit(skillPattern(name), stripSlashTokens(draft).toLowerCase())
-
-describe('skillPattern + skillHit', () => {
- it('matches the exact name as a completed whole word', () => {
- expect(hits('perf', 'run the perf loop')).toBe(true)
- expect(hits('perf', 'performance is bad')).toBe(false)
- })
-
- it('hyphenated names also match spaced phrasing', () => {
- expect(hits('pr-ready', 'make this pr ready pls')).toBe(true)
- expect(hits('pr-ready', 'run pr-ready on it')).toBe(true)
- expect(hits('pr_ready', 'pr ready please')).toBe(true)
- })
-
- it('never matches inside other words', () => {
- expect(hits('read', 'i already did')).toBe(false)
- expect(hits('work', 'reworked the layout')).toBe(false)
- // Suffix boundary includes hyphen: "clean" must not fire inside "clean-up"
- // (a different skill may own that name).
- expect(hits('clean', 'do a clean-up pass')).toBe(false)
- })
-
- it('is case-insensitive via lowercased input', () => {
- expect(hits('Clean', 'please clean this diff')).toBe(true)
- })
-
- it('a name still under the caret is not a hit yet', () => {
- // The debounce fires while the word is the last thing typed — wait for
- // the next keystroke to call it intent.
- expect(hits('perf', 'run perf')).toBe(false)
- expect(hits('perf', 'run perf ')).toBe(true)
- expect(hits('perf', 'run perf.')).toBe(true)
- })
-
- it('an earlier completed occurrence still counts', () => {
- expect(hits('perf', 'perf first, then more perf')).toBe(true)
- })
-})
-
-describe('collidesWithWorkspace', () => {
- it('suppresses a skill named exactly like the cwd folder', () => {
- expect(collidesWithWorkspace('hermes-agent', '/Users/b/www/hermes-agent')).toBe(true)
- })
-
- it('suppresses inside worktree-suffixed folders too', () => {
- expect(collidesWithWorkspace('hermes-agent', '/Users/b/www/hermes-agent-suggest')).toBe(true)
- })
-
- it('does not suppress on substring-only overlap', () => {
- // "perf" inside "perfect-app" is not a homonym of the project.
- expect(collidesWithWorkspace('perf', '/Users/b/www/perfect-app')).toBe(false)
- expect(collidesWithWorkspace('clean', '/Users/b/www/hermes-agent')).toBe(false)
- })
-
- it('never collides when detached (empty cwd)', () => {
- expect(collidesWithWorkspace('hermes-agent', '')).toBe(false)
- })
-})
-
-// -- skillTouchedInMessages ---------------------------------------------------
-
-const toolCall = (toolName: string, args?: unknown, argsText = ''): ChatMessage => ({
- id: 't',
- role: 'assistant',
- parts: [{ args: args as never, argsText, toolCallId: 'x', toolName, type: 'tool-call' }]
-})
-
-const userText = (text: string): ChatMessage => ({
- id: 'u',
- role: 'user',
- parts: [{ text, type: 'text' }]
-})
-
-describe('skillTouchedInMessages', () => {
- it('detects a skill_view load of the skill', () => {
- expect(skillTouchedInMessages('pr-ready', [toolCall('skill_view', { name: 'pr-ready' })])).toBe(true)
- })
-
- it('detects a skill_manage touch of the skill', () => {
- expect(skillTouchedInMessages('pr-ready', [toolCall('skill_manage', { action: 'patch', name: 'pr-ready' })])).toBe(
- true
- )
- })
-
- it('matches qualified skill names (category/name, plugin:name)', () => {
- expect(
- skillTouchedInMessages('hermes-agent-dev', [toolCall('skill_view', { name: 'github/hermes-agent-dev' })])
- ).toBe(true)
- expect(
- skillTouchedInMessages('writing-plans', [toolCall('skill_view', { name: 'superpowers:writing-plans' })])
- ).toBe(true)
- })
-
- it('falls back to argsText when args were not parsed', () => {
- expect(skillTouchedInMessages('pr-ready', [toolCall('skill_view', undefined, '{"name":"pr-ready"}')])).toBe(true)
- })
-
- it('detects the user loading the skill via its slash command', () => {
- expect(skillTouchedInMessages('pr-ready', [userText('/pr-ready check this branch')])).toBe(true)
- expect(skillTouchedInMessages('pr-ready', [userText('/pr-ready')])).toBe(true)
- })
-
- it('ignores touches of OTHER skills and non-skill tools', () => {
- expect(skillTouchedInMessages('pr-ready', [toolCall('skill_view', { name: 'clean' })])).toBe(false)
- expect(skillTouchedInMessages('pr-ready', [toolCall('read_file', { path: 'pr-ready' })])).toBe(false)
- // Slash prefix must be exact — /pr-ready-extra is a different command.
- expect(skillTouchedInMessages('pr-ready', [userText('/pr-ready-extra go')])).toBe(false)
- // Merely mentioning the name in prose is not a load.
- expect(skillTouchedInMessages('pr-ready', [userText('is pr-ready any good?')])).toBe(false)
- })
-
- it('is case-insensitive on the stored arg', () => {
- expect(skillTouchedInMessages('pr-ready', [toolCall('skill_view', { name: 'PR-Ready' })])).toBe(true)
- })
-
- it('empty transcript touches nothing', () => {
- expect(skillTouchedInMessages('pr-ready', [])).toBe(false)
- })
-})
-
-describe('draft haystack sanitization (slash-prefixed skills, #91626)', () => {
- it('strips slash commands mid-message before scanning', () => {
- // The bug: "please run /github-auth on this" re-fired the "Use skill:
- // github-auth" pill because skillHit matched "github-auth" inside the
- // slash command the user had already typed.
- expect(hitsAfterSanitize('github-auth', 'please run /github-auth on this')).toBe(false)
- expect(hitsAfterSanitize('vault', 'When I trigger /vault and /github-auth please')).toBe(false)
- })
-
- it('preserves URL fragments mid-prose (no leading whitespace)', () => {
- // https://example.com/api/v1 is not stripped: the regex only removes
- // whitespace-bounded slash tokens.
- expect(hitsAfterSanitize('api', 'visit https://example.com/api/v1 for api docs ')).toBe(true)
- })
-
- it('a real prose mention after a slash command still hits', () => {
- // Stripping the slash token must not blind the provider to a genuine
- // prose mention elsewhere in the draft.
- expect(hitsAfterSanitize('github-auth', '/github-auth loaded. Is github-auth any good? ')).toBe(true)
- })
-})
diff --git a/apps/desktop/src/store/suggestion-providers/skill.ts b/apps/desktop/src/store/suggestion-providers/skill.ts
deleted file mode 100644
index d845a2680a3..00000000000
--- a/apps/desktop/src/store/suggestion-providers/skill.ts
+++ /dev/null
@@ -1,245 +0,0 @@
-import { requestComposerFocus, requestComposerInsert } from '@/app/chat/composer/focus'
-import { getSkills } from '@/hermes'
-import { translateNow } from '@/i18n'
-import type { ChatMessage } from '@/lib/chat-messages'
-import { type ComposerSuggestion, registerDraftProvider } from '@/store/composer-suggestions'
-import { $activeSessionId, $currentCwd, $messages } from '@/store/session'
-import { $sessionStates } from '@/store/session-states'
-
-/**
- * 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, '\\$&')
-
-/** Whole-word pattern for a skill name, exported for tests. Hyphens and
- * underscores in the name also match spaces — people type "pr ready", the
- * skill is `pr-ready` — while "already" can never match a skill `read`. */
-export function skillPattern(name: string): RegExp {
- const flexible = name.toLowerCase().split(/[-_]/).map(escape).join('[-_ ]')
-
- return new RegExp(`(?<![\\p{L}\\p{N}])${flexible}(?![\\p{L}\\p{N}-])`, 'gu')
-}
-
-/** Completed whole-word hit, exported for tests: the match only counts once
- * at least one character follows it. The debounce fires mid-sentence, and a
- * name still under the caret is a word in progress, not a request — the pill
- * waiting for the next keystroke is the difference between "offering" and
- * "reading over your shoulder". */
-export function skillHit(pattern: RegExp, haystack: string): boolean {
- pattern.lastIndex = 0
-
- for (const match of haystack.matchAll(pattern)) {
- if (match.index + match[0].length < haystack.length) {
- return true
- }
- }
-
- return false
-}
-
-/** Strip whitespace-bounded /<token> slash commands the user authored, so a
- * skill name inside a command ("run /github-auth") does not self-trigger the
- * prose suggestion pill (#91626). Whitespace-bounded on purpose: a URL like
- * /api/v1 mid-prose has no leading whitespace and is left intact. Exported so
- * the provider and its tests exercise the same sanitizer instead of a copy. */
-export function stripSlashTokens(text: string): string {
- return text.replace(/\s\/[\w-]+/g, ' ')
-}
-
-/** Workspace homonym guard, exported for tests: a skill named like the
- * working directory is the project's name, not a request for the skill.
- * Working in `~/www/hermes-agent`, the draft says "hermes-agent" constantly
- * — a "Use skill: hermes-agent" pill on every mention is noise (the reported
- * annoyance that prompted this guard). Boundary containment, not exact
- * segment equality, so worktree dirs (`hermes-agent-suggest`) suppress too. */
-export function collidesWithWorkspace(name: string, cwd: string): boolean {
- return new RegExp(`(?<![\\p{L}\\p{N}])${escape(name.toLowerCase())}(?![\\p{L}\\p{N}])`, 'u').test(cwd.toLowerCase())
-}
-
-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,
- pattern: skillPattern(skill.name)
- }))
- indexAt = Date.now()
-
- return index
-}
-
-// ---------------------------------------------------------------------------
-// Already-in-context guard: a skill the session has engaged with must not be
-// re-offered. skill_view loads the whole SKILL.md into the conversation and
-// skill_manage implies the agent is already working with it — clicking the
-// pill would just re-inject content the context already carries (the reported
-// annoyance: a "Use skill" pill for a skill loaded at session start).
-// ---------------------------------------------------------------------------
-
-const SKILL_TOOL_NAMES = new Set(['skill_manage', 'skill_view'])
-
-/** The `name` argument of a skill tool call, however the transcript stored
- * it: live rows carry a parsed `args` object, hydrated rows may only have
- * the JSON `argsText`. */
-function skillArgName(part: { args?: unknown; argsText?: unknown }): string {
- const record = part.args && typeof part.args === 'object' ? (part.args as Record<string, unknown>) : null
-
- if (record && typeof record.name === 'string') {
- return record.name
- }
-
- if (typeof part.argsText === 'string' && part.argsText) {
- try {
- const parsed: unknown = JSON.parse(part.argsText)
-
- if (parsed && typeof parsed === 'object' && typeof (parsed as { name?: unknown }).name === 'string') {
- return (parsed as { name: string }).name
- }
- } catch {
- // Non-JSON argsText carries no name.
- }
- }
-
- return ''
-}
-
-/** True when the tool-call arg names this skill — exactly, or as the final
- * segment of a qualified form (`github/hermes-agent-dev`, `plugin:skill`). */
-function argNamesSkill(arg: string, skillName: string): boolean {
- const value = arg.trim().toLowerCase()
-
- if (!value) {
- return false
- }
-
- const target = skillName.toLowerCase()
-
- return value === target || (value.split(/[/:]/).pop() ?? '') === target
-}
-
-/** Session already touched this skill: the agent loaded it (`skill_view`),
- * edited it (`skill_manage`), or the user sent its `/name` command.
- * Exported for tests. */
-export function skillTouchedInMessages(skillName: string, messages: readonly ChatMessage[]): boolean {
- const slash = new RegExp(`^/${escape(skillName.toLowerCase())}(?:\\s|$)`)
-
- for (const message of messages) {
- for (const part of message.parts) {
- if (
- part.type === 'tool-call' &&
- SKILL_TOOL_NAMES.has(part.toolName) &&
- argNamesSkill(skillArgName(part), skillName)
- ) {
- return true
- }
-
- if (
- message.role === 'user' &&
- part.type === 'text' &&
- typeof part.text === 'string' &&
- slash.test(part.text.trimStart().toLowerCase())
- ) {
- return true
- }
- }
- }
-
- return false
-}
-
-/** This session's transcript, wherever it currently lives: the per-runtime
- * mirror ($sessionStates) for any session, falling back to the active view
- * ($messages) for a session whose mirror hasn't populated yet. */
-function sessionTranscript(sessionId: string | null): readonly ChatMessage[] {
- const cached = sessionId ? $sessionStates.get()[sessionId]?.messages : undefined
-
- if (cached?.length) {
- return cached
- }
-
- if (sessionId && sessionId === $activeSessionId.get()) {
- return $messages.get()
- }
-
- return cached ?? []
-}
-
-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 ({ sessionId, 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 = stripSlashTokens(text).toLowerCase()
- const cwd = $currentCwd.get()
- const skills = await loadIndex()
- const matched = skills.filter(skill => skillHit(skill.pattern, haystack) && !collidesWithWorkspace(skill.name, cwd))
-
- if (matched.length === 0) {
- return []
- }
-
- // Transcript scan only for actual matches — the common no-match sample
- // never pays for it.
- const transcript = sessionTranscript(sessionId)
-
- return matched.filter(skill => !skillTouchedInMessages(skill.name, transcript)).map(skill => toSuggestion(skill.name))
-})
diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.json
index 736b3e0deaf..3167e14a7cb 100644
--- a/locales/_keys.desktop.json
+++ b/locales/_keys.desktop.json
@@ -959,11 +959,6 @@
"composer.commandDescs./yolo",
"composer.commonCommands",
"composer.couldNotPreview",
- "composer.cronSuggestions.done",
- "composer.cronSuggestions.doneTip",
- "composer.cronSuggestions.label",
- "composer.cronSuggestions.prefix",
- "composer.cronSuggestions.tip",
"composer.dictating",
"composer.dropFiles",
"composer.dropSession",
@@ -975,10 +970,6 @@
"composer.files",
"composer.folder",
"composer.followUpPlaceholders",
- "composer.githubSuggestions.done",
- "composer.githubSuggestions.doneTip",
- "composer.githubSuggestions.label",
- "composer.githubSuggestions.tip",
"composer.helpFooter",
"composer.hiddenQueued",
"composer.hotkeyDescs.composer.cancel",
@@ -996,13 +987,6 @@
"composer.lookupNoMatches",
"composer.lookupOr",
"composer.lookupTry",
- "composer.mcpSuggestions.added",
- "composer.mcpSuggestions.addedTip",
- "composer.mcpSuggestions.cancelTip",
- "composer.mcpSuggestions.connectFailed",
- "composer.mcpSuggestions.connecting",
- "composer.mcpSuggestions.label",
- "composer.mcpSuggestions.tip",
"composer.message",
"composer.muteMic",
"composer.muted",
@@ -1041,21 +1025,10 @@
"composer.readingAloud",
"composer.redirect",
"composer.removeAttachment",
- "composer.repairSuggestions.done",
- "composer.repairSuggestions.doneTip",
- "composer.repairSuggestions.failed",
- "composer.repairSuggestions.label",
- "composer.repairSuggestions.tip",
- "composer.repairSuggestions.working",
- "composer.repairSuggestions.workingTip",
"composer.restoreImageDraft",
"composer.restoredDraftNotice",
"composer.restoredDraftUndo",
"composer.send",
- "composer.skillSuggestions.done",
- "composer.skillSuggestions.doneTip",
- "composer.skillSuggestions.label",
- "composer.skillSuggestions.tip",
"composer.snippets.codeReview.description",
"composer.snippets.codeReview.label",
"composer.snippets.codeReview.text",