Skip to content

The agent that grows with you

12.5 KB
Raw Blame
import { atom } from 'nanostores'

import { resetLiveRuntimeTracking } from '@/app/contrib/hooks/use-background-sync'
import { resetSidebarBatchCapability } from '@/hermes'
import { invalidateProfileScopedQueries } from '@/lib/query-client'
import { clearArtifactRegistry } from '@/store/artifacts'
import { invalidateCronJobsRequests, setCronJobs } from '@/store/cron'
import { resetDeadSessionPrune } from '@/store/dead-session-prune'
import { resetSessionsLimit } from '@/store/layout'
import { resetLiveSync } from '@/store/live-sync'
import { invalidateProfileListFetches } from '@/store/profile'
import { exitProjectScope } from '@/store/project-scope'
import { clearLiveReactionOverlays } from '@/store/reactions-local'
import {
  $unreadFinishedSessionIds,
  setActiveSessionId,
  setCronSessions,
  setCurrentBranch,
  setCurrentCwdTransient,
  setFreshDraftReady,
  setMessages,
  setMessagingListServer,
  setMessagingPlatformTotals,
  setMessagingSessions,
  setMessagingTruncated,
  setSelectedStoredSessionId,
  setSessionProfilesFailed,
  setSessionProfilesTruncated,
  setSessionProfilesUsage,
  setSessions,
  setSessionsLoadError,
  setSessionsLoading
} from '@/store/session'
import { clearAllSessionControl } from '@/store/session-control'
import { resetSessionPinMirror } from '@/store/session-pin-sync'
import { clearAllSessionStates } from '@/store/session-states'
import { reloadOpenStarmapGraph, resetStarmapGraph } from '@/store/starmap'
import { clearAllSessionTodos } from '@/store/todos'
import { clearTranscriptTailPaging } from '@/store/transcript-tail'
import { clearTranscriptTails } from '@/store/transcript-tail-cache'

// True while a Settings → Gateway connection-mode apply is mid-flight (wipe →
// re-dial, use-gateway-boot softSwitch). Picking a registered gateway in
// Sessions is not a switch: every gateway stays connected and the pick is a
// live activation (store/connections selectConnection). Lets the boot hook suppress the
// backend-exit toast, keeps the cold-boot CONNECTING overlay from resurrecting
// when startHermes re-emits boot progress, and tells the resume path that a
// "session not found" mid-switch means "retry once things settle", not "gone".
export const $gatewaySwitching = atom(false)

/**
 * Renderer-side cleanup a connection switch must run before the next gateway
 * is activated or published: fresh-draft the open transcript, drop the overlay
 * return route, reset the project tree, close terminals — everything bound to
 * the OUTGOING backend that lives outside the session store. Registered by
 * useGatewayBoot (whose host owns those React callbacks) so store-driven
 * switches run the exact same reset as a Settings → Gateway apply.
 */
export interface GatewaySwitchLifecycle {
  beforeConnectionSwitch: () => void
  /** Re-pull the session lists from whichever backend is active NOW. */
  refreshSessions: (shouldPublish?: () => boolean) => Promise<void>
}

let switchLifecycle: GatewaySwitchLifecycle | null = null

/** Ownership handle returned by beginGatewaySwitch; see endGatewaySwitch. */
export type GatewaySwitchToken = number

let latestSwitchToken = 0

/** True only while token owns the latest connection-switch lifecycle. */
export function isCurrentGatewaySwitch(token: GatewaySwitchToken): boolean {
  return token === latestSwitchToken
}

export function registerGatewaySwitchLifecycle(lifecycle: GatewaySwitchLifecycle): () => void {
  switchLifecycle = lifecycle

  return () => {
    if (switchLifecycle === lifecycle) {
      switchLifecycle = null
    }
  }
}

/**
 * Commit point of a connection-mode apply: raise the barrier and sever every
 * binding to the outgoing backend in ONE synchronous step, BEFORE the next
 * gateway is activated or its descriptor published. Activating first and
 * wiping after (across an IPC round-trip) let route/session effects see the new
 * source while $activeSessionId still named the previous backend's runtime —
 * "session not found" (#93937).
 */
