### Manual Installation and Serve Command Source: https://github.com/githubetienne/claude-session-manager/blob/main/prd.md Steps for manually installing the Claude Session Manager from source and starting the server. This involves cloning the repository, running a make install command, and then serving the application. ```bash git clone https://github.com/user/claude-session-manager cd claude-session-manager make install claude-session-manager serve ``` -------------------------------- ### Start Backend Server with Go Source: https://github.com/githubetienne/claude-session-manager/blob/main/backend/internal/api/websocket_test_example.md Command to start the backend server using Go. This assumes the `cmd/main.go` file is the entry point for the application. ```bash cd backend go run cmd/main.go ``` -------------------------------- ### Install and Use wscat for WebSocket Testing Source: https://github.com/githubetienne/claude-session-manager/blob/main/backend/internal/api/websocket_test_example.md Instructions for installing `wscat` globally via npm and connecting to a WebSocket server. It also demonstrates sending 'subscribe' and 'ping' messages and shows expected responses. ```bash # Install wscat npm install -g wscat # Connect to WebSocket wscat -c ws://localhost:8080/api/v1/ws # Send subscribe message {"type":"subscribe","timestamp":1234567890} # You should receive {"type":"subscribed","timestamp":1234567890} # Send ping {"type":"ping","timestamp":1234567890} # You should receive {"type":"pong","timestamp":1234567890} ``` -------------------------------- ### Serve Command with Options Source: https://github.com/githubetienne/claude-session-manager/blob/main/prd.md Examples of how to start the Claude Session Manager server with various command-line options. These options allow customization of the port, configuration file, development mode, and API-only operation. ```bash # Start the server claude-session-manager serve --port 8080 # Open in browser open http://localhost:8080 # Run with custom config claude-session-manager serve --config config.yaml # Run in development mode claude-session-manager serve --dev # API-only mode (no frontend) claude-session-manager serve --api-only ``` -------------------------------- ### Manual Installation of Claude Session Manager Backend Source: https://github.com/githubetienne/claude-session-manager/blob/main/README.md This snippet details the backend setup for manual installation of the Claude Session Manager. It includes cloning the repository, navigating to the backend directory, downloading Go modules, and building the executable. ```bash # Clone the repository git clone https://github.com/ksred/claude-session-manager.git cd claude-session-manager # Backend setup cd backend go mod download go build -o claude-session-manager ./cmd/main.go ``` -------------------------------- ### Manual Installation of Claude Session Manager Frontend Source: https://github.com/githubetienne/claude-session-manager/blob/main/README.md This snippet covers the frontend setup for manual installation. It involves navigating to the frontend directory, installing Node.js dependencies using npm, and building the frontend assets. ```bash # Frontend setup cd ../frontend npm install npm run build ``` -------------------------------- ### Configuration File Example (YAML) Source: https://github.com/githubetienne/claude-session-manager/blob/main/prd.md An example YAML configuration file for the Claude Session Manager. This file defines settings for the server, Claude integration, pricing, UI preferences, features, API, and database. ```yaml # Server settings server: host: "0.0.0.0" port: 8080 cors_origins: ["http://localhost:3000"] tls: enabled: false cert_file: "" key_file: "" # Claude Code settings claude: home_dir: "~/.claude" projects_dir: "~/.claude/projects" watch_interval: 2s # Token pricing pricing: input_token_cost: 0.00001 output_token_cost: 0.00003 currency: "USD" # UI settings ui: theme: "dark" # dark, light, auto language: "en" date_format: "relative" # relative, absolute # Features features: auto_refresh: true notifications: true export_enabled: true multi_user: false # API settings api: rate_limit: 100 # requests per minute enable_swagger: true api_keys: [] # Optional API key authentication # Database (optional, for persistence) database: type: "sqlite" # sqlite, postgres connection: "~/.claude-session-manager/data.db" ``` -------------------------------- ### Frontend Development Commands (Bash) Source: https://github.com/githubetienne/claude-session-manager/blob/main/README.md Commands to set up and run the frontend development server. This involves installing Node.js dependencies and starting the development server. Ensure you are in the `frontend` directory. ```bash cd frontend npm install npm run dev ``` -------------------------------- ### Build and Run from Source Docker Image Source: https://github.com/githubetienne/claude-session-manager/blob/main/DOCKER.md Clones the repository, builds the Docker image locally, and then runs the container. This process is similar to the recommended Docker run but starts from the source code. ```bash git clone https://github.com/ksred/claude-session-manager.git cd claude-session-manager # Build the Docker image docker build -t claude-session-manager . # Run the container docker run -d \ --name claude-session-manager \ -p 80:80 \ -v ~/.claude:/data/claude \ claude-session-manager ``` -------------------------------- ### Start Backend Server (Bash) Source: https://github.com/githubetienne/claude-session-manager/blob/main/backend/POSTMAN.md Command to start the backend server, which is necessary for generating Swagger documentation and for direct import of the API into Postman. ```bash make run ``` -------------------------------- ### Docker Installation Command Source: https://github.com/githubetienne/claude-session-manager/blob/main/prd.md Command to run the Claude Session Manager using Docker. This method is recommended for ease of setup and isolation. It maps port 8080 and mounts a local directory for persistent data. ```bash docker run -d -p 8080:8080 -v ~/.claude:/root/.claude claude-session-manager ``` -------------------------------- ### Configure Environment Variables and Start Server Source: https://context7.com/githubetienne/claude-session-manager/llms.txt Sets up essential environment variables for the Claude Session Manager, including port, host, Claude directory, and database path. It then starts the server in development mode using a shell script. ```shell export PORT=8080 export HOST=0.0.0.0 export CLAUDE_DIR=~/.claude export DATABASE_PATH=/path/to/custom/sessions.db ./claude-session-manager serve --dev ``` -------------------------------- ### Example JSON Payload for Activity Update Source: https://github.com/githubetienne/claude-session-manager/blob/main/backend/internal/api/websocket_test_example.md Illustrates the JSON format for an 'activity_update' event, detailing the type of activity, session information, and a timestamp. ```json { "type": "activity_update", "data": { "activity": { "timestamp": "2024-01-01T12:00:00Z", "type": "file_modified", "session_id": "session-123", "session_name": "Project Name", "details": "Modified /src/app.js using Edit" } }, "timestamp": 1234567890 } ``` -------------------------------- ### Start Claude Session Manager with Docker Compose Source: https://github.com/githubetienne/claude-session-manager/blob/main/README.md This snippet outlines the steps to start the Claude Session Manager using Docker Compose. It involves cloning the repository, navigating to the project directory, and running 'docker-compose up -d'. The dashboard will be accessible at http://localhost:8080. ```bash # Clone the repository git clone https://github.com/ksred/claude-session-manager.git cd claude-session-manager # Start with Docker Compose docker-compose up -d # Open in browser open http://localhost:8080 ``` -------------------------------- ### Initialize and Start Claude Session Manager Server Source: https://github.com/githubetienne/claude-session-manager/blob/main/backend/coverage.html Initializes the server by setting up the sessions cache, file watcher (if enabled), periodic cache refresh, middleware, and routes. The Start method then configures HTTP server timeouts and begins listening for incoming requests. ```Go func (s *Server) Initialize() { if err := server.initializeSessionsCache(); err != nil { logger.WithError(err).Error("Failed to initialize sessions cache") } // Setup file watcher if enabled if cfg.Features.EnableFileWatcher { if err := server.setupFileWatcher(); err != nil { logger.WithError(err).Error("Failed to setup file watcher") } } // Start periodic cache refresh based on config if cfg.Claude.CacheRefreshRate > 0 { refreshInterval := time.Duration(cfg.Claude.CacheRefreshRate) * time.Minute go server.startPeriodicCacheRefresh(refreshInterval) } // Setup middleware server.setupMiddleware() // Setup routes server.setupRoutes() return server } // Start starts the server func (s *Server) Start() error { addr := fmt.Sprintf("%s:%d", s.config.Server.Host, s.config.Server.Port) s.logger.WithFields(logrus.Fields{ "address": addr, "port": s.config.Server.Port, "host": s.config.Server.Host, }).Info("Starting server") // Configure timeouts server := &http.Server{ Addr: addr, Handler: s.router, ReadTimeout: time.Duration(s.config.Server.ReadTimeout) * time.Second, WriteTimeout: time.Duration(s.config.Server.WriteTimeout) * time.Second, } return server.ListenAndServe() } ``` -------------------------------- ### Example JSON Payload for Session Update Source: https://github.com/githubetienne/claude-session-manager/blob/main/backend/internal/api/websocket_test_example.md Demonstrates the structure of a JSON payload for a 'session_update' event. This includes session details, token usage, and a timestamp. ```json { "type": "session_update", "data": { "session_id": "session-123", "session": { "id": "session-123", "title": "Project Name", "project_path": "/path/to/project", "status": "active", "last_activity": "2024-01-01T12:00:00Z", "tokens_used": { "input_tokens": 1000, "output_tokens": 500, "total_tokens": 1500, "estimated_cost": 0.015 } } }, "timestamp": 1234567890 } ``` -------------------------------- ### Install openapi-to-postmanv2 Tool (Bash) Source: https://github.com/githubetienne/claude-session-manager/blob/main/backend/POSTMAN.md Command to install the `openapi-to-postmanv2` npm package globally, which is required for automated Postman collection generation. ```bash npm install -g openapi-to-postmanv2 ``` -------------------------------- ### Run Claude Session Manager with Docker Source: https://github.com/githubetienne/claude-session-manager/blob/main/docker-hub-description.md This command starts the Claude Session Manager using Docker, mapping port 80 and mounting the default Claude directory. It's the quickest way to get the application running. ```bash docker run -p 80:80 -v ~/.claude:/data/claude ksred/claude-session-manager ``` -------------------------------- ### Configure WebSocket and File Watcher in YAML Source: https://github.com/githubetienne/claude-session-manager/blob/main/backend/internal/api/websocket_test_example.md Enables WebSocket and file watcher features in the backend configuration. These are essential for real-time updates and detecting changes in session data. ```yaml features: enable_websocket: true enable_file_watcher: true ``` -------------------------------- ### Backend Development Commands (Bash) Source: https://github.com/githubetienne/claude-session-manager/blob/main/README.md Commands to set up and run the backend development server. This includes downloading Go dependencies and starting the server in development mode. Navigate to the `backend` directory before executing. ```bash cd backend go mod download go run ./cmd/main.go serve --dev ``` -------------------------------- ### Go Project File Structure Source: https://github.com/githubetienne/claude-session-manager/blob/main/prd.md Illustrates the directory and file structure for the backend component of the Claude Session Manager written in Go. It outlines the organization of server entry points, API handlers, internal logic modules, utility packages, and configuration management. ```go claude-session-manager/ ├── backend/ │ ├── cmd/ │ │ └── main.go # Server entry point │ ├── internal/ │ │ ├── api/ │ │ │ ├── routes.go # API route definitions │ │ │ ├── handlers.go # Request handlers │ │ │ └── websocket.go # Real-time updates │ │ ├── claude/ │ │ │ ├── parser.go # JSONL parsing logic │ │ │ ├── session.go # Session data structures │ │ │ ├── project.go # Project context parsing │ │ │ └── watcher.go # File system monitoring │ │ └── config/ │ │ └── config.go # Configuration management │ ├── pkg/ │ │ └── utils/ │ │ ├── encoding.go # Path encoding/decoding │ │ └── git.go # Git utilities │ ├── go.mod │ └── go.sum ├── frontend/ │ ├── src/ │ │ ├── components/ # React components │ │ │ ├── Dashboard/ # Main dashboard view │ │ │ ├── SessionList/ # Session sidebar │ │ │ ├── MetricsPanel/ # Metrics cards │ │ │ ├── Charts/ # Chart components │ │ │ └── ActivityFeed/ # Activity timeline │ │ ├── hooks/ # Custom React hooks │ │ ├── services/ # API/WebSocket services │ │ ├── store/ # State management │ │ ├── styles/ # Global styles │ │ └── App.tsx # Root component │ ├── public/ │ ├── package.json │ ├── tailwind.config.js │ ├── tsconfig.json │ └── vite.config.ts ├── docker-compose.yml # Easy local development └── README.md ``` -------------------------------- ### Example JSON Payload for Metrics Update Source: https://github.com/githubetienne/claude-session-manager/blob/main/backend/internal/api/websocket_test_example.md Shows the JSON structure for a 'metrics_update' event, focusing on token usage changes for a specific session, along with a timestamp. ```json { "type": "metrics_update", "data": { "session_id": "session-123", "usage": { "input_tokens": 100, "output_tokens": 50, "total_tokens": 150, "estimated_cost": 0.0015 } }, "timestamp": 1234567890 } ``` -------------------------------- ### Quick Start with Docker Source: https://context7.com/githubetienne/claude-session-manager/llms.txt Instructions for running the Claude Session Manager using Docker. This includes commands for pulling the image, running with default settings, using a custom Claude directory, and deploying with Docker Compose. It also provides the default access URL. ```bash # Pull and run with default settings (mounts ~/.claude directory) docker run -p 80:80 -v ~/.claude:/data/claude ksred/claude-session-manager # Access the dashboard open http://localhost # Run with custom Claude directory location docker run -p 80:80 \ -e CLAUDE_DIR=/custom/claude/path \ -v /your/custom/claude/dir:/custom/claude/path \ ksred/claude-session-manager # Using Docker Compose docker-compose up -d # Dashboard available at http://localhost:8080 ``` -------------------------------- ### Configuration File Setup (YAML) Source: https://github.com/githubetienne/claude-session-manager/blob/main/README.md Defines the structure and default values for the application's configuration. This YAML file specifies server settings, Claude-specific parameters, and pricing details for different models. It's located at `configs/default.yaml`. ```yaml server: host: "0.0.0.0" port: 8080 cors_origins: - "http://localhost:3000" - "http://localhost:5173" claude: home_dir: "~/.claude" watch_interval: 2s db_path: "./claude_sessions.db" pricing: models: claude-3-opus-20240229: input_cost_per_1k: 0.015 output_cost_per_1k: 0.075 claude-3-5-sonnet-20241022: input_cost_per_1k: 0.003 output_cost_per_1k: 0.015 ``` -------------------------------- ### Docker Compose for Claude Session Manager Source: https://github.com/githubetienne/claude-session-manager/blob/main/DOCKER.md Manages the Claude Session Manager application using Docker Compose. This includes commands to build and start the services in detached mode, view logs, and stop the services. ```bash # Build and start the container docker-compose up -d # View logs docker-compose logs -f # Stop the container docker-compose down ``` -------------------------------- ### Generate Postman Collection with Fixed URLs (Bash) Source: https://github.com/githubetienne/claude-session-manager/blob/main/backend/POSTMAN.md Installs the openapi-to-postmanv2 tool and generates a Postman collection with automatically fixed URLs for easy API testing. This method requires no manual variable setup in Postman. ```bash # Install the openapi-to-postmanv2 tool first (official Postman converter) npm install -g openapi-to-postmanv2 # Generate Postman collection with working URLs make postman-fixed ``` -------------------------------- ### Go Session Discovery and Parsing Logic Source: https://github.com/githubetienne/claude-session-manager/blob/main/prd.md Implements the core logic for discovering session files within the user's home directory and parsing them into Session structs. It uses `filepath.Walk` to traverse directories and `bufio.Scanner` with `json.Unmarshal` to process JSONL files. ```go func DiscoverSessions() ([]Session, error) { claudeDir := filepath.Join(os.Getenv("HOME"), ".claude", "projects") var sessions []Session err := filepath.Walk(claudeDir, func(path string, info os.FileInfo, err error) error { if strings.HasSuffix(path, ".jsonl") && !strings.Contains(path, "summary") { session, err := ParseSessionFile(path) if err == nil { sessions = append(sessions, session) } } return nil }) return sessions, err } func ParseSessionFile(filePath string) (Session, error) { file, err := os.Open(filePath) if err != nil { return Session{}, err } defer file.Close() var session Session scanner := bufio.NewScanner(file) for scanner.Scan() { var message Message if err := json.Unmarshal(scanner.Bytes(), &message); err == nil { session.Messages = append(session.Messages, message) updateSessionMetrics(&session, message) } } return session, nil } ``` -------------------------------- ### Backend Dependencies (Go) Source: https://github.com/githubetienne/claude-session-manager/blob/main/prd.md Defines the backend module and its direct dependencies for the Claude Session Manager project using Go modules. It specifies the Go version and lists required packages like Gin, Gorilla WebSocket, and Viper. ```go module github.com/user/claude-session-manager go 1.21 require ( github.com/gin-gonic/gin v1.9.1 github.com/gorilla/websocket v1.5.1 github.com/fsnotify/fsnotify v1.7.0 github.com/spf13/cobra v1.8.0 github.com/spf13/viper v1.18.0 gopkg.in/yaml.v3 v3.0.1 ) ``` -------------------------------- ### Load Configuration from Multiple Sources (Go) Source: https://github.com/githubetienne/claude-session-manager/blob/main/backend/coverage.html The LoadConfig function loads configuration settings from a specified file, standard locations, and environment variables. It uses the Viper library for flexible configuration management and includes validation to ensure the configuration is correct. Dependencies include Viper, os, filepath, fmt, and strings. ```go import ( "fmt" "os" "path/filepath" "strings" "github.com/spf13/viper" ) // LoadConfig loads configuration from multiple sources func LoadConfig(configFile string) (*Config, error) { v := viper.New() // Set default values setDefaults(v) // Set config file if configFile != "" { v.SetConfigFile(configFile) } else { // Look for config in standard locations v.SetConfigName("config") v.SetConfigType("yaml") // Add config paths v.AddConfigPath(".") v.AddConfigPath("./configs") v.AddConfigPath("/etc/claude-session-manager") // User config directory if homeDir, err := os.UserHomeDir(); err == nil { v.AddConfigPath(filepath.Join(homeDir, ".config", "claude-session-manager")) } } // Environment variables v.SetEnvPrefix("CSM") v.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) v.AutomaticEnv() // Read config file if it exists if err := v.ReadInConfig(); err != nil { // It's okay if the config file doesn't exist, we have defaults if _, ok := err.(viper.ConfigFileNotFoundError); !ok { return nil, fmt.Errorf("error reading config file: %w", err) } } // Unmarshal config var config Config if err := v.Unmarshal(&config); err != nil { return nil, fmt.Errorf("unable to decode config: %w", err) } // Validate config if err := validateConfig(&config); err != nil { return nil, fmt.Errorf("invalid configuration: %w", err) } return &config, nil } ``` -------------------------------- ### Define Application Configuration Structures (Go) Source: https://github.com/githubetienne/claude-session-manager/blob/main/backend/coverage.html Defines the main application configuration structure and its nested components for server, Claude, pricing, and features. These structures are designed to be mapped from configuration files using Viper. ```Go package config import ( "fmt" "os" "path/filepath" "strings" "github.com/spf13/viper" ) // Config represents the complete application configuration type Config struct { Server ServerConfig `mapstructure:"server"` Claude ClaudeConfig `mapstructure:"claude"` Pricing PricingConfig `mapstructure:"pricing"` Features FeaturesConfig `mapstructure:"features"` } // ServerConfig contains HTTP server settings type ServerConfig struct { Port int `mapstructure:"port"` Host string `mapstructure:"host"` ReadTimeout int `mapstructure:"read_timeout"` // seconds WriteTimeout int `mapstructure:"write_timeout"` // seconds ShutdownTimeout int `mapstructure:"shutdown_timeout"` // seconds CORS CORSConfig `mapstructure:"cors"` } // CORSConfig contains CORS settings type CORSConfig struct { Enabled bool `mapstructure:"enabled"` AllowedOrigins []string `mapstructure:"allowed_origins"` AllowedMethods []string `mapstructure:"allowed_methods"` AllowedHeaders []string `mapstructure:"allowed_headers"` AllowCredentials bool `mapstructure:"allow_credentials"` MaxAge int `mapstructure:"max_age"` } // ClaudeConfig contains Claude-specific settings type ClaudeConfig struct { HomeDirectory string `mapstructure:"home_directory"` ProjectsPath string `mapstructure:"projects_path"` WatchInterval int `mapstructure:"watch_interval"` // seconds CacheRefreshRate int `mapstructure:"cache_refresh_rate"` // minutes } // PricingConfig contains token pricing information type PricingConfig struct { InputTokensPerK float64 `mapstructure:"input_tokens_per_k"` // Cost per 1K input tokens OutputTokensPerK float64 `mapstructure:"output_tokens_per_k"` // Cost per 1K output tokens Currency string `mapstructure:"currency"` } // FeaturesConfig contains feature flags and settings type FeaturesConfig struct { EnableWebSocket bool `mapstructure:"enable_websocket"` EnableFileWatcher bool `mapstructure:"enable_file_watcher"` EnableMetrics bool `mapstructure:"enable_metrics"` EnableProfiling bool `mapstructure:"enable_profiling"` DebugMode bool `mapstructure:"debug_mode"` } ``` -------------------------------- ### Calculate Session Duration (Go) Source: https://github.com/githubetienne/claude-session-manager/blob/main/backend/coverage.html Calculates the total duration of a Claude session. It uses the session's start time and last activity time to determine the elapsed time. If the session hasn't started or has no recorded activity, it returns zero duration. ```Go // Duration returns the total duration of the session func (s *Session) Duration() time.Duration { if s.StartTime.IsZero() { return 0 } endTime := s.LastActivity if endTime.IsZero() { endTime = time.Now() } return endTime.Sub(s.StartTime) } ``` -------------------------------- ### API Server Initialization in Go Source: https://github.com/githubetienne/claude-session-manager/blob/main/backend/coverage.html Initializes a new API server instance, setting the Gin mode based on the debug configuration. It creates a Gin engine, a logger, and optionally a WebSocket hub. The server struct holds configuration, router, logger, WebSocket hub, session cache, and session watcher. ```go // Server represents the API server type Server struct { config *config.Config router *gin.Engine logger *logrus.Logger wsHub *WebSocketHub sessionsCache []claude.Session sessionsMutex sync.RWMutex sessionWatcher *claude.SessionWatcher } // NewServer creates a new API server instance func NewServer(cfg *config.Config) *Server { // Set Gin mode based on debug setting if cfg.Features.DebugMode { gin.SetMode(gin.DebugMode) } else { gin.SetMode(gin.ReleaseMode) } router := gin.New() logger := logrus.StandardLogger() // Create WebSocket hub if enabled var wsHub *WebSocketHub if cfg.Features.EnableWebSocket { wsHub = NewWebSocketHub(logger) } server := &Server{ config: cfg, router: router, logger: logger, wsHub: wsHub, sessionsCache: []claude.Session{}, } // Start WebSocket hub if enabled if server.wsHub != nil { go server.wsHub.Run() } // Initialize sessions cache return server } ``` -------------------------------- ### GET /metrics/summary Source: https://github.com/githubetienne/claude-session-manager/blob/main/backend/coverage.html Retrieves an overall summary of metrics for all sessions. ```APIDOC ## GET /metrics/summary ### Description Retrieves an overall summary of metrics for all sessions, including total sessions, active sessions, message counts, token usage, cost, average duration, and model usage statistics. ### Method GET ### Endpoint /metrics/summary ### Parameters None ### Request Example ``` GET /metrics/summary ``` ### Response #### Success Response (200) - **MetricsSummary** (object) - An object containing the overall metrics summary. - **TotalSessions** (integer) - The total number of sessions recorded. - **ActiveSessions** (integer) - The number of currently active sessions. - **TotalMessages** (integer) - The total number of messages across all sessions. - **TotalTokensUsed** (integer) - The total number of tokens used across all sessions. - **TotalEstimatedCost** (number) - The total estimated cost for all token usage. - **AverageSessionDuration** (number) - The average duration of sessions in minutes. - **MostUsedModel** (string) - The name of the most frequently used model. - **ModelUsage** (object) - A map of model names to their usage counts. #### Response Example ```json { "TotalSessions": 120, "ActiveSessions": 35, "TotalMessages": 5000, "TotalTokensUsed": 1200000, "TotalEstimatedCost": 60.0, "AverageSessionDuration": 15.5, "MostUsedModel": "claude-3-opus", "ModelUsage": { "claude-3-opus": 80, "claude-3-sonnet": 40 } } ``` ``` -------------------------------- ### Discover Claude Sessions and Display Information (Go) Source: https://github.com/githubetienne/claude-session-manager/blob/main/backend/internal/claude/README.md This snippet demonstrates how to discover all Claude sessions, iterate through them, and print key information such as session ID, status, project name, Git branch, total tokens used, and estimated cost. It requires the 'claude' package. ```go sessions, err := claude.DiscoverSessions() if err != nil { log.Fatal(err) } for _, session := range sessions { fmt.Printf("Session %s: %s\n", session.ID, session.Status) fmt.Printf("Project: %s (Branch: %s)\n", session.ProjectName, session.GitBranch) fmt.Printf("Tokens: %d (Cost: $%.4f)\n", session.TokensUsed.TotalTokens, session.TokensUsed.EstimatedCost) } ``` -------------------------------- ### GET /api/v1/analytics/tokens/timeline Source: https://context7.com/githubetienne/claude-session-manager/llms.txt Retrieve token usage over time with configurable granularity. ```APIDOC ## GET /api/v1/analytics/tokens/timeline ### Description Retrieve token usage over time with configurable granularity. ### Method GET ### Endpoint /api/v1/analytics/tokens/timeline #### Query Parameters - **hours** (integer) - Required - The number of past hours to retrieve data for. - **granularity** (string) - Required - The time granularity (e.g., 'hour', 'minute'). ### Response #### Success Response (200) - **data** (array) - An array of token usage data points over the specified time period and granularity. #### Response Example ```json { "data": [ { "timestamp": "2024-01-15T14:00:00Z", "tokens_consumed": 15000 }, { "timestamp": "2024-01-15T15:00:00Z", "tokens_consumed": 18000 } ] } ``` ``` -------------------------------- ### Go WebSocket Handler for Real-Time Updates Source: https://github.com/githubetienne/claude-session-manager/blob/main/prd.md Sets up a backend WebSocket handler for real-time session updates. It upgrades the HTTP connection to a WebSocket, sends the initial list of sessions, and then starts a goroutine to watch for changes and push updates to connected clients. ```go // Backend WebSocket handler func HandleWebSocket(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { return } defer conn.Close() // Send initial session data sessions, _ := claude.DiscoverSessions() conn.WriteJSON(map[string]interface{}{ "type": "sessions", "data": sessions, }) // Watch for changes and push updates go watchAndPushUpdates(conn) } ``` -------------------------------- ### Running Backend and Frontend Tests (Bash) Source: https://github.com/githubetienne/claude-session-manager/blob/main/README.md Commands to execute tests for both the backend and frontend applications. For backend tests, navigate to the `backend` directory. For frontend tests, navigate to the `frontend` directory. ```bash # Backend tests cd backend go test ./... # Frontend tests cd frontend npm test ``` -------------------------------- ### GET /api/v1/analytics/costs Source: https://context7.com/githubetienne/claude-session-manager/llms.txt Retrieve cost breakdown by project, model, or day with projections and cache savings. ```APIDOC ## GET /api/v1/analytics/costs ### Description Retrieve cost breakdown by project, model, or day with projections and cache savings. ### Method GET ### Endpoint /api/v1/analytics/costs #### Query Parameters - **group_by** (string) - Required - The field to group cost data by (e.g., 'project', 'model', 'day'). - **days** (integer) - Required - The number of past days to include in the analysis. ### Response #### Success Response (200) - **total_cost** (number) - The total cost over the specified period. - **cache_savings** (number) - The estimated savings from using the cache. - **breakdown** (array) - An array of cost breakdown objects, detailing cost, token usage, sessions, and percentage for each group. - **projection** (object) - An object containing cost projections, such as daily average and monthly estimate. #### Response Example ```json { "total_cost": 125.50, "cache_savings": 35.20, "breakdown": [ { "name": "my-app", "cost": 45.30, "tokens": { "total": 450000, "cached": 180000, "fresh": 270000 }, "sessions": 23, "percentage": 0.36 }, { "name": "api-service", "cost": 38.75, "tokens": { "total": 380000, "cached": 150000, "fresh": 230000 }, "sessions": 18, "percentage": 0.31 } ], "projection": { "daily_average": 4.18, "monthly_estimate": 125.40 } } ``` ``` -------------------------------- ### Get Recent Files Source: https://context7.com/githubetienne/claude-session-manager/llms.txt Retrieve files that were recently modified across all Claude sessions or for a specific project. ```APIDOC ## GET /api/v1/files/recent ### Description Retrieve files that were recently modified across all Claude sessions. ### Method GET ### Endpoint /api/v1/files/recent #### Query Parameters - **limit** (integer) - Optional - The maximum number of files to return. - **offset** (integer) - Optional - The number of files to skip. ### Response #### Success Response (200) - **files** (array) - An array of file objects, each containing file path, last modified timestamp, session details, project details, and tool name. - **total** (integer) - The total number of files found. - **limit** (integer) - The limit applied to the result set. - **offset** (integer) - The offset applied to the result set. #### Response Example ```json { "files": [ { "file_path": "/src/auth.go", "last_modified": "2024-01-15T14:30:00Z", "session_id": "session_abc123", "session_title": "Implement authentication", "project_name": "my-app", "project_path": "/home/user/my-app", "tool_name": "Edit", "occurrences": 5, "git_branch": "feature/auth" } ], "total": 150, "limit": 20, "offset": 0 } ``` ## GET /api/v1/projects/{projectName}/files/recent ### Description Retrieve files that were recently modified for a specific project. ### Method GET ### Endpoint /api/v1/projects/{projectName}/files/recent #### Query Parameters - **limit** (integer) - Optional - The maximum number of files to return. - **branch** (string) - Optional - Filter files by a specific Git branch. ### Response #### Success Response (200) - **files** (array) - An array of file objects, each containing file path, last modified timestamp, session details, project details, and tool name. - **total** (integer) - The total number of files found. - **limit** (integer) - The limit applied to the result set. #### Response Example ```json { "files": [ { "file_path": "/src/auth.go", "last_modified": "2024-01-15T14:30:00Z", "session_id": "session_abc123", "session_title": "Implement authentication", "project_name": "my-app", "project_path": "/home/user/my-app", "tool_name": "Edit", "occurrences": 5, "git_branch": "feature/auth" } ], "total": 150, "limit": 20 } ``` ``` -------------------------------- ### API Route Configuration in Go Source: https://github.com/githubetienne/claude-session-manager/blob/main/backend/coverage.html Sets up the API routes for version 1 of the application using Gin router groups. Includes endpoints for health checks, session management (get all, by ID, active, recent), metrics (summary, activity, usage), search, and a WebSocket endpoint. Also configures static file serving. ```go // setupRoutes configures all API routes func (s *Server) setupRoutes() { // API v1 routes v1 := s.router.Group("/api/v1") { // Health check v1.GET("/health", s.healthHandler) // Session routes sessions := v1.Group("/sessions") { sessions.GET("", s.getSessionsHandler) sessions.GET("/:id", s.getSessionHandler) sessions.GET("/active", s.getActiveSessionsHandler) sessions.GET("/recent", s.getRecentSessionsHandler) } // Metrics routes metrics := v1.Group("/metrics") { metrics.GET("/summary", s.getMetricsSummaryHandler) metrics.GET("/activity", s.getActivityHandler) metrics.GET("/usage", s.getUsageStatsHandler) } // Search routes v1.GET("/search", s.searchHandler) // WebSocket endpoint for real-time updates v1.GET("/ws", s.websocketHandler) } // Static files (if needed) s.router.Static("/static", "./static") } ``` -------------------------------- ### GET /api/v1/analytics/timeseries Source: https://context7.com/githubetienne/claude-session-manager/llms.txt Retrieve time series data showing sessions, messages, tokens, and costs over time. ```APIDOC ## GET /api/v1/analytics/timeseries ### Description Retrieve time series data showing sessions, messages, tokens, and costs over time. ### Method GET ### Endpoint /api/v1/analytics/timeseries #### Query Parameters - **period** (string) - Required - The granularity of the time series data (e.g., 'day', 'hour'). - **days** (integer) - Required - The number of past days to retrieve data for. ### Response #### Success Response (200) - **period** (string) - The specified period for the time series data. - **data** (array) - An array of time series data points, each containing date, sessions, messages, total_tokens, total_cost, and a breakdown by model. #### Response Example ```json { "period": "day", "data": [ { "date": "2024-01-15", "sessions": 12, "messages": 145, "total_tokens": 125000, "total_cost": 3.75, "models": { "claude-3-5-sonnet-20241022": { "sessions": 10, "tokens": 100000 }, "claude-3-opus-20240229": { "sessions": 2, "tokens": 25000 } } } ] } ``` ``` -------------------------------- ### Get Session by ID Source: https://context7.com/githubetienne/claude-session-manager/llms.txt Retrieves detailed information for a specific Claude session identified by its unique ID. ```APIDOC ## GET /api/v1/sessions/{id} ### Description Retrieves detailed information about a specific Claude session using its unique identifier. ### Method GET ### Endpoint /api/v1/sessions/{id} #### Path Parameters - **id** (string) - Required - The unique identifier of the session to retrieve. ### Response #### Success Response (200) - **id** (string) - Unique identifier for the session. - **title** (string) - The title or description of the session. - **project_path** (string) - The absolute path to the project associated with the session. - **project_name** (string) - The name of the project. - **git_branch** (string) - The Git branch the session is associated with. - **git_worktree** (string) - The Git worktree associated with the session. - **status** (string) - The current status of the session (e.g., 'active', 'completed', 'idle'). - **created_at** (string) - Timestamp when the session was created (ISO 8601 format). - **updated_at** (string) - Timestamp when the session was last updated (ISO 8601 format). - **message_count** (integer) - The total number of messages exchanged in the session. - **current_task** (string) - The current task being performed in the session. - **tokens_used** (object) - An object detailing token consumption. - **input_tokens** (integer) - Tokens used for input. - **output_tokens** (integer) - Tokens used for output. - **total_tokens** (integer) - Total tokens consumed. - **estimated_cost** (number) - Estimated cost in USD. - **files_modified** (array of strings) - List of files modified during the session. - **duration_seconds** (integer) - The duration of the session in seconds. - **is_active** (boolean) - Indicates if the session is currently active. - **model** (string) - The Claude model used for the session. #### Response Example ```json { "id": "session_abc123", "title": "Implement user authentication", "project_path": "/home/user/my-project", "project_name": "my-project", "git_branch": "feature/auth", "git_worktree": "main", "status": "active", "created_at": "2024-01-15T10:00:00Z", "updated_at": "2024-01-15T11:30:00Z", "message_count": 45, "current_task": "Implement user authentication", "tokens_used": { "input_tokens": 15000, "output_tokens": 8000, "total_tokens": 30000, "estimated_cost": 0.85 }, "files_modified": ["/src/auth.go", "/src/user.go"], "duration_seconds": 5400, "is_active": true, "model": "claude-3-5-sonnet-20241022" } ``` ``` -------------------------------- ### Provide Default Application Configuration (Go) Source: https://github.com/githubetienne/claude-session-manager/blob/main/backend/coverage.html Returns a default configuration object for the application. It sets sensible defaults for server port, timeouts, CORS, Claude directory, and feature flags. ```Go // DefaultConfig returns the default configuration func DefaultConfig() *Config { homeDir, _ := os.UserHomeDir() claudeDir := filepath.Join(homeDir, ".claude") return &Config{ Server: ServerConfig{ Port: 8080, Host: "0.0.0.0", ReadTimeout: 15, WriteTimeout: 15, ShutdownTimeout: 10, CORS: CORSConfig{ Enabled: true, AllowedOrigins: []string{"*"}, ``` -------------------------------- ### GET /activity Source: https://github.com/githubetienne/claude-session-manager/blob/main/backend/coverage.html Retrieves activity timeline data, including session creation and recent message events. ```APIDOC ## GET /activity ### Description Retrieves activity timeline data, including session creation events and recent message events from sessions. Supports limiting the number of activities returned. ### Method GET ### Endpoint /activity ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of activities to return. Defaults to 50. ### Request Example ``` GET /activity?limit=20 ``` ### Response #### Success Response (200) - **activities** (array) - A list of activity entries. - **Timestamp** (string) - The timestamp of the activity (ISO 8601 format). - **Type** (string) - The type of activity (e.g., "session_created", "message_sent"). - **SessionID** (string) - The ID of the session related to the activity. - **SessionName** (string) - The name of the project associated with the session. - **Details** (string) - Additional details about the activity. #### Response Example ```json { "activities": [ { "Timestamp": "2023-10-27T10:30:00Z", "Type": "message_sent", "SessionID": "sess_abc123", "SessionName": "Project Alpha", "Details": "User sent a message: 'What is the weather like?'" }, { "Timestamp": "2023-10-27T10:00:00Z", "Type": "session_created", "SessionID": "sess_abc123", "SessionName": "Project Alpha", "Details": "Session started in Project Alpha" } ] } ``` ``` -------------------------------- ### Monitor Claude Session File Changes (Go) Source: https://github.com/githubetienne/claude-session-manager/blob/main/backend/internal/claude/README.md This code sets up a real-time watcher for Claude session files. It initializes a watcher with a callback function that is triggered when sessions are updated. It also shows how to set an optional callback for individual file system events (created, modified, deleted) and how to start and stop the watcher. Requires the 'claude' package. ```go watcher, err := claude.NewSessionWatcher(func(sessions []claude.Session) { fmt.Printf("Sessions updated: %d total\n", len(sessions)) }) // Optional: Set event callback for individual events watcher.SetEventCallback(func(event claude.WatchEvent) { fmt.Printf("Event: %s for session %s\n", event.Type, event.SessionID) }) if err := watcher.Start(); err != nil { log.Fatal(err) } // Don't forget to stop when done defer watcher.Stop() ``` -------------------------------- ### GET /api/v1/analytics/models Source: https://context7.com/githubetienne/claude-session-manager/llms.txt Retrieve performance statistics for each Claude model including token usage, costs, and cache efficiency. ```APIDOC ## GET /api/v1/analytics/models ### Description Retrieve performance statistics for each Claude model including token usage, costs, and cache efficiency. ### Method GET ### Endpoint /api/v1/analytics/models ### Response #### Success Response (200) - **models** (array) - An array of model performance objects, each containing model name, display name, and a stats object with metrics like total sessions, total tokens, total cost, etc. #### Response Example ```json { "models": [ { "model": "claude-3-5-sonnet-20241022", "display_name": "Claude 3.5 Sonnet", "stats": { "total_sessions": 85, "total_tokens": 950000, "total_cost": 28.50, "avg_tokens_per_session": 11176, "avg_cost_per_session": 0.34, "cache_efficiency": 0.45, "avg_session_duration_seconds": 2700 } }, { "model": "claude-3-opus-20240229", "display_name": "Claude 3 Opus", "stats": { "total_sessions": 15, "total_tokens": 300000, "total_cost": 17.25, "avg_tokens_per_session": 20000, "avg_cost_per_session": 1.15, "cache_efficiency": 0.35, "avg_session_duration_seconds": 3600 } } ] } ``` ```