Skip to content

The agent that grows with you

30.8 KB
Raw Blame
import { JSON_RPC_INTERNAL_ERROR, type SetupBeat } from '@hermes/shared'

import {
  hasLivePreviewSurface,
  requestPopoutPreviewAct,
  requestPopoutPreviewRead
} from '@/app/chat/right-rail/preview-popout-bridge'
import { readActivePreview } from '@/app/chat/right-rail/preview-reader'
import {
  abortPreviewTyping,
  releasePreviewTyping,
  trackPreviewTyping
} from '@/app/chat/right-rail/preview-typing-abort'
import { readActiveTerminal } from '@/app/right-sidebar/terminal/buffer'
import { pendingClarifyToolPayload } from '@/app/session/hooks/use-session-actions/restore-pending-clarify'
import { translateNow } from '@/i18n'
import { restorePendingClarifyToolCall } from '@/lib/chat-messages'
import { hostHas } from '@/lib/host-capabilities'
import type { PreviewActAction } from '@/lib/preview-act/act-in-page'
import type { TourAction, TourStep } from '@/lib/tour'
import { type AppearanceValues, applyAppearance, THEME_MODES } from '@/store/appearance-apply'
import { type ClarifyRequest, normalizeQuestions, setClarifyRequest } from '@/store/clarify'
import type { ScopedServerRequest } from '@/store/gateway'
import { dispatchNativeNotification } from '@/store/native-notifications'
import type { PreviewOwner } from '@/store/preview-ownership'
import {
  receiveApprovalRequest,
  setSecretRequest,
  setSudoRequest,
  setVaultCodeRequest,
  setVaultSaveLoginRequest,
  setVaultUnlockRequest
} from '@/store/prompts'
import { rememberServerRequest } from '@/store/server-requests'
import { $selectedStoredSessionId, $sessions, lineageAliases, sessionMatchesStoredId } from '@/store/session'
import {
  $sessionStates,
  $sessionTiles,
  previewScopeForRuntime,
  storedSessionIdForRuntimeId
} from '@/store/session-states'
import { parkSetupBeat, type SetupBeatCard } from '@/store/setup-beat'
import { parkThemePick } from '@/store/theme-pick'
import { requestScrollToBottom } from '@/store/thread-scroll'
import { $toursEnabled } from '@/store/tours'

import type { GatewayEventDeps } from './types'

/** The preview engine, loaded on demand so ~25KB of page-injectable source stays
 *  off the boot path (dev: a fresh copy per action so edits reach the guest — see
 *  the previous home of this loader in desktop-bridge.ts for the full story). */
const loadPreviewEngine = () => {
  const stable = () => import('@/app/chat/right-rail/preview-act')

  if (!import.meta.hot) {
    return stable().then(mod => mod.actOnActivePreview)
  }

  return import(/* @vite-ignore */ '/src/app/chat/right-rail/preview-act.ts?hot=' + Date.now())
    .catch(stable)
    .then(mod => mod.actOnActivePreview as Awaited<ReturnType<typeof stable>>['actOnActivePreview'])
}

const str = (v: unknown): string => (typeof v === 'string' ? v : '')

/** Whose preview tabs a scoped agent request may see: the requesting
 *  runtime's stored id plus the tabs that runtime opened before the id bound,
 *  and the pins of the profile that runtime belongs to — never the viewed
 *  profile's pins on another profile's behalf. An id that does not resolve
 *  yet has no stored id — the runtime's own pending tabs — never the focused
 *  session's tabs. Only an unscoped request (no id) falls through to the
 *  focused session (undefined). */
const previewOwnerFor = (sessionId: string): PreviewOwner | undefined =>
  sessionId
    ? {
        profile: previewScopeForRuntime(sessionId),
        runtimeId: sessionId,
        sessionId: storedSessionIdForRuntimeId(sessionId)
      }
    : undefined

const num = (v: unknown): number | undefined => (typeof v === 'number' ? v : undefined)