export function beginGatewaySwitch(): GatewaySwitchToken {
  const token = ++latestSwitchToken
  let wipeStarted = false

  $gatewaySwitching.set(true)

  try {
    switchLifecycle?.beforeConnectionSwitch()
    wipeStarted = true
    wipeSessionListsForGatewaySwitch()

    return token
  } catch (error) {
    // No caller received this token, so begin owns cleanup. Token-aware teardown
    // preserves a newer recursively-started switch, if lifecycle code began one.
    const stillOwnsSwitch = isCurrentGatewaySwitch(token)

    endGatewaySwitch(token)

    // A synchronous wipe has no rollback: once it starts, some outgoing-source
    // stores may already be empty. Repaint the still-active source best-effort.
    // A lifecycle failure happens before the wipe and leaves lists untouched.
    // If a nested switch superseded this one, its owner is responsible instead.
    if (wipeStarted && stillOwnsSwitch) {
      try {
        recoverActiveSourceAfterFailedGatewaySwitch(token)
      } catch {
        // Recovery must never replace the original commit failure.
      }
    }

    throw error
  }
}

/**
 * A gateway pick made while a Settings apply is mid-flight wins: the apply's
 * token stops owning any later publication, and its barrier comes down.
 */
export function supersedeGatewaySwitch(): void {
  if ($gatewaySwitching.get()) {
    latestSwitchToken += 1
    endGatewaySwitch()
  }
}

/**
 * Lower the barrier once the switch that owns it has committed (or failed).
 * Switches overlap — a click can supersede one that is mid-commit — and the
 * barrier belongs to the LATEST one: an older switch ending is a no-op while a
 * newer one is still in flight. No token = force down (host teardown).
 */
export function endGatewaySwitch(token?: GatewaySwitchToken): void {
  if (token !== undefined && !isCurrentGatewaySwitch(token)) {
    return
  }

  $gatewaySwitching.set(false)
  // The wipe reset the star map while the outgoing source was still active; requests now route
  // to whichever source the switch left active, so an open view reloads against it.
  reloadOpenStarmapGraph()
}

/**
 * A commit that fails AFTER beginGatewaySwitch leaves the still-active source
 * with its lists wiped and the sidebar skeleton armed, and nothing reactive
 * re-pulls them (no source/profile scope moved). Repaint it explicitly so the
 * sidebar doesn't sit on the skeleton; the fetch is best-effort. Recovery
 * retains the failed switch's token across the async refresh so it cannot
 * request through, or disarm loading for, a newer route.
 */
export function recoverActiveSourceAfterFailedGatewaySwitch(token: GatewaySwitchToken): void {
  const lifecycle = switchLifecycle

  if (!lifecycle) {
    console.debug('[gateway-switch] cannot repaint the active source because no switch lifecycle is registered')

    if (isCurrentGatewaySwitch(token)) {
      setSessionsLoading(false)
    }

    return
  }

  void Promise.resolve()
    .then(() =>
      isCurrentGatewaySwitch(token) ? lifecycle.refreshSessions(() => isCurrentGatewaySwitch(token)) : undefined
    )
    .catch(() => undefined)
    .finally(() => {
      if (isCurrentGatewaySwitch(token)) {
        setSessionsLoading(false)
      }
    })
}

/**
 * Clear gateway-bound session UI so sidebar skeletons retrigger.
 *
 * Sessions live in nanostores (not React Query) — refreshSessions merges into
 * the existing list, so without an explicit wipe a soft switch would keep
 * painting the previous gateway's rows. RQ caches (settings/config/skills) are
 * invalidated separately; the live session list is this path.
 *
 * Does NOT call requestFreshSession() — that navigates to NEW_CHAT and would
 * close route overlays (Settings). Clear chat state in place; leave the URL
 * alone so the user stays where they were (e.g. mid-Gateway settings).
 */
export function wipeSessionListsForGatewaySwitch(): void {
  // The next backend is a different runtime — don't carry the old one's
  // "batched sidebar endpoint missing" capability verdict across the switch.
  resetSidebarBatchCapability()
  // Strand any in-flight /api/profiles fetch from the PREVIOUS backend. The
  // rail's $profiles cache is deliberately NOT wiped (an empty list flickers
  // the rail away), but a late response from the old backend must not
  // overwrite what the new backend reports — that stale write is how a
  // remote/Cloud connection apply made the profile rail vanish (#85731).
  invalidateProfileListFetches()
  // Pins are mirrored per-backend. The next gateway has its own state.db and
  // has never seen them, so drop the "already pushed" bookkeeping and let the
  // next reconcile re-assert the whole set against the new backend.
  resetSessionPinMirror()
  // Project ids belong to the outgoing backend's projects.db; a scope left
  // entered would root the next draft's cwd in the old source's project.
  exitProjectScope()
  setSessions([])
  // Reset AFTER the wipe: the wipe's empty payload schedules a sweep, and
  // resetting first would leave that timer live — sweeping every stored id
  // against a backend that hasn't answered yet. The reset cancels the timer,
  // clears the alive cache, and marks the list unloaded, so the next real
  // payload starts a fresh first-pass window against the new backend.
  resetDeadSessionPrune()
  setSessionProfilesTruncated({})
  setSessionProfilesUsage({})
  setSessionProfilesFailed([])
  setCronSessions([])
  invalidateCronJobsRequests()
  // The star map is a scan of the outgoing backend's skills and memory; an open view reloads it
  // when the switch ends (endGatewaySwitch), not here: the outgoing source is still active.
  resetStarmapGraph()
  setCronJobs([])
  setMessagingSessions([])
  setMessagingListServer(null)
  setMessagingPlatformTotals({})
  setMessagingTruncated(false)
  // Clearing $sessionStates automatically clears $workingSessionIds and
  // $attentionSessionIds (computed) and $stalledSessionIds (owned beside it).
  // $unreadFinishedSessionIds is separate, so wipe it explicitly. Only the
  // transient paint layer is wiped: the persisted markers/watermarks in
  // session-unread.ts are keyed by durable session id and repaint the rows
  // that are still unread once the next gateway's lists load — so a profile
  // round-trip doesn't swallow green dots.
  // Runtime ids can be reused by the next backend. Retire both the live
  // checklist and its review snapshot before any new session is bound.
  clearAllSessionTodos()
  clearAllSessionStates()
  // Structured goal/loop/heartbeat entries are keyed by runtime id, which the
  // next backend re-mints, so a full wipe is exact (and stale-response-safe).
  clearAllSessionControl()
  resetLiveRuntimeTracking()
  resetLiveSync()
  $unreadFinishedSessionIds.set([])
  setSessionsLoading(true)
  setSessionsLoadError(false)
  resetSessionsLimit()

  setActiveSessionId(null)
  setSelectedStoredSessionId(null)
  setMessages([])
  setFreshDraftReady(true)

  // The draft workspace belongs to the outgoing backend. Nothing downstream
  // clears it: ensureDefaultWorkspaceCwd only seeds a NON-empty remembered
  // path and seedDefaultCwd only applies the new gateway's default when the
  // cwd is EMPTY, so a gateway with nothing remembered kept painting (and
  // sending on session.create) the previous gateway's folder (#114306).
  // Transient on purpose: the per-backend memory of the old gateway stays.
  setCurrentCwdTransient('')
  setCurrentBranch('')

  // Reaction overlays describe the outgoing backend's messages: $agentReactions
  // is keyed by bare DB row id (per-database, so the next backend's row ids name
  // different messages) and $localReactions by renderer ids the next transcript
  // regenerates. The profile-swap boundary is covered by the subscribe inside
  // reactions-local; a connection switch can keep the profile name, so it needs
  // this explicit wipe.
  clearLiveReactionOverlays()

  // Artifacts are keyed by sessions on the previous backend, so both the
  // registry and any rail tab pointing into it go with them.
  clearArtifactRegistry()

  // Cached transcript tails belong to the PREVIOUS backend's sessions; a
  // different backend can recycle stored ids, and painting another machine's
  // conversation under a same-named id is worse than a loader. Wipe both the
  // persisted cache and the in-memory paging entries — the latter are keyed by
  // owner, so a survivor from the old backend would sit beside the new one and
  // fail the unique-match lookup that shows "Show earlier".
  clearTranscriptTails()
  clearTranscriptTailPaging()

  // Narrowed: account/marketplace/onboarding caches are global, not gateway-
  // scoped, so a mode swap must not refetch them.
  invalidateProfileScopedQueries()
}