Skip to content

The agent that grows with you

57.4 KB
Raw Blame
import type { AppendMessage, ThreadMessage } from '@assistant-ui/react'
import { isUndeliveredCorrectionRefusal, JsonRpcGatewayError } from '@hermes/shared'
import { stripAnsi } from '@hermes/shared/ansi'
import { useStore } from '@nanostores/react'
import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'

import { type ResolvedOwner, transcribeAudio } from '@/hermes'
import { useI18n } from '@/i18n'
import { attachmentPathNeedsUpload } from '@/lib/attachment-upload-policy'
import { type ChatMessage, textPart } from '@/lib/chat-messages'
import { isSlashCommandText, pathLabel } from '@/lib/chat-runtime'
import { sanitizeComposerInput } from '@/lib/composer-input-sanitize'
import { triggerHaptic } from '@/lib/haptics'
import { setMutableRef } from '@/lib/mutable-ref'
import { normalize } from '@/lib/text'
import { transcribeAudioClientDirect } from '@/lib/voice-client-direct'
import { clearClarifyRequest } from '@/store/clarify'
import { setSessionCompacting } from '@/store/compaction'
import {
  $composerAttachments,
  type ComposerAttachment,
  patchMainComposerAttachmentOccurrence,
  setComposerAttachmentUploadState,
  updateComposerAttachment
} from '@/store/composer'
import { serverOwnsComposerQueue } from '@/store/composer-queue'
import { resetSessionBackground } from '@/store/composer-status'
import { confirm } from '@/store/confirm'
import { clearNotifications, notify, notifyError } from '@/store/notifications'
import { clearPreviewArtifacts } from '@/store/preview-status'
import { clearAllPrompts } from '@/store/prompts'
import {
  $busy,
  $currentCwd,
  $messages,
  $terminalBackend,
  setActiveSessionId,
  setAwaitingResponse,
  setBusy,
  setMessages,
  setTurnStartedAt
} from '@/store/session'
import { $sessionStates, isLiveTurnAwaitingEvents, isSessionRemote } from '@/store/session-states'
import { flushStreamDeltas } from '@/store/stream-delta-flush'
import { pruneFinishedSessionSubagents } from '@/store/subagents'
import { runGatewayRestart } from '@/store/system-actions'
import { clearSessionTodos } from '@/store/todos'
import { setSessionDraftingTool } from '@/store/tool-drafting'

import type {
  ClientSessionState,
  FileAttachResponse,
  HandoffFailResponse,
  HandoffRequestResponse,
  HandoffStateResponse,
  ImageAttachResponse,
  SessionRedirectResponse
} from '../../../types'
import type { CreateBackendSessionForSend } from '../use-session-actions/create-overrides'

import {
  appendMidTurnUserMessage,
  applyBranchVisibility,
  applyReloadOptimistic,
  applyRewindOptimistic,
  deepCutConfirmRequest,
  durableRowIdsForRebind,
  type EditPlan,
  finalizeStoppedMessages,
  planConfirmedReload,
  planEdit,
  planEditAfterConfirm,
  planRestore,
  rebindSurvivorRowIds,
  retryKeepsDeepConfirm,
  runRewindSubmit,
  sealAcceptedCorrection,
  type SurvivorUserRowIds
} from './rewind'
import { useSlashCommand } from './slash'
import { captureSteeringSession } from './steering-session'
import { captureSubmissionDestination } from './submission-destination'
import { useSubmitPrompt } from './submit'
import { uploadServerOwnedImage } from './upload-server-image'
import {
  blobToDataUrl,
  delay,
  friendlyRemoteAttachError,
  type GatewayRequest,
  inlineErrorMessage,
  isDeepTruncateRefusal,
  markSessionRecentlyInterrupted,
  readFileDataUrlForAttach,
  readImageForRemoteAttach,
  shouldInterruptBeforeRewind,
  type SubmitTextOptions,
  withSessionNotFoundResume
} from './utils'

interface HandoffResult {
  ok: boolean
  error?: string
}

/**
 * Stage one file/image attachment into the session workspace and return the
 * attachment rewritten with the gateway-side ref. Attachments upload their
 * bytes for remote gateways and local cross-filesystem backends; otherwise the
 * gateway receives the shared local path. Throws on failure so callers can
 * surface an error. Shared by submit-time sync, the eager drop-time upload, and
 * the message-edit composer drop — keep them in lockstep.
 */
export async function uploadComposerAttachment(
  attachment: ComposerAttachment,
  opts: {
    backendCwd?: null | string
    remote: boolean
    requestGateway: GatewayRequest
    sessionId: string
    /** Durable id used to re-register after sleep/wake or a backend restart. */
    storedSessionId?: null | string
    /** Runs BEFORE the retried attach: publish the recovered stored→runtime binding here. */
    onRecovered?: (sessionId: string) => void
    /** Called when the attach recovered onto a fresh live id. */
    onSessionRecovered?: (sessionId: string) => void
    terminalBackend?: string
  }
): Promise<ComposerAttachment> {
  const { backendCwd, remote, storedSessionId, onRecovered, onSessionRecovered, terminalBackend } = opts

  const destination = captureSubmissionDestination(storedSessionId ?? opts.sessionId, opts.requestGateway)
  const requestGateway = destination.requestGateway

  const path = attachment.path ?? ''
  const label = attachment.label || pathLabel(path)

  // Edit-message drops bypass the main composer store, so also resolve their
  // source descriptor here. Absence means an older browser backend/native file
  // and retains the existing byte-upload rules.
  const stagedUpload = attachment.kind === 'file'
    ? attachment.stagedUpload ?? window.hermesDesktop?.getStagedFileForAttach?.(path)
    : undefined

  if (stagedUpload && stagedUpload.path !== path) {
    throw new Error(`Could not attach ${label}: staged source changed; select the file again`)
  }

  const uploadBytes = !stagedUpload && (remote || attachmentPathNeedsUpload(path, backendCwd, terminalBackend))

  if (attachment.kind === 'image' && serverOwnsComposerQueue(storedSessionId ?? opts.sessionId)) {
    // Pin HTTP to the same owner before the native byte read yields. Images
    // are immutable admission payloads, never legacy agent.pending_images.
    return await uploadServerOwnedImage(attachment, destination, path, label, opts.sessionId)
  }

  // Read bytes/paths ONCE, outside the retry. Only the session-scoped RPC is
  // replayed on recovery — re-reading a multi-MB file to retry a dead session
  // id would double the disk/IPC cost of every recovered attach. Images are
  // always read fresh from disk here: the chip's cached `previewUrl` is
  // dropped once a thumbnail exists, so it cannot be trusted to hold the
  // full-resolution bytes the model needs.
  let imagePayload: Awaited<ReturnType<typeof readImageForRemoteAttach>> | null = null
  let fileDataUrl: null | string = null

  if (uploadBytes) {
    try {
      if (attachment.kind === 'image') {
        imagePayload = await readImageForRemoteAttach(path)
      } else {
        fileDataUrl = await readFileDataUrlForAttach(path)
      }
    } catch (err) {
      throw friendlyRemoteAttachError(err, label)
    }

    if (attachment.kind === 'image' ? !imagePayload : !fileDataUrl) {
      throw new Error(`Could not read ${label}`)
    }
  }

  const stageForSession = async (liveSessionId: string): Promise<ComposerAttachment> => {
    if (attachment.kind === 'image') {
      const result = imagePayload
        ? await requestGateway<ImageAttachResponse>('image.attach_bytes', {
            session_id: liveSessionId,
            content_base64: imagePayload.contentBase64,
            filename: imagePayload.filename
          })
        : await requestGateway<ImageAttachResponse>('image.attach', {
            path,
            session_id: liveSessionId
          })

      if (!result.attached) {
        throw new Error(result.message || `Could not attach ${label}`)
      }

      const attachedPath = result.path || path

      return {
        ...attachment,
        attachedSessionId: liveSessionId,
        label: attachedPath ? pathLabel(attachedPath) : attachment.label,
        path: attachedPath,
        uploadState: undefined
      }
    }

    const result = await requestGateway<FileAttachResponse>('file.attach', {
      name: label,
      session_id: liveSessionId,
      // Omit path as well as bytes for the provenance-aware branch: an older
      // RPC implementation must reject it rather than ignore source ownership.
      ...(stagedUpload
        ? { staged_upload: stagedUpload }
        : { path, ...(fileDataUrl ? { data_url: fileDataUrl } : {}) })
    })

    if (!result.attached || !result.ref_text) {
      throw new Error(result.message || `Could not attach ${label}`)
    }

    return {
      ...attachment,
      attachedSessionId: liveSessionId,
      refText: result.ref_text,
      ...(stagedUpload ? { stagedUpload } : {}),
      uploadState: undefined
    }
  }

  // Attach runs BEFORE prompt.submit, so submit's own recovery never gets a
  // chance: a stale runtime id fails here first and the user sees "session not
  // found" on an image while plain text works.
  const { result, sessionId: usedSessionId } = await withSessionNotFoundResume(
    opts.sessionId,
    storedSessionId,
    stageForSession,
    // onRecovered fires before the retried attach: the window dispatcher routes a
    // session-scoped RPC by translating its runtime id back to the stored session
    // and that session's owner, so the recovered binding must be published first
    // or an off-screen remote / multi-profile retry is rejected as ownerless.
    { requestGateway, onRecovered }
  )

  if (usedSessionId !== opts.sessionId) {
    onSessionRecovered?.(usedSessionId)
  }

  return result
}

interface PromptActionsOptions {
  activeSessionId: string | null
  activeSessionIdRef: MutableRefObject<string | null>
  busyRef: MutableRefObject<boolean>
  branchCurrentSession: () => Promise<boolean>
  createBackendSessionForSend: CreateBackendSessionForSend
  getRoutedStoredSessionId: () => null | string
  getRuntimeIdForStoredSession: (storedSessionId: string) => null | string
  getRouteToken: () => string
  handleSkinCommand: (arg: string) => string
  openMemoryGraph: () => void
  refreshSessions: () => Promise<void>
  requestGateway: <T>(method: string, params?: Record<string, unknown>, timeoutMs?: number) => Promise<T>
  resumeStoredSession: (storedSessionId: string) => Promise<void> | void
  runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>>
  selectedStoredSessionIdRef: MutableRefObject<string | null>
  startFreshSessionDraft: () => void
  sttEnabled: boolean
  updateSessionState: (
    sessionId: string,
    updater: (state: ClientSessionState) => ClientSessionState,
    storedSessionId?: string | null
  ) => ClientSessionState
}

/** Everything a slash handler needs about the invocation it's serving. */

interface RestoreMessageTarget {
  text?: string
  userOrdinal?: number | null
}

const currentMessages = (sessionId: string) => $sessionStates.get()[sessionId]?.messages ?? $messages.get()

const isStaleAfterConfirm = (sessionId: string, planned: ChatMessage[]) =>
  Boolean($sessionStates.get()[sessionId]?.busy) || currentMessages(sessionId) !== planned

// 4018 whose target sits before the live segment (compressed away): no retry can reach it.
const isCompressedAwayError = (err: unknown) => {
  const segmentOrdinal =
    err instanceof JsonRpcGatewayError && err.code === 4018 && err.data && typeof err.data === 'object'
      ? (err.data as { segment_ordinal?: unknown }).segment_ordinal
      : undefined

  return typeof segmentOrdinal === 'number' && segmentOrdinal < 0
}

const isStaleTargetError = (err: unknown) =>
  /no longer in session history|not in session history/i.test(err instanceof Error ? err.message : String(err))

export { isStaleTargetError }

export function usePromptActions({
  activeSessionId,
  activeSessionIdRef,
  busyRef,
  branchCurrentSession,
  createBackendSessionForSend,
  getRoutedStoredSessionId,
  getRuntimeIdForStoredSession,
  getRouteToken,
  handleSkinCommand,
  openMemoryGraph,
  refreshSessions,
  requestGateway,
  resumeStoredSession,
  runtimeIdByStoredSessionIdRef,
  selectedStoredSessionIdRef,
  startFreshSessionDraft,
  sttEnabled,
  updateSessionState
}: PromptActionsOptions) {
  const { t } = useI18n()
  const copy = t.desktop

  const appendSessionTextMessage = useCallback(
    (
      sessionId: string,
      role: ChatMessage['role'],
      text: string,
      storedSessionId?: string | null,
      options: { appendAfterActiveReply?: boolean } = {}
    ) => {
      // Strip ANSI: slash-command output from the backend worker carries SGR
      // color codes (e.g. "Unknown command" in red). The ESC byte is invisible
      // in the chat panel, so without this the `[1;31m…[0m` payload leaks as
      // literal text.
      const body = stripAnsi(text).trim()

      if (!body) {
        return
      }

      const messageId = `${role}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`

      updateSessionState(
        sessionId,
        state => {
          const message: ChatMessage = {
            id: messageId,
            role,
            parts: [textPart(body)]
          }

          // Mid-turn correction: arrival order. The bubble lands after the
          // assistant output the user had already seen (sealing the live
          // stream so post-redirect deltas continue BELOW the correction),
          // never spliced above it (#73793) or mid-thread via the old
          // last-assistant fallback (#83151).
          if (options.appendAfterActiveReply) {
            return appendMidTurnUserMessage(state, message)
          }

          return { ...state, messages: [...state.messages, message] }
        },
        storedSessionId ?? selectedStoredSessionIdRef.current
      )

      return messageId
    },
    [selectedStoredSessionIdRef, updateSessionState]
  )

  // In-flight drop-time eager uploads, keyed by attachment id. Submit joins
  // these before re-uploading so a drop-then-immediately-Enter can't fire
  // file.attach twice and stage duplicate copies on the gateway.
  const eagerUploadInFlight = useRef<Map<string, Promise<void>>>(new Map())

  const syncAttachmentsForSubmit = useCallback(
    async (
      sessionId: string,
      attachments: ComposerAttachment[],
      options: {
        updateComposerAttachments?: boolean
        storedSessionId?: string | null
        requestGateway?: GatewayRequest
      } = {}
    ): Promise<{ attachments: ComposerAttachment[]; sessionId: string }> => {
      const updateComposerAttachments = options.updateComposerAttachments ?? true

      // The submit's own target, never the chat on screen: a queued send drains
      // after the user has moved on, so a stale runtime here must recover the
      // session the text belongs to — not stage the files on, and then submit
      // into, whichever chat is selected now (#46194, the attachments edition).
      const storedSessionId =
        options.storedSessionId !== undefined ? options.storedSessionId : selectedStoredSessionIdRef.current

      const targetIsForeground = storedSessionId === selectedStoredSessionIdRef.current

      const uploadRequest =
        options.requestGateway ??
        captureSubmissionDestination(storedSessionId ?? sessionId, requestGateway).requestGateway

      const backendCwd = $currentCwd.get()
      const terminalBackend = $terminalBackend.get()
      const remote = isSessionRemote(storedSessionId ?? sessionId)
      let liveSessionId = sessionId
      const synced: ComposerAttachment[] = []

      // Published BEFORE the retried attach (see uploadComposerAttachment): the
      // stored→runtime binding is what routes the retry to the session's owner.
      const onRecovered = (recoveredId: string) => {
        if (storedSessionId) {
          runtimeIdByStoredSessionIdRef.current.set(storedSessionId, recoveredId)
          updateSessionState(recoveredId, state => state, storedSessionId)
        }

        // Only a foreground send may retarget the foreground: a background
        // drain that recovers its own session must not steal the view.
        if (targetIsForeground) {
          activeSessionIdRef.current = recoveredId
          setActiveSessionId(recoveredId)
        }
      }

      const onSessionRecovered = (recoveredId: string) => {
        liveSessionId = recoveredId
      }

      for (const original of attachments) {
        let attachment = original

        // Join a drop-time eager upload still in flight for this attachment
        // before deciding anything — otherwise submit and the eager task both
        // call file.attach and stage duplicate files. After it settles, take the
        // store's updated copy (its gateway ref, or its failure) over the stale
        // pre-upload snapshot.
        const inFlight = eagerUploadInFlight.current.get(attachment.id)

        if (inFlight) {
          await inFlight
          attachment = $composerAttachments.get().find(item => item.id === attachment.id) ?? attachment
        }

        // Already-synced or pathless refs (terminal, url, etc.) pass through.
        // A drop-time eager upload may already have staged this one (matching
        // attachedSessionId) — don't re-upload it. Compare against the LIVE id:
        // after a mid-loop recovery an earlier chip's attachedSessionId points
        // at the dead runtime and must be re-staged.
        if (!attachment.path || attachment.attachedSessionId === liveSessionId) {
          synced.push(attachment)

          continue
        }

        if (attachment.kind === 'image' || attachment.kind === 'file') {
          const nextAttachment = await uploadComposerAttachment(attachment, {
            backendCwd,
            remote,
            requestGateway: uploadRequest,
            sessionId: liveSessionId,
            storedSessionId,
            onRecovered,
            onSessionRecovered,
            terminalBackend
          })

          // Update-only: never resurrect a chip the user removed mid-upload.
          if (updateComposerAttachments) {
            if (original.occurrenceId) {
              // Preserve a preview that may have completed after staging began,
              // while still refusing a remove + re-add of the same path.
              patchMainComposerAttachmentOccurrence(original, {
                attachedSessionId: nextAttachment.attachedSessionId,
                label: nextAttachment.label,
                path: nextAttachment.path,
                mime: nextAttachment.mime,
                refText: nextAttachment.refText,
                stagedUpload: nextAttachment.stagedUpload,
                uploadState: nextAttachment.uploadState
              })
            } else {
              updateComposerAttachment(nextAttachment)
            }
          }

          synced.push(nextAttachment)

          continue
        }

        synced.push(attachment)
      }

      return { attachments: synced, sessionId: liveSessionId }
    },
    [activeSessionIdRef, requestGateway, runtimeIdByStoredSessionIdRef, selectedStoredSessionIdRef, updateSessionState]
  )

  // Stage a freshly dropped file as soon as it lands (when a session already
  // exists), so the upload runs while the user is still typing rather than
  // stalling the send. The card shows a spinner via `uploadState`; on success
  // the chip carries its gateway-side ref so submit skips re-uploading.
  //
  // Images are intentionally NOT eager-uploaded: thumbnail preparation already
  // performs a bounded full-file read/decode, and an eager upload would perform
  // another full-file read/IPC transfer immediately for every image in a batch.
  // Original bytes are still uploaded sequentially at submit via
  // image.attach_bytes.
  const eagerlyUploadAttachment = useCallback(
    async (sessionId: string, attachment: ComposerAttachment) => {
      const remote = isSessionRemote(sessionId)

      setComposerAttachmentUploadState(attachment.id, 'uploading')

      try {
        // Update-only: if the user removed the chip while this was uploading,
        // don't resurrect it — just drop the staged result on the floor.
        updateComposerAttachment(
          await uploadComposerAttachment(attachment, {
            backendCwd: $currentCwd.get(),
            remote,
            requestGateway,
            sessionId,
            terminalBackend: $terminalBackend.get()
          })
        )
      } catch (err) {
        // Leave the chip in place so submit-time sync can retry (or the user can
        // remove it) and flag the card; also toast so a hard failure (unreadable
        // file, gateway perms) isn't swallowed while the user keeps typing.
        setComposerAttachmentUploadState(attachment.id, 'error')
        notifyError(err, copy.dropFiles)
      }
    },
    [copy.dropFiles, requestGateway]
  )

  const composerAttachments = useStore($composerAttachments)

  useEffect(() => {
    if (!activeSessionId) {
      return
    }

    for (const attachment of composerAttachments) {
      const needsUpload =
        attachment.kind === 'file' &&
        Boolean(attachment.path) &&
        !attachment.attachedSessionId &&
        !attachment.uploadState &&
        !eagerUploadInFlight.current.has(attachment.id)

      if (!needsUpload) {
        continue
      }

      const task = eagerlyUploadAttachment(activeSessionId, attachment).finally(() =>
        eagerUploadInFlight.current.delete(attachment.id)
      )

      eagerUploadInFlight.current.set(attachment.id, task)
    }
  }, [activeSessionId, composerAttachments, eagerlyUploadAttachment])

  const submitPromptText = useSubmitPrompt({
    activeSessionIdRef,
    busyRef,
    copy,
    createBackendSessionForSend,
    getRoutedStoredSessionId,
    getRuntimeIdForStoredSession,
    getRouteToken,
    // Window dispatcher: exact owner + turn lease through the terminal event.
    // A private requestGatewayForAgent wrapper released the only client at ACK.
    requestGateway,
    runtimeIdByStoredSessionIdRef,
    resumeStoredSession,
    selectedStoredSessionIdRef,
    syncAttachmentsForSubmit,
    updateSessionState
  })

  // Queue a handoff of this session to a messaging platform and watch it to
  // a terminal state. We only write the request through the gateway; the
  // separate `hermes gateway` process performs the actual transfer, so we
  // poll `handoff.state` (mirror of the CLI's block-poll) for the result.
  const handoffSession = useCallback(
    async (
      platform: string,
      options?: { onProgress?: (state: string) => void; sessionId?: string }
    ): Promise<HandoffResult> => {
      const sid = options?.sessionId || activeSessionIdRef.current

      if (!sid) {
        return { error: copy.sessionUnavailable, ok: false }
      }

      const target = normalize(platform)

      if (!target) {
        return { error: copy.handoff.failed(''), ok: false }
      }

      try {
        options?.onProgress?.('pending')
        await requestGateway<HandoffRequestResponse>('handoff.request', {
          platform: target,
          session_id: sid
        })
      } catch (err) {
        return { error: inlineErrorMessage(err, copy.handoff.failed(target)), ok: false }
      }

      const markCompleted = (): HandoffResult => {
        appendSessionTextMessage(sid, 'system', copy.handoff.systemNote(target))
        notify({ kind: 'success', message: copy.handoff.success(target) })

        return { ok: true }
      }

      const deadline = Date.now() + 60_000
      let lastState = 'pending'

      while (Date.now() < deadline) {
        await delay(800)

        let record: HandoffStateResponse

        try {
          record = await requestGateway<HandoffStateResponse>('handoff.state', { session_id: sid })
        } catch {
          continue
        }

        const state = record.state || 'pending'

        if (state !== lastState) {
          options?.onProgress?.(state)
          lastState = state
        }

        if (state === 'completed') {
          return markCompleted()
        }

        if (state === 'failed') {
          return { error: record.error || copy.handoff.failed(target), ok: false }
        }
      }

      const cleanup = await requestGateway<HandoffFailResponse>('handoff.fail', {
        error: copy.handoff.timedOut,
        session_id: sid
      }).catch(() => null)

      if (cleanup?.state === 'completed') {
        return markCompleted()
      }

      // The messaging service can be started from the app — offer it here
      // instead of asking a desktop user a CLI question (desktop-17).
      notify({
        kind: 'error',
        message: copy.handoff.timedOut,
        action: { label: copy.handoff.startMessaging, onClick: () => void runGatewayRestart() }
      })

      return { error: copy.handoff.timedOut, ok: false }
    },
    [activeSessionIdRef, appendSessionTextMessage, copy, requestGateway]
  )

  const executeSlashCommand = useSlashCommand({
    activeSessionIdRef,
    appendSessionTextMessage,
    branchCurrentSession,
    busyRef,
    copy,
    createBackendSessionForSend,
    getRoutedStoredSessionId,
    getRuntimeIdForStoredSession,
    handleSkinCommand,
    handoffSession,
    openMemoryGraph,
    refreshSessions,
    requestGateway,
    resumeStoredSession,
    selectedStoredSessionIdRef,
    startFreshSessionDraft,
    submitPromptText,
    updateSessionState
  })

  const submitText = useCallback(
    async (rawText: string, options?: SubmitTextOptions) => {
      const visibleText = sanitizeComposerInput(rawText).trim()
      const attachments = options?.attachments ?? $composerAttachments.get()

      if (isSlashCommandText(visibleText)) {
        if (attachments.length) {
          notify({
            kind: 'warning',
            title: copy.slashCommandIgnoredTitle,
            message: copy.slashCommandIgnoredBody
          })

          return false
        }

        triggerHaptic('selection')

        // Forward the explicit target (background queue drain, tile) — dropping
        // it ran the command against whatever chat happened to be in front.
        return await executeSlashCommand(visibleText, options)
      }

      return await submitPromptText(rawText, options)
    },
    [executeSlashCommand, submitPromptText]
  )

  const transcribeVoiceAudio = useCallback(
    async (audio: Blob, owner?: ResolvedOwner) => {
      if (!sttEnabled) {
        throw new Error(copy.sttDisabled)
      }

      // Client-direct first: mic audio goes straight to the profile's STT
      // provider (config + key fetched from the connected gateway), cutting
      // the desktop→gateway audio hop. `null` = provider not client-callable
      // (local whisper, command providers, older backend) → relay unchanged.
      // Provider REJECTIONS surface — re-running the same request through
      // the relay would fail identically, just slower. `owner` is the
      // recording's owner, resolved when the mic opened: the config lookup and
      // the relay decode on the backend its STT warm-up targeted.
      const direct = await transcribeAudioClientDirect(audio, owner)

      if (direct !== null) {
        return direct
      }

      const dataUrl = await blobToDataUrl(audio)
      const result = await transcribeAudio(dataUrl, audio.type, owner)

      return result.transcript
    },
    [copy.sttDisabled, sttEnabled]
  )

  const cancelRun = useCallback(async () => {
    // Read from the ref, not the closure-captured `activeSessionId`. The
    // actions bag is a stable ref mutated in place (Object.assign on each
    // ContribWiring render), and ChatRoutesSurface is memoized on that stable
    // ref — so it does NOT re-render when activeSessionId changes, which means
    // the ChatView element's onCancel prop holds a stale cancelRun closure.
    // The closure's `activeSessionId` can be a previous session's id (or null
    // from a new-chat draft), sending session.interrupt to the wrong session.
    // The ref is updated via useEffect on every activeSessionId change, so it
    // always reflects the current session — same pattern submitText uses.
    const sessionId = activeSessionIdRef.current

    const releaseBusy = () => {
      setMutableRef(busyRef, false)
      setBusy(false)
    }

    setAwaitingResponse(false)
    setTurnStartedAt(null)

    if (!sessionId) {
      releaseBusy()
      setMessages(finalizeStoppedMessages($messages.get()))

      return
    }

    // Frontend busy clears immediately; gateway wind-down can lag. Mark so a
    // fast edit/resend still interrupt-first instead of racing 4009 (#83855).
    markSessionRecentlyInterrupted(sessionId)

    updateSessionState(sessionId, state => {
      const streamId = state.streamId
      const messages = finalizeStoppedMessages(state.messages, streamId)

      return {
        ...state,
        messages,
        busy: false,
        awaitingResponse: false,
        streamId: null,
        pendingBranchGroup: null,
        needsInput: false,
        interrupted: true,
        turnStartedAt: null,
        turnLive: false
      }
    })

    clearSessionTodos(sessionId)
    // Stop ends this turn only: background subagents keep running and keep their rows; the
    // stopped turn's own children drop out of the next roster snapshot.
    pruneFinishedSessionSubagents(sessionId)
    // No resetSessionBackground() here. A plain interrupt (Stop, or "send now"
    // on a queued message while busy) keeps the timeline, and the gateway's
    // session.interrupt deliberately leaves terminal(background=true) processes
    // running. Killing them belongs only to the rewind paths (reload / restore /
    // edit), where the spawning turns are discarded.
    setSessionDraftingTool(sessionId, '')
    // Auto-compaction sets a per-session flag that only clears on message.start
    // / message.complete / error. A hung compaction emits none of those, so the
    // "Summarizing thread" overlay sticks and Stop is the user's only recourse —
    // clear it here too so cancelling actually dismisses the panel.
    setSessionCompacting(sessionId, false)
    // Stop ends the turn, so the gateway is no longer blocked on any prompt it
    // raised. Drop this session's pending clarify / approval / sudo / secret so
    // a dead panel (and the sidebar "needs input" dot) can't linger and accept
    // an answer the backend will reject.
    clearAllPrompts(sessionId)
    clearClarifyRequest(undefined, sessionId)

    try {
      await withSessionNotFoundResume(
        sessionId,
        selectedStoredSessionIdRef.current,
        liveId => requestGateway('session.interrupt', { session_id: liveId }),
        {
          requestGateway,
          onRecovered: recoveredId => {
            activeSessionIdRef.current = recoveredId
            setActiveSessionId(recoveredId)
          }
        }
      )
      releaseBusy()
    } catch (err) {
      releaseBusy()
      notifyError(err, copy.stopFailed)
    }
  }, [activeSessionIdRef, busyRef, copy.stopFailed, requestGateway, selectedStoredSessionIdRef, updateSessionState])

  // The desktop steering action is an immediate correction: the core cancels
  // model generation and rebuilds the live turn with displayed reasoning and
  // completed work intact. During a tool it waits for the safe result boundary.
  // Returns false when the turn raced to completion so the composer can queue.
  const redirectPrompt = useCallback(
    async (rawText: string, mode: 'interrupt' | 'steer' = 'interrupt'): Promise<boolean> => {
      const text = sanitizeComposerInput(rawText).trim()

      // Ref, not the closure-captured prop — see cancelRun above. A redirect
      // reaches the live model mid-turn, so a stale target delivers the user's
      // correction into a conversation they are no longer looking at.
      const target = captureSteeringSession({
        activeSessionIdRef,
        selectedStoredSessionIdRef,
        runtimeIdByStoredSessionIdRef,
        getRoutedStoredSessionId,
        requestGateway,
        updateSessionState
      })

      if (!text || !target) {
        return false
      }

      // #105176: a steer reaches here on the composer's own busy belief, and
      // the composer keeps that belief one effect tick past the busy→false
      // settle. When it lags, the turn has already ended: redirecting would
      // echo the bubble into a chat the user never typed in and RPC an idle
      // session whose text the backend can cross-deliver into another
      // session's live run. The slice is authoritative, so refuse before the
      // optimistic insert and the caller queues the text for the conversation
      // whose run is actually live. Without a stale belief there is nothing
      // stale to catch: the caller deliberately asked for a correction (a
      // rotation gap, a recovery retry) and the gateway authoritatively
      // rejects an idle redirect.
      const liveTurn = $sessionStates.get()[target.sessionId]

      if (busyRef.current && liveTurn && !isLiveTurnAwaitingEvents(liveTurn)) {
        return false
      }

      // Accepted whether the live turn was redirected in place or queued for
      // the next turn (the build window, before the agent is wired) — either
      // way the correction reaches the model, so record it once as a real user
      // message after the interrupted checkpoint, matching the durable core
      // transcript rather than a system note that changes role after reload.
      const send = async (id: string): Promise<boolean> => {
        // Reserve the correction's arrival position, but do not seal the live
        // stream until acceptance: a refusal must leave in-flight deltas intact.
        const messageId = appendSessionTextMessage(id, 'user', text, target.storedSessionId)

        const discardOptimisticMessage = () =>
          updateSessionState(id, state => ({
            ...state,
            messages: state.messages.filter(message => message.id !== messageId)
          }))

        const moveOptimisticMessageToEnd = () =>
          updateSessionState(id, state => {
            const message = state.messages.find(candidate => candidate.id === messageId)

            return message
              ? { ...state, messages: [...state.messages.filter(candidate => candidate.id !== messageId), message] }
              : state
          })

        try {
          const result = await target.requestGateway<SessionRedirectResponse>(
            mode === 'steer' ? 'session.steer' : 'session.redirect',
            { session_id: id, text }
          )

          // TUI-26: a bare stop phrase typed mid-turn into a LOCAL voice chat ended that chat on
          // the owner and reached no turn. Settled (nothing to re-queue), and no bubble stays.
          if (result?.voice_stopped === true) {
            discardOptimisticMessage()

            return true
          }

          if (result?.status === 'redirected') {
            if (mode === 'interrupt') {
              flushStreamDeltas(id)
              updateSessionState(id, state => sealAcceptedCorrection(state, messageId))
            }

            triggerHaptic('submit')

            return true
          }

          if (result?.status === 'queued') {
            // A redirect queued in the build window is the next turn; an
            // accepted steer joins this one after its running tool.
            if (mode === 'steer') {
              flushStreamDeltas(id)
              updateSessionState(id, state => sealAcceptedCorrection(state, messageId, { keepRunningTools: true }))
            } else {
              moveOptimisticMessageToEnd()
            }

            triggerHaptic('submit')

            return true
          }
        } catch (err) {
          discardOptimisticMessage()

          // Refused before any agent saw it (the turn this pane believed busy is gone):
          // not a failed send. The composer re-queues the words as the next turn (#141644).
          if (isUndeliveredCorrectionRefusal(err)) {
            return false
          }

          throw err
        }

        discardOptimisticMessage()

        return false
      }

      try {
        // A stale runtime id after reconnect 404s ("session not found"): the
        // shared resolver resumes the stored session and retries once, so a
        // correction right after a reconnect isn't lost to the race.
        const { result } = await withSessionNotFoundResume(target.sessionId, target.storedSessionId, send, target)

        return result
      } catch (err) {
        notifyError(err, copy.promptFailed)
        throw err
      }
    },
    [
      activeSessionIdRef,
      appendSessionTextMessage,
      busyRef,
      copy.promptFailed,
      getRoutedStoredSessionId,
      requestGateway,
      runtimeIdByStoredSessionIdRef,
      selectedStoredSessionIdRef,
      updateSessionState
    ]
  )

  // A hidden note that lands mid-turn must reach the model without becoming a
  // user turn. session.steer injects it into the model's next tool result and
  // records nothing in the transcript; a redirect would paint it as the user's
  // own bubble and store it as one.
  const injectHiddenPrompt = useCallback(
    async (rawText: string): Promise<boolean> => {
      const text = sanitizeComposerInput(rawText).trim()

      const target = captureSteeringSession({
        activeSessionIdRef,
        selectedStoredSessionIdRef,
        runtimeIdByStoredSessionIdRef,
        getRoutedStoredSessionId,
        requestGateway,
        updateSessionState
      })

      if (!text || !target) {
        return false
      }

      const send = async (id: string): Promise<boolean> => {
        const response = await target.requestGateway<SessionRedirectResponse>('session.steer', { session_id: id, text })

        return response?.status === 'queued'
      }

      try {
        const { result } = await withSessionNotFoundResume(target.sessionId, target.storedSessionId, send, target)

        return result
      } catch {
        return false
      }
    },
    [
      activeSessionIdRef,
      getRoutedStoredSessionId,
      requestGateway,
      runtimeIdByStoredSessionIdRef,
      selectedStoredSessionIdRef,
      updateSessionState
    ]
  )

  // After a durable rewind the surviving bubbles' cached rowIds are stale (the
  // gateway re-inserted the kept prefix as new SQLite rows). Rebind them to the
  // authoritative post-rewrite ids so the NEXT rewind/edit/regenerate doesn't
  // send a dead id and get refused with 4018 (consecutive-rewind staleness,
  // #83202 review).
  const applySurvivorRowIds = useCallback(
    (sessionId: string, survivorRowIds: SurvivorUserRowIds | undefined) => {
      if (!survivorRowIds) {
        return
      }

      updateSessionState(sessionId, state => ({
        ...state,
        messages: rebindSurvivorRowIds(state.messages, survivorRowIds)
      }))
    },
    [updateSessionState]
  )

  const submitRewindPrompt = useCallback(
    (
      sessionId: string,
      text: string,
      truncateOrdinal: number | undefined,
      truncateMessageId: string | undefined,
      interruptFirst: boolean,
      truncateRowId?: number,
      sourceText?: string,
      rebindRowIds?: readonly number[],
      confirmDeepTruncate?: boolean
    ) =>
      runRewindSubmit(
        requestGateway,
        sessionId,
        text,
        truncateOrdinal,
        truncateMessageId,
        interruptFirst,
        {
          storedSessionId: selectedStoredSessionIdRef.current,
          onSessionRecovered: recoveredId => {
            activeSessionIdRef.current = recoveredId
            setActiveSessionId(recoveredId)
          }
        },
        truncateRowId,
        sourceText,
        rebindRowIds,
        confirmDeepTruncate
      ),
    [activeSessionIdRef, requestGateway, selectedStoredSessionIdRef]
  )

  // answeredFor is internal (the 4033 re-run); assistant-ui calls onReload(parentId, config).
  const runReload = useCallback(
    async (parentId: string | null, answeredFor?: ChatMessage[]): Promise<void> => {
      // Ref, not the closure-captured prop — a truncating resubmit aimed at a
      // stale session deletes the wrong transcript.
      const sessionId = activeSessionIdRef.current

      if (!sessionId || $sessionStates.get()[sessionId]?.busy) {
        return
      }

      // Active sessions publish their transcript into $sessionStates[runtimeId];
      // the global $messages mirror is empty/divergent for them (#68734).
      const messages = (sessionId ? $sessionStates.get()[sessionId]?.messages : null) ?? $messages.get()
      const confirmDeep = () => confirm(deepCutConfirmRequest(t.assistant.thread))
      // The user's answer to a 4033 covers only the transcript they answered for: any change asks again.
      const forceDeep = answeredFor !== undefined && answeredFor === messages
      const planned = await planConfirmedReload(messages, parentId, forceDeep ? async () => true : confirmDeep)
      const plan = planned && forceDeep ? { ...planned, confirmDeepTruncate: true } : planned

      // The confirm is a wait of user length: a turn that started or output that landed meanwhile
      // makes the plan (and the rollback snapshot) stale, so drop it rather than cut a live turn.
      if (!plan || activeSessionIdRef.current !== sessionId || isStaleAfterConfirm(sessionId, messages)) {
        return
      }

      // Regenerate truncates history (prompt.submit truncate_before_*) just like
      // restore/edit, so the discarded turns' todos and background processes
      // belong to an abandoned timeline — drop them before the re-run.
      clearSessionTodos(sessionId)
      resetSessionBackground(sessionId)
      clearPreviewArtifacts(sessionId)

      clearNotifications()
      updateSessionState(sessionId, state => applyReloadOptimistic(state, plan))

      try {
        const survivorRowIds = await submitRewindPrompt(
          sessionId,
          plan.text,
          plan.truncateOrdinal,
          plan.truncateMessageId,
          false,
          plan.truncateRowId,
          plan.sourceText,
          durableRowIdsForRebind(messages),
          plan.confirmDeepTruncate
        )

        applySurvivorRowIds(sessionId, survivorRowIds)
      } catch (err) {
        // Same rollback as restoreToMessage below: applyReloadOptimistic
        // already hid/truncated the transcript, and leaving that in place
        // after a rejected submit is what blanked the chat (#95745).
        updateSessionState(sessionId, state => ({
          ...state,
          busy: false,
          awaitingResponse: false,
          turnLive: false,
          turnStartedAt: null,
          messages
        }))

        if (!isDeepTruncateRefusal(err) || plan.confirmDeepTruncate) {
          notifyError(err, copy.regenerateFailed)
        } else if ((await confirmDeep()) && activeSessionIdRef.current === sessionId) {
          // Re-run from the top: the session is re-read and re-validated after this wait. The answer
          // belongs to this session: a switch during the dialog drops it.
          await runReloadRef.current(parentId, messages)
        }
      }
    },
    [activeSessionIdRef, applySurvivorRowIds, copy.regenerateFailed, submitRewindPrompt, t, updateSessionState]
  )

  const runReloadRef = useRef(runReload)
  runReloadRef.current = runReload
  const reloadFromMessage = useCallback((parentId: string | null) => runReload(parentId), [runReload])

  // Cursor-style "restore checkpoint": rewind the conversation to a past user
  // prompt and run it again from there. Reuses the edit composer's rewind
  // mechanism — `prompt.submit` with `truncate_before_user_ordinal` drops that
  // user turn and everything after it from the session history, then the same
  // text is submitted as a fresh turn. Callers confirm before invoking; errors
  // are rethrown so callers can surface failures. Idle rewinds submit directly:
  // interrupting an idle agent can leave a stale interrupt flag that cancels the
  // fresh turn. Live/stuck turns interrupt first, and a raced "session busy"
  // response interrupts + retries through the shared busy gate.
  const restoreToMessage = useCallback(
    async (messageId: string, target?: RestoreMessageTarget) => {
      // Ref, not the closure-captured prop — a rewind is destructive, so a
      // stale target truncates a conversation the user did not ask to rewind.
      const sessionId = activeSessionIdRef.current

      if (!sessionId) {
        throw new Error('No active session to restore.')
      }

      // Same dual-store read as reloadFromMessage (#68734).
      const messages = (sessionId ? $sessionStates.get()[sessionId]?.messages : null) ?? $messages.get()

      const plan = planRestore(messages, messageId, target)

      // The turns we're discarding may have spawned todos and background
      // processes; they belong to the abandoned timeline, so wipe their status
      // rows (and kill the live processes) before the fresh run repopulates.
      clearSessionTodos(sessionId)
      resetSessionBackground(sessionId)
      clearPreviewArtifacts(sessionId)

      // Capture before optimistic busy=true — otherwise interruptFirst is always
      // true and idle restores wrongly interrupt (and Stop→edit misses cooldown).
      const interruptFirst = shouldInterruptBeforeRewind({
        busy: busyRef.current || $busy.get(),
        sessionId
      })

      clearNotifications()
      setMutableRef(busyRef, true)
      setBusy(true)
      setAwaitingResponse(true)
      updateSessionState(sessionId, state => applyRewindOptimistic(state, plan.sourceIndex))

      try {
        const survivorRowIds = await submitRewindPrompt(
          sessionId,
          plan.text,
          plan.truncateOrdinal,
          plan.truncateMessageId,
          interruptFirst,
          plan.truncateRowId,
          plan.sourceText,
          durableRowIdsForRebind(messages),
          true
        )

        applySurvivorRowIds(sessionId, survivorRowIds)
      } catch (err) {
        let surfaced: unknown = err

        // A restore target can be addressed by a cached durable row id that
        // went stale after optimistic sends, resume drift, or session.branch
        // row-id remapping. Mirror edit's recovery: reload the selected stored
        // session, recompute the restore plan against fresh history, and retry
        // once instead of leaving Restore uniquely fail-closed (#107593).
        if ((plan.truncateMessageId || plan.truncateRowId !== undefined) && isStaleTargetError(err)) {
          try {
            const storedId = selectedStoredSessionIdRef.current

            if (storedId) {
              await resumeStoredSession(storedId)
            }

            const refreshed = $messages.get()

            const retryPlan = planRestore(refreshed, messageId, {
              text: target?.text ?? plan.sourceText,
              userOrdinal: target?.userOrdinal ?? plan.truncateOrdinal
            })

            if (retryPlan.truncateMessageId || retryPlan.truncateRowId !== undefined) {
              const survivorRowIds = await submitRewindPrompt(
                sessionId,
                retryPlan.text,
                retryPlan.truncateOrdinal,
                retryPlan.truncateMessageId,
                false,
                retryPlan.truncateRowId,
                retryPlan.sourceText,
                durableRowIdsForRebind(refreshed),
                true
              )

              applySurvivorRowIds(sessionId, survivorRowIds)

              return
            }
          } catch (retryErr) {
            surfaced = retryErr
          }
        }

        // The rewind never landed (e.g. the gateway stayed busy past the retry
        // deadline). Roll the optimistic truncation back to the full original
        // history so the UI doesn't desync from what's persisted — leaving it
        // truncated is what made subsequent sends look duplicative.
        setMutableRef(busyRef, false)
        setBusy(false)
        setAwaitingResponse(false)
        updateSessionState(sessionId, state => ({
          ...state,
          busy: false,
          awaitingResponse: false,
          turnLive: false,
          turnStartedAt: null,
          messages
        }))
        throw surfaced
      }
    },
    [
      activeSessionIdRef,
      applySurvivorRowIds,
      busyRef,
      resumeStoredSession,
      selectedStoredSessionIdRef,
      submitRewindPrompt,
      updateSessionState
    ]
  )

  // Roll an optimistic edit/truncation back to *messages* (the original history) so the UI stays in
  // sync with what's persisted instead of stranding a partial timeline; without *messages* only the
  // busy state is cleared. *ownsForeground* is false when the foreground flags now belong to another
  // session (the user switched away during a confirm).
  const rollBackEdit = useCallback(
    (sessionId: string, messages?: ChatMessage[], ownsForeground = true) => {
      if (ownsForeground) {
        setMutableRef(busyRef, false)
        setBusy(false)
        setAwaitingResponse(false)
      }

      updateSessionState(sessionId, state => ({
        ...state,
        busy: false,
        awaitingResponse: false,
        turnLive: false,
        turnStartedAt: null,
        ...(messages ? { messages } : {})
      }))
    },
    [busyRef, updateSessionState]
  )

  // Stale target after compression/resume drift (the cached rowId and ordinal address the
  // pre-compression segment): reload server history, recompute the full edit plan against the
  // refreshed transcript, and retry the real edit once. Do NOT plain-resubmit without a truncation
  // address — that drops rewind semantics and silently appends the edit as a new turn (#82462).
  // Returns 'done' once the retry was sent, or declined and rolled back; otherwise the error to
  // surface and whether that submit carried the deep confirm.
  const retryStaleEdit = useCallback(
    async (
      sessionId: string,
      edited: AppendMessage,
      plan: EditPlan & { confirmDeepTruncate: boolean },
      messages: ChatMessage[]
    ): Promise<'done' | { surfaced?: unknown; surfacedConfirmed?: boolean; unavailable: boolean }> => {
      let surfacedConfirmed: boolean | undefined

      try {
        const storedId = selectedStoredSessionIdRef.current

        if (storedId) {
          await resumeStoredSession(storedId)
        }

        // The resume can rebind the runtime (or the user switched away meanwhile): surface that as
        // unavailable rather than drop the edit.
        if (activeSessionIdRef.current !== sessionId) {
          return { unavailable: true }
        }

        // A refresh that keeps the same later turns keeps the user's answer; one that reveals more
        // asks again. After the dialog the plan is re-aimed by content (revalidateEditPlan), since the
        // session slice and the $messages mirror are distinct arrays.
        const refreshed = $messages.get()
        const first = planEdit(refreshed, edited)

        if (!first || first.isFailedTurn) {
          return { unavailable: true }
        }

        const planned = await planEditAfterConfirm({
          answeredFor: retryKeepsDeepConfirm(plan, messages, first, refreshed) ? refreshed : undefined,
          confirmDeep: () => confirm(deepCutConfirmRequest(t.assistant.thread)),
          current: () => currentMessages(sessionId),
          edited,
          planning: refreshed,
          stillOwned: () => activeSessionIdRef.current === sessionId
        })

        if (planned === null || planned === 'moved') {
          if (planned === 'moved') {
            // The edited turn moved while the confirm was open: nothing was sent.
            notify({ kind: 'warning', message: copy.editFailed })
          }

          // Nothing was cut. A turn the backend accepted meanwhile (another window, a queued
          // follow-up) owns the busy flags and the transcript now, so leave both to it. Otherwise,
          // after a refresh the optimistic edit is already gone: keep whatever history the session
          // holds now; with no stored session to refresh from, restore the original history. A
          // switch during the confirm leaves the foreground flags to the session now on screen.
          if (!$sessionStates.get()[sessionId]?.turnLive) {
            rollBackEdit(sessionId, storedId ? undefined : messages, activeSessionIdRef.current === sessionId)
          }

          return 'done'
        }

        const { messages: target, plan: retryPlan } = planned
        surfacedConfirmed = retryPlan.confirmDeepTruncate

        const survivorRowIds = await submitRewindPrompt(
          sessionId,
          retryPlan.text,
          retryPlan.truncateOrdinal,
          retryPlan.truncateMessageId,
          false,
          retryPlan.truncateRowId,
          retryPlan.sourceText,
          durableRowIdsForRebind(target),
          surfacedConfirmed
        )

        applySurvivorRowIds(sessionId, survivorRowIds)

        return 'done'
      } catch (retryErr) {
        return {
          surfaced: retryErr,
          surfacedConfirmed,
          unavailable: isCompressedAwayError(retryErr) || isStaleTargetError(retryErr)
        }
      }
    },
    [
      activeSessionIdRef,
      applySurvivorRowIds,
      copy.editFailed,
      resumeStoredSession,
      rollBackEdit,
      selectedStoredSessionIdRef,
      submitRewindPrompt,
      t
    ]
  )

  const runEdit = useCallback(
    async (edited: AppendMessage, answeredFor?: ChatMessage[]): Promise<void> => {
      // Ref, not the closure-captured prop — an edit rewinds and resubmits, so
      // a stale target rewrites the wrong session's history.
      const sessionId = activeSessionIdRef.current

      // Same dual-store read as reloadFromMessage (#68734).
      const planning = (sessionId ? $sessionStates.get()[sessionId]?.messages : null) ?? $messages.get()

      const confirmDeep = () => confirm(deepCutConfirmRequest(t.assistant.thread))

      if (!sessionId) {
        return
      }

      const planned = await planEditAfterConfirm({
        answeredFor,
        confirmDeep,
        current: () => currentMessages(sessionId),
        edited,
        planning,
        stillOwned: () => activeSessionIdRef.current === sessionId
      })

      if (planned === 'moved') {
        // The edited turn moved while the confirm was open: nothing was sent.
        notify({ kind: 'warning', message: copy.editFailed })
      }

      if (!planned || planned === 'moved') {
        return
      }

      const { messages, plan } = planned

      // Sending an edit is a revert: rewind to this prompt and re-run with the
      // new text (submitRewindPrompt interrupts a live turn first). Same as
      // restore, so drop the abandoned timeline's todos/background rows before
      // the re-run repopulates them.
      clearSessionTodos(sessionId)
      resetSessionBackground(sessionId)
      clearPreviewArtifacts(sessionId)

      // Before optimistic busy=true — see restoreToMessage (#83855).
      const interruptFirst = shouldInterruptBeforeRewind({
        busy: busyRef.current || $busy.get(),
        sessionId
      })

      clearNotifications()
      setMutableRef(busyRef, true)
      setBusy(true)
      setAwaitingResponse(true)
      updateSessionState(sessionId, state => applyRewindOptimistic(state, plan.sourceIndex, plan.editedMessage))

      try {
        const survivorRowIds = await submitRewindPrompt(
          sessionId,
          plan.text,
          plan.truncateOrdinal,
          plan.truncateMessageId,
          interruptFirst,
          plan.truncateRowId,
          plan.sourceText,
          durableRowIdsForRebind(messages),
          plan.confirmDeepTruncate
        )

        applySurvivorRowIds(sessionId, survivorRowIds)
      } catch (err) {
        let surfaced: unknown = err
        let unavailable = isCompressedAwayError(err)
        // Whether the submit that produced *surfaced* carried a deep-cut confirm.
        let surfacedConfirmed = plan.confirmDeepTruncate

        // Stale target after compression/resume drift: reload, re-plan, retry once (#82462).
        if (!plan.isFailedTurn && !unavailable && isStaleTargetError(err)) {
          const retried = await retryStaleEdit(sessionId, edited, plan, messages)

          if (retried === 'done') {
            return
          }

          unavailable = retried.unavailable

          if (retried.surfaced !== undefined) {
            surfaced = retried.surfaced
          }

          if (retried.surfacedConfirmed !== undefined) {
            surfacedConfirmed = retried.surfacedConfirmed
          }
        }

        rollBackEdit(sessionId, messages)

        if (!isDeepTruncateRefusal(surfaced) || surfacedConfirmed) {
          notifyError(surfaced, unavailable ? copy.editTurnUnavailable : copy.editFailed)
        } else if ((await confirmDeep()) && activeSessionIdRef.current === sessionId) {
          // Re-run from the top: the session is re-read and re-validated after this wait. The answer
          // belongs to this session (a switch during the dialog drops it) and to *planning*: after a
          // refresh the transcript differs, so the re-run asks once more.
          await runEditRef.current(edited, planning)
        }
      }
    },
    [
      activeSessionIdRef,
      applySurvivorRowIds,
      busyRef,
      copy.editFailed,
      copy.editTurnUnavailable,
      resumeStoredSession,
      selectedStoredSessionIdRef,
      retryStaleEdit,
      rollBackEdit,
      submitRewindPrompt,
      t,
      updateSessionState
    ]
  )

  const runEditRef = useRef(runEdit)
  runEditRef.current = runEdit
  const editMessage = useCallback((edited: AppendMessage) => runEdit(edited), [runEdit])

  const handleThreadMessagesChange = useCallback(
    (nextMessages: readonly ThreadMessage[]) => {
      const sessionId = activeSessionIdRef.current

      if (!sessionId) {
        return
      }

      updateSessionState(sessionId, state => applyBranchVisibility(state, nextMessages))
    },
    [activeSessionIdRef, updateSessionState]
  )

  return {
    cancelRun,
    editMessage,
    // Session tiles route their slash input here (targets THEIR session via
    // options.sessionId; app-level effects — branch, handoff — act on main).
    executeSlashCommand,
    handleThreadMessagesChange,
    handoffSession,
    injectHiddenPrompt,
    reloadFromMessage,
    restoreToMessage,
    redirectPrompt,
    /** @deprecated Use `redirectPrompt` — this is an active-turn redirect, not tool steer. */
    steerPrompt: redirectPrompt,
    submitText,
    transcribeVoiceAudio
  }
}