Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:0xranx OpenContext useAgentSessions

From Leeroopedia
Knowledge Sources
Domains UI, Session_Management
Last Updated 2026-10-24 12:00 GMT

Overview

Concrete tool for managing agent chat sessions in the React frontend, with dual persistence to Tauri backend (`agent-sessions.json`) and localStorage fallback.

Description

The useAgentSessions hook manages the session lifecycle for the Desktop Agent Chat feature. It provides:

  • Session state: An array of sessions, the active session ID, and a next index counter.
  • Dual persistence: Sessions are saved to both the Tauri backend (`agent-sessions.json` in app data dir) and browser localStorage. On mount, it tries the backend first, falling back to localStorage, and migrates localStorage data to the backend.
  • Debounced saving: Session state changes trigger a debounced (600ms) save to both persistence layers, avoiding excessive writes during rapid state changes.
  • Model catalog: Loads available models from the backend (`getAgentModelConfig`), merging with default Codex models.
  • Storage ready flag: Prevents saves until initial load is complete, avoiding overwriting stored data with empty state.

The hook manages model catalogs per agent type (e.g., `codex` models) and merges them with default models.

Usage

  • Desktop Agent Chat: Used by the AgentSidebar component to manage multiple concurrent agent sessions.
  • Session tabs: Supports the session tab bar UI for switching between sessions.
  • Persistence: Sessions survive app restarts via the dual persistence system.

Code Reference

Source Location

  • Repository: OpenContext
  • File: src/ui/src/components/agent/hooks/useAgentSessions.js
  • File (Rust persistence):** src-tauri/src/commands/agent.rs

Signature

export const useAgentSessions = ({ storageKey }) => {
  const [sessions, setSessions] = useState([]);
  const [activeId, setActiveId] = useState(null);
  const [nextIndex, setNextIndex] = useState(1);
  const [storageReady, setStorageReady] = useState(false);
  const [agentModelCatalog, setAgentModelCatalog] = useState({ codex: [...] });

  return {
    sessions,        // Session array
    activeId,        // Active session ID
    nextIndex,       // Next session index
    storageReady,    // Whether initial load is complete
    agentModelCatalog, // Available models per agent type
    setSessions, setActiveId, setNextIndex,
    // ... other utilities
  };
};

Import

import { useAgentSessions } from './hooks/useAgentSessions';

I/O Contract

Inputs

Name Type Required Description
storageKey string Yes localStorage key for fallback persistence

Outputs

Name Type Description
sessions Array Array of session objects
activeId null Active session ID
nextIndex number Next session index for naming
storageReady boolean Whether initial load completed
agentModelCatalog Object Available models per agent type

Session Object

Name Type Description
id string Session unique ID
agentId string Agent type (codex/claude/opencode)
model string Selected model name
messages Array Chat messages
availableModels Array Models available for this session's agent

Usage Examples

Basic Usage

import { useAgentSessions } from './hooks/useAgentSessions';

function AgentSidebar() {
  const {
    sessions,
    activeId,
    storageReady,
    setSessions,
    setActiveId,
  } = useAgentSessions({ storageKey: 'opencontext-agent-sessions' });

  // Create a new session
  const newSession = {
    id: `session-${nextIndex}`,
    agentId: 'codex',
    model: 'gpt-5.1-codex-mini',
    messages: [],
  };
  setSessions(prev => [...prev, newSession]);
  setActiveId(newSession.id);
}

Persistence Flow

// Internal flow:
// 1. On mount: try api.loadAgentSessions() (Tauri backend)
// 2. If no backend data, try localStorage
// 3. If localStorage has data, migrate to backend via api.saveAgentSessions()
// 4. On state change (debounced 600ms): save to both localStorage and backend

Rust Backend (agent_sessions_load/save)

#[tauri::command]
pub(crate) fn agent_sessions_load(app: tauri::AppHandle) -> CmdResult<Option<serde_json::Value>> {
    let path = agent_sessions_path(&app)?;
    if !path.exists() { return Ok(None); }
    let content = std::fs::read_to_string(&path).map_err(map_err)?;
    let payload = serde_json::from_str(&content).map_err(map_err)?;
    Ok(Some(payload))
}

#[tauri::command]
pub(crate) fn agent_sessions_save(
    app: tauri::AppHandle,
    payload: serde_json::Value,
) -> CmdResult<bool> {
    let path = agent_sessions_path(&app)?;
    // Save to app data dir as agent-sessions.json
}

Related Pages

Implements Principle

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment