Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

33.4 KB
Raw Blame
'use client';

import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';

import type { HistoryAgentIntent } from '../utils/historyAgentSearch.js';
import { replaceSessionShareSearch } from '../utils/sessionShareUrl.js';
import {
  freshAgentBuilderSeed,
  readDraftSpecPreferences,
  selectDraftSpecPreferences,
  webSearchPreferenceToStore,
  withCapabilitiesSandbox,
  withCapabilitiesWebSearch,
  writeDraftSpecPreferences,
  type DraftPreferenceKind,
} from './draftSpecPreferences.js';
import {
  isEnvironmentsChromeEnabled,
  isSchedulesChromeEnabled,
  isSessionsChromeEnabled,
  isSettingsChromeEnabled,
} from './serverChrome.js';
import {
  useOptionalAgentSessionsServer,
  useOptionalCatalogServer,
  useOptionalRefreshServerCapabilities,
  useOptionalSandboxEnvironmentServer,
  useOptionalScheduleServer,
  useServerCapabilities,
  useServerCapabilitiesSettled,
} from './ServerContext.js';
import type { AgentLibraryEntry, AgentSpec } from './types.js';

/** Host-facing shell configuration for agent / library / composer chrome. */
export type AgentConfig =
  | { mode: 'SingleAgent'; name: string }
  | { mode: 'AgentLibrary' }
  | { mode: 'AgentComposer'; defaultAgentSpec?: AgentSpec }
  | { mode: 'AgentLibraryWithComposer'; defaultAgentSpec?: AgentSpec };

export const DEFAULT_AGENT_CONFIG: AgentConfig = {
  mode: 'AgentLibraryWithComposer',
};

/**
 * Active chat binding. Mutability (`isMutable`) decides draft vs named runtime.
 * `isCreateAgent` (mutable only) splits New Agent builder chrome from simple New Chat.
 */
export type ShellMode =
  | { status: 'idle' }
  | {
      status: 'active';
      isMutable: boolean;
      /**
       * Mutable only: true = Agent builder (config drawer + Save); false = simple chat.
       * Always false when `isMutable` is false (Try / named).
       */
      isCreateAgent: boolean;
      /** Identity for immutable bind + history filter. */
      agentId?: string;
      /** Display / welcome label (often same as agentId). */
      agentName?: string;
      /** Published-agent description, kept outside the executable agent spec. */
      description?: string;
      /** Seed for mutable (draft) runtime. */
      agentSpec?: AgentSpec;
      locked: boolean;
    };

/** Library / New Chat / New Agent create intent. */
export type SelectLibraryAgentRequest = {
  isMutable: boolean;
  /**
   * Mutable only. When omitted: true if Edit identity is present, else false (New Chat).
   */
  isCreateAgent?: boolean;
  agentId?: string;
  agentName?: string;
  description?: string;
  agentSpec?: AgentSpec;
};

export type SettingsSection = 'models' | 'connectors' | 'skills' | 'sandbox' | 'web-search';

export type HistoryAgentFilter = {
  agentId?: string;
  agentName: string;
  intent: HistoryAgentIntent;
};

type ShellModeContextValue = {
  mode: ShellMode;
  /** Host agentConfig mode (capabilities source). */
  agentConfigMode: AgentConfig['mode'];
  /** Agents chrome. */
  isLibraryEnabled: boolean;
  /** Mutable composer / Save Agent chrome (host capability). */
  isComposerEnabled: boolean;
  /** Sidebar / list New Chat control. */
  isNewChatEnabled: boolean;
  settingsOpen: boolean;
  settingsSection: SettingsSection;
  setSettingsOpen: (open: boolean, section?: SettingsSection) => void;
  agentConfigOpen: boolean;
  setAgentConfigOpen: (open: boolean) => void;
  /** Agents main-pane overlay (sidebar layout). */
  libraryOpen: boolean;
  libraryAgentId: string | null;
  setLibraryAgentId: (id: string | null) => void;
  setLibraryOpen: (open: boolean) => void;
  /** All-user sessions browser (includes drafts). */
  sessionsOpen: boolean;
  setSessionsOpen: (open: boolean) => void;
  /** Session shown in the detail-only sharing surface. */
  sharedSessionId: string | null;
  openSharedSession: (sessionId: string) => void;
  closeSharedSession: () => void;
  openLibraryAgent: (agentId: string) => void;
  closeLibraryAgent: () => void;
  schedulesOpen: boolean;
  setSchedulesOpen: (open: boolean) => void;
  environmentsOpen: boolean;
  setEnvironmentsOpen: (open: boolean) => void;
  /**
   * Bind from Agents (Try = immutable, Edit = mutable + agentSpec).
   * Prefer this over `selectAgent` / `openDraft` when both fields are available.
   */
  selectLibraryAgent: (req: SelectLibraryAgentRequest) => void;
  /**
   * Attach identity + agentSpec to the *current* mutable chat without remounting.
   * Used after `saveAgent` so the same draft session continues as an editable agent.
   */
  bindMutableAgent: (req: { agentId: string; agentName: string; description?: string; agentSpec: AgentSpec }) => void;
  /** @deprecated Prefer `selectLibraryAgent({ isMutable: false, agentName })`. */
  selectAgent: (agentName: string) => void;
  /** Open a simple New Chat (mutable, no agent-builder chrome). */
  openDraft: () => void;
  /** Open New Agent builder (mutable + Agent Config drawer). */
  openAgentBuilder: () => void;
  /**
   * Remount New Agent with a clean config panel (model + runtime toggles only).
   * Clears instructions, MCP servers, skills, and saved-agent identity.
   * Pass the live draft when available so model/runtime edits are not discarded.
   */
  resetAgentBuilder: (liveSpec?: AgentSpec) => void;
  /** Remember plain-draft composer choices as the seed for future New Chat / New Agent. */
  rememberDraftSpec: (agentSpec: AgentSpec, kind?: DraftPreferenceKind) => void;
  /**
   * Open a history session without remounting the runtime.
   * Prefer explicit `isMutable`; otherwise agentName means immutable.
   */
  openHistorySession: (req: {
    sessionId: string;
    agentName?: string;
    isMutable?: boolean;
    isCreateAgent?: boolean;
  }) => void;
  /**
   * Keep `/sessions/:id` in place and surface a full-pane load failure
   * (no toast / redirect). Cleared when opening another session or draft.
   */
  openInaccessibleSession: (req: { sessionId: string; message: string }) => void;
  /** Backend/access message when the current pending session could not be opened. */
  sessionAccessError: string | null;
  /**
   * Reset current chat; no-op when idle.
   * Builder New Chat passes the live draft so the remount keeps the left panel.
   */
  clearChat: (liveSpec?: AgentSpec) => void;
  /** Return library-only mode to its idle landing; no-op in other modes. */
  openLibraryHome: () => void;
  /** Changes only when the chat runtime must reset. */
  runtimeKey: string;
  /**
   * History list filter forwarded as `listSessions({ agentId })`.
   * `null` = All chats. Only meaningful when `isLibraryEnabled`.
   */
  historyAgentFilter: HistoryAgentFilter | null;
  setHistoryAgentFilter: (filter: HistoryAgentFilter | null) => void;
  /** Effective `listSessionsAgentId` for the runtime (SingleAgent locks to name). */
  listSessionsAgentId: string | undefined;
  /** Session selected from history. */
  pendingSessionId: string | undefined;
  /** Distinguishes repeated selections of the same session. */
  pendingSessionEpoch: number;
  /**
   * Bumped when the Agents catalog may have changed (e.g. after saveAgent).
   * Library chrome should re-fetch when this changes.
   */
  agentsListEpoch: number;
  invalidateAgentsList: () => void;
  /**
   * Bumped when sandbox environments may have changed (create/update/delete/ready).
   * Agent environment pickers should re-fetch when this changes.
   */
  environmentsListEpoch: number;
  invalidateEnvironmentsList: () => void;
};

const ShellModeContext = createContext<ShellModeContextValue | null>(null);

const FALLBACK_MUTABLE_SPEC: AgentSpec = {
  model: { name: 'openai-main/gpt-4.1' },
};

function mutableSeedFromConfig(config: AgentConfig): AgentSpec {
  if (config.mode === 'AgentComposer' || config.mode === 'AgentLibraryWithComposer') {
    return config.defaultAgentSpec ?? FALLBACK_MUTABLE_SPEC;
  }
  return FALLBACK_MUTABLE_SPEC;
}

function initialMode(config: AgentConfig, mutableSeed: AgentSpec): ShellMode {
  switch (config.mode) {
    case 'SingleAgent':
      return {
        status: 'active',
        isMutable: false,
        isCreateAgent: false,
        agentId: config.name,
        agentName: config.name,
        locked: true,
      };
    case 'AgentLibrary':
      return { status: 'idle' };
    case 'AgentComposer':
    case 'AgentLibraryWithComposer':
      return {
        status: 'active',
        isMutable: true,
        isCreateAgent: false,
        agentSpec: mutableSeed,
        locked: false,
      };
  }
}

function resolveMutableIsCreateAgent(req: SelectLibraryAgentRequest): boolean {
  if (req.isCreateAgent !== undefined) return req.isCreateAgent;
  return req.agentId != null || req.agentName != null;
}

function libraryAgentId(agent: Pick<AgentLibraryEntry, 'agentId' | 'name'>): string {
  return agent.agentId ?? agent.name;
}

export function ShellModeProvider({
  agentConfig = DEFAULT_AGENT_CONFIG,
  initialSettingsOpen = false,
  children,
}: {
  agentConfig?: AgentConfig;
  /** Open settings on first paint (e.g. host boot with no models). Does not re-open later. */
  initialSettingsOpen?: boolean;
  children: ReactNode;
}) {
  const capabilities = useServerCapabilities();
  const capabilitiesPending = !useServerCapabilitiesSettled();
  const catalog = useOptionalCatalogServer();
  const refreshCapabilities = useOptionalRefreshServerCapabilities();
  const sessionsServer = useOptionalAgentSessionsServer();
  const scheduleServer = useOptionalScheduleServer();
  const sandboxEnvironmentServer = useOptionalSandboxEnvironmentServer();
  const chatSeedRef = useRef(
    readDraftSpecPreferences('chat') ?? selectDraftSpecPreferences(mutableSeedFromConfig(agentConfig), 'chat'),
  );
  const agentSeedRef = useRef(
    readDraftSpecPreferences('agent') ?? selectDraftSpecPreferences(mutableSeedFromConfig(agentConfig), 'agent'),
  );

  const isLibraryEnabled = agentConfig.mode === 'AgentLibrary' || agentConfig.mode === 'AgentLibraryWithComposer';
  const isComposerEnabled = agentConfig.mode === 'AgentComposer' || agentConfig.mode === 'AgentLibraryWithComposer';
  const isNewChatEnabled = agentConfig.mode !== 'AgentLibrary';
  const locked = agentConfig.mode === 'SingleAgent';

  const [mode, setMode] = useState<ShellMode>(() => initialMode(agentConfig, chatSeedRef.current));
  const [mutableEpoch, setMutableEpoch] = useState(0);
  const [clearEpoch, setClearEpoch] = useState(0);
  const [agentsListEpoch, setAgentsListEpoch] = useState(0);
  const [environmentsListEpoch, setEnvironmentsListEpoch] = useState(0);
  const [settingsOpenState, setSettingsOpenState] = useState(initialSettingsOpen);
  const [settingsSection, setSettingsSection] = useState<SettingsSection>('models');
  const [agentConfigOpenState, setAgentConfigOpenState] = useState(false);
  const [libraryOpenState, setLibraryOpenState] = useState(false);
  const [sessionsOpenState, setSessionsOpenState] = useState(false);
  const [sharedSessionId, setSharedSessionId] = useState<string | null>(null);
  const [libraryAgentId, setLibraryAgentId] = useState<string | null>(null);
  const [schedulesOpenState, setSchedulesOpenState] = useState(false);
  const [environmentsOpenState, setEnvironmentsOpenState] = useState(false);
  const [historyAgentFilter, setHistoryAgentFilter] = useState<HistoryAgentFilter | null>(null);
  const [pendingSessionId, setPendingSessionId] = useState<string | undefined>(undefined);
  const [pendingSessionEpoch, setPendingSessionEpoch] = useState(0);
  const [sessionAccessError, setSessionAccessError] = useState<string | null>(null);
  const settingsEnabled = isSettingsChromeEnabled({ catalog, capabilities });
  const settingsOpen = settingsEnabled && settingsOpenState;
  const sessionsEnabled = isSessionsChromeEnabled({ sessions: sessionsServer });
  const schedulesEnabled = isSchedulesChromeEnabled({ schedules: scheduleServer });
  const schedulesOpen = schedulesEnabled && schedulesOpenState;
  const environmentsEnabled = isEnvironmentsChromeEnabled({ sandboxEnvironments: sandboxEnvironmentServer });
  const environmentsOpen = environmentsEnabled && environmentsOpenState;
  const libraryOpen = isLibraryEnabled && libraryOpenState;
  const sessionsOpen = sessionsEnabled && sessionsOpenState;
  const setSessionsOpen = useCallback(
    (open: boolean) => {
      if (open) {
        setSettingsOpenState(false);
        setAgentConfigOpenState(false);
        setLibraryOpenState(false);
        setLibraryAgentId(null);
        setSchedulesOpenState(false);
        setEnvironmentsOpenState(false);
      } else {
        replaceSessionShareSearch({
          view: null,
          ...(sharedSessionId == null ? {} : { sessionId: null }),
        });
      }
      setSharedSessionId(null);
      setSessionsOpenState(sessionsEnabled && open);
    },
    [sessionsEnabled, sharedSessionId],
  );
  const openSharedSession = useCallback(
    (sessionId: string) => {
      if (!sessionsEnabled) return;
      setSettingsOpenState(false);
      setAgentConfigOpenState(false);
      setLibraryOpenState(false);
      setLibraryAgentId(null);
      setSchedulesOpenState(false);
      setEnvironmentsOpenState(false);
      setSharedSessionId(sessionId);
      setSessionsOpenState(true);
    },
    [sessionsEnabled],
  );
  const closeSharedSession = useCallback(() => {
    setSharedSessionId(null);
    replaceSessionShareSearch({ sessionId: null, view: 'sessions' });
  }, []);
  const setLibraryOpen = useCallback(
    (open: boolean) => {
      if (!isLibraryEnabled) return;
      if (open) {
        setSettingsOpenState(false);
        setAgentConfigOpenState(false);
        setSessionsOpen(false);
        setSchedulesOpenState(false);
        setEnvironmentsOpenState(false);
      }
      setLibraryAgentId(null);
      setLibraryOpenState(open);
    },
    [isLibraryEnabled, setSessionsOpen],
  );
  const openLibraryAgent = useCallback(
    (agentId: string) => {
      if (!isLibraryEnabled || !sessionsEnabled) return;
      setSettingsOpenState(false);
      setAgentConfigOpenState(false);
      setSessionsOpen(false);
      setSchedulesOpenState(false);
      setEnvironmentsOpenState(false);
      setLibraryOpenState(true);
      setLibraryAgentId(agentId);
    },
    [isLibraryEnabled, sessionsEnabled, setSessionsOpen],
  );
  const closeLibraryAgent = useCallback(() => {
    setLibraryAgentId(null);
  }, []);
  const setSettingsOpen = useCallback(
    (open: boolean, section?: SettingsSection) => {
      if (section !== undefined) {
        setSettingsSection(section);
      }
      if (open) {
        setAgentConfigOpenState(false);
        setLibraryOpenState(false);
        setLibraryAgentId(null);
        setSessionsOpen(false);
        setSchedulesOpenState(false);
        setEnvironmentsOpenState(false);
      }
      setSettingsOpenState(settingsEnabled && open);
    },
    [setSessionsOpen, settingsEnabled],
  );
  const setAgentConfigOpen = useCallback(
    (open: boolean) => {
      if (open) {
        setSettingsOpenState(false);
        setLibraryOpenState(false);
        setLibraryAgentId(null);
        setSessionsOpen(false);
        setSchedulesOpenState(false);
        setEnvironmentsOpenState(false);
      }
      setAgentConfigOpenState(open);
    },
    [setSessionsOpen],
  );
  const setSchedulesOpen = useCallback(
    (open: boolean) => {
      if (open) {
        setSettingsOpenState(false);
        setAgentConfigOpenState(false);
        setLibraryOpenState(false);
        setLibraryAgentId(null);
        setSessionsOpen(false);
        setEnvironmentsOpenState(false);
      }
      setSchedulesOpenState(schedulesEnabled && open);
    },
    [schedulesEnabled, setSessionsOpen],
  );
  const setEnvironmentsOpen = useCallback(
    (open: boolean) => {
      if (open) {
        setSettingsOpenState(false);
        setAgentConfigOpenState(false);
        setLibraryOpenState(false);
        setLibraryAgentId(null);
        setSessionsOpen(false);
        setSchedulesOpenState(false);
      }
      setEnvironmentsOpenState(environmentsEnabled && open);
    },
    [environmentsEnabled, setSessionsOpen],
  );

  useEffect(() => {
    if (catalog == null || capabilities?.settings?.enabled === false) {
      setSettingsOpenState(false);
    }
  }, [capabilities?.settings?.enabled, catalog]);

  useEffect(() => {
    if (!sessionsEnabled) {
      setSessionsOpenState(false);
      setLibraryAgentId(null);
    }
  }, [sessionsEnabled]);

  useEffect(() => {
    if (!schedulesEnabled) {
      setSchedulesOpenState(false);
    }
  }, [schedulesEnabled]);

  useEffect(() => {
    if (!environmentsEnabled) {
      setEnvironmentsOpenState(false);
    }
  }, [environmentsEnabled]);

  const invalidateAgentsList = useCallback(() => {
    setAgentsListEpoch(n => n + 1);
  }, []);

  const invalidateEnvironmentsList = useCallback(() => {
    setEnvironmentsListEpoch(n => n + 1);
  }, []);

  const lockedAgentName = agentConfig.mode === 'SingleAgent' ? agentConfig.name : '';
  const effectiveMode: ShellMode = useMemo(() => {
    if (!locked) return mode;
    return {
      status: 'active',
      isMutable: false,
      isCreateAgent: false,
      agentId: lockedAgentName,
      agentName: lockedAgentName,
      locked: true,
    };
  }, [locked, lockedAgentName, mode]);
  const agentConfigOpen =
    effectiveMode.status === 'active' && effectiveMode.isMutable && effectiveMode.isCreateAgent && agentConfigOpenState;

  useEffect(() => {
    if (effectiveMode.status !== 'active' || !effectiveMode.isMutable || !effectiveMode.isCreateAgent) {
      setAgentConfigOpenState(false);
    }
  }, [effectiveMode]);

  const listSessionsAgentId = useMemo(() => {
    if (locked) return lockedAgentName;
    if (!isLibraryEnabled) return undefined;
    return historyAgentFilter?.agentId;
  }, [locked, lockedAgentName, isLibraryEnabled, historyAgentFilter]);

  const bumpEpoch = useCallback((isMutable: boolean) => {
    if (isMutable) setMutableEpoch(n => n + 1);
    else setClearEpoch(n => n + 1);
  }, []);

  const selectLibraryAgent = useCallback(
    (req: SelectLibraryAgentRequest) => {
      if (req.isMutable) {
        if (!isComposerEnabled) return;
        setSettingsOpen(false);
        setLibraryOpenState(false);
        setLibraryAgentId(null);
        setSessionsOpen(false);
        setSchedulesOpen(false);
        setEnvironmentsOpen(false);
        setSessionAccessError(null);
        setPendingSessionId(undefined);
        const isCreateAgent = resolveMutableIsCreateAgent(req);
        const kind: DraftPreferenceKind = isCreateAgent ? 'agent' : 'chat';
        setMode({
          status: 'active',
          isMutable: true,
          isCreateAgent,
          agentId: req.agentId,
          agentName: req.agentName,
          description: req.description,
          agentSpec: req.agentSpec ?? (kind === 'agent' ? agentSeedRef.current : chatSeedRef.current),
          locked: false,
        });
        setAgentConfigOpenState(isCreateAgent);
        bumpEpoch(true);
        return;
      }
      if (!isLibraryEnabled) return;
      const agentName = req.agentName ?? req.agentId;
      if (agentName == null) return;
      setSettingsOpen(false);
      setLibraryOpenState(false);
      setLibraryAgentId(null);
      setSessionsOpen(false);
      setSchedulesOpen(false);
      setEnvironmentsOpen(false);
      setSessionAccessError(null);
      setPendingSessionId(undefined);
      setAgentConfigOpenState(false);
      setMode({
        status: 'active',
        isMutable: false,
        isCreateAgent: false,
        agentId: req.agentId ?? agentName,
        agentName,
        locked: false,
      });
      if (req.agentId != null) {
        setHistoryAgentFilter({
          agentId: req.agentId,
          agentName,
          intent: 'try-agent',
        });
      } else {
        setHistoryAgentFilter(null);
      }
      bumpEpoch(false);
    },
    [
      isComposerEnabled,
      isLibraryEnabled,
      bumpEpoch,
      setSettingsOpen,
      setSessionsOpen,
      setSchedulesOpen,
      setEnvironmentsOpen,
    ],
  );

  const applyFreshAgentBuilderSeed = useCallback((source: AgentSpec) => {
    const seed = freshAgentBuilderSeed(source);
    agentSeedRef.current = seed;
    writeDraftSpecPreferences('agent', seed);
    return seed;
  }, []);

  const bindMutableAgent = useCallback(
    (req: { agentId: string; agentName: string; description?: string; agentSpec: AgentSpec }) => {
      if (!isComposerEnabled) return;
      setMode(prev => {
        if (prev.status !== 'active' || !prev.isMutable) return prev;
        return {
          status: 'active',
          isMutable: true,
          isCreateAgent: true,
          agentId: req.agentId,
          agentName: req.agentName,
          description: req.description,
          agentSpec: req.agentSpec,
          locked: false,
        };
      });
      // Drop mounts from the next New Agent seed so leaving via New Chat / Try / history
      // does not bring the just-saved agent's instructions / MCP / skills back.
      applyFreshAgentBuilderSeed(req.agentSpec);
    },
    [applyFreshAgentBuilderSeed, isComposerEnabled],
  );

  const selectAgent = useCallback(
    (name: string) => {
      selectLibraryAgent({ isMutable: false, agentId: name, agentName: name });
    },
    [selectLibraryAgent],
  );

  const sandboxEnabled = capabilities?.sandbox.enabled;
  const webSearchEnabled = capabilities?.webSearch?.enabled;

  const openDraft = useCallback(() => {
    if (!isComposerEnabled) return;
    refreshCapabilities?.();
    setHistoryAgentFilter(null);
    // Prefer storage so a just-toggled web-search preference is not lost if the
    // in-memory seed has not been rewritten yet this tick.
    // Align web-search with capability so inline New Chat sessions admit enabled:true
    // even if createSession races the preference bridge.
    const seed = withCapabilitiesWebSearch({
      spec: readDraftSpecPreferences('chat') ?? chatSeedRef.current,
      webSearchEnabled,
      kind: 'chat',
    });
    chatSeedRef.current = seed;
    selectLibraryAgent({ isMutable: true, isCreateAgent: false, agentSpec: seed });
  }, [isComposerEnabled, refreshCapabilities, selectLibraryAgent, webSearchEnabled]);

  const isActiveAgentBuilder =
    effectiveMode.status === 'active' && effectiveMode.isMutable && effectiveMode.isCreateAgent;
  const isBoundAgentBuilder = isActiveAgentBuilder && effectiveMode.agentId != null;

  const openAgentBuilder = useCallback(() => {
    if (!isComposerEnabled) return;
    refreshCapabilities?.();
    // Preserve unsaved drafts, saved builders start fresh when revisited.
    if (isActiveAgentBuilder && !isBoundAgentBuilder) {
      setSettingsOpen(false);
      setLibraryOpenState(false);
      setLibraryAgentId(null);
      setSessionsOpen(false);
      setSchedulesOpen(false);
      setEnvironmentsOpen(false);
      setSessionAccessError(null);
      setAgentConfigOpenState(true);
      return;
    }
    // After save, drop previous instructions / MCP / skills from the left panel seed.
    const boundSpec = isBoundAgentBuilder && effectiveMode.status === 'active' ? effectiveMode.agentSpec : undefined;
    const agentSpec = isBoundAgentBuilder
      ? applyFreshAgentBuilderSeed(boundSpec ?? agentSeedRef.current)
      : agentSeedRef.current;
    selectLibraryAgent({ isMutable: true, isCreateAgent: true, agentSpec });
  }, [
    applyFreshAgentBuilderSeed,
    effectiveMode,
    isActiveAgentBuilder,
    isBoundAgentBuilder,
    isComposerEnabled,
    refreshCapabilities,
    selectLibraryAgent,
    setEnvironmentsOpen,
    setSchedulesOpen,
    setSessionsOpen,
    setSettingsOpen,
  ]);

  const resetAgentBuilder = useCallback(
    (liveSpec?: AgentSpec) => {
      if (!isComposerEnabled) return;
      refreshCapabilities?.();
      // Prefer the live draft (button) or remembered seed — mode.agentSpec is only open/save snapshot.
      const source = liveSpec ?? agentSeedRef.current;
      selectLibraryAgent({
        isMutable: true,
        isCreateAgent: true,
        agentSpec: applyFreshAgentBuilderSeed(source),
      });
    },
    [applyFreshAgentBuilderSeed, isComposerEnabled, refreshCapabilities, selectLibraryAgent],
  );

  // Child effects (DraftSpecPreferenceBridge) run before this updates — so remember still
  // sees the prior capability when Settings refresh flips web-search on.
  const prevWebSearchEnabledRef = useRef(webSearchEnabled);
  useEffect(() => {
    prevWebSearchEnabledRef.current = webSearchEnabled;
  }, [webSearchEnabled]);
  const rememberDraftSpec = useCallback(
    (agentSpec: AgentSpec, kind: DraftPreferenceKind = 'chat') => {
      const previousWebSearchEnabled = prevWebSearchEnabledRef.current;
      const selected = selectDraftSpecPreferences(agentSpec, kind);
      const withSandbox = kind === 'agent' ? withCapabilitiesSandbox(selected, sandboxEnabled) : selected;
      const aligned = withCapabilitiesWebSearch({
        spec: withSandbox,
        webSearchEnabled,
        kind,
      });
      const preferences = webSearchPreferenceToStore({
        spec: aligned,
        webSearchEnabled,
        previousWebSearchEnabled,
        capabilitiesPending,
        kind,
      });
      if (kind === 'chat') {
        chatSeedRef.current = preferences;
      } else {
        // Keep the active builder intact in memory; storage remains limited to reusable preferences.
        const agentAligned = withCapabilitiesWebSearch({
          spec: withCapabilitiesSandbox(agentSpec, sandboxEnabled),
          webSearchEnabled,
          kind: 'agent',
        });
        agentSeedRef.current = webSearchPreferenceToStore({
          spec: agentAligned,
          webSearchEnabled,
          previousWebSearchEnabled,
          capabilitiesPending,
          kind: 'agent',
        });
      }
      writeDraftSpecPreferences(kind, preferences);
    },
    [sandboxEnabled, webSearchEnabled, capabilitiesPending],
  );

  const openHistorySession = useCallback(
    ({
      sessionId,
      agentName,
      isMutable: isMutableOpt,
      isCreateAgent: isCreateAgentOpt,
    }: {
      sessionId: string;
      agentName?: string;
      isMutable?: boolean;
      isCreateAgent?: boolean;
    }) => {
      const isMutable = isMutableOpt ?? agentName == null;
      if (isMutable) {
        if (!isComposerEnabled) return;
      } else if (locked) {
        if (agentName == null || lockedAgentName !== agentName) return;
      } else if (!isLibraryEnabled) {
        return;
      }

      setSettingsOpen(false);
      setLibraryOpenState(false);
      setLibraryAgentId(null);
      setSessionsOpen(false);
      setSchedulesOpen(false);
      setEnvironmentsOpen(false);
      setSessionAccessError(null);
      setPendingSessionId(sessionId);
      setPendingSessionEpoch(n => n + 1);
      if (isMutable) {
        const isCreateAgent = isCreateAgentOpt === true;
        setMode({
          status: 'active',
          isMutable: true,
          isCreateAgent,
          agentSpec: isCreateAgent ? agentSeedRef.current : chatSeedRef.current,
          locked: false,
        });
        setAgentConfigOpenState(isCreateAgent);
        return;
      }
      setAgentConfigOpenState(false);
      setMode({
        status: 'active',
        isMutable: false,
        isCreateAgent: false,
        locked: false,
        ...(agentName != null ? { agentId: agentName, agentName } : {}),
      });
    },
    [
      isLibraryEnabled,
      isComposerEnabled,
      locked,
      lockedAgentName,
      setSettingsOpen,
      setSessionsOpen,
      setSchedulesOpen,
      setEnvironmentsOpen,
    ],
  );

  const openInaccessibleSession = useCallback(
    ({ sessionId, message }: { sessionId: string; message: string }) => {
      setSettingsOpen(false);
      setLibraryOpenState(false);
      setLibraryAgentId(null);
      setSessionsOpen(false);
      setSchedulesOpen(false);
      setEnvironmentsOpen(false);
      setAgentConfigOpenState(false);
      setSessionAccessError(message);
      setPendingSessionId(sessionId);
      setPendingSessionEpoch(n => n + 1);
      // Keep chrome non-idle so layouts render the thread slot (gated by sessionAccessError).
      if (isComposerEnabled) {
        setMode({
          status: 'active',
          isMutable: true,
          isCreateAgent: false,
          agentSpec: chatSeedRef.current,
          locked: false,
        });
        return;
      }
      setMode({
        status: 'active',
        isMutable: false,
        isCreateAgent: false,
        locked: false,
      });
    },
    [isComposerEnabled, setSettingsOpen, setSessionsOpen, setSchedulesOpen, setEnvironmentsOpen],
  );

  const clearChat = useCallback(
    (liveSpec?: AgentSpec) => {
      if (effectiveMode.status === 'idle') return;
      setSessionAccessError(null);
      setPendingSessionId(undefined);
      if (effectiveMode.isMutable) {
        // Plain New Chat uses the chat seed. Builder New Chat keeps the live draft
        // so the remount does not replace the left panel with the open/save snapshot.
        const kind: DraftPreferenceKind = effectiveMode.isCreateAgent ? 'agent' : 'chat';
        const agentSpec =
          kind === 'agent'
            ? (liveSpec ?? effectiveMode.agentSpec ?? agentSeedRef.current)
            : withCapabilitiesWebSearch({
                spec: readDraftSpecPreferences('chat') ?? chatSeedRef.current,
                webSearchEnabled,
                kind: 'chat',
              });
        if (kind === 'chat') {
          chatSeedRef.current = agentSpec;
        }
        setMode({
          status: 'active',
          isMutable: true,
          isCreateAgent: effectiveMode.isCreateAgent,
          agentId: effectiveMode.agentId,
          agentName: effectiveMode.agentName,
          agentSpec,
          locked: false,
        });
        setAgentConfigOpenState(effectiveMode.isCreateAgent);
        bumpEpoch(true);
        return;
      }
      bumpEpoch(false);
    },
    [effectiveMode, bumpEpoch, webSearchEnabled],
  );

  const openLibraryHome = useCallback(() => {
    // Only library-only mode has an idle landing; other modes root via openDraft / clearChat.
    if (!isLibraryEnabled || isComposerEnabled) return;
    setSessionAccessError(null);
    setPendingSessionId(undefined);
    setSettingsOpen(false);
    setLibraryOpenState(false);
    setLibraryAgentId(null);
    setSchedulesOpen(false);
    setEnvironmentsOpen(false);
    setMode({ status: 'idle' });
    bumpEpoch(false);
  }, [isLibraryEnabled, isComposerEnabled, setSettingsOpen, setSchedulesOpen, setEnvironmentsOpen, bumpEpoch]);

  // Only explicit resets remount the runtime; history and identity changes happen in place.
  const runtimeKey = useMemo(() => {
    if (effectiveMode.status === 'idle') return 'idle';
    return `chat:${mutableEpoch}:${clearEpoch}`;
  }, [effectiveMode.status, mutableEpoch, clearEpoch]);

  const value = useMemo<ShellModeContextValue>(
    () => ({
      mode: effectiveMode,
      agentConfigMode: agentConfig.mode,
      isLibraryEnabled,
      isComposerEnabled,
      isNewChatEnabled,
      settingsOpen,
      settingsSection,
      setSettingsOpen,
      agentConfigOpen,
      setAgentConfigOpen,
      libraryOpen,
      libraryAgentId,
      setLibraryAgentId,
      setLibraryOpen,
      sessionsOpen,
      setSessionsOpen,
      sharedSessionId,
      openSharedSession,
      closeSharedSession,
      openLibraryAgent,
      closeLibraryAgent,
      schedulesOpen,
      setSchedulesOpen,
      environmentsOpen,
      setEnvironmentsOpen,
      selectLibraryAgent,
      bindMutableAgent,
      selectAgent,
      openDraft,
      openAgentBuilder,
      resetAgentBuilder,
      rememberDraftSpec,
      openHistorySession,
      openInaccessibleSession,
      sessionAccessError,
      clearChat,
      openLibraryHome,
      runtimeKey,
      historyAgentFilter,
      setHistoryAgentFilter,
      listSessionsAgentId,
      pendingSessionId,
      pendingSessionEpoch,
      agentsListEpoch,
      invalidateAgentsList,
      environmentsListEpoch,
      invalidateEnvironmentsList,
    }),
    [
      effectiveMode,
      agentConfig.mode,
      isLibraryEnabled,
      isComposerEnabled,
      isNewChatEnabled,
      settingsOpen,
      settingsSection,
      setSettingsOpen,
      agentConfigOpen,
      setAgentConfigOpen,
      libraryOpen,
      libraryAgentId,
      setLibraryOpen,
      sessionsOpen,
      setSessionsOpen,
      sharedSessionId,
      openSharedSession,
      closeSharedSession,
      openLibraryAgent,
      closeLibraryAgent,
      schedulesOpen,
      setSchedulesOpen,
      environmentsOpen,
      setEnvironmentsOpen,
      selectLibraryAgent,
      bindMutableAgent,
      selectAgent,
      openDraft,
      openAgentBuilder,
      resetAgentBuilder,
      rememberDraftSpec,
      openHistorySession,
      openInaccessibleSession,
      sessionAccessError,
      clearChat,
      openLibraryHome,
      runtimeKey,
      historyAgentFilter,
      listSessionsAgentId,
      pendingSessionId,
      pendingSessionEpoch,
      agentsListEpoch,
      invalidateAgentsList,
      environmentsListEpoch,
      invalidateEnvironmentsList,
    ],
  );

  return <ShellModeContext.Provider value={value}>{children}</ShellModeContext.Provider>;
}

export function useShellMode(): ShellModeContextValue {
  const ctx = useContext(ShellModeContext);
  if (ctx == null) {
    throw new Error('useShellMode must be used within a ShellModeProvider.');
  }
  return ctx;
}

export function useOptionalShellMode(): ShellModeContextValue | null {
  return useContext(ShellModeContext);
}

/** True when the shell is bound to a mutable (editable) agentSpec. */
export function shellIsMutable(mode: ShellMode): boolean {
  return mode.status === 'active' && mode.isMutable;
}

/** True when the shell is in New Agent / Edit builder chrome. */
export function shellIsCreateAgent(mode: ShellMode): boolean {
  return mode.status === 'active' && mode.isMutable && mode.isCreateAgent;
}

export { libraryAgentId };