/** Answer a string-valued request with a JSON-encoded result ('' = nothing / unavailable). */
const answerValue = (request: ScopedServerRequest, result: unknown) =>
  request.respond({ value: result ? JSON.stringify(result) : '' })

export interface ServerRequestContext {
  deps: Pick<
    GatewayEventDeps,
    'activeSessionIdRef' | 'sessionInterrupted' | 'sessionStateByRuntimeIdRef' | 'updateSessionState' | 'upsertToolCall'
  >
  request: ScopedServerRequest
  /** The session the request names ('' when unscoped). */
  sessionId: string
  /** The named session is the one on screen. */
  isActiveSession: boolean
}

type Handler = (ctx: ServerRequestContext) => void

type PreviewSessionRoute = 'ignore' | 'retry' | 'run'

/**
 * Bridges answered from THIS window's panes (preview tab, xterm buffer, the
 * native window below, the tour overlay). Every attached window sees the
 * request; one not hosting the session has no pane for it and its empty answer
 * would win the race, so the tool reports "no preview tab / no terminal" while
 * the owner's pane is open (#113348).
 */
const WINDOW_OWNED_REQUESTS = new Set([
  'preview.act',
  'preview.read',
  'terminal.read',
  'theme.apply',
  'window.read',
  'tour'
])

/**
 * A window not hosting the session declines instead of staying silent. The
 * backend keeps the request open for the owner and only settles once every
 * attached window declined, so when no window shows the chat the agent is told
 * now rather than after its whole deadline (#119333). `decline` is a no-op
 * against a backend that would take the first error as the answer.
 */
const declineNotShown = (request: ScopedServerRequest) => request.decline?.('This window is not showing the session.')

/**
 * Whether a request's `session_id` names the same conversation as the pane's
 * active session. The two sides are not always the same identity class: the
 * gateway stamps requests with the RUNTIME session id — which auto-compression
 * rotates mid-conversation — while the pane may hold the durable/lineage id it
 * navigated to, so plain equality refuses the very session on screen (#122062).
 * Compare through the stored id each side resolves to (an unknown id passes
 * through unchanged: it may already be a stored id), then through the lineage,
 * so a compression-rotated tip and its root still read as one conversation.
 * The lineage leg requires ONE session row to answer to both ids — branch
 * siblings share a root but are distinct conversations.
 */
export function requestNamesActiveSession({
  activeSessionId,
  sessionId,
  storedIdForRuntimeId = () => undefined
}: {
  activeSessionId: null | string
  sessionId: string
  storedIdForRuntimeId?: (runtimeId: string) => string | undefined
}): boolean {
  if (!sessionId || !activeSessionId) {
    return false
  }

  if (sessionId === activeSessionId) {
    return true
  }

  const requestStoredId = storedIdForRuntimeId(sessionId) ?? sessionId
  const activeStoredId = storedIdForRuntimeId(activeSessionId) ?? activeSessionId

  if (requestStoredId === activeStoredId) {
    return true
  }

  return $sessions
    .get()
    .some(
      session => sessionMatchesStoredId(session, requestStoredId) && sessionMatchesStoredId(session, activeStoredId)
    )
}

/** This window hosts the session: it is the primary view or an open session tile. */
export function windowHostsSession(
  sessionId: string,
  activeSessionId: null | string,
  storedIdForRuntimeId?: (runtimeId: string) => string | undefined
): boolean {
  return (
    requestNamesActiveSession({ activeSessionId, sessionId, storedIdForRuntimeId }) ||
    $sessionTiles.get().some(tile => tile.runtimeId === sessionId)
  )
}

/**
 * The window.read claim. window.read has no per-window pane, but its answer is
 * keyed to the ANSWERING window's bounds — "below" is measured from them — so
 * the only window that may answer is one showing the conversation. The strict
 * host check strands real states (#121609): the HUD shows the conversation
 * without holding it active (main holds the id on its behalf — hud-shell.tsx),
 * and after the HUD hands the conversation back the app window's active id
 * still names the pre-handoff runtime until a resume re-binds it (verified
 * live: only an explicit session resume restored the answer). So beyond the
 * strict checks, the asked id may resolve to a conversation this window
 * SHOWS: the selected stored session or a tile's stored session, matched
 * through lineageAliases (compression rotates the runtime tip under the
 * stored identity) and the session-state cache, which records which stored id
 * each runtime id maps to — an entry's stored id is what this window observed
 * for that runtime, so a stale entry still maps within its own conversation.
 * No shown conversation — nothing claimed, as before.
 *
 * Scoped to window.read only. preview.act and tour refuse unless
 * isActiveSession (raw id equality), so a tolerated claim there would turn
 * another window's silence into a false refusal that wins the multi-window
 * race — and a tour refusal latches session["tour_bridge"] = "answered",
 * converting every later tour action in the session into a full 45s wait.
 * Pane-owned reads keep #113348's owner-waiting semantics.
 */
export function windowReadClaimsSession(sessionId: string, activeSessionId: null | string): boolean {
  if (windowHostsSession(sessionId, activeSessionId)) {
    return true
  }

  const sessions = $sessions.get()

  const shown = [$selectedStoredSessionId.get(), ...$sessionTiles.get().map(tile => tile.storedSessionId)]

  return shown.some(
    stored =>
      stored !== null &&
      (stored === sessionId ||
        lineageAliases(stored, sessions).includes(sessionId) ||
        ($sessionStates.get()[sessionId]?.storedSessionId ?? null) === stored)
  )
}

/**
 * Panes are local to one desktop window, while gateway requests fan out
 * to every connected window. A scoped request may only be answered by the
 * window hosting its session (primary view or a tile). During reconnect,
 * however, an open request can replay one event-loop turn before the resumed
 * session becomes active; retry that one narrow race and otherwise leave the
 * request for its owner.
 */
export function previewSessionRoute({
  activeSessionId,
  method,
  replayed,
  sessionId,
  storedIdForRuntimeId
}: {
  activeSessionId: null | string
  method?: string
  replayed: boolean | undefined
  sessionId: string
  storedIdForRuntimeId?: (runtimeId: string) => string | undefined
}): PreviewSessionRoute {
  if (!sessionId) {
    return 'run'
  }

  // window.read routes through the tolerant claim (see windowReadClaimsSession);
  // every other window-owned request keeps the strict host check.
  if (
    method === 'window.read'
      ? windowReadClaimsSession(sessionId, activeSessionId)
      : windowHostsSession(sessionId, activeSessionId, storedIdForRuntimeId)
  ) {
    return 'run'
  }

  return replayed && !activeSessionId ? 'retry' : 'ignore'
}

const markNeedsInput = (ctx: ServerRequestContext) => {
  if (ctx.sessionId) {
    ctx.deps.updateSessionState(ctx.sessionId, state => ({ ...state, needsInput: true }))
  }
}

/**
 * A blocking-input card must not park for a session whose runtime is already
 * interrupted — the user hit Stop, or `removeSession` marked the doomed runtime
 * interrupted before it deletes the row. A frame still in flight would otherwise
 * re-create an overlay (and native notification) for a turn that is gone
 * (#75587). Answer it rather than drop it: the backend blocks on this frame, and
 * an error reply is the same "unanswered" its own `request.cancel` produces, so
 * the tool returns now instead of waiting out its deadline. Sessionless requests
 * (app-level Bot Screen install) are never gated.
 */
const declineIfSessionStopped = (ctx: ServerRequestContext): boolean => {
  if (!ctx.sessionId || !ctx.deps.sessionInterrupted(ctx.sessionId)) {
    return false
  }

  ctx.request.fail(JSON_RPC_INTERNAL_ERROR, 'session interrupted')

  return true
}

const notifyInput = (ctx: ServerRequestContext, body: string) => {
  if (!ctx.request.replayed) {
    dispatchNativeNotification({
      body,
      kind: 'input',
      sessionId: ctx.sessionId || null,
      title: translateNow('notifications.native.inputTitle')
    })
  }
}

// ── Blocking-input family (clarify / approval / sudo / secret / vault / MCP setup) ──
// Every one is parked per-session (like clarify) so a BACKGROUND session's turn can
// raise it and wait — the sidebar flags "needs input" and the card surfaces once the
// user focuses that chat. The Python side blocks on the response frame; without a
// handler the channel answers -32601 and the tool fails fast instead of stalling.

const parkClarify = (ctx: ServerRequestContext, clarifyRequest: ClarifyRequest) => {
  const { deps, request, sessionId } = ctx

  rememberServerRequest(request)
  setClarifyRequest(clarifyRequest)

  if (sessionId) {
    // A resumed/hydrated transcript may already contain this provider's clarify
    // call while carrying no live streamId. Re-arm that exact row instead of
    // letting the generic stream mutator append a second card.
    const occurredAt = Date.now() / 1000

    deps.updateSessionState(sessionId, state => {
      const projection = restorePendingClarifyToolCall(
        state.messages,
        pendingClarifyToolPayload(clarifyRequest),
        occurredAt
      )

      return {
        ...state,
        messages: projection.messages,
        streamId: projection.streamId,
        sawAssistantPayload: true,
        awaitingResponse: false,
        needsInput: true
      }
    })

    if (sessionId === deps.activeSessionIdRef.current) {
      requestScrollToBottom(sessionId)
    }
  }

  notifyInput(ctx, clarifyRequest.questions.map(q => q.question).join(' · '))
}

const clarify: Handler = ctx => {
  const { deps, request, sessionId } = ctx
  const p = request.params

  if (sessionId && deps.sessionInterrupted(sessionId)) {
    request.respond({})

    return
  }

  const questions = normalizeQuestions(p.questions)

  // `answers` rides along only on a reconnect replay (locks the server
  // already accepted).
  const lockedAnswers =
    typeof p.answers === 'object' && p.answers !== null
      ? Object.fromEntries(
          Object.entries(p.answers as Record<string, unknown>).filter(
            (entry): entry is [string, null | string] => entry[1] === null || typeof entry[1] === 'string'
          )
        )
      : undefined

  if (questions.length === 0) {
    request.respond({})

    return
  }

  parkClarify(ctx, {
    lockedAnswers,
    questions,
    receivedAt: Date.now() / 1000,
    requestId: request.id,
    sessionId: sessionId || null
  })
}

const approval: Handler = ctx => {
  const { request, sessionId } = ctx
  const p = request.params
  const command = str(p.command)
  const description = str(p.description) || 'dangerous command'

  if (declineIfSessionStopped(ctx)) {
    return
  }

  rememberServerRequest(request)
  void receiveApprovalRequest(null, {
    // false only when the backend forbids a permanent allow; it omits the field otherwise.
    allowPermanent: p.allow_permanent !== false,
    choices: Array.isArray(p.choices)
      ? p.choices.filter((choice): choice is string => typeof choice === 'string')
      : undefined,
    command,
    description,
    // The approval queue's own id — `approval.pending` / `approval.received` / `approval.respond` key on it.
    requestId: str(p.request_id) || undefined,
    serverRequestId: request.id,
    sessionId: sessionId || null,
    smartDenied: p.smart_denied === true
  }).catch(() => undefined)
  markNeedsInput(ctx)

  if (!request.replayed) {
    dispatchNativeNotification({
      actions: [
        {
          id: str(p.request_id) ? `approve:${str(p.request_id)}` : 'approve',
          text: translateNow('notifications.native.approveAction')
        },
        {
          id: str(p.request_id) ? `reject:${str(p.request_id)}` : 'reject',
          text: translateNow('notifications.native.rejectAction')
        }
      ],
      body: command || description,
      kind: 'approval',
      sessionId: sessionId || null,
      title: translateNow('notifications.native.approvalTitle')
    })
  }
}

const sudo: Handler = ctx => {
  if (declineIfSessionStopped(ctx)) {
    return
  }

  rememberServerRequest(ctx.request)
  setSudoRequest({
    command: str(ctx.request.params.command),
    requestId: ctx.request.id,
    sessionId: ctx.sessionId || null
  })
  markNeedsInput(ctx)
  notifyInput(ctx, translateNow('notifications.native.inputBody'))
}

/** Bot Screen package install (`tui_gateway/methods_display.py`): the same masked card as `sudo`,
 *  but app-level. The gateway sends it sessionless — it belongs to the connection that clicked
 *  Install, not to a chat — so it is stored under the null session and survives a chat switch. */
const displayInstallSudo: Handler = ctx => {
  rememberServerRequest(ctx.request)
  setSudoRequest({
    description: translateNow('prompts.sudoInstallDesc'),
    requestId: ctx.request.id,
    sessionId: null
  })
  notifyInput(ctx, translateNow('prompts.sudoInstallDesc'))
}

const secret: Handler = ctx => {
  const p = ctx.request.params
  const envVar = str(p.env_var)
  const promptText = str(p.prompt)

  if (declineIfSessionStopped(ctx)) {
    return
  }

  rememberServerRequest(ctx.request)
  setSecretRequest({ envVar, prompt: promptText, requestId: ctx.request.id, sessionId: ctx.sessionId || null })
  markNeedsInput(ctx)
  notifyInput(ctx, promptText || envVar || translateNow('notifications.native.inputBody'))
}

const vaultCode: Handler = ctx => {
  const p = ctx.request.params
  const site = str(p.site)

  if (declineIfSessionStopped(ctx)) {
    return
  }

  rememberServerRequest(ctx.request)
  setVaultCodeRequest({ hint: str(p.hint), requestId: ctx.request.id, sessionId: ctx.sessionId || null, site })
  markNeedsInput(ctx)
  notifyInput(ctx, translateNow('prompts.vaultCodeTitle', site))
}

const vaultSaveLogin: Handler = ctx => {
  const p = ctx.request.params
  const origin = str(p.origin)
  const site = str(p.site) || origin

  if (declineIfSessionStopped(ctx)) {
    return
  }

  rememberServerRequest(ctx.request)
  setVaultSaveLoginRequest({ origin, requestId: ctx.request.id, sessionId: ctx.sessionId || null, site })
  markNeedsInput(ctx)
  notifyInput(ctx, translateNow('prompts.vaultSaveTitle', site))
}

const vaultUnlockPrompt: Handler = ctx => {
  const p = ctx.request.params
  const backend = str(p.backend)
  const displayName = str(p.display_name) || backend

  if (declineIfSessionStopped(ctx)) {
    return
  }

  rememberServerRequest(ctx.request)
  setVaultUnlockRequest({ backend, displayName, requestId: ctx.request.id, sessionId: ctx.sessionId || null })
  markNeedsInput(ctx)
  notifyInput(ctx, translateNow('prompts.vaultUnlockTitle', displayName))
}

// ── Desktop-surface bridges (answered immediately, no card) ─────────────────

const terminalRead: Handler = ({ request }) => {
  // read_terminal tool: serialize the renderer's xterm buffer. Empty = no live pane.
  answerValue(request, readActiveTerminal({ count: num(request.params.count), start: num(request.params.start) }))
}

