Skip to content

The agent that grows with you

refactor(desktop): move no-reply helpers and plugin profile routing to siblings

Teknium2f76f45991be
diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.ts
index 849a7f4b051..007580ad916 100644
--- a/apps/desktop/src/sdk/index.ts
+++ b/apps/desktop/src/sdk/index.ts
@@ -59,11 +59,9 @@ import {
openGatewayForAgent,
openGatewayForProfile,
requestGatewayForAgent,
- requestGatewayForProfile,
retainGatewayForAgent,
retainGatewayForRelay,
- retireLocalProfileGateways,
- type SpawnPriority
+ retireLocalProfileGateways
} from '@/store/gateway'
import { notify, notifyError } from '@/store/notifications'
import {
@@ -115,11 +113,18 @@ import { pluginDecisions, profiles, skills, toolsets } from './bridge'
import { composerHost } from './composer'
import { i18nHost } from './i18n'
import { planPluginOpenSession } from './plugin-open-session-plan'
+import {
+ type PluginProfileRequestOptions,
+ type PluginProfileRoute,
+ pluginRouteStillRegistered,
+ requestPluginProfile
+} from './profile-request'
import { sessionsHost } from './sessions'
import { desktopSettings } from './settings'
/** Pane, status bar and titlebar slots; see `./areas` for the mount rules. */
export { PANES_AREA, STATUSBAR_AREAS, TITLEBAR_AREAS } from './areas'
+export type { PluginProfileRequestOptions, PluginProfileRoute } from './profile-request'
// -- state: readonly views over the app's live atoms -------------------------
@@ -213,17 +218,6 @@ const $focusedSessionProfile = computed(
owner?.profile || rememberedSessionProfile(sessions, focused, activeProfile)
)
-export interface PluginProfileRoute {
- connectionId: string
- mode: 'local' | 'remote'
- /** Electron's authoritative registry primary. Absent on older shells. */
- primary?: true
- /** Desktop profile used to select the connection route. */
- profile: string
- /** Backend Hermes profile served by that route. */
- targetProfile: string
-}
-
/** Window geometry + the app's responsive posture, one readonly rect. */
export interface ViewportRect {
width: number
@@ -251,97 +245,6 @@ const $busyBySession = computed($sessionStates, states => {
const $viewport = atom<ViewportRect>(readViewport())
-/** Options a plugin may attach to one `host.requestProfile` call. */
-export interface PluginProfileRequestOptions {
- /** Tag the dial that may cold-spawn this route's backend. Default
- * 'background'; an explicit user action passes 'foreground' so its spawn
- * takes the pool's reserved interactive slot (#102281 primitive). */
- spawnPriority?: SpawnPriority
-}
-
-async function requestPluginProfile<T>(
- route: PluginProfileRoute | string,
- method: string,
- params: Record<string, unknown>,
- timeoutMs?: number,
- options?: PluginProfileRequestOptions
-): Promise<T> {
- const spawnPriority = options?.spawnPriority
-
- // Preserve the exact call arity the pool tests pin: pass the deadline and the
- // dial options only when the caller set them, so a plain routed RPC keeps its
- // four-argument shape and a timeout-only caller its five-argument shape.
- const dialProfile = (profile: string): Promise<T> =>
- spawnPriority
- ? requestGatewayForProfile<T>(profile, method, params, timeoutMs, undefined, { spawnPriority })
- : timeoutMs === undefined
- ? requestGatewayForProfile<T>(profile, method, params)
- : requestGatewayForProfile<T>(profile, method, params, timeoutMs)
-
- if (typeof route !== 'string') {
- if (!route.connectionId.trim() || !route.profile.trim() || !route.targetProfile.trim()) {
- throw new Error('Profile route must include connectionId, profile, and targetProfile')
- }
-
- if (spawnPriority) {
- return requestGatewayForAgent<T>(route.connectionId, route.profile, method, params, timeoutMs, undefined, {
- spawnPriority
- })
- }
-
- return timeoutMs === undefined
- ? requestGatewayForAgent<T>(route.connectionId, route.profile, method, params)
- : requestGatewayForAgent<T>(route.connectionId, route.profile, method, params, timeoutMs)
- }
-
- const getAgentRoster = window.hermesDesktop?.getAgentRoster
-
- if (!getAgentRoster) {
- return dialProfile(route)
- }
-
- const roster = await getAgentRoster()
- const profile = route.trim() || 'default'
- const soleLocalSource = roster.sources.length === 1 && roster.sources[0]?.kind === 'local'
-
- // The string overload is compatibility-only. A sole local registry is the
- // one topology where a profile name is intrinsically unambiguous, even when
- // its live enumeration transiently failed. Any additional source requires a
- // descriptor because an undialed/unreachable source may expose the same name.
- if (soleLocalSource) {
- return dialProfile(profile)
- }
-
- throw new Error(
- `Profile "${profile}" requires a route descriptor from host.profileRoutes(); profile-only routing is limited to legacy/local profiles.`
- )
-}
-
-/** Re-read Electron's current registry before retrying an exact-owner wake.
- * A route that was removed or replaced while the first hydration wait ran is
- * no longer authority to touch that backend, even when its labels still look
- * identical. */
-async function pluginRouteStillRegistered(route: PluginProfileRoute): Promise<boolean> {
- const getProfileRoutes = window.hermesDesktop?.getProfileRoutes
-
- if (!getProfileRoutes) {
- return false
- }
-
- try {
- const routes = await getProfileRoutes($profiles.get().map(profile => profile.name))
-
- return routes.some(
- candidate =>
- candidate.connectionId === route.connectionId &&
- candidate.profile === route.profile &&
- candidate.targetProfile === route.targetProfile
- )
- } catch {
- return false
- }
-}
-
if (typeof window !== 'undefined') {
const refresh = () => $viewport.set(readViewport())
window.addEventListener('resize', refresh)
@@ -1617,11 +1520,21 @@ export const host = {
const path = `/api/sessions/${encodeURIComponent(options.sessionId)}`
const payload = { hidden: options.hidden, profile }
- return mutatePersistedVisibility(JSON.stringify([scope, options.sessionId, payload]),
- () => hermesApi<SessionMutationSnapshot>({ ...scope,
- path: `${path}/mutation-snapshot?profile=${encodeURIComponent(profile)}` }),
- identity => hermesApi<{ ok: boolean; hidden: boolean }>({ ...scope, path,
- method: 'PATCH', body: { ...payload, ...identity } }))
+ return mutatePersistedVisibility(
+ JSON.stringify([scope, options.sessionId, payload]),
+ () =>
+ hermesApi<SessionMutationSnapshot>({
+ ...scope,
+ path: `${path}/mutation-snapshot?profile=${encodeURIComponent(profile)}`
+ }),
+ identity =>
+ hermesApi<{ ok: boolean; hidden: boolean }>({
+ ...scope,
+ path,
+ method: 'PATCH',
+ body: { ...payload, ...identity }
+ })
+ )
},
/** Gateway JSON-RPC — sessions, config, skills, cron, kanban, everything
diff --git a/apps/desktop/src/sdk/profile-request.ts b/apps/desktop/src/sdk/profile-request.ts
new file mode 100644
index 00000000000..1b24565de7a
--- /dev/null
+++ b/apps/desktop/src/sdk/profile-request.ts
@@ -0,0 +1,106 @@
+import { requestGatewayForAgent, requestGatewayForProfile, type SpawnPriority } from '@/store/gateway'
+import { $profiles } from '@/store/profile'
+
+/** Plugin-facing profile routing for `host.requestProfile` and friends. */
+
+export interface PluginProfileRoute {
+ connectionId: string
+ mode: 'local' | 'remote'
+ /** Electron's authoritative registry primary. Absent on older shells. */
+ primary?: true
+ /** Desktop profile used to select the connection route. */
+ profile: string
+ /** Backend Hermes profile served by that route. */
+ targetProfile: string
+}
+
+/** Options a plugin may attach to one `host.requestProfile` call. */
+export interface PluginProfileRequestOptions {
+ /** Tag the dial that may cold-spawn this route's backend. Default
+ * 'background'; an explicit user action passes 'foreground' so its spawn
+ * takes the pool's reserved interactive slot (#102281 primitive). */
+ spawnPriority?: SpawnPriority
+}
+
+export async function requestPluginProfile<T>(
+ route: PluginProfileRoute | string,
+ method: string,
+ params: Record<string, unknown>,
+ timeoutMs?: number,
+ options?: PluginProfileRequestOptions
+): Promise<T> {
+ const spawnPriority = options?.spawnPriority
+
+ // Preserve the exact call arity the pool tests pin: pass the deadline and the
+ // dial options only when the caller set them, so a plain routed RPC keeps its
+ // four-argument shape and a timeout-only caller its five-argument shape.
+ const dialProfile = (profile: string): Promise<T> =>
+ spawnPriority
+ ? requestGatewayForProfile<T>(profile, method, params, timeoutMs, undefined, { spawnPriority })
+ : timeoutMs === undefined
+ ? requestGatewayForProfile<T>(profile, method, params)
+ : requestGatewayForProfile<T>(profile, method, params, timeoutMs)
+
+ if (typeof route !== 'string') {
+ if (!route.connectionId.trim() || !route.profile.trim() || !route.targetProfile.trim()) {
+ throw new Error('Profile route must include connectionId, profile, and targetProfile')
+ }
+
+ if (spawnPriority) {
+ return requestGatewayForAgent<T>(route.connectionId, route.profile, method, params, timeoutMs, undefined, {
+ spawnPriority
+ })
+ }
+
+ return timeoutMs === undefined
+ ? requestGatewayForAgent<T>(route.connectionId, route.profile, method, params)
+ : requestGatewayForAgent<T>(route.connectionId, route.profile, method, params, timeoutMs)
+ }
+
+ const getAgentRoster = window.hermesDesktop?.getAgentRoster
+
+ if (!getAgentRoster) {
+ return dialProfile(route)
+ }
+
+ const roster = await getAgentRoster()
+ const profile = route.trim() || 'default'
+ const soleLocalSource = roster.sources.length === 1 && roster.sources[0]?.kind === 'local'
+
+ // The string overload is compatibility-only. A sole local registry is the
+ // one topology where a profile name is intrinsically unambiguous, even when
+ // its live enumeration transiently failed. Any additional source requires a
+ // descriptor because an undialed/unreachable source may expose the same name.
+ if (soleLocalSource) {
+ return dialProfile(profile)
+ }
+
+ throw new Error(
+ `Profile "${profile}" requires a route descriptor from host.profileRoutes(); profile-only routing is limited to legacy/local profiles.`
+ )
+}
+
+/** Re-read Electron's current registry before retrying an exact-owner wake.
+ * A route that was removed or replaced while the first hydration wait ran is
+ * no longer authority to touch that backend, even when its labels still look
+ * identical. */
+export async function pluginRouteStillRegistered(route: PluginProfileRoute): Promise<boolean> {
+ const getProfileRoutes = window.hermesDesktop?.getProfileRoutes
+
+ if (!getProfileRoutes) {
+ return false
+ }
+
+ try {
+ const routes = await getProfileRoutes($profiles.get().map(profile => profile.name))
+
+ return routes.some(
+ candidate =>
+ candidate.connectionId === route.connectionId &&
+ candidate.profile === route.profile &&
+ candidate.targetProfile === route.targetProfile
+ )
+ } catch {
+ return false
+ }
+}
diff --git a/apps/desktop/src/store/session-no-reply.ts b/apps/desktop/src/store/session-no-reply.ts
new file mode 100644
index 00000000000..420243d08d0
--- /dev/null
+++ b/apps/desktop/src/store/session-no-reply.ts
@@ -0,0 +1,54 @@
+import { type ChatMessage, chatMessageText } from '@/lib/chat-messages'
+import type { ErrorSurface } from '@/lib/error-surface'
+
+// Raised only after the backend confirmed the turn is over and no reply reached
+// this window, so Retry cannot run the prompt twice.
+const NO_REPLY_SURFACE: ErrorSurface = { code: 'no_reply', layer: 'runtime', retryable: true }
+const NO_REPLY_ERROR = 'Hermes ended this turn without a reply.'
+
+export function turnHasReply(messages: ChatMessage[]): boolean {
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
+ const message = messages[index]
+
+ if (message.hidden) {
+ continue
+ }
+
+ if (message.role === 'user') {
+ return false
+ }
+
+ if (message.role === 'assistant' && (message.error || chatMessageText(message).trim())) {
+ return true
+ }
+ }
+
+ return false
+}
+
+export function withNoReplyNotice(messages: ChatMessage[]): ChatMessage[] {
+ const last = messages.findLast(message => !message.hidden)
+
+ // A turn that ran tools but never wrote text carries the notice on its own bubble.
+ if (last?.role === 'assistant') {
+ return messages.map(message =>
+ message === last ? { ...message, error: NO_REPLY_ERROR, errorSurface: NO_REPLY_SURFACE } : message
+ )
+ }
+
+ const occurredAt = Date.now() / 1000
+
+ return [
+ ...messages,
+ {
+ completedAt: occurredAt,
+ error: NO_REPLY_ERROR,
+ errorSurface: NO_REPLY_SURFACE,
+ id: `assistant-no-reply-${Date.now()}`,
+ parts: [],
+ pending: false,
+ role: 'assistant',
+ timestamp: occurredAt
+ }
+ ]
+}
diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.ts
index 06712ef043b..95c9201a982 100644
--- a/apps/desktop/src/store/session-states.ts
+++ b/apps/desktop/src/store/session-states.ts
@@ -33,8 +33,7 @@ import {
} from '@/components/pane-shell/tree/store'
import { resolveRememberedActivePane, workspaceScopeKey } from '@/components/pane-shell/workspace-scope'
import type { WorkspaceMode } from '@/contrib/types'
-import { type ChatMessage, chatMessageText, finalizeInterruptedMessages, sealOpenToolParts } from '@/lib/chat-messages'
-import type { ErrorSurface } from '@/lib/error-surface'
+import { finalizeInterruptedMessages, sealOpenToolParts } from '@/lib/chat-messages'
import { tileFocusStampOnFocusChange } from '@/lib/session-timer-since'
import { stableArray } from '@/lib/stable-array'
import { readJson, writeJson } from '@/lib/storage'
@@ -85,6 +84,7 @@ import {
} from './session'
import { secondaryProfileOwnerForEvent } from './session-event-provenance'
import { $focusedStoredSessionId, TILE_PANE_PREFIX } from './session-focus'
+import { turnHasReply, withNoReplyNotice } from './session-no-reply'
import { assertSessionOwnerResolved } from './session-owner-resolution'
import {
isSessionOwnerRoute,
@@ -485,58 +485,6 @@ function settleEndedLiveTurn(runtimeId: string) {
})
}
-// Raised only after the backend confirmed the turn is over and no reply reached
-// this window, so Retry cannot run the prompt twice.
-const NO_REPLY_SURFACE: ErrorSurface = { code: 'no_reply', layer: 'runtime', retryable: true }
-const NO_REPLY_ERROR = 'Hermes ended this turn without a reply.'
-
-function turnHasReply(messages: ChatMessage[]): boolean {
- for (let index = messages.length - 1; index >= 0; index -= 1) {
- const message = messages[index]
-
- if (message.hidden) {
- continue
- }
-
- if (message.role === 'user') {
- return false
- }
-
- if (message.role === 'assistant' && (message.error || chatMessageText(message).trim())) {
- return true
- }
- }
-
- return false
-}
-
-function withNoReplyNotice(messages: ChatMessage[]): ChatMessage[] {
- const last = messages.findLast(message => !message.hidden)
-
- // A turn that ran tools but never wrote text carries the notice on its own bubble.
- if (last?.role === 'assistant') {
- return messages.map(message =>
- message === last ? { ...message, error: NO_REPLY_ERROR, errorSurface: NO_REPLY_SURFACE } : message
- )
- }
-
- const occurredAt = Date.now() / 1000
-
- return [
- ...messages,
- {
- completedAt: occurredAt,
- error: NO_REPLY_ERROR,
- errorSurface: NO_REPLY_SURFACE,
- id: `assistant-no-reply-${Date.now()}`,
- parts: [],
- pending: false,
- role: 'assistant',
- timestamp: occurredAt
- }
- ]
-}
-
/** Stamp the retry card on an ended turn that has no reply, never an intentional
* interruption. A newer turn is either live (skipped) or has its own reply. */
function markTurnWithoutReply(runtimeId: string) {