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

@@ -7,6 +7,7 @@ import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { ProjectList } from "@/components/ProjectList";
import { SessionList } from "@/components/SessionList";
import { RunningClaudeSessions } from "@/components/RunningClaudeSessions";
import { Topbar } from "@/components/Topbar";
import { MarkdownEditor } from "@/components/MarkdownEditor";
import { ClaudeFileEditor } from "@/components/ClaudeFileEditor";
@@ -36,6 +37,8 @@ function App() {
const [showNFO, setShowNFO] = useState(false);
const [showClaudeBinaryDialog, setShowClaudeBinaryDialog] = useState(false);
const [toast, setToast] = useState<{ message: string; type: "success" | "error" | "info" } | null>(null);
const [activeClaudeSessionId, setActiveClaudeSessionId] = useState<string | null>(null);
const [isClaudeStreaming, setIsClaudeStreaming] = useState(false);
// Load projects on mount when in projects view
useEffect(() => {
@@ -52,7 +55,7 @@ function App() {
const handleSessionSelected = (event: CustomEvent) => {
const { session } = event.detail;
setSelectedSession(session);
setView("claude-code-session");
handleViewChange("claude-code-session");
};
const handleClaudeNotFound = () => {
@@ -106,7 +109,7 @@ function App() {
* Opens a new Claude Code session in the interactive UI
*/
const handleNewSession = async () => {
setView("claude-code-session");
handleViewChange("claude-code-session");
setSelectedSession(null);
};
@@ -123,7 +126,7 @@ function App() {
*/
const handleEditClaudeFile = (file: ClaudeMdFile) => {
setEditingClaudeFile(file);
setView("claude-file-editor");
handleViewChange("claude-file-editor");
};
/**
@@ -131,7 +134,27 @@ function App() {
*/
const handleBackFromClaudeFileEditor = () => {
setEditingClaudeFile(null);
setView("projects");
handleViewChange("projects");
};
/**
* Handles view changes with navigation protection
*/
const handleViewChange = (newView: View) => {
// Check if we're navigating away from an active Claude session
if (view === "claude-code-session" && isClaudeStreaming && activeClaudeSessionId) {
const shouldLeave = window.confirm(
"Claude is still responding. If you navigate away, Claude will continue running in the background.\n\n" +
"You can return to this session from the Projects view.\n\n" +
"Do you want to continue?"
);
if (!shouldLeave) {
return;
}
}
setView(newView);
};
const renderContent = () => {
@@ -163,7 +186,7 @@ function App() {
>
<Card
className="h-64 cursor-pointer transition-all duration-200 hover:scale-105 hover:shadow-lg border border-border/50 shimmer-hover"
onClick={() => setView("agents")}
onClick={() => handleViewChange("agents")}
>
<div className="h-full flex flex-col items-center justify-center p-8">
<Bot className="h-16 w-16 mb-4 text-primary" />
@@ -180,7 +203,7 @@ function App() {
>
<Card
className="h-64 cursor-pointer transition-all duration-200 hover:scale-105 hover:shadow-lg border border-border/50 shimmer-hover"
onClick={() => setView("projects")}
onClick={() => handleViewChange("projects")}
>
<div className="h-full flex flex-col items-center justify-center p-8">
<FolderCode className="h-16 w-16 mb-4 text-primary" />
@@ -197,21 +220,21 @@ function App() {
case "agents":
return (
<div className="flex-1 overflow-hidden">
<CCAgents onBack={() => setView("welcome")} />
<CCAgents onBack={() => handleViewChange("welcome")} />
</div>
);
case "editor":
return (
<div className="flex-1 overflow-hidden">
<MarkdownEditor onBack={() => setView("welcome")} />
<MarkdownEditor onBack={() => handleViewChange("welcome")} />
</div>
);
case "settings":
return (
<div className="flex-1 flex flex-col" style={{ minHeight: 0 }}>
<Settings onBack={() => setView("welcome")} />
<Settings onBack={() => handleViewChange("welcome")} />
</div>
);
@@ -229,7 +252,7 @@ function App() {
<Button
variant="ghost"
size="sm"
onClick={() => setView("welcome")}
onClick={() => handleViewChange("welcome")}
className="mb-4"
>
Back to Home
@@ -303,6 +326,9 @@ function App() {
</Button>
</motion.div>
{/* Running Claude Sessions */}
<RunningClaudeSessions />
{/* Project list */}
{projects.length > 0 ? (
<ProjectList
@@ -338,19 +364,23 @@ function App() {
session={selectedSession || undefined}
onBack={() => {
setSelectedSession(null);
setView("projects");
handleViewChange("projects");
}}
onStreamingChange={(isStreaming, sessionId) => {
setIsClaudeStreaming(isStreaming);
setActiveClaudeSessionId(sessionId);
}}
/>
);
case "usage-dashboard":
return (
<UsageDashboard onBack={() => setView("welcome")} />
<UsageDashboard onBack={() => handleViewChange("welcome")} />
);
case "mcp":
return (
<MCPManager onBack={() => setView("welcome")} />
<MCPManager onBack={() => handleViewChange("welcome")} />
);
default:
@@ -363,10 +393,10 @@ function App() {
<div className="h-screen bg-background flex flex-col">
{/* Topbar */}
<Topbar
onClaudeClick={() => setView("editor")}
onSettingsClick={() => setView("settings")}
onUsageClick={() => setView("usage-dashboard")}
onMCPClick={() => setView("mcp")}
onClaudeClick={() => handleViewChange("editor")}
onSettingsClick={() => handleViewChange("settings")}
onUsageClick={() => handleViewChange("usage-dashboard")}
onMCPClick={() => handleViewChange("mcp")}
onInfoClick={() => setShowNFO(true)}
/>

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";

View File

@@ -1,5 +1,21 @@
import { invoke } from "@tauri-apps/api/core";
/** Process type for tracking in ProcessRegistry */
export type ProcessType =
| { AgentRun: { agent_id: number; agent_name: string } }
| { ClaudeSession: { session_id: string } };
/** Information about a running process */
export interface ProcessInfo {
run_id: number;
process_type: ProcessType;
pid: number;
started_at: string;
project_path: string;
task: string;
model: string;
}
/**
* Represents a project in the ~/.claude/projects directory
*/
@@ -1045,6 +1061,23 @@ export const api = {
return invoke("cancel_claude_execution", { sessionId });
},
/**
* Lists all currently running Claude sessions
* @returns Promise resolving to list of running Claude sessions
*/
async listRunningClaudeSessions(): Promise<any[]> {
return invoke("list_running_claude_sessions");
},
/**
* Gets live output from a Claude session
* @param sessionId - The session ID to get output for
* @returns Promise resolving to the current live output
*/
async getClaudeSessionOutput(sessionId: string): Promise<string> {
return invoke("get_claude_session_output", { sessionId });
},
/**
* Lists files and directories in a given path
*/