const previewRead: Handler = ({ request, sessionId }) => {
  // read_preview tool: the active preview tab's page text is async. Empty = nothing open.
  // The window that passes the session gate may be the chat window while the
  // live webview lives in the popped-out Browser renderer — forward there
  // first; a null (no pop-out answered) falls back to the legacy local read.
  // A local read sees only the tabs the requesting session can see.
  const opts = { count: num(request.params.count), start: num(request.params.start) }
  const owner = previewOwnerFor(sessionId)

  // A browser host has no pop-out and no readable surface to forward to, so
  // asking would only wait out the pop-out timeout before the same answer.
  void (async () => {
    const result = hasLivePreviewSurface(owner) || !hostHas('webviewPreview')
      ? await readActivePreview(opts, owner)
      : ((await requestPopoutPreviewRead(opts, owner)) ?? (await readActivePreview(opts, owner)))

    answerValue(request, result)
  })()
}

const previewAct: Handler = ({ deps, isActiveSession, request, sessionId }) => {
  // drive_preview tool: click/type/scroll/press inside the guest page. Active
  // session only: a background turn (including one in a tile this window hosts)
  // must never reach into the page the user is working in (desktop AGENTS.md:
  // offer, don't hijack). Window ownership is settled by WINDOW_OWNED_REQUESTS
  // before this runs, so a refusal here reaches the tool instead of stalling it.
  const p = request.params

  if (!isActiveSession) {
    answerValue(request, {
      error: 'The in-app browser only takes actions in the session the user is looking at.',
      success: false
    })

    return
  }

  // The agent drives ITS session's page: with a tile focused, the primary's
  // agent must not reach into the tile's tabs (#73890).
  const owner = previewOwnerFor(sessionId)

  // The keystroke loop has to be able to stop when this request is withdrawn
  // (tool timeout or turn interrupt). The local interrupted flag can flip
  // before request.cancel arrives; poll it so Stop cuts the loop off too.
  const signal = trackPreviewTyping(request.id)

  const watch = sessionId
    ? setInterval(() => {
        if (deps.sessionInterrupted(sessionId)) {
          abortPreviewTyping(request.id, 'interrupted')
        }
      }, 50)
    : undefined

  const action = {
    allowShortcut: p.allow_shortcut === true,
    amount: p.amount as never,
    key: p.key as never,
    kind: (str(p.action) || '') as never,
    max: p.max as never,
    ref: p.ref as never,
    selector: p.selector as never,
    submit: p.submit as never,
    text: p.text as never,
    to: p.to as PreviewActAction['to']
  }

  void (async () => {
    try {
      // After pop-out the live webview lives in the Browser window; this
      // window still owns the session gate, so forward the action there and
      // answer with the pop-out's result. No pop-out answering (null) falls
      // through to the local engine, which keeps the legacy NOTHING_OPEN
      // error for a genuinely closed pane.
      if (!hasLivePreviewSurface(owner)) {
        const remote = await requestPopoutPreviewAct(action, owner)

        if (remote) {
          answerValue(request, remote)

          return
        }
      }

      const run = await loadPreviewEngine()
      const result = await run(action, signal, owner)

      answerValue(request, result)
    } catch (error) {
      answerValue(request, { error: error instanceof Error ? error.message : String(error), success: false })
    } finally {
      if (watch !== undefined) {
        clearInterval(watch)
      }

      releasePreviewTyping(request.id, signal)
    }
  })()
}

/** read_window_below's `{error, platform}` answer on a browser host: the
 *  agent relays it instead of retrying a call that can never succeed. */
const BROWSER_WINDOW_READ_REFUSAL = {
  error:
    'read_window_below needs the Hermes desktop app: this session is in a browser tab, which cannot see the OS windows around it.',
  platform: 'browser'
}

const windowRead: Handler = ({ request }) => {
  if (!hostHas('osWindowEnumeration')) {
    answerValue(request, BROWSER_WINDOW_READ_REFUSAL)

    return
  }

  // read_window_below tool: main owns native window enumeration. Empty =
  // unavailable (older shell without the handler, Wayland, …) — without an
  // answer the tool would stall its full 30s deadline.
  const read = window.hermesDesktop?.readWindowBelow

  void Promise.resolve(read ? read() : null).then(
    result => answerValue(request, result),
    () => answerValue(request, null)
  )
}

const NOT_ACTIVE_TOUR_ERROR = 'Tours only run in the session the user is looking at.'

const tour: Handler = ({ deps, isActiveSession, request, sessionId }) => {
  // tour tool: one guided-tour action via driver.js, app DOM or preview guest
  // page. Active session only, same window-ownership rule as preview.act
  // (WINDOW_OWNED_REQUESTS).
  const p = request.params

  if (!$toursEnabled.get()) {
    // Refused in words, not silently dropped: a no-op would leave the agent
    // narrating a spotlight the user can't see.
    answerValue(request, { error: 'The user has turned guided tours off.', success: false })

    return
  }

  if (!isActiveSession) {
    answerValue(request, { error: NOT_ACTIVE_TOUR_ERROR, success: false })

    return
  }

  const kind = (str(p.action) || 'stop') as TourAction['kind']

  // The built-in tour waits for local-model data before it opens, and the user
  // may switch chats meanwhile: ask again, against the live active id.
  const stillActive = () =>
    requestNamesActiveSession({
      activeSessionId: deps.activeSessionIdRef.current,
      sessionId,
      storedIdForRuntimeId: runtimeId =>
        deps.sessionStateByRuntimeIdRef.current.get(runtimeId)?.storedSessionId ?? undefined
    })

  // start with no steps is the app's own tour: one call, the app owns the stops.
  // The backend validated `preset`; absent means full.
  const run =
    kind === 'start' && !Array.isArray(p.steps)
      ? import('@/app/chat/built-in-tour').then(({ runBuiltInTour }) =>
          runBuiltInTour(p.preset === 'quick' ? 'quick' : 'full', stillActive, NOT_ACTIVE_TOUR_ERROR)
        )
      : import('@/lib/tour').then(({ runTour }) =>
          runTour(
            {
              kind,
              selector: p.selector as never,
              side: p.side as TourStep['side'],
              startAt: p.step_index as never,
              steps: p.steps as TourStep[] | undefined,
              text: p.text as never,
              title: p.title as never
            },
            p.surface === 'preview' ? 'preview' : 'app',
            previewOwnerFor(sessionId)
          )
        )

  void run.then(
    result => answerValue(request, result),
    error => answerValue(request, { error: error instanceof Error ? error.message : String(error), success: false })
  )
}

// ── set_theme ───────────────────────────────────────────────────────────────

const appearanceValues = ({ params }: ScopedServerRequest): AppearanceValues => {
  const mode = THEME_MODES.find(candidate => candidate === params.mode)

  return {
    ...(str(params.accent) && { accent: str(params.accent) }),
    ...(str(params.layout) && { layout: str(params.layout) }),
    ...(mode && { mode })
  }
}

const themeApply: Handler = ({ isActiveSession, request }) => {
  // Active session only, like the tour: a background turn never repaints the app the user is looking at.
  answerValue(
    request,
    isActiveSession
      ? applyAppearance(appearanceValues(request))
      : { error: 'set_theme only changes the app while the user is looking at this chat.', success: false }
  )
}

const themePick: Handler = ctx => {
  const picker = ctx.request.params.picker

  if (!ctx.sessionId || (picker !== 'accent' && picker !== 'layout')) {
    ctx.request.respond({ cancelled: true })

    return
  }

  if (declineIfSessionStopped(ctx)) {
    return
  }

  rememberServerRequest(ctx.request)
  parkThemePick({ picker, requestId: ctx.request.id, sessionId: ctx.sessionId })
  markNeedsInput(ctx)
  notifyInput(ctx, translateNow(`assistant.themePicker.${picker}`))
}

const SETUP_BEATS: readonly SetupBeat[] = ['name', 'theme', 'layout', 'connectors', 'plugins', 'tour', 'build']

const setupBeat: Handler = ctx => {
  const { request, sessionId } = ctx
  const beat = SETUP_BEATS.find(candidate => candidate === request.params.beat)

  if (!sessionId || !beat) {
    request.respond({})

    return
  }

  if (declineIfSessionStopped(ctx)) {
    return
  }

  const question = str(request.params.question)

  rememberServerRequest(request)
  parkSetupBeat({
    beat,
    // SAFETY: tools/setup_beat_tool.py::_card builds every card from agent/onboarding_flow.py::BEATS.
    card: (request.params.card ?? {}) as SetupBeatCard,
    question,
    requestId: request.id,
    sessionId,
    toolCallId: str(request.params.tool_call_id) || null
  })
  markNeedsInput(ctx)
  notifyInput(ctx, question)
}

/** Method → handler. Every `ServerRequestMap` key the desktop answers. */
export const SERVER_REQUEST_HANDLERS: Record<string, Handler> = {
  approval,
  clarify,
  'display.install.sudo': displayInstallSudo,
  'preview.act': previewAct,
  'preview.read': previewRead,
  secret,
  setup_beat: setupBeat,
  sudo,
  'terminal.read': terminalRead,
  'theme.apply': themeApply,
  'theme.pick': themePick,
  tour,
  'vault.code': vaultCode,
  'vault.save_login': vaultSaveLogin,
  'vault.unlock_prompt': vaultUnlockPrompt,
  'window.read': windowRead
}

/** Dispatch one server→client request; false when the desktop has no handler for its method. */
export function handleServerRequest(
  request: ScopedServerRequest,
  deps: ServerRequestContext['deps'],
  activeSessionId: null | string
): boolean {
  const handler = SERVER_REQUEST_HANDLERS[request.method]

  if (!handler) {
    return false
  }

  const sessionId = str(request.params.session_id)

  // Resolve a request's runtime session id to its stored id through the state
  // cache the message stream maintains (rotation-aware: auto-compression
  // re-stamps `storedSessionId` on the same runtime entry). Unknown ids fall
  // through unchanged — they may already be stored ids.
  const storedIdForRuntimeId = (runtimeId: string) =>
    deps.sessionStateByRuntimeIdRef.current.get(runtimeId)?.storedSessionId ?? undefined

  if (WINDOW_OWNED_REQUESTS.has(request.method)) {
    // Route window.read through the tolerant claim (see windowReadClaimsSession);
    // every other window-owned request keeps the strict host check.
    const route = previewSessionRoute({
      activeSessionId,
      method: request.method,
      replayed: request.replayed,
      sessionId,
      storedIdForRuntimeId
    })

    if (route === 'ignore') {
      // Silence alone lets the owner win the fanout race (#113348:
      // resolve_response keeps the FIRST response, so a fast empty or
      // wrong-geometry answer from a non-claiming window could beat the
      // claimant's real answer), but a decline is not an answer: the backend
      // counts it as that client's vote and keeps the request open for the
      // owner, settling only once every attached window declined (#119333).
      // So an unclaimed window.read — even in a tolerated state where no
      // window claims it (#121609) — fails fast instead of stalling the tool
      // for its whole deadline.
      declineNotShown(request)

      return true
    }

    if (route === 'retry') {
      // Re-read the ref instead of capturing activeSessionId: session resume
      // publishes its binding synchronously between this replay and the next
      // turn. A second miss leaves the request to another window.
      setTimeout(() => {
        if (
          previewSessionRoute({
            activeSessionId: deps.activeSessionIdRef.current,
            replayed: false,
            sessionId,
            storedIdForRuntimeId
          }) === 'run'
        ) {
          handler({ deps, request, sessionId, isActiveSession: true })
        } else {
          declineNotShown(request)
        }
      }, 0)

      return true
    }
  }

  handler({
    deps,
    request,
    sessionId,
    isActiveSession: requestNamesActiveSession({ activeSessionId, sessionId, storedIdForRuntimeId })
  })

  return true
}