feat: implement resumable Claude sessions with background execution (#93)

This comprehensive update adds support for resumable Claude Code sessions that can run in the background and be resumed later. Key improvements include:

Backend enhancements:
- Enhanced ProcessRegistry to track both agent runs and Claude sessions
- Added new Tauri commands: list_running_claude_sessions, get_claude_session_output
- Improved Claude process management with proper session ID extraction and lifecycle handling
- Enhanced cancellation logic with registry-based process killing and fallback mechanisms
- Added live output capture and storage for session persistence

Frontend improvements:
- New RunningClaudeSessions component to display and manage active sessions
- Added streaming state management and session tracking in App component
- Implemented navigation protection when Claude is actively streaming
- Enhanced ClaudeCodeSession component with streaming callbacks and session management

Configuration updates:
- Updated .gitignore to exclude documentation files (AGENTS.md, CLAUDE.md, *_TASK.md)

This feature enables users to start Claude sessions, navigate away while Claude continues processing, and resume sessions later from the Projects view, significantly improving the user experience for long-running AI interactions.
This commit is contained in:
Mufeed VH
2025-07-02 18:07:14 +05:30
committed by GitHub
parent 4fb6fd5159
commit e8c54d7fad
9 changed files with 637 additions and 100 deletions

View File

@@ -49,6 +49,10 @@ interface ClaudeCodeSessionProps {
* Optional className for styling
*/
className?: string;
/**
* Callback when streaming state changes
*/
onStreamingChange?: (isStreaming: boolean, sessionId: string | null) => void;
}
/**
@@ -62,6 +66,7 @@ export const ClaudeCodeSession: React.FC<ClaudeCodeSessionProps> = ({
initialProjectPath = "",
onBack,
className,
onStreamingChange,
}) => {
const [projectPath, setProjectPath] = useState(initialProjectPath || session?.project_path || "");
const [messages, setMessages] = useState<ClaudeStreamMessage[]>([]);
@@ -196,6 +201,16 @@ export const ClaudeCodeSession: React.FC<ClaudeCodeSessionProps> = ({
}
}, [session]);
// Report streaming state changes
useEffect(() => {
onStreamingChange?.(isLoading, claudeSessionId);
}, [isLoading, claudeSessionId, onStreamingChange]);
// Check for active Claude sessions on mount
useEffect(() => {
checkForActiveSession();
}, []);
// Auto-scroll to bottom when new messages arrive
useEffect(() => {
@@ -246,6 +261,89 @@ export const ClaudeCodeSession: React.FC<ClaudeCodeSessionProps> = ({
}
};
const checkForActiveSession = async () => {
// If we have a session prop, check if it's still active
if (session) {
try {
const activeSessions = await api.listRunningClaudeSessions();
const activeSession = activeSessions.find((s: any) => {
if ('process_type' in s && s.process_type && 'ClaudeSession' in s.process_type) {
return (s.process_type as any).ClaudeSession.session_id === session.id;
}
return false;
});
if (activeSession) {
// Session is still active, reconnect to its stream
console.log('[ClaudeCodeSession] Found active session, reconnecting:', session.id);
setClaudeSessionId(session.id);
// Get any buffered output
const bufferedOutput = await api.getClaudeSessionOutput(session.id);
if (bufferedOutput) {
// Parse and add buffered messages
const lines = bufferedOutput.split('\n').filter((line: string) => line.trim());
for (const line of lines) {
try {
const message = JSON.parse(line) as ClaudeStreamMessage;
setMessages(prev => [...prev, message]);
setRawJsonlOutput(prev => [...prev, line]);
} catch (err) {
console.error('Failed to parse buffered message:', err);
}
}
}
// Set up listeners for the active session
reconnectToSession(session.id);
}
} catch (err) {
console.error('Failed to check for active sessions:', err);
}
}
};
const reconnectToSession = async (sessionId: string) => {
console.log('[ClaudeCodeSession] Reconnecting to session:', sessionId);
// Clean up previous listeners
unlistenRefs.current.forEach(unlisten => unlisten());
unlistenRefs.current = [];
// Set up session-specific listeners
const outputUnlisten = await listen<string>(`claude-output:${sessionId}`, async (event) => {
try {
console.log('[ClaudeCodeSession] Received claude-output on reconnect:', event.payload);
// Store raw JSONL
setRawJsonlOutput(prev => [...prev, event.payload]);
// Parse and display
const message = JSON.parse(event.payload) as ClaudeStreamMessage;
setMessages(prev => [...prev, message]);
} catch (err) {
console.error("Failed to parse message:", err, event.payload);
}
});
const errorUnlisten = await listen<string>(`claude-error:${sessionId}`, (event) => {
console.error("Claude error:", event.payload);
setError(event.payload);
});
const completeUnlisten = await listen<boolean>(`claude-complete:${sessionId}`, async (event) => {
console.log('[ClaudeCodeSession] Received claude-complete on reconnect:', event.payload);
setIsLoading(false);
hasActiveSessionRef.current = false;
});
unlistenRefs.current = [outputUnlisten, errorUnlisten, completeUnlisten];
// Mark as loading to show the session is active
setIsLoading(true);
hasActiveSessionRef.current = true;
};
const handleSelectPath = async () => {
try {
const selected = await open({

View File

@@ -0,0 +1,175 @@
import React, { useState, useEffect } from "react";
import { motion } from "framer-motion";
import { Play, Loader2, Terminal, AlertCircle } from "lucide-react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { api, type ProcessInfo, type Session } from "@/lib/api";
import { cn } from "@/lib/utils";
import { formatISOTimestamp } from "@/lib/date-utils";
interface RunningClaudeSessionsProps {
/**
* Callback when a running session is clicked to resume
*/
onSessionClick?: (session: Session) => void;
/**
* Optional className for styling
*/
className?: string;
}
/**
* Component to display currently running Claude sessions
*/
export const RunningClaudeSessions: React.FC<RunningClaudeSessionsProps> = ({
onSessionClick,
className,
}) => {
const [runningSessions, setRunningSessions] = useState<ProcessInfo[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
loadRunningSessions();
// Poll for updates every 5 seconds
const interval = setInterval(loadRunningSessions, 5000);
return () => clearInterval(interval);
}, []);
const loadRunningSessions = async () => {
try {
const sessions = await api.listRunningClaudeSessions();
setRunningSessions(sessions);
setError(null);
} catch (err) {
console.error("Failed to load running sessions:", err);
setError("Failed to load running sessions");
} finally {
setLoading(false);
}
};
const handleResumeSession = (processInfo: ProcessInfo) => {
// Extract session ID from process type
if ('ClaudeSession' in processInfo.process_type) {
const sessionId = processInfo.process_type.ClaudeSession.session_id;
// Create a minimal session object for resumption
const session: Session = {
id: sessionId,
project_id: processInfo.project_path.replace(/[^a-zA-Z0-9]/g, '-'),
project_path: processInfo.project_path,
created_at: new Date(processInfo.started_at).getTime() / 1000,
};
// Emit event to navigate to the session
const event = new CustomEvent('claude-session-selected', {
detail: { session, projectPath: processInfo.project_path }
});
window.dispatchEvent(event);
onSessionClick?.(session);
}
};
if (loading && runningSessions.length === 0) {
return (
<div className={cn("flex items-center justify-center py-4", className)}>
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
</div>
);
}
if (error) {
return (
<div className={cn("flex items-center gap-2 text-destructive text-sm", className)}>
<AlertCircle className="h-4 w-4" />
<span>{error}</span>
</div>
);
}
if (runningSessions.length === 0) {
return null;
}
return (
<div className={cn("space-y-3", className)}>
<div className="flex items-center gap-2">
<div className="flex items-center gap-1">
<div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
<h3 className="text-sm font-medium">Active Claude Sessions</h3>
</div>
<span className="text-xs text-muted-foreground">
({runningSessions.length} running)
</span>
</div>
<div className="space-y-2">
{runningSessions.map((session) => {
const sessionId = 'ClaudeSession' in session.process_type
? session.process_type.ClaudeSession.session_id
: null;
if (!sessionId) return null;
return (
<motion.div
key={session.run_id}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.2 }}
>
<Card className="transition-all hover:shadow-md hover:scale-[1.01] cursor-pointer">
<CardContent
className="p-3"
onClick={() => handleResumeSession(session)}
>
<div className="flex items-start justify-between gap-3">
<div className="flex items-start gap-3 flex-1 min-w-0">
<Terminal className="h-4 w-4 text-green-600 mt-0.5 flex-shrink-0" />
<div className="space-y-1 flex-1 min-w-0">
<div className="flex items-center gap-2">
<p className="font-mono text-xs text-muted-foreground truncate">
{sessionId.substring(0, 20)}...
</p>
<span className="text-xs text-green-600 font-medium">
Running
</span>
</div>
<p className="text-xs text-muted-foreground truncate">
{session.project_path}
</p>
<div className="flex items-center gap-3 text-xs text-muted-foreground">
<span>Started: {formatISOTimestamp(session.started_at)}</span>
<span>Model: {session.model}</span>
{session.task && (
<span className="truncate max-w-[200px]" title={session.task}>
Task: {session.task}
</span>
)}
</div>
</div>
</div>
<Button
size="sm"
variant="ghost"
className="flex-shrink-0"
>
<Play className="h-3 w-3 mr-1" />
Resume
</Button>
</div>
</CardContent>
</Card>
</motion.div>
);
})}
</div>
</div>
);
};

View File

@@ -27,4 +27,5 @@ export * from "./ui/tooltip";
export * from "./ui/popover";
export * from "./ui/pagination";
export * from "./ui/split-pane";
export * from "./ui/scroll-area";
export * from "./ui/scroll-area";
export * from "./RunningClaudeSessions";