From 94b6230531360d387709a1852bdb12c9a5250c02 Mon Sep 17 00:00:00 2001 From: Ricky Xiang Date: Fri, 23 Oct 2026 09:31:01 -0400 Subject: [PATCH] Add Claude Code provider, system design follow-ups, and model updates - Add a "claude-code" provider that uses the Claude subscription (no API key) - Update OpenAI, Gemini and Anthropic model lists to current models - Detect system design problems and let users ask follow-up questions - Cap window height to the screen so long content scrolls - Add Cmd/Ctrl+Shift+Q quit shortcut and SHOW_IN_CAPTURE debug toggle Co-Authored-By: Claude Opus 5.5 --- README.md | 3 +- electron/ConfigHelper.ts | 68 ++-- electron/ProcessingHelper.ts | 406 ++++++++++++++++++--- electron/ipcHandlers.ts | 17 + electron/main.ts | 11 +- electron/preload.ts | 5 + electron/shortcuts.ts | 5 + src/App.tsx | 4 +- src/_pages/Solutions.tsx | 149 +++++++- src/components/Settings/SettingsDialog.tsx | 270 ++++++++++---- src/types/electron.d.ts | 5 + src/types/solutions.ts | 1 + 12 files changed, 769 insertions(+), 175 deletions(-) diff --git a/README.md b/README.md index 47aeaf6..b5b1c16 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ The application uses unidentifiable global keyboard shortcuts that won't be dete - Delete Last Screenshot: [Control or Cmd + L] - Process Screenshots: [Control or Cmd + Enter] - Start New Problem: [Control or Cmd + R] -- Quit: [Control or Cmd + Q] +- Quit: [Control or Cmd + Q] or [Control or Cmd + Shift + Q] - Decrease Opacity: [Control or Cmd + [] - Increase Opacity: [Control or Cmd + ]] - Zoom Out: [Control or Cmd + -] @@ -239,6 +239,7 @@ The packaged applications will be available in the `release` directory. - View the generated solutions with detailed explanations - Use debugging feature by taking more screenshots of error messages or code - Get structured analysis with identified issues, corrections, and optimizations + - For system design answers, type follow-up questions in the box under the design (Enter to send, Shift+Enter for a new line) - Toggle between solutions and queue views as needed 5. **Window Management** diff --git a/electron/ConfigHelper.ts b/electron/ConfigHelper.ts index 6d1d2db..59f04bf 100644 --- a/electron/ConfigHelper.ts +++ b/electron/ConfigHelper.ts @@ -7,7 +7,7 @@ import { OpenAI } from "openai" interface Config { apiKey: string; - apiProvider: "openai" | "gemini" | "anthropic"; // Added provider selection + apiProvider: "openai" | "gemini" | "anthropic" | "claude-code"; // Added provider selection extractionModel: string; solutionModel: string; debuggingModel: string; @@ -20,9 +20,9 @@ export class ConfigHelper extends EventEmitter { private defaultConfig: Config = { apiKey: "", apiProvider: "gemini", // Default to Gemini - extractionModel: "gemini-2.0-flash", // Default to Flash for faster responses - solutionModel: "gemini-2.0-flash", - debuggingModel: "gemini-2.0-flash", + extractionModel: "gemini-3.8-flash", // Default to Flash for faster responses + solutionModel: "gemini-3.8-flash", + debuggingModel: "gemini-3.8-flash", language: "python", opacity: 1.0 }; @@ -58,29 +58,37 @@ export class ConfigHelper extends EventEmitter { /** * Validate and sanitize model selection to ensure only allowed models are used */ - private sanitizeModelSelection(model: string, provider: "openai" | "gemini" | "anthropic"): string { + private sanitizeModelSelection(model: string, provider: Config["apiProvider"]): string { if (provider === "openai") { - // Only allow gpt-4o and gpt-4o-mini for OpenAI - const allowedModels = ['gpt-4o', 'gpt-4o-mini']; + // Only allow current GPT-6 models for OpenAI + const allowedModels = ['gpt-6.1-sol', 'gpt-6-astra', 'gpt-6-luna']; if (!allowedModels.includes(model)) { - console.warn(`Invalid OpenAI model specified: ${model}. Using default model: gpt-4o`); - return 'gpt-4o'; + console.warn(`Invalid OpenAI model specified: ${model}. Using default model: gpt-6.1-sol`); + return 'gpt-6.1-sol'; } return model; } else if (provider === "gemini") { - // Only allow gemini-1.5-pro and gemini-2.0-flash for Gemini - const allowedModels = ['gemini-1.5-pro', 'gemini-2.0-flash']; + // Only allow current Gemini models + const allowedModels = ['gemini-3.8-flash', 'gemini-4-argon', 'gemini-3.5-flash-lite']; if (!allowedModels.includes(model)) { - console.warn(`Invalid Gemini model specified: ${model}. Using default model: gemini-2.0-flash`); - return 'gemini-2.0-flash'; // Changed default to flash + console.warn(`Invalid Gemini model specified: ${model}. Using default model: gemini-3.8-flash`); + return 'gemini-3.8-flash'; // Changed default to flash } return model; } else if (provider === "anthropic") { // Only allow Claude models - const allowedModels = ['claude-3-7-sonnet-20250219', 'claude-3-5-sonnet-20241022', 'claude-3-opus-20240229']; + const allowedModels = ['claude-opus-5-5', 'claude-sonnet-5-5', 'claude-haiku-5-5']; if (!allowedModels.includes(model)) { - console.warn(`Invalid Anthropic model specified: ${model}. Using default model: claude-3-7-sonnet-20250219`); - return 'claude-3-7-sonnet-20250219'; + console.warn(`Invalid Anthropic model specified: ${model}. Using default model: claude-opus-5-5`); + return 'claude-opus-5-5'; + } + return model; + } else if (provider === "claude-code") { + // Claude Code takes model aliases, which always point at the latest model in each tier + const allowedModels = ['opus', 'sonnet', 'haiku']; + if (!allowedModels.includes(model)) { + console.warn(`Invalid Claude Code model specified: ${model}. Using default model: opus`); + return 'opus'; } return model; } @@ -95,7 +103,7 @@ export class ConfigHelper extends EventEmitter { const config = JSON.parse(configData); // Ensure apiProvider is a valid value - if (config.apiProvider !== "openai" && config.apiProvider !== "gemini" && config.apiProvider !== "anthropic") { + if (config.apiProvider !== "openai" && config.apiProvider !== "gemini" && config.apiProvider !== "anthropic" && config.apiProvider !== "claude-code") { config.apiProvider = "gemini"; // Default to Gemini if invalid } @@ -171,17 +179,21 @@ export class ConfigHelper extends EventEmitter { // If provider is changing, reset models to the default for that provider if (updates.apiProvider && updates.apiProvider !== currentConfig.apiProvider) { if (updates.apiProvider === "openai") { - updates.extractionModel = "gpt-4o"; - updates.solutionModel = "gpt-4o"; - updates.debuggingModel = "gpt-4o"; + updates.extractionModel = "gpt-6.1-sol"; + updates.solutionModel = "gpt-6.1-sol"; + updates.debuggingModel = "gpt-6.1-sol"; } else if (updates.apiProvider === "anthropic") { - updates.extractionModel = "claude-3-7-sonnet-20250219"; - updates.solutionModel = "claude-3-7-sonnet-20250219"; - updates.debuggingModel = "claude-3-7-sonnet-20250219"; + updates.extractionModel = "claude-opus-5-5"; + updates.solutionModel = "claude-opus-5-5"; + updates.debuggingModel = "claude-opus-5-5"; + } else if (updates.apiProvider === "claude-code") { + updates.extractionModel = "opus"; + updates.solutionModel = "opus"; + updates.debuggingModel = "opus"; } else { - updates.extractionModel = "gemini-2.0-flash"; - updates.solutionModel = "gemini-2.0-flash"; - updates.debuggingModel = "gemini-2.0-flash"; + updates.extractionModel = "gemini-3.8-flash"; + updates.solutionModel = "gemini-3.8-flash"; + updates.debuggingModel = "gemini-3.8-flash"; } } @@ -219,6 +231,10 @@ export class ConfigHelper extends EventEmitter { */ public hasApiKey(): boolean { const config = this.loadConfig(); + // Claude Code signs in with the user's Claude subscription, so it needs no key + if (config.apiProvider === "claude-code") { + return true; + } return !!config.apiKey && config.apiKey.trim().length > 0; } diff --git a/electron/ProcessingHelper.ts b/electron/ProcessingHelper.ts index 0dcd26f..f915f24 100644 --- a/electron/ProcessingHelper.ts +++ b/electron/ProcessingHelper.ts @@ -1,6 +1,8 @@ // ProcessingHelper.ts import fs from "node:fs" +import os from "node:os" import path from "node:path" +import { spawn } from "node:child_process" import { ScreenshotHelper } from "./ScreenshotHelper" import { IProcessingHelperDeps } from "./main" import * as axios from "axios" @@ -25,7 +27,7 @@ interface GeminiResponse { candidates: Array<{ content: { parts: Array<{ - text: string; + text?: string; }>; }; finishReason: string; @@ -53,6 +55,7 @@ export class ProcessingHelper { // AbortControllers for API requests private currentProcessingAbortController: AbortController | null = null private currentExtraProcessingAbortController: AbortController | null = null + private currentFollowUpAbortController: AbortController | null = null constructor(deps: IProcessingHelperDeps) { this.deps = deps @@ -477,7 +480,7 @@ export class ProcessingHelper { const messages = [ { role: "system" as const, - content: "You are a coding challenge interpreter. Analyze the screenshot of the coding problem and extract all relevant information. Return the information in JSON format with these fields: problem_statement, constraints, example_input, example_output. Just return the structured JSON without any other text." + content: "You are a coding challenge interpreter. Analyze the screenshot of the coding problem and extract all relevant information. Return the information in JSON format with these fields: problem_statement, constraints, example_input, example_output, problem_type. Set problem_type to 'system_design' if the screenshots ask you to design a system, product or architecture rather than write code, otherwise 'coding'. Use exactly these keys and no others. For a system design question, put the design question itself in problem_statement, word for word. Example or possible questions that a page says might be asked count as design questions; if several are listed, include all of them, numbered. Put surrounding guidance such as tips or evaluation criteria in constraints. Just return the structured JSON without any other text." }, { role: "user" as const, @@ -496,10 +499,9 @@ export class ProcessingHelper { // Send to OpenAI Vision API const extractionResponse = await this.openaiClient.chat.completions.create({ - model: config.extractionModel || "gpt-4o", + model: config.extractionModel || "gpt-6.1-sol", messages: messages, - max_tokens: 4000, - temperature: 0.2 + max_completion_tokens: 16000 }); // Parse the response @@ -531,7 +533,7 @@ export class ProcessingHelper { role: "user", parts: [ { - text: `You are a coding challenge interpreter. Analyze the screenshots of the coding problem and extract all relevant information. Return the information in JSON format with these fields: problem_statement, constraints, example_input, example_output. Just return the structured JSON without any other text. Preferred coding language we gonna use for this problem is ${language}.` + text: `You are a coding challenge interpreter. Analyze the screenshots of the coding problem and extract all relevant information. Return the information in JSON format with these fields: problem_statement, constraints, example_input, example_output, problem_type. Set problem_type to 'system_design' if the screenshots ask you to design a system, product or architecture rather than write code, otherwise 'coding'. Use exactly these keys and no others. For a system design question, put the design question itself in problem_statement, word for word. Example or possible questions that a page says might be asked count as design questions; if several are listed, include all of them, numbered. Put surrounding guidance such as tips or evaluation criteria in constraints. Just return the structured JSON without any other text. Preferred coding language we gonna use for this problem is ${language}.` }, ...imageDataList.map(data => ({ inlineData: { @@ -545,12 +547,11 @@ export class ProcessingHelper { // Make API request to Gemini const response = await axios.default.post( - `https://generativelanguage.googleapis.com/v1beta/models/${config.extractionModel || "gemini-2.0-flash"}:generateContent?key=${this.geminiApiKey}`, + `https://generativelanguage.googleapis.com/v1beta/models/${config.extractionModel || "gemini-3.8-flash"}:generateContent?key=${this.geminiApiKey}`, { contents: geminiMessages, generationConfig: { - temperature: 0.2, - maxOutputTokens: 4000 + maxOutputTokens: 16000 } }, { signal } @@ -562,7 +563,7 @@ export class ProcessingHelper { throw new Error("Empty response from Gemini API"); } - const responseText = responseData.candidates[0].content.parts[0].text; + const responseText = responseData.candidates[0].content.parts.map(part => part.text ?? "").join(""); // Handle when Gemini might wrap the JSON in markdown code blocks const jsonText = responseText.replace(/```json|```/g, '').trim(); @@ -574,8 +575,8 @@ export class ProcessingHelper { error: "Failed to process with Gemini API. Please check your API key or try again later." }; } - } else if (config.apiProvider === "anthropic") { - if (!this.anthropicClient) { + } else if (config.apiProvider === "anthropic" || config.apiProvider === "claude-code") { + if (config.apiProvider === "anthropic" && !this.anthropicClient) { return { success: false, error: "Anthropic API key not configured. Please check your settings." @@ -589,7 +590,7 @@ export class ProcessingHelper { content: [ { type: "text" as const, - text: `Extract the coding problem details from these screenshots. Return in JSON format with these fields: problem_statement, constraints, example_input, example_output. Preferred coding language is ${language}.` + text: `Extract the coding problem details from these screenshots. Return in JSON format with these fields: problem_statement, constraints, example_input, example_output, problem_type. Set problem_type to 'system_design' if the screenshots ask you to design a system, product or architecture rather than write code, otherwise 'coding'. Use exactly these keys and no others. For a system design question, put the design question itself in problem_statement, word for word. Example or possible questions that a page says might be asked count as design questions; if several are listed, include all of them, numbered. Put surrounding guidance such as tips or evaluation criteria in constraints. Preferred coding language is ${language}. Return only the JSON object, with no other text.` }, ...imageDataList.map(data => ({ type: "image" as const, @@ -603,19 +604,19 @@ export class ProcessingHelper { } ]; - const response = await this.anthropicClient.messages.create({ - model: config.extractionModel || "claude-3-7-sonnet-20250219", - max_tokens: 4000, - messages: messages, - temperature: 0.2 - }); - - const responseText = (response.content[0] as { type: 'text', text: string }).text; - const jsonText = responseText.replace(/```json|```/g, '').trim(); + const responseText = config.apiProvider === "claude-code" + ? await this.runClaudeCode(config.extractionModel || "opus", messages, signal) + : await this.createAnthropicText(config.extractionModel || "claude-opus-5-5", messages); + // Claude sometimes wraps the JSON in a sentence or a code fence; keep only the object + const jsonText = responseText.slice(responseText.indexOf("{"), responseText.lastIndexOf("}") + 1); problemInfo = JSON.parse(jsonText); } catch (error: any) { console.error("Error using Anthropic API:", error); + if (config.apiProvider === "claude-code") { + return { success: false, error: `Claude Code: ${error.message}` }; + } + // Add specific handling for Claude's limitations if (error.status === 429) { return { @@ -733,8 +734,41 @@ export class ProcessingHelper { }); } + // System design questions get a written design instead of code and complexity + const isSystemDesign = problemInfo.problem_type === "system_design"; + // Create prompt for solution generation - const promptText = ` + const promptText = isSystemDesign ? ` +Answer the following system design interview question the way a strong candidate would, following the Hello Interview delivery framework. + +QUESTION: +${problemInfo.problem_statement} + +ADDITIONAL CONTEXT: +${problemInfo.constraints || "None provided."} + +If several design questions are listed, answer the first one and name the others in one line at the very end. + +Use exactly these markdown sections, in this order: +## Functional Requirements +(the top 3 core requirements as "Users should be able to..." statements, then a short "Below the line (out of scope)" list) +## Non-Functional Requirements +(the 3 to 5 that matter most as "The system should..." statements, quantified where possible, such as "search latency under 500ms" or "availability over consistency", then a short "Below the line" list; include a scale estimate only where it changes the design) +## Core Entities +(a bulleted list of entity names with a few words each, not a full schema) +## API +(REST endpoints covering each functional requirement, such as "GET /businesses?query&lat&long&category -> Business[]"; take the user from the auth token, never from the request body) +## High-Level Design +(build it up one functional requirement at a time, with a ### subsection per requirement saying which components serve it and how a request flows through them; finish with one small ASCII diagram of the complete design, listing next to each database only the fields that matter) +## Deep Dives +(the 3 or 4 problems an interviewer would probe to meet the non-functional requirements, each as a ### heading phrased as a question; under each, give a Bad, Good and Great solution in a line or two apiece saying what each gets wrong, then explain the Great one in more depth) +## Key Decisions +(one bullet per decision, in the form "Decision: chosen option over the alternative, because of the trade-off") + +Only for a data-processing system such as a web crawler, add a ## Data Flow section after API listing the steps from input to output. + +Keep the high-level design simple and save the complexity for the deep dives. Always write the full answer: cover every section above completely, with no length limit, and never shorten a section, skip one or replace it with a summary. Use short bullets wherever prose isn't needed. +` : ` Generate a detailed solution for the following coding problem: PROBLEM STATEMENT: @@ -775,13 +809,12 @@ Your solution should be efficient, well-commented, and handle edge cases. // Send to OpenAI API const solutionResponse = await this.openaiClient.chat.completions.create({ - model: config.solutionModel || "gpt-4o", + model: config.solutionModel || "gpt-6.1-sol", messages: [ { role: "system", content: "You are an expert coding interview assistant. Provide clear, optimal solutions with detailed explanations." }, { role: "user", content: promptText } ], - max_tokens: 4000, - temperature: 0.2 + max_completion_tokens: 16000 }); responseContent = solutionResponse.choices[0].message.content; @@ -809,12 +842,11 @@ Your solution should be efficient, well-commented, and handle edge cases. // Make API request to Gemini const response = await axios.default.post( - `https://generativelanguage.googleapis.com/v1beta/models/${config.solutionModel || "gemini-2.0-flash"}:generateContent?key=${this.geminiApiKey}`, + `https://generativelanguage.googleapis.com/v1beta/models/${config.solutionModel || "gemini-3.8-flash"}:generateContent?key=${this.geminiApiKey}`, { contents: geminiMessages, generationConfig: { - temperature: 0.2, - maxOutputTokens: 4000 + maxOutputTokens: 16000 } }, { signal } @@ -826,7 +858,7 @@ Your solution should be efficient, well-commented, and handle edge cases. throw new Error("Empty response from Gemini API"); } - responseContent = responseData.candidates[0].content.parts[0].text; + responseContent = responseData.candidates[0].content.parts.map(part => part.text ?? "").join(""); } catch (error) { console.error("Error using Gemini API for solution:", error); return { @@ -834,9 +866,9 @@ Your solution should be efficient, well-commented, and handle edge cases. error: "Failed to generate solution with Gemini API. Please check your API key or try again later." }; } - } else if (config.apiProvider === "anthropic") { + } else if (config.apiProvider === "anthropic" || config.apiProvider === "claude-code") { // Anthropic processing - if (!this.anthropicClient) { + if (config.apiProvider === "anthropic" && !this.anthropicClient) { return { success: false, error: "Anthropic API key not configured. Please check your settings." @@ -857,17 +889,16 @@ Your solution should be efficient, well-commented, and handle edge cases. ]; // Send to Anthropic API - const response = await this.anthropicClient.messages.create({ - model: config.solutionModel || "claude-3-7-sonnet-20250219", - max_tokens: 4000, - messages: messages, - temperature: 0.2 - }); - - responseContent = (response.content[0] as { type: 'text', text: string }).text; + responseContent = config.apiProvider === "claude-code" + ? await this.runClaudeCode(config.solutionModel || "opus", messages, signal) + : await this.createAnthropicText(config.solutionModel || "claude-opus-5-5", messages); } catch (error: any) { console.error("Error using Anthropic API for solution:", error); + if (config.apiProvider === "claude-code") { + return { success: false, error: `Claude Code: ${error.message}` }; + } + // Add specific handling for Claude's limitations if (error.status === 429) { return { @@ -888,6 +919,26 @@ Your solution should be efficient, well-commented, and handle edge cases. } } + if (isSystemDesign) { + // The whole write-up is the design; its Key Decisions bullets fill the thoughts list + const decisionsMatch = responseContent?.match(/##\s*Key Decisions\s*\n([\s\S]*?)(?=\n##\s|$)/i); + const decisions = decisionsMatch + ? decisionsMatch[1].split("\n") + .filter((line) => /^\s*(?:[-*•]|\d+\.)\s+/.test(line)) + .map((line) => line.replace(/^\s*(?:[-*•]|\d+\.)\s+/, "").trim()) + : []; + + return { + success: true, + data: { + code: responseContent, + thoughts: decisions.length > 0 ? decisions : ["See the design below"], + time_complexity: "", + space_complexity: "" + } + }; + } + // Extract parts from the response const codeMatch = responseContent.match(/```(?:\w+)?\s*([\s\S]*?)```/); const code = codeMatch ? codeMatch[1].trim() : responseContent; @@ -1067,10 +1118,9 @@ If you include code examples, use proper markdown code blocks with language spec } const debugResponse = await this.openaiClient.chat.completions.create({ - model: config.debuggingModel || "gpt-4o", + model: config.debuggingModel || "gpt-6.1-sol", messages: messages, - max_tokens: 4000, - temperature: 0.2 + max_completion_tokens: 16000 }); debugContent = debugResponse.choices[0].message.content; @@ -1130,12 +1180,11 @@ If you include code examples, use proper markdown code blocks with language spec } const response = await axios.default.post( - `https://generativelanguage.googleapis.com/v1beta/models/${config.debuggingModel || "gemini-2.0-flash"}:generateContent?key=${this.geminiApiKey}`, + `https://generativelanguage.googleapis.com/v1beta/models/${config.debuggingModel || "gemini-3.8-flash"}:generateContent?key=${this.geminiApiKey}`, { contents: geminiMessages, generationConfig: { - temperature: 0.2, - maxOutputTokens: 4000 + maxOutputTokens: 16000 } }, { signal } @@ -1147,7 +1196,7 @@ If you include code examples, use proper markdown code blocks with language spec throw new Error("Empty response from Gemini API"); } - debugContent = responseData.candidates[0].content.parts[0].text; + debugContent = responseData.candidates[0].content.parts.map(part => part.text ?? "").join(""); } catch (error) { console.error("Error using Gemini API for debugging:", error); return { @@ -1155,14 +1204,14 @@ If you include code examples, use proper markdown code blocks with language spec error: "Failed to process debug request with Gemini API. Please check your API key or try again later." }; } - } else if (config.apiProvider === "anthropic") { - if (!this.anthropicClient) { + } else if (config.apiProvider === "anthropic" || config.apiProvider === "claude-code") { + if (config.apiProvider === "anthropic" && !this.anthropicClient) { return { success: false, error: "Anthropic API key not configured. Please check your settings." }; } - + try { const debugPrompt = ` You are a coding interview assistant helping debug and improve solutions. Analyze these screenshots which include either error messages, incorrect outputs, or test cases, and provide detailed debugging help. @@ -1215,17 +1264,16 @@ If you include code examples, use proper markdown code blocks with language spec }); } - const response = await this.anthropicClient.messages.create({ - model: config.debuggingModel || "claude-3-7-sonnet-20250219", - max_tokens: 4000, - messages: messages, - temperature: 0.2 - }); - - debugContent = (response.content[0] as { type: 'text', text: string }).text; + debugContent = config.apiProvider === "claude-code" + ? await this.runClaudeCode(config.debuggingModel || "opus", messages, signal) + : await this.createAnthropicText(config.debuggingModel || "claude-opus-5-5", messages); } catch (error: any) { console.error("Error using Anthropic API for debugging:", error); - + + if (config.apiProvider === "claude-code") { + return { success: false, error: `Claude Code: ${error.message}` }; + } + // Add specific handling for Claude's limitations if (error.status === 429) { return { @@ -1290,9 +1338,128 @@ If you include code examples, use proper markdown code blocks with language spec } } + /** + * Answer a follow-up question about a system design answer. The question, the design + * and the earlier follow-ups go in as a single prompt, so every provider (including the + * Claude Code CLI, which takes one turn per call) sees the whole conversation. + */ + public async answerFollowUp(request: { + design: string + history: Array<{ question: string; answer: string }> + question: string + }): Promise<{ success: boolean; data?: string; error?: string }> { + const problemInfo = this.deps.getProblemInfo(); + const config = configHelper.loadConfig(); + + const earlierFollowUps = request.history + .map((turn) => `Q: ${turn.question}\nA: ${turn.answer}`) + .join("\n\n"); + + const promptText = ` +You are an expert system design interview assistant. You answered the system design question below; now answer a follow-up question about your design. + +QUESTION: +${problemInfo?.problem_statement || "Not available."} + +ADDITIONAL CONTEXT: +${problemInfo?.constraints || "None provided."} + +YOUR DESIGN: +${request.design} +${earlierFollowUps ? `\nEARLIER FOLLOW-UPS:\n${earlierFollowUps}\n` : ""} +FOLLOW-UP QUESTION: +${request.question} + +Always give the full write-up: answer the follow-up completely and in depth, with no length limit, building on the design above rather than repeating it. If it changes a requirement or adds a constraint, walk through everything in the design that changes and why. Use markdown with short bullets wherever prose isn't needed, and add an ASCII diagram if it helps. +`; + + this.currentFollowUpAbortController = new AbortController(); + const { signal } = this.currentFollowUpAbortController; + + try { + let answer: string | null | undefined; + + if (config.apiProvider === "openai") { + if (!this.openaiClient) { + return { success: false, error: "OpenAI API key not configured. Please check your settings." }; + } + + const response = await this.openaiClient.chat.completions.create({ + model: config.solutionModel || "gpt-6.1-sol", + messages: [{ role: "user", content: promptText }], + max_completion_tokens: 16000 + }, { signal }); + + answer = response.choices[0].message.content; + } else if (config.apiProvider === "gemini") { + if (!this.geminiApiKey) { + return { success: false, error: "Gemini API key not configured. Please check your settings." }; + } + + const response = await axios.default.post( + `https://generativelanguage.googleapis.com/v1beta/models/${config.solutionModel || "gemini-3.8-flash"}:generateContent?key=${this.geminiApiKey}`, + { + contents: [{ role: "user", parts: [{ text: promptText }] }], + generationConfig: { + maxOutputTokens: 16000 + } + }, + { signal } + ); + + const responseData = response.data as GeminiResponse; + answer = responseData.candidates?.[0]?.content?.parts?.map(part => part.text ?? "").join(""); + } else if (config.apiProvider === "anthropic" || config.apiProvider === "claude-code") { + if (config.apiProvider === "anthropic" && !this.anthropicClient) { + return { success: false, error: "Anthropic API key not configured. Please check your settings." }; + } + + const messages = [ + { + role: "user" as const, + content: [{ type: "text" as const, text: promptText }] + } + ]; + + answer = config.apiProvider === "claude-code" + ? await this.runClaudeCode(config.solutionModel || "opus", messages, signal) + : await this.createAnthropicText(config.solutionModel || "claude-opus-5-5", messages, signal); + } + + if (!answer?.trim()) { + return { success: false, error: "The model returned an empty answer. Please try again." }; + } + + return { success: true, data: answer.trim() }; + } catch (error: any) { + console.error("Error answering follow-up:", error); + + if (signal.aborted) { + return { success: false, error: "The follow-up was canceled." }; + } + + return { + success: false, + error: config.apiProvider === "claude-code" + ? `Claude Code: ${error.message}` + : error.message || "Failed to answer the follow-up. Please try again." + }; + } finally { + // A reset may already have replaced this controller with a newer request's + if (this.currentFollowUpAbortController?.signal === signal) { + this.currentFollowUpAbortController = null; + } + } + } + public cancelOngoingRequests(): void { let wasCancelled = false + if (this.currentFollowUpAbortController) { + this.currentFollowUpAbortController.abort() + this.currentFollowUpAbortController = null + } + if (this.currentProcessingAbortController) { this.currentProcessingAbortController.abort() this.currentProcessingAbortController = null @@ -1314,4 +1481,125 @@ If you include code examples, use proper markdown code blocks with language spec mainWindow.webContents.send(this.deps.PROCESSING_EVENTS.NO_SCREENSHOTS) } } + + /** + * Send a request to Claude and return the text of its reply. + * Current Claude models think before answering (thinking tokens count toward + * max_tokens) and reject a custom temperature. Opus and Sonnet requests opt into + * server-side refusal fallbacks; Haiku has none. + */ + private async createAnthropicText( + model: string, + messages: Anthropic.Beta.Messages.BetaMessageParam[], + signal?: AbortSignal + ): Promise { + if (!this.anthropicClient) { + throw new Error("Anthropic client not initialized"); + } + + // SDK 0.39 predates the fallbacks parameter, hence the cast below + const fallbackParams = model.startsWith("claude-haiku") + ? {} + : { betas: ["server-side-fallback-2026-07-01"], fallbacks: "default" }; + + const response = await this.anthropicClient.beta.messages.create({ + model, + max_tokens: 16000, + messages, + ...fallbackParams + } as Anthropic.Beta.Messages.MessageCreateParamsNonStreaming, { signal }); + + if ((response.stop_reason as string) === "refusal") { + throw new Error("Claude declined to answer this request."); + } + + return response.content + .filter((block): block is Anthropic.Beta.Messages.BetaTextBlock => block.type === "text") + .map((block) => block.text) + .join(""); + } + + /** + * Send a request through the local Claude Code CLI, so it counts against the user's + * Claude subscription instead of API billing. Messages go in as stream-json, which lets + * screenshots travel inline, with every tool disabled and the user's own Claude Code + * customizations (CLAUDE.md, hooks, MCP servers) switched off by --safe-mode. + */ + private runClaudeCode( + model: string, + messages: Anthropic.Beta.Messages.BetaMessageParam[], + signal?: AbortSignal + ): Promise { + // Drop the variables a parent Claude Code session sets (a nested session refuses to + // start) and any API key, so the CLI signs in with the subscription + const env: NodeJS.ProcessEnv = {}; + for (const [name, value] of Object.entries(process.env)) { + if (!/^(CLAUDECODE$|CLAUDE_CODE_|CLAUDE_PID$|CLAUDE_EFFORT$|ANTHROPIC_API_KEY$)/.test(name)) { + env[name] = value; + } + } + // Apps opened from Finder get a minimal PATH, so add the usual install locations + env.PATH = [env.PATH, path.join(os.homedir(), ".local", "bin"), "/opt/homebrew/bin", "/usr/local/bin"] + .filter(Boolean) + .join(path.delimiter); + + const args = [ + "-p", + "--input-format", "stream-json", + "--output-format", "stream-json", + "--verbose", + "--model", model, + // Matches the API's default for Opus; Claude Code's own default runs far longer per answer + "--effort", "medium", + "--tools", "", + "--safe-mode", + "--no-session-persistence", + "--system-prompt", "You are an expert coding interview assistant. Follow the user's instructions exactly and answer directly." + ]; + + return new Promise((resolve, reject) => { + const child = spawn("claude", args, { + cwd: app.getPath("temp"), + env, + signal, + timeout: 5 * 60 * 1000 + }); + + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (chunk) => { stdout += chunk; }); + child.stderr.on("data", (chunk) => { stderr += chunk; }); + // A failed spawn also fails the stdin write; the process "error" event reports it + child.stdin.on("error", () => {}); + + child.on("error", (error: NodeJS.ErrnoException) => { + reject(error.code === "ENOENT" + ? new Error("Claude Code isn't installed or isn't on your PATH. Install it from claude.com/claude-code and sign in with your Claude account.") + : error); + }); + + child.on("close", (code) => { + // The final stream-json event is the result: { type: "result", is_error, result } + let result: { is_error?: boolean; result?: string } | undefined; + for (const line of stdout.split("\n")) { + try { + const event = JSON.parse(line); + if (event.type === "result") result = event; + } catch { + // Not a JSON event line + } + } + + if (result && !result.is_error && typeof result.result === "string") { + resolve(result.result); + } else { + reject(new Error(result?.result || stderr.trim() || `exited with code ${code} without a result`)); + } + }); + + child.stdin.end( + messages.map((message) => JSON.stringify({ type: "user", message })).join("\n") + "\n" + ); + }); + } } diff --git a/electron/ipcHandlers.ts b/electron/ipcHandlers.ts index f05a9ae..2e8d7e6 100644 --- a/electron/ipcHandlers.ts +++ b/electron/ipcHandlers.ts @@ -103,6 +103,23 @@ export function initializeIpcHandlers(deps: IIpcHandlerDeps): void { await deps.processingHelper?.processScreenshots() }) + ipcMain.handle( + "ask-follow-up", + async ( + _event, + request: { + design: string + history: Array<{ question: string; answer: string }> + question: string + } + ) => { + if (!deps.processingHelper) { + return { success: false, error: "The app hasn't finished starting. Please try again." } + } + return deps.processingHelper.answerFollowUp(request) + } + ) + // Window dimension handlers ipcMain.handle( "update-content-dimensions", diff --git a/electron/main.ts b/electron/main.ts index 0eae187..88fb278 100644 --- a/electron/main.ts +++ b/electron/main.ts @@ -11,6 +11,8 @@ import * as dotenv from "dotenv" // Constants const isDev = process.env.NODE_ENV === "development" +// Set SHOW_IN_CAPTURE=1 to let screenshots and screen sharing see the window (useful for debugging) +const contentProtection = process.env.SHOW_IN_CAPTURE !== "1" // Application State const state = { @@ -309,7 +311,7 @@ async function createWindow(): Promise { }) // Enhanced screen capture resistance - state.mainWindow.setContentProtection(true) + state.mainWindow.setContentProtection(contentProtection) state.mainWindow.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true @@ -413,7 +415,7 @@ function showMainWindow(): void { state.mainWindow.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true }); - state.mainWindow.setContentProtection(true); + state.mainWindow.setContentProtection(contentProtection); state.mainWindow.setOpacity(0); // Set opacity to 0 before showing state.mainWindow.showInactive(); // Use showInactive instead of show+focus state.mainWindow.setOpacity(1); // Then set opacity to 1 after showing @@ -477,12 +479,15 @@ function setWindowDimensions(width: number, height: number): void { const primaryDisplay = screen.getPrimaryDisplay() const workArea = primaryDisplay.workAreaSize const maxWidth = Math.floor(workArea.width * 0.5) + // Keep the window on screen; taller content scrolls inside it + const { y: workTop, height: workHeight } = primaryDisplay.workArea + const maxHeight = Math.max(550, workTop + workHeight - currentY) state.mainWindow.setBounds({ x: Math.min(currentX, workArea.width - maxWidth), y: currentY, width: Math.min(width + 32, maxWidth), - height: Math.ceil(height) + height: Math.min(Math.ceil(height), maxHeight) }) } } diff --git a/electron/preload.ts b/electron/preload.ts index 85f3215..dee358e 100644 --- a/electron/preload.ts +++ b/electron/preload.ts @@ -35,6 +35,11 @@ const electronAPI = { ipcRenderer.invoke("update-content-dimensions", dimensions), clearStore: () => ipcRenderer.invoke("clear-store"), getScreenshots: () => ipcRenderer.invoke("get-screenshots"), + askFollowUp: (request: { + design: string + history: Array<{ question: string; answer: string }> + question: string + }) => ipcRenderer.invoke("ask-follow-up", request), deleteScreenshot: (path: string) => ipcRenderer.invoke("delete-screenshot", path), toggleMainWindow: async () => { diff --git a/electron/shortcuts.ts b/electron/shortcuts.ts index a6fa5eb..5d0dec1 100644 --- a/electron/shortcuts.ts +++ b/electron/shortcuts.ts @@ -111,6 +111,11 @@ export class ShortcutsHelper { app.quit() }) + globalShortcut.register("CommandOrControl+Shift+Q", () => { + console.log("Command/Ctrl + Shift + Q pressed. Quitting application.") + app.quit() + }) + // Adjust opacity shortcuts globalShortcut.register("CommandOrControl+[", () => { console.log("Command/Ctrl + [ pressed. Decreasing opacity.") diff --git a/src/App.tsx b/src/App.tsx index f2dd348..337499c 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -182,8 +182,8 @@ function App() { // Event listeners for process events const onApiKeyInvalid = () => { showToast( - "API Key Invalid", - "Your OpenAI API key appears to be invalid or has insufficient credits", + "API Key Missing", + "The selected provider has no valid API key. Add one in Settings, or choose Claude Code to use your Claude subscription.", "error" ) setApiKeyDialogOpen(true) diff --git a/src/_pages/Solutions.tsx b/src/_pages/Solutions.tsx index e193945..d5ead0c 100644 --- a/src/_pages/Solutions.tsx +++ b/src/_pages/Solutions.tsx @@ -103,6 +103,134 @@ const SolutionSection = ({ ) } +interface FollowUp { + id: number + question: string + answer: string | null + error?: string +} + +const FollowUpSection = ({ design }: { design: string }) => { + const [followUps, setFollowUps] = useState([]) + const [question, setQuestion] = useState("") + const latestFollowUpRef = useRef(null) + const isAsking = followUps.some( + (followUp) => followUp.answer === null && !followUp.error + ) + + // Bring each new question into view so its answer appears right below it + useEffect(() => { + latestFollowUpRef.current?.scrollIntoView({ + behavior: "smooth", + block: "start" + }) + }, [followUps.length]) + + const askFollowUp = async () => { + const trimmedQuestion = question.trim() + if (!trimmedQuestion || isAsking) return + + const id = Date.now() + // Failed follow-ups have no answer, so they don't go back to the model + const history = followUps.flatMap((followUp) => + followUp.answer + ? [{ question: followUp.question, answer: followUp.answer }] + : [] + ) + setFollowUps((current) => [ + ...current, + { id, question: trimmedQuestion, answer: null } + ]) + setQuestion("") + + let result: { success: boolean; data?: string; error?: string } + try { + result = await window.electronAPI.askFollowUp({ + design, + history, + question: trimmedQuestion + }) + } catch (error) { + console.error("Error asking follow-up:", error) + result = { success: false } + } + + setFollowUps((current) => + current.map((followUp) => { + if (followUp.id !== id) return followUp + return result.success && result.data + ? { ...followUp, answer: result.data } + : { + ...followUp, + error: result.error || "Failed to answer the follow-up." + } + }) + ) + } + + return ( +
+

+ Follow-ups +

+ + {followUps.map((followUp, index) => ( +
+
+ {followUp.question} +
+ {followUp.error ? ( +

{followUp.error}

+ ) : followUp.answer === null ? ( +

+ Thinking... +

+ ) : ( + + {followUp.answer} + + )} +
+ ))} + +