Skip to content

The agent that grows with you

refactor(desktop): give duplicated helpers one owner

Brooklyn Nicholson5a027a0081ec
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-trigger.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-trigger.ts
index fae1d03a313..a6c5c898aff 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-trigger.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-trigger.ts
@@ -36,6 +36,26 @@ import { detectTrigger, textBeforeCaret, type TriggerState } from '../text-utils
* prose off and stranded a partial `folder:` in front of the chip, because the
* window it removed wasn't the token the user was typing.
*/
+/** The keyup half of trigger detection, shared by both composers.
+ *
+ * If the open popover already consumed this key in keydown (Arrow/Enter/Tab/
+ * Escape), skip the refresh: those keys never edit text, and for Escape the
+ * keydown already closed the menu — refreshing here would re-detect the
+ * still-present `/` and instantly reopen it. It reads a ref set during keydown
+ * rather than `trigger`, because by keyup time React has re-rendered and
+ * `trigger` may already be null. */
+export function triggerKeyUpHandler(consumedRef: MutableRefObject<boolean>, refreshTrigger: () => void) {
+ return () => {
+ if (consumedRef.current) {
+ consumedRef.current = false
+
+ return
+ }
+
+ window.setTimeout(refreshTrigger, 0)
+ }
+}
+
export function rebuildAroundCaret(editor: HTMLDivElement, tokenLength: number, insert: DocumentFragment | string) {
const current = composerPlainText(editor)
const caret = caretOffsetInEditor(editor)
diff --git a/apps/desktop/src/app/chat/composer/index.tsx b/apps/desktop/src/app/chat/composer/index.tsx
index c61f81f1fc2..519e6422eb4 100644
--- a/apps/desktop/src/app/chat/composer/index.tsx
+++ b/apps/desktop/src/app/chat/composer/index.tsx
@@ -50,7 +50,7 @@ import { useComposerPlaceholder } from './hooks/use-composer-placeholder'
import { useComposerPopout } from './hooks/use-composer-popout'
import { useComposerQueue } from './hooks/use-composer-queue'
import { useComposerSubmit } from './hooks/use-composer-submit'
-import { useComposerTrigger } from './hooks/use-composer-trigger'
+import { triggerKeyUpHandler, useComposerTrigger } from './hooks/use-composer-trigger'
import { useComposerUndo } from './hooks/use-composer-undo'
import { useComposerUrlDialog } from './hooks/use-composer-url-dialog'
import { useComposerVoice } from './hooks/use-composer-voice'
@@ -904,21 +904,7 @@ export function ChatBar({
}
}
- const handleEditorKeyUp = () => {
- // If this keyup belongs to a key the open trigger popover already consumed
- // in keydown (Arrow/Enter/Tab/Escape), skip the refresh. Those keys never
- // edit text, and for Escape the keydown already closed the menu — a refresh
- // here would re-detect the still-present `/` and instantly reopen it. We
- // read a ref set during keydown rather than `trigger`, because by keyup
- // time React has re-rendered and `trigger` may already be null.
- if (triggerKeyConsumedRef.current) {
- triggerKeyConsumedRef.current = false
-
- return
- }
-
- window.setTimeout(refreshTrigger, 0)
- }
+ const handleEditorKeyUp = triggerKeyUpHandler(triggerKeyConsumedRef, refreshTrigger)
const {
dragActive,
diff --git a/apps/desktop/src/app/command-palette/marketplace-theme-page.tsx b/apps/desktop/src/app/command-palette/marketplace-theme-page.tsx
index 6766b2dae30..1adab907f32 100644
--- a/apps/desktop/src/app/command-palette/marketplace-theme-page.tsx
+++ b/apps/desktop/src/app/command-palette/marketplace-theme-page.tsx
@@ -10,9 +10,11 @@
import { useStore } from '@nanostores/react'
import { useQuery } from '@tanstack/react-query'
-import { useEffect, useState } from 'react'
+import { useState } from 'react'
+import { StatusRow } from '@/app/command-palette/status-row'
import { HUD_ITEM, HUD_TEXT } from '@/app/floating-hud'
+import { useDebounced } from '@/app/hooks/use-debounced'
import type { DesktopMarketplaceSearchItem } from '@/global'
import { useI18n } from '@/i18n'
import { triggerHaptic } from '@/lib/haptics'
@@ -23,18 +25,6 @@ import { $marketplaceInstalls } from '@/themes/user-themes'
const compactNumber = new Intl.NumberFormat(undefined, { notation: 'compact', maximumFractionDigits: 1 })
-function useDebounced<T>(value: T, delayMs: number): T {
- const [debounced, setDebounced] = useState(value)
-
- useEffect(() => {
- const handle = setTimeout(() => setDebounced(value), delayMs)
-
- return () => clearTimeout(handle)
- }, [value, delayMs])
-
- return debounced
-}
-
interface MarketplaceThemePageProps {
search: string
/** Activate a freshly installed theme by slug. */
@@ -90,17 +80,17 @@ export function MarketplaceThemePage({ search, onPickTheme }: MarketplaceThemePa
}
if (query.isLoading) {
- return <Status icon={<Loader2 className="size-3.5 animate-spin" />} text={copy.loading} />
+ return <StatusRow icon={<Loader2 className="size-3.5 animate-spin" />} text={copy.loading} />
}
if (query.isError) {
- return <Status text={copy.error} tone="error" />
+ return <StatusRow text={copy.error} tone="error" />
}
const results = query.data ?? []
if (results.length === 0) {
- return <Status text={copy.empty} />
+ return <StatusRow text={copy.empty} />
}
return (
@@ -156,17 +146,3 @@ export function MarketplaceThemePage({ search, onPickTheme }: MarketplaceThemePa
</div>
)
}
-
-function Status({ icon, text, tone }: { icon?: React.ReactNode; text: string; tone?: 'error' }) {
- return (
- <div
- className={cn(
- 'flex items-center justify-center gap-2 px-2 py-6 text-xs',
- tone === 'error' ? 'text-(--ui-red)' : 'text-muted-foreground'
- )}
- >
- {icon}
- {text}
- </div>
- )
-}
diff --git a/apps/desktop/src/app/command-palette/pet-palette-page.tsx b/apps/desktop/src/app/command-palette/pet-palette-page.tsx
index 241bb433126..b23157f5d48 100644
--- a/apps/desktop/src/app/command-palette/pet-palette-page.tsx
+++ b/apps/desktop/src/app/command-palette/pet-palette-page.tsx
@@ -10,6 +10,7 @@
import { useStore } from '@nanostores/react'
import { useEffect, useMemo } from 'react'
+import { StatusRow } from '@/app/command-palette/status-row'
import { HUD_ITEM, HUD_TEXT } from '@/app/floating-hud'
import { useGatewayRequest } from '@/app/gateway/hooks/use-gateway-request'
import { PetThumb } from '@/components/pet/pet-thumb'
@@ -59,15 +60,15 @@ export function PetPalettePage({ search, onGenerate }: PetPalettePageProps) {
}
if (status === 'loading' && !gallery) {
- return <Status icon={<Loader2 className="size-3.5 animate-spin" />} text={copy.loading} />
+ return <StatusRow icon={<Loader2 className="size-3.5 animate-spin" />} text={copy.loading} />
}
if (status === 'stale') {
- return <Status text={copy.staleBackend} tone="error" />
+ return <StatusRow text={copy.staleBackend} tone="error" />
}
if (!gallery?.pets.length && error) {
- return <Status text={error} tone="error" />
+ return <StatusRow text={error} tone="error" />
}
const mutating = Boolean(busy)
@@ -95,7 +96,7 @@ export function PetPalettePage({ search, onGenerate }: PetPalettePageProps) {
{error && <p className="px-2 pb-1 pt-1.5 text-[0.6875rem] text-(--ui-red)">{error}</p>}
{shown.length === 0 ? (
- <Status text={copy.empty} />
+ <StatusRow text={copy.empty} />
) : (
shown.map(pet => {
const isActive = enabled && pet.slug === active
@@ -198,17 +199,3 @@ export function PetInlineToggle() {
</button>
)
}
-
-function Status({ icon, text, tone }: { icon?: React.ReactNode; text: string; tone?: 'error' }) {
- return (
- <div
- className={cn(
- 'flex items-center justify-center gap-2 px-2 py-6 text-xs',
- tone === 'error' ? 'text-(--ui-red)' : 'text-muted-foreground'
- )}
- >
- {icon}
- {text}
- </div>
- )
-}
diff --git a/apps/desktop/src/app/command-palette/status-row.tsx b/apps/desktop/src/app/command-palette/status-row.tsx
new file mode 100644
index 00000000000..2fad2de52fb
--- /dev/null
+++ b/apps/desktop/src/app/command-palette/status-row.tsx
@@ -0,0 +1,18 @@
+import type React from 'react'
+
+import { cn } from '@/lib/utils'
+
+/** Centered loading / empty / error row for a Cmd-K page's result list. */
+export function StatusRow({ icon, text, tone }: { icon?: React.ReactNode; text: string; tone?: 'error' }) {
+ return (
+ <div
+ className={cn(
+ 'flex items-center justify-center gap-2 px-2 py-6 text-xs',
+ tone === 'error' ? 'text-(--ui-red)' : 'text-muted-foreground'
+ )}
+ >
+ {icon}
+ {text}
+ </div>
+ )
+}
diff --git a/apps/desktop/src/app/contrib/mcp-install-deeplink-dialog.tsx b/apps/desktop/src/app/contrib/mcp-install-deeplink-dialog.tsx
index aa4b1b3cab3..a657c986879 100644
--- a/apps/desktop/src/app/contrib/mcp-install-deeplink-dialog.tsx
+++ b/apps/desktop/src/app/contrib/mcp-install-deeplink-dialog.tsx
@@ -16,19 +16,12 @@ import { getHermesConfigRecord, saveMcpServers } from '@/hermes'
import { useI18n } from '@/i18n'
import { AlertTriangle } from '@/lib/icons'
import { MCP_DEEPLINK_NAME_RE } from '@/lib/mcp-deeplink'
+import { getServers } from '@/lib/mcp-servers'
import { $mcpInstallRequest } from '@/store/mcp-deeplink-install'
import { notify, readableError } from '@/store/notifications'
import { setHermesConfigCache } from '../hooks/use-config-record'
-type McpServers = Record<string, Record<string, unknown>>
-
-const getServers = (config: { mcp_servers?: unknown } | null): McpServers => {
- const raw = config?.mcp_servers
-
- return raw && typeof raw === 'object' && !Array.isArray(raw) ? (raw as McpServers) : {}
-}
-
/**
* Explicit-confirm gate for `hermes://mcp/install` deep links. The payload is
* arbitrary attacker-controllable input (any web page can open the link), so
diff --git a/apps/desktop/src/app/settings/appearance-settings.tsx b/apps/desktop/src/app/settings/appearance-settings.tsx
index b84debd6068..c401bea383c 100644
--- a/apps/desktop/src/app/settings/appearance-settings.tsx
+++ b/apps/desktop/src/app/settings/appearance-settings.tsx
@@ -2,6 +2,7 @@ import { useStore } from '@nanostores/react'
import { useQuery } from '@tanstack/react-query'
import { useEffect, useState } from 'react'
+import { useDebounced } from '@/app/hooks/use-debounced'
import { LanguageSwitcher } from '@/components/language-switcher'
import { Button } from '@/components/ui/button'
import { SegmentedControl } from '@/components/ui/segmented-control'
@@ -102,18 +103,6 @@ function matchUiScalePreset(percent: number): UiScalePreset | null {
return UI_SCALE_PRESETS.find(preset => Number(preset) === percent) ?? null
}
-function useDebounced<T>(value: T, delayMs: number): T {
- const [debounced, setDebounced] = useState(value)
-
- useEffect(() => {
- const handle = setTimeout(() => setDebounced(value), delayMs)
-
- return () => clearTimeout(handle)
- }, [value, delayMs])
-
- return debounced
-}
-
const compactNumber = new Intl.NumberFormat(undefined, { notation: 'compact', maximumFractionDigits: 1 })
/**
diff --git a/apps/desktop/src/app/skills/mcp-tab.tsx b/apps/desktop/src/app/skills/mcp-tab.tsx
index 78b5d74937e..93088c62582 100644
--- a/apps/desktop/src/app/skills/mcp-tab.tsx
+++ b/apps/desktop/src/app/skills/mcp-tab.tsx
@@ -38,12 +38,12 @@ import { estimateServerTokens, serverUsageCount } from '@/lib/mcp-cost'
import { completeMcpDesktopOAuth } from '@/lib/mcp-dashboard-oauth'
import { type McpImportEntry, parseMcpImport } from '@/lib/mcp-import'
import { NEEDS_AUTH_RE, PROBE_TTL_MS, probeCache, probeKey, serverFingerprint } from '@/lib/mcp-probe-cache'
+import { getServers, isServerShape, type McpServers, normalizeEntry } from '@/lib/mcp-servers'
import { countEnabledTools, isToolEnabled, toggleToolInServer } from '@/lib/mcp-tool-filter'
import { cn } from '@/lib/utils'
import { notify, notifyError } from '@/store/notifications'
import { $activeGatewayProfile, normalizeProfileKey } from '@/store/profile'
import { $activeSessionId } from '@/store/session'
-import type { HermesConfigRecord } from '@/types/hermes'
import { hermesConfigCacheWriter, useHermesConfigRecord } from '../hooks/use-config-record'
import { useOnProfileSwitch } from '../hooks/use-on-profile-switch'
@@ -52,8 +52,6 @@ import { PanelAddButton, PanelEmpty } from '../overlays/panel'
import { prettyName } from '../settings/helpers'
import { useDeepLinkHighlight } from '../settings/use-deep-link-highlight'
-type McpServers = Record<string, Record<string, unknown>>
-
// The editor always speaks the ecosystem's mcp.json document format — names
// are the JSON keys, transport is inferred from `command` vs `url` — so any
// README's "add this to your mcp.json" snippet pastes verbatim. Storage stays
@@ -63,21 +61,6 @@ const STARTER_ENTRY = { command: 'npx', args: ['-y', '@modelcontextprotocol/serv
const pretty = (value: unknown) => JSON.stringify(value, null, 2)
const wrapDoc = (entries: McpServers) => pretty({ mcpServers: entries })
-const isServerShape = (value: Record<string, unknown>) =>
- typeof value.command === 'string' || typeof value.url === 'string'
-
-// Cursor/Claude write `type`; Hermes reads `transport`. Normalize on the way
-// in so pasted configs behave identically under the CLI/TUI loader.
-function normalizeEntry(entry: Record<string, unknown>): Record<string, unknown> {
- if (typeof entry.type === 'string' && entry.transport === undefined) {
- const { type, ...rest } = entry
-
- return { ...rest, transport: type }
- }
-
- return entry
-}
-
/** Accepts `{"mcpServers": {...}}` (ecosystem), a bare name→config map, or throws. */
function parseServersDoc(raw: string): McpServers {
const parsed = JSON.parse(raw) as unknown
@@ -100,12 +83,6 @@ function parseServersDoc(raw: string): McpServers {
return Object.fromEntries(Object.entries(map).map(([name, entry]) => [name, normalizeEntry(entry)]))
}
-function getServers(config: HermesConfigRecord | null): McpServers {
- const raw = config?.mcp_servers
-
- return raw && typeof raw === 'object' && !Array.isArray(raw) ? (raw as McpServers) : {}
-}
-
// The runtime gate is `enabled: false` — the same flag `hermes mcp` and the
// agent's MCP loader read.
const serverEnabled = (server: Record<string, unknown>) => server.enabled !== false
diff --git a/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx b/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx
index b29715f98b9..d9bf458c80c 100644
--- a/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx
@@ -24,7 +24,7 @@ import {
releaseActiveComposer
} from '@/app/chat/composer/focus'
import { useAtCompletions } from '@/app/chat/composer/hooks/use-at-completions'
-import { rebuildAroundCaret } from '@/app/chat/composer/hooks/use-composer-trigger'
+import { rebuildAroundCaret, triggerKeyUpHandler } from '@/app/chat/composer/hooks/use-composer-trigger'
import { useComposerUndo } from '@/app/chat/composer/hooks/use-composer-undo'
import { useEmojiCompletions } from '@/app/chat/composer/hooks/use-emoji-completions'
import { useSlashCompletions } from '@/app/chat/composer/hooks/use-slash-completions'
@@ -760,21 +760,7 @@ export const UserEditComposer: FC<UserEditComposerProps> = ({ cwd, gateway, sess
}
}
- const handleKeyUp = () => {
- // If this keyup belongs to a key the open trigger popover already consumed
- // in keydown (Arrow/Enter/Tab/Escape), skip the refresh. Those keys never
- // edit text, and for Escape the keydown already closed the menu — a refresh
- // here would re-detect the still-present `/` and instantly reopen it. We
- // read a ref set during keydown rather than `trigger`, because by keyup
- // time React has re-rendered and `trigger` may already be null.
- if (triggerKeyConsumedRef.current) {
- triggerKeyConsumedRef.current = false
-
- return
- }
-
- window.setTimeout(refreshTrigger, 0)
- }
+ const handleKeyUp = triggerKeyUpHandler(triggerKeyConsumedRef, refreshTrigger)
return (
<ComposerPrimitive.Root className="contents" data-slot="aui_edit-composer-root">
diff --git a/apps/desktop/src/components/assistant-ui/tool/delegate-model.ts b/apps/desktop/src/components/assistant-ui/tool/delegate-model.ts
index eff61ec17d4..694c34d7526 100644
--- a/apps/desktop/src/components/assistant-ui/tool/delegate-model.ts
+++ b/apps/desktop/src/components/assistant-ui/tool/delegate-model.ts
@@ -1,7 +1,7 @@
-import { normalize } from '@/lib/text'
+import { firstStringField, normalize } from '@/lib/text'
import type { SubagentProgress, SubagentStatus } from '@/store/subagents'
-import { firstStringField, numberValue, parseMaybeObject } from './fallback-model'
+import { numberValue, parseMaybeObject } from './fallback-model'
/**
* A delegation runs somewhere the transcript can't see: the tool call carries
diff --git a/apps/desktop/src/components/assistant-ui/tool/fallback-model/index.ts b/apps/desktop/src/components/assistant-ui/tool/fallback-model/index.ts
index 2a21657f68e..4ea420732e4 100644
--- a/apps/desktop/src/components/assistant-ui/tool/fallback-model/index.ts
+++ b/apps/desktop/src/components/assistant-ui/tool/fallback-model/index.ts
@@ -1,7 +1,7 @@
import { type ToolTitleKey, translateNow } from '@/i18n'
import { normalizeExternalUrl } from '@/lib/external-link'
import { summarizeShellCommand } from '@/lib/summarize-command'
-import { capitalize, normalize } from '@/lib/text'
+import { capitalize, firstStringField, normalize } from '@/lib/text'
import { isCardTool, isFileEditTool, isSilentTool } from '@/lib/tool-render-class'
import { extractToolErrorMessage, formatToolResultSummary } from '@/lib/tool-result-summary'
@@ -595,18 +595,6 @@ function summarizeBrowserSnapshot(snapshot: string): string {
return labels.length ? `${stats}\nTop controls: ${labels.join(', ')}` : stats
}
-export function firstStringField(record: Record<string, unknown>, keys: readonly string[]): string {
- for (const key of keys) {
- const value = record[key]
-
- if (typeof value === 'string' && value.trim()) {
- return value.trim()
- }
- }
-
- return ''
-}
-
function collectResultItems(value: unknown): unknown[] {
if (Array.isArray(value)) {
return value
diff --git a/apps/desktop/src/components/assistant-ui/tool/run-summary.ts b/apps/desktop/src/components/assistant-ui/tool/run-summary.ts
index 6abf559a33f..7693e67ed60 100644
--- a/apps/desktop/src/components/assistant-ui/tool/run-summary.ts
+++ b/apps/desktop/src/components/assistant-ui/tool/run-summary.ts
@@ -1,6 +1,7 @@
import { summarizeShellCommand } from '@/lib/summarize-command'
+import { firstStringField } from '@/lib/text'
-import { fileEditBasename, firstStringField, isFileEditTool, parseMaybeObject } from './fallback-model'
+import { fileEditBasename, isFileEditTool, parseMaybeObject } from './fallback-model'
/**
* The little a summary needs from a tool call, stated structurally so both
diff --git a/apps/desktop/src/components/gateway-connecting-overlay.tsx b/apps/desktop/src/components/gateway-connecting-overlay.tsx
index 34303bb52cf..dcc24c64d86 100644
--- a/apps/desktop/src/components/gateway-connecting-overlay.tsx
+++ b/apps/desktop/src/components/gateway-connecting-overlay.tsx
@@ -2,6 +2,7 @@ import { useStore } from '@nanostores/react'
import { useEffect, useRef, useState } from 'react'
import { DecodeText } from '@/components/ui/decode-text'
+import { prefersReducedMotion } from '@/hooks/use-media-query'
import { cn } from '@/lib/utils'
import { $desktopBoot } from '@/store/boot'
import { $gatewaySwitching } from '@/store/gateway-switch'
@@ -35,10 +36,6 @@ function forcedPreview(): boolean {
}
}
-function prefersReducedMotion(): boolean {
- return typeof window !== 'undefined' && Boolean(window.matchMedia?.('(prefers-reduced-motion: reduce)').matches)
-}
-
export function GatewayConnectingOverlay() {
const gatewayState = useStore($gatewayState)
const boot = useStore($desktopBoot)
diff --git a/apps/desktop/src/components/pane-shell/tree/renderer/edit-bar.tsx b/apps/desktop/src/components/pane-shell/tree/renderer/edit-bar.tsx
index 56e5c66e22e..854229c8f84 100644
--- a/apps/desktop/src/components/pane-shell/tree/renderer/edit-bar.tsx
+++ b/apps/desktop/src/components/pane-shell/tree/renderer/edit-bar.tsx
@@ -11,6 +11,7 @@ import { type PointerEvent as ReactPointerEvent, useCallback, useRef, useState }
import { Button } from '@/components/ui/button'
import { useI18n } from '@/i18n'
import { formatCombo } from '@/lib/keybinds/combo'
+import { startPointerDrag } from '@/lib/pointer-drag'
import { $bindings, bindingsFor } from '@/store/keybinds'
import { $layoutEditMode } from '../../edit-mode'
@@ -61,13 +62,7 @@ export function TreeEditBar() {
setPos(next)
}
- const onUp = () => {
- window.removeEventListener('pointermove', onMove, true)
- window.removeEventListener('pointerup', onUp, true)
- }
-
- window.addEventListener('pointermove', onMove, true)
- window.addEventListener('pointerup', onUp, true)
+ startPointerDrag(onMove)
}, [])
if (!editMode) {
diff --git a/apps/desktop/src/components/pane-shell/tree/zone-editor.tsx b/apps/desktop/src/components/pane-shell/tree/zone-editor.tsx
index 74a269463e8..fe40ca2c8bb 100644
--- a/apps/desktop/src/components/pane-shell/tree/zone-editor.tsx
+++ b/apps/desktop/src/components/pane-shell/tree/zone-editor.tsx
@@ -25,6 +25,7 @@ import { Input } from '@/components/ui/input'
import { registry } from '@/contrib/registry'
import { useI18n } from '@/i18n'
import { ESCAPE_PRIORITY, isTopEscapeLayer, pushEscapeLayer } from '@/lib/escape-layers'
+import { startPointerDrag } from '@/lib/pointer-drag'
import { cn } from '@/lib/utils'
import {
@@ -214,9 +215,7 @@ export function ZoneEditor() {
setSelection(mergeClosureIndices(model, picked))
}
- const onUp = (ev: PointerEvent) => {
- window.removeEventListener('pointermove', onMove, true)
- window.removeEventListener('pointerup', onUp, true)
+ startPointerDrag(onMove, ev => {
setSelectBox(null)
if (!dragged) {
@@ -233,10 +232,7 @@ export function ZoneEditor() {
const rect = canvasRef.current!.getBoundingClientRect()
setMergeAt({ x: ev.clientX - rect.x, y: ev.clientY - rect.y })
- }
-
- window.addEventListener('pointermove', onMove, true)
- window.addEventListener('pointerup', onUp, true)
+ })
}
const startResizerDrag = (index: number, e: ReactPointerEvent<HTMLDivElement>) => {
@@ -267,13 +263,7 @@ export function ZoneEditor() {
}
}
- const onUp = () => {
- window.removeEventListener('pointermove', onMove, true)
- window.removeEventListener('pointerup', onUp, true)
- }
-
- window.addEventListener('pointermove', onMove, true)
- window.addEventListener('pointerup', onUp, true)
+ startPointerDrag(onMove)
}
const merge = () => {
diff --git a/apps/desktop/src/components/ui/decode-text.tsx b/apps/desktop/src/components/ui/decode-text.tsx
index 243de60f620..edd91641a66 100644
--- a/apps/desktop/src/components/ui/decode-text.tsx
+++ b/apps/desktop/src/components/ui/decode-text.tsx
@@ -1,5 +1,6 @@
import { type ComponentProps, useEffect, useState } from 'react'
+import { prefersReducedMotion } from '@/hooks/use-media-query'
import { cn } from '@/lib/utils'
/**
@@ -23,10 +24,6 @@ export const DECODE_SCRAMBLE_CHARS = '/\\|-_=+<>~:*'
const TICK_MS = 45
const HOLD_TICKS = 16
-function prefersReducedMotion(): boolean {
- return typeof window !== 'undefined' && Boolean(window.matchMedia?.('(prefers-reduced-motion: reduce)').matches)
-}
-
function scrambled(tail: string, resolvedCount: number): string {
return Array.from(tail, (ch, i) =>
ch === ' ' || i < resolvedCount ? ch : DECODE_SCRAMBLE_CHARS[(Math.random() * DECODE_SCRAMBLE_CHARS.length) | 0]
diff --git a/apps/desktop/src/hooks/use-media-query.ts b/apps/desktop/src/hooks/use-media-query.ts
index aa368dfb931..219715811da 100644
--- a/apps/desktop/src/hooks/use-media-query.ts
+++ b/apps/desktop/src/hooks/use-media-query.ts
@@ -3,6 +3,10 @@ import { useEffect, useState } from 'react'
export const matchesQuery = (query: string) =>
typeof window !== 'undefined' && !!window.matchMedia && window.matchMedia(query).matches
+/** Read at call time, not render time: animations check this as they start, and
+ * the OS setting can flip mid-session. */
+export const prefersReducedMotion = () => matchesQuery('(prefers-reduced-motion: reduce)')
+
export function useMediaQuery(query: string): boolean {
const [matches, setMatches] = useState(() => matchesQuery(query))
diff --git a/apps/desktop/src/lib/audio-context.ts b/apps/desktop/src/lib/audio-context.ts
new file mode 100644
index 00000000000..a506399c2de
--- /dev/null
+++ b/apps/desktop/src/lib/audio-context.ts
@@ -0,0 +1,37 @@
+// One lazily-created AudioContext for the app's synthesized UI cues (wake
+// chime, turn-completion sound, thinking blips). Browsers cap how many
+// contexts a page may open, and these cues are short oscillator bursts that
+// need no isolation from each other, so they share one instead of each holding
+// its own. Nothing closes it — it lives for the window.
+
+let ctx: AudioContext | null = null
+
+/** The shared AudioContext, or null where WebAudio is unavailable. */
+export function getAudioContext(): AudioContext | null {
+ if (typeof window === 'undefined') {
+ return null
+ }
+
+ try {
+ if (!ctx) {
+ const Ctor =
+ window.AudioContext || (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext
+
+ if (!Ctor) {
+ return null
+ }
+
+ ctx = new Ctor()
+ }
+
+ // Autoplay policies can leave the context suspended until a gesture; a
+ // resume() here recovers it once the user has interacted with the window.
+ if (ctx.state === 'suspended') {
+ void ctx.resume().catch(() => undefined)
+ }
+
+ return ctx
+ } catch {
+ return null
+ }
+}
diff --git a/apps/desktop/src/lib/completion-sound.ts b/apps/desktop/src/lib/completion-sound.ts
index 1557c58e419..6245c10723e 100644
--- a/apps/desktop/src/lib/completion-sound.ts
+++ b/apps/desktop/src/lib/completion-sound.ts
@@ -1,43 +1,13 @@
// Completion sound bank for agent turn-end cues.
// Fourteen curated presets for A/B in Settings → Appearance. Default is variant 1.
+import { getAudioContext } from '@/lib/audio-context'
import { ownsAmbientCue } from '@/store/ambient'
import { $completionSoundVariantId, resolveCompletionSoundVariantId } from '@/store/completion-sound'
import { $hapticsMuted } from '@/store/haptics'
type OscType = OscillatorType
-let ctx: AudioContext | null = null
-
-function getCtx(): AudioContext | null {
- if (typeof window === 'undefined') {
- return null
- }
-
- try {
- if (!ctx) {
- const Ctor =
- window.AudioContext || (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext
-
- if (!Ctor) {
- return null
- }
-
- ctx = new Ctor()
- }
-
- // Autoplay policies can leave the context suspended until a gesture; a
- // resume() here recovers it once the user has interacted with the window.
- if (ctx.state === 'suspended') {
- void ctx.resume().catch(() => undefined)
- }
-
- return ctx
- } catch {
- return null
- }
-}
-
// One enveloped oscillator voice → master. Linear attack into an exponential
// decay keeps the tail smooth and avoids the click you get ramping to zero.
function voice(ac: AudioContext, master: GainNode, t0: number, spec: ToneSpec) {
@@ -417,7 +387,7 @@ function playVariant(variantId: number) {
return
}
- const ac = getCtx()
+ const ac = getAudioContext()
if (!ac) {
return
diff --git a/apps/desktop/src/lib/desktop-git.ts b/apps/desktop/src/lib/desktop-git.ts
index 0009900b722..98f41fbf87e 100644
--- a/apps/desktop/src/lib/desktop-git.ts
+++ b/apps/desktop/src/lib/desktop-git.ts
@@ -115,20 +115,3 @@ export function desktopGit(): GitBridge | undefined {
return isDesktopFsRemoteMode() ? remoteGit : window.hermesDesktop?.git
}
-
-// True only for "the /api/git route does not exist on this backend" shapes:
-// the backend catch-all ('404: {"detail":"No such API endpoint: ...}'), a bare
-// FastAPI 404 (directly or through the IPC bridge's "Error invoking remote
-// method" wrapper), and the Electron JSON-guard ("endpoint is likely
-// missing"). Transient failures (timeouts, 5xx, connection refused) must NOT
-// match — they are retryable, not a capability verdict. Mirrors the sidebar
-// batch-endpoint detector in hermes.ts.
-export function isGitEndpointMissingError(err: unknown): boolean {
- const message = err instanceof Error ? err.message : String(err)
-
- return (
- /no such api endpoint/i.test(message) ||
- /endpoint is likely missing/i.test(message) ||
- /(?:^\s*|error:\s*)404\b/i.test(message)
- )
-}
diff --git a/apps/desktop/src/lib/gateway-rpc.ts b/apps/desktop/src/lib/gateway-rpc.ts
index 372cf0bc496..1b52ef1f331 100644
--- a/apps/desktop/src/lib/gateway-rpc.ts
+++ b/apps/desktop/src/lib/gateway-rpc.ts
@@ -5,6 +5,24 @@ export function isMissingRpcMethod(error: unknown): boolean {
return /method not found|-32601|unknown method|no such method/i.test(message)
}
+/** REST twin of isMissingRpcMethod: the route does not exist on this backend.
+ * Matches the backend catch-all ('404: {"detail":"No such API endpoint: …}'),
+ * FastAPI's bare 404 on headless serve — directly, or wrapped as "Error
+ * invoking remote method 'hermes:api': Error: 404: …" through the IPC bridge
+ * — and the Electron JSON-guard ("endpoint is likely missing"). Transient
+ * failures (timeouts, 5xx, connection refused) must NOT match: they are
+ * retryable, not a capability verdict. Only sound for calls where a 404 can
+ * mean nothing else — a route with path params can 404 on a bad id. */
+export function isMissingRestEndpoint(error: unknown): boolean {
+ const message = error instanceof Error ? error.message : String(error)
+
+ return (
+ /no such api endpoint/i.test(message) ||
+ /endpoint is likely missing/i.test(message) ||
+ /(?:^\s*|error:\s*)404\b/i.test(message)
+ )
+}
+
/** True when a prompt response raced a backend-side timeout / completion. */
export function isMissingPendingPromptRequest(error: unknown, key: string): boolean {
const message = error instanceof Error ? error.message : String(error)
diff --git a/apps/desktop/src/lib/keyed-timeouts.ts b/apps/desktop/src/lib/keyed-timeouts.ts
new file mode 100644
index 00000000000..fc3208cb927
--- /dev/null
+++ b/apps/desktop/src/lib/keyed-timeouts.ts
@@ -0,0 +1,29 @@
+/** Per-key setTimeout registry for "let this linger, then drop it" UI state.
+ * Scheduling a key replaces its pending timer, and an entry removes itself
+ * when it fires, so the map never accumulates dead keys. */
+export function keyedTimeouts() {
+ const timers = new Map<string, ReturnType<typeof setTimeout>>()
+
+ const cancel = (key: string) => {
+ const timer = timers.get(key)
+
+ if (timer !== undefined) {
+ clearTimeout(timer)
+ timers.delete(key)
+ }
+ }
+
+ return {
+ cancel,
+ schedule(key: string, delayMs: number, run: () => void) {
+ cancel(key)
+ timers.set(
+ key,
+ setTimeout(() => {
+ timers.delete(key)
+ run()
+ }, delayMs)
+ )
+ }
+ }
+}
diff --git a/apps/desktop/src/lib/mcp-import.ts b/apps/desktop/src/lib/mcp-import.ts
index 7b83460b01d..7437c375ea6 100644
--- a/apps/desktop/src/lib/mcp-import.ts
+++ b/apps/desktop/src/lib/mcp-import.ts
@@ -4,6 +4,8 @@
// entries. Pure and side-effect free; the MCP tab merges the result into the
// editor draft. Returns null when nothing recognizable is in the text.
+import { isServerShape, normalizeEntry } from '@/lib/mcp-servers'
+
export interface McpImportEntry {
config: Record<string, unknown>
name: string
@@ -12,21 +14,6 @@ export interface McpImportEntry {
const isRecord = (value: unknown): value is Record<string, unknown> =>
!!value && typeof value === 'object' && !Array.isArray(value)
-const isServerShape = (value: Record<string, unknown>) =>
- typeof value.command === 'string' || typeof value.url === 'string'
-
-// Cursor/Claude write `type`; Hermes reads `transport` (same normalization the
-// MCP tab applies to pasted JSON).
-function normalizeEntry(entry: Record<string, unknown>): Record<string, unknown> {
- if (typeof entry.type === 'string' && entry.transport === undefined) {
- const { type, ...rest } = entry
-
- return { ...rest, transport: type }
- }
-
- return entry
-}
-
const URL_RE = /^https?:\/\/\S+$/i
// "mcp.linear.app" → "linear": drop generic front labels, keep the brand one.
diff --git a/apps/desktop/src/lib/mcp-servers.ts b/apps/desktop/src/lib/mcp-servers.ts
new file mode 100644
index 00000000000..38bf9046bc6
--- /dev/null
+++ b/apps/desktop/src/lib/mcp-servers.ts
@@ -0,0 +1,29 @@
+// Shape helpers for the `mcp_servers` config map, shared by everything that
+// reads or writes it: the MCP tab editor, the paste-anything importer, and the
+// `hermes://mcp/install` deeplink dialog. These agree on what a server entry
+// looks like, so they belong in one place — a config written by one path has to
+// be readable by the others.
+
+export type McpServers = Record<string, Record<string, unknown>>
+
+export const isServerShape = (value: Record<string, unknown>) =>
+ typeof value.command === 'string' || typeof value.url === 'string'
+
+/** Cursor/Claude write `type`; Hermes reads `transport`. Normalizing on the way
+ * in makes pasted configs behave identically under the CLI/TUI loader. */
+export function normalizeEntry(entry: Record<string, unknown>): Record<string, unknown> {
+ if (typeof entry.type === 'string' && entry.transport === undefined) {
+ const { type, ...rest } = entry
+
+ return { ...rest, transport: type }
+ }
+
+ return entry
+}
+
+/** The `mcp_servers` map out of a config record, or `{}` when absent/malformed. */
+export function getServers(config: { mcp_servers?: unknown } | null): McpServers {
+ const raw = config?.mcp_servers
+
+ return raw && typeof raw === 'object' && !Array.isArray(raw) ? (raw as McpServers) : {}
+}
diff --git a/apps/desktop/src/lib/pointer-drag.ts b/apps/desktop/src/lib/pointer-drag.ts
new file mode 100644
index 00000000000..43ae8aa5a04
--- /dev/null
+++ b/apps/desktop/src/lib/pointer-drag.ts
@@ -0,0 +1,26 @@
+/** Run a pointer drag until pointerup, then unbind both listeners.
+ *
+ * Capture-phase, on `window`, so the drag keeps tracking when the pointer
+ * leaves the element it started on. Forgetting one half of the teardown leaks
+ * a live pointermove handler for the rest of the session, which is why the
+ * unbinding lives here rather than at each call site. */
+export function startPointerDrag(
+ onMove: (event: PointerEvent) => void,
+ onEnd?: (event: PointerEvent) => void
+): () => void {
+ const move = (event: PointerEvent) => onMove(event)
+
+ const up = (event: PointerEvent) => {
+ window.removeEventListener('pointermove', move, true)
+ window.removeEventListener('pointerup', up, true)
+ onEnd?.(event)
+ }
+
+ window.addEventListener('pointermove', move, true)
+ window.addEventListener('pointerup', up, true)
+
+ return () => {
+ window.removeEventListener('pointermove', move, true)
+ window.removeEventListener('pointerup', up, true)
+ }
+}
diff --git a/apps/desktop/src/lib/text.ts b/apps/desktop/src/lib/text.ts
index 815a5d731dc..eecb0cc715d 100644
--- a/apps/desktop/src/lib/text.ts
+++ b/apps/desktop/src/lib/text.ts
@@ -13,3 +13,17 @@ export const normalize = (v: unknown): string => asText(v).trim().toLowerCase()
/** Uppercase the first character, leave the rest. Matches the
* `s.charAt(0).toUpperCase() + s.slice(1)` idiom (empty-safe). */
export const capitalize = (v: string): string => (v ? v.charAt(0).toUpperCase() + v.slice(1) : v)
+
+/** First non-empty string among `keys`, trimmed. For reading tool args and
+ * results, where the key carrying the interesting value varies by tool. */
+export const firstStringField = (record: Record<string, unknown>, keys: readonly string[]): string => {
+ for (const key of keys) {
+ const value = record[key]
+
+ if (typeof value === 'string' && value.trim()) {
+ return value.trim()
+ }
+ }
+
+ return ''
+}
diff --git a/apps/desktop/src/lib/thinking-sound.ts b/apps/desktop/src/lib/thinking-sound.ts
index 6a4d2bd6da8..6d78dc50fea 100644
--- a/apps/desktop/src/lib/thinking-sound.ts
+++ b/apps/desktop/src/lib/thinking-sound.ts
@@ -11,40 +11,13 @@
// stopThinkingSound() — callers fire it the moment TTS starts, the mic re-arms,
// or the conversation ends.
+import { getAudioContext } from '@/lib/audio-context'
import { $hapticsMuted } from '@/store/haptics'
import { $thinkingSoundEnabled } from '@/store/voice-prefs'
-let ctx: AudioContext | null = null
let timer: number | null = null
let blipIndex = 0
-function getCtx(): AudioContext | null {
- if (typeof window === 'undefined') {
- return null
- }
-
- try {
- if (!ctx) {
- const Ctor =
- window.AudioContext || (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext
-
- if (!Ctor) {
- return null
- }
-
- ctx = new Ctor()
- }
-
- if (ctx.state === 'suspended') {
- void ctx.resume().catch(() => undefined)
- }
-
- return ctx
- } catch {
- return null
- }
-}
-
// One soft "blub": short sine with a gentle downward pitch glide and a smooth
// attack into an exponential decay — no clicks, deliberately quiet.
function blub(ac: AudioContext, freq: number) {
@@ -79,7 +52,7 @@ export function startThinkingSound(): void {
const tick = () => {
if ($hapticsMuted.get() === false) {
- const ac = getCtx()
+ const ac = getAudioContext()
if (ac) {
try {
diff --git a/apps/desktop/src/lib/wake-sound.ts b/apps/desktop/src/lib/wake-sound.ts
index 3eb9f1c0d86..acd61a267c7 100644
--- a/apps/desktop/src/lib/wake-sound.ts
+++ b/apps/desktop/src/lib/wake-sound.ts
@@ -5,39 +5,9 @@
// the completion cue settles (done). Reuses the same lightweight WebAudio
// synthesis approach — no asset file to ship.
+import { getAudioContext } from '@/lib/audio-context'
import { $hapticsMuted } from '@/store/haptics'
-let ctx: AudioContext | null = null
-
-function getCtx(): AudioContext | null {
- if (typeof window === 'undefined') {
- return null
- }
-
- try {
- if (!ctx) {
- const Ctor =
- window.AudioContext || (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext
-
- if (!Ctor) {
- return null
- }
-
- ctx = new Ctor()
- }
-
- // Autoplay policies can leave the context suspended until a gesture; a
- // resume() here recovers it once the user has interacted with the window.
- if (ctx.state === 'suspended') {
- void ctx.resume().catch(() => undefined)
- }
-
- return ctx
- } catch {
- return null
- }
-}
-
// One enveloped sine voice → master. Linear-ish attack into an exponential
// decay keeps the tail smooth and avoids the click you get ramping to zero.
function ding(ac: AudioContext, master: GainNode, t0: number, freq: number, dur: number, gain: number) {
@@ -66,7 +36,7 @@ export function playWakeSound(): void {
return
}
- const ac = getCtx()
+ const ac = getAudioContext()
if (!ac) {
return
diff --git a/apps/desktop/src/store/data-url-read-max.ts b/apps/desktop/src/store/data-url-read-max.ts
index b37556d3fd6..e95dfb61afd 100644
--- a/apps/desktop/src/store/data-url-read-max.ts
+++ b/apps/desktop/src/store/data-url-read-max.ts
@@ -2,28 +2,21 @@
* Max size for local files Desktop loads as data URLs (composer attach, image
* previews, etc.). Main owns the real cap + its JSON under userData — this
* atom only mirrors it for Settings → Chat. See electron/main.ts
- * (`hermes:data-url-read-max:*`) and the default/clamp in electron/hardening.ts.
+ * (`hermes:data-url-read-max:*`). The default and the clamp are shared with
+ * main via apps/shared so the two ends cannot drift.
*/
+import {
+ clampDataUrlReadMaxMb,
+ DATA_URL_READ_DEFAULT_MAX_MB,
+ DATA_URL_READ_MAX_MAX_MB,
+ DATA_URL_READ_MIN_MAX_MB
+} from '@hermes/shared'
import { atom } from 'nanostores'
import { notifyError } from '@/store/notifications'
-/** Ship default; must match DATA_URL_READ_DEFAULT_MAX_MB in hardening.ts. */
-export const DATA_URL_READ_DEFAULT_MAX_MB = 16
-export const DATA_URL_READ_MIN_MAX_MB = 1
-/** Typo / absurd-value guard only — large values can still OOM the app. */
-export const DATA_URL_READ_MAX_MAX_MB = 4096
-
-export function clampDataUrlReadMaxMb(value: unknown): number {
- const parsed = Number(value)
-
- if (!Number.isFinite(parsed)) {
- return DATA_URL_READ_DEFAULT_MAX_MB
- }
-
- return Math.min(DATA_URL_READ_MAX_MAX_MB, Math.max(DATA_URL_READ_MIN_MAX_MB, Math.round(parsed)))
-}
+export { clampDataUrlReadMaxMb, DATA_URL_READ_DEFAULT_MAX_MB, DATA_URL_READ_MAX_MAX_MB, DATA_URL_READ_MIN_MAX_MB }
export const $dataUrlReadMaxMb = atom<number>(DATA_URL_READ_DEFAULT_MAX_MB)
diff --git a/apps/desktop/src/store/goals.ts b/apps/desktop/src/store/goals.ts
index 3b19b7eb63b..eab0188d66d 100644
--- a/apps/desktop/src/store/goals.ts
+++ b/apps/desktop/src/store/goals.ts
@@ -1,5 +1,7 @@
import { atom } from 'nanostores'
+import { keyedTimeouts } from '@/lib/keyed-timeouts'
+
import { $gateway } from './gateway'
export type GoalStatus = 'active' | 'done' | 'paused' | 'waiting'
@@ -14,38 +16,23 @@ export interface SessionGoal {
export const $goalsBySession = atom<Record<string, SessionGoal>>({})
const DONE_LINGER_MS = 8_000
-const clearTimers = new Map<string, ReturnType<typeof setTimeout>>()
-
-function cancelScheduledClear(sid: string) {
- const timer = clearTimers.get(sid)
-
- if (timer !== undefined) {
- clearTimeout(timer)
- clearTimers.delete(sid)
- }
-}
+const clearTimers = keyedTimeouts()
export function setSessionGoal(sid: string, goal: SessionGoal) {
if (!sid) {
return
}
- cancelScheduledClear(sid)
+ clearTimers.cancel(sid)
$goalsBySession.set({ ...$goalsBySession.get(), [sid]: goal })
if (goal.status === 'done') {
- clearTimers.set(
- sid,
- setTimeout(() => {
- clearTimers.delete(sid)
- clearSessionGoal(sid)
- }, DONE_LINGER_MS)
- )
+ clearTimers.schedule(sid, DONE_LINGER_MS, () => clearSessionGoal(sid))
}
}
export function clearSessionGoal(sid: string) {
- cancelScheduledClear(sid)
+ clearTimers.cancel(sid)
const map = $goalsBySession.get()
diff --git a/apps/desktop/src/store/pet-gallery.ts b/apps/desktop/src/store/pet-gallery.ts
index 60322bcc1fd..8c7f282c563 100644
--- a/apps/desktop/src/store/pet-gallery.ts
+++ b/apps/desktop/src/store/pet-gallery.ts
@@ -1,5 +1,6 @@
import { atom } from 'nanostores'
+import { isMissingRpcMethod } from '@/lib/gateway-rpc'
import { normalize } from '@/lib/text'
import {
$petInfo,
@@ -64,12 +65,6 @@ const petRpc = <T>(request: GatewayRequest, method: string, params: Record<strin
request<T>(method, { ...params, profile: petProfile() })
/** A JSON-RPC "method not found" — the backend predates the pet RPCs. */
-function isMissingMethod(error: unknown): boolean {
- const message = error instanceof Error ? error.message : String(error)
-
- return /method not found|-32601|unknown method|no such method/i.test(message)
-}
-
export const $petGallery = atom<PetGallery | null>(null)
export const $petGalleryStatus = atom<PetGalleryStatus>('idle')
export const $petGalleryError = atom<string | null>(null)
@@ -148,7 +143,7 @@ export function loadPetGallery(request: GatewayRequest, options: { force?: boole
localOk = true
}
} catch (e) {
- if (isMissingMethod(e)) {
+ if (isMissingRpcMethod(e)) {
$petGalleryStatus.set('stale')
} else if (!$petGallery.get()) {
// Only surface a hard error when we have nothing to show; a transient
@@ -188,7 +183,7 @@ async function syncInfo(request: GatewayRequest): Promise<void> {
try {
meta = await petRpc<PetInfoMeta>(request, 'pet.info.meta')
} catch (e) {
- if (!isMissingMethod(e)) {
+ if (!isMissingRpcMethod(e)) {
throw e
}
@@ -308,7 +303,7 @@ async function mutate(
return true
} catch (e) {
- if (isMissingMethod(e)) {
+ if (isMissingRpcMethod(e)) {
$petGalleryStatus.set('stale')
} else {
$petGalleryError.set(e instanceof Error ? e.message : fallback)
diff --git a/apps/desktop/src/store/pet-generate.ts b/apps/desktop/src/store/pet-generate.ts
index e829e68c09d..bbb6986edc6 100644
--- a/apps/desktop/src/store/pet-generate.ts
+++ b/apps/desktop/src/store/pet-generate.ts
@@ -1,5 +1,6 @@
import { atom } from 'nanostores'
+import { isMissingRpcMethod } from '@/lib/gateway-rpc'
import { persistBoolean, persistString, storedBoolean, storedString } from '@/lib/storage'
import { capitalize } from '@/lib/text'
import { $gateway } from '@/store/gateway'
@@ -181,12 +182,6 @@ export const $petGenInput = atom('')
export const $petGenRefImage = atom<string | null>(null)
export const $petGenRefName = atom('')
-function isMissingMethod(error: unknown): boolean {
- const message = error instanceof Error ? error.message : String(error)
-
- return /method not found|-32601|unknown method|no such method/i.test(message)
-}
-
/** Clear all generation state (before a fresh run). */
export function resetPetGen(): void {
$petGenStatus.set('idle')
@@ -439,7 +434,7 @@ export async function generateDrafts(request: GatewayRequest, options: GenerateO
return false
}
- if (isMissingMethod(e)) {
+ if (isMissingRpcMethod(e)) {
$petGenStatus.set('stale')
} else {
$petGenStatus.set('error')
diff --git a/apps/desktop/src/store/projects.ts b/apps/desktop/src/store/projects.ts
index 9af7255c6fc..b904b0f34e6 100644
--- a/apps/desktop/src/store/projects.ts
+++ b/apps/desktop/src/store/projects.ts
@@ -9,8 +9,8 @@ import type { HermesGitBaseBranch, HermesGitBranch } from '@/global'
import { getHermesConfig, hermesApi, type HermesGateway } from '@/hermes'
import { translateNow } from '@/i18n'
import { desktopDefaultCwd, isDesktopFsRemoteMode, selectDesktopPaths, writeDesktopFileText } from '@/lib/desktop-fs'
-import { desktopGit, isGitEndpointMissingError } from '@/lib/desktop-git'
-import { isMissingRpcMethod } from '@/lib/gateway-rpc'
+import { desktopGit } from '@/lib/desktop-git'
+import { isMissingRestEndpoint, isMissingRpcMethod } from '@/lib/gateway-rpc'
import { isUnderPath } from '@/lib/path-compare'
import { persistentAtom } from '@/lib/persisted'
import { $gateway, activeGateway, ensureActiveGatewayOpen } from '@/store/gateway'
@@ -1097,7 +1097,7 @@ export async function startWorkInRepo(
// backend's /api/git mirror, and an older backend may predate it. The raw
// failure ("Expected JSON … but got HTML" / a bare 404) reads like a git
// error — name the real remedy instead of degrading silently.
- if (isDesktopFsRemoteMode() && isGitEndpointMissingError(err)) {
+ if (isDesktopFsRemoteMode() && isMissingRestEndpoint(err)) {
throw new Error(translateNow('sidebar.projects.worktreeStaleBackend'))
}
diff --git a/apps/desktop/src/store/todos.ts b/apps/desktop/src/store/todos.ts
index e63c4f67f55..864ab5c2cb5 100644
--- a/apps/desktop/src/store/todos.ts
+++ b/apps/desktop/src/store/todos.ts
@@ -1,5 +1,6 @@
import { atom, computed } from 'nanostores'
+import { keyedTimeouts } from '@/lib/keyed-timeouts'
import { stableRecord } from '@/lib/stable-array'
import type { TodoItem } from '@/lib/todos'
@@ -66,38 +67,23 @@ export function todosForHydration(todos: readonly TodoItem[] | null): TodoItem[]
// lingers just long enough to see the last checkmark land, then the group
// drops out of the stack on its own.
const FINISHED_LINGER_MS = 4_000
-const clearTimers = new Map<string, ReturnType<typeof setTimeout>>()
-
-function cancelScheduledClear(sid: string) {
- const timer = clearTimers.get(sid)
-
- if (timer !== undefined) {
- clearTimeout(timer)
- clearTimers.delete(sid)
- }
-}
+const clearTimers = keyedTimeouts()
export function setSessionTodos(sid: string, todos: TodoItem[]) {
if (!sid) {
return
}
- cancelScheduledClear(sid)
+ clearTimers.cancel(sid)
$todosBySession.set({ ...$todosBySession.get(), [sid]: todos })
if (!todoListActive(todos)) {
- clearTimers.set(
- sid,
- setTimeout(() => {
- clearTimers.delete(sid)
- clearSessionTodos(sid)
- }, FINISHED_LINGER_MS)
- )
+ clearTimers.schedule(sid, FINISHED_LINGER_MS, () => clearSessionTodos(sid))
}
}
export function clearSessionTodos(sid: string) {
- cancelScheduledClear(sid)
+ clearTimers.cancel(sid)
const map = $todosBySession.get()
diff --git a/apps/shared/src/data-url-read-max.ts b/apps/shared/src/data-url-read-max.ts
new file mode 100644
index 00000000000..1b8cd157f61
--- /dev/null
+++ b/apps/shared/src/data-url-read-max.ts
@@ -0,0 +1,27 @@
+/**
+ * Size cap for local files Desktop loads as data URLs (composer attach, image
+ * preview, …).
+ *
+ * Main owns the persisted value; the renderer mirrors it in Settings → Chat and
+ * clamps optimistically before sending. Both ends have to agree on the default
+ * and the bounds, so they live here rather than as two constants with a
+ * "keep these in sync" comment between them.
+ *
+ * The whole file is base64-buffered in main, so this is a memory guard, not a
+ * model limit. The ceiling is only a typo guard — values well below it can
+ * still OOM the app.
+ */
+
+export const DATA_URL_READ_DEFAULT_MAX_MB = 16
+export const DATA_URL_READ_MIN_MAX_MB = 1
+export const DATA_URL_READ_MAX_MAX_MB = 4096
+
+export function clampDataUrlReadMaxMb(value: unknown): number {
+ const parsed = Number(value)
+
+ if (!Number.isFinite(parsed)) {
+ return DATA_URL_READ_DEFAULT_MAX_MB
+ }
+
+ return Math.min(DATA_URL_READ_MAX_MAX_MB, Math.max(DATA_URL_READ_MIN_MAX_MB, Math.round(parsed)))
+}
diff --git a/apps/shared/src/index.ts b/apps/shared/src/index.ts
index b4f6299ca22..5dfe39e1ff5 100644
--- a/apps/shared/src/index.ts
+++ b/apps/shared/src/index.ts
@@ -40,6 +40,12 @@ export {
type CronTriggerController,
type CronTriggerRunResult
} from './cron-trigger-controller'
+export {
+ clampDataUrlReadMaxMb,
+ DATA_URL_READ_DEFAULT_MAX_MB,
+ DATA_URL_READ_MAX_MAX_MB,
+ DATA_URL_READ_MIN_MAX_MB
+} from './data-url-read-max'
export {
type ConnectionState,
type GatewayClientOptions,