claude

package
v0.0.0-...-f0049f5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 21, 2025 License: Apache-2.0 Imports: 24 Imported by: 0

README

Claude Web Interface

A comprehensive React component for interfacing with Claude AI through a web browser. This component provides a full-featured chat interface with session management, real-time streaming, and extensive customization options.

Features

Core Functionality
  • Real-time WebSocket communication with Claude CLI service
  • Session management - create, resume, save, and organize conversations
  • Streaming responses with live message updates
  • Message history with persistent storage
  • Error handling and connection recovery
User Interface
  • Modern, responsive design using Tailwind CSS + DaisyUI
  • Dark/light theme support with auto-detection
  • Session browser with search and filtering
  • Message formatting with syntax highlighting
  • Export capabilities (JSON, Markdown, HTML, Text)
  • Keyboard shortcuts for power users
Advanced Features
  • Auto-reconnection on WebSocket disconnect
  • Message copy/share functionality
  • Usage statistics display
  • Accessibility support (ARIA labels, keyboard navigation)
  • Mobile-friendly responsive layout
  • Customizable theming and configuration

Installation

# The component is part of the coderunner package
# Simply import from the claude package

Basic Usage

import React from 'react';
import { ClaudeWebInterface } from '../claude';

function App() {
  return (
    <div className="h-screen">
      <ClaudeWebInterface
        darkMode={false}
        autoConnect={true}
        showSessionBrowser={true}
        enableExport={true}
      />
    </div>
  );
}

export default App;

Advanced Usage

import React, { useState } from 'react';
import { ClaudeWebInterface, ClaudeMessage, ClaudeConnectionStatus } from '../claude';

function AdvancedApp() {
  const [messages, setMessages] = useState<ClaudeMessage[]>([]);
  const [connectionStatus, setConnectionStatus] = useState<ClaudeConnectionStatus>();

  const handleMessageReceived = (message: ClaudeMessage) => {
    setMessages(prev => [...prev, message]);
    console.log('New message:', message);
  };

  const handleConnectionChange = (status: ClaudeConnectionStatus) => {
    setConnectionStatus(status);
    console.log('Connection status:', status);
  };

  const handleSessionChange = (sessionId: string | null) => {
    console.log('Current session:', sessionId);
  };

  return (
    <ClaudeWebInterface
      theme="auto" // 'light' | 'dark' | 'auto'
      className="custom-claude-interface"
      apiBaseUrl="https://your-api-server.com"
      autoConnect={true}
      showSessionBrowser={true}
      maxMessages={500}
      enableExport={true}
      enableKeyboardShortcuts={true}
      onMessageReceived={handleMessageReceived}
      onConnectionStatusChange={handleConnectionChange}
      onSessionChange={handleSessionChange}
    />
  );
}

export default AdvancedApp;

Component Props

ClaudeWebInterfaceProps
Prop Type Default Description
darkMode boolean false Force dark mode (overrides theme detection)
theme 'light' | 'dark' | 'auto' 'auto' Theme mode
className string '' Additional CSS classes
apiBaseUrl string '' Base URL for API calls
autoConnect boolean true Auto-connect on mount
showSessionBrowser boolean true Show session management sidebar
maxMessages number 1000 Maximum messages to keep in memory
enableExport boolean true Enable export functionality
enableKeyboardShortcuts boolean true Enable keyboard shortcuts
onSessionChange (sessionId: string | null) => void - Session change callback
onMessageReceived (message: ClaudeMessage) => void - New message callback
onConnectionStatusChange (status: ClaudeConnectionStatus) => void - Connection status callback

Hooks

useClaudeWebSocket

Manages WebSocket connection to Claude service.

import { useClaudeWebSocket } from '../claude';

const { 
  connectionStatus, 
  connect, 
  disconnect, 
  sendMessage, 
  lastMessage, 
  messageHistory 
} = useClaudeWebSocket({
  autoConnect: true,
  reconnectAttempts: 3,
  reconnectDelay: 2000,
  messageHistoryLimit: 1000,
  apiBaseUrl: 'https://api.example.com'
});
useClaudeSession

Manages Claude session operations.

import { useClaudeSession } from '../claude';

const {
  sessions,
  currentSession,
  currentSessionId,
  loading,
  error,
  createSession,
  resumeSession,
  deleteSession,
  updateSessionTitle,
  exportSession,
  refreshSessions
} = useClaudeSession({
  apiBaseUrl: 'https://api.example.com'
});
useClaudeMessages

Manages message state and operations.

import { useClaudeMessages } from '../claude';

const {
  messages,
  addMessage,
  clearMessages,
  getMessagesByType,
  getLastAssistantMessage,
  exportMessages
} = useClaudeMessages();

Standalone Components

You can also use individual components separately:

import { 
  MessageList, 
  SessionBrowser, 
  InputArea, 
  StatusIndicator 
} from '../claude';

// Use components individually with your own state management

Keyboard Shortcuts

When enableKeyboardShortcuts is true:

  • Ctrl/Cmd + Enter - Send message
  • Ctrl/Cmd + N - Start new session
  • Ctrl/Cmd + B - Toggle sidebar
  • Ctrl/Cmd + K - Focus input
  • Shift + Esc - Disconnect
  • Esc - Clear input (when focused)

Styling

The component uses Tailwind CSS for styling. You can customize the appearance by:

  1. Overriding CSS classes: Pass custom classes via className prop
  2. Custom CSS: Import the provided styles.css or create your own
  3. Tailwind configuration: Modify your Tailwind config for global changes
/* Custom styling example */
.custom-claude-interface {
  --primary-color: #your-color;
}

.custom-claude-interface .message {
  border-radius: 12px;
}

Theme Support

The component supports multiple theme modes:

  • light - Force light theme
  • dark - Force dark theme
  • auto - Automatically detect system preference

Themes are implemented using CSS classes and Tailwind's dark mode support.

Export Formats

When enableExport is true, users can export conversations in multiple formats:

  • JSON - Complete message data with metadata
  • Markdown - Formatted for documentation
  • HTML - Self-contained HTML file with styling
  • Text - Plain text format

Error Handling

The component includes comprehensive error handling:

  • Connection errors - Auto-retry with exponential backoff
  • Session errors - User-friendly error messages
  • Message parsing errors - Graceful fallbacks
  • API errors - Detailed error reporting

Accessibility

The component is built with accessibility in mind:

  • Keyboard navigation - Full keyboard support
  • Screen reader support - ARIA labels and descriptions
  • High contrast mode - Respects user preferences
  • Reduced motion - Honors prefers-reduced-motion
  • Focus management - Proper focus indicators

Browser Support

  • Modern browsers - Chrome 90+, Firefox 88+, Safari 14+, Edge 90+
  • WebSocket support - Required for real-time communication
  • ES2020 features - Optional chaining, nullish coalescing
  • CSS Grid & Flexbox - For responsive layout

Performance

The component is optimized for performance:

  • Virtual scrolling - For large message lists
  • Message chunking - Configurable message limits
  • Debounced inputs - Reduces API calls
  • Memoized components - Prevents unnecessary re-renders
  • Lazy loading - Components load on demand

Development

To extend or modify the component:

  1. TypeScript - Fully typed with comprehensive interfaces
  2. React Hooks - Modern React patterns throughout
  3. Modular architecture - Easily extensible components
  4. Test coverage - Unit tests for all major functionality

API Integration

The component expects a backend service that implements the Claude CLI interface:

  • WebSocket endpoint: /coderunner/claude/ws
  • Session endpoints: /coderunner/claude/sessions
  • Authentication: Cookie-based session auth

See the backend implementation in coderunner/claude/claude.go for details.

Troubleshooting

Common Issues
  1. Connection fails: Check WebSocket URL and authentication
  2. Messages not appearing: Verify message format compatibility
  3. Styling issues: Ensure Tailwind CSS is properly configured
  4. TypeScript errors: Check type imports and compatibility
Debug Mode

Enable debug logging:

// Add to your component
useEffect(() => {
  window.claudeDebug = true;
}, []);

This will log detailed information about WebSocket messages, state changes, and errors to the browser console.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewHTTP

func NewHTTP(d deps.Deps) *http.ServeMux

NewHTTP creates a new HTTP handler for Claude WebSocket connections

Types

type ClaudeMDConfig

type ClaudeMDConfig struct {
	ID          string    `json:"id" gorm:"primaryKey"`
	Name        string    `json:"name" gorm:"uniqueIndex;not null"`
	Description string    `json:"description"`
	Content     string    `json:"content" gorm:"type:text;not null"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
	IsDefault   bool      `json:"is_default" gorm:"default:false"`
}

ClaudeMDConfig represents a CLAUDE.md configuration

type ClaudeMDConfigListResponse

type ClaudeMDConfigListResponse struct {
	Configs []ClaudeMDConfig `json:"configs"`
	Total   int              `json:"total"`
}

ClaudeMDConfigListResponse represents the response for listing configurations

type ClaudeMDCreateRequest

type ClaudeMDCreateRequest struct {
	Name        string `json:"name" binding:"required"`
	Description string `json:"description"`
	Content     string `json:"content" binding:"required"`
}

ClaudeMDCreateRequest represents the request for creating a configuration

type ClaudeMDUpdateRequest

type ClaudeMDUpdateRequest struct {
	Name        *string `json:"name"`
	Description *string `json:"description"`
	Content     *string `json:"content"`
}

ClaudeMDUpdateRequest represents the request for updating a configuration

type ClaudeMessage

type ClaudeMessage struct {
	Type      string          `json:"type"`
	Subtype   string          `json:"subtype,omitempty"`
	Message   json.RawMessage `json:"message,omitempty"`
	SessionID string          `json:"session_id,omitempty"`
	ParentID  string          `json:"parent_tool_use_id,omitempty"`
	Result    string          `json:"result,omitempty"`
	IsError   bool            `json:"is_error,omitempty"`
}

ClaudeMessage represents a message from Claude CLI

type ClaudeService

type ClaudeService struct {
	// contains filtered or unexported fields
}

ClaudeService provides database-integrated Claude session management

func NewClaudeService

func NewClaudeService(d deps.Deps) *ClaudeService

NewClaudeService creates a new database-integrated Claude service

func (*ClaudeService) CleanupSessionWorktree

func (cs *ClaudeService) CleanupSessionWorktree(sessionID, userID string) error

CleanupSessionWorktree removes the git worktree for a Claude session

func (*ClaudeService) CommitSessionChanges

func (cs *ClaudeService) CommitSessionChanges(sessionID, userID, commitMessage string) (string, error)

CommitSessionChanges commits changes in a Claude session's git worktree

func (*ClaudeService) CreateClaudeMDConfig

func (cs *ClaudeService) CreateClaudeMDConfig(req *ClaudeMDCreateRequest) (*ClaudeMDConfig, error)

CreateClaudeMDConfig creates a new CLAUDE.md configuration

func (*ClaudeService) CreateGitSessionWithPersistence

func (cs *ClaudeService) CreateGitSessionWithPersistence(threadTS, channelID, userID, repoPath, baseBranch string) (*Process, *SessionInfo, *GitSessionInfo, error)

CreateGitSessionWithPersistence creates a new Claude session with git repository integration

func (*ClaudeService) CreateGitSessionWithPersistenceAndConfig

func (cs *ClaudeService) CreateGitSessionWithPersistenceAndConfig(threadTS, channelID, userID, repoPath, baseBranch, configID string) (*Process, *SessionInfo, *GitSessionInfo, error)

func (*ClaudeService) CreateSessionWithCallbackFix

func (cs *ClaudeService) CreateSessionWithCallbackFix(threadTS, channelID, userID, workingDir string) (*ProcessWithCallback, *SessionInfo, error)

CreateSessionWithCallbackFix creates a Claude session that properly handles session ID mismatches

func (*ClaudeService) CreateSessionWithDeferredDirectory

func (cs *ClaudeService) CreateSessionWithDeferredDirectory(threadTS, channelID, userID, workingDir string) (*Process, *SessionInfo, error)

CreateSessionWithDeferredDirectory creates a Claude session but defers session directory creation until we get the actual session ID from Claude. This fixes the session ID mismatch issue.

func (*ClaudeService) CreateSessionWithPersistence

func (cs *ClaudeService) CreateSessionWithPersistence(threadTS, channelID, userID, workingDir string) (*Process, *SessionInfo, error)

CreateSessionWithPersistence creates a new Claude session and persists it to database

func (*ClaudeService) CreateSessionWithPersistenceAndConfig

func (cs *ClaudeService) CreateSessionWithPersistenceAndConfig(threadTS, channelID, userID, workingDir, configID string) (*Process, *SessionInfo, error)

CreateSessionWithPersistenceAndConfig creates a new Claude session with specified CLAUDE.md configuration

func (*ClaudeService) DeactivateSession

func (cs *ClaudeService) DeactivateSession(sessionID string) error

DeactivateSession marks a session as inactive in the database

func (*ClaudeService) DeleteClaudeMDConfig

func (cs *ClaudeService) DeleteClaudeMDConfig(id string) error

DeleteClaudeMDConfig deletes a CLAUDE.md configuration

func (*ClaudeService) DiagnoseSessionDirectories

func (cs *ClaudeService) DiagnoseSessionDirectories() error

DiagnoseSessionDirectories scans for orphaned session directories

func (*ClaudeService) FixSessionIDMismatch

func (cs *ClaudeService) FixSessionIDMismatch(goSessionID, claudeSessionID string) error

FixSessionIDMismatch moves files from Go UUID directory to Claude session directory

func (*ClaudeService) GetClaudeMDConfig

func (cs *ClaudeService) GetClaudeMDConfig(id string) (*ClaudeMDConfig, error)

GetClaudeMDConfig returns a specific CLAUDE.md configuration by ID

func (*ClaudeService) GetClaudeMDConfigByName

func (cs *ClaudeService) GetClaudeMDConfigByName(name string) (*ClaudeMDConfig, error)

GetClaudeMDConfigByName returns a specific CLAUDE.md configuration by name

func (*ClaudeService) GetClaudeMDConfigContent

func (cs *ClaudeService) GetClaudeMDConfigContent(configName string) (string, error)

GetClaudeMDConfigContent returns the content of a CLAUDE.md configuration

func (*ClaudeService) GetDB

func (cs *ClaudeService) GetDB() *gorm.DB

GetDB returns the database instance for external access

func (*ClaudeService) GetSession

func (cs *ClaudeService) GetSession(sessionID, userID string) (*models.ClaudeSession, error)

GetSession returns a specific session for a user

func (*ClaudeService) GetSessionDiff

func (cs *ClaudeService) GetSessionDiff(sessionID, userID string) (string, error)

GetSessionDiff returns the git diff for a Claude session

func (*ClaudeService) GetSessionGitStatus

func (cs *ClaudeService) GetSessionGitStatus(sessionID, userID string) (*RepositoryStatus, error)

GetSessionGitStatus returns the git status for a Claude session

func (*ClaudeService) GetSessionInfo

func (cs *ClaudeService) GetSessionInfo(threadTS, userID string) (*SessionInfo, error)

GetSessionInfo retrieves session information from database

func (*ClaudeService) GetSessions

func (cs *ClaudeService) GetSessions(userID string) ([]models.ClaudeSession, error)

GetSessions returns all sessions for a user

func (*ClaudeService) HandleWebSocket

func (cs *ClaudeService) HandleWebSocket(conn *websocket.Conn, userID string)

HandleWebSocket handles WebSocket connections for Claude sessions

func (*ClaudeService) InitializeClaudeMDConfigs

func (cs *ClaudeService) InitializeClaudeMDConfigs() error

InitializeClaudeMDConfigs initializes default CLAUDE.md configurations

func (*ClaudeService) ListClaudeMDConfigs

func (cs *ClaudeService) ListClaudeMDConfigs() (*ClaudeMDConfigListResponse, error)

ListClaudeMDConfigs returns all available CLAUDE.md configurations

func (*ClaudeService) ReceiveMessages

func (cs *ClaudeService) ReceiveMessages(process *Process) <-chan Message

ReceiveMessages returns the output channel for a Claude process

func (*ClaudeService) ResumeSession

func (cs *ClaudeService) ResumeSession(sessionID, userID string) (*Process, error)

ResumeSession attempts to resume an existing Claude session using --resume

func (*ClaudeService) SendMessage

func (cs *ClaudeService) SendMessage(process *Process, text string) error

SendMessage sends a message to a Claude process

func (*ClaudeService) StopSession

func (cs *ClaudeService) StopSession(sessionID string)

StopSession stops a Claude session and marks it as inactive

func (*ClaudeService) UpdateClaudeMDConfig

func (cs *ClaudeService) UpdateClaudeMDConfig(id string, req *ClaudeMDUpdateRequest) (*ClaudeMDConfig, error)

UpdateClaudeMDConfig updates an existing CLAUDE.md configuration

func (*ClaudeService) UpdateSessionActivity

func (cs *ClaudeService) UpdateSessionActivity(sessionID string) error

UpdateSessionActivity updates the last activity time for a session

func (*ClaudeService) UpdateSessionInfoWithClaudeID

func (cs *ClaudeService) UpdateSessionInfoWithClaudeID(sessionInfo *SessionInfo, claudeSessionID string) error

UpdateSessionInfoWithClaudeID updates the session info once we receive Claude's session ID

func (*ClaudeService) ValidateSessionConsistency

func (cs *ClaudeService) ValidateSessionConsistency(goSessionID, claudeSessionID string) error

ValidateSessionConsistency checks for session ID mismatches

type CommitInfo

type CommitInfo struct {
	Hash      string    `json:"hash"`
	Message   string    `json:"message"`
	Author    string    `json:"author"`
	Email     string    `json:"email"`
	Timestamp time.Time `json:"timestamp"`
}

type Config

type Config struct {
	Debug    bool
	DebugDir string
	Tools    []string
}

type GitService

type GitService struct {
	// contains filtered or unexported fields
}

GitService handles git operations for Claude sessions

func NewGitService

func NewGitService() *GitService

NewGitService creates a new GitService instance

func (*GitService) CleanupOldWorktrees

func (g *GitService) CleanupOldWorktrees(maxAge time.Duration) error

CleanupOldWorktrees removes worktrees older than the specified duration

func (*GitService) CleanupOrphanedWorktrees

func (g *GitService) CleanupOrphanedWorktrees(db *gorm.DB) error

CleanupOrphanedWorktrees removes worktrees that exist on disk but are not referenced by any active sessions

func (*GitService) CommitChanges

func (g *GitService) CommitChanges(worktreePath, message string) (string, error)

CommitChanges commits all changes in the worktree

func (*GitService) CreateBranch

func (g *GitService) CreateBranch(repoPath, branchName, baseBranch string) error

CreateBranch creates a new branch in the repository

func (*GitService) CreateWorktree

func (g *GitService) CreateWorktree(repoPath, branchName, baseBranch string) (string, error)

CreateWorktree creates a new git worktree for isolated Claude session execution

func (*GitService) GetBranchDiff

func (g *GitService) GetBranchDiff(repoPath, baseBranch, targetBranch string) (string, error)

GetBranchDiff returns the diff between two branches in a repository

func (*GitService) GetBranches

func (g *GitService) GetBranches(repoPath string) ([]string, error)

GetBranches returns a list of branches in the repository

func (*GitService) GetCommitInfo

func (g *GitService) GetCommitInfo(repoPath, commitHash string) (*CommitInfo, error)

GetCommitInfo returns information about a commit

func (*GitService) GetDiff

func (g *GitService) GetDiff(worktreePath string) (string, error)

GetDiff returns the git diff for a worktree

func (*GitService) GetDiffFromBaseBranch

func (g *GitService) GetDiffFromBaseBranch(worktreePath, baseBranch string) (string, error)

GetDiffFromBaseBranch returns the diff between the current branch and base branch

func (*GitService) GetRepositoryStatus

func (g *GitService) GetRepositoryStatus(repoPath string) (*RepositoryStatus, error)

GetRepositoryStatus returns the current status of the repository

func (*GitService) PushBranch

func (g *GitService) PushBranch(worktreePath, branchName string) error

PushBranch pushes the current branch to origin

func (*GitService) RemoveWorktree

func (g *GitService) RemoveWorktree(repoPath, worktreePath string) error

RemoveWorktree removes a git worktree

func (*GitService) ValidateRepository

func (g *GitService) ValidateRepository(repoPath string) error

ValidateRepository checks if the path contains a valid Git repository

type GitSessionInfo

type GitSessionInfo struct {
	RepositoryPath string `json:"repository_path"`
	WorktreePath   string `json:"worktree_path"`
	BranchName     string `json:"branch_name"`
	BaseBranch     string `json:"base_branch"`
	CommitHash     string `json:"commit_hash,omitempty"`
	HasChanges     bool   `json:"has_changes"`
}

GitSessionInfo represents git-related information for a Claude session

type Input

type Input struct {
	Type    string       `json:"type"`
	Message InputMessage `json:"message"`
}

type InputMessage

type InputMessage struct {
	Role    string                `json:"role"`
	Content []InputMessageContent `json:"content"`
}

type InputMessageContent

type InputMessageContent struct {
	Type string `json:"type"`
	Text string `json:"text"`
}

type Message

type Message struct {
	Type      string          `json:"type"`
	Subtype   string          `json:"subtype,omitempty"`
	Message   json.RawMessage `json:"message,omitempty"`
	SessionID string          `json:"session_id,omitempty"`
	ParentID  string          `json:"parent_tool_use_id,omitempty"`
	Result    string          `json:"result,omitempty"`
	IsError   bool            `json:"is_error,omitempty"`
}

Message represents a message from Claude CLI

type Process

type Process struct {
	// contains filtered or unexported fields
}

func (*Process) GetCorrelationID

func (p *Process) GetCorrelationID() string

GetCorrelationID returns the correlation ID for this process

type ProcessWithCallback

type ProcessWithCallback struct {
	*Process
	// contains filtered or unexported fields
}

ProcessWithCallback extends Process with session ID callback functionality

func (*ProcessWithCallback) SetSessionIDCallback

func (p *ProcessWithCallback) SetSessionIDCallback(callback SessionIDCallback)

SetSessionIDCallback sets a callback to be executed when Claude's session ID is received

type RepositoryStatus

type RepositoryStatus struct {
	CurrentBranch string   `json:"current_branch"`
	CommitHash    string   `json:"commit_hash"`
	IsClean       bool     `json:"is_clean"`
	ModifiedFiles []string `json:"modified_files"`
	AddedFiles    []string `json:"added_files"`
	DeletedFiles  []string `json:"deleted_files"`
}

type Service

type Service struct {
	// contains filtered or unexported fields
}

func NewService

func NewService(config Config) *Service

func (*Service) CreateSession

func (s *Service) CreateSession() (*Process, error)

func (*Service) CreateSessionWithMultipleDirs

func (s *Service) CreateSessionWithMultipleDirs(dirs []string) (*Process, error)

CreateSessionWithMultipleDirs creates a new Claude session with multiple directories

func (*Service) CreateSessionWithOptions

func (s *Service) CreateSessionWithOptions(workingDir string) (*Process, error)

func (*Service) ReceiveMessages

func (s *Service) ReceiveMessages(process *Process) <-chan Message

func (*Service) SendMessage

func (s *Service) SendMessage(process *Process, text string) error

func (*Service) StopSession

func (s *Service) StopSession(sessionID string)

type SessionIDCallback

type SessionIDCallback func(claudeSessionID string) error

SessionIDCallback is called when Claude's session ID is received

type SessionIDMismatchError

type SessionIDMismatchError struct {
	GoSessionID     string
	ClaudeSessionID string
	DirectoryPath   string
	ExpectedPath    string
}

SessionIDMismatchError represents a session ID mismatch issue

func (*SessionIDMismatchError) Error

func (e *SessionIDMismatchError) Error() string

type SessionInfo

type SessionInfo struct {
	SessionID     string
	ThreadTS      string
	UserID        string
	ChannelID     string
	WorkingDir    string
	LastActivity  time.Time
	Active        bool
	ProcessExists bool
}

SessionInfo represents session metadata stored in database

type WSMessage

type WSMessage struct {
	Type      string          `json:"type"`
	Payload   json.RawMessage `json:"payload"`
	Timestamp int64           `json:"timestamp"`
}

WSMessage represents a WebSocket message

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL