generated from nhcarrigan/template
feat: add interrupt button
This commit is contained in:
@@ -25,6 +25,12 @@ pub async fn stop_claude(app: AppHandle, bridge: State<'_, SharedBridge>) -> Res
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn interrupt_claude(app: AppHandle, bridge: State<'_, SharedBridge>) -> Result<(), String> {
|
||||||
|
let mut bridge = bridge.lock();
|
||||||
|
bridge.interrupt(&app)
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn send_prompt(bridge: State<'_, SharedBridge>, message: String) -> Result<(), String> {
|
pub async fn send_prompt(bridge: State<'_, SharedBridge>, message: String) -> Result<(), String> {
|
||||||
let mut bridge = bridge.lock();
|
let mut bridge = bridge.lock();
|
||||||
|
|||||||
@@ -19,6 +19,9 @@ pub struct ClaudeStartOptions {
|
|||||||
|
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub allowed_tools: Vec<String>,
|
pub allowed_tools: Vec<String>,
|
||||||
|
|
||||||
|
#[serde(default)]
|
||||||
|
pub skip_greeting: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ pub fn run() {
|
|||||||
.invoke_handler(tauri::generate_handler![
|
.invoke_handler(tauri::generate_handler![
|
||||||
start_claude,
|
start_claude,
|
||||||
stop_claude,
|
stop_claude,
|
||||||
|
interrupt_claude,
|
||||||
send_prompt,
|
send_prompt,
|
||||||
is_claude_running,
|
is_claude_running,
|
||||||
get_working_directory,
|
get_working_directory,
|
||||||
|
|||||||
@@ -332,6 +332,30 @@ impl WslBridge {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn interrupt(&mut self, app: &AppHandle) -> Result<(), String> {
|
||||||
|
// Due to persistent bug in Claude Code where ESC/Ctrl+C doesn't work,
|
||||||
|
// we have to kill the process. This is the only reliable way to stop it.
|
||||||
|
// See: https://github.com/anthropics/claude-code/issues/3455
|
||||||
|
if let Some(mut process) = self.process.take() {
|
||||||
|
// Kill the process immediately
|
||||||
|
let _ = process.kill();
|
||||||
|
let _ = process.wait();
|
||||||
|
|
||||||
|
// Clear stdin
|
||||||
|
self.stdin = None;
|
||||||
|
|
||||||
|
// Keep session_id and working directory for user reference
|
||||||
|
// The user will see what session was interrupted
|
||||||
|
|
||||||
|
// Emit disconnected status
|
||||||
|
emit_connection_status(app, ConnectionStatus::Disconnected);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err("No active process to interrupt".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn stop(&mut self, app: &AppHandle) {
|
pub fn stop(&mut self, app: &AppHandle) {
|
||||||
if let Some(mut process) = self.process.take() {
|
if let Some(mut process) = self.process.take() {
|
||||||
let _ = process.kill();
|
let _ = process.kill();
|
||||||
|
|||||||
@@ -1,17 +1,30 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { invoke } from "@tauri-apps/api/core";
|
import { invoke } from "@tauri-apps/api/core";
|
||||||
import { claudeStore } from "$lib/stores/claude";
|
import { claudeStore, isClaudeProcessing } from "$lib/stores/claude";
|
||||||
import { characterState } from "$lib/stores/character";
|
import { characterState } from "$lib/stores/character";
|
||||||
import { handleNewUserMessage } from "$lib/notifications/rules";
|
import { handleNewUserMessage } from "$lib/notifications/rules";
|
||||||
|
import { setSkipNextGreeting } from "$lib/tauri";
|
||||||
|
import {
|
||||||
|
setShouldRestoreHistory,
|
||||||
|
setSavedHistory,
|
||||||
|
getShouldRestoreHistory,
|
||||||
|
getSavedHistory,
|
||||||
|
clearHistoryRestore
|
||||||
|
} from "$lib/stores/historyRestore";
|
||||||
|
|
||||||
let inputValue = $state("");
|
let inputValue = $state("");
|
||||||
let isSubmitting = $state(false);
|
let isSubmitting = $state(false);
|
||||||
let isConnected = $state(false);
|
let isConnected = $state(false);
|
||||||
|
let isProcessing = $state(false);
|
||||||
|
|
||||||
claudeStore.connectionStatus.subscribe((status) => {
|
claudeStore.connectionStatus.subscribe((status) => {
|
||||||
isConnected = status === "connected";
|
isConnected = status === "connected";
|
||||||
});
|
});
|
||||||
|
|
||||||
|
isClaudeProcessing.subscribe((processing) => {
|
||||||
|
isProcessing = processing;
|
||||||
|
});
|
||||||
|
|
||||||
async function handleSubmit(event: Event) {
|
async function handleSubmit(event: Event) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
|
|
||||||
@@ -21,6 +34,30 @@
|
|||||||
isSubmitting = true;
|
isSubmitting = true;
|
||||||
inputValue = "";
|
inputValue = "";
|
||||||
|
|
||||||
|
// Check if we need to restore conversation history
|
||||||
|
let messageToSend = message;
|
||||||
|
if (getShouldRestoreHistory()) {
|
||||||
|
const savedHistory = getSavedHistory();
|
||||||
|
console.log("Should restore history:", true);
|
||||||
|
console.log("Saved history:", savedHistory);
|
||||||
|
|
||||||
|
if (savedHistory) {
|
||||||
|
// Prepend the conversation history with a context message
|
||||||
|
messageToSend = `[Previous conversation context:]
|
||||||
|
${savedHistory}
|
||||||
|
|
||||||
|
[Continuing conversation after reconnection:]
|
||||||
|
User: ${message}`;
|
||||||
|
|
||||||
|
console.log("Message with history:", messageToSend);
|
||||||
|
|
||||||
|
// Clear the restoration flags
|
||||||
|
clearHistoryRestore();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.log("Should restore history:", false);
|
||||||
|
}
|
||||||
|
|
||||||
// Reset notification state for new user message
|
// Reset notification state for new user message
|
||||||
handleNewUserMessage();
|
handleNewUserMessage();
|
||||||
|
|
||||||
@@ -28,7 +65,7 @@
|
|||||||
characterState.setState("thinking");
|
characterState.setState("thinking");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await invoke("send_prompt", { message });
|
await invoke("send_prompt", { message: messageToSend });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to send prompt:", error);
|
console.error("Failed to send prompt:", error);
|
||||||
claudeStore.addLine("error", `Failed to send: ${error}`);
|
claudeStore.addLine("error", `Failed to send: ${error}`);
|
||||||
@@ -38,6 +75,55 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function handleInterrupt() {
|
||||||
|
// Save the conversation history FIRST before anything else
|
||||||
|
const history = claudeStore.getConversationHistory();
|
||||||
|
console.log("Saving conversation history:", history);
|
||||||
|
|
||||||
|
if (history) {
|
||||||
|
setSavedHistory(history);
|
||||||
|
setShouldRestoreHistory(true);
|
||||||
|
console.log("History saved and restoration flag set");
|
||||||
|
} else {
|
||||||
|
console.log("No history to save");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await invoke("interrupt_claude");
|
||||||
|
claudeStore.addLine("system", "Process interrupted - reconnecting...");
|
||||||
|
characterState.setState("idle");
|
||||||
|
|
||||||
|
// Show connecting status while we reconnect
|
||||||
|
claudeStore.setConnectionStatus("connecting");
|
||||||
|
|
||||||
|
// Auto-reconnect after a brief delay
|
||||||
|
setTimeout(async () => {
|
||||||
|
try {
|
||||||
|
// Get current working directory before reconnecting
|
||||||
|
const workingDir = await invoke<string>("get_working_directory");
|
||||||
|
|
||||||
|
// Set the flag to skip greeting on next connection
|
||||||
|
setSkipNextGreeting(true);
|
||||||
|
|
||||||
|
// Reconnect to Claude
|
||||||
|
await invoke("start_claude", {
|
||||||
|
options: {
|
||||||
|
working_dir: workingDir
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (reconnectError) {
|
||||||
|
console.error("Failed to auto-reconnect:", reconnectError);
|
||||||
|
claudeStore.addLine("error", `Failed to reconnect: ${reconnectError}`);
|
||||||
|
claudeStore.addLine("system", "Please manually reconnect to continue");
|
||||||
|
}
|
||||||
|
}, 500); // Brief delay to ensure process is fully terminated
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to interrupt:", error);
|
||||||
|
claudeStore.addLine("error", `Failed to interrupt: ${error}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function handleKeyDown(event: KeyboardEvent) {
|
function handleKeyDown(event: KeyboardEvent) {
|
||||||
if (event.key === "Enter" && !event.shiftKey) {
|
if (event.key === "Enter" && !event.shiftKey) {
|
||||||
handleSubmit(event);
|
handleSubmit(event);
|
||||||
@@ -61,18 +147,31 @@
|
|||||||
></textarea>
|
></textarea>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button
|
{#if isProcessing}
|
||||||
type="submit"
|
<button
|
||||||
disabled={!isConnected || isSubmitting || !inputValue.trim()}
|
type="button"
|
||||||
class="px-6 py-3 bg-[var(--accent-primary)] hover:bg-[var(--accent-secondary)]
|
onclick={handleInterrupt}
|
||||||
text-white font-medium rounded-lg
|
class="px-6 py-3 bg-red-600 hover:bg-red-700
|
||||||
disabled:opacity-50 disabled:cursor-not-allowed
|
text-white font-medium rounded-lg
|
||||||
transition-all duration-200 transform hover:scale-105 active:scale-95"
|
transition-all duration-200 transform hover:scale-105 active:scale-95"
|
||||||
>
|
title="Interrupt the current response (Ctrl+C)"
|
||||||
{#if isSubmitting}
|
>
|
||||||
<span class="inline-block animate-spin">⏳</span>
|
<span class="font-bold">■</span> Stop
|
||||||
{:else}
|
</button>
|
||||||
Send
|
{:else}
|
||||||
{/if}
|
<button
|
||||||
</button>
|
type="submit"
|
||||||
|
disabled={!isConnected || isSubmitting || !inputValue.trim()}
|
||||||
|
class="px-6 py-3 bg-[var(--accent-primary)] hover:bg-[var(--accent-secondary)]
|
||||||
|
text-white font-medium rounded-lg
|
||||||
|
disabled:opacity-50 disabled:cursor-not-allowed
|
||||||
|
transition-all duration-200 transform hover:scale-105 active:scale-95"
|
||||||
|
>
|
||||||
|
{#if isSubmitting}
|
||||||
|
<span class="inline-block animate-spin">⏳</span>
|
||||||
|
{:else}
|
||||||
|
Send
|
||||||
|
{/if}
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { writable, derived } from "svelte/store";
|
import { writable, derived } from "svelte/store";
|
||||||
import type { ConnectionStatus, PermissionRequest } from "$lib/types/messages";
|
import type { ConnectionStatus, PermissionRequest } from "$lib/types/messages";
|
||||||
|
import { characterState } from "$lib/stores/character";
|
||||||
|
|
||||||
export interface TerminalLine {
|
export interface TerminalLine {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -18,6 +19,8 @@ function createClaudeStore() {
|
|||||||
const isProcessing = writable<boolean>(false);
|
const isProcessing = writable<boolean>(false);
|
||||||
const grantedTools = writable<Set<string>>(new Set());
|
const grantedTools = writable<Set<string>>(new Set());
|
||||||
const pendingRetryMessage = writable<string | null>(null);
|
const pendingRetryMessage = writable<string | null>(null);
|
||||||
|
const shouldRestoreHistory = writable<boolean>(false);
|
||||||
|
const savedConversationHistory = writable<string | null>(null);
|
||||||
|
|
||||||
let lineIdCounter = 0;
|
let lineIdCounter = 0;
|
||||||
|
|
||||||
@@ -34,6 +37,8 @@ function createClaudeStore() {
|
|||||||
isProcessing: { subscribe: isProcessing.subscribe },
|
isProcessing: { subscribe: isProcessing.subscribe },
|
||||||
grantedTools: { subscribe: grantedTools.subscribe },
|
grantedTools: { subscribe: grantedTools.subscribe },
|
||||||
pendingRetryMessage: { subscribe: pendingRetryMessage.subscribe },
|
pendingRetryMessage: { subscribe: pendingRetryMessage.subscribe },
|
||||||
|
shouldRestoreHistory: { subscribe: shouldRestoreHistory.subscribe },
|
||||||
|
savedConversationHistory: { subscribe: savedConversationHistory.subscribe },
|
||||||
|
|
||||||
setConnectionStatus: (status: ConnectionStatus) => connectionStatus.set(status),
|
setConnectionStatus: (status: ConnectionStatus) => connectionStatus.set(status),
|
||||||
setSessionId: (id: string | null) => sessionId.set(id),
|
setSessionId: (id: string | null) => sessionId.set(id),
|
||||||
@@ -106,6 +111,21 @@ function createClaudeStore() {
|
|||||||
|
|
||||||
setPendingRetryMessage: (message: string | null) => pendingRetryMessage.set(message),
|
setPendingRetryMessage: (message: string | null) => pendingRetryMessage.set(message),
|
||||||
|
|
||||||
|
setShouldRestoreHistory: (should: boolean) => shouldRestoreHistory.set(should),
|
||||||
|
setSavedConversationHistory: (history: string | null) => savedConversationHistory.set(history),
|
||||||
|
|
||||||
|
getShouldRestoreHistory: (): boolean => {
|
||||||
|
let should = false;
|
||||||
|
shouldRestoreHistory.subscribe((s) => (should = s))();
|
||||||
|
return should;
|
||||||
|
},
|
||||||
|
|
||||||
|
getSavedConversationHistory: (): string | null => {
|
||||||
|
let history: string | null = null;
|
||||||
|
savedConversationHistory.subscribe((h) => (history = h))();
|
||||||
|
return history;
|
||||||
|
},
|
||||||
|
|
||||||
reset: () => {
|
reset: () => {
|
||||||
connectionStatus.set("disconnected");
|
connectionStatus.set("disconnected");
|
||||||
sessionId.set(null);
|
sessionId.set(null);
|
||||||
@@ -115,6 +135,8 @@ function createClaudeStore() {
|
|||||||
isProcessing.set(false);
|
isProcessing.set(false);
|
||||||
grantedTools.set(new Set());
|
grantedTools.set(new Set());
|
||||||
pendingRetryMessage.set(null);
|
pendingRetryMessage.set(null);
|
||||||
|
shouldRestoreHistory.set(false);
|
||||||
|
savedConversationHistory.set(null);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -125,3 +147,13 @@ export const hasPermissionPending = derived(
|
|||||||
claudeStore.pendingPermission,
|
claudeStore.pendingPermission,
|
||||||
($permission) => $permission !== null
|
($permission) => $permission !== null
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Derived store to check if Claude is currently processing (can be interrupted)
|
||||||
|
export const isClaudeProcessing = derived(
|
||||||
|
[claudeStore.connectionStatus, characterState],
|
||||||
|
([$connectionStatus, $characterState]) => {
|
||||||
|
// Must be connected and in one of the processing states
|
||||||
|
return $connectionStatus === "connected" &&
|
||||||
|
["thinking", "typing", "searching", "coding", "mcp"].includes($characterState);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
// Separate module for history restoration to ensure persistence across reconnects
|
||||||
|
let shouldRestore = false;
|
||||||
|
let savedHistory: string | null = null;
|
||||||
|
|
||||||
|
export function setShouldRestoreHistory(should: boolean) {
|
||||||
|
shouldRestore = should;
|
||||||
|
console.log("Setting shouldRestoreHistory to:", should);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setSavedHistory(history: string | null) {
|
||||||
|
savedHistory = history;
|
||||||
|
console.log("Setting savedHistory, length:", history?.length || 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getShouldRestoreHistory(): boolean {
|
||||||
|
console.log("Getting shouldRestoreHistory:", shouldRestore);
|
||||||
|
return shouldRestore;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getSavedHistory(): string | null {
|
||||||
|
console.log("Getting savedHistory, length:", savedHistory?.length || 0);
|
||||||
|
return savedHistory;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearHistoryRestore() {
|
||||||
|
console.log("Clearing history restore flags");
|
||||||
|
shouldRestore = false;
|
||||||
|
savedHistory = null;
|
||||||
|
}
|
||||||
+21
-2
@@ -21,6 +21,11 @@ interface StateChangePayload {
|
|||||||
|
|
||||||
let hasConnectedThisSession = false;
|
let hasConnectedThisSession = false;
|
||||||
let unlisteners: Array<() => void> = [];
|
let unlisteners: Array<() => void> = [];
|
||||||
|
let skipNextGreeting = false;
|
||||||
|
|
||||||
|
export function setSkipNextGreeting(skip: boolean) {
|
||||||
|
skipNextGreeting = skip;
|
||||||
|
}
|
||||||
|
|
||||||
function getTimeOfDay(): string {
|
function getTimeOfDay(): string {
|
||||||
const hour = new Date().getHours();
|
const hour = new Date().getHours();
|
||||||
@@ -42,6 +47,12 @@ function generateGreetingPrompt(): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function sendGreeting() {
|
async function sendGreeting() {
|
||||||
|
// Check if we should skip this greeting
|
||||||
|
if (skipNextGreeting) {
|
||||||
|
skipNextGreeting = false; // Reset the flag
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const config = configStore.getConfig();
|
const config = configStore.getConfig();
|
||||||
|
|
||||||
if (!config.greeting_enabled) {
|
if (!config.greeting_enabled) {
|
||||||
@@ -100,8 +111,16 @@ export async function initializeTauriListeners() {
|
|||||||
await sendGreeting();
|
await sendGreeting();
|
||||||
}
|
}
|
||||||
} else if (status === "disconnected") {
|
} else if (status === "disconnected") {
|
||||||
hasConnectedThisSession = false;
|
// Only reset session flag if we're not about to reconnect
|
||||||
claudeStore.addLine("system", "Disconnected from Claude Code");
|
if (!skipNextGreeting) {
|
||||||
|
hasConnectedThisSession = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Don't add system message if we're about to reconnect
|
||||||
|
if (!skipNextGreeting) {
|
||||||
|
claudeStore.addLine("system", "Disconnected from Claude Code");
|
||||||
|
}
|
||||||
|
|
||||||
characterState.setState("idle");
|
characterState.setState("idle");
|
||||||
} else if (status === "error") {
|
} else if (status === "error") {
|
||||||
hasConnectedThisSession = false;
|
hasConnectedThisSession = false;
|
||||||
|
|||||||
Reference in New Issue
Block a user