Skip to content

The agent that grows with you

22.8 KB
Raw Blame
import { useStore } from '@nanostores/react'
import { useEffect, useRef } from 'react'

import { resumeAccountConnect } from '@/app/capabilities/connectors/data/deep-link'
import { closeActiveTab } from '@/app/chat/close-tab'
import { commandFocusedPreview } from '@/app/chat/right-rail/preview-nav'
import { openSession } from '@/app/open-session'
import { commandFocusedTerminal, wordEraseFocusedTerminal } from '@/app/right-sidebar/terminal/terminal-context-menu'
import { openConnectionDoneLink } from '@/components/assistant-ui/connector-tool'
import { $diskPluginsScanPending } from '@/contrib/runtime-loader'
import { getSession } from '@/hermes'
import { resolveDeepLinkAction } from '@/lib/deeplink-routes'
import { pathFromHermesDeepLink, resolveHermesOpenPath } from '@/lib/hermes-open-target'
import { storedSessionIdForNotification } from '@/lib/session-ids'
import { announceNewSessionDraftKey } from '@/store/composer'
import { recordAction } from '@/store/desktop-metrics'
import { onKeptRouteOpened } from '@/store/gateway-kept-routes'
import { requestMcpInstallFromDeepLink } from '@/store/mcp-deeplink-install'
import { startMcpHealthChecker, stopMcpHealthChecker } from '@/store/mcp-health'
import {
  clearPluginNotifyHandlers,
  invokePluginNotifyAction,
  invokePluginNotifyActivate,
  respondToApprovalAction
} from '@/store/native-notifications'
import { requestPluginCatalogInstallFromDeepLink } from '@/store/plugin-catalog-install'
import { openPluginInstallRequest } from '@/store/plugin-install-request'
import { openFolderAsProject } from '@/store/projects'
import {
  $selectedStoredSessionId,
  forgetSessionOwnerHintsForSession,
  getRememberedRoute,
  getRememberedSessionId,
  resolveComposerSessionKey,
  sessionBelongsToProfile,
  sessionMatchesStoredId,
  sessionOwnerRouteFromRow,
  setRememberedRoute,
  setRememberedSessionId,
  setSessionOwnerHint
} from '@/store/session'
import { $botChatScopes, $sessionTiles, storedSessionIdForRuntimeId } from '@/store/session-states'
import { onSessionsChanged } from '@/store/session-sync'
import { requestSkillInstallFromDeepLink } from '@/store/skill-deeplink-install'
import { openUpdatesWindow, startUpdatePoller, stopUpdatePoller } from '@/store/updates'
import { isBrowserWindow, isHudWindow, isPeerInstanceWindow, isSecondaryWindow } from '@/store/windows'
import type { SessionInfo } from '@/types/hermes'

import { requestComposerFocus, requestComposerInsert } from '../../chat/composer/focus'
import { appViewForPath, isOverlayView, NEW_CHAT_ROUTE, routeSessionId, sessionRoute } from '../../routes'

import { resolveRememberedSessionId } from './remembered-session'

type RememberedSession = Pick<SessionInfo, '_lineage_root_id' | 'id' | 'parent_session_id' | 'profile' | 'source'>

interface DesktopIntegrationsParams {
  activeProfile: string
  chatOpen: boolean
  hasPreview: boolean
  locationPathname: string
  navigate: (to: string, options?: { replace?: boolean }) => void
  profileReady: boolean
  refreshSessions: () => Promise<unknown> | unknown
  /** `display.resume_last_session`; `undefined` while the config record is still loading. */
  resumeLastSession: boolean | undefined
  resumeExhaustedSessionId: null | string
  routedSessionId: null | string
  runtimeIdByStoredSessionId: { readonly current: Map<string, string> }
  sessions: readonly RememberedSession[]
}

/**
 * All the Electron-main / OS / cross-window integrations the shell listens for:
 * update polling, the ⌘W close shortcut, deep links, native-notification
 * navigation, preview-shortcut enablement, remembered-session restore, and
 * cross-window session-list sync. Kept out of the wiring controller so the
 * "talks to the desktop shell" surface reads as one unit.
 */
export function useDesktopIntegrations({
  activeProfile,
  locationPathname,
  navigate,
  profileReady,
  refreshSessions,
  resumeLastSession,
  resumeExhaustedSessionId,
  routedSessionId,
  runtimeIdByStoredSessionId,
  sessions
}: DesktopIntegrationsParams): void {
  // Update polling — populates $desktopVersion/$updateStatus, which feed the
  // statusbar version pill and the update toasts. Also honors the main
  // process's "open updates" menu request.
  useEffect(() => {
    startUpdatePoller()
    // Background MCP health: HTTP/SSE servers only (never spawns stdio),
    // notifies on transitions into needs-auth/error with a Sign in action.
    startMcpHealthChecker()
    // The native "Check for Updates…" menu item lives in the app menu next to
    // "About Hermes" — it is the OS-standard affordance for updating THIS app,
    // so it always opens the client overlay. Inheriting the connection-mode
    // default pointed a Mac at its remote Linux backend and left the app itself
    // silently stale (#70266).
    const unsubscribe = window.hermesDesktop?.onOpenUpdatesRequested?.(() => openUpdatesWindow('client'))

    return () => {
      unsubscribe?.()
      stopUpdatePoller()
      stopMcpHealthChecker()
    }
  }, [])

  // The renderer OWNS ⌘W: on macOS the native menu accelerator would else
  // close the window, so claim it unconditionally — the menu then routes ⌘W
  // to us (close-preview-requested IPC) and we decide tab-vs-window.
  useEffect(() => {
    window.hermesDesktop?.setPreviewShortcutActive?.(true)
  }, [])

  const restoredRef = useRef(false)
  const diskPluginsScanPending = useStore($diskPluginsScanPending)

  // Wait until boot has adopted the primary profile, then restore that profile's
  // navigation exactly once. The same effect owns subsequent writes so the
  // initial `/` cannot overwrite remembered history before it is read.
  // This ref is a one-time lifecycle latch, not a mirror of reactive atom state.
  // eslint-disable-next-line no-restricted-syntax
  useEffect(() => {
    // A peer instance window (Ctrl+Shift+N / New Window) boots on the fresh
    // draft route by design: it must not replay the primary window's
    // remembered-route/remembered-session restore, which lands it back on the
    // very session Window 1 has open (#74948). Connections' source
    // restoration already skips peers for the same reason.
    if (!profileReady || isHudWindow() || isBrowserWindow() || isPeerInstanceWindow()) {
      return
    }

    if (!restoredRef.current) {
      // Only cold-start navigation at the default route is replaceable; a deep
      // link or hidden-then-shown window keeps its explicit destination.
      if (locationPathname === NEW_CHAT_ROUTE) {
        // display.resume_last_session (#60812): hold the latch until the config
        // record answers, then either restore below or stay on the fresh chat.
        // Remembered ids keep being written either way, so flipping the switch
        // back on resumes from the very next launch.
        if (resumeLastSession === undefined) {
          return
        }

        if (!resumeLastSession) {
          restoredRef.current = true

          return
        }

        const route = getRememberedRoute(activeProfile)
        const routeSession = route ? routeSessionId(route) : null
        const last = getRememberedSessionId(activeProfile)

        const restorableNonSessionRoute =
          !!route && route !== NEW_CHAT_ROUTE && !routeSession && !isOverlayView(appViewForPath(route))

        // Boot adoption can publish renderer.ready before its async session
        // refresh completes. Keep the restore latch open until ownership can be
        // decided; treating an unloaded list as authoritative would erase valid
        // remembered navigation permanently.
        if (sessions.length === 0 && !restorableNonSessionRoute && (routeSession || last)) {
          return
        }

        // A remembered plugin page looks session-shaped until its route
        // registers, and disk plugins load async. Hold the latch through the
        // first disk scan so a page that is merely late is not erased as stale
        // (an already-running backend can hand us the session list first).
        if (routeSession && diskPluginsScanPending) {
          return
        }

        restoredRef.current = true

        // A delegate child (source='subagent') is never a restorable
        // destination: it is invisible in the sidebar, so resuming one leaves
        // the app split between the highlighted parent and the child the chat
        // area shows (#56983). `/branch` children also carry
        // parent_session_id but ARE user-facing — source, not parenthood, is
        // the discriminator. A listed row carries its source, so the guard is
        // synchronous there; an unlisted id resolves by id below.
        const rowFor = (id: string) => sessions.find(session => sessionMatchesStoredId(session, id))

        // The same owner hygiene the click path (openStoredSession) applies to
        // a list row: an untagged row is owned by the ambient backend, so a
        // stale explicit hint (older builds persisted `local` for legacy
        // primary-SSH rows) must not survive into the pathname-driven resume —
        // it would dial the Mac backend for a remote session and die with
        // "session not found" (#97809). A connection-tagged row pins its exact
        // route instead, exactly as a clicked row does.
        const repairOwnerHintsForRestore = (id: string) => {
          const row = rowFor(id)

          if (!row) {
            return
          }

          const ownerRoute = sessionOwnerRouteFromRow(row)

          if (ownerRoute) {
            setSessionOwnerHint(id, ownerRoute)
          } else {
            forgetSessionOwnerHintsForSession(id)
          }
        }

        const restorableRouteSession = routeSession && rowFor(routeSession)?.source !== 'subagent' ? routeSession : null

        if (
          route &&
          route !== NEW_CHAT_ROUTE &&
          !isOverlayView(appViewForPath(route)) &&
          (!routeSession || (restorableRouteSession && sessionBelongsToProfile(sessions, routeSession, activeProfile)))
        ) {
          // The user may have started typing on the fresh chat while the
          // backend was still coming up; the composer moves that draft onto
          // the restored session when its scope swaps (#114122).
          if (routeSession) {
            repairOwnerHintsForRestore(routeSession)
          }

          announceNewSessionDraftKey(routeSession && resolveComposerSessionKey(routeSession, sessions))
          navigate(route, { replace: true })

          return
        }

        // A remembered route carried a session id we can no longer validate —
        // clear the stale entry so the next cold start won't re-try it.
        if (routeSession) {
          setRememberedRoute(null, activeProfile)
        }

        if (last) {
          // Fast path: a listed, non-delegate row restores directly, exactly
          // as before — no by-id fetch on the common cold start.
          if (rowFor(last)?.source !== 'subagent' && sessionBelongsToProfile(sessions, last, activeProfile)) {
            repairOwnerHintsForRestore(last)
            announceNewSessionDraftKey(resolveComposerSessionKey(last, sessions))
            navigate(sessionRoute(last), { replace: true })

            return
          }

          // Unlisted (or a delegate row that reached a list slice): resolve
          // the id directly — the by-id endpoint serves delegate children the
          // list omits. A delegate child repairs to its parent, an orphan or
          // foreign-profile id clears, and a fetch failure keeps the
          // remembered value for the next launch instead of discarding it.
          void resolveRememberedSessionId(last, getSession)
            .then(remembered => {
              if (!remembered || !sessionBelongsToProfile(sessions, remembered, activeProfile)) {
                setRememberedSessionId(null, activeProfile)

                return
              }

              repairOwnerHintsForRestore(remembered)
              announceNewSessionDraftKey(resolveComposerSessionKey(remembered, sessions))
              setRememberedSessionId(remembered, activeProfile)
              navigate(sessionRoute(remembered), { replace: true })
            })
            .catch(() => undefined)

          return
        }
      } else {
        restoredRef.current = true
      }
    }

    // Remember the open chat (session id for notifications/resume) AND the last
    // non-overlay route (a page like /skills, or a session route) per profile.
    // Session-shaped routes require an explicit matching owner; unresolved and
    // wrong-profile rows must not replace known-safe navigation.
    // The resume-exhausted session must not be written back into remembered
    // navigation: the cleanup effect above drops it once, but this
    // persistence effect re-runs on every session-list refresh while its
    // deps are unchanged — without the barrier the dead id outlives every
    // restart and the window boots into the resume-error screen each time.
    const exhausted = routedSessionId !== null && routedSessionId === resumeExhaustedSessionId

    if (routedSessionId && !exhausted && sessionBelongsToProfile(sessions, routedSessionId, activeProfile)) {
      // A delegate child (source='subagent') is never itself a rememberable
      // destination: it is invisible in the sidebar, so a restart would resume
      // an orphan chat while the sidebar highlights its parent (#56983).
      // `/branch` children also carry parent_session_id but ARE user-facing —
      // source, not parenthood, is the discriminator.
      const routedRow = sessions.find(session => sessionMatchesStoredId(session, routedSessionId))

      const rememberedSessionId =
        routedRow?.source === 'subagent' ? routedRow.parent_session_id || null : routedSessionId

      if (rememberedSessionId) {
        setRememberedSessionId(rememberedSessionId, activeProfile)
        setRememberedRoute(
          rememberedSessionId === routedSessionId ? locationPathname : sessionRoute(rememberedSessionId),
          activeProfile
        )
      }
    } else if (!routedSessionId && !isOverlayView(appViewForPath(locationPathname))) {
      setRememberedRoute(locationPathname, activeProfile)
    }
  }, [
    activeProfile,
    diskPluginsScanPending,
    locationPathname,
    navigate,
    profileReady,
    resumeExhaustedSessionId,
    resumeLastSession,
    routedSessionId,
    sessions
  ])

  useEffect(() => {
    if (!profileReady || !resumeExhaustedSessionId) {
      return
    }

    if (getRememberedSessionId(activeProfile) === resumeExhaustedSessionId) {
      setRememberedSessionId(null, activeProfile)
    }

    if (routeSessionId(getRememberedRoute(activeProfile) ?? '') === resumeExhaustedSessionId) {
      setRememberedRoute(null, activeProfile)
    }
  }, [activeProfile, profileReady, resumeExhaustedSessionId])

  // Native-notification click -> jump to the session WHERE IT ALREADY IS (open
  // tile / main), else beside what's loaded rather than over it — the click
  // came from outside the app and shouldn't cost the user the chat they left
  // on screen. Runtime id is translated to the stored id the chat route is
  // keyed by; action buttons resolve in place.
  useEffect(() => {
    const unsubscribe = window.hermesDesktop?.onFocusSession?.(sessionId => {
      if (sessionId) {
        // Reloads and runtime recovery can leave only the shared mirror bound.
        const viaLocalMap = storedSessionIdForNotification(sessionId, runtimeIdByStoredSessionId.current)
        const storedId = viaLocalMap !== sessionId ? viaLocalMap : (storedSessionIdForRuntimeId(sessionId) ?? sessionId)

        // A notification reveals a tab; it must not reclassify a Bot chat.
        const scope =
          $sessionTiles.get().find(tile => tile.storedSessionId === storedId) ?? $botChatScopes.get()[storedId]

        if (isOverlayView(appViewForPath(locationPathname))) {
          navigate(sessionRoute($selectedStoredSessionId.get() ?? ''), { replace: true })
        }

        openSession(
          storedId,
          navigate,
          'stack',
          scope && { ...scope, workspaceMode: scope.workspaceMode ?? 'sessions' }
        )
      }
    })

    return () => unsubscribe?.()
  }, [locationPathname, navigate, runtimeIdByStoredSessionId])

  useEffect(() => {
    const unsubscribe = window.hermesDesktop?.onNotificationAction?.(({ actionId, sessionId }) => {
      void respondToApprovalAction(sessionId ?? null, actionId)
    })

    return () => unsubscribe?.()
  }, [])

  // Plugin OS notification body/action → optional callback + navigate. Activation
  // is user-driven (click), so this is offer-not-hijack. Paths share the
  // hermes://index-network/intent/1 vocabulary with deep links.
  useEffect(() => {
    const unsubscribe = window.hermesDesktop?.onNotificationActivate?.(payload => {
      if (!payload) {
        return
      }

      if (payload.actionId) {
        invokePluginNotifyAction(payload.notifyId, payload.actionId)
      } else {
        invokePluginNotifyActivate(payload.notifyId)
      }

      if (payload.activate) {
        // Defense-in-depth: re-resolve at the IPC boundary rather than trusting
        // the pre-IPC validation — any future hermesDesktop.notify caller gets
        // funneled through the same resolver.
        const path = resolveHermesOpenPath(payload.activate)

        if (path) {
          navigate(path)
        }
      }

      clearPluginNotifyHandlers(payload.notifyId)
    })

    return () => unsubscribe?.()
  }, [navigate])

  // hermes:// deep links:
  //  - mcp/install?… → pending MCP install (explicit confirm, never auto-install)
  //  - plugin/install?catalog=<name> → curated-catalog lookup, then the same
  //    reviewed/pinned install modal an in-app catalog pick opens; unknown
  //    names toast an error and never fall back to a git-path install.
  //  - plugin/install?… (and legacy plugin-agent/plugin-desktop) → plugin install
  //    modal awaiting explicit confirmation. Never auto-installs.
  //  - skill/install?identifier=… → confirmation, then the existing hub pipeline
  //  - blueprint/<name>?… → reviewable /blueprint command in the composer
  //  - <plugin>/<path>?… → in-app navigate (e.g. index-network/intent/1)
  //  - open/<path>?… → in-app navigate (generic)
  useEffect(() => {
    const unsubscribe = window.hermesDesktop?.onDeepLink?.(payload => {
      if (!payload?.kind) {
        return
      }

      if (payload.kind === 'mcp' && payload.name === 'install') {
        requestMcpInstallFromDeepLink(payload.params || {})

        return
      }

      const action = resolveDeepLinkAction(payload)

      // The user finished a sign-in in their browser and the portal sent them back. Show the card
      // and wake its watcher; the link's status is not allowed to move any row.
      if (action.type === 'connection-done') {
        void resumeAccountConnect(action.op, navigate).then(handled => {
          if (handled) {
            return
          }

          return openConnectionDoneLink(action.op, navigate, runtimeId => {
            const viaLocalMap = storedSessionIdForNotification(runtimeId, runtimeIdByStoredSessionId.current)

            return viaLocalMap !== runtimeId ? viaLocalMap : (storedSessionIdForRuntimeId(runtimeId) ?? runtimeId)
          })
        })

        return
      }

      if (action.type === 'composer-blueprint') {
        const slots = Object.entries(action.params || {})
          .map(([k, v]) => {
            const sval = /\s/.test(v) ? `"${v.replace(/"/g, '\\"')}"` : v

            return `${k}=${sval}`
          })
          .join(' ')

        const command = `/blueprint ${action.name}${slots ? ' ' + slots : ''}`
        requestComposerInsert(command, { mode: 'block', target: 'main' })
        requestComposerFocus('main')

        return
      }

      if (action.type === 'plugin-catalog-install') {
        void requestPluginCatalogInstallFromDeepLink(action.name)

        return
      }

      if (action.type === 'plugin-install') {
        openPluginInstallRequest({
          repo: action.repo,
          enable: action.enable,
          force: action.force,
          legacyHint: action.legacyHint
        })

        return
      }

      if (action.type === 'skill-install') {
        void requestSkillInstallFromDeepLink(action.identifier)

        return
      }

      if (payload.kind === 'skill') {
        return
      }

      // Not a core action — treat as a plugin-scoped or open/ navigation deep
      // link (hermes://index-network/intent/1, hermes://open/…). The resolver
      // rejects reserved kinds and unsafe paths.
      const path = pathFromHermesDeepLink(payload.kind, payload.name || '', payload.params || {})

      if (path) {
        navigate(path)
      }
    })

    void window.hermesDesktop?.signalDeepLinkReady?.()

    return () => unsubscribe?.()
  }, [navigate, runtimeIdByStoredSessionId])

  // ⌘W via the macOS menu accelerator → close the focused tab; if nothing is
  // closeable, fall back to closing the window (so ⌘W still works as the
  // OS-standard window close, esp. secondary windows). The Win/Linux keyboard
  // path is the `view.closeTab` keybind (use-keybinds), sharing closeActiveTab.
  useEffect(() => {
    const unsubscribe = window.hermesDesktop?.onClosePreviewRequested?.(() => {
      // A focused user terminal owns the chord as the shell's word erase: main
      // claimed the keystroke (before-input-event), so re-deliver the ^W byte
      // to the PTY instead of closing the pane and killing the shell (#65457).
      // Read-only agent mirrors and everything else keep the close meaning.
      if (wordEraseFocusedTerminal()) {
        return
      }

      void closeActiveTab(id => navigate(sessionRoute(id)))
    })

    return () => unsubscribe?.()
  }, [navigate])

  // Native browser gestures (⌘R, a mouse's back/forward buttons, a trackpad
  // swipe) that landed on the app's own chrome rather than inside a page — main
  // answers those against the focused guest and never asks. Only ⌘R has an
  // app-level meaning to fall back to; an unfocused swipe is a no-op.
  useEffect(() => {
    const unsubscribe = window.hermesDesktop?.onPreviewNav?.(command => {
      if (commandFocusedTerminal(command)) {
        return
      }

      if (!commandFocusedPreview(command) && command === 'reload') {
        window.location.reload()
      }
    })

    return () => unsubscribe?.()
  }, [])

  // File > Open Folder… — same open-folder-as-project upsert as the ⌘O keybind.
  useEffect(() => {
    const unsubscribe = window.hermesDesktop?.onOpenFolderRequested?.(() => {
      recordAction('workspace.openFolder', 'menu')
      void openFolderAsProject()
    })

    return () => unsubscribe?.()
  }, [])

  // Another window mutated the shared session list -> re-pull the sidebar.
  useEffect(() => {
    if (isSecondaryWindow() || isBrowserWindow()) {
      return
    }

    return onSessionsChanged(() => void refreshSessions())
  }, [refreshSessions])

  // A gateway that connects after the list was drawn adds its rows to it.
  useEffect(() => onKeptRouteOpened(() => void refreshSessions()), [refreshSessions])
}