parent
6f2f042ffa
commit
4d5faa0076
@ -0,0 +1,3 @@
|
||||
release/Interview[[:space:]]Coder-1.0.0-arm64-mac.zip filter=lfs diff=lfs merge=lfs -text
|
||||
release/Interview[[:space:]]Coder-1.0.0-arm64.dmg filter=lfs diff=lfs merge=lfs -text
|
||||
release/mac-arm64/Interview[[:space:]]Coder.app/Contents/Frameworks/Electron[[:space:]]Framework.framework/Versions/A/Electron[[:space:]]Framework filter=lfs diff=lfs merge=lfs -text
|
||||
@ -0,0 +1,13 @@
|
||||
node_modules
|
||||
dist-electron
|
||||
release
|
||||
dist
|
||||
.env
|
||||
.env.*
|
||||
**/.DS_Store
|
||||
**/.vscode
|
||||
**/.idea
|
||||
**/package-lock.json
|
||||
scripts/
|
||||
**/scripts/
|
||||
scripts/manual-notarize.js
|
||||
@ -0,0 +1,36 @@
|
||||
# Interview Coder - Unlocked Edition - Changes
|
||||
|
||||
## Fixes and Improvements
|
||||
|
||||
### UI Improvements
|
||||
1. **Fixed Language Dropdown Functionality**:
|
||||
- Enabled the language dropdown in the settings panel
|
||||
- Added proper language change handling
|
||||
- Made language selection persist across sessions
|
||||
|
||||
2. **Implemented Working Logout Button**:
|
||||
- Added proper API key clearing functionality to the logout button
|
||||
- Added success feedback via toast message
|
||||
- Implemented app reload after logout to reset state
|
||||
|
||||
3. **Fixed Window Size Issues**:
|
||||
- Added explicit window dimensions in main.ts (width: 800px, height: 600px)
|
||||
- Added minimum window size constraints to prevent UI issues
|
||||
- Improved dimension handling with fallback sizes
|
||||
|
||||
4. **Improved Settings Dialog Positioning**:
|
||||
- Made settings dialog responsive with min/max constraints
|
||||
- Added z-index to ensure dialog appears above other content
|
||||
- Improved positioning to center properly regardless of window size
|
||||
|
||||
5. **Enhanced Dropdown Initialization**:
|
||||
- Improved dropdown initialization timing
|
||||
- Reduced initialization delay for better responsiveness
|
||||
|
||||
### Maintaining Original UI Design
|
||||
- Preserved the original UI design and interaction patterns
|
||||
- Fixed functionality within the existing UI rather than adding new elements
|
||||
- Kept the settings accessible through the gear icon menu
|
||||
|
||||
These changes fix the issues while preserving the original app's look and feel, just removing the payment restrictions and making everything work properly.
|
||||
|
||||
@ -0,0 +1,57 @@
|
||||
# Contributing to Interview Coder - Unlocked Edition
|
||||
|
||||
First off, thank you for considering contributing to Interview Coder! We created this tool to help the community, and we welcome improvements that make it better for everyone.
|
||||
|
||||
## Our Community Values
|
||||
|
||||
- **Collaborative Development**: We believe in building together rather than fragmenting our efforts
|
||||
- **Open Access**: We want to keep this tool accessible to everyone who needs it
|
||||
- **Continuous Improvement**: The tool should get better with each contribution
|
||||
|
||||
## How to Contribute
|
||||
|
||||
### 1. Fork the Repository
|
||||
|
||||
- Click the "Fork" button at the top of the repository page
|
||||
- Clone your fork locally: `git clone https://github.com/YOUR-USERNAME/interview-coder-unlocked.git`
|
||||
|
||||
### 2. Create a Branch
|
||||
|
||||
- Create a branch for your feature: `git checkout -b feature/your-feature-name`
|
||||
|
||||
### 3. Make Your Changes
|
||||
|
||||
- Implement your changes, improvements, or bug fixes
|
||||
- Make sure to test your changes thoroughly
|
||||
- Ensure your code follows the existing style
|
||||
|
||||
### 4. Submit a Pull Request
|
||||
|
||||
- Push your changes to your fork: `git push origin feature/your-feature-name`
|
||||
- Go to the original repository and create a Pull Request
|
||||
- Describe your changes in detail
|
||||
- Reference any related issues
|
||||
|
||||
## Guidelines for Modifications
|
||||
|
||||
Under the AGPL-3.0 license, you are free to modify the code, but we strongly encourage you to:
|
||||
|
||||
1. **Contribute Back**: Submit your improvements as Pull Requests to the main repository
|
||||
2. **Share Openly**: Make your modifications available to the public, especially if you deploy a modified version
|
||||
3. **Maintain Attribution**: Keep the original copyright notices and license information
|
||||
|
||||
## License Compliance
|
||||
|
||||
Remember that this project is licensed under the GNU Affero General Public License v3.0 (AGPL-3.0). This means:
|
||||
|
||||
- You must disclose your source code when you distribute the software
|
||||
- If you modify the software and run it on a server that users interact with, you must make the source code of your modified version available to those users
|
||||
- Any modifications you make must also be licensed under the AGPL-3.0
|
||||
|
||||
## Community Guidelines
|
||||
|
||||
- Be respectful and constructive in your comments and feedback
|
||||
- Help review other contributors' pull requests
|
||||
- Report bugs and issues clearly with steps to reproduce
|
||||
|
||||
Thank you for helping make Interview Coder better for everyone!
|
||||
@ -0,0 +1,23 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2025 Interview Coder - Unlocked Edition
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
The full text of the license can be found at: https://www.gnu.org/licenses/agpl-3.0.html
|
||||
|
||||
ADDITIONAL TERMS:
|
||||
- Any modifications made to this software should be contributed back to the main project repository.
|
||||
- If you deploy this software on a network server, you must make the complete source code of your modifications available to all users of that server.
|
||||
@ -0,0 +1,167 @@
|
||||
# Interview Coder - Unlocked Edition
|
||||
|
||||
An invisible desktop application that helps you pass your technical interviews.
|
||||
|
||||
## Features
|
||||
|
||||
- 🎯 99% Invisibility: Undetectable window that bypasses most screen capture methods
|
||||
- 📸 Smart Screenshot Capture: Capture both question text and code separately for better analysis
|
||||
- 🤖 AI-Powered Analysis: Automatically extracts and analyzes coding problems using GPT-4o
|
||||
- 💡 Solution Generation: Get detailed explanations and solutions with time/space complexity analysis
|
||||
- 🔧 Real-time Debugging: Debug your code with AI assistance and structured feedback
|
||||
- 🎨 Advanced Window Management: Freely move, resize, change opacity, and zoom the window
|
||||
- 🔄 Model Selection: Choose between GPT-4o and GPT-4o-mini for different processing stages
|
||||
- 🔒 Privacy-Focused: Your API key and data never leave your computer except for OpenAI API calls
|
||||
|
||||
## Global Commands
|
||||
|
||||
The application uses unidentifiable global keyboard shortcuts that won't be detected by browsers or other applications:
|
||||
|
||||
- Toggle Window Visibility: [Control or Cmd + B]
|
||||
- Move Window: [Control or Cmd + Arrow keys]
|
||||
- Take Screenshot: [Control or Cmd + H]
|
||||
- Delete Last Screenshot: [Control or Cmd + L]
|
||||
- Process Screenshots: [Control or Cmd + Enter]
|
||||
- Reset View: [Control or Cmd + R]
|
||||
- Quit: [Control or Cmd + Q]
|
||||
- Decrease Opacity: [Control or Cmd + []
|
||||
- Increase Opacity: [Control or Cmd + ]]
|
||||
- Zoom Out: [Control or Cmd + -]
|
||||
- Reset Zoom: [Control or Cmd + 0]
|
||||
- Zoom In: [Control or Cmd + =]
|
||||
|
||||
## Invisibility Compatibility
|
||||
|
||||
The application is invisible to:
|
||||
|
||||
- Zoom versions below 6.1.6 (inclusive)
|
||||
- All browser-based screen recording software
|
||||
- All versions of Discord
|
||||
- Mac OS _screenshot_ functionality (Command + Shift + 3/4)
|
||||
|
||||
Note: The application is **NOT** invisible to:
|
||||
|
||||
- Zoom versions 6.1.6 and above
|
||||
- https://zoom.en.uptodown.com/mac/versions (link to downgrade Zoom if needed)
|
||||
- Mac OS native screen _recording_ (Command + Shift + 5)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js (v16 or higher)
|
||||
- npm or bun package manager
|
||||
- OpenAI API Key
|
||||
- Screen Recording Permission for Terminal/IDE
|
||||
- On macOS:
|
||||
1. Go to System Preferences > Security & Privacy > Privacy > Screen Recording
|
||||
2. Ensure that Interview Coder has screen recording permission enabled
|
||||
3. Restart Interview Coder after enabling permissions
|
||||
- On Windows:
|
||||
- No additional permissions needed
|
||||
- On Linux:
|
||||
- May require `xhost` access depending on your distribution
|
||||
|
||||
## Installation
|
||||
|
||||
1. Clone the repository:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/yourusername/interview-coder-unlocked.git
|
||||
cd interview-coder-unlocked
|
||||
```
|
||||
|
||||
2. Install dependencies:
|
||||
|
||||
```bash
|
||||
npm install
|
||||
# or if using bun
|
||||
bun install
|
||||
```
|
||||
|
||||
3. Start the application:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
4. Enter your OpenAI API key in the settings dialog when prompted.
|
||||
|
||||
## Running in Production
|
||||
|
||||
1. Build the application:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
2. The built application will be in the `dist` directory.
|
||||
|
||||
3. Alternatively, you can use the provided `stealth-run.bat` to quickly build and launch the application.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- Electron
|
||||
- React
|
||||
- TypeScript
|
||||
- Vite
|
||||
- Tailwind CSS
|
||||
- Radix UI Components
|
||||
- OpenAI API
|
||||
|
||||
## How It Works
|
||||
|
||||
1. **Initial Setup**
|
||||
- Launch the invisible window
|
||||
- Enter your OpenAI API key in the settings
|
||||
- Choose your preferred model for extraction, solution generation, and debugging
|
||||
|
||||
2. **Capturing Problem**
|
||||
- Use global shortcut [Control or Cmd + H] to take screenshots of code problems
|
||||
- Screenshots are automatically added to the queue of up to 2
|
||||
- If needed, remove the last screenshot with [Control or Cmd + L]
|
||||
|
||||
3. **Processing**
|
||||
- Press [Control or Cmd + Enter] to analyze the screenshots
|
||||
- AI extracts problem requirements from the screenshots using GPT-4 Vision API
|
||||
- The model generates an optimal solution based on the extracted information
|
||||
- All analysis is done using your personal OpenAI API key
|
||||
|
||||
4. **Solution & Debugging**
|
||||
- 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
|
||||
- Toggle between solutions and queue views as needed
|
||||
|
||||
5. **Window Management**
|
||||
- Move window using [Control or Cmd + Arrow keys]
|
||||
- Toggle visibility with [Control or Cmd + B]
|
||||
- Adjust opacity with [Control or Cmd + [] and [Control or Cmd + ]]
|
||||
- Window remains invisible to specified screen sharing applications
|
||||
- Reset view using [Control or Cmd + R]
|
||||
|
||||
## Configuration
|
||||
|
||||
- **OpenAI API Key**: Your personal API key is stored locally and only used for API calls to OpenAI
|
||||
- **Model Selection**: You can choose between GPT-4o and GPT-4o-mini for each stage of processing:
|
||||
- Problem Extraction: Analyzes screenshots to understand the coding problem
|
||||
- Solution Generation: Creates optimized solutions with explanations
|
||||
- Debugging: Provides detailed analysis of errors and improvement suggestions
|
||||
- **Language**: Select your preferred programming language for solutions
|
||||
- **Window Controls**: Adjust opacity, position, and zoom level using keyboard shortcuts
|
||||
- **All settings are stored locally** in your user data directory and persist between sessions
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the GNU Affero General Public License v3.0 (AGPL-3.0).
|
||||
|
||||
### What This Means
|
||||
|
||||
- You are free to use, modify, and distribute this software
|
||||
- If you modify the code, you must make your changes available under the same license
|
||||
- If you run a modified version on a network server, you must make the source code available to users
|
||||
- We strongly encourage you to contribute improvements back to the main project
|
||||
|
||||
See the [LICENSE-SHORT](LICENSE-SHORT) file for a summary of terms or visit [GNU AGPL-3.0](https://www.gnu.org/licenses/agpl-3.0.html) for the full license text.
|
||||
|
||||
### Contributing
|
||||
|
||||
We welcome contributions! Please see our [Contributing Guidelines](CONTRIBUTING.md) for more information.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 232 KiB |
@ -0,0 +1,20 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.cs.allow-jit</key>
|
||||
<true/>
|
||||
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
|
||||
<true/>
|
||||
<key>com.apple.security.cs.debugger</key>
|
||||
<true/>
|
||||
<key>com.apple.security.device.camera</key>
|
||||
<true/>
|
||||
<key>com.apple.security.device.microphone</key>
|
||||
<true/>
|
||||
<key>com.apple.security.files.user-selected.read-write</key>
|
||||
<true/>
|
||||
<key>com.apple.security.network.client</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@ -0,0 +1,28 @@
|
||||
@echo off
|
||||
echo Cleaning up project for GitHub...
|
||||
|
||||
echo Removing node_modules directory...
|
||||
if exist node_modules rmdir /s /q node_modules
|
||||
|
||||
echo Removing dist directory...
|
||||
if exist dist rmdir /s /q dist
|
||||
|
||||
echo Removing dist-electron directory...
|
||||
if exist dist-electron rmdir /s /q dist-electron
|
||||
|
||||
echo Removing release directory...
|
||||
if exist release rmdir /s /q release
|
||||
|
||||
echo Removing package-lock.json...
|
||||
if exist package-lock.json del package-lock.json
|
||||
|
||||
echo Removing any .env files...
|
||||
if exist .env del .env
|
||||
if exist .env.local del .env.local
|
||||
if exist .env.development del .env.development
|
||||
if exist .env.production del .env.production
|
||||
|
||||
echo Cleanup complete!
|
||||
echo Ready to commit to GitHub.
|
||||
echo Run 'npm install' after cloning to install dependencies.
|
||||
pause
|
||||
@ -0,0 +1,237 @@
|
||||
// ConfigHelper.ts
|
||||
import fs from "node:fs"
|
||||
import path from "node:path"
|
||||
import { app } from "electron"
|
||||
import { EventEmitter } from "events"
|
||||
import { OpenAI } from "openai"
|
||||
|
||||
interface Config {
|
||||
apiKey: string;
|
||||
extractionModel: string;
|
||||
solutionModel: string;
|
||||
debuggingModel: string;
|
||||
language: string;
|
||||
opacity: number;
|
||||
}
|
||||
|
||||
export class ConfigHelper extends EventEmitter {
|
||||
private configPath: string;
|
||||
private defaultConfig: Config = {
|
||||
apiKey: "",
|
||||
extractionModel: "gpt-4o",
|
||||
solutionModel: "gpt-4o",
|
||||
debuggingModel: "gpt-4o",
|
||||
language: "python",
|
||||
opacity: 1.0
|
||||
};
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
// Use the app's user data directory to store the config
|
||||
try {
|
||||
this.configPath = path.join(app.getPath('userData'), 'config.json');
|
||||
console.log('Config path:', this.configPath);
|
||||
} catch (err) {
|
||||
console.warn('Could not access user data path, using fallback');
|
||||
this.configPath = path.join(process.cwd(), 'config.json');
|
||||
}
|
||||
|
||||
// Ensure the initial config file exists
|
||||
this.ensureConfigExists();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure config file exists
|
||||
*/
|
||||
private ensureConfigExists(): void {
|
||||
try {
|
||||
if (!fs.existsSync(this.configPath)) {
|
||||
this.saveConfig(this.defaultConfig);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Error ensuring config exists:", err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the configuration from disk
|
||||
*/
|
||||
/**
|
||||
* Validate and sanitize model selection to ensure only allowed models are used
|
||||
*/
|
||||
private sanitizeModelSelection(model: string): string {
|
||||
// Only allow gpt-4o and gpt-4o-mini
|
||||
const allowedModels = ['gpt-4o', 'gpt-4o-mini'];
|
||||
if (!allowedModels.includes(model)) {
|
||||
// Default to gpt-4o if an invalid model is specified
|
||||
console.warn(`Invalid model specified: ${model}. Using default model: gpt-4o`);
|
||||
return 'gpt-4o';
|
||||
}
|
||||
return model;
|
||||
}
|
||||
|
||||
public loadConfig(): Config {
|
||||
try {
|
||||
if (fs.existsSync(this.configPath)) {
|
||||
const configData = fs.readFileSync(this.configPath, 'utf8');
|
||||
const config = JSON.parse(configData);
|
||||
|
||||
// Sanitize model selections to ensure only allowed models are used
|
||||
if (config.extractionModel) {
|
||||
config.extractionModel = this.sanitizeModelSelection(config.extractionModel);
|
||||
}
|
||||
if (config.solutionModel) {
|
||||
config.solutionModel = this.sanitizeModelSelection(config.solutionModel);
|
||||
}
|
||||
if (config.debuggingModel) {
|
||||
config.debuggingModel = this.sanitizeModelSelection(config.debuggingModel);
|
||||
}
|
||||
|
||||
return {
|
||||
...this.defaultConfig,
|
||||
...config
|
||||
};
|
||||
}
|
||||
|
||||
// If no config exists, create a default one
|
||||
this.saveConfig(this.defaultConfig);
|
||||
return this.defaultConfig;
|
||||
} catch (err) {
|
||||
console.error("Error loading config:", err);
|
||||
return this.defaultConfig;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save configuration to disk
|
||||
*/
|
||||
public saveConfig(config: Config): void {
|
||||
try {
|
||||
// Ensure the directory exists
|
||||
const configDir = path.dirname(this.configPath);
|
||||
if (!fs.existsSync(configDir)) {
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
}
|
||||
// Write the config file
|
||||
fs.writeFileSync(this.configPath, JSON.stringify(config, null, 2));
|
||||
} catch (err) {
|
||||
console.error("Error saving config:", err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update specific configuration values
|
||||
*/
|
||||
public updateConfig(updates: Partial<Config>): Config {
|
||||
try {
|
||||
const currentConfig = this.loadConfig();
|
||||
|
||||
// Sanitize model selections in the updates
|
||||
if (updates.extractionModel) {
|
||||
updates.extractionModel = this.sanitizeModelSelection(updates.extractionModel);
|
||||
}
|
||||
if (updates.solutionModel) {
|
||||
updates.solutionModel = this.sanitizeModelSelection(updates.solutionModel);
|
||||
}
|
||||
if (updates.debuggingModel) {
|
||||
updates.debuggingModel = this.sanitizeModelSelection(updates.debuggingModel);
|
||||
}
|
||||
|
||||
const newConfig = { ...currentConfig, ...updates };
|
||||
this.saveConfig(newConfig);
|
||||
|
||||
// Only emit update event for changes other than opacity
|
||||
// This prevents re-initializing the OpenAI client when only opacity changes
|
||||
if (updates.apiKey !== undefined || updates.extractionModel !== undefined ||
|
||||
updates.solutionModel !== undefined || updates.debuggingModel !== undefined ||
|
||||
updates.language !== undefined) {
|
||||
this.emit('config-updated', newConfig);
|
||||
}
|
||||
|
||||
return newConfig;
|
||||
} catch (error) {
|
||||
console.error('Error updating config:', error);
|
||||
return this.defaultConfig;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the API key is configured
|
||||
*/
|
||||
public hasApiKey(): boolean {
|
||||
const config = this.loadConfig();
|
||||
return !!config.apiKey && config.apiKey.trim().length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the API key format
|
||||
*/
|
||||
public isValidApiKeyFormat(apiKey: string): boolean {
|
||||
// Basic format validation for OpenAI API keys
|
||||
return /^sk-[a-zA-Z0-9]{32,}$/.test(apiKey.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the stored opacity value
|
||||
*/
|
||||
public getOpacity(): number {
|
||||
const config = this.loadConfig();
|
||||
return config.opacity !== undefined ? config.opacity : 1.0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the window opacity value
|
||||
*/
|
||||
public setOpacity(opacity: number): void {
|
||||
// Ensure opacity is between 0.1 and 1.0
|
||||
const validOpacity = Math.min(1.0, Math.max(0.1, opacity));
|
||||
this.updateConfig({ opacity: validOpacity });
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the preferred programming language
|
||||
*/
|
||||
public getLanguage(): string {
|
||||
const config = this.loadConfig();
|
||||
return config.language || "python";
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the preferred programming language
|
||||
*/
|
||||
public setLanguage(language: string): void {
|
||||
this.updateConfig({ language });
|
||||
}
|
||||
|
||||
/**
|
||||
* Test API key with OpenAI
|
||||
*/
|
||||
public async testApiKey(apiKey: string): Promise<{valid: boolean, error?: string}> {
|
||||
try {
|
||||
const openai = new OpenAI({ apiKey });
|
||||
// Make a simple API call to test the key
|
||||
await openai.models.list();
|
||||
return { valid: true };
|
||||
} catch (error: any) {
|
||||
console.error('API key test failed:', error);
|
||||
|
||||
// Determine the specific error type for better error messages
|
||||
let errorMessage = 'Unknown error validating API key';
|
||||
|
||||
if (error.status === 401) {
|
||||
errorMessage = 'Invalid API key. Please check your key and try again.';
|
||||
} else if (error.status === 429) {
|
||||
errorMessage = 'Rate limit exceeded. Your API key has reached its request limit or has insufficient quota.';
|
||||
} else if (error.status === 500) {
|
||||
errorMessage = 'OpenAI server error. Please try again later.';
|
||||
} else if (error.message) {
|
||||
errorMessage = `Error: ${error.message}`;
|
||||
}
|
||||
|
||||
return { valid: false, error: errorMessage };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Export a singleton instance
|
||||
export const configHelper = new ConfigHelper();
|
||||
@ -0,0 +1,780 @@
|
||||
// ProcessingHelper.ts
|
||||
import fs from "node:fs"
|
||||
import path from "node:path"
|
||||
import { ScreenshotHelper } from "./ScreenshotHelper"
|
||||
import { IProcessingHelperDeps } from "./main"
|
||||
import * as axios from "axios"
|
||||
import { app, BrowserWindow } from "electron"
|
||||
import { OpenAI } from "openai"
|
||||
import { configHelper } from "./ConfigHelper"
|
||||
|
||||
export class ProcessingHelper {
|
||||
private deps: IProcessingHelperDeps
|
||||
private screenshotHelper: ScreenshotHelper
|
||||
private openaiClient: OpenAI | null = null
|
||||
|
||||
// AbortControllers for API requests
|
||||
private currentProcessingAbortController: AbortController | null = null
|
||||
private currentExtraProcessingAbortController: AbortController | null = null
|
||||
|
||||
constructor(deps: IProcessingHelperDeps) {
|
||||
this.deps = deps
|
||||
this.screenshotHelper = deps.getScreenshotHelper()
|
||||
|
||||
// Initialize OpenAI client
|
||||
this.initializeOpenAIClient();
|
||||
|
||||
// Listen for config changes to re-initialize the OpenAI client
|
||||
configHelper.on('config-updated', () => {
|
||||
this.initializeOpenAIClient();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize or reinitialize the OpenAI client with current config
|
||||
*/
|
||||
private initializeOpenAIClient(): void {
|
||||
try {
|
||||
const config = configHelper.loadConfig();
|
||||
if (config.apiKey) {
|
||||
this.openaiClient = new OpenAI({
|
||||
apiKey: config.apiKey,
|
||||
timeout: 60000, // 60 second timeout
|
||||
maxRetries: 2 // Retry up to 2 times
|
||||
});
|
||||
console.log("OpenAI client initialized successfully");
|
||||
} else {
|
||||
this.openaiClient = null;
|
||||
console.warn("No API key available, OpenAI client not initialized");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to initialize OpenAI client:", error);
|
||||
this.openaiClient = null;
|
||||
}
|
||||
}
|
||||
|
||||
private async waitForInitialization(
|
||||
mainWindow: BrowserWindow
|
||||
): Promise<void> {
|
||||
let attempts = 0
|
||||
const maxAttempts = 50 // 5 seconds total
|
||||
|
||||
while (attempts < maxAttempts) {
|
||||
const isInitialized = await mainWindow.webContents.executeJavaScript(
|
||||
"window.__IS_INITIALIZED__"
|
||||
)
|
||||
if (isInitialized) return
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
attempts++
|
||||
}
|
||||
throw new Error("App failed to initialize after 5 seconds")
|
||||
}
|
||||
|
||||
private async getCredits(): Promise<number> {
|
||||
const mainWindow = this.deps.getMainWindow()
|
||||
if (!mainWindow) return 999 // Unlimited credits in this version
|
||||
|
||||
try {
|
||||
await this.waitForInitialization(mainWindow)
|
||||
return 999 // Always return sufficient credits to work
|
||||
} catch (error) {
|
||||
console.error("Error getting credits:", error)
|
||||
return 999 // Unlimited credits as fallback
|
||||
}
|
||||
}
|
||||
|
||||
private async getLanguage(): Promise<string> {
|
||||
try {
|
||||
// Get language from config
|
||||
const config = configHelper.loadConfig();
|
||||
if (config.language) {
|
||||
return config.language;
|
||||
}
|
||||
|
||||
// Fallback to window variable if config doesn't have language
|
||||
const mainWindow = this.deps.getMainWindow()
|
||||
if (mainWindow) {
|
||||
try {
|
||||
await this.waitForInitialization(mainWindow)
|
||||
const language = await mainWindow.webContents.executeJavaScript(
|
||||
"window.__LANGUAGE__"
|
||||
)
|
||||
|
||||
if (
|
||||
typeof language === "string" &&
|
||||
language !== undefined &&
|
||||
language !== null
|
||||
) {
|
||||
return language;
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Could not get language from window", err);
|
||||
}
|
||||
}
|
||||
|
||||
// Default fallback
|
||||
return "python";
|
||||
} catch (error) {
|
||||
console.error("Error getting language:", error)
|
||||
return "python"
|
||||
}
|
||||
}
|
||||
|
||||
public async processScreenshots(): Promise<void> {
|
||||
const mainWindow = this.deps.getMainWindow()
|
||||
if (!mainWindow) return
|
||||
|
||||
// First verify we have a valid OpenAI client
|
||||
if (!this.openaiClient) {
|
||||
this.initializeOpenAIClient();
|
||||
|
||||
if (!this.openaiClient) {
|
||||
console.error("OpenAI client not initialized");
|
||||
mainWindow.webContents.send(
|
||||
this.deps.PROCESSING_EVENTS.API_KEY_INVALID
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const view = this.deps.getView()
|
||||
console.log("Processing screenshots in view:", view)
|
||||
|
||||
if (view === "queue") {
|
||||
mainWindow.webContents.send(this.deps.PROCESSING_EVENTS.INITIAL_START)
|
||||
const screenshotQueue = this.screenshotHelper.getScreenshotQueue()
|
||||
console.log("Processing main queue screenshots:", screenshotQueue)
|
||||
if (screenshotQueue.length === 0) {
|
||||
mainWindow.webContents.send(this.deps.PROCESSING_EVENTS.NO_SCREENSHOTS)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
// Initialize AbortController
|
||||
this.currentProcessingAbortController = new AbortController()
|
||||
const { signal } = this.currentProcessingAbortController
|
||||
|
||||
const screenshots = await Promise.all(
|
||||
screenshotQueue.map(async (path) => ({
|
||||
path,
|
||||
preview: await this.screenshotHelper.getImagePreview(path),
|
||||
data: fs.readFileSync(path).toString('base64')
|
||||
}))
|
||||
)
|
||||
|
||||
const result = await this.processScreenshotsHelper(screenshots, signal)
|
||||
|
||||
if (!result.success) {
|
||||
console.log("Processing failed:", result.error)
|
||||
if (result.error?.includes("API Key") || result.error?.includes("OpenAI")) {
|
||||
mainWindow.webContents.send(
|
||||
this.deps.PROCESSING_EVENTS.API_KEY_INVALID
|
||||
)
|
||||
} else {
|
||||
mainWindow.webContents.send(
|
||||
this.deps.PROCESSING_EVENTS.INITIAL_SOLUTION_ERROR,
|
||||
result.error
|
||||
)
|
||||
}
|
||||
// Reset view back to queue on error
|
||||
console.log("Resetting view to queue due to error")
|
||||
this.deps.setView("queue")
|
||||
return
|
||||
}
|
||||
|
||||
// Only set view to solutions if processing succeeded
|
||||
console.log("Setting view to solutions after successful processing")
|
||||
mainWindow.webContents.send(
|
||||
this.deps.PROCESSING_EVENTS.SOLUTION_SUCCESS,
|
||||
result.data
|
||||
)
|
||||
this.deps.setView("solutions")
|
||||
} catch (error: any) {
|
||||
mainWindow.webContents.send(
|
||||
this.deps.PROCESSING_EVENTS.INITIAL_SOLUTION_ERROR,
|
||||
error
|
||||
)
|
||||
console.error("Processing error:", error)
|
||||
if (axios.isCancel(error)) {
|
||||
mainWindow.webContents.send(
|
||||
this.deps.PROCESSING_EVENTS.INITIAL_SOLUTION_ERROR,
|
||||
"Processing was canceled by the user."
|
||||
)
|
||||
} else {
|
||||
mainWindow.webContents.send(
|
||||
this.deps.PROCESSING_EVENTS.INITIAL_SOLUTION_ERROR,
|
||||
error.message || "Server error. Please try again."
|
||||
)
|
||||
}
|
||||
// Reset view back to queue on error
|
||||
console.log("Resetting view to queue due to error")
|
||||
this.deps.setView("queue")
|
||||
} finally {
|
||||
this.currentProcessingAbortController = null
|
||||
}
|
||||
} else {
|
||||
// view == 'solutions'
|
||||
const extraScreenshotQueue =
|
||||
this.screenshotHelper.getExtraScreenshotQueue()
|
||||
console.log("Processing extra queue screenshots:", extraScreenshotQueue)
|
||||
if (extraScreenshotQueue.length === 0) {
|
||||
mainWindow.webContents.send(this.deps.PROCESSING_EVENTS.NO_SCREENSHOTS)
|
||||
return
|
||||
}
|
||||
mainWindow.webContents.send(this.deps.PROCESSING_EVENTS.DEBUG_START)
|
||||
|
||||
// Initialize AbortController
|
||||
this.currentExtraProcessingAbortController = new AbortController()
|
||||
const { signal } = this.currentExtraProcessingAbortController
|
||||
|
||||
try {
|
||||
const screenshots = await Promise.all(
|
||||
[
|
||||
...this.screenshotHelper.getScreenshotQueue(),
|
||||
...extraScreenshotQueue
|
||||
].map(async (path) => ({
|
||||
path,
|
||||
preview: await this.screenshotHelper.getImagePreview(path),
|
||||
data: fs.readFileSync(path).toString('base64')
|
||||
}))
|
||||
)
|
||||
console.log(
|
||||
"Combined screenshots for processing:",
|
||||
screenshots.map((s) => s.path)
|
||||
)
|
||||
|
||||
const result = await this.processExtraScreenshotsHelper(
|
||||
screenshots,
|
||||
signal
|
||||
)
|
||||
|
||||
if (result.success) {
|
||||
this.deps.setHasDebugged(true)
|
||||
mainWindow.webContents.send(
|
||||
this.deps.PROCESSING_EVENTS.DEBUG_SUCCESS,
|
||||
result.data
|
||||
)
|
||||
} else {
|
||||
mainWindow.webContents.send(
|
||||
this.deps.PROCESSING_EVENTS.DEBUG_ERROR,
|
||||
result.error
|
||||
)
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (axios.isCancel(error)) {
|
||||
mainWindow.webContents.send(
|
||||
this.deps.PROCESSING_EVENTS.DEBUG_ERROR,
|
||||
"Extra processing was canceled by the user."
|
||||
)
|
||||
} else {
|
||||
mainWindow.webContents.send(
|
||||
this.deps.PROCESSING_EVENTS.DEBUG_ERROR,
|
||||
error.message
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
this.currentExtraProcessingAbortController = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async processScreenshotsHelper(
|
||||
screenshots: Array<{ path: string; data: string }>,
|
||||
signal: AbortSignal
|
||||
) {
|
||||
try {
|
||||
const config = configHelper.loadConfig();
|
||||
const language = await this.getLanguage();
|
||||
const mainWindow = this.deps.getMainWindow();
|
||||
|
||||
// Verify OpenAI client
|
||||
if (!this.openaiClient) {
|
||||
this.initializeOpenAIClient(); // Try to reinitialize
|
||||
|
||||
if (!this.openaiClient) {
|
||||
return {
|
||||
success: false,
|
||||
error: "OpenAI API key not configured or invalid. Please check your settings."
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Step 1: Extract problem info using OpenAI Vision API
|
||||
const imageDataList = screenshots.map(screenshot => screenshot.data);
|
||||
|
||||
// Update the user on progress
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send("processing-status", {
|
||||
message: "Analyzing problem from screenshots...",
|
||||
progress: 20
|
||||
});
|
||||
}
|
||||
|
||||
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."
|
||||
},
|
||||
{
|
||||
role: "user" as const,
|
||||
content: [
|
||||
{
|
||||
type: "text" as const,
|
||||
text: `Extract the coding problem details from these screenshots. Return in JSON format. Preferred coding language we gonna use for this problem is ${language}.`
|
||||
},
|
||||
...imageDataList.map(data => ({
|
||||
type: "image_url" as const,
|
||||
image_url: { url: `data:image/png;base64,${data}` }
|
||||
}))
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
// Send to OpenAI Vision API
|
||||
const extractionResponse = await this.openaiClient.chat.completions.create({
|
||||
model: config.extractionModel || "gpt-4o",
|
||||
messages: messages,
|
||||
max_tokens: 4000,
|
||||
temperature: 0.2
|
||||
});
|
||||
|
||||
// Parse the response to get structured problem info
|
||||
let problemInfo;
|
||||
try {
|
||||
const responseText = extractionResponse.choices[0].message.content;
|
||||
// Handle when OpenAI might wrap the JSON in markdown code blocks
|
||||
const jsonText = responseText.replace(/```json|```/g, '').trim();
|
||||
problemInfo = JSON.parse(jsonText);
|
||||
|
||||
// Update the user on progress
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send("processing-status", {
|
||||
message: "Problem analyzed successfully. Preparing to generate solution...",
|
||||
progress: 40
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error parsing problem extraction response:", error);
|
||||
console.log("Raw response:", extractionResponse.choices[0].message.content);
|
||||
return {
|
||||
success: false,
|
||||
error: "Failed to parse problem information. Please try again or use clearer screenshots."
|
||||
};
|
||||
}
|
||||
|
||||
// Store problem info in AppState
|
||||
this.deps.setProblemInfo(problemInfo);
|
||||
|
||||
// Send first success event
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send(
|
||||
this.deps.PROCESSING_EVENTS.PROBLEM_EXTRACTED,
|
||||
problemInfo
|
||||
);
|
||||
|
||||
// Generate solutions after successful extraction
|
||||
const solutionsResult = await this.generateSolutionsHelper(signal);
|
||||
if (solutionsResult.success) {
|
||||
// Clear any existing extra screenshots before transitioning to solutions view
|
||||
this.screenshotHelper.clearExtraScreenshotQueue();
|
||||
|
||||
// Final progress update
|
||||
mainWindow.webContents.send("processing-status", {
|
||||
message: "Solution generated successfully",
|
||||
progress: 100
|
||||
});
|
||||
|
||||
mainWindow.webContents.send(
|
||||
this.deps.PROCESSING_EVENTS.SOLUTION_SUCCESS,
|
||||
solutionsResult.data
|
||||
);
|
||||
return { success: true, data: solutionsResult.data };
|
||||
} else {
|
||||
throw new Error(
|
||||
solutionsResult.error || "Failed to generate solutions"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return { success: false, error: "Failed to process screenshots" };
|
||||
} catch (error: any) {
|
||||
// If the request was cancelled, don't retry
|
||||
if (axios.isCancel(error)) {
|
||||
return {
|
||||
success: false,
|
||||
error: "Processing was canceled by the user."
|
||||
};
|
||||
}
|
||||
|
||||
// Handle OpenAI API errors specifically
|
||||
if (error?.response?.status === 401) {
|
||||
return {
|
||||
success: false,
|
||||
error: "Invalid OpenAI API key. Please check your settings."
|
||||
};
|
||||
} else if (error?.response?.status === 429) {
|
||||
return {
|
||||
success: false,
|
||||
error: "OpenAI API rate limit exceeded or insufficient credits. Please try again later."
|
||||
};
|
||||
} else if (error?.response?.status === 500) {
|
||||
return {
|
||||
success: false,
|
||||
error: "OpenAI server error. Please try again later."
|
||||
};
|
||||
}
|
||||
|
||||
console.error("API Error Details:", error);
|
||||
return {
|
||||
success: false,
|
||||
error: error.message || "Failed to process screenshots. Please try again."
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private async generateSolutionsHelper(signal: AbortSignal) {
|
||||
try {
|
||||
const problemInfo = this.deps.getProblemInfo();
|
||||
const language = await this.getLanguage();
|
||||
const config = configHelper.loadConfig();
|
||||
const mainWindow = this.deps.getMainWindow();
|
||||
|
||||
if (!problemInfo) {
|
||||
throw new Error("No problem info available");
|
||||
}
|
||||
|
||||
if (!this.openaiClient) {
|
||||
return {
|
||||
success: false,
|
||||
error: "OpenAI API key not configured. Please check your settings."
|
||||
};
|
||||
}
|
||||
|
||||
// Update progress status
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send("processing-status", {
|
||||
message: "Creating optimal solution with detailed explanations...",
|
||||
progress: 60
|
||||
});
|
||||
}
|
||||
|
||||
// Create prompt for solution generation
|
||||
const promptText = `
|
||||
Generate a detailed solution for the following coding problem:
|
||||
|
||||
PROBLEM STATEMENT:
|
||||
${problemInfo.problem_statement}
|
||||
|
||||
CONSTRAINTS:
|
||||
${problemInfo.constraints || "No specific constraints provided."}
|
||||
|
||||
EXAMPLE INPUT:
|
||||
${problemInfo.example_input || "No example input provided."}
|
||||
|
||||
EXAMPLE OUTPUT:
|
||||
${problemInfo.example_output || "No example output provided."}
|
||||
|
||||
LANGUAGE: ${language}
|
||||
|
||||
I need the response in the following format:
|
||||
1. Code: A clean, optimized implementation in ${language}
|
||||
2. Your Thoughts: A list of key insights and reasoning behind your approach
|
||||
3. Time complexity: O(X) with a detailed explanation (at least 2 sentences)
|
||||
4. Space complexity: O(X) with a detailed explanation (at least 2 sentences)
|
||||
|
||||
For complexity explanations, please be thorough. For example: "Time complexity: O(n) because we iterate through the array only once. This is optimal as we need to examine each element at least once to find the solution." or "Space complexity: O(n) because in the worst case, we store all elements in the hashmap. The additional space scales linearly with the input size."
|
||||
|
||||
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", // Using selected model for code generation
|
||||
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
|
||||
});
|
||||
|
||||
const responseContent = solutionResponse.choices[0].message.content;
|
||||
|
||||
// Extract parts from the response
|
||||
const codeMatch = responseContent.match(/```(?:\w+)?\s*([\s\S]*?)```/);
|
||||
const code = codeMatch ? codeMatch[1].trim() : responseContent;
|
||||
|
||||
// Extract thoughts, looking for bullet points or numbered lists
|
||||
const thoughtsRegex = /(?:Thoughts:|Key Insights:|Reasoning:|Approach:)([\s\S]*?)(?:Time complexity:|$)/i;
|
||||
const thoughtsMatch = responseContent.match(thoughtsRegex);
|
||||
let thoughts: string[] = [];
|
||||
|
||||
if (thoughtsMatch && thoughtsMatch[1]) {
|
||||
// Extract bullet points or numbered items
|
||||
const bulletPoints = thoughtsMatch[1].match(/(?:^|\n)\s*(?:[-*•]|\d+\.)\s*(.*)/g);
|
||||
if (bulletPoints) {
|
||||
thoughts = bulletPoints.map(point =>
|
||||
point.replace(/^\s*(?:[-*•]|\d+\.)\s*/, '').trim()
|
||||
).filter(Boolean);
|
||||
} else {
|
||||
// If no bullet points found, split by newlines and filter empty lines
|
||||
thoughts = thoughtsMatch[1].split('\n')
|
||||
.map(line => line.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
}
|
||||
|
||||
// Extract complexity information
|
||||
// Use more flexible patterns to find complexity sections
|
||||
const timeComplexityPattern = /Time complexity:?\s*([^\n]+(?:\n[^\n]+)*?)(?=\n\s*(?:Space complexity|$))/i;
|
||||
const spaceComplexityPattern = /Space complexity:?\s*([^\n]+(?:\n[^\n]+)*?)(?=\n\s*(?:[A-Z]|$))/i;
|
||||
|
||||
let timeComplexity = "O(n) - Linear time complexity because we only iterate through the array once. Each element is processed exactly one time, and the hashmap lookups are O(1) operations.";
|
||||
let spaceComplexity = "O(n) - Linear space complexity because we store elements in the hashmap. In the worst case, we might need to store all elements before finding the solution pair.";
|
||||
|
||||
// Extract time complexity with better matching
|
||||
const timeMatch = responseContent.match(timeComplexityPattern);
|
||||
if (timeMatch && timeMatch[1]) {
|
||||
timeComplexity = timeMatch[1].trim();
|
||||
// Ensure the response includes actual Big O notation and a dash
|
||||
if (!timeComplexity.match(/O\([^)]+\)/i)) {
|
||||
timeComplexity = `O(n) - ${timeComplexity}`;
|
||||
} else if (!timeComplexity.includes('-') && !timeComplexity.includes('because')) {
|
||||
// Add a dash if there isn't one and no 'because'
|
||||
const notationMatch = timeComplexity.match(/O\([^)]+\)/i);
|
||||
if (notationMatch) {
|
||||
const notation = notationMatch[0];
|
||||
const rest = timeComplexity.replace(notation, '').trim();
|
||||
timeComplexity = `${notation} - ${rest}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extract space complexity with better matching
|
||||
const spaceMatch = responseContent.match(spaceComplexityPattern);
|
||||
if (spaceMatch && spaceMatch[1]) {
|
||||
spaceComplexity = spaceMatch[1].trim();
|
||||
// Ensure the response includes actual Big O notation and a dash
|
||||
if (!spaceComplexity.match(/O\([^)]+\)/i)) {
|
||||
spaceComplexity = `O(n) - ${spaceComplexity}`;
|
||||
} else if (!spaceComplexity.includes('-') && !spaceComplexity.includes('because')) {
|
||||
// Add a dash if there isn't one and no 'because'
|
||||
const notationMatch = spaceComplexity.match(/O\([^)]+\)/i);
|
||||
if (notationMatch) {
|
||||
const notation = notationMatch[0];
|
||||
const rest = spaceComplexity.replace(notation, '').trim();
|
||||
spaceComplexity = `${notation} - ${rest}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Construct the formatted response
|
||||
const formattedResponse = {
|
||||
code: code,
|
||||
thoughts: thoughts.length > 0 ? thoughts : ["Solution approach based on efficiency and readability"],
|
||||
time_complexity: timeComplexity,
|
||||
space_complexity: spaceComplexity
|
||||
};
|
||||
|
||||
return { success: true, data: formattedResponse };
|
||||
} catch (error: any) {
|
||||
// Handle OpenAI API errors specifically
|
||||
if (error?.response?.status === 401) {
|
||||
return {
|
||||
success: false,
|
||||
error: "Invalid OpenAI API key. Please check your settings."
|
||||
};
|
||||
} else if (error?.response?.status === 429) {
|
||||
return {
|
||||
success: false,
|
||||
error: "OpenAI API rate limit exceeded or insufficient credits. Please try again later."
|
||||
};
|
||||
}
|
||||
|
||||
console.error("Solution generation error:", error);
|
||||
return { success: false, error: error.message || "Failed to generate solution" };
|
||||
}
|
||||
}
|
||||
|
||||
private async processExtraScreenshotsHelper(
|
||||
screenshots: Array<{ path: string; data: string }>,
|
||||
signal: AbortSignal
|
||||
) {
|
||||
try {
|
||||
const problemInfo = this.deps.getProblemInfo();
|
||||
const language = await this.getLanguage();
|
||||
const config = configHelper.loadConfig();
|
||||
const mainWindow = this.deps.getMainWindow();
|
||||
|
||||
if (!problemInfo) {
|
||||
throw new Error("No problem info available");
|
||||
}
|
||||
|
||||
if (!this.openaiClient) {
|
||||
return {
|
||||
success: false,
|
||||
error: "OpenAI API key not configured. Please check your settings."
|
||||
};
|
||||
}
|
||||
|
||||
// Update progress status
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send("processing-status", {
|
||||
message: "Processing debug screenshots...",
|
||||
progress: 30
|
||||
});
|
||||
}
|
||||
|
||||
// Prepare the images for the API call
|
||||
const imageDataList = screenshots.map(screenshot => screenshot.data);
|
||||
const messages = [
|
||||
{
|
||||
role: "system" as const,
|
||||
content: `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.
|
||||
|
||||
Your response MUST follow this exact structure with these section headers (use ### for headers):
|
||||
### Issues Identified
|
||||
- List each issue as a bullet point with clear explanation
|
||||
|
||||
### Specific Improvements and Corrections
|
||||
- List specific code changes needed as bullet points
|
||||
|
||||
### Optimizations
|
||||
- List any performance optimizations if applicable
|
||||
|
||||
### Explanation of Changes Needed
|
||||
Here provide a clear explanation of why the changes are needed
|
||||
|
||||
### Key Points
|
||||
- Summary bullet points of the most important takeaways
|
||||
|
||||
If you include code examples, use proper markdown code blocks with language specification (e.g. \`\`\`java).`
|
||||
},
|
||||
{
|
||||
role: "user" as const,
|
||||
content: [
|
||||
{
|
||||
type: "text" as const,
|
||||
text: `I'm solving this coding problem: "${problemInfo.problem_statement}" in ${language}. I need help with debugging or improving my solution. Here are screenshots of my code, the errors or test cases. Please provide a detailed analysis with:
|
||||
1. What issues you found in my code
|
||||
2. Specific improvements and corrections
|
||||
3. Any optimizations that would make the solution better
|
||||
4. A clear explanation of the changes needed`
|
||||
},
|
||||
...imageDataList.map(data => ({
|
||||
type: "image_url" as const,
|
||||
image_url: { url: `data:image/png;base64,${data}` }
|
||||
}))
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
// Update progress
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send("processing-status", {
|
||||
message: "Analyzing code and generating debug feedback...",
|
||||
progress: 60
|
||||
});
|
||||
}
|
||||
|
||||
// Send to OpenAI Vision API
|
||||
const debugResponse = await this.openaiClient.chat.completions.create({
|
||||
model: config.debuggingModel || "gpt-4o",
|
||||
messages: messages,
|
||||
max_tokens: 4000,
|
||||
temperature: 0.2
|
||||
});
|
||||
|
||||
// Update final progress
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send("processing-status", {
|
||||
message: "Debug analysis complete",
|
||||
progress: 100
|
||||
});
|
||||
}
|
||||
|
||||
// Extract and format the debug response
|
||||
const debugContent = debugResponse.choices[0].message.content;
|
||||
|
||||
// Extract code if there's code block in the response
|
||||
let extractedCode = "// Debug mode - see analysis below";
|
||||
const codeMatch = debugContent.match(/```(?:[a-zA-Z]+)?([\s\S]*?)```/);
|
||||
if (codeMatch && codeMatch[1]) {
|
||||
extractedCode = codeMatch[1].trim();
|
||||
}
|
||||
|
||||
// Format the debug content for better display - add clear section headings
|
||||
let formattedDebugContent = debugContent;
|
||||
|
||||
// Ensure proper section formatting
|
||||
if (!debugContent.includes('# ') && !debugContent.includes('## ')) {
|
||||
formattedDebugContent = debugContent
|
||||
.replace(/issues identified|problems found|bugs found/i, '## Issues Identified')
|
||||
.replace(/code improvements|improvements|suggested changes/i, '## Code Improvements')
|
||||
.replace(/optimizations|performance improvements/i, '## Optimizations')
|
||||
.replace(/explanation|detailed analysis/i, '## Explanation');
|
||||
}
|
||||
|
||||
// Try to extract bullet points for "thoughts"
|
||||
const bulletPoints = formattedDebugContent.match(/(?:^|\n)[ ]*(?:[-*•]|\d+\.)[ ]+([^\n]+)/g);
|
||||
const thoughts = bulletPoints
|
||||
? bulletPoints.map(point => point.replace(/^[ ]*(?:[-*•]|\d+\.)[ ]+/, '').trim()).slice(0, 5)
|
||||
: ["Debug analysis based on your screenshots"];
|
||||
|
||||
// Return the debug assistance in the format expected by the app
|
||||
const response = {
|
||||
code: extractedCode,
|
||||
debug_analysis: formattedDebugContent,
|
||||
thoughts: thoughts,
|
||||
time_complexity: "N/A - Debug mode",
|
||||
space_complexity: "N/A - Debug mode"
|
||||
};
|
||||
|
||||
return { success: true, data: response };
|
||||
} catch (error: any) {
|
||||
// Handle OpenAI API errors specifically
|
||||
if (error?.response?.status === 401) {
|
||||
return {
|
||||
success: false,
|
||||
error: "Invalid OpenAI API key. Please check your settings."
|
||||
};
|
||||
} else if (error?.response?.status === 429) {
|
||||
return {
|
||||
success: false,
|
||||
error: "OpenAI API rate limit exceeded or insufficient credits. Please try again later."
|
||||
};
|
||||
}
|
||||
|
||||
console.error("Debug processing error:", error);
|
||||
return { success: false, error: error.message || "Failed to process debug request" };
|
||||
}
|
||||
}
|
||||
|
||||
public cancelOngoingRequests(): void {
|
||||
let wasCancelled = false
|
||||
|
||||
if (this.currentProcessingAbortController) {
|
||||
this.currentProcessingAbortController.abort()
|
||||
this.currentProcessingAbortController = null
|
||||
wasCancelled = true
|
||||
}
|
||||
|
||||
if (this.currentExtraProcessingAbortController) {
|
||||
this.currentExtraProcessingAbortController.abort()
|
||||
this.currentExtraProcessingAbortController = null
|
||||
wasCancelled = true
|
||||
}
|
||||
|
||||
// Reset hasDebugged flag
|
||||
this.deps.setHasDebugged(false)
|
||||
|
||||
// Clear any pending state
|
||||
this.deps.setProblemInfo(null)
|
||||
|
||||
const mainWindow = this.deps.getMainWindow()
|
||||
if (wasCancelled && mainWindow && !mainWindow.isDestroyed()) {
|
||||
// Send a clear message that processing was cancelled
|
||||
mainWindow.webContents.send(this.deps.PROCESSING_EVENTS.NO_SCREENSHOTS)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,221 @@
|
||||
// ScreenshotHelper.ts
|
||||
|
||||
import path from "node:path"
|
||||
import fs from "node:fs"
|
||||
import { app } from "electron"
|
||||
import { v4 as uuidv4 } from "uuid"
|
||||
import { execFile } from "child_process"
|
||||
import { promisify } from "util"
|
||||
import screenshot from "screenshot-desktop"
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
export class ScreenshotHelper {
|
||||
private screenshotQueue: string[] = []
|
||||
private extraScreenshotQueue: string[] = []
|
||||
private readonly MAX_SCREENSHOTS = 5
|
||||
|
||||
private readonly screenshotDir: string
|
||||
private readonly extraScreenshotDir: string
|
||||
|
||||
private view: "queue" | "solutions" | "debug" = "queue"
|
||||
|
||||
constructor(view: "queue" | "solutions" | "debug" = "queue") {
|
||||
this.view = view
|
||||
|
||||
// Initialize directories
|
||||
this.screenshotDir = path.join(app.getPath("userData"), "screenshots")
|
||||
this.extraScreenshotDir = path.join(
|
||||
app.getPath("userData"),
|
||||
"extra_screenshots"
|
||||
)
|
||||
|
||||
// Create directories if they don't exist
|
||||
if (!fs.existsSync(this.screenshotDir)) {
|
||||
fs.mkdirSync(this.screenshotDir, { recursive: true })
|
||||
}
|
||||
if (!fs.existsSync(this.extraScreenshotDir)) {
|
||||
fs.mkdirSync(this.extraScreenshotDir, { recursive: true })
|
||||
}
|
||||
|
||||
// Ensure temp directory exists
|
||||
const tempDir = app.getPath("temp")
|
||||
if (!fs.existsSync(tempDir)) {
|
||||
fs.mkdirSync(tempDir, { recursive: true })
|
||||
}
|
||||
}
|
||||
|
||||
public getView(): "queue" | "solutions" | "debug" {
|
||||
return this.view
|
||||
}
|
||||
|
||||
public setView(view: "queue" | "solutions" | "debug"): void {
|
||||
console.log("Setting view in ScreenshotHelper:", view)
|
||||
console.log(
|
||||
"Current queues - Main:",
|
||||
this.screenshotQueue,
|
||||
"Extra:",
|
||||
this.extraScreenshotQueue
|
||||
)
|
||||
this.view = view
|
||||
}
|
||||
|
||||
public getScreenshotQueue(): string[] {
|
||||
return this.screenshotQueue
|
||||
}
|
||||
|
||||
public getExtraScreenshotQueue(): string[] {
|
||||
console.log("Getting extra screenshot queue:", this.extraScreenshotQueue)
|
||||
return this.extraScreenshotQueue
|
||||
}
|
||||
|
||||
public clearQueues(): void {
|
||||
// Clear screenshotQueue
|
||||
this.screenshotQueue.forEach((screenshotPath) => {
|
||||
fs.unlink(screenshotPath, (err) => {
|
||||
if (err)
|
||||
console.error(`Error deleting screenshot at ${screenshotPath}:`, err)
|
||||
})
|
||||
})
|
||||
this.screenshotQueue = []
|
||||
|
||||
// Clear extraScreenshotQueue
|
||||
this.extraScreenshotQueue.forEach((screenshotPath) => {
|
||||
fs.unlink(screenshotPath, (err) => {
|
||||
if (err)
|
||||
console.error(
|
||||
`Error deleting extra screenshot at ${screenshotPath}:`,
|
||||
err
|
||||
)
|
||||
})
|
||||
})
|
||||
this.extraScreenshotQueue = []
|
||||
}
|
||||
|
||||
private async captureScreenshot(): Promise<Buffer> {
|
||||
try {
|
||||
// Ensure temp directory exists
|
||||
const tempDir = app.getPath("temp")
|
||||
if (!fs.existsSync(tempDir)) {
|
||||
fs.mkdirSync(tempDir, { recursive: true })
|
||||
}
|
||||
|
||||
// Use screenshot-desktop for cross-platform support
|
||||
const buffer = await screenshot({ format: 'png' });
|
||||
return buffer;
|
||||
} catch (error) {
|
||||
console.error("Error capturing screenshot:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async takeScreenshot(
|
||||
hideMainWindow: () => void,
|
||||
showMainWindow: () => void
|
||||
): Promise<string> {
|
||||
console.log("Taking screenshot in view:", this.view)
|
||||
hideMainWindow()
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
|
||||
let screenshotPath = ""
|
||||
try {
|
||||
// Get screenshot buffer using cross-platform method
|
||||
const screenshotBuffer = await this.captureScreenshot();
|
||||
|
||||
// Save and manage the screenshot based on current view
|
||||
if (this.view === "queue") {
|
||||
screenshotPath = path.join(this.screenshotDir, `${uuidv4()}.png`)
|
||||
await fs.promises.writeFile(screenshotPath, screenshotBuffer)
|
||||
console.log("Adding screenshot to main queue:", screenshotPath)
|
||||
this.screenshotQueue.push(screenshotPath)
|
||||
if (this.screenshotQueue.length > this.MAX_SCREENSHOTS) {
|
||||
const removedPath = this.screenshotQueue.shift()
|
||||
if (removedPath) {
|
||||
try {
|
||||
await fs.promises.unlink(removedPath)
|
||||
console.log(
|
||||
"Removed old screenshot from main queue:",
|
||||
removedPath
|
||||
)
|
||||
} catch (error) {
|
||||
console.error("Error removing old screenshot:", error)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// In solutions view, only add to extra queue
|
||||
screenshotPath = path.join(this.extraScreenshotDir, `${uuidv4()}.png`)
|
||||
await fs.promises.writeFile(screenshotPath, screenshotBuffer)
|
||||
console.log("Adding screenshot to extra queue:", screenshotPath)
|
||||
this.extraScreenshotQueue.push(screenshotPath)
|
||||
if (this.extraScreenshotQueue.length > this.MAX_SCREENSHOTS) {
|
||||
const removedPath = this.extraScreenshotQueue.shift()
|
||||
if (removedPath) {
|
||||
try {
|
||||
await fs.promises.unlink(removedPath)
|
||||
console.log(
|
||||
"Removed old screenshot from extra queue:",
|
||||
removedPath
|
||||
)
|
||||
} catch (error) {
|
||||
console.error("Error removing old screenshot:", error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Screenshot error:", error)
|
||||
throw error
|
||||
} finally {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
showMainWindow()
|
||||
}
|
||||
|
||||
return screenshotPath
|
||||
}
|
||||
|
||||
public async getImagePreview(filepath: string): Promise<string> {
|
||||
try {
|
||||
const data = await fs.promises.readFile(filepath)
|
||||
return `data:image/png;base64,${data.toString("base64")}`
|
||||
} catch (error) {
|
||||
console.error("Error reading image:", error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
public async deleteScreenshot(
|
||||
path: string
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
try {
|
||||
await fs.promises.unlink(path)
|
||||
if (this.view === "queue") {
|
||||
this.screenshotQueue = this.screenshotQueue.filter(
|
||||
(filePath) => filePath !== path
|
||||
)
|
||||
} else {
|
||||
this.extraScreenshotQueue = this.extraScreenshotQueue.filter(
|
||||
(filePath) => filePath !== path
|
||||
)
|
||||
}
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
console.error("Error deleting file:", error)
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
}
|
||||
|
||||
public clearExtraScreenshotQueue(): void {
|
||||
// Clear extraScreenshotQueue
|
||||
this.extraScreenshotQueue.forEach((screenshotPath) => {
|
||||
fs.unlink(screenshotPath, (err) => {
|
||||
if (err)
|
||||
console.error(
|
||||
`Error deleting extra screenshot at ${screenshotPath}:`,
|
||||
err
|
||||
)
|
||||
})
|
||||
})
|
||||
this.extraScreenshotQueue = []
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,109 @@
|
||||
import { autoUpdater } from "electron-updater"
|
||||
import { BrowserWindow, ipcMain, app } from "electron"
|
||||
import log from "electron-log"
|
||||
|
||||
export function initAutoUpdater() {
|
||||
console.log("Initializing auto-updater...")
|
||||
|
||||
// Skip update checks in development
|
||||
if (!app.isPackaged) {
|
||||
console.log("Skipping auto-updater in development mode")
|
||||
return
|
||||
}
|
||||
|
||||
if (!process.env.GH_TOKEN) {
|
||||
console.error("GH_TOKEN environment variable is not set")
|
||||
return
|
||||
}
|
||||
|
||||
// Configure auto updater
|
||||
autoUpdater.autoDownload = true
|
||||
autoUpdater.autoInstallOnAppQuit = true
|
||||
autoUpdater.allowDowngrade = true
|
||||
autoUpdater.allowPrerelease = true
|
||||
|
||||
// Enable more verbose logging
|
||||
autoUpdater.logger = log
|
||||
log.transports.file.level = "debug"
|
||||
console.log(
|
||||
"Auto-updater logger configured with level:",
|
||||
log.transports.file.level
|
||||
)
|
||||
|
||||
// Log all update events
|
||||
autoUpdater.on("checking-for-update", () => {
|
||||
console.log("Checking for updates...")
|
||||
})
|
||||
|
||||
autoUpdater.on("update-available", (info) => {
|
||||
console.log("Update available:", info)
|
||||
// Notify renderer process about available update
|
||||
BrowserWindow.getAllWindows().forEach((window) => {
|
||||
console.log("Sending update-available to window")
|
||||
window.webContents.send("update-available", info)
|
||||
})
|
||||
})
|
||||
|
||||
autoUpdater.on("update-not-available", (info) => {
|
||||
console.log("Update not available:", info)
|
||||
})
|
||||
|
||||
autoUpdater.on("download-progress", (progressObj) => {
|
||||
console.log("Download progress:", progressObj)
|
||||
})
|
||||
|
||||
autoUpdater.on("update-downloaded", (info) => {
|
||||
console.log("Update downloaded:", info)
|
||||
// Notify renderer process that update is ready to install
|
||||
BrowserWindow.getAllWindows().forEach((window) => {
|
||||
console.log("Sending update-downloaded to window")
|
||||
window.webContents.send("update-downloaded", info)
|
||||
})
|
||||
})
|
||||
|
||||
autoUpdater.on("error", (err) => {
|
||||
console.error("Auto updater error:", err)
|
||||
})
|
||||
|
||||
// Check for updates immediately
|
||||
console.log("Checking for updates...")
|
||||
autoUpdater
|
||||
.checkForUpdates()
|
||||
.then((result) => {
|
||||
console.log("Update check result:", result)
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error("Error checking for updates:", err)
|
||||
})
|
||||
|
||||
// Set up update checking interval (every 1 hour)
|
||||
setInterval(() => {
|
||||
console.log("Checking for updates (interval)...")
|
||||
autoUpdater
|
||||
.checkForUpdates()
|
||||
.then((result) => {
|
||||
console.log("Update check result (interval):", result)
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error("Error checking for updates (interval):", err)
|
||||
})
|
||||
}, 60 * 60 * 1000)
|
||||
|
||||
// Handle IPC messages from renderer
|
||||
ipcMain.handle("start-update", async () => {
|
||||
console.log("Start update requested")
|
||||
try {
|
||||
await autoUpdater.downloadUpdate()
|
||||
console.log("Update download completed")
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
console.error("Failed to start update:", error)
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle("install-update", () => {
|
||||
console.log("Install update requested")
|
||||
autoUpdater.quitAndInstall()
|
||||
})
|
||||
}
|
||||
@ -0,0 +1,351 @@
|
||||
// ipcHandlers.ts
|
||||
|
||||
import { ipcMain, shell, dialog } from "electron"
|
||||
import { randomBytes } from "crypto"
|
||||
import { IIpcHandlerDeps } from "./main"
|
||||
import { configHelper } from "./ConfigHelper"
|
||||
|
||||
export function initializeIpcHandlers(deps: IIpcHandlerDeps): void {
|
||||
console.log("Initializing IPC handlers")
|
||||
|
||||
// Configuration handlers
|
||||
ipcMain.handle("get-config", () => {
|
||||
return configHelper.loadConfig();
|
||||
})
|
||||
|
||||
ipcMain.handle("update-config", (_event, updates) => {
|
||||
return configHelper.updateConfig(updates);
|
||||
})
|
||||
|
||||
ipcMain.handle("check-api-key", () => {
|
||||
return configHelper.hasApiKey();
|
||||
})
|
||||
|
||||
ipcMain.handle("validate-api-key", async (_event, apiKey) => {
|
||||
// First check the format
|
||||
if (!configHelper.isValidApiKeyFormat(apiKey)) {
|
||||
return {
|
||||
valid: false,
|
||||
error: "Invalid API key format. OpenAI API keys start with 'sk-'"
|
||||
};
|
||||
}
|
||||
|
||||
// Then test the API key with OpenAI
|
||||
const result = await configHelper.testApiKey(apiKey);
|
||||
return result;
|
||||
})
|
||||
|
||||
// Credits handlers
|
||||
ipcMain.handle("set-initial-credits", async (_event, credits: number) => {
|
||||
const mainWindow = deps.getMainWindow()
|
||||
if (!mainWindow) return
|
||||
|
||||
try {
|
||||
// Set the credits in a way that ensures atomicity
|
||||
await mainWindow.webContents.executeJavaScript(
|
||||
`window.__CREDITS__ = ${credits}`
|
||||
)
|
||||
mainWindow.webContents.send("credits-updated", credits)
|
||||
} catch (error) {
|
||||
console.error("Error setting initial credits:", error)
|
||||
throw error
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle("decrement-credits", async () => {
|
||||
const mainWindow = deps.getMainWindow()
|
||||
if (!mainWindow) return
|
||||
|
||||
try {
|
||||
const currentCredits = await mainWindow.webContents.executeJavaScript(
|
||||
"window.__CREDITS__"
|
||||
)
|
||||
if (currentCredits > 0) {
|
||||
const newCredits = currentCredits - 1
|
||||
await mainWindow.webContents.executeJavaScript(
|
||||
`window.__CREDITS__ = ${newCredits}`
|
||||
)
|
||||
mainWindow.webContents.send("credits-updated", newCredits)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error decrementing credits:", error)
|
||||
}
|
||||
})
|
||||
|
||||
// Screenshot queue handlers
|
||||
ipcMain.handle("get-screenshot-queue", () => {
|
||||
return deps.getScreenshotQueue()
|
||||
})
|
||||
|
||||
ipcMain.handle("get-extra-screenshot-queue", () => {
|
||||
return deps.getExtraScreenshotQueue()
|
||||
})
|
||||
|
||||
ipcMain.handle("delete-screenshot", async (event, path: string) => {
|
||||
return deps.deleteScreenshot(path)
|
||||
})
|
||||
|
||||
ipcMain.handle("get-image-preview", async (event, path: string) => {
|
||||
return deps.getImagePreview(path)
|
||||
})
|
||||
|
||||
// Screenshot processing handlers
|
||||
ipcMain.handle("process-screenshots", async () => {
|
||||
// Check for API key before processing
|
||||
if (!configHelper.hasApiKey()) {
|
||||
const mainWindow = deps.getMainWindow();
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send(deps.PROCESSING_EVENTS.API_KEY_INVALID);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
await deps.processingHelper?.processScreenshots()
|
||||
})
|
||||
|
||||
// Window dimension handlers
|
||||
ipcMain.handle(
|
||||
"update-content-dimensions",
|
||||
async (event, { width, height }: { width: number; height: number }) => {
|
||||
if (width && height) {
|
||||
deps.setWindowDimensions(width, height)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
"set-window-dimensions",
|
||||
(event, width: number, height: number) => {
|
||||
deps.setWindowDimensions(width, height)
|
||||
}
|
||||
)
|
||||
|
||||
// Screenshot management handlers
|
||||
ipcMain.handle("get-screenshots", async () => {
|
||||
try {
|
||||
let previews = []
|
||||
const currentView = deps.getView()
|
||||
|
||||
if (currentView === "queue") {
|
||||
const queue = deps.getScreenshotQueue()
|
||||
previews = await Promise.all(
|
||||
queue.map(async (path) => ({
|
||||
path,
|
||||
preview: await deps.getImagePreview(path)
|
||||
}))
|
||||
)
|
||||
} else {
|
||||
const extraQueue = deps.getExtraScreenshotQueue()
|
||||
previews = await Promise.all(
|
||||
extraQueue.map(async (path) => ({
|
||||
path,
|
||||
preview: await deps.getImagePreview(path)
|
||||
}))
|
||||
)
|
||||
}
|
||||
|
||||
return previews
|
||||
} catch (error) {
|
||||
console.error("Error getting screenshots:", error)
|
||||
throw error
|
||||
}
|
||||
})
|
||||
|
||||
// Screenshot trigger handlers
|
||||
ipcMain.handle("trigger-screenshot", async () => {
|
||||
const mainWindow = deps.getMainWindow()
|
||||
if (mainWindow) {
|
||||
try {
|
||||
const screenshotPath = await deps.takeScreenshot()
|
||||
const preview = await deps.getImagePreview(screenshotPath)
|
||||
mainWindow.webContents.send("screenshot-taken", {
|
||||
path: screenshotPath,
|
||||
preview
|
||||
})
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
console.error("Error triggering screenshot:", error)
|
||||
return { error: "Failed to trigger screenshot" }
|
||||
}
|
||||
}
|
||||
return { error: "No main window available" }
|
||||
})
|
||||
|
||||
ipcMain.handle("take-screenshot", async () => {
|
||||
try {
|
||||
const screenshotPath = await deps.takeScreenshot()
|
||||
const preview = await deps.getImagePreview(screenshotPath)
|
||||
return { path: screenshotPath, preview }
|
||||
} catch (error) {
|
||||
console.error("Error taking screenshot:", error)
|
||||
return { error: "Failed to take screenshot" }
|
||||
}
|
||||
})
|
||||
|
||||
// Auth-related handlers removed
|
||||
|
||||
ipcMain.handle("open-external-url", (event, url: string) => {
|
||||
shell.openExternal(url)
|
||||
})
|
||||
|
||||
// Open external URL handler
|
||||
ipcMain.handle("openLink", (event, url: string) => {
|
||||
try {
|
||||
console.log(`Opening external URL: ${url}`);
|
||||
shell.openExternal(url);
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error(`Error opening URL ${url}:`, error);
|
||||
return { success: false, error: `Failed to open URL: ${error}` };
|
||||
}
|
||||
})
|
||||
|
||||
// Settings portal handler
|
||||
ipcMain.handle("open-settings-portal", () => {
|
||||
const mainWindow = deps.getMainWindow();
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send("show-settings-dialog");
|
||||
return { success: true };
|
||||
}
|
||||
return { success: false, error: "Main window not available" };
|
||||
})
|
||||
|
||||
// Window management handlers
|
||||
ipcMain.handle("toggle-window", () => {
|
||||
try {
|
||||
deps.toggleMainWindow()
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
console.error("Error toggling window:", error)
|
||||
return { error: "Failed to toggle window" }
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle("reset-queues", async () => {
|
||||
try {
|
||||
deps.clearQueues()
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
console.error("Error resetting queues:", error)
|
||||
return { error: "Failed to reset queues" }
|
||||
}
|
||||
})
|
||||
|
||||
// Process screenshot handlers
|
||||
ipcMain.handle("trigger-process-screenshots", async () => {
|
||||
try {
|
||||
// Check for API key before processing
|
||||
if (!configHelper.hasApiKey()) {
|
||||
const mainWindow = deps.getMainWindow();
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send(deps.PROCESSING_EVENTS.API_KEY_INVALID);
|
||||
}
|
||||
return { success: false, error: "API key required" };
|
||||
}
|
||||
|
||||
await deps.processingHelper?.processScreenshots()
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
console.error("Error processing screenshots:", error)
|
||||
return { error: "Failed to process screenshots" }
|
||||
}
|
||||
})
|
||||
|
||||
// Reset handlers
|
||||
ipcMain.handle("trigger-reset", () => {
|
||||
try {
|
||||
// First cancel any ongoing requests
|
||||
deps.processingHelper?.cancelOngoingRequests()
|
||||
|
||||
// Clear all queues immediately
|
||||
deps.clearQueues()
|
||||
|
||||
// Reset view to queue
|
||||
deps.setView("queue")
|
||||
|
||||
// Get main window and send reset events
|
||||
const mainWindow = deps.getMainWindow()
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
// Send reset events in sequence
|
||||
mainWindow.webContents.send("reset-view")
|
||||
mainWindow.webContents.send("reset")
|
||||
}
|
||||
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
console.error("Error triggering reset:", error)
|
||||
return { error: "Failed to trigger reset" }
|
||||
}
|
||||
})
|
||||
|
||||
// Window movement handlers
|
||||
ipcMain.handle("trigger-move-left", () => {
|
||||
try {
|
||||
deps.moveWindowLeft()
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
console.error("Error moving window left:", error)
|
||||
return { error: "Failed to move window left" }
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle("trigger-move-right", () => {
|
||||
try {
|
||||
deps.moveWindowRight()
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
console.error("Error moving window right:", error)
|
||||
return { error: "Failed to move window right" }
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle("trigger-move-up", () => {
|
||||
try {
|
||||
deps.moveWindowUp()
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
console.error("Error moving window up:", error)
|
||||
return { error: "Failed to move window up" }
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle("trigger-move-down", () => {
|
||||
try {
|
||||
deps.moveWindowDown()
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
console.error("Error moving window down:", error)
|
||||
return { error: "Failed to move window down" }
|
||||
}
|
||||
})
|
||||
|
||||
// Delete last screenshot handler
|
||||
ipcMain.handle("delete-last-screenshot", async () => {
|
||||
try {
|
||||
const queue = deps.getView() === "queue"
|
||||
? deps.getScreenshotQueue()
|
||||
: deps.getExtraScreenshotQueue()
|
||||
|
||||
if (queue.length === 0) {
|
||||
return { success: false, error: "No screenshots to delete" }
|
||||
}
|
||||
|
||||
// Get the last screenshot in the queue
|
||||
const lastScreenshot = queue[queue.length - 1]
|
||||
|
||||
// Delete it
|
||||
const result = await deps.deleteScreenshot(lastScreenshot)
|
||||
|
||||
// Notify the renderer about the change
|
||||
const mainWindow = deps.getMainWindow()
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
mainWindow.webContents.send("screenshot-deleted", { path: lastScreenshot })
|
||||
}
|
||||
|
||||
return result
|
||||
} catch (error) {
|
||||
console.error("Error deleting last screenshot:", error)
|
||||
return { success: false, error: "Failed to delete last screenshot" }
|
||||
}
|
||||
})
|
||||
}
|
||||
@ -0,0 +1,712 @@
|
||||
import { app, BrowserWindow, screen, shell, ipcMain } from "electron"
|
||||
import path from "path"
|
||||
import fs from "fs"
|
||||
import { initializeIpcHandlers } from "./ipcHandlers"
|
||||
import { ProcessingHelper } from "./ProcessingHelper"
|
||||
import { ScreenshotHelper } from "./ScreenshotHelper"
|
||||
import { ShortcutsHelper } from "./shortcuts"
|
||||
import { initAutoUpdater } from "./autoUpdater"
|
||||
import { configHelper } from "./ConfigHelper"
|
||||
import * as dotenv from "dotenv"
|
||||
|
||||
// Constants
|
||||
const isDev = process.env.NODE_ENV === "development"
|
||||
|
||||
// Application State
|
||||
const state = {
|
||||
// Window management properties
|
||||
mainWindow: null as BrowserWindow | null,
|
||||
isWindowVisible: false,
|
||||
windowPosition: null as { x: number; y: number } | null,
|
||||
windowSize: null as { width: number; height: number } | null,
|
||||
screenWidth: 0,
|
||||
screenHeight: 0,
|
||||
step: 0,
|
||||
currentX: 0,
|
||||
currentY: 0,
|
||||
|
||||
// Application helpers
|
||||
screenshotHelper: null as ScreenshotHelper | null,
|
||||
shortcutsHelper: null as ShortcutsHelper | null,
|
||||
processingHelper: null as ProcessingHelper | null,
|
||||
|
||||
// View and state management
|
||||
view: "queue" as "queue" | "solutions" | "debug",
|
||||
problemInfo: null as any,
|
||||
hasDebugged: false,
|
||||
|
||||
// Processing events
|
||||
PROCESSING_EVENTS: {
|
||||
UNAUTHORIZED: "processing-unauthorized",
|
||||
NO_SCREENSHOTS: "processing-no-screenshots",
|
||||
OUT_OF_CREDITS: "out-of-credits",
|
||||
API_KEY_INVALID: "api-key-invalid",
|
||||
INITIAL_START: "initial-start",
|
||||
PROBLEM_EXTRACTED: "problem-extracted",
|
||||
SOLUTION_SUCCESS: "solution-success",
|
||||
INITIAL_SOLUTION_ERROR: "solution-error",
|
||||
DEBUG_START: "debug-start",
|
||||
DEBUG_SUCCESS: "debug-success",
|
||||
DEBUG_ERROR: "debug-error"
|
||||
} as const
|
||||
}
|
||||
|
||||
// Add interfaces for helper classes
|
||||
export interface IProcessingHelperDeps {
|
||||
getScreenshotHelper: () => ScreenshotHelper | null
|
||||
getMainWindow: () => BrowserWindow | null
|
||||
getView: () => "queue" | "solutions" | "debug"
|
||||
setView: (view: "queue" | "solutions" | "debug") => void
|
||||
getProblemInfo: () => any
|
||||
setProblemInfo: (info: any) => void
|
||||
getScreenshotQueue: () => string[]
|
||||
getExtraScreenshotQueue: () => string[]
|
||||
clearQueues: () => void
|
||||
takeScreenshot: () => Promise<string>
|
||||
getImagePreview: (filepath: string) => Promise<string>
|
||||
deleteScreenshot: (
|
||||
path: string
|
||||
) => Promise<{ success: boolean; error?: string }>
|
||||
setHasDebugged: (value: boolean) => void
|
||||
getHasDebugged: () => boolean
|
||||
PROCESSING_EVENTS: typeof state.PROCESSING_EVENTS
|
||||
}
|
||||
|
||||
export interface IShortcutsHelperDeps {
|
||||
getMainWindow: () => BrowserWindow | null
|
||||
takeScreenshot: () => Promise<string>
|
||||
getImagePreview: (filepath: string) => Promise<string>
|
||||
processingHelper: ProcessingHelper | null
|
||||
clearQueues: () => void
|
||||
setView: (view: "queue" | "solutions" | "debug") => void
|
||||
isVisible: () => boolean
|
||||
toggleMainWindow: () => void
|
||||
moveWindowLeft: () => void
|
||||
moveWindowRight: () => void
|
||||
moveWindowUp: () => void
|
||||
moveWindowDown: () => void
|
||||
}
|
||||
|
||||
export interface IIpcHandlerDeps {
|
||||
getMainWindow: () => BrowserWindow | null
|
||||
setWindowDimensions: (width: number, height: number) => void
|
||||
getScreenshotQueue: () => string[]
|
||||
getExtraScreenshotQueue: () => string[]
|
||||
deleteScreenshot: (
|
||||
path: string
|
||||
) => Promise<{ success: boolean; error?: string }>
|
||||
getImagePreview: (filepath: string) => Promise<string>
|
||||
processingHelper: ProcessingHelper | null
|
||||
PROCESSING_EVENTS: typeof state.PROCESSING_EVENTS
|
||||
takeScreenshot: () => Promise<string>
|
||||
getView: () => "queue" | "solutions" | "debug"
|
||||
toggleMainWindow: () => void
|
||||
clearQueues: () => void
|
||||
setView: (view: "queue" | "solutions" | "debug") => void
|
||||
moveWindowLeft: () => void
|
||||
moveWindowRight: () => void
|
||||
moveWindowUp: () => void
|
||||
moveWindowDown: () => void
|
||||
}
|
||||
|
||||
// Initialize helpers
|
||||
function initializeHelpers() {
|
||||
state.screenshotHelper = new ScreenshotHelper(state.view)
|
||||
state.processingHelper = new ProcessingHelper({
|
||||
getScreenshotHelper,
|
||||
getMainWindow,
|
||||
getView,
|
||||
setView,
|
||||
getProblemInfo,
|
||||
setProblemInfo,
|
||||
getScreenshotQueue,
|
||||
getExtraScreenshotQueue,
|
||||
clearQueues,
|
||||
takeScreenshot,
|
||||
getImagePreview,
|
||||
deleteScreenshot,
|
||||
setHasDebugged,
|
||||
getHasDebugged,
|
||||
PROCESSING_EVENTS: state.PROCESSING_EVENTS
|
||||
} as IProcessingHelperDeps)
|
||||
state.shortcutsHelper = new ShortcutsHelper({
|
||||
getMainWindow,
|
||||
takeScreenshot,
|
||||
getImagePreview,
|
||||
processingHelper: state.processingHelper,
|
||||
clearQueues,
|
||||
setView,
|
||||
isVisible: () => state.isWindowVisible,
|
||||
toggleMainWindow,
|
||||
moveWindowLeft: () =>
|
||||
moveWindowHorizontal((x) =>
|
||||
Math.max(-(state.windowSize?.width || 0) / 2, x - state.step)
|
||||
),
|
||||
moveWindowRight: () =>
|
||||
moveWindowHorizontal((x) =>
|
||||
Math.min(
|
||||
state.screenWidth - (state.windowSize?.width || 0) / 2,
|
||||
x + state.step
|
||||
)
|
||||
),
|
||||
moveWindowUp: () => moveWindowVertical((y) => y - state.step),
|
||||
moveWindowDown: () => moveWindowVertical((y) => y + state.step)
|
||||
} as IShortcutsHelperDeps)
|
||||
}
|
||||
|
||||
// Auth callback handler
|
||||
|
||||
// Register the interview-coder protocol
|
||||
if (process.platform === "darwin") {
|
||||
app.setAsDefaultProtocolClient("interview-coder")
|
||||
} else {
|
||||
app.setAsDefaultProtocolClient("interview-coder", process.execPath, [
|
||||
path.resolve(process.argv[1] || "")
|
||||
])
|
||||
}
|
||||
|
||||
// Handle the protocol. In this case, we choose to show an Error Box.
|
||||
if (process.defaultApp && process.argv.length >= 2) {
|
||||
app.setAsDefaultProtocolClient("interview-coder", process.execPath, [
|
||||
path.resolve(process.argv[1])
|
||||
])
|
||||
}
|
||||
|
||||
// Force Single Instance Lock
|
||||
const gotTheLock = app.requestSingleInstanceLock()
|
||||
|
||||
if (!gotTheLock) {
|
||||
app.quit()
|
||||
} else {
|
||||
app.on("second-instance", (event, commandLine) => {
|
||||
// Someone tried to run a second instance, we should focus our window.
|
||||
if (state.mainWindow) {
|
||||
if (state.mainWindow.isMinimized()) state.mainWindow.restore()
|
||||
state.mainWindow.focus()
|
||||
|
||||
// Protocol handler removed - no longer using auth callbacks
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Auth callback removed as we no longer use Supabase authentication
|
||||
|
||||
// Window management functions
|
||||
async function createWindow(): Promise<void> {
|
||||
if (state.mainWindow) {
|
||||
if (state.mainWindow.isMinimized()) state.mainWindow.restore()
|
||||
state.mainWindow.focus()
|
||||
return
|
||||
}
|
||||
|
||||
const primaryDisplay = screen.getPrimaryDisplay()
|
||||
const workArea = primaryDisplay.workAreaSize
|
||||
state.screenWidth = workArea.width
|
||||
state.screenHeight = workArea.height
|
||||
state.step = 60
|
||||
state.currentY = 50
|
||||
|
||||
const windowSettings: Electron.BrowserWindowConstructorOptions = {
|
||||
width: 800,
|
||||
height: 600,
|
||||
minWidth: 750,
|
||||
minHeight: 550,
|
||||
x: state.currentX,
|
||||
y: 50,
|
||||
alwaysOnTop: true,
|
||||
webPreferences: {
|
||||
nodeIntegration: false,
|
||||
contextIsolation: true,
|
||||
preload: isDev
|
||||
? path.join(__dirname, "../dist-electron/preload.js")
|
||||
: path.join(__dirname, "preload.js"),
|
||||
scrollBounce: true
|
||||
},
|
||||
show: true,
|
||||
frame: false,
|
||||
transparent: true,
|
||||
fullscreenable: false,
|
||||
hasShadow: false,
|
||||
opacity: 1.0, // Start with full opacity
|
||||
backgroundColor: "#00000000",
|
||||
focusable: true,
|
||||
skipTaskbar: true,
|
||||
type: "panel",
|
||||
paintWhenInitiallyHidden: true,
|
||||
titleBarStyle: "hidden",
|
||||
enableLargerThanScreen: true,
|
||||
movable: true
|
||||
}
|
||||
|
||||
state.mainWindow = new BrowserWindow(windowSettings)
|
||||
|
||||
// Add more detailed logging for window events
|
||||
state.mainWindow.webContents.on("did-finish-load", () => {
|
||||
console.log("Window finished loading")
|
||||
})
|
||||
state.mainWindow.webContents.on(
|
||||
"did-fail-load",
|
||||
async (event, errorCode, errorDescription) => {
|
||||
console.error("Window failed to load:", errorCode, errorDescription)
|
||||
if (isDev) {
|
||||
// In development, retry loading after a short delay
|
||||
console.log("Retrying to load development server...")
|
||||
setTimeout(() => {
|
||||
state.mainWindow?.loadURL("http://localhost:54321").catch((error) => {
|
||||
console.error("Failed to load dev server on retry:", error)
|
||||
})
|
||||
}, 1000)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if (isDev) {
|
||||
// In development, load from the dev server
|
||||
console.log("Loading from development server: http://localhost:54321")
|
||||
state.mainWindow.loadURL("http://localhost:54321").catch((error) => {
|
||||
console.error("Failed to load dev server, falling back to local file:", error)
|
||||
// Fallback to local file if dev server is not available
|
||||
const indexPath = path.join(__dirname, "../dist/index.html")
|
||||
console.log("Falling back to:", indexPath)
|
||||
if (fs.existsSync(indexPath)) {
|
||||
state.mainWindow.loadFile(indexPath)
|
||||
} else {
|
||||
console.error("Could not find index.html in dist folder")
|
||||
}
|
||||
})
|
||||
} else {
|
||||
// In production, load from the built files
|
||||
const indexPath = path.join(__dirname, "../dist/index.html")
|
||||
console.log("Loading production build:", indexPath)
|
||||
|
||||
if (fs.existsSync(indexPath)) {
|
||||
state.mainWindow.loadFile(indexPath)
|
||||
} else {
|
||||
console.error("Could not find index.html in dist folder")
|
||||
}
|
||||
}
|
||||
|
||||
// Configure window behavior
|
||||
state.mainWindow.webContents.setZoomFactor(1)
|
||||
if (isDev) {
|
||||
state.mainWindow.webContents.openDevTools()
|
||||
}
|
||||
state.mainWindow.webContents.setWindowOpenHandler(({ url }) => {
|
||||
console.log("Attempting to open URL:", url)
|
||||
if (url.includes("google.com") || url.includes("supabase.co")) {
|
||||
shell.openExternal(url)
|
||||
return { action: "deny" }
|
||||
}
|
||||
return { action: "allow" }
|
||||
})
|
||||
|
||||
// Enhanced screen capture resistance
|
||||
state.mainWindow.setContentProtection(true)
|
||||
|
||||
state.mainWindow.setVisibleOnAllWorkspaces(true, {
|
||||
visibleOnFullScreen: true
|
||||
})
|
||||
state.mainWindow.setAlwaysOnTop(true, "screen-saver", 1)
|
||||
|
||||
// Additional screen capture resistance settings
|
||||
if (process.platform === "darwin") {
|
||||
// Prevent window from being captured in screenshots
|
||||
state.mainWindow.setHiddenInMissionControl(true)
|
||||
state.mainWindow.setWindowButtonVisibility(false)
|
||||
state.mainWindow.setBackgroundColor("#00000000")
|
||||
|
||||
// Prevent window from being included in window switcher
|
||||
state.mainWindow.setSkipTaskbar(true)
|
||||
|
||||
// Disable window shadow
|
||||
state.mainWindow.setHasShadow(false)
|
||||
}
|
||||
|
||||
// Prevent the window from being captured by screen recording
|
||||
state.mainWindow.webContents.setBackgroundThrottling(false)
|
||||
state.mainWindow.webContents.setFrameRate(60)
|
||||
|
||||
// Set up window listeners
|
||||
state.mainWindow.on("move", handleWindowMove)
|
||||
state.mainWindow.on("resize", handleWindowResize)
|
||||
state.mainWindow.on("closed", handleWindowClosed)
|
||||
|
||||
// Initialize window state
|
||||
const bounds = state.mainWindow.getBounds()
|
||||
state.windowPosition = { x: bounds.x, y: bounds.y }
|
||||
state.windowSize = { width: bounds.width, height: bounds.height }
|
||||
state.currentX = bounds.x
|
||||
state.currentY = bounds.y
|
||||
state.isWindowVisible = true
|
||||
|
||||
// Set opacity based on user preferences or hide initially
|
||||
// Ensure the window is visible for the first launch or if opacity > 0.1
|
||||
const savedOpacity = configHelper.getOpacity();
|
||||
console.log(`Initial opacity from config: ${savedOpacity}`);
|
||||
|
||||
// Always make sure window is shown first
|
||||
state.mainWindow.show();
|
||||
state.mainWindow.focus();
|
||||
|
||||
if (savedOpacity <= 0.1) {
|
||||
console.log('Initial opacity too low, setting to 0 and hiding window');
|
||||
state.mainWindow.setOpacity(0);
|
||||
state.isWindowVisible = false;
|
||||
} else {
|
||||
console.log(`Setting initial opacity to ${savedOpacity}`);
|
||||
state.mainWindow.setOpacity(savedOpacity);
|
||||
state.isWindowVisible = true;
|
||||
}
|
||||
}
|
||||
|
||||
function handleWindowMove(): void {
|
||||
if (!state.mainWindow) return
|
||||
const bounds = state.mainWindow.getBounds()
|
||||
state.windowPosition = { x: bounds.x, y: bounds.y }
|
||||
state.currentX = bounds.x
|
||||
state.currentY = bounds.y
|
||||
}
|
||||
|
||||
function handleWindowResize(): void {
|
||||
if (!state.mainWindow) return
|
||||
const bounds = state.mainWindow.getBounds()
|
||||
state.windowSize = { width: bounds.width, height: bounds.height }
|
||||
}
|
||||
|
||||
function handleWindowClosed(): void {
|
||||
state.mainWindow = null
|
||||
state.isWindowVisible = false
|
||||
state.windowPosition = null
|
||||
state.windowSize = null
|
||||
}
|
||||
|
||||
// Window visibility functions
|
||||
function hideMainWindow(): void {
|
||||
if (!state.mainWindow?.isDestroyed()) {
|
||||
const bounds = state.mainWindow.getBounds();
|
||||
state.windowPosition = { x: bounds.x, y: bounds.y };
|
||||
state.windowSize = { width: bounds.width, height: bounds.height };
|
||||
state.mainWindow.setIgnoreMouseEvents(true, { forward: true });
|
||||
state.mainWindow.setOpacity(0);
|
||||
state.isWindowVisible = false;
|
||||
console.log('Window hidden, opacity set to 0');
|
||||
}
|
||||
}
|
||||
|
||||
function showMainWindow(): void {
|
||||
if (!state.mainWindow?.isDestroyed()) {
|
||||
if (state.windowPosition && state.windowSize) {
|
||||
state.mainWindow.setBounds({
|
||||
...state.windowPosition,
|
||||
...state.windowSize
|
||||
});
|
||||
}
|
||||
state.mainWindow.setIgnoreMouseEvents(false);
|
||||
state.mainWindow.setAlwaysOnTop(true, "screen-saver", 1);
|
||||
state.mainWindow.setVisibleOnAllWorkspaces(true, {
|
||||
visibleOnFullScreen: true
|
||||
});
|
||||
state.mainWindow.setContentProtection(true);
|
||||
state.mainWindow.show();
|
||||
state.mainWindow.focus();
|
||||
state.mainWindow.setOpacity(1);
|
||||
state.isWindowVisible = true;
|
||||
console.log('Window shown, opacity set to 1');
|
||||
}
|
||||
}
|
||||
|
||||
function toggleMainWindow(): void {
|
||||
console.log(`Toggling window. Current state: ${state.isWindowVisible ? 'visible' : 'hidden'}`);
|
||||
if (state.isWindowVisible) {
|
||||
hideMainWindow();
|
||||
} else {
|
||||
showMainWindow();
|
||||
}
|
||||
}
|
||||
|
||||
// Window movement functions
|
||||
function moveWindowHorizontal(updateFn: (x: number) => number): void {
|
||||
if (!state.mainWindow) return
|
||||
state.currentX = updateFn(state.currentX)
|
||||
state.mainWindow.setPosition(
|
||||
Math.round(state.currentX),
|
||||
Math.round(state.currentY)
|
||||
)
|
||||
}
|
||||
|
||||
function moveWindowVertical(updateFn: (y: number) => number): void {
|
||||
if (!state.mainWindow) return
|
||||
|
||||
const newY = updateFn(state.currentY)
|
||||
// Allow window to go 2/3 off screen in either direction
|
||||
const maxUpLimit = (-(state.windowSize?.height || 0) * 2) / 3
|
||||
const maxDownLimit =
|
||||
state.screenHeight + ((state.windowSize?.height || 0) * 2) / 3
|
||||
|
||||
// Log the current state and limits
|
||||
console.log({
|
||||
newY,
|
||||
maxUpLimit,
|
||||
maxDownLimit,
|
||||
screenHeight: state.screenHeight,
|
||||
windowHeight: state.windowSize?.height,
|
||||
currentY: state.currentY
|
||||
})
|
||||
|
||||
// Only update if within bounds
|
||||
if (newY >= maxUpLimit && newY <= maxDownLimit) {
|
||||
state.currentY = newY
|
||||
state.mainWindow.setPosition(
|
||||
Math.round(state.currentX),
|
||||
Math.round(state.currentY)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Window dimension functions
|
||||
function setWindowDimensions(width: number, height: number): void {
|
||||
if (!state.mainWindow?.isDestroyed()) {
|
||||
const [currentX, currentY] = state.mainWindow.getPosition()
|
||||
const primaryDisplay = screen.getPrimaryDisplay()
|
||||
const workArea = primaryDisplay.workAreaSize
|
||||
const maxWidth = Math.floor(workArea.width * 0.5)
|
||||
|
||||
state.mainWindow.setBounds({
|
||||
x: Math.min(currentX, workArea.width - maxWidth),
|
||||
y: currentY,
|
||||
width: Math.min(width + 32, maxWidth),
|
||||
height: Math.ceil(height)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Environment setup
|
||||
function loadEnvVariables() {
|
||||
if (isDev) {
|
||||
console.log("Loading env variables from:", path.join(process.cwd(), ".env"))
|
||||
dotenv.config({ path: path.join(process.cwd(), ".env") })
|
||||
} else {
|
||||
console.log(
|
||||
"Loading env variables from:",
|
||||
path.join(process.resourcesPath, ".env")
|
||||
)
|
||||
dotenv.config({ path: path.join(process.resourcesPath, ".env") })
|
||||
}
|
||||
console.log("Loaded environment variables:", {
|
||||
VITE_SUPABASE_URL: process.env.VITE_SUPABASE_URL ? "exists" : "missing",
|
||||
VITE_SUPABASE_ANON_KEY: process.env.VITE_SUPABASE_ANON_KEY
|
||||
? "exists"
|
||||
: "missing"
|
||||
})
|
||||
}
|
||||
|
||||
// Initialize application
|
||||
async function initializeApp() {
|
||||
try {
|
||||
// Set custom cache directory to prevent permission issues
|
||||
const appDataPath = path.join(app.getPath('appData'), 'interview-coder-v1')
|
||||
const sessionPath = path.join(appDataPath, 'session')
|
||||
const tempPath = path.join(appDataPath, 'temp')
|
||||
const cachePath = path.join(appDataPath, 'cache')
|
||||
|
||||
// Create directories if they don't exist
|
||||
for (const dir of [appDataPath, sessionPath, tempPath, cachePath]) {
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
}
|
||||
}
|
||||
|
||||
app.setPath('userData', appDataPath)
|
||||
app.setPath('sessionData', sessionPath)
|
||||
app.setPath('temp', tempPath)
|
||||
app.setPath('cache', cachePath)
|
||||
|
||||
loadEnvVariables()
|
||||
|
||||
// Ensure a configuration file exists
|
||||
if (!configHelper.hasApiKey()) {
|
||||
console.log("No API key found in configuration. User will need to set up.")
|
||||
}
|
||||
|
||||
initializeHelpers()
|
||||
initializeIpcHandlers({
|
||||
getMainWindow,
|
||||
setWindowDimensions,
|
||||
getScreenshotQueue,
|
||||
getExtraScreenshotQueue,
|
||||
deleteScreenshot,
|
||||
getImagePreview,
|
||||
processingHelper: state.processingHelper,
|
||||
PROCESSING_EVENTS: state.PROCESSING_EVENTS,
|
||||
takeScreenshot,
|
||||
getView,
|
||||
toggleMainWindow,
|
||||
clearQueues,
|
||||
setView,
|
||||
moveWindowLeft: () =>
|
||||
moveWindowHorizontal((x) =>
|
||||
Math.max(-(state.windowSize?.width || 0) / 2, x - state.step)
|
||||
),
|
||||
moveWindowRight: () =>
|
||||
moveWindowHorizontal((x) =>
|
||||
Math.min(
|
||||
state.screenWidth - (state.windowSize?.width || 0) / 2,
|
||||
x + state.step
|
||||
)
|
||||
),
|
||||
moveWindowUp: () => moveWindowVertical((y) => y - state.step),
|
||||
moveWindowDown: () => moveWindowVertical((y) => y + state.step)
|
||||
})
|
||||
await createWindow()
|
||||
state.shortcutsHelper?.registerGlobalShortcuts()
|
||||
|
||||
// Initialize auto-updater regardless of environment
|
||||
initAutoUpdater()
|
||||
console.log(
|
||||
"Auto-updater initialized in",
|
||||
isDev ? "development" : "production",
|
||||
"mode"
|
||||
)
|
||||
} catch (error) {
|
||||
console.error("Failed to initialize application:", error)
|
||||
app.quit()
|
||||
}
|
||||
}
|
||||
|
||||
// Auth callback handling removed - no longer needed
|
||||
app.on("open-url", (event, url) => {
|
||||
console.log("open-url event received:", url)
|
||||
event.preventDefault()
|
||||
})
|
||||
|
||||
// Handle second instance (removed auth callback handling)
|
||||
app.on("second-instance", (event, commandLine) => {
|
||||
console.log("second-instance event received:", commandLine)
|
||||
|
||||
// Focus or create the main window
|
||||
if (!state.mainWindow) {
|
||||
createWindow()
|
||||
} else {
|
||||
if (state.mainWindow.isMinimized()) state.mainWindow.restore()
|
||||
state.mainWindow.focus()
|
||||
}
|
||||
})
|
||||
|
||||
// Prevent multiple instances of the app
|
||||
if (!app.requestSingleInstanceLock()) {
|
||||
app.quit()
|
||||
} else {
|
||||
app.on("window-all-closed", () => {
|
||||
if (process.platform !== "darwin") {
|
||||
app.quit()
|
||||
state.mainWindow = null
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
app.on("activate", () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
createWindow()
|
||||
}
|
||||
})
|
||||
|
||||
// State getter/setter functions
|
||||
function getMainWindow(): BrowserWindow | null {
|
||||
return state.mainWindow
|
||||
}
|
||||
|
||||
function getView(): "queue" | "solutions" | "debug" {
|
||||
return state.view
|
||||
}
|
||||
|
||||
function setView(view: "queue" | "solutions" | "debug"): void {
|
||||
state.view = view
|
||||
state.screenshotHelper?.setView(view)
|
||||
}
|
||||
|
||||
function getScreenshotHelper(): ScreenshotHelper | null {
|
||||
return state.screenshotHelper
|
||||
}
|
||||
|
||||
function getProblemInfo(): any {
|
||||
return state.problemInfo
|
||||
}
|
||||
|
||||
function setProblemInfo(problemInfo: any): void {
|
||||
state.problemInfo = problemInfo
|
||||
}
|
||||
|
||||
function getScreenshotQueue(): string[] {
|
||||
return state.screenshotHelper?.getScreenshotQueue() || []
|
||||
}
|
||||
|
||||
function getExtraScreenshotQueue(): string[] {
|
||||
return state.screenshotHelper?.getExtraScreenshotQueue() || []
|
||||
}
|
||||
|
||||
function clearQueues(): void {
|
||||
state.screenshotHelper?.clearQueues()
|
||||
state.problemInfo = null
|
||||
setView("queue")
|
||||
}
|
||||
|
||||
async function takeScreenshot(): Promise<string> {
|
||||
if (!state.mainWindow) throw new Error("No main window available")
|
||||
return (
|
||||
state.screenshotHelper?.takeScreenshot(
|
||||
() => hideMainWindow(),
|
||||
() => showMainWindow()
|
||||
) || ""
|
||||
)
|
||||
}
|
||||
|
||||
async function getImagePreview(filepath: string): Promise<string> {
|
||||
return state.screenshotHelper?.getImagePreview(filepath) || ""
|
||||
}
|
||||
|
||||
async function deleteScreenshot(
|
||||
path: string
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
return (
|
||||
state.screenshotHelper?.deleteScreenshot(path) || {
|
||||
success: false,
|
||||
error: "Screenshot helper not initialized"
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
function setHasDebugged(value: boolean): void {
|
||||
state.hasDebugged = value
|
||||
}
|
||||
|
||||
function getHasDebugged(): boolean {
|
||||
return state.hasDebugged
|
||||
}
|
||||
|
||||
// Export state and functions for other modules
|
||||
export {
|
||||
state,
|
||||
createWindow,
|
||||
hideMainWindow,
|
||||
showMainWindow,
|
||||
toggleMainWindow,
|
||||
setWindowDimensions,
|
||||
moveWindowHorizontal,
|
||||
moveWindowVertical,
|
||||
getMainWindow,
|
||||
getView,
|
||||
setView,
|
||||
getScreenshotHelper,
|
||||
getProblemInfo,
|
||||
setProblemInfo,
|
||||
getScreenshotQueue,
|
||||
getExtraScreenshotQueue,
|
||||
clearQueues,
|
||||
takeScreenshot,
|
||||
getImagePreview,
|
||||
deleteScreenshot,
|
||||
setHasDebugged,
|
||||
getHasDebugged
|
||||
}
|
||||
|
||||
app.whenReady().then(initializeApp)
|
||||
@ -0,0 +1,262 @@
|
||||
console.log("Preload script starting...")
|
||||
import { contextBridge, ipcRenderer } from "electron"
|
||||
const { shell } = require("electron")
|
||||
|
||||
export const PROCESSING_EVENTS = {
|
||||
//global states
|
||||
UNAUTHORIZED: "procesing-unauthorized",
|
||||
NO_SCREENSHOTS: "processing-no-screenshots",
|
||||
OUT_OF_CREDITS: "out-of-credits",
|
||||
API_KEY_INVALID: "api-key-invalid",
|
||||
|
||||
//states for generating the initial solution
|
||||
INITIAL_START: "initial-start",
|
||||
PROBLEM_EXTRACTED: "problem-extracted",
|
||||
SOLUTION_SUCCESS: "solution-success",
|
||||
INITIAL_SOLUTION_ERROR: "solution-error",
|
||||
RESET: "reset",
|
||||
|
||||
//states for processing the debugging
|
||||
DEBUG_START: "debug-start",
|
||||
DEBUG_SUCCESS: "debug-success",
|
||||
DEBUG_ERROR: "debug-error"
|
||||
} as const
|
||||
|
||||
// At the top of the file
|
||||
console.log("Preload script is running")
|
||||
|
||||
const electronAPI = {
|
||||
// Original methods
|
||||
openSubscriptionPortal: async (authData: { id: string; email: string }) => {
|
||||
return ipcRenderer.invoke("open-subscription-portal", authData)
|
||||
},
|
||||
openSettingsPortal: () => ipcRenderer.invoke("open-settings-portal"),
|
||||
updateContentDimensions: (dimensions: { width: number; height: number }) =>
|
||||
ipcRenderer.invoke("update-content-dimensions", dimensions),
|
||||
clearStore: () => ipcRenderer.invoke("clear-store"),
|
||||
getScreenshots: () => ipcRenderer.invoke("get-screenshots"),
|
||||
deleteScreenshot: (path: string) =>
|
||||
ipcRenderer.invoke("delete-screenshot", path),
|
||||
toggleMainWindow: async () => {
|
||||
console.log("toggleMainWindow called from preload")
|
||||
try {
|
||||
const result = await ipcRenderer.invoke("toggle-window")
|
||||
console.log("toggle-window result:", result)
|
||||
return result
|
||||
} catch (error) {
|
||||
console.error("Error in toggleMainWindow:", error)
|
||||
throw error
|
||||
}
|
||||
},
|
||||
// Event listeners
|
||||
onScreenshotTaken: (
|
||||
callback: (data: { path: string; preview: string }) => void
|
||||
) => {
|
||||
const subscription = (_: any, data: { path: string; preview: string }) =>
|
||||
callback(data)
|
||||
ipcRenderer.on("screenshot-taken", subscription)
|
||||
return () => {
|
||||
ipcRenderer.removeListener("screenshot-taken", subscription)
|
||||
}
|
||||
},
|
||||
onResetView: (callback: () => void) => {
|
||||
const subscription = () => callback()
|
||||
ipcRenderer.on("reset-view", subscription)
|
||||
return () => {
|
||||
ipcRenderer.removeListener("reset-view", subscription)
|
||||
}
|
||||
},
|
||||
onSolutionStart: (callback: () => void) => {
|
||||
const subscription = () => callback()
|
||||
ipcRenderer.on(PROCESSING_EVENTS.INITIAL_START, subscription)
|
||||
return () => {
|
||||
ipcRenderer.removeListener(PROCESSING_EVENTS.INITIAL_START, subscription)
|
||||
}
|
||||
},
|
||||
onDebugStart: (callback: () => void) => {
|
||||
const subscription = () => callback()
|
||||
ipcRenderer.on(PROCESSING_EVENTS.DEBUG_START, subscription)
|
||||
return () => {
|
||||
ipcRenderer.removeListener(PROCESSING_EVENTS.DEBUG_START, subscription)
|
||||
}
|
||||
},
|
||||
onDebugSuccess: (callback: (data: any) => void) => {
|
||||
ipcRenderer.on("debug-success", (_event, data) => callback(data))
|
||||
return () => {
|
||||
ipcRenderer.removeListener("debug-success", (_event, data) =>
|
||||
callback(data)
|
||||
)
|
||||
}
|
||||
},
|
||||
onDebugError: (callback: (error: string) => void) => {
|
||||
const subscription = (_: any, error: string) => callback(error)
|
||||
ipcRenderer.on(PROCESSING_EVENTS.DEBUG_ERROR, subscription)
|
||||
return () => {
|
||||
ipcRenderer.removeListener(PROCESSING_EVENTS.DEBUG_ERROR, subscription)
|
||||
}
|
||||
},
|
||||
onSolutionError: (callback: (error: string) => void) => {
|
||||
const subscription = (_: any, error: string) => callback(error)
|
||||
ipcRenderer.on(PROCESSING_EVENTS.INITIAL_SOLUTION_ERROR, subscription)
|
||||
return () => {
|
||||
ipcRenderer.removeListener(
|
||||
PROCESSING_EVENTS.INITIAL_SOLUTION_ERROR,
|
||||
subscription
|
||||
)
|
||||
}
|
||||
},
|
||||
onProcessingNoScreenshots: (callback: () => void) => {
|
||||
const subscription = () => callback()
|
||||
ipcRenderer.on(PROCESSING_EVENTS.NO_SCREENSHOTS, subscription)
|
||||
return () => {
|
||||
ipcRenderer.removeListener(PROCESSING_EVENTS.NO_SCREENSHOTS, subscription)
|
||||
}
|
||||
},
|
||||
onOutOfCredits: (callback: () => void) => {
|
||||
const subscription = () => callback()
|
||||
ipcRenderer.on(PROCESSING_EVENTS.OUT_OF_CREDITS, subscription)
|
||||
return () => {
|
||||
ipcRenderer.removeListener(PROCESSING_EVENTS.OUT_OF_CREDITS, subscription)
|
||||
}
|
||||
},
|
||||
onProblemExtracted: (callback: (data: any) => void) => {
|
||||
const subscription = (_: any, data: any) => callback(data)
|
||||
ipcRenderer.on(PROCESSING_EVENTS.PROBLEM_EXTRACTED, subscription)
|
||||
return () => {
|
||||
ipcRenderer.removeListener(
|
||||
PROCESSING_EVENTS.PROBLEM_EXTRACTED,
|
||||
subscription
|
||||
)
|
||||
}
|
||||
},
|
||||
onSolutionSuccess: (callback: (data: any) => void) => {
|
||||
const subscription = (_: any, data: any) => callback(data)
|
||||
ipcRenderer.on(PROCESSING_EVENTS.SOLUTION_SUCCESS, subscription)
|
||||
return () => {
|
||||
ipcRenderer.removeListener(
|
||||
PROCESSING_EVENTS.SOLUTION_SUCCESS,
|
||||
subscription
|
||||
)
|
||||
}
|
||||
},
|
||||
onUnauthorized: (callback: () => void) => {
|
||||
const subscription = () => callback()
|
||||
ipcRenderer.on(PROCESSING_EVENTS.UNAUTHORIZED, subscription)
|
||||
return () => {
|
||||
ipcRenderer.removeListener(PROCESSING_EVENTS.UNAUTHORIZED, subscription)
|
||||
}
|
||||
},
|
||||
// External URL handler
|
||||
openLink: (url: string) => shell.openExternal(url),
|
||||
triggerScreenshot: () => ipcRenderer.invoke("trigger-screenshot"),
|
||||
triggerProcessScreenshots: () =>
|
||||
ipcRenderer.invoke("trigger-process-screenshots"),
|
||||
triggerReset: () => ipcRenderer.invoke("trigger-reset"),
|
||||
triggerMoveLeft: () => ipcRenderer.invoke("trigger-move-left"),
|
||||
triggerMoveRight: () => ipcRenderer.invoke("trigger-move-right"),
|
||||
triggerMoveUp: () => ipcRenderer.invoke("trigger-move-up"),
|
||||
triggerMoveDown: () => ipcRenderer.invoke("trigger-move-down"),
|
||||
onSubscriptionUpdated: (callback: () => void) => {
|
||||
const subscription = () => callback()
|
||||
ipcRenderer.on("subscription-updated", subscription)
|
||||
return () => {
|
||||
ipcRenderer.removeListener("subscription-updated", subscription)
|
||||
}
|
||||
},
|
||||
onSubscriptionPortalClosed: (callback: () => void) => {
|
||||
const subscription = () => callback()
|
||||
ipcRenderer.on("subscription-portal-closed", subscription)
|
||||
return () => {
|
||||
ipcRenderer.removeListener("subscription-portal-closed", subscription)
|
||||
}
|
||||
},
|
||||
onReset: (callback: () => void) => {
|
||||
const subscription = () => callback()
|
||||
ipcRenderer.on(PROCESSING_EVENTS.RESET, subscription)
|
||||
return () => {
|
||||
ipcRenderer.removeListener(PROCESSING_EVENTS.RESET, subscription)
|
||||
}
|
||||
},
|
||||
startUpdate: () => ipcRenderer.invoke("start-update"),
|
||||
installUpdate: () => ipcRenderer.invoke("install-update"),
|
||||
onUpdateAvailable: (callback: (info: any) => void) => {
|
||||
const subscription = (_: any, info: any) => callback(info)
|
||||
ipcRenderer.on("update-available", subscription)
|
||||
return () => {
|
||||
ipcRenderer.removeListener("update-available", subscription)
|
||||
}
|
||||
},
|
||||
onUpdateDownloaded: (callback: (info: any) => void) => {
|
||||
const subscription = (_: any, info: any) => callback(info)
|
||||
ipcRenderer.on("update-downloaded", subscription)
|
||||
return () => {
|
||||
ipcRenderer.removeListener("update-downloaded", subscription)
|
||||
}
|
||||
},
|
||||
decrementCredits: () => ipcRenderer.invoke("decrement-credits"),
|
||||
onCreditsUpdated: (callback: (credits: number) => void) => {
|
||||
const subscription = (_event: any, credits: number) => callback(credits)
|
||||
ipcRenderer.on("credits-updated", subscription)
|
||||
return () => {
|
||||
ipcRenderer.removeListener("credits-updated", subscription)
|
||||
}
|
||||
},
|
||||
getPlatform: () => process.platform,
|
||||
|
||||
// New methods for OpenAI API integration
|
||||
getConfig: () => ipcRenderer.invoke("get-config"),
|
||||
updateConfig: (config: { apiKey?: string; model?: string; language?: string; opacity?: number }) =>
|
||||
ipcRenderer.invoke("update-config", config),
|
||||
onShowSettings: (callback: () => void) => {
|
||||
const subscription = () => callback()
|
||||
ipcRenderer.on("show-settings-dialog", subscription)
|
||||
return () => {
|
||||
ipcRenderer.removeListener("show-settings-dialog", subscription)
|
||||
}
|
||||
},
|
||||
checkApiKey: () => ipcRenderer.invoke("check-api-key"),
|
||||
validateApiKey: (apiKey: string) =>
|
||||
ipcRenderer.invoke("validate-api-key", apiKey),
|
||||
openExternal: (url: string) =>
|
||||
ipcRenderer.invoke("openExternal", url),
|
||||
onApiKeyInvalid: (callback: () => void) => {
|
||||
const subscription = () => callback()
|
||||
ipcRenderer.on(PROCESSING_EVENTS.API_KEY_INVALID, subscription)
|
||||
return () => {
|
||||
ipcRenderer.removeListener(PROCESSING_EVENTS.API_KEY_INVALID, subscription)
|
||||
}
|
||||
},
|
||||
removeListener: (eventName: string, callback: (...args: any[]) => void) => {
|
||||
ipcRenderer.removeListener(eventName, callback)
|
||||
},
|
||||
onDeleteLastScreenshot: (callback: () => void) => {
|
||||
const subscription = () => callback()
|
||||
ipcRenderer.on("delete-last-screenshot", subscription)
|
||||
return () => {
|
||||
ipcRenderer.removeListener("delete-last-screenshot", subscription)
|
||||
}
|
||||
},
|
||||
deleteLastScreenshot: () => ipcRenderer.invoke("delete-last-screenshot")
|
||||
}
|
||||
|
||||
// Before exposing the API
|
||||
console.log(
|
||||
"About to expose electronAPI with methods:",
|
||||
Object.keys(electronAPI)
|
||||
)
|
||||
|
||||
// Expose the API
|
||||
contextBridge.exposeInMainWorld("electronAPI", electronAPI)
|
||||
|
||||
console.log("electronAPI exposed to window")
|
||||
|
||||
// Add this focus restoration handler
|
||||
ipcRenderer.on("restore-focus", () => {
|
||||
// Try to focus the active element if it exists
|
||||
const activeElement = document.activeElement as HTMLElement
|
||||
if (activeElement && typeof activeElement.focus === "function") {
|
||||
activeElement.focus()
|
||||
}
|
||||
})
|
||||
|
||||
// Remove auth-callback handling - no longer needed
|
||||
@ -0,0 +1,167 @@
|
||||
import { globalShortcut, app } from "electron"
|
||||
import { IShortcutsHelperDeps } from "./main"
|
||||
import { configHelper } from "./ConfigHelper"
|
||||
|
||||
export class ShortcutsHelper {
|
||||
private deps: IShortcutsHelperDeps
|
||||
|
||||
constructor(deps: IShortcutsHelperDeps) {
|
||||
this.deps = deps
|
||||
}
|
||||
|
||||
private adjustOpacity(delta: number): void {
|
||||
const mainWindow = this.deps.getMainWindow();
|
||||
if (!mainWindow) return;
|
||||
|
||||
let currentOpacity = mainWindow.getOpacity();
|
||||
let newOpacity = Math.max(0.1, Math.min(1.0, currentOpacity + delta));
|
||||
console.log(`Adjusting opacity from ${currentOpacity} to ${newOpacity}`);
|
||||
|
||||
mainWindow.setOpacity(newOpacity);
|
||||
|
||||
// Save the opacity setting to config without re-initializing the client
|
||||
try {
|
||||
const config = configHelper.loadConfig();
|
||||
config.opacity = newOpacity;
|
||||
configHelper.saveConfig(config);
|
||||
} catch (error) {
|
||||
console.error('Error saving opacity to config:', error);
|
||||
}
|
||||
|
||||
// If we're making the window visible, also make sure it's shown and interaction is enabled
|
||||
if (newOpacity > 0.1 && !this.deps.isVisible()) {
|
||||
this.deps.toggleMainWindow();
|
||||
}
|
||||
}
|
||||
|
||||
public registerGlobalShortcuts(): void {
|
||||
globalShortcut.register("CommandOrControl+H", async () => {
|
||||
const mainWindow = this.deps.getMainWindow()
|
||||
if (mainWindow) {
|
||||
console.log("Taking screenshot...")
|
||||
try {
|
||||
const screenshotPath = await this.deps.takeScreenshot()
|
||||
const preview = await this.deps.getImagePreview(screenshotPath)
|
||||
mainWindow.webContents.send("screenshot-taken", {
|
||||
path: screenshotPath,
|
||||
preview
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Error capturing screenshot:", error)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
globalShortcut.register("CommandOrControl+Enter", async () => {
|
||||
await this.deps.processingHelper?.processScreenshots()
|
||||
})
|
||||
|
||||
globalShortcut.register("CommandOrControl+R", () => {
|
||||
console.log(
|
||||
"Command + R pressed. Canceling requests and resetting queues..."
|
||||
)
|
||||
|
||||
// Cancel ongoing API requests
|
||||
this.deps.processingHelper?.cancelOngoingRequests()
|
||||
|
||||
// Clear both screenshot queues
|
||||
this.deps.clearQueues()
|
||||
|
||||
console.log("Cleared queues.")
|
||||
|
||||
// Update the view state to 'queue'
|
||||
this.deps.setView("queue")
|
||||
|
||||
// Notify renderer process to switch view to 'queue'
|
||||
const mainWindow = this.deps.getMainWindow()
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
mainWindow.webContents.send("reset-view")
|
||||
mainWindow.webContents.send("reset")
|
||||
}
|
||||
})
|
||||
|
||||
// New shortcuts for moving the window
|
||||
globalShortcut.register("CommandOrControl+Left", () => {
|
||||
console.log("Command/Ctrl + Left pressed. Moving window left.")
|
||||
this.deps.moveWindowLeft()
|
||||
})
|
||||
|
||||
globalShortcut.register("CommandOrControl+Right", () => {
|
||||
console.log("Command/Ctrl + Right pressed. Moving window right.")
|
||||
this.deps.moveWindowRight()
|
||||
})
|
||||
|
||||
globalShortcut.register("CommandOrControl+Down", () => {
|
||||
console.log("Command/Ctrl + down pressed. Moving window down.")
|
||||
this.deps.moveWindowDown()
|
||||
})
|
||||
|
||||
globalShortcut.register("CommandOrControl+Up", () => {
|
||||
console.log("Command/Ctrl + Up pressed. Moving window Up.")
|
||||
this.deps.moveWindowUp()
|
||||
})
|
||||
|
||||
globalShortcut.register("CommandOrControl+B", () => {
|
||||
console.log("Command/Ctrl + B pressed. Toggling window visibility.")
|
||||
this.deps.toggleMainWindow()
|
||||
})
|
||||
|
||||
globalShortcut.register("CommandOrControl+Q", () => {
|
||||
console.log("Command/Ctrl + Q pressed. Quitting application.")
|
||||
app.quit()
|
||||
})
|
||||
|
||||
// Adjust opacity shortcuts
|
||||
globalShortcut.register("CommandOrControl+[", () => {
|
||||
console.log("Command/Ctrl + [ pressed. Decreasing opacity.")
|
||||
this.adjustOpacity(-0.1)
|
||||
})
|
||||
|
||||
globalShortcut.register("CommandOrControl+]", () => {
|
||||
console.log("Command/Ctrl + ] pressed. Increasing opacity.")
|
||||
this.adjustOpacity(0.1)
|
||||
})
|
||||
|
||||
// Zoom controls
|
||||
globalShortcut.register("CommandOrControl+-", () => {
|
||||
console.log("Command/Ctrl + - pressed. Zooming out.")
|
||||
const mainWindow = this.deps.getMainWindow()
|
||||
if (mainWindow) {
|
||||
const currentZoom = mainWindow.webContents.getZoomLevel()
|
||||
mainWindow.webContents.setZoomLevel(currentZoom - 0.5)
|
||||
}
|
||||
})
|
||||
|
||||
globalShortcut.register("CommandOrControl+0", () => {
|
||||
console.log("Command/Ctrl + 0 pressed. Resetting zoom.")
|
||||
const mainWindow = this.deps.getMainWindow()
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.setZoomLevel(0)
|
||||
}
|
||||
})
|
||||
|
||||
globalShortcut.register("CommandOrControl+=", () => {
|
||||
console.log("Command/Ctrl + = pressed. Zooming in.")
|
||||
const mainWindow = this.deps.getMainWindow()
|
||||
if (mainWindow) {
|
||||
const currentZoom = mainWindow.webContents.getZoomLevel()
|
||||
mainWindow.webContents.setZoomLevel(currentZoom + 0.5)
|
||||
}
|
||||
})
|
||||
|
||||
// Delete last screenshot shortcut
|
||||
globalShortcut.register("CommandOrControl+L", () => {
|
||||
console.log("Command/Ctrl + L pressed. Deleting last screenshot.")
|
||||
const mainWindow = this.deps.getMainWindow()
|
||||
if (mainWindow) {
|
||||
// Send an event to the renderer to delete the last screenshot
|
||||
mainWindow.webContents.send("delete-last-screenshot")
|
||||
}
|
||||
})
|
||||
|
||||
// Unregister shortcuts when quitting
|
||||
app.on("will-quit", () => {
|
||||
globalShortcut.unregisterAll()
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,16 @@
|
||||
import Store from "electron-store"
|
||||
|
||||
interface StoreSchema {
|
||||
// Empty for now, we can add other store items here later
|
||||
}
|
||||
|
||||
const store = new Store<StoreSchema>({
|
||||
defaults: {},
|
||||
encryptionKey: "your-encryption-key"
|
||||
}) as Store<StoreSchema> & {
|
||||
store: StoreSchema
|
||||
get: <K extends keyof StoreSchema>(key: K) => StoreSchema[K]
|
||||
set: <K extends keyof StoreSchema>(key: K, value: StoreSchema[K]) => void
|
||||
}
|
||||
|
||||
export { store }
|
||||
@ -0,0 +1,18 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"module": "CommonJS",
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"noImplicitAny": true,
|
||||
"sourceMap": true,
|
||||
"jsx": "react-jsx",
|
||||
"baseUrl": ".",
|
||||
"outDir": "../dist-electron",
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
"allowSyntheticDefaultImports": true
|
||||
},
|
||||
"include": ["*.ts", "ConfigHelper.ts", "../src/types/electron.d.ts"]
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_SUPABASE_URL: string
|
||||
readonly VITE_SUPABASE_ANON_KEY: string
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv
|
||||
}
|
||||
@ -0,0 +1,16 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Interview Coder</title>
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@ -0,0 +1,187 @@
|
||||
{
|
||||
"name": "interview-coder-v1",
|
||||
"version": "1.0.19",
|
||||
"main": "./dist-electron/main.js",
|
||||
"scripts": {
|
||||
"clean": "rimraf dist dist-electron",
|
||||
"dev": "cross-env NODE_ENV=development npm run clean && concurrently \"tsc -w -p tsconfig.electron.json\" \"vite\" \"wait-on -t 30000 http://localhost:54321 && electron ./dist-electron/main.js\"",
|
||||
"start": "cross-env NODE_ENV=development concurrently \"tsc -p tsconfig.electron.json\" \"vite\" \"wait-on -t 30000 http://localhost:54321 && electron ./dist-electron/main.js\"",
|
||||
"build": "cross-env NODE_ENV=production rimraf dist dist-electron && vite build && tsc -p tsconfig.electron.json",
|
||||
"run-prod": "cross-env NODE_ENV=production electron ./dist-electron/main.js"
|
||||
},
|
||||
"build": {
|
||||
"appId": "com.chunginlee.interviewcoder",
|
||||
"productName": "Interview Coder",
|
||||
"files": [
|
||||
"dist/**/*",
|
||||
"dist-electron/**/*",
|
||||
"package.json",
|
||||
"electron/**/*"
|
||||
],
|
||||
"directories": {
|
||||
"output": "release",
|
||||
"buildResources": "assets"
|
||||
},
|
||||
"asar": true,
|
||||
"compression": "maximum",
|
||||
"generateUpdatesFilesForAllChannels": true,
|
||||
"mac": {
|
||||
"category": "public.app-category.developer-tools",
|
||||
"target": [
|
||||
{
|
||||
"target": "dmg",
|
||||
"arch": [
|
||||
"x64",
|
||||
"arm64"
|
||||
]
|
||||
},
|
||||
{
|
||||
"target": "zip",
|
||||
"arch": [
|
||||
"x64",
|
||||
"arm64"
|
||||
]
|
||||
}
|
||||
],
|
||||
"artifactName": "Interview-Coder-${arch}.${ext}",
|
||||
"icon": "assets/icons/mac/icon.icns",
|
||||
"hardenedRuntime": true,
|
||||
"gatekeeperAssess": false,
|
||||
"entitlements": "build/entitlements.mac.plist",
|
||||
"entitlementsInherit": "build/entitlements.mac.plist",
|
||||
"identity": "Developer ID Application",
|
||||
"notarize": true,
|
||||
"protocols": {
|
||||
"name": "interview-coder-protocol",
|
||||
"schemes": [
|
||||
"interview-coder"
|
||||
]
|
||||
}
|
||||
},
|
||||
"win": {
|
||||
"target": [
|
||||
"nsis"
|
||||
],
|
||||
"icon": "assets/icons/win/icon.ico",
|
||||
"artifactName": "${productName}-Windows-${version}.${ext}",
|
||||
"protocols": {
|
||||
"name": "interview-coder-protocol",
|
||||
"schemes": [
|
||||
"interview-coder"
|
||||
]
|
||||
}
|
||||
},
|
||||
"linux": {
|
||||
"target": [
|
||||
"AppImage"
|
||||
],
|
||||
"icon": "assets/icons/png/icon-256x256.png",
|
||||
"artifactName": "${productName}-Linux-${version}.${ext}",
|
||||
"protocols": {
|
||||
"name": "interview-coder-protocol",
|
||||
"schemes": [
|
||||
"interview-coder"
|
||||
]
|
||||
}
|
||||
},
|
||||
"publish": [
|
||||
{
|
||||
"provider": "github",
|
||||
"owner": "ibttf",
|
||||
"repo": "interview-coder",
|
||||
"private": false,
|
||||
"releaseType": "release"
|
||||
}
|
||||
],
|
||||
"extraResources": [
|
||||
{
|
||||
"from": ".env",
|
||||
"to": ".env",
|
||||
"filter": [
|
||||
"**/*"
|
||||
]
|
||||
}
|
||||
],
|
||||
"extraMetadata": {
|
||||
"main": "dist-electron/main.js"
|
||||
}
|
||||
},
|
||||
"keywords": ["interview", "coding", "interview prep", "technical interview", "tool"],
|
||||
"author": "Interview Coder Contributors",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"description": "An invisible desktop application to help you pass your technical interviews.",
|
||||
"dependencies": {
|
||||
"@electron/notarize": "^2.3.0",
|
||||
"@emotion/react": "^11.11.0",
|
||||
"@emotion/styled": "^11.11.0",
|
||||
"@radix-ui/react-dialog": "^1.1.2",
|
||||
"@radix-ui/react-label": "^2.1.0",
|
||||
"@radix-ui/react-slot": "^1.1.0",
|
||||
"@radix-ui/react-toast": "^1.2.2",
|
||||
"@supabase/supabase-js": "^2.39.0",
|
||||
"@tanstack/react-query": "^5.64.0",
|
||||
"axios": "^1.7.7",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"diff": "^7.0.0",
|
||||
"dotenv": "^16.4.7",
|
||||
"electron-log": "^5.2.4",
|
||||
"electron-store": "^10.0.0",
|
||||
"electron-updater": "^6.3.9",
|
||||
"form-data": "^4.0.1",
|
||||
"lucide-react": "^0.460.0",
|
||||
"openai": "^4.28.4",
|
||||
"react": "^18.2.0",
|
||||
"react-code-blocks": "^0.1.6",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-router-dom": "^6.28.1",
|
||||
"react-syntax-highlighter": "^15.6.1",
|
||||
"screenshot-desktop": "^1.15.0",
|
||||
"tailwind-merge": "^2.5.5",
|
||||
"uuid": "^11.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@electron/typescript-definitions": "^8.14.0",
|
||||
"@types/color": "^4.2.0",
|
||||
"@types/diff": "^6.0.0",
|
||||
"@types/electron-store": "^1.3.1",
|
||||
"@types/node": "^20.11.30",
|
||||
"@types/react": "^18.2.67",
|
||||
"@types/react-dom": "^18.2.22",
|
||||
"@types/react-syntax-highlighter": "^15.5.13",
|
||||
"@types/screenshot-desktop": "^1.12.3",
|
||||
"@types/uuid": "^9.0.8",
|
||||
"@typescript-eslint/eslint-plugin": "^7.3.1",
|
||||
"@typescript-eslint/parser": "^7.3.1",
|
||||
"@vitejs/plugin-react": "^4.2.1",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"concurrently": "^8.2.2",
|
||||
"cross-env": "^7.0.3",
|
||||
"electron": "^29.1.4",
|
||||
"electron-builder": "^24.13.3",
|
||||
"electron-is-dev": "^3.0.1",
|
||||
"eslint": "^8.57.0",
|
||||
"eslint-plugin-react-hooks": "^4.6.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.6",
|
||||
"postcss": "^8.4.49",
|
||||
"rimraf": "^6.0.1",
|
||||
"tailwindcss": "^3.4.15",
|
||||
"typescript": "^5.4.2",
|
||||
"vite": "^5.1.6",
|
||||
"vite-plugin-electron": "^0.28.4",
|
||||
"vite-plugin-electron-renderer": "^0.14.6",
|
||||
"wait-on": "^7.2.0"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,6 @@
|
||||
module.exports = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
@ -0,0 +1,23 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
@ -0,0 +1,43 @@
|
||||
{
|
||||
"name": "renderer",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@testing-library/jest-dom": "^5.17.0",
|
||||
"@testing-library/react": "^13.4.0",
|
||||
"@testing-library/user-event": "^13.5.0",
|
||||
"@types/jest": "^27.5.2",
|
||||
"@types/node": "^16.18.119",
|
||||
"@types/react": "^18.3.12",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-scripts": "5.0.1",
|
||||
"typescript": "^4.9.5",
|
||||
"web-vitals": "^2.1.4"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"test": "react-scripts test",
|
||||
"eject": "react-scripts eject"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"react-app",
|
||||
"react-app/jest"
|
||||
]
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 3.8 KiB |
@ -0,0 +1,43 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<meta
|
||||
name="description"
|
||||
content="Web site created using create-react-app"
|
||||
/>
|
||||
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is installed on a
|
||||
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||
-->
|
||||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
|
||||
<!--
|
||||
Notice the use of %PUBLIC_URL% in the tags above.
|
||||
It will be replaced with the URL of the `public` folder during the build.
|
||||
Only files inside the `public` folder can be referenced from the HTML.
|
||||
|
||||
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
|
||||
work correctly both with client-side routing and a non-root public URL.
|
||||
Learn how to configure a non-root public URL by running `npm run build`.
|
||||
-->
|
||||
<title>React App</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<!--
|
||||
This HTML file is a template.
|
||||
If you open it directly in the browser, you will see an empty page.
|
||||
|
||||
You can add webfonts, meta tags, or analytics to this file.
|
||||
The build step will place the bundled scripts into the <body> tag.
|
||||
|
||||
To begin the development, run `npm start` or `yarn start`.
|
||||
To create a production bundle, use `npm run build` or `yarn build`.
|
||||
-->
|
||||
</body>
|
||||
</html>
|
||||
|
After Width: | Height: | Size: 5.2 KiB |
|
After Width: | Height: | Size: 9.4 KiB |
@ -0,0 +1,25 @@
|
||||
{
|
||||
"short_name": "Interview Coder",
|
||||
"name": "Interview Coder",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
},
|
||||
{
|
||||
"src": "logo192.png",
|
||||
"type": "image/png",
|
||||
"sizes": "192x192"
|
||||
},
|
||||
{
|
||||
"src": "logo512.png",
|
||||
"type": "image/png",
|
||||
"sizes": "512x512"
|
||||
}
|
||||
],
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#ffffff"
|
||||
}
|
||||
@ -0,0 +1,3 @@
|
||||
# https://www.robotstxt.org/robotstxt.html
|
||||
User-agent: *
|
||||
Disallow:
|
||||
@ -0,0 +1,38 @@
|
||||
.App {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.App-logo {
|
||||
height: 40vmin;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.App-logo {
|
||||
animation: App-logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.App-header {
|
||||
background-color: #282c34;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: calc(10px + 2vmin);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.App-link {
|
||||
color: #61dafb;
|
||||
}
|
||||
|
||||
@keyframes App-logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,9 @@
|
||||
import React from 'react';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import App from './App';
|
||||
|
||||
test('renders learn react link', () => {
|
||||
render(<App />);
|
||||
const linkElement = screen.getByText(/learn react/i);
|
||||
expect(linkElement).toBeInTheDocument();
|
||||
});
|
||||
@ -0,0 +1,26 @@
|
||||
import React from 'react';
|
||||
import logo from './logo.svg';
|
||||
import './App.css';
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<div className="App">
|
||||
<header className="App-header">
|
||||
<img src={logo} className="App-logo" alt="logo" />
|
||||
<p>
|
||||
Edit <code>src/App.tsx</code> and save to reload.
|
||||
</p>
|
||||
<a
|
||||
className="App-link"
|
||||
href="https://reactjs.org"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Learn React
|
||||
</a>
|
||||
</header>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
@ -0,0 +1,13 @@
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
|
||||
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
|
||||
sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
|
||||
monospace;
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import './index.css';
|
||||
import App from './App';
|
||||
import reportWebVitals from './reportWebVitals';
|
||||
|
||||
const root = ReactDOM.createRoot(
|
||||
document.getElementById('root') as HTMLElement
|
||||
);
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
);
|
||||
|
||||
// If you want to start measuring performance in your app, pass a function
|
||||
// to log results (for example: reportWebVitals(console.log))
|
||||
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
|
||||
reportWebVitals();
|
||||
|
After Width: | Height: | Size: 2.6 KiB |
@ -0,0 +1 @@
|
||||
/// <reference types="react-scripts" />
|
||||
@ -0,0 +1,15 @@
|
||||
import { ReportHandler } from 'web-vitals';
|
||||
|
||||
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
|
||||
if (onPerfEntry && onPerfEntry instanceof Function) {
|
||||
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
|
||||
getCLS(onPerfEntry);
|
||||
getFID(onPerfEntry);
|
||||
getFCP(onPerfEntry);
|
||||
getLCP(onPerfEntry);
|
||||
getTTFB(onPerfEntry);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export default reportWebVitals;
|
||||
@ -0,0 +1,5 @@
|
||||
// jest-dom adds custom jest matchers for asserting on DOM nodes.
|
||||
// allows you to do things like:
|
||||
// expect(element).toHaveTextContent(/react/i)
|
||||
// learn more: https://github.com/testing-library/jest-dom
|
||||
import '@testing-library/jest-dom';
|
||||
@ -0,0 +1,20 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@ -0,0 +1,291 @@
|
||||
import SubscribedApp from "./_pages/SubscribedApp"
|
||||
import { UpdateNotification } from "./components/UpdateNotification"
|
||||
import {
|
||||
QueryClient,
|
||||
QueryClientProvider
|
||||
} from "@tanstack/react-query"
|
||||
import { useEffect, useState, useCallback } from "react"
|
||||
import {
|
||||
Toast,
|
||||
ToastDescription,
|
||||
ToastProvider,
|
||||
ToastTitle,
|
||||
ToastViewport
|
||||
} from "./components/ui/toast"
|
||||
import { ToastContext } from "./contexts/toast"
|
||||
import { WelcomeScreen } from "./components/WelcomeScreen"
|
||||
import { SettingsDialog } from "./components/Settings/SettingsDialog"
|
||||
|
||||
// Create a React Query client
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 0,
|
||||
gcTime: Infinity,
|
||||
retry: 1,
|
||||
refetchOnWindowFocus: false
|
||||
},
|
||||
mutations: {
|
||||
retry: 1
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Root component that provides the QueryClient
|
||||
function App() {
|
||||
const [toastState, setToastState] = useState({
|
||||
open: false,
|
||||
title: "",
|
||||
description: "",
|
||||
variant: "neutral" as const
|
||||
})
|
||||
const [credits, setCredits] = useState<number>(999) // Unlimited credits
|
||||
const [currentLanguage, setCurrentLanguage] = useState<string>("python")
|
||||
const [isInitialized, setIsInitialized] = useState(false)
|
||||
const [hasApiKey, setHasApiKey] = useState(false)
|
||||
const [apiKeyDialogOpen, setApiKeyDialogOpen] = useState(false)
|
||||
// Note: Model selection is now handled via separate extraction/solution/debugging model settings
|
||||
|
||||
const [isSettingsOpen, setIsSettingsOpen] = useState(false)
|
||||
|
||||
// Set unlimited credits
|
||||
const updateCredits = useCallback(() => {
|
||||
setCredits(999) // No credit limit in this version
|
||||
window.__CREDITS__ = 999
|
||||
}, [])
|
||||
|
||||
// Helper function to safely update language
|
||||
const updateLanguage = useCallback((newLanguage: string) => {
|
||||
setCurrentLanguage(newLanguage)
|
||||
window.__LANGUAGE__ = newLanguage
|
||||
}, [])
|
||||
|
||||
// Helper function to mark initialization complete
|
||||
const markInitialized = useCallback(() => {
|
||||
setIsInitialized(true)
|
||||
window.__IS_INITIALIZED__ = true
|
||||
}, [])
|
||||
|
||||
// Show toast method
|
||||
const showToast = useCallback(
|
||||
(
|
||||
title: string,
|
||||
description: string,
|
||||
variant: "neutral" | "success" | "error"
|
||||
) => {
|
||||
setToastState({
|
||||
open: true,
|
||||
title,
|
||||
description,
|
||||
variant
|
||||
})
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
// Check for OpenAI API key and prompt if not found
|
||||
useEffect(() => {
|
||||
const checkApiKey = async () => {
|
||||
try {
|
||||
const hasKey = await window.electronAPI.checkApiKey()
|
||||
setHasApiKey(hasKey)
|
||||
|
||||
// If no API key is found, show the settings dialog after a short delay
|
||||
if (!hasKey) {
|
||||
setTimeout(() => {
|
||||
setIsSettingsOpen(true)
|
||||
}, 1000)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to check API key:", error)
|
||||
}
|
||||
}
|
||||
|
||||
if (isInitialized) {
|
||||
checkApiKey()
|
||||
}
|
||||
}, [isInitialized])
|
||||
|
||||
// Initialize dropdown handler
|
||||
useEffect(() => {
|
||||
if (isInitialized) {
|
||||
// Process all types of dropdown elements with a shorter delay
|
||||
const timer = setTimeout(() => {
|
||||
// Find both native select elements and custom dropdowns
|
||||
const selectElements = document.querySelectorAll('select');
|
||||
const customDropdowns = document.querySelectorAll('.dropdown-trigger, [role="combobox"], button:has(.dropdown)');
|
||||
|
||||
// Enable native selects
|
||||
selectElements.forEach(dropdown => {
|
||||
dropdown.disabled = false;
|
||||
});
|
||||
|
||||
// Enable custom dropdowns by removing any disabled attributes
|
||||
customDropdowns.forEach(dropdown => {
|
||||
if (dropdown instanceof HTMLElement) {
|
||||
dropdown.removeAttribute('disabled');
|
||||
dropdown.setAttribute('aria-disabled', 'false');
|
||||
}
|
||||
});
|
||||
|
||||
console.log(`Enabled ${selectElements.length} select elements and ${customDropdowns.length} custom dropdowns`);
|
||||
}, 1000);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [isInitialized]);
|
||||
|
||||
// Listen for settings dialog open requests
|
||||
useEffect(() => {
|
||||
const unsubscribeSettings = window.electronAPI.onShowSettings(() => {
|
||||
console.log("Show settings dialog requested");
|
||||
setIsSettingsOpen(true);
|
||||
});
|
||||
|
||||
return () => {
|
||||
unsubscribeSettings();
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Initialize basic app state
|
||||
useEffect(() => {
|
||||
// Load config and set values
|
||||
const initializeApp = async () => {
|
||||
try {
|
||||
// Set unlimited credits
|
||||
updateCredits()
|
||||
|
||||
// Load config including language and model settings
|
||||
const config = await window.electronAPI.getConfig()
|
||||
|
||||
// Load language preference
|
||||
if (config && config.language) {
|
||||
updateLanguage(config.language)
|
||||
} else {
|
||||
updateLanguage("python")
|
||||
}
|
||||
|
||||
// Model settings are now managed through the settings dialog
|
||||
// and stored in config as extractionModel, solutionModel, and debuggingModel
|
||||
|
||||
markInitialized()
|
||||
} catch (error) {
|
||||
console.error("Failed to initialize app:", error)
|
||||
// Fallback to defaults
|
||||
updateLanguage("python")
|
||||
markInitialized()
|
||||
}
|
||||
}
|
||||
|
||||
initializeApp()
|
||||
|
||||
// Event listeners for process events
|
||||
const onApiKeyInvalid = () => {
|
||||
showToast(
|
||||
"API Key Invalid",
|
||||
"Your OpenAI API key appears to be invalid or has insufficient credits",
|
||||
"error"
|
||||
)
|
||||
setApiKeyDialogOpen(true)
|
||||
}
|
||||
|
||||
// Setup API key invalid listener
|
||||
window.electronAPI.onApiKeyInvalid(onApiKeyInvalid)
|
||||
|
||||
// Define a no-op handler for solution success
|
||||
const unsubscribeSolutionSuccess = window.electronAPI.onSolutionSuccess(
|
||||
() => {
|
||||
console.log("Solution success - no credits deducted in this version")
|
||||
// No credit deduction in this version
|
||||
}
|
||||
)
|
||||
|
||||
// Cleanup function
|
||||
return () => {
|
||||
window.electronAPI.removeListener("API_KEY_INVALID", onApiKeyInvalid)
|
||||
unsubscribeSolutionSuccess()
|
||||
window.__IS_INITIALIZED__ = false
|
||||
setIsInitialized(false)
|
||||
}
|
||||
}, [updateCredits, updateLanguage, markInitialized, showToast])
|
||||
|
||||
// API Key dialog management
|
||||
const handleOpenSettings = useCallback(() => {
|
||||
console.log('Opening settings dialog');
|
||||
setIsSettingsOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleCloseSettings = useCallback((open: boolean) => {
|
||||
console.log('Settings dialog state changed:', open);
|
||||
setIsSettingsOpen(open);
|
||||
}, []);
|
||||
|
||||
const handleApiKeySave = useCallback(async (apiKey: string) => {
|
||||
try {
|
||||
await window.electronAPI.updateConfig({ apiKey })
|
||||
setHasApiKey(true)
|
||||
showToast("Success", "API key saved successfully", "success")
|
||||
|
||||
// Reload app after a short delay to reinitialize with the new API key
|
||||
setTimeout(() => {
|
||||
window.location.reload()
|
||||
}, 1500)
|
||||
} catch (error) {
|
||||
console.error("Failed to save API key:", error)
|
||||
showToast("Error", "Failed to save API key", "error")
|
||||
}
|
||||
}, [showToast])
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<ToastContext.Provider value={{ showToast }}>
|
||||
<div className="relative">
|
||||
{isInitialized ? (
|
||||
hasApiKey ? (
|
||||
<SubscribedApp
|
||||
credits={credits}
|
||||
currentLanguage={currentLanguage}
|
||||
setLanguage={updateLanguage}
|
||||
/>
|
||||
) : (
|
||||
<WelcomeScreen onOpenSettings={handleOpenSettings} />
|
||||
)
|
||||
) : (
|
||||
<div className="min-h-screen bg-black flex items-center justify-center">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<div className="w-6 h-6 border-2 border-white/20 border-t-white/80 rounded-full animate-spin"></div>
|
||||
<p className="text-white/60 text-sm">
|
||||
Initializing...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<UpdateNotification />
|
||||
</div>
|
||||
|
||||
{/* Settings Dialog */}
|
||||
<SettingsDialog
|
||||
open={isSettingsOpen}
|
||||
onOpenChange={handleCloseSettings}
|
||||
/>
|
||||
|
||||
<Toast
|
||||
open={toastState.open}
|
||||
onOpenChange={(open) =>
|
||||
setToastState((prev) => ({ ...prev, open }))
|
||||
}
|
||||
variant={toastState.variant}
|
||||
duration={1500}
|
||||
>
|
||||
<ToastTitle>{toastState.title}</ToastTitle>
|
||||
<ToastDescription>{toastState.description}</ToastDescription>
|
||||
</Toast>
|
||||
<ToastViewport />
|
||||
</ToastContext.Provider>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
export default App
|
||||
@ -0,0 +1,466 @@
|
||||
// Debug.tsx
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
import React, { useEffect, useRef, useState } from "react"
|
||||
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter"
|
||||
import { dracula } from "react-syntax-highlighter/dist/esm/styles/prism"
|
||||
import ScreenshotQueue from "../components/Queue/ScreenshotQueue"
|
||||
import SolutionCommands from "../components/Solutions/SolutionCommands"
|
||||
import { Screenshot } from "../types/screenshots"
|
||||
import { ComplexitySection, ContentSection } from "./Solutions"
|
||||
import { useToast } from "../contexts/toast"
|
||||
|
||||
const CodeSection = ({
|
||||
title,
|
||||
code,
|
||||
isLoading,
|
||||
currentLanguage
|
||||
}: {
|
||||
title: string
|
||||
code: React.ReactNode
|
||||
isLoading: boolean
|
||||
currentLanguage: string
|
||||
}) => (
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-[13px] font-medium text-white tracking-wide"></h2>
|
||||
{isLoading ? (
|
||||
<div className="space-y-1.5">
|
||||
<div className="mt-4 flex">
|
||||
<p className="text-xs bg-gradient-to-r from-gray-300 via-gray-100 to-gray-300 bg-clip-text text-transparent animate-pulse">
|
||||
Loading solutions...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="w-full">
|
||||
<SyntaxHighlighter
|
||||
showLineNumbers
|
||||
language={currentLanguage == "golang" ? "go" : currentLanguage}
|
||||
style={dracula}
|
||||
customStyle={{
|
||||
maxWidth: "100%",
|
||||
margin: 0,
|
||||
padding: "1rem",
|
||||
whiteSpace: "pre-wrap",
|
||||
wordBreak: "break-all",
|
||||
backgroundColor: "rgba(22, 27, 34, 0.5)"
|
||||
}}
|
||||
wrapLongLines={true}
|
||||
>
|
||||
{code as string}
|
||||
</SyntaxHighlighter>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
|
||||
async function fetchScreenshots(): Promise<Screenshot[]> {
|
||||
try {
|
||||
const existing = await window.electronAPI.getScreenshots()
|
||||
console.log("Raw screenshot data in Debug:", existing)
|
||||
return (Array.isArray(existing) ? existing : []).map((p) => ({
|
||||
id: p.path,
|
||||
path: p.path,
|
||||
preview: p.preview,
|
||||
timestamp: Date.now()
|
||||
}))
|
||||
} catch (error) {
|
||||
console.error("Error loading screenshots:", error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
interface DebugProps {
|
||||
isProcessing: boolean
|
||||
setIsProcessing: (isProcessing: boolean) => void
|
||||
currentLanguage: string
|
||||
setLanguage: (language: string) => void
|
||||
}
|
||||
|
||||
const Debug: React.FC<DebugProps> = ({
|
||||
isProcessing,
|
||||
setIsProcessing,
|
||||
currentLanguage,
|
||||
setLanguage
|
||||
}) => {
|
||||
const [tooltipVisible, setTooltipVisible] = useState(false)
|
||||
const [tooltipHeight, setTooltipHeight] = useState(0)
|
||||
const { showToast } = useToast()
|
||||
|
||||
const { data: screenshots = [], refetch } = useQuery<Screenshot[]>({
|
||||
queryKey: ["screenshots"],
|
||||
queryFn: fetchScreenshots,
|
||||
staleTime: Infinity,
|
||||
gcTime: Infinity,
|
||||
refetchOnWindowFocus: false
|
||||
})
|
||||
|
||||
const [newCode, setNewCode] = useState<string | null>(null)
|
||||
const [thoughtsData, setThoughtsData] = useState<string[] | null>(null)
|
||||
const [timeComplexityData, setTimeComplexityData] = useState<string | null>(
|
||||
null
|
||||
)
|
||||
const [spaceComplexityData, setSpaceComplexityData] = useState<string | null>(
|
||||
null
|
||||
)
|
||||
const [debugAnalysis, setDebugAnalysis] = useState<string | null>(null)
|
||||
|
||||
const queryClient = useQueryClient()
|
||||
const contentRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
// Try to get the new solution data from cache first
|
||||
const newSolution = queryClient.getQueryData(["new_solution"]) as {
|
||||
code: string
|
||||
debug_analysis: string
|
||||
thoughts: string[]
|
||||
time_complexity: string
|
||||
space_complexity: string
|
||||
} | null
|
||||
|
||||
// If we have cached data, set all state variables to the cached data
|
||||
if (newSolution) {
|
||||
console.log("Found cached debug solution:", newSolution);
|
||||
|
||||
if (newSolution.debug_analysis) {
|
||||
// Store the debug analysis in its own state variable
|
||||
setDebugAnalysis(newSolution.debug_analysis);
|
||||
// Set code separately for the code section
|
||||
setNewCode(newSolution.code || "// Debug mode - see analysis below");
|
||||
|
||||
// Process thoughts/analysis points
|
||||
if (newSolution.debug_analysis.includes('\n\n')) {
|
||||
const sections = newSolution.debug_analysis.split('\n\n').filter(Boolean);
|
||||
// Pick first few sections as thoughts
|
||||
setThoughtsData(sections.slice(0, 3));
|
||||
} else {
|
||||
setThoughtsData(["Debug analysis based on your screenshots"]);
|
||||
}
|
||||
} else {
|
||||
// Fallback to code or default
|
||||
setNewCode(newSolution.code || "// No analysis available");
|
||||
setThoughtsData(newSolution.thoughts || ["Debug analysis based on your screenshots"]);
|
||||
}
|
||||
setTimeComplexityData(newSolution.time_complexity || "N/A - Debug mode")
|
||||
setSpaceComplexityData(newSolution.space_complexity || "N/A - Debug mode")
|
||||
setIsProcessing(false)
|
||||
}
|
||||
|
||||
// Set up event listeners
|
||||
const cleanupFunctions = [
|
||||
window.electronAPI.onScreenshotTaken(() => refetch()),
|
||||
window.electronAPI.onResetView(() => refetch()),
|
||||
window.electronAPI.onDebugSuccess((data) => {
|
||||
console.log("Debug success event received with data:", data);
|
||||
queryClient.setQueryData(["new_solution"], data);
|
||||
|
||||
// Also update local state for immediate rendering
|
||||
if (data.debug_analysis) {
|
||||
// Store the debug analysis in its own state variable
|
||||
setDebugAnalysis(data.debug_analysis);
|
||||
// Set code separately for the code section
|
||||
setNewCode(data.code || "// Debug mode - see analysis below");
|
||||
|
||||
// Process thoughts/analysis points
|
||||
if (data.debug_analysis.includes('\n\n')) {
|
||||
const sections = data.debug_analysis.split('\n\n').filter(Boolean);
|
||||
// Pick first few sections as thoughts
|
||||
setThoughtsData(sections.slice(0, 3));
|
||||
} else if (data.debug_analysis.includes('\n')) {
|
||||
// Try to find bullet points or numbered lists
|
||||
const lines = data.debug_analysis.split('\n');
|
||||
const bulletPoints = lines.filter(line =>
|
||||
line.trim().match(/^[\d*\-•]+\s/) ||
|
||||
line.trim().match(/^[A-Z][\d\.\)\:]/) ||
|
||||
line.includes(':') && line.length < 100
|
||||
);
|
||||
|
||||
if (bulletPoints.length > 0) {
|
||||
setThoughtsData(bulletPoints.slice(0, 5));
|
||||
} else {
|
||||
setThoughtsData(["Debug analysis based on your screenshots"]);
|
||||
}
|
||||
} else {
|
||||
setThoughtsData(["Debug analysis based on your screenshots"]);
|
||||
}
|
||||
} else {
|
||||
// Fallback to code or default
|
||||
setNewCode(data.code || "// No analysis available");
|
||||
setThoughtsData(data.thoughts || ["Debug analysis based on your screenshots"]);
|
||||
setDebugAnalysis(null);
|
||||
}
|
||||
setTimeComplexityData(data.time_complexity || "N/A - Debug mode");
|
||||
setSpaceComplexityData(data.space_complexity || "N/A - Debug mode");
|
||||
|
||||
setIsProcessing(false);
|
||||
}),
|
||||
|
||||
window.electronAPI.onDebugStart(() => {
|
||||
setIsProcessing(true)
|
||||
}),
|
||||
window.electronAPI.onDebugError((error: string) => {
|
||||
showToast(
|
||||
"Processing Failed",
|
||||
"There was an error debugging your code.",
|
||||
"error"
|
||||
)
|
||||
setIsProcessing(false)
|
||||
console.error("Processing error:", error)
|
||||
})
|
||||
]
|
||||
|
||||
// Set up resize observer
|
||||
const updateDimensions = () => {
|
||||
if (contentRef.current) {
|
||||
let contentHeight = contentRef.current.scrollHeight
|
||||
const contentWidth = contentRef.current.scrollWidth
|
||||
if (tooltipVisible) {
|
||||
contentHeight += tooltipHeight
|
||||
}
|
||||
window.electronAPI.updateContentDimensions({
|
||||
width: contentWidth,
|
||||
height: contentHeight
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const resizeObserver = new ResizeObserver(updateDimensions)
|
||||
if (contentRef.current) {
|
||||
resizeObserver.observe(contentRef.current)
|
||||
}
|
||||
updateDimensions()
|
||||
|
||||
return () => {
|
||||
resizeObserver.disconnect()
|
||||
cleanupFunctions.forEach((cleanup) => cleanup())
|
||||
}
|
||||
}, [queryClient, setIsProcessing])
|
||||
|
||||
const handleTooltipVisibilityChange = (visible: boolean, height: number) => {
|
||||
setTooltipVisible(visible)
|
||||
setTooltipHeight(height)
|
||||
}
|
||||
|
||||
const handleDeleteExtraScreenshot = async (index: number) => {
|
||||
const screenshotToDelete = screenshots[index]
|
||||
|
||||
try {
|
||||
const response = await window.electronAPI.deleteScreenshot(
|
||||
screenshotToDelete.path
|
||||
)
|
||||
|
||||
if (response.success) {
|
||||
refetch()
|
||||
} else {
|
||||
console.error("Failed to delete extra screenshot:", response.error)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error deleting extra screenshot:", error)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={contentRef} className="relative">
|
||||
<div className="space-y-3 px-4 py-3">
|
||||
{/* Conditionally render the screenshot queue */}
|
||||
<div className="bg-transparent w-fit">
|
||||
<div className="pb-3">
|
||||
<div className="space-y-3 w-fit">
|
||||
<ScreenshotQueue
|
||||
screenshots={screenshots}
|
||||
onDeleteScreenshot={handleDeleteExtraScreenshot}
|
||||
isLoading={isProcessing}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Navbar of commands with the tooltip */}
|
||||
<SolutionCommands
|
||||
screenshots={screenshots}
|
||||
onTooltipVisibilityChange={handleTooltipVisibilityChange}
|
||||
isProcessing={isProcessing}
|
||||
extraScreenshots={screenshots}
|
||||
credits={window.__CREDITS__}
|
||||
currentLanguage={currentLanguage}
|
||||
setLanguage={setLanguage}
|
||||
/>
|
||||
|
||||
{/* Main Content */}
|
||||
<div className="w-full text-sm text-black bg-black/60 rounded-md">
|
||||
<div className="rounded-lg overflow-hidden">
|
||||
<div className="px-4 py-3 space-y-4">
|
||||
{/* Thoughts Section */}
|
||||
<ContentSection
|
||||
title="What I Changed"
|
||||
content={
|
||||
thoughtsData && (
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1">
|
||||
{thoughtsData.map((thought, index) => (
|
||||
<div key={index} className="flex items-start gap-2">
|
||||
<div className="w-1 h-1 rounded-full bg-blue-400/80 mt-2 shrink-0" />
|
||||
<div>{thought}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
isLoading={!thoughtsData}
|
||||
/>
|
||||
|
||||
{/* Code Section */}
|
||||
<CodeSection
|
||||
title="Original Code"
|
||||
code={newCode}
|
||||
isLoading={!newCode}
|
||||
currentLanguage={currentLanguage}
|
||||
/>
|
||||
|
||||
{/* Debug Analysis Section */}
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-[13px] font-medium text-white tracking-wide">Analysis & Improvements</h2>
|
||||
{!debugAnalysis ? (
|
||||
<div className="space-y-1.5">
|
||||
<div className="mt-4 flex">
|
||||
<p className="text-xs bg-gradient-to-r from-gray-300 via-gray-100 to-gray-300 bg-clip-text text-transparent animate-pulse">
|
||||
Loading debug analysis...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="w-full bg-black/30 rounded-md p-4 text-[13px] leading-[1.4] text-gray-100 whitespace-pre-wrap overflow-auto max-h-[600px]">
|
||||
{/* Process the debug analysis text by sections and lines */}
|
||||
{(() => {
|
||||
// First identify key sections based on common patterns in the debug output
|
||||
const sections = [];
|
||||
let currentSection = { title: '', content: [] };
|
||||
|
||||
// Split by possible section headers (### or ##)
|
||||
const mainSections = debugAnalysis.split(/(?=^#{1,3}\s|^\*\*\*|^\s*[A-Z][\w\s]+\s*$)/m);
|
||||
|
||||
// Filter out empty sections and process each one
|
||||
mainSections.filter(Boolean).forEach(sectionText => {
|
||||
// First line might be a header
|
||||
const lines = sectionText.split('\n');
|
||||
let title = '';
|
||||
let startLineIndex = 0;
|
||||
|
||||
// Check if first line is a header
|
||||
if (lines[0] && (lines[0].startsWith('#') || lines[0].startsWith('**') ||
|
||||
lines[0].match(/^[A-Z][\w\s]+$/) || lines[0].includes('Issues') ||
|
||||
lines[0].includes('Improvements') || lines[0].includes('Optimizations'))) {
|
||||
title = lines[0].replace(/^#+\s*|\*\*/g, '');
|
||||
startLineIndex = 1;
|
||||
}
|
||||
|
||||
// Add the section
|
||||
sections.push({
|
||||
title,
|
||||
content: lines.slice(startLineIndex).filter(Boolean)
|
||||
});
|
||||
});
|
||||
|
||||
// Render the processed sections
|
||||
return sections.map((section, sectionIndex) => (
|
||||
<div key={sectionIndex} className="mb-6">
|
||||
{section.title && (
|
||||
<div className="font-bold text-white/90 text-[14px] mb-2 pb-1 border-b border-white/10">
|
||||
{section.title}
|
||||
</div>
|
||||
)}
|
||||
<div className="pl-1">
|
||||
{section.content.map((line, lineIndex) => {
|
||||
// Handle code blocks - detect full code blocks
|
||||
if (line.trim().startsWith('```')) {
|
||||
// If we find the start of a code block, collect all lines until the end
|
||||
if (line.trim() === '```' || line.trim().startsWith('```')) {
|
||||
// Find end of this code block
|
||||
const codeBlockEndIndex = section.content.findIndex(
|
||||
(l, i) => i > lineIndex && l.trim() === '```'
|
||||
);
|
||||
|
||||
if (codeBlockEndIndex > lineIndex) {
|
||||
// Extract language if specified
|
||||
const langMatch = line.trim().match(/```(\w+)/);
|
||||
const language = langMatch ? langMatch[1] : '';
|
||||
|
||||
// Get the code content
|
||||
const codeContent = section.content
|
||||
.slice(lineIndex + 1, codeBlockEndIndex)
|
||||
.join('\n');
|
||||
|
||||
// Skip ahead in our loop
|
||||
lineIndex = codeBlockEndIndex;
|
||||
|
||||
return (
|
||||
<div key={lineIndex} className="font-mono text-xs bg-black/50 p-3 my-2 rounded overflow-x-auto">
|
||||
{codeContent}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle bullet points
|
||||
if (line.trim().match(/^[\-*•]\s/) || line.trim().match(/^\d+\.\s/)) {
|
||||
return (
|
||||
<div key={lineIndex} className="flex items-start gap-2 my-1.5">
|
||||
<div className="w-1.5 h-1.5 rounded-full bg-blue-400/80 mt-2 shrink-0" />
|
||||
<div className="flex-1">
|
||||
{line.replace(/^[\-*•]\s|^\d+\.\s/, '')}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Handle inline code
|
||||
if (line.includes('`')) {
|
||||
const parts = line.split(/(`[^`]+`)/g);
|
||||
return (
|
||||
<div key={lineIndex} className="my-1.5">
|
||||
{parts.map((part, partIndex) => {
|
||||
if (part.startsWith('`') && part.endsWith('`')) {
|
||||
return <span key={partIndex} className="font-mono bg-black/30 px-1 py-0.5 rounded">{part.slice(1, -1)}</span>;
|
||||
}
|
||||
return <span key={partIndex}>{part}</span>;
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Handle sub-headers
|
||||
if (line.trim().match(/^#+\s/) || (line.trim().match(/^[A-Z][\w\s]+:/) && line.length < 60)) {
|
||||
return (
|
||||
<div key={lineIndex} className="font-semibold text-white/80 mt-3 mb-1">
|
||||
{line.replace(/^#+\s+/, '')}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Regular text
|
||||
return <div key={lineIndex} className="my-1.5">{line}</div>;
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
));
|
||||
})()}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Complexity Section */}
|
||||
<ComplexitySection
|
||||
timeComplexity={timeComplexityData}
|
||||
spaceComplexity={spaceComplexityData}
|
||||
isLoading={!timeComplexityData || !spaceComplexityData}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Debug
|
||||
@ -0,0 +1,162 @@
|
||||
import React, { useState, useEffect, useRef } from "react"
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import ScreenshotQueue from "../components/Queue/ScreenshotQueue"
|
||||
import QueueCommands from "../components/Queue/QueueCommands"
|
||||
|
||||
import { useToast } from "../contexts/toast"
|
||||
import { Screenshot } from "../types/screenshots"
|
||||
|
||||
async function fetchScreenshots(): Promise<Screenshot[]> {
|
||||
try {
|
||||
const existing = await window.electronAPI.getScreenshots()
|
||||
return existing
|
||||
} catch (error) {
|
||||
console.error("Error loading screenshots:", error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
interface QueueProps {
|
||||
setView: (view: "queue" | "solutions" | "debug") => void
|
||||
credits: number
|
||||
currentLanguage: string
|
||||
setLanguage: (language: string) => void
|
||||
}
|
||||
|
||||
const Queue: React.FC<QueueProps> = ({
|
||||
setView,
|
||||
credits,
|
||||
currentLanguage,
|
||||
setLanguage
|
||||
}) => {
|
||||
const { showToast } = useToast()
|
||||
|
||||
const [isTooltipVisible, setIsTooltipVisible] = useState(false)
|
||||
const [tooltipHeight, setTooltipHeight] = useState(0)
|
||||
const contentRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const {
|
||||
data: screenshots = [],
|
||||
isLoading,
|
||||
refetch
|
||||
} = useQuery<Screenshot[]>({
|
||||
queryKey: ["screenshots"],
|
||||
queryFn: fetchScreenshots,
|
||||
staleTime: Infinity,
|
||||
gcTime: Infinity,
|
||||
refetchOnWindowFocus: false
|
||||
})
|
||||
|
||||
const handleDeleteScreenshot = async (index: number) => {
|
||||
const screenshotToDelete = screenshots[index]
|
||||
|
||||
try {
|
||||
const response = await window.electronAPI.deleteScreenshot(
|
||||
screenshotToDelete.path
|
||||
)
|
||||
|
||||
if (response.success) {
|
||||
refetch() // Refetch screenshots instead of managing state directly
|
||||
} else {
|
||||
console.error("Failed to delete screenshot:", response.error)
|
||||
showToast("Error", "Failed to delete the screenshot file", "error")
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error deleting screenshot:", error)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
// Height update logic
|
||||
const updateDimensions = () => {
|
||||
if (contentRef.current) {
|
||||
let contentHeight = contentRef.current.scrollHeight
|
||||
const contentWidth = contentRef.current.scrollWidth
|
||||
if (isTooltipVisible) {
|
||||
contentHeight += tooltipHeight
|
||||
}
|
||||
window.electronAPI.updateContentDimensions({
|
||||
width: contentWidth,
|
||||
height: contentHeight
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize resize observer
|
||||
const resizeObserver = new ResizeObserver(updateDimensions)
|
||||
if (contentRef.current) {
|
||||
resizeObserver.observe(contentRef.current)
|
||||
}
|
||||
updateDimensions()
|
||||
|
||||
// Set up event listeners
|
||||
const cleanupFunctions = [
|
||||
window.electronAPI.onScreenshotTaken(() => refetch()),
|
||||
window.electronAPI.onResetView(() => refetch()),
|
||||
window.electronAPI.onDeleteLastScreenshot(async () => {
|
||||
if (screenshots.length > 0) {
|
||||
const lastScreenshot = screenshots[screenshots.length - 1];
|
||||
await handleDeleteScreenshot(screenshots.length - 1);
|
||||
// Toast removed as requested
|
||||
} else {
|
||||
showToast("No Screenshots", "There are no screenshots to delete", "neutral");
|
||||
}
|
||||
}),
|
||||
window.electronAPI.onSolutionError((error: string) => {
|
||||
showToast(
|
||||
"Processing Failed",
|
||||
"There was an error processing your screenshots.",
|
||||
"error"
|
||||
)
|
||||
setView("queue") // Revert to queue if processing fails
|
||||
console.error("Processing error:", error)
|
||||
}),
|
||||
window.electronAPI.onProcessingNoScreenshots(() => {
|
||||
showToast(
|
||||
"No Screenshots",
|
||||
"There are no screenshots to process.",
|
||||
"neutral"
|
||||
)
|
||||
}),
|
||||
// Removed out of credits handler - unlimited credits in this version
|
||||
]
|
||||
|
||||
return () => {
|
||||
resizeObserver.disconnect()
|
||||
cleanupFunctions.forEach((cleanup) => cleanup())
|
||||
}
|
||||
}, [isTooltipVisible, tooltipHeight, screenshots])
|
||||
|
||||
const handleTooltipVisibilityChange = (visible: boolean, height: number) => {
|
||||
setIsTooltipVisible(visible)
|
||||
setTooltipHeight(height)
|
||||
}
|
||||
|
||||
const handleOpenSettings = () => {
|
||||
window.electronAPI.openSettingsPortal();
|
||||
};
|
||||
|
||||
return (
|
||||
<div ref={contentRef} className={`bg-transparent w-1/2`}>
|
||||
<div className="px-4 py-3">
|
||||
<div className="space-y-3 w-fit">
|
||||
<ScreenshotQueue
|
||||
isLoading={false}
|
||||
screenshots={screenshots}
|
||||
onDeleteScreenshot={handleDeleteScreenshot}
|
||||
/>
|
||||
|
||||
<QueueCommands
|
||||
onTooltipVisibilityChange={handleTooltipVisibilityChange}
|
||||
screenshotCount={screenshots.length}
|
||||
credits={credits}
|
||||
currentLanguage={currentLanguage}
|
||||
setLanguage={setLanguage}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Queue
|
||||
@ -0,0 +1,549 @@
|
||||
// Solutions.tsx
|
||||
import React, { useState, useEffect, useRef } from "react"
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter"
|
||||
import { dracula } from "react-syntax-highlighter/dist/esm/styles/prism"
|
||||
|
||||
import ScreenshotQueue from "../components/Queue/ScreenshotQueue"
|
||||
|
||||
import { ProblemStatementData } from "../types/solutions"
|
||||
import SolutionCommands from "../components/Solutions/SolutionCommands"
|
||||
import Debug from "./Debug"
|
||||
import { useToast } from "../contexts/toast"
|
||||
import { COMMAND_KEY } from "../utils/platform"
|
||||
|
||||
export const ContentSection = ({
|
||||
title,
|
||||
content,
|
||||
isLoading
|
||||
}: {
|
||||
title: string
|
||||
content: React.ReactNode
|
||||
isLoading: boolean
|
||||
}) => (
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-[13px] font-medium text-white tracking-wide">
|
||||
{title}
|
||||
</h2>
|
||||
{isLoading ? (
|
||||
<div className="mt-4 flex">
|
||||
<p className="text-xs bg-gradient-to-r from-gray-300 via-gray-100 to-gray-300 bg-clip-text text-transparent animate-pulse">
|
||||
Extracting problem statement...
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-[13px] leading-[1.4] text-gray-100 max-w-[600px]">
|
||||
{content}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
const SolutionSection = ({
|
||||
title,
|
||||
content,
|
||||
isLoading,
|
||||
currentLanguage
|
||||
}: {
|
||||
title: string
|
||||
content: React.ReactNode
|
||||
isLoading: boolean
|
||||
currentLanguage: string
|
||||
}) => (
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-[13px] font-medium text-white tracking-wide">
|
||||
{title}
|
||||
</h2>
|
||||
{isLoading ? (
|
||||
<div className="space-y-1.5">
|
||||
<div className="mt-4 flex">
|
||||
<p className="text-xs bg-gradient-to-r from-gray-300 via-gray-100 to-gray-300 bg-clip-text text-transparent animate-pulse">
|
||||
Loading solutions...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="w-full">
|
||||
<SyntaxHighlighter
|
||||
showLineNumbers
|
||||
language={currentLanguage == "golang" ? "go" : currentLanguage}
|
||||
style={dracula}
|
||||
customStyle={{
|
||||
maxWidth: "100%",
|
||||
margin: 0,
|
||||
padding: "1rem",
|
||||
whiteSpace: "pre-wrap",
|
||||
wordBreak: "break-all",
|
||||
backgroundColor: "rgba(22, 27, 34, 0.5)"
|
||||
}}
|
||||
wrapLongLines={true}
|
||||
>
|
||||
{content as string}
|
||||
</SyntaxHighlighter>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
|
||||
export const ComplexitySection = ({
|
||||
timeComplexity,
|
||||
spaceComplexity,
|
||||
isLoading
|
||||
}: {
|
||||
timeComplexity: string | null
|
||||
spaceComplexity: string | null
|
||||
isLoading: boolean
|
||||
}) => {
|
||||
// Helper to ensure we have proper complexity values
|
||||
const formatComplexity = (complexity: string | null): string => {
|
||||
if (!complexity) return "O(n) - Linear time/space complexity";
|
||||
|
||||
// Return the complexity as is if it already has Big O notation
|
||||
if (complexity.match(/O\([^)]+\)/i)) {
|
||||
return complexity;
|
||||
}
|
||||
|
||||
// Otherwise, add a default Big O
|
||||
return `O(n) - ${complexity}`;
|
||||
};
|
||||
|
||||
const formattedTimeComplexity = formatComplexity(timeComplexity);
|
||||
const formattedSpaceComplexity = formatComplexity(spaceComplexity);
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-[13px] font-medium text-white tracking-wide">
|
||||
Complexity
|
||||
</h2>
|
||||
{isLoading ? (
|
||||
<p className="text-xs bg-gradient-to-r from-gray-300 via-gray-100 to-gray-300 bg-clip-text text-transparent animate-pulse">
|
||||
Calculating complexity...
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<div className="text-[13px] leading-[1.4] text-gray-100 bg-white/5 rounded-md p-3">
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="w-1 h-1 rounded-full bg-blue-400/80 mt-2 shrink-0" />
|
||||
<div>
|
||||
<strong>Time:</strong> {formattedTimeComplexity}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-[13px] leading-[1.4] text-gray-100 bg-white/5 rounded-md p-3">
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="w-1 h-1 rounded-full bg-blue-400/80 mt-2 shrink-0" />
|
||||
<div>
|
||||
<strong>Space:</strong> {formattedSpaceComplexity}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export interface SolutionsProps {
|
||||
setView: (view: "queue" | "solutions" | "debug") => void
|
||||
credits: number
|
||||
currentLanguage: string
|
||||
setLanguage: (language: string) => void
|
||||
}
|
||||
const Solutions: React.FC<SolutionsProps> = ({
|
||||
setView,
|
||||
credits,
|
||||
currentLanguage,
|
||||
setLanguage
|
||||
}) => {
|
||||
const queryClient = useQueryClient()
|
||||
const contentRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const [debugProcessing, setDebugProcessing] = useState(false)
|
||||
const [problemStatementData, setProblemStatementData] =
|
||||
useState<ProblemStatementData | null>(null)
|
||||
const [solutionData, setSolutionData] = useState<string | null>(null)
|
||||
const [thoughtsData, setThoughtsData] = useState<string[] | null>(null)
|
||||
const [timeComplexityData, setTimeComplexityData] = useState<string | null>(
|
||||
null
|
||||
)
|
||||
const [spaceComplexityData, setSpaceComplexityData] = useState<string | null>(
|
||||
null
|
||||
)
|
||||
|
||||
const [isTooltipVisible, setIsTooltipVisible] = useState(false)
|
||||
const [tooltipHeight, setTooltipHeight] = useState(0)
|
||||
|
||||
const [isResetting, setIsResetting] = useState(false)
|
||||
|
||||
interface Screenshot {
|
||||
id: string
|
||||
path: string
|
||||
preview: string
|
||||
timestamp: number
|
||||
}
|
||||
|
||||
const [extraScreenshots, setExtraScreenshots] = useState<Screenshot[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
const fetchScreenshots = async () => {
|
||||
try {
|
||||
const existing = await window.electronAPI.getScreenshots()
|
||||
console.log("Raw screenshot data:", existing)
|
||||
const screenshots = (Array.isArray(existing) ? existing : []).map(
|
||||
(p) => ({
|
||||
id: p.path,
|
||||
path: p.path,
|
||||
preview: p.preview,
|
||||
timestamp: Date.now()
|
||||
})
|
||||
)
|
||||
console.log("Processed screenshots:", screenshots)
|
||||
setExtraScreenshots(screenshots)
|
||||
} catch (error) {
|
||||
console.error("Error loading extra screenshots:", error)
|
||||
setExtraScreenshots([])
|
||||
}
|
||||
}
|
||||
|
||||
fetchScreenshots()
|
||||
}, [solutionData])
|
||||
|
||||
const { showToast } = useToast()
|
||||
|
||||
useEffect(() => {
|
||||
// Height update logic
|
||||
const updateDimensions = () => {
|
||||
if (contentRef.current) {
|
||||
let contentHeight = contentRef.current.scrollHeight
|
||||
const contentWidth = contentRef.current.scrollWidth
|
||||
if (isTooltipVisible) {
|
||||
contentHeight += tooltipHeight
|
||||
}
|
||||
window.electronAPI.updateContentDimensions({
|
||||
width: contentWidth,
|
||||
height: contentHeight
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize resize observer
|
||||
const resizeObserver = new ResizeObserver(updateDimensions)
|
||||
if (contentRef.current) {
|
||||
resizeObserver.observe(contentRef.current)
|
||||
}
|
||||
updateDimensions()
|
||||
|
||||
// Set up event listeners
|
||||
const cleanupFunctions = [
|
||||
window.electronAPI.onScreenshotTaken(async () => {
|
||||
try {
|
||||
const existing = await window.electronAPI.getScreenshots()
|
||||
const screenshots = (Array.isArray(existing) ? existing : []).map(
|
||||
(p) => ({
|
||||
id: p.path,
|
||||
path: p.path,
|
||||
preview: p.preview,
|
||||
timestamp: Date.now()
|
||||
})
|
||||
)
|
||||
setExtraScreenshots(screenshots)
|
||||
} catch (error) {
|
||||
console.error("Error loading extra screenshots:", error)
|
||||
}
|
||||
}),
|
||||
window.electronAPI.onResetView(() => {
|
||||
// Set resetting state first
|
||||
setIsResetting(true)
|
||||
|
||||
// Remove queries
|
||||
queryClient.removeQueries({
|
||||
queryKey: ["solution"]
|
||||
})
|
||||
queryClient.removeQueries({
|
||||
queryKey: ["new_solution"]
|
||||
})
|
||||
|
||||
// Reset screenshots
|
||||
setExtraScreenshots([])
|
||||
|
||||
// After a small delay, clear the resetting state
|
||||
setTimeout(() => {
|
||||
setIsResetting(false)
|
||||
}, 0)
|
||||
}),
|
||||
window.electronAPI.onSolutionStart(() => {
|
||||
// Every time processing starts, reset relevant states
|
||||
setSolutionData(null)
|
||||
setThoughtsData(null)
|
||||
setTimeComplexityData(null)
|
||||
setSpaceComplexityData(null)
|
||||
}),
|
||||
window.electronAPI.onProblemExtracted((data) => {
|
||||
queryClient.setQueryData(["problem_statement"], data)
|
||||
}),
|
||||
//if there was an error processing the initial solution
|
||||
window.electronAPI.onSolutionError((error: string) => {
|
||||
showToast("Processing Failed", error, "error")
|
||||
// Reset solutions in the cache (even though this shouldn't ever happen) and complexities to previous states
|
||||
const solution = queryClient.getQueryData(["solution"]) as {
|
||||
code: string
|
||||
thoughts: string[]
|
||||
time_complexity: string
|
||||
space_complexity: string
|
||||
} | null
|
||||
if (!solution) {
|
||||
setView("queue")
|
||||
}
|
||||
setSolutionData(solution?.code || null)
|
||||
setThoughtsData(solution?.thoughts || null)
|
||||
setTimeComplexityData(solution?.time_complexity || null)
|
||||
setSpaceComplexityData(solution?.space_complexity || null)
|
||||
console.error("Processing error:", error)
|
||||
}),
|
||||
//when the initial solution is generated, we'll set the solution data to that
|
||||
window.electronAPI.onSolutionSuccess((data) => {
|
||||
if (!data) {
|
||||
console.warn("Received empty or invalid solution data")
|
||||
return
|
||||
}
|
||||
console.log({ data })
|
||||
const solutionData = {
|
||||
code: data.code,
|
||||
thoughts: data.thoughts,
|
||||
time_complexity: data.time_complexity,
|
||||
space_complexity: data.space_complexity
|
||||
}
|
||||
|
||||
queryClient.setQueryData(["solution"], solutionData)
|
||||
setSolutionData(solutionData.code || null)
|
||||
setThoughtsData(solutionData.thoughts || null)
|
||||
setTimeComplexityData(solutionData.time_complexity || null)
|
||||
setSpaceComplexityData(solutionData.space_complexity || null)
|
||||
|
||||
// Fetch latest screenshots when solution is successful
|
||||
const fetchScreenshots = async () => {
|
||||
try {
|
||||
const existing = await window.electronAPI.getScreenshots()
|
||||
const screenshots =
|
||||
existing.previews?.map((p) => ({
|
||||
id: p.path,
|
||||
path: p.path,
|
||||
preview: p.preview,
|
||||
timestamp: Date.now()
|
||||
})) || []
|
||||
setExtraScreenshots(screenshots)
|
||||
} catch (error) {
|
||||
console.error("Error loading extra screenshots:", error)
|
||||
setExtraScreenshots([])
|
||||
}
|
||||
}
|
||||
fetchScreenshots()
|
||||
}),
|
||||
|
||||
//########################################################
|
||||
//DEBUG EVENTS
|
||||
//########################################################
|
||||
window.electronAPI.onDebugStart(() => {
|
||||
//we'll set the debug processing state to true and use that to render a little loader
|
||||
setDebugProcessing(true)
|
||||
}),
|
||||
//the first time debugging works, we'll set the view to debug and populate the cache with the data
|
||||
window.electronAPI.onDebugSuccess((data) => {
|
||||
queryClient.setQueryData(["new_solution"], data)
|
||||
setDebugProcessing(false)
|
||||
}),
|
||||
//when there was an error in the initial debugging, we'll show a toast and stop the little generating pulsing thing.
|
||||
window.electronAPI.onDebugError(() => {
|
||||
showToast(
|
||||
"Processing Failed",
|
||||
"There was an error debugging your code.",
|
||||
"error"
|
||||
)
|
||||
setDebugProcessing(false)
|
||||
}),
|
||||
window.electronAPI.onProcessingNoScreenshots(() => {
|
||||
showToast(
|
||||
"No Screenshots",
|
||||
"There are no extra screenshots to process.",
|
||||
"neutral"
|
||||
)
|
||||
}),
|
||||
// Removed out of credits handler - unlimited credits in this version
|
||||
]
|
||||
|
||||
return () => {
|
||||
resizeObserver.disconnect()
|
||||
cleanupFunctions.forEach((cleanup) => cleanup())
|
||||
}
|
||||
}, [isTooltipVisible, tooltipHeight])
|
||||
|
||||
useEffect(() => {
|
||||
setProblemStatementData(
|
||||
queryClient.getQueryData(["problem_statement"]) || null
|
||||
)
|
||||
setSolutionData(queryClient.getQueryData(["solution"]) || null)
|
||||
|
||||
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
|
||||
if (event?.query.queryKey[0] === "problem_statement") {
|
||||
setProblemStatementData(
|
||||
queryClient.getQueryData(["problem_statement"]) || null
|
||||
)
|
||||
}
|
||||
if (event?.query.queryKey[0] === "solution") {
|
||||
const solution = queryClient.getQueryData(["solution"]) as {
|
||||
code: string
|
||||
thoughts: string[]
|
||||
time_complexity: string
|
||||
space_complexity: string
|
||||
} | null
|
||||
|
||||
setSolutionData(solution?.code ?? null)
|
||||
setThoughtsData(solution?.thoughts ?? null)
|
||||
setTimeComplexityData(solution?.time_complexity ?? null)
|
||||
setSpaceComplexityData(solution?.space_complexity ?? null)
|
||||
}
|
||||
})
|
||||
return () => unsubscribe()
|
||||
}, [queryClient])
|
||||
|
||||
const handleTooltipVisibilityChange = (visible: boolean, height: number) => {
|
||||
setIsTooltipVisible(visible)
|
||||
setTooltipHeight(height)
|
||||
}
|
||||
|
||||
const handleDeleteExtraScreenshot = async (index: number) => {
|
||||
const screenshotToDelete = extraScreenshots[index]
|
||||
|
||||
try {
|
||||
const response = await window.electronAPI.deleteScreenshot(
|
||||
screenshotToDelete.path
|
||||
)
|
||||
|
||||
if (response.success) {
|
||||
// Fetch and update screenshots after successful deletion
|
||||
const existing = await window.electronAPI.getScreenshots()
|
||||
const screenshots = (Array.isArray(existing) ? existing : []).map(
|
||||
(p) => ({
|
||||
id: p.path,
|
||||
path: p.path,
|
||||
preview: p.preview,
|
||||
timestamp: Date.now()
|
||||
})
|
||||
)
|
||||
setExtraScreenshots(screenshots)
|
||||
} else {
|
||||
console.error("Failed to delete extra screenshot:", response.error)
|
||||
showToast("Error", "Failed to delete the screenshot", "error")
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error deleting extra screenshot:", error)
|
||||
showToast("Error", "Failed to delete the screenshot", "error")
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{!isResetting && queryClient.getQueryData(["new_solution"]) ? (
|
||||
<Debug
|
||||
isProcessing={debugProcessing}
|
||||
setIsProcessing={setDebugProcessing}
|
||||
currentLanguage={currentLanguage}
|
||||
setLanguage={setLanguage}
|
||||
/>
|
||||
) : (
|
||||
<div ref={contentRef} className="relative">
|
||||
<div className="space-y-3 px-4 py-3">
|
||||
{/* Conditionally render the screenshot queue if solutionData is available */}
|
||||
{solutionData && (
|
||||
<div className="bg-transparent w-fit">
|
||||
<div className="pb-3">
|
||||
<div className="space-y-3 w-fit">
|
||||
<ScreenshotQueue
|
||||
isLoading={debugProcessing}
|
||||
screenshots={extraScreenshots}
|
||||
onDeleteScreenshot={handleDeleteExtraScreenshot}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Navbar of commands with the SolutionsHelper */}
|
||||
<SolutionCommands
|
||||
onTooltipVisibilityChange={handleTooltipVisibilityChange}
|
||||
isProcessing={!problemStatementData || !solutionData}
|
||||
extraScreenshots={extraScreenshots}
|
||||
credits={credits}
|
||||
currentLanguage={currentLanguage}
|
||||
setLanguage={setLanguage}
|
||||
/>
|
||||
|
||||
{/* Main Content - Modified width constraints */}
|
||||
<div className="w-full text-sm text-black bg-black/60 rounded-md">
|
||||
<div className="rounded-lg overflow-hidden">
|
||||
<div className="px-4 py-3 space-y-4 max-w-full">
|
||||
{!solutionData && (
|
||||
<>
|
||||
<ContentSection
|
||||
title="Problem Statement"
|
||||
content={problemStatementData?.problem_statement}
|
||||
isLoading={!problemStatementData}
|
||||
/>
|
||||
{problemStatementData && (
|
||||
<div className="mt-4 flex">
|
||||
<p className="text-xs bg-gradient-to-r from-gray-300 via-gray-100 to-gray-300 bg-clip-text text-transparent animate-pulse">
|
||||
Generating solutions...
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{solutionData && (
|
||||
<>
|
||||
<ContentSection
|
||||
title={`My Thoughts (${COMMAND_KEY} + Arrow keys to scroll)`}
|
||||
content={
|
||||
thoughtsData && (
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1">
|
||||
{thoughtsData.map((thought, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-start gap-2"
|
||||
>
|
||||
<div className="w-1 h-1 rounded-full bg-blue-400/80 mt-2 shrink-0" />
|
||||
<div>{thought}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
isLoading={!thoughtsData}
|
||||
/>
|
||||
|
||||
<SolutionSection
|
||||
title="Solution"
|
||||
content={solutionData}
|
||||
isLoading={!solutionData}
|
||||
currentLanguage={currentLanguage}
|
||||
/>
|
||||
|
||||
<ComplexitySection
|
||||
timeComplexity={timeComplexityData}
|
||||
spaceComplexity={spaceComplexityData}
|
||||
isLoading={!timeComplexityData || !spaceComplexityData}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default Solutions
|
||||
@ -0,0 +1,161 @@
|
||||
import { useState, useRef, useEffect } from "react"
|
||||
import { supabase } from "../lib/supabase"
|
||||
import { User } from "@supabase/supabase-js"
|
||||
|
||||
interface SubscribePageProps {
|
||||
user: User
|
||||
}
|
||||
|
||||
export default function SubscribePage({ user }: SubscribePageProps) {
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const updateDimensions = () => {
|
||||
if (containerRef.current) {
|
||||
window.electronAPI.updateContentDimensions({
|
||||
width: 400, // Fixed width
|
||||
height: 400 // Fixed height
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
updateDimensions()
|
||||
}, [])
|
||||
|
||||
const handleSignOut = async () => {
|
||||
try {
|
||||
const { error: signOutError } = await supabase.auth.signOut()
|
||||
if (signOutError) throw signOutError
|
||||
} catch (err) {
|
||||
console.error("Error signing out:", err)
|
||||
setError("Failed to sign out. Please try again.")
|
||||
setTimeout(() => setError(null), 3000)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubscribe = async () => {
|
||||
if (!user) return
|
||||
|
||||
try {
|
||||
const result = await window.electronAPI.openSubscriptionPortal({
|
||||
id: user.id,
|
||||
email: user.email!
|
||||
})
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.error || "Failed to open subscription portal")
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Error opening subscription portal:", err)
|
||||
setError("Failed to open subscription portal. Please try again.")
|
||||
setTimeout(() => setError(null), 3000)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="h-[400px] w-[400px] bg-black flex items-center justify-center"
|
||||
>
|
||||
<div className="w-full px-6">
|
||||
<div className="text-center">
|
||||
<h2 className="text-2xl font-bold text-white">
|
||||
Welcome to Interview Coder
|
||||
</h2>
|
||||
<p className="text-gray-400 text-sm mt-2 mb-6">
|
||||
To continue using Interview Coder, you'll need to subscribe
|
||||
($60/month)
|
||||
</p>
|
||||
<p className="text-gray-500 text-[11px] -mt-4 mb-6 italic">
|
||||
* Undetectability may not work with some versions of MacOS. See our
|
||||
help center for more details
|
||||
</p>
|
||||
|
||||
{/* Keyboard Shortcuts */}
|
||||
<div className="bg-white/[0.03] border border-white/[0.06] rounded-xl p-3 mb-6">
|
||||
<div className="flex items-center justify-between text-white/70 text-xs">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-white/40">Toggle Visibility</span>
|
||||
<div className="flex gap-1">
|
||||
<kbd className="bg-white/[0.07] border border-white/[0.1] rounded-md px-1.5 py-1 text-[10px] leading-none text-white/60">
|
||||
⌘
|
||||
</kbd>
|
||||
<kbd className="bg-white/[0.07] border border-white/[0.1] rounded-md px-1.5 py-1 text-[10px] leading-none text-white/60">
|
||||
B
|
||||
</kbd>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-white/40">Quit App</span>
|
||||
<div className="flex gap-1">
|
||||
<kbd className="bg-white/[0.07] border border-white/[0.1] rounded-md px-1.5 py-1 text-[10px] leading-none text-white/60">
|
||||
⌘
|
||||
</kbd>
|
||||
<kbd className="bg-white/[0.07] border border-white/[0.1] rounded-md px-1.5 py-1 text-[10px] leading-none text-white/60">
|
||||
Q
|
||||
</kbd>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Subscribe Button */}
|
||||
<button
|
||||
onClick={handleSubscribe}
|
||||
className="w-full px-4 py-3 bg-white text-black rounded-xl font-medium hover:bg-white/90 transition-colors flex items-center justify-center gap-2 mb-6"
|
||||
>
|
||||
Subscribe
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
|
||||
<polyline points="15 3 21 3 21 9" />
|
||||
<line x1="10" y1="14" x2="21" y2="3" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{/* Logout Section */}
|
||||
<div className="border-t border-white/[0.06] pt-4">
|
||||
<button
|
||||
onClick={handleSignOut}
|
||||
className="flex items-center justify-center gap-1.5 text-[11px] text-red-400/80 hover:text-red-400 transition-colors w-full group"
|
||||
>
|
||||
<div className="w-3.5 h-3.5 flex items-center justify-center opacity-60 group-hover:opacity-100 transition-opacity">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className="w-full h-full"
|
||||
>
|
||||
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
|
||||
<polyline points="16 17 21 12 16 7" />
|
||||
<line x1="21" y1="12" x2="9" y2="12" />
|
||||
</svg>
|
||||
</div>
|
||||
Log Out
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mt-4 px-3 py-2 rounded-lg bg-red-500/10 border border-red-500/20">
|
||||
<p className="text-xs text-red-400">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -0,0 +1,158 @@
|
||||
// file: src/components/SubscribedApp.tsx
|
||||
import { useQueryClient } from "@tanstack/react-query"
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import Queue from "../_pages/Queue"
|
||||
import Solutions from "../_pages/Solutions"
|
||||
import { useToast } from "../contexts/toast"
|
||||
|
||||
interface SubscribedAppProps {
|
||||
credits: number
|
||||
currentLanguage: string
|
||||
setLanguage: (language: string) => void
|
||||
}
|
||||
|
||||
const SubscribedApp: React.FC<SubscribedAppProps> = ({
|
||||
credits,
|
||||
currentLanguage,
|
||||
setLanguage
|
||||
}) => {
|
||||
const queryClient = useQueryClient()
|
||||
const [view, setView] = useState<"queue" | "solutions" | "debug">("queue")
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const { showToast } = useToast()
|
||||
|
||||
// Let's ensure we reset queries etc. if some electron signals happen
|
||||
useEffect(() => {
|
||||
const cleanup = window.electronAPI.onResetView(() => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["screenshots"]
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["problem_statement"]
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["solution"]
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["new_solution"]
|
||||
})
|
||||
setView("queue")
|
||||
})
|
||||
|
||||
return () => {
|
||||
cleanup()
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Dynamically update the window size
|
||||
useEffect(() => {
|
||||
if (!containerRef.current) return
|
||||
|
||||
const updateDimensions = () => {
|
||||
if (!containerRef.current) return
|
||||
const height = containerRef.current.scrollHeight || 600
|
||||
const width = containerRef.current.scrollWidth || 800
|
||||
window.electronAPI?.updateContentDimensions({ width, height })
|
||||
}
|
||||
|
||||
// Force initial dimension update immediately
|
||||
updateDimensions()
|
||||
|
||||
// Set a fallback timer to ensure dimensions are set even if content isn't fully loaded
|
||||
const fallbackTimer = setTimeout(() => {
|
||||
window.electronAPI?.updateContentDimensions({ width: 800, height: 600 })
|
||||
}, 500)
|
||||
|
||||
const resizeObserver = new ResizeObserver(updateDimensions)
|
||||
resizeObserver.observe(containerRef.current)
|
||||
|
||||
// Also watch DOM changes
|
||||
const mutationObserver = new MutationObserver(updateDimensions)
|
||||
mutationObserver.observe(containerRef.current, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
attributes: true,
|
||||
characterData: true
|
||||
})
|
||||
|
||||
// Do another update after a delay to catch any late-loading content
|
||||
const delayedUpdate = setTimeout(updateDimensions, 1000)
|
||||
|
||||
return () => {
|
||||
resizeObserver.disconnect()
|
||||
mutationObserver.disconnect()
|
||||
clearTimeout(fallbackTimer)
|
||||
clearTimeout(delayedUpdate)
|
||||
}
|
||||
}, [view])
|
||||
|
||||
// Listen for events that might switch views or show errors
|
||||
useEffect(() => {
|
||||
const cleanupFunctions = [
|
||||
window.electronAPI.onSolutionStart(() => {
|
||||
setView("solutions")
|
||||
}),
|
||||
window.electronAPI.onUnauthorized(() => {
|
||||
queryClient.removeQueries({
|
||||
queryKey: ["screenshots"]
|
||||
})
|
||||
queryClient.removeQueries({
|
||||
queryKey: ["solution"]
|
||||
})
|
||||
queryClient.removeQueries({
|
||||
queryKey: ["problem_statement"]
|
||||
})
|
||||
setView("queue")
|
||||
}),
|
||||
window.electronAPI.onResetView(() => {
|
||||
queryClient.removeQueries({
|
||||
queryKey: ["screenshots"]
|
||||
})
|
||||
queryClient.removeQueries({
|
||||
queryKey: ["solution"]
|
||||
})
|
||||
queryClient.removeQueries({
|
||||
queryKey: ["problem_statement"]
|
||||
})
|
||||
setView("queue")
|
||||
}),
|
||||
window.electronAPI.onResetView(() => {
|
||||
queryClient.setQueryData(["problem_statement"], null)
|
||||
}),
|
||||
window.electronAPI.onProblemExtracted((data: any) => {
|
||||
if (view === "queue") {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["problem_statement"]
|
||||
})
|
||||
queryClient.setQueryData(["problem_statement"], data)
|
||||
}
|
||||
}),
|
||||
window.electronAPI.onSolutionError((error: string) => {
|
||||
showToast("Error", error, "error")
|
||||
})
|
||||
]
|
||||
return () => cleanupFunctions.forEach((fn) => fn())
|
||||
}, [view])
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="min-h-0">
|
||||
{view === "queue" ? (
|
||||
<Queue
|
||||
setView={setView}
|
||||
credits={credits}
|
||||
currentLanguage={currentLanguage}
|
||||
setLanguage={setLanguage}
|
||||
/>
|
||||
) : view === "solutions" ? (
|
||||
<Solutions
|
||||
setView={setView}
|
||||
credits={credits}
|
||||
currentLanguage={currentLanguage}
|
||||
setLanguage={setLanguage}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default SubscribedApp
|
||||
@ -0,0 +1,132 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Settings, LogOut, ChevronDown, ChevronUp } from 'lucide-react';
|
||||
import { Button } from '../ui/button';
|
||||
import { useToast } from '../../contexts/toast';
|
||||
|
||||
interface HeaderProps {
|
||||
currentLanguage: string;
|
||||
setLanguage: (language: string) => void;
|
||||
onOpenSettings: () => void;
|
||||
}
|
||||
|
||||
// Available programming languages
|
||||
const LANGUAGES = [
|
||||
{ value: 'python', label: 'Python' },
|
||||
{ value: 'javascript', label: 'JavaScript' },
|
||||
{ value: 'java', label: 'Java' },
|
||||
{ value: 'cpp', label: 'C++' },
|
||||
{ value: 'csharp', label: 'C#' },
|
||||
{ value: 'go', label: 'Go' },
|
||||
{ value: 'rust', label: 'Rust' },
|
||||
{ value: 'typescript', label: 'TypeScript' },
|
||||
];
|
||||
|
||||
export function Header({ currentLanguage, setLanguage, onOpenSettings }: HeaderProps) {
|
||||
const [dropdownOpen, setDropdownOpen] = useState(false);
|
||||
const { showToast } = useToast();
|
||||
|
||||
// Handle logout - clear API key and reload app
|
||||
const handleLogout = async () => {
|
||||
try {
|
||||
// Update config with empty API key
|
||||
await window.electronAPI.updateConfig({
|
||||
apiKey: '',
|
||||
});
|
||||
|
||||
showToast('Success', 'Logged out successfully', 'success');
|
||||
|
||||
// Reload the app after a short delay
|
||||
setTimeout(() => {
|
||||
window.location.reload();
|
||||
}, 1500);
|
||||
} catch (error) {
|
||||
console.error('Error logging out:', error);
|
||||
showToast('Error', 'Failed to log out', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
// Handle language selection
|
||||
const handleLanguageSelect = (lang: string) => {
|
||||
setLanguage(lang);
|
||||
setDropdownOpen(false);
|
||||
|
||||
// Also save the language preference to config
|
||||
window.electronAPI.updateConfig({
|
||||
language: lang
|
||||
}).catch(error => {
|
||||
console.error('Failed to save language preference:', error);
|
||||
});
|
||||
};
|
||||
|
||||
const toggleDropdown = () => {
|
||||
setDropdownOpen(!dropdownOpen);
|
||||
};
|
||||
|
||||
// Find the current language object
|
||||
const currentLangObj = LANGUAGES.find(lang => lang.value === currentLanguage) || LANGUAGES[0];
|
||||
|
||||
return (
|
||||
<div className="bg-black p-2 border-b border-white/10 flex items-center justify-between">
|
||||
<div className="flex items-center space-x-1">
|
||||
<span className="text-white text-sm mr-2">Language:</span>
|
||||
<div className="relative">
|
||||
<button
|
||||
onClick={toggleDropdown}
|
||||
className="flex items-center gap-1 rounded-md bg-white/5 px-3 py-1.5 text-sm text-white hover:bg-white/10 transition-colors"
|
||||
>
|
||||
{currentLangObj.label}
|
||||
{dropdownOpen ? (
|
||||
<ChevronUp className="h-4 w-4 text-white/70" />
|
||||
) : (
|
||||
<ChevronDown className="h-4 w-4 text-white/70" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{dropdownOpen && (
|
||||
<div className="absolute z-10 mt-1 w-full rounded-md bg-black border border-white/10 shadow-lg">
|
||||
<div className="py-1">
|
||||
{LANGUAGES.map((lang) => (
|
||||
<button
|
||||
key={lang.value}
|
||||
onClick={() => handleLanguageSelect(lang.value)}
|
||||
className={`block w-full text-left px-4 py-2 text-sm ${
|
||||
currentLanguage === lang.value
|
||||
? 'bg-white/10 text-white'
|
||||
: 'text-white/70 hover:bg-white/5'
|
||||
}`}
|
||||
>
|
||||
{lang.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 px-2 text-white/70 hover:text-white hover:bg-white/10"
|
||||
onClick={onOpenSettings}
|
||||
title="Settings"
|
||||
>
|
||||
<Settings className="h-4 w-4 mr-1" />
|
||||
<span className="text-xs">Settings</span>
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 px-2 text-red-400/80 hover:text-red-400 hover:bg-white/10"
|
||||
onClick={handleLogout}
|
||||
title="Log Out"
|
||||
>
|
||||
<LogOut className="h-4 w-4 mr-1" />
|
||||
<span className="text-xs">Log Out</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -0,0 +1,434 @@
|
||||
import React, { useState, useEffect, useRef } from "react"
|
||||
|
||||
import { useToast } from "../../contexts/toast"
|
||||
import { LanguageSelector } from "../shared/LanguageSelector"
|
||||
import { COMMAND_KEY } from "../../utils/platform"
|
||||
|
||||
interface QueueCommandsProps {
|
||||
onTooltipVisibilityChange: (visible: boolean, height: number) => void
|
||||
screenshotCount?: number
|
||||
credits: number
|
||||
currentLanguage: string
|
||||
setLanguage: (language: string) => void
|
||||
}
|
||||
|
||||
const QueueCommands: React.FC<QueueCommandsProps> = ({
|
||||
onTooltipVisibilityChange,
|
||||
screenshotCount = 0,
|
||||
credits,
|
||||
currentLanguage,
|
||||
setLanguage
|
||||
}) => {
|
||||
const [isTooltipVisible, setIsTooltipVisible] = useState(false)
|
||||
const tooltipRef = useRef<HTMLDivElement>(null)
|
||||
const { showToast } = useToast()
|
||||
|
||||
useEffect(() => {
|
||||
let tooltipHeight = 0
|
||||
if (tooltipRef.current && isTooltipVisible) {
|
||||
tooltipHeight = tooltipRef.current.offsetHeight + 10
|
||||
}
|
||||
onTooltipVisibilityChange(isTooltipVisible, tooltipHeight)
|
||||
}, [isTooltipVisible])
|
||||
|
||||
const handleSignOut = async () => {
|
||||
try {
|
||||
// Clear any local storage or electron-specific data
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
|
||||
// Clear the API key in the configuration
|
||||
await window.electronAPI.updateConfig({
|
||||
apiKey: '',
|
||||
});
|
||||
|
||||
showToast('Success', 'Logged out successfully', 'success');
|
||||
|
||||
// Reload the app after a short delay
|
||||
setTimeout(() => {
|
||||
window.location.reload();
|
||||
}, 1500);
|
||||
} catch (err) {
|
||||
console.error("Error logging out:", err);
|
||||
showToast('Error', 'Failed to log out', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
const handleMouseEnter = () => {
|
||||
setIsTooltipVisible(true)
|
||||
}
|
||||
|
||||
const handleMouseLeave = () => {
|
||||
setIsTooltipVisible(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="pt-2 w-fit">
|
||||
<div className="text-xs text-white/90 backdrop-blur-md bg-black/60 rounded-lg py-2 px-4 flex items-center justify-center gap-4">
|
||||
{/* Screenshot */}
|
||||
<div
|
||||
className="flex items-center gap-2 cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
|
||||
onClick={async () => {
|
||||
try {
|
||||
const result = await window.electronAPI.triggerScreenshot()
|
||||
if (!result.success) {
|
||||
console.error("Failed to take screenshot:", result.error)
|
||||
showToast("Error", "Failed to take screenshot", "error")
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error taking screenshot:", error)
|
||||
showToast("Error", "Failed to take screenshot", "error")
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span className="text-[11px] leading-none truncate">
|
||||
{screenshotCount === 0
|
||||
? "Take first screenshot"
|
||||
: screenshotCount === 1
|
||||
? "Take second screenshot"
|
||||
: screenshotCount === 2
|
||||
? "Take third screenshot"
|
||||
: screenshotCount === 3
|
||||
? "Take fourth screenshot"
|
||||
: screenshotCount === 4
|
||||
? "Take fifth screenshot"
|
||||
: "Next will replace first screenshot"}
|
||||
</span>
|
||||
<div className="flex gap-1">
|
||||
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
|
||||
{COMMAND_KEY}
|
||||
</button>
|
||||
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
|
||||
H
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Solve Command */}
|
||||
{screenshotCount > 0 && (
|
||||
<div
|
||||
className={`flex flex-col cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors ${
|
||||
credits <= 0 ? "opacity-50 cursor-not-allowed" : ""
|
||||
}`}
|
||||
onClick={async () => {
|
||||
|
||||
try {
|
||||
const result =
|
||||
await window.electronAPI.triggerProcessScreenshots()
|
||||
if (!result.success) {
|
||||
console.error(
|
||||
"Failed to process screenshots:",
|
||||
result.error
|
||||
)
|
||||
showToast("Error", "Failed to process screenshots", "error")
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error processing screenshots:", error)
|
||||
showToast("Error", "Failed to process screenshots", "error")
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-[11px] leading-none">Solve </span>
|
||||
<div className="flex gap-1 ml-2">
|
||||
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
|
||||
{COMMAND_KEY}
|
||||
</button>
|
||||
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
|
||||
↵
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Separator */}
|
||||
<div className="mx-2 h-4 w-px bg-white/20" />
|
||||
|
||||
{/* Settings with Tooltip */}
|
||||
<div
|
||||
className="relative inline-block"
|
||||
onMouseEnter={handleMouseEnter}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
>
|
||||
{/* Gear icon */}
|
||||
<div className="w-4 h-4 flex items-center justify-center cursor-pointer text-white/70 hover:text-white/90 transition-colors">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className="w-3.5 h-3.5"
|
||||
>
|
||||
<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" />
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
{/* Tooltip Content */}
|
||||
{isTooltipVisible && (
|
||||
<div
|
||||
ref={tooltipRef}
|
||||
className="absolute top-full left-0 mt-2 w-80 transform -translate-x-[calc(50%-12px)]"
|
||||
style={{ zIndex: 100 }}
|
||||
>
|
||||
{/* Add transparent bridge */}
|
||||
<div className="absolute -top-2 right-0 w-full h-2" />
|
||||
<div className="p-3 text-xs bg-black/80 backdrop-blur-md rounded-lg border border-white/10 text-white/90 shadow-lg">
|
||||
<div className="space-y-4">
|
||||
<h3 className="font-medium truncate">Keyboard Shortcuts</h3>
|
||||
<div className="space-y-3">
|
||||
{/* Toggle Command */}
|
||||
<div
|
||||
className="cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
|
||||
onClick={async () => {
|
||||
try {
|
||||
const result =
|
||||
await window.electronAPI.toggleMainWindow()
|
||||
if (!result.success) {
|
||||
console.error(
|
||||
"Failed to toggle window:",
|
||||
result.error
|
||||
)
|
||||
showToast(
|
||||
"Error",
|
||||
"Failed to toggle window",
|
||||
"error"
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error toggling window:", error)
|
||||
showToast(
|
||||
"Error",
|
||||
"Failed to toggle window",
|
||||
"error"
|
||||
)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="truncate">Toggle Window</span>
|
||||
<div className="flex gap-1 flex-shrink-0">
|
||||
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
|
||||
{COMMAND_KEY}
|
||||
</span>
|
||||
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
|
||||
B
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-[10px] leading-relaxed text-white/70 truncate mt-1">
|
||||
Show or hide this window.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Screenshot Command */}
|
||||
<div
|
||||
className="cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
|
||||
onClick={async () => {
|
||||
try {
|
||||
const result =
|
||||
await window.electronAPI.triggerScreenshot()
|
||||
if (!result.success) {
|
||||
console.error(
|
||||
"Failed to take screenshot:",
|
||||
result.error
|
||||
)
|
||||
showToast(
|
||||
"Error",
|
||||
"Failed to take screenshot",
|
||||
"error"
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error taking screenshot:", error)
|
||||
showToast(
|
||||
"Error",
|
||||
"Failed to take screenshot",
|
||||
"error"
|
||||
)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="truncate">Take Screenshot</span>
|
||||
<div className="flex gap-1 flex-shrink-0">
|
||||
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
|
||||
{COMMAND_KEY}
|
||||
</span>
|
||||
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
|
||||
H
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-[10px] leading-relaxed text-white/70 truncate mt-1">
|
||||
Take a screenshot of the problem description.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Solve Command */}
|
||||
<div
|
||||
className={`cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors ${
|
||||
screenshotCount > 0
|
||||
? ""
|
||||
: "opacity-50 cursor-not-allowed"
|
||||
}`}
|
||||
onClick={async () => {
|
||||
if (screenshotCount === 0) return
|
||||
|
||||
try {
|
||||
const result =
|
||||
await window.electronAPI.triggerProcessScreenshots()
|
||||
if (!result.success) {
|
||||
console.error(
|
||||
"Failed to process screenshots:",
|
||||
result.error
|
||||
)
|
||||
showToast(
|
||||
"Error",
|
||||
"Failed to process screenshots",
|
||||
"error"
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"Error processing screenshots:",
|
||||
error
|
||||
)
|
||||
showToast(
|
||||
"Error",
|
||||
"Failed to process screenshots",
|
||||
"error"
|
||||
)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="truncate">Solve</span>
|
||||
<div className="flex gap-1 flex-shrink-0">
|
||||
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
|
||||
{COMMAND_KEY}
|
||||
</span>
|
||||
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
|
||||
↵
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-[10px] leading-relaxed text-white/70 truncate mt-1">
|
||||
{screenshotCount > 0
|
||||
? "Generate a solution based on the current problem."
|
||||
: "Take a screenshot first to generate a solution."}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Delete Last Screenshot Command */}
|
||||
<div
|
||||
className={`cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors ${
|
||||
screenshotCount > 0
|
||||
? ""
|
||||
: "opacity-50 cursor-not-allowed"
|
||||
}`}
|
||||
onClick={async () => {
|
||||
if (screenshotCount === 0) return
|
||||
|
||||
try {
|
||||
const result = await window.electronAPI.deleteLastScreenshot()
|
||||
if (!result.success) {
|
||||
console.error(
|
||||
"Failed to delete last screenshot:",
|
||||
result.error
|
||||
)
|
||||
showToast(
|
||||
"Error",
|
||||
result.error || "Failed to delete screenshot",
|
||||
"error"
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error deleting screenshot:", error)
|
||||
showToast(
|
||||
"Error",
|
||||
"Failed to delete screenshot",
|
||||
"error"
|
||||
)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="truncate">Delete Last Screenshot</span>
|
||||
<div className="flex gap-1 flex-shrink-0">
|
||||
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
|
||||
{COMMAND_KEY}
|
||||
</span>
|
||||
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
|
||||
L
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-[10px] leading-relaxed text-white/70 truncate mt-1">
|
||||
{screenshotCount > 0
|
||||
? "Remove the most recently taken screenshot."
|
||||
: "No screenshots to delete."}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Separator and Log Out */}
|
||||
<div className="pt-3 mt-3 border-t border-white/10">
|
||||
<LanguageSelector
|
||||
currentLanguage={currentLanguage}
|
||||
setLanguage={setLanguage}
|
||||
/>
|
||||
|
||||
{/* API Key Settings */}
|
||||
<div className="mb-3 px-2 space-y-1">
|
||||
<div className="flex items-center justify-between text-[13px] font-medium text-white/90">
|
||||
<span>OpenAI API Settings</span>
|
||||
<button
|
||||
className="bg-white/10 hover:bg-white/20 px-2 py-1 rounded text-[11px]"
|
||||
onClick={() => window.electronAPI.openSettingsPortal()}
|
||||
>
|
||||
Settings
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleSignOut}
|
||||
className="flex items-center gap-2 text-[11px] text-red-400 hover:text-red-300 transition-colors w-full"
|
||||
>
|
||||
<div className="w-4 h-4 flex items-center justify-center">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className="w-3 h-3"
|
||||
>
|
||||
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
|
||||
<polyline points="16 17 21 12 16 7" />
|
||||
<line x1="21" y1="12" x2="9" y2="12" />
|
||||
</svg>
|
||||
</div>
|
||||
Log Out
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default QueueCommands
|
||||
@ -0,0 +1,67 @@
|
||||
// src/components/ScreenshotItem.tsx
|
||||
import React from "react"
|
||||
import { X } from "lucide-react"
|
||||
|
||||
interface Screenshot {
|
||||
path: string
|
||||
preview: string
|
||||
}
|
||||
|
||||
interface ScreenshotItemProps {
|
||||
screenshot: Screenshot
|
||||
onDelete: (index: number) => void
|
||||
index: number
|
||||
isLoading: boolean
|
||||
}
|
||||
|
||||
const ScreenshotItem: React.FC<ScreenshotItemProps> = ({
|
||||
screenshot,
|
||||
onDelete,
|
||||
index,
|
||||
isLoading
|
||||
}) => {
|
||||
const handleDelete = async () => {
|
||||
await onDelete(index)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={`border border-white relative w-[128px] h-[72px] ${
|
||||
isLoading ? "" : "group"
|
||||
}`}
|
||||
>
|
||||
<div className="w-full h-full relative">
|
||||
{isLoading && (
|
||||
<div className="absolute inset-0 bg-black bg-opacity-50 z-10 flex items-center justify-center">
|
||||
<div className="w-6 h-6 border-2 border-white border-t-transparent rounded-full animate-spin" />
|
||||
</div>
|
||||
)}
|
||||
<img
|
||||
src={screenshot.preview}
|
||||
alt="Screenshot"
|
||||
className={`w-full h-full object-cover transition-transform duration-300 ${
|
||||
isLoading
|
||||
? "opacity-50"
|
||||
: "cursor-pointer group-hover:scale-105 group-hover:brightness-75"
|
||||
}`}
|
||||
/>
|
||||
</div>
|
||||
{!isLoading && (
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleDelete()
|
||||
}}
|
||||
className="absolute top-2 left-2 p-1 rounded-full bg-black bg-opacity-50 text-white opacity-0 group-hover:opacity-100 transition-opacity duration-300"
|
||||
aria-label="Delete screenshot"
|
||||
>
|
||||
<X size={16} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default ScreenshotItem
|
||||
@ -0,0 +1,40 @@
|
||||
import React from "react"
|
||||
import ScreenshotItem from "./ScreenshotItem"
|
||||
|
||||
interface Screenshot {
|
||||
path: string
|
||||
preview: string
|
||||
}
|
||||
|
||||
interface ScreenshotQueueProps {
|
||||
isLoading: boolean
|
||||
screenshots: Screenshot[]
|
||||
onDeleteScreenshot: (index: number) => void
|
||||
}
|
||||
const ScreenshotQueue: React.FC<ScreenshotQueueProps> = ({
|
||||
isLoading,
|
||||
screenshots,
|
||||
onDeleteScreenshot
|
||||
}) => {
|
||||
if (screenshots.length === 0) {
|
||||
return <></>
|
||||
}
|
||||
|
||||
const displayScreenshots = screenshots.slice(0, 5)
|
||||
|
||||
return (
|
||||
<div className="flex gap-4">
|
||||
{displayScreenshots.map((screenshot, index) => (
|
||||
<ScreenshotItem
|
||||
key={screenshot.path}
|
||||
isLoading={isLoading}
|
||||
screenshot={screenshot}
|
||||
index={index}
|
||||
onDelete={onDeleteScreenshot}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ScreenshotQueue
|
||||
@ -0,0 +1,355 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import {
|
||||
Dialog,
|
||||
DialogTrigger,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from "../ui/dialog";
|
||||
import { Input } from "../ui/input";
|
||||
import { Button } from "../ui/button";
|
||||
import { Settings } from "lucide-react";
|
||||
import { useToast } from "../../contexts/toast";
|
||||
|
||||
type OpenAIModel = {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
};
|
||||
|
||||
type ModelCategory = {
|
||||
key: 'extractionModel' | 'solutionModel' | 'debuggingModel';
|
||||
title: string;
|
||||
description: string;
|
||||
models: OpenAIModel[];
|
||||
};
|
||||
|
||||
// Define available models for each category
|
||||
const modelCategories: ModelCategory[] = [
|
||||
{
|
||||
key: 'extractionModel',
|
||||
title: 'Problem Extraction',
|
||||
description: 'Model used to analyze screenshots and extract problem details',
|
||||
models: [
|
||||
{
|
||||
id: "gpt-4o",
|
||||
name: "gpt-4o",
|
||||
description: "Best overall performance for problem extraction"
|
||||
},
|
||||
{
|
||||
id: "gpt-4o-mini",
|
||||
name: "gpt-4o-mini",
|
||||
description: "Faster, more cost-effective option"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
key: 'solutionModel',
|
||||
title: 'Solution Generation',
|
||||
description: 'Model used to generate coding solutions',
|
||||
models: [
|
||||
{
|
||||
id: "gpt-4o",
|
||||
name: "gpt-4o",
|
||||
description: "Strong overall performance for coding tasks"
|
||||
},
|
||||
{
|
||||
id: "gpt-4o-mini",
|
||||
name: "gpt-4o-mini",
|
||||
description: "Faster, more cost-effective option"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
key: 'debuggingModel',
|
||||
title: 'Debugging',
|
||||
description: 'Model used to debug and improve solutions',
|
||||
models: [
|
||||
{
|
||||
id: "gpt-4o",
|
||||
name: "gpt-4o",
|
||||
description: "Best for analyzing code and error messages"
|
||||
},
|
||||
{
|
||||
id: "gpt-4o-mini",
|
||||
name: "gpt-4o-mini",
|
||||
description: "Faster, more cost-effective option"
|
||||
}
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
interface SettingsDialogProps {
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function SettingsDialog({ open: externalOpen, onOpenChange }: SettingsDialogProps) {
|
||||
const [open, setOpen] = useState(externalOpen || false);
|
||||
const [apiKey, setApiKey] = useState("");
|
||||
const [extractionModel, setExtractionModel] = useState("gpt-4o");
|
||||
const [solutionModel, setSolutionModel] = useState("gpt-4o");
|
||||
const [debuggingModel, setDebuggingModel] = useState("gpt-4o");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const { showToast } = useToast();
|
||||
|
||||
// Sync with external open state
|
||||
useEffect(() => {
|
||||
if (externalOpen !== undefined) {
|
||||
setOpen(externalOpen);
|
||||
}
|
||||
}, [externalOpen]);
|
||||
|
||||
// Handle open state changes
|
||||
const handleOpenChange = (newOpen: boolean) => {
|
||||
setOpen(newOpen);
|
||||
// Only call onOpenChange when there's actually a change
|
||||
if (onOpenChange && newOpen !== externalOpen) {
|
||||
onOpenChange(newOpen);
|
||||
}
|
||||
};
|
||||
|
||||
// Load current config on dialog open
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setIsLoading(true);
|
||||
window.electronAPI
|
||||
.getConfig()
|
||||
.then((config) => {
|
||||
setApiKey(config.apiKey || "");
|
||||
setExtractionModel(config.extractionModel || "gpt-4o");
|
||||
setSolutionModel(config.solutionModel || "gpt-4o");
|
||||
setDebuggingModel(config.debuggingModel || "gpt-4o");
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Failed to load config:", error);
|
||||
showToast("Error", "Failed to load settings", "error");
|
||||
})
|
||||
.finally(() => {
|
||||
setIsLoading(false);
|
||||
});
|
||||
}
|
||||
}, [open, showToast]);
|
||||
|
||||
const handleSave = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const result = await window.electronAPI.updateConfig({
|
||||
apiKey,
|
||||
extractionModel,
|
||||
solutionModel,
|
||||
debuggingModel,
|
||||
});
|
||||
|
||||
if (result) {
|
||||
showToast("Success", "Settings saved successfully", "success");
|
||||
handleOpenChange(false);
|
||||
|
||||
// Force reload the app to apply the API key
|
||||
setTimeout(() => {
|
||||
window.location.reload();
|
||||
}, 1500);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to save settings:", error);
|
||||
showToast("Error", "Failed to save settings", "error");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Mask API key for display
|
||||
const maskApiKey = (key: string) => {
|
||||
if (!key || key.length < 10) return "";
|
||||
return `${key.substring(0, 4)}...${key.substring(key.length - 4)}`;
|
||||
};
|
||||
|
||||
// Open external link handler
|
||||
const openExternalLink = (url: string) => {
|
||||
window.electronAPI.openLink(url);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
{/* Removed unnecessary dialog trigger - using the icon in QueueCommands instead */}
|
||||
<DialogContent
|
||||
className="sm:max-w-md bg-black border border-white/10 text-white settings-dialog"
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: '50%',
|
||||
left: '50%',
|
||||
transform: 'translate(-50%, -50%)',
|
||||
width: 'min(450px, 90vw)',
|
||||
height: 'auto',
|
||||
minHeight: '400px',
|
||||
maxHeight: '90vh',
|
||||
overflowY: 'auto',
|
||||
zIndex: 9999,
|
||||
margin: 0,
|
||||
padding: '20px',
|
||||
transition: 'opacity 0.25s ease, transform 0.25s ease',
|
||||
animation: 'fadeIn 0.25s ease forwards',
|
||||
opacity: 0.98
|
||||
}}
|
||||
> <DialogHeader>
|
||||
<DialogTitle>OpenAI API Settings</DialogTitle>
|
||||
<DialogDescription className="text-white/70">
|
||||
Configure your OpenAI API key and model preferences. You'll need your own OpenAI API key to use this application.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-white" htmlFor="apiKey">
|
||||
OpenAI API Key
|
||||
</label>
|
||||
<Input
|
||||
id="apiKey"
|
||||
type="password"
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
placeholder="sk-..."
|
||||
className="bg-black/50 border-white/10 text-white"
|
||||
/>
|
||||
{apiKey && (
|
||||
<p className="text-xs text-white/50">
|
||||
Current: {maskApiKey(apiKey)}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-xs text-white/50">
|
||||
Your API key is stored locally and never sent to any server except OpenAI
|
||||
</p>
|
||||
<div className="mt-2 p-2 rounded-md bg-white/5 border border-white/10">
|
||||
<p className="text-xs text-white/80 mb-1">Don't have an API key?</p>
|
||||
<p className="text-xs text-white/60 mb-1">1. Create an account at <button
|
||||
onClick={() => openExternalLink('https://platform.openai.com/signup')}
|
||||
className="text-blue-400 hover:underline cursor-pointer">OpenAI</button>
|
||||
</p>
|
||||
<p className="text-xs text-white/60 mb-1">2. Go to <button
|
||||
onClick={() => openExternalLink('https://platform.openai.com/api-keys')}
|
||||
className="text-blue-400 hover:underline cursor-pointer">API Keys</button> section
|
||||
</p>
|
||||
<p className="text-xs text-white/60">3. Create a new secret key and paste it here</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 mt-4">
|
||||
<label className="text-sm font-medium text-white mb-2 block">Keyboard Shortcuts</label>
|
||||
<div className="bg-black/30 border border-white/10 rounded-lg p-3">
|
||||
<div className="grid grid-cols-2 gap-y-2 text-xs">
|
||||
<div className="text-white/70">Toggle Visibility</div>
|
||||
<div className="text-white/90 font-mono">Ctrl+B / Cmd+B</div>
|
||||
|
||||
<div className="text-white/70">Take Screenshot</div>
|
||||
<div className="text-white/90 font-mono">Ctrl+H / Cmd+H</div>
|
||||
|
||||
<div className="text-white/70">Process Screenshots</div>
|
||||
<div className="text-white/90 font-mono">Ctrl+Enter / Cmd+Enter</div>
|
||||
|
||||
<div className="text-white/70">Delete Last Screenshot</div>
|
||||
<div className="text-white/90 font-mono">Ctrl+L / Cmd+L</div>
|
||||
|
||||
<div className="text-white/70">Reset View</div>
|
||||
<div className="text-white/90 font-mono">Ctrl+R / Cmd+R</div>
|
||||
|
||||
<div className="text-white/70">Quit Application</div>
|
||||
<div className="text-white/90 font-mono">Ctrl+Q / Cmd+Q</div>
|
||||
|
||||
<div className="text-white/70">Move Window</div>
|
||||
<div className="text-white/90 font-mono">Ctrl+Arrow Keys</div>
|
||||
|
||||
<div className="text-white/70">Decrease Opacity</div>
|
||||
<div className="text-white/90 font-mono">Ctrl+[ / Cmd+[</div>
|
||||
|
||||
<div className="text-white/70">Increase Opacity</div>
|
||||
<div className="text-white/90 font-mono">Ctrl+] / Cmd+]</div>
|
||||
|
||||
<div className="text-white/70">Zoom Out</div>
|
||||
<div className="text-white/90 font-mono">Ctrl+- / Cmd+-</div>
|
||||
|
||||
<div className="text-white/70">Reset Zoom</div>
|
||||
<div className="text-white/90 font-mono">Ctrl+0 / Cmd+0</div>
|
||||
|
||||
<div className="text-white/70">Zoom In</div>
|
||||
<div className="text-white/90 font-mono">Ctrl+= / Cmd+=</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 mt-4">
|
||||
<label className="text-sm font-medium text-white">AI Model Selection</label>
|
||||
<p className="text-xs text-white/60 -mt-3 mb-2">
|
||||
Select which models to use for each stage of the process
|
||||
</p>
|
||||
|
||||
{modelCategories.map((category) => (
|
||||
<div key={category.key} className="mb-4">
|
||||
<label className="text-sm font-medium text-white mb-1 block">
|
||||
{category.title}
|
||||
</label>
|
||||
<p className="text-xs text-white/60 mb-2">{category.description}</p>
|
||||
|
||||
<div className="space-y-2">
|
||||
{category.models.map((m) => {
|
||||
// Determine which state to use based on category key
|
||||
const currentValue =
|
||||
category.key === 'extractionModel' ? extractionModel :
|
||||
category.key === 'solutionModel' ? solutionModel :
|
||||
debuggingModel;
|
||||
|
||||
// Determine which setter function to use
|
||||
const setValue =
|
||||
category.key === 'extractionModel' ? setExtractionModel :
|
||||
category.key === 'solutionModel' ? setSolutionModel :
|
||||
setDebuggingModel;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={m.id}
|
||||
className={`p-2 rounded-lg cursor-pointer transition-colors ${
|
||||
currentValue === m.id
|
||||
? "bg-white/10 border border-white/20"
|
||||
: "bg-black/30 border border-white/5 hover:bg-white/5"
|
||||
}`}
|
||||
onClick={() => setValue(m.id)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className={`w-3 h-3 rounded-full ${
|
||||
currentValue === m.id ? "bg-white" : "bg-white/20"
|
||||
}`}
|
||||
/>
|
||||
<div>
|
||||
<p className="font-medium text-white text-xs">{m.name}</p>
|
||||
<p className="text-xs text-white/60">{m.description}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter className="flex justify-between sm:justify-between">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
className="border-white/10 hover:bg-white/5 text-white"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
className="px-4 py-3 bg-white text-black rounded-xl font-medium hover:bg-white/90 transition-colors"
|
||||
onClick={handleSave}
|
||||
disabled={isLoading || !apiKey}
|
||||
>
|
||||
{isLoading ? "Saving..." : "Save Settings"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@ -0,0 +1,466 @@
|
||||
import React, { useState, useEffect, useRef } from "react"
|
||||
import { useToast } from "../../contexts/toast"
|
||||
import { Screenshot } from "../../types/screenshots"
|
||||
import { supabase } from "../../lib/supabase"
|
||||
import { LanguageSelector } from "../shared/LanguageSelector"
|
||||
import { COMMAND_KEY } from "../../utils/platform"
|
||||
|
||||
export interface SolutionCommandsProps {
|
||||
onTooltipVisibilityChange: (visible: boolean, height: number) => void
|
||||
isProcessing: boolean
|
||||
screenshots?: Screenshot[]
|
||||
extraScreenshots?: Screenshot[]
|
||||
credits: number
|
||||
currentLanguage: string
|
||||
setLanguage: (language: string) => void
|
||||
}
|
||||
|
||||
const handleSignOut = async () => {
|
||||
try {
|
||||
// Clear any local storage or electron-specific data first
|
||||
localStorage.clear()
|
||||
sessionStorage.clear()
|
||||
|
||||
// Then sign out from Supabase
|
||||
const { error } = await supabase.auth.signOut()
|
||||
if (error) throw error
|
||||
} catch (err) {
|
||||
console.error("Error signing out:", err)
|
||||
}
|
||||
}
|
||||
|
||||
const SolutionCommands: React.FC<SolutionCommandsProps> = ({
|
||||
onTooltipVisibilityChange,
|
||||
isProcessing,
|
||||
extraScreenshots = [],
|
||||
credits,
|
||||
currentLanguage,
|
||||
setLanguage
|
||||
}) => {
|
||||
const [isTooltipVisible, setIsTooltipVisible] = useState(false)
|
||||
const tooltipRef = useRef<HTMLDivElement>(null)
|
||||
const { showToast } = useToast()
|
||||
|
||||
useEffect(() => {
|
||||
if (onTooltipVisibilityChange) {
|
||||
let tooltipHeight = 0
|
||||
if (tooltipRef.current && isTooltipVisible) {
|
||||
tooltipHeight = tooltipRef.current.offsetHeight + 10 // Adjust if necessary
|
||||
}
|
||||
onTooltipVisibilityChange(isTooltipVisible, tooltipHeight)
|
||||
}
|
||||
}, [isTooltipVisible, onTooltipVisibilityChange])
|
||||
|
||||
const handleMouseEnter = () => {
|
||||
setIsTooltipVisible(true)
|
||||
}
|
||||
|
||||
const handleMouseLeave = () => {
|
||||
setIsTooltipVisible(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="pt-2 w-fit">
|
||||
<div className="text-xs text-white/90 backdrop-blur-md bg-black/60 rounded-lg py-2 px-4 flex items-center justify-center gap-4">
|
||||
{/* Show/Hide - Always visible */}
|
||||
<div
|
||||
className="flex items-center gap-2 cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
|
||||
onClick={async () => {
|
||||
try {
|
||||
const result = await window.electronAPI.toggleMainWindow()
|
||||
if (!result.success) {
|
||||
console.error("Failed to toggle window:", result.error)
|
||||
showToast("Error", "Failed to toggle window", "error")
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error toggling window:", error)
|
||||
showToast("Error", "Failed to toggle window", "error")
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span className="text-[11px] leading-none">Show/Hide</span>
|
||||
<div className="flex gap-1">
|
||||
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
|
||||
{COMMAND_KEY}
|
||||
</button>
|
||||
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
|
||||
B
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Screenshot and Debug commands - Only show if not processing */}
|
||||
{!isProcessing && (
|
||||
<>
|
||||
<div
|
||||
className="flex items-center gap-2 cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
|
||||
onClick={async () => {
|
||||
try {
|
||||
const result = await window.electronAPI.triggerScreenshot()
|
||||
if (!result.success) {
|
||||
console.error("Failed to take screenshot:", result.error)
|
||||
showToast("Error", "Failed to take screenshot", "error")
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error taking screenshot:", error)
|
||||
showToast("Error", "Failed to take screenshot", "error")
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span className="text-[11px] leading-none truncate">
|
||||
{extraScreenshots.length === 0
|
||||
? "Screenshot your code"
|
||||
: "Screenshot"}
|
||||
</span>
|
||||
<div className="flex gap-1">
|
||||
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
|
||||
{COMMAND_KEY}
|
||||
</button>
|
||||
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
|
||||
H
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{extraScreenshots.length > 0 && (
|
||||
<div
|
||||
className="flex items-center gap-2 cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
|
||||
onClick={async () => {
|
||||
try {
|
||||
const result =
|
||||
await window.electronAPI.triggerProcessScreenshots()
|
||||
if (!result.success) {
|
||||
console.error(
|
||||
"Failed to process screenshots:",
|
||||
result.error
|
||||
)
|
||||
showToast(
|
||||
"Error",
|
||||
"Failed to process screenshots",
|
||||
"error"
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error processing screenshots:", error)
|
||||
showToast(
|
||||
"Error",
|
||||
"Failed to process screenshots",
|
||||
"error"
|
||||
)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span className="text-[11px] leading-none">Debug</span>
|
||||
<div className="flex gap-1">
|
||||
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
|
||||
{COMMAND_KEY}
|
||||
</button>
|
||||
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
|
||||
↵
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Start Over - Always visible */}
|
||||
<div
|
||||
className="flex items-center gap-2 cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
|
||||
onClick={async () => {
|
||||
try {
|
||||
const result = await window.electronAPI.triggerReset()
|
||||
if (!result.success) {
|
||||
console.error("Failed to reset:", result.error)
|
||||
showToast("Error", "Failed to reset", "error")
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error resetting:", error)
|
||||
showToast("Error", "Failed to reset", "error")
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span className="text-[11px] leading-none">Start Over</span>
|
||||
<div className="flex gap-1">
|
||||
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
|
||||
{COMMAND_KEY}
|
||||
</button>
|
||||
<button className="bg-white/10 rounded-md px-1.5 py-1 text-[11px] leading-none text-white/70">
|
||||
R
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Separator */}
|
||||
<div className="mx-2 h-4 w-px bg-white/20" />
|
||||
|
||||
{/* Settings with Tooltip */}
|
||||
<div
|
||||
className="relative inline-block"
|
||||
onMouseEnter={handleMouseEnter}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
>
|
||||
{/* Gear icon */}
|
||||
<div className="w-4 h-4 flex items-center justify-center cursor-pointer text-white/70 hover:text-white/90 transition-colors">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className="w-3.5 h-3.5"
|
||||
>
|
||||
<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" />
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
{/* Tooltip Content */}
|
||||
{isTooltipVisible && (
|
||||
<div
|
||||
ref={tooltipRef}
|
||||
className="absolute top-full right-0 mt-2 w-80"
|
||||
style={{ zIndex: 100 }}
|
||||
>
|
||||
{/* Add transparent bridge */}
|
||||
<div className="absolute -top-2 right-0 w-full h-2" />
|
||||
<div className="p-3 text-xs bg-black/80 backdrop-blur-md rounded-lg border border-white/10 text-white/90 shadow-lg">
|
||||
<div className="space-y-4">
|
||||
<h3 className="font-medium whitespace-nowrap">
|
||||
Keyboard Shortcuts
|
||||
</h3>
|
||||
<div className="space-y-3">
|
||||
{/* Show/Hide - Always visible */}
|
||||
<div
|
||||
className="cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
|
||||
onClick={async () => {
|
||||
try {
|
||||
const result =
|
||||
await window.electronAPI.toggleMainWindow()
|
||||
if (!result.success) {
|
||||
console.error(
|
||||
"Failed to toggle window:",
|
||||
result.error
|
||||
)
|
||||
showToast(
|
||||
"Error",
|
||||
"Failed to toggle window",
|
||||
"error"
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error toggling window:", error)
|
||||
showToast(
|
||||
"Error",
|
||||
"Failed to toggle window",
|
||||
"error"
|
||||
)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="truncate">Toggle Window</span>
|
||||
<div className="flex gap-1 flex-shrink-0">
|
||||
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
|
||||
{COMMAND_KEY}
|
||||
</span>
|
||||
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
|
||||
B
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-[10px] leading-relaxed text-white/70 truncate mt-1">
|
||||
Show or hide this window.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Screenshot and Debug commands - Only show if not processing */}
|
||||
{!isProcessing && (
|
||||
<>
|
||||
<div
|
||||
className="cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
|
||||
onClick={async () => {
|
||||
try {
|
||||
const result =
|
||||
await window.electronAPI.triggerScreenshot()
|
||||
if (!result.success) {
|
||||
console.error(
|
||||
"Failed to take screenshot:",
|
||||
result.error
|
||||
)
|
||||
showToast(
|
||||
"Error",
|
||||
"Failed to take screenshot",
|
||||
"error"
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error taking screenshot:", error)
|
||||
showToast(
|
||||
"Error",
|
||||
"Failed to take screenshot",
|
||||
"error"
|
||||
)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="truncate">Take Screenshot</span>
|
||||
<div className="flex gap-1 flex-shrink-0">
|
||||
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
|
||||
{COMMAND_KEY}
|
||||
</span>
|
||||
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
|
||||
H
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-[10px] leading-relaxed text-white/70 truncate mt-1">
|
||||
Capture additional parts of the question or your
|
||||
solution for debugging help.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{extraScreenshots.length > 0 && (
|
||||
<div
|
||||
className="cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
|
||||
onClick={async () => {
|
||||
try {
|
||||
const result =
|
||||
await window.electronAPI.triggerProcessScreenshots()
|
||||
if (!result.success) {
|
||||
console.error(
|
||||
"Failed to process screenshots:",
|
||||
result.error
|
||||
)
|
||||
showToast(
|
||||
"Error",
|
||||
"Failed to process screenshots",
|
||||
"error"
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"Error processing screenshots:",
|
||||
error
|
||||
)
|
||||
showToast(
|
||||
"Error",
|
||||
"Failed to process screenshots",
|
||||
"error"
|
||||
)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="truncate">Debug</span>
|
||||
<div className="flex gap-1 flex-shrink-0">
|
||||
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
|
||||
{COMMAND_KEY}
|
||||
</span>
|
||||
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
|
||||
↵
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-[10px] leading-relaxed text-white/70 truncate mt-1">
|
||||
Generate new solutions based on all previous and
|
||||
newly added screenshots.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Start Over - Always visible */}
|
||||
<div
|
||||
className="cursor-pointer rounded px-2 py-1.5 hover:bg-white/10 transition-colors"
|
||||
onClick={async () => {
|
||||
try {
|
||||
const result =
|
||||
await window.electronAPI.triggerReset()
|
||||
if (!result.success) {
|
||||
console.error("Failed to reset:", result.error)
|
||||
showToast("Error", "Failed to reset", "error")
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error resetting:", error)
|
||||
showToast("Error", "Failed to reset", "error")
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="truncate">Start Over</span>
|
||||
<div className="flex gap-1 flex-shrink-0">
|
||||
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
|
||||
{COMMAND_KEY}
|
||||
</span>
|
||||
<span className="bg-white/20 px-1.5 py-0.5 rounded text-[10px] leading-none">
|
||||
R
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-[10px] leading-relaxed text-white/70 truncate mt-1">
|
||||
Start fresh with a new question.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Separator and Log Out */}
|
||||
<div className="pt-3 mt-3 border-t border-white/10">
|
||||
<LanguageSelector
|
||||
currentLanguage={currentLanguage}
|
||||
setLanguage={setLanguage}
|
||||
/>
|
||||
|
||||
{/* API Key Settings */}
|
||||
<div className="mb-3 px-2 space-y-1">
|
||||
<div className="flex items-center justify-between text-[13px] font-medium text-white/90">
|
||||
<span>OpenAI API Settings</span>
|
||||
<button
|
||||
className="bg-white/10 hover:bg-white/20 px-2 py-1 rounded text-[11px]"
|
||||
onClick={() => window.electronAPI.openSettingsPortal()}
|
||||
>
|
||||
Settings
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleSignOut}
|
||||
className="flex items-center gap-2 text-[11px] text-red-400 hover:text-red-300 transition-colors w-full"
|
||||
>
|
||||
<div className="w-4 h-4 flex items-center justify-center">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className="w-3 h-3"
|
||||
>
|
||||
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
|
||||
<polyline points="16 17 21 12 16 7" />
|
||||
<line x1="21" y1="12" x2="9" y2="12" />
|
||||
</svg>
|
||||
</div>
|
||||
Log Out
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default SolutionCommands
|
||||
@ -0,0 +1,101 @@
|
||||
import React, { useEffect, useState } from "react"
|
||||
import { Dialog, DialogContent } from "./ui/dialog"
|
||||
import { Button } from "./ui/button"
|
||||
import { useToast } from "../contexts/toast"
|
||||
|
||||
export const UpdateNotification: React.FC = () => {
|
||||
const [updateAvailable, setUpdateAvailable] = useState(false)
|
||||
const [updateDownloaded, setUpdateDownloaded] = useState(false)
|
||||
const [isDownloading, setIsDownloading] = useState(false)
|
||||
const { showToast } = useToast()
|
||||
|
||||
useEffect(() => {
|
||||
console.log("UpdateNotification: Setting up event listeners")
|
||||
|
||||
const unsubscribeAvailable = window.electronAPI.onUpdateAvailable(
|
||||
(info) => {
|
||||
console.log("UpdateNotification: Update available received", info)
|
||||
setUpdateAvailable(true)
|
||||
}
|
||||
)
|
||||
|
||||
const unsubscribeDownloaded = window.electronAPI.onUpdateDownloaded(
|
||||
(info) => {
|
||||
console.log("UpdateNotification: Update downloaded received", info)
|
||||
setUpdateDownloaded(true)
|
||||
setIsDownloading(false)
|
||||
}
|
||||
)
|
||||
|
||||
return () => {
|
||||
console.log("UpdateNotification: Cleaning up event listeners")
|
||||
unsubscribeAvailable()
|
||||
unsubscribeDownloaded()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleStartUpdate = async () => {
|
||||
console.log("UpdateNotification: Starting update download")
|
||||
setIsDownloading(true)
|
||||
const result = await window.electronAPI.startUpdate()
|
||||
console.log("UpdateNotification: Update download result", result)
|
||||
if (!result.success) {
|
||||
setIsDownloading(false)
|
||||
showToast("Error", "Failed to download update", "error")
|
||||
}
|
||||
}
|
||||
|
||||
const handleInstallUpdate = () => {
|
||||
console.log("UpdateNotification: Installing update")
|
||||
window.electronAPI.installUpdate()
|
||||
}
|
||||
|
||||
console.log("UpdateNotification: Render state", {
|
||||
updateAvailable,
|
||||
updateDownloaded,
|
||||
isDownloading
|
||||
})
|
||||
if (!updateAvailable && !updateDownloaded) return null
|
||||
|
||||
return (
|
||||
<Dialog open={true}>
|
||||
<DialogContent
|
||||
className="bg-black/90 text-white border-white/20"
|
||||
onPointerDownOutside={(e) => e.preventDefault()}
|
||||
>
|
||||
<div className="p-4">
|
||||
<h2 className="text-lg font-semibold mb-4">
|
||||
{updateDownloaded
|
||||
? "Update Ready to Install"
|
||||
: "A New Version is Available"}
|
||||
</h2>
|
||||
<p className="text-sm text-white/70 mb-6">
|
||||
{updateDownloaded
|
||||
? "The update has been downloaded and will be installed when you restart the app."
|
||||
: "A new version of Interview Coder is available. Please update to continue using the app."}
|
||||
</p>
|
||||
<div className="flex justify-end gap-2">
|
||||
{updateDownloaded ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleInstallUpdate}
|
||||
className="border-white/20 hover:bg-white/10"
|
||||
>
|
||||
Restart and Install
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleStartUpdate}
|
||||
disabled={isDownloading}
|
||||
className="border-white/20 hover:bg-white/10"
|
||||
>
|
||||
{isDownloading ? "Downloading..." : "Download Update"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@ -0,0 +1,73 @@
|
||||
import React from 'react';
|
||||
import { Button } from './ui/button';
|
||||
|
||||
interface WelcomeScreenProps {
|
||||
onOpenSettings: () => void;
|
||||
}
|
||||
|
||||
export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({ onOpenSettings }) => {
|
||||
return (
|
||||
<div className="bg-black min-h-screen flex flex-col items-center justify-center p-6">
|
||||
<div className="max-w-md w-full bg-black border border-white/10 rounded-xl p-6 shadow-lg">
|
||||
<h1 className="text-2xl font-bold text-white mb-6 flex items-center gap-2">
|
||||
<span>Interview Coder</span>
|
||||
<span className="text-sm font-normal px-2 py-0.5 bg-blue-500/20 text-blue-400 rounded-md">Unlocked Edition</span>
|
||||
</h1>
|
||||
|
||||
<div className="mb-8">
|
||||
<h2 className="text-lg font-medium text-white mb-3">Welcome to Interview Coder</h2>
|
||||
<p className="text-white/70 text-sm mb-4">
|
||||
This application helps you ace technical interviews by providing AI-powered
|
||||
solutions to coding problems.
|
||||
</p>
|
||||
<div className="bg-white/5 border border-white/10 rounded-lg p-4 mb-4">
|
||||
<h3 className="text-white/90 font-medium mb-2">Global Shortcuts</h3>
|
||||
<ul className="space-y-2">
|
||||
<li className="flex justify-between text-sm">
|
||||
<span className="text-white/70">Toggle Visibility</span>
|
||||
<span className="text-white/90">Ctrl+B / Cmd+B</span>
|
||||
</li>
|
||||
<li className="flex justify-between text-sm">
|
||||
<span className="text-white/70">Take Screenshot</span>
|
||||
<span className="text-white/90">Ctrl+H / Cmd+H</span>
|
||||
</li>
|
||||
<li className="flex justify-between text-sm">
|
||||
<span className="text-white/70">Delete Last Screenshot</span>
|
||||
<span className="text-white/90">Ctrl+L / Cmd+L</span>
|
||||
</li>
|
||||
<li className="flex justify-between text-sm">
|
||||
<span className="text-white/70">Process Screenshots</span>
|
||||
<span className="text-white/90">Ctrl+Enter / Cmd+Enter</span>
|
||||
</li>
|
||||
<li className="flex justify-between text-sm">
|
||||
<span className="text-white/70">Reset View</span>
|
||||
<span className="text-white/90">Ctrl+R / Cmd+R</span>
|
||||
</li>
|
||||
<li className="flex justify-between text-sm">
|
||||
<span className="text-white/70">Quit App</span>
|
||||
<span className="text-white/90">Ctrl+Q / Cmd+Q</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white/5 border border-white/10 rounded-lg p-4 mb-6">
|
||||
<h3 className="text-white/90 font-medium mb-2">Getting Started</h3>
|
||||
<p className="text-white/70 text-sm mb-3">
|
||||
Before using the application, you need to configure your OpenAI API key.
|
||||
</p>
|
||||
<Button
|
||||
className="w-full px-4 py-3 bg-white text-black rounded-xl font-medium hover:bg-white/90 transition-colors flex items-center justify-center gap-2"
|
||||
onClick={onOpenSettings}
|
||||
>
|
||||
Open Settings
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="text-white/40 text-xs text-center">
|
||||
Start by taking screenshots of your coding problem (Ctrl+H / Cmd+H)
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@ -0,0 +1,57 @@
|
||||
import React from "react"
|
||||
|
||||
interface LanguageSelectorProps {
|
||||
currentLanguage: string
|
||||
setLanguage: (language: string) => void
|
||||
}
|
||||
|
||||
export const LanguageSelector: React.FC<LanguageSelectorProps> = ({
|
||||
currentLanguage,
|
||||
setLanguage
|
||||
}) => {
|
||||
const handleLanguageChange = async (
|
||||
e: React.ChangeEvent<HTMLSelectElement>
|
||||
) => {
|
||||
const newLanguage = e.target.value
|
||||
|
||||
try {
|
||||
// Save language preference to electron store
|
||||
await window.electronAPI.updateConfig({ language: newLanguage })
|
||||
|
||||
// Update global language variable
|
||||
window.__LANGUAGE__ = newLanguage
|
||||
|
||||
// Update state in React
|
||||
setLanguage(newLanguage)
|
||||
|
||||
console.log(`Language changed to ${newLanguage}`);
|
||||
} catch (error) {
|
||||
console.error("Error updating language:", error)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mb-3 px-2 space-y-1">
|
||||
<div className="flex items-center justify-between text-[13px] font-medium text-white/90">
|
||||
<span>Language</span>
|
||||
<select
|
||||
value={currentLanguage}
|
||||
onChange={handleLanguageChange}
|
||||
className="bg-black/80 text-white/90 rounded px-2 py-1 text-sm outline-none border border-white/10 focus:border-white/20"
|
||||
style={{ WebkitAppearance: 'menulist' }}
|
||||
>
|
||||
<option value="python" className="bg-black text-white">Python</option>
|
||||
<option value="javascript" className="bg-black text-white">JavaScript</option>
|
||||
<option value="java" className="bg-black text-white">Java</option>
|
||||
<option value="golang" className="bg-black text-white">Go</option>
|
||||
<option value="cpp" className="bg-black text-white">C++</option>
|
||||
<option value="swift" className="bg-black text-white">Swift</option>
|
||||
<option value="kotlin" className="bg-black text-white">Kotlin</option>
|
||||
<option value="ruby" className="bg-black text-white">Ruby</option>
|
||||
<option value="sql" className="bg-black text-white">SQL</option>
|
||||
<option value="r" className="bg-black text-white">R</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -0,0 +1,56 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "../../lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"bg-primary text-primary-foreground shadow hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
|
||||
outline:
|
||||
"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
link: "text-primary underline-offset-4 hover:underline"
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2",
|
||||
sm: "h-8 rounded-md px-3 text-xs",
|
||||
lg: "h-10 rounded-md px-8",
|
||||
icon: "h-9 w-9"
|
||||
}
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default"
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof buttonVariants> {
|
||||
asChild?: boolean
|
||||
}
|
||||
|
||||
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
({ className, variant, size, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
return (
|
||||
<Comp
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
)
|
||||
Button.displayName = "Button"
|
||||
|
||||
export { Button, buttonVariants }
|
||||
@ -0,0 +1,75 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "../../lib/utils"
|
||||
|
||||
const Card = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"rounded-xl border bg-card text-card-foreground shadow",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
Card.displayName = "Card"
|
||||
|
||||
const CardHeader = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("flex flex-col space-y-1.5 p-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
CardHeader.displayName = "CardHeader"
|
||||
|
||||
const CardTitle = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLHeadingElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<h3
|
||||
ref={ref}
|
||||
className={cn("font-semibold leading-none tracking-tight", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
CardTitle.displayName = "CardTitle"
|
||||
|
||||
const CardDescription = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<p
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
CardDescription.displayName = "CardDescription"
|
||||
|
||||
const CardContent = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
|
||||
))
|
||||
CardContent.displayName = "CardContent"
|
||||
|
||||
const CardFooter = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("flex items-center p-6 pt-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
CardFooter.displayName = "CardFooter"
|
||||
|
||||
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
|
||||
@ -0,0 +1,98 @@
|
||||
// src/components/ui/dialog.tsx
|
||||
|
||||
import * as React from "react"
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||
import { cn } from "../../lib/utils"
|
||||
|
||||
const Dialog = DialogPrimitive.Root
|
||||
const DialogTrigger = DialogPrimitive.Trigger
|
||||
const DialogPortal = DialogPrimitive.Portal
|
||||
|
||||
const DialogOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn("fixed inset-0 bg-black bg-opacity-50 z-50", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
|
||||
|
||||
const DialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed z-50 top-[50%] left-[50%] -translate-x-1/2 -translate-y-1/2",
|
||||
"w-[90vw] max-w-md md:w-full",
|
||||
"bg-white p-4 rounded-lg shadow-lg",
|
||||
"focus:outline-none focus-visible:ring-0",
|
||||
className
|
||||
)}
|
||||
style={{ maxHeight: '90vh', overflow: 'auto' }}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
))
|
||||
DialogContent.displayName = DialogPrimitive.Content.displayName
|
||||
|
||||
const DialogClose = DialogPrimitive.Close
|
||||
|
||||
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn("flex flex-col space-y-1.5 text-left mb-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
DialogHeader.displayName = "DialogHeader"
|
||||
|
||||
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2 mt-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
DialogFooter.displayName = "DialogFooter"
|
||||
|
||||
const DialogTitle = React.forwardRef<
|
||||
HTMLHeadingElement,
|
||||
React.HTMLAttributes<HTMLHeadingElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn("text-lg font-semibold text-white", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DialogTitle.displayName = DialogPrimitive.Title.displayName
|
||||
|
||||
const DialogDescription = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm text-gray-400", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DialogDescription.displayName = DialogPrimitive.Description.displayName
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogTrigger,
|
||||
DialogContent,
|
||||
DialogClose,
|
||||
DialogHeader,
|
||||
DialogFooter,
|
||||
DialogTitle,
|
||||
DialogDescription
|
||||
}
|
||||
@ -0,0 +1,24 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "../../lib/utils"
|
||||
|
||||
export interface InputProps
|
||||
extends React.InputHTMLAttributes<HTMLInputElement> {}
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
||||
({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
)
|
||||
Input.displayName = "Input"
|
||||
|
||||
export { Input }
|
||||
@ -0,0 +1,125 @@
|
||||
import * as React from "react"
|
||||
import * as ToastPrimitive from "@radix-ui/react-toast"
|
||||
import { cn } from "../../lib/utils"
|
||||
import { AlertCircle, CheckCircle2, Info, X } from "lucide-react"
|
||||
|
||||
const ToastProvider = ToastPrimitive.Provider
|
||||
|
||||
export type ToastMessage = {
|
||||
title: string
|
||||
description: string
|
||||
variant: ToastVariant
|
||||
}
|
||||
|
||||
const ToastViewport = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitive.Viewport>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitive.Viewport>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitive.Viewport
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed top-0 right-0 z-[100] flex max-h-screen w-full flex-col-reverse gap-1 p-2 sm:top-0 sm:right-0 sm:flex-col md:max-w-[320px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastViewport.displayName = ToastPrimitive.Viewport.displayName
|
||||
|
||||
type ToastVariant = "neutral" | "success" | "error"
|
||||
|
||||
interface ToastProps
|
||||
extends React.ComponentPropsWithoutRef<typeof ToastPrimitive.Root> {
|
||||
variant?: ToastVariant
|
||||
swipeDirection?: "right" | "left" | "up" | "down"
|
||||
}
|
||||
|
||||
const toastVariants: Record<
|
||||
ToastVariant,
|
||||
{ icon: React.ReactNode; bgColor: string }
|
||||
> = {
|
||||
neutral: {
|
||||
icon: <Info className="h-3 w-3 text-amber-700" />,
|
||||
bgColor: "bg-amber-100"
|
||||
},
|
||||
success: {
|
||||
icon: <CheckCircle2 className="h-3 w-3 text-emerald-700" />,
|
||||
bgColor: "bg-emerald-100"
|
||||
},
|
||||
error: {
|
||||
icon: <AlertCircle className="h-3 w-3 text-red-700" />,
|
||||
bgColor: "bg-red-100"
|
||||
}
|
||||
}
|
||||
|
||||
const Toast = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitive.Root>,
|
||||
ToastProps
|
||||
>(({ className, variant = "neutral", ...props }, ref) => (
|
||||
<ToastPrimitive.Root
|
||||
ref={ref}
|
||||
duration={4000}
|
||||
className={cn(
|
||||
"group pointer-events-auto relative flex w-full items-center space-x-2 overflow-hidden rounded-md p-2",
|
||||
toastVariants[variant].bgColor,
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{toastVariants[variant].icon}
|
||||
<div className="flex-1">{props.children}</div>
|
||||
<ToastPrimitive.Close className="absolute right-1 top-1 rounded-md p-0.5 text-zinc-500 opacity-0 transition-opacity hover:text-zinc-700 group-hover:opacity-100">
|
||||
<X className="h-2 w-2" />
|
||||
</ToastPrimitive.Close>
|
||||
</ToastPrimitive.Root>
|
||||
))
|
||||
Toast.displayName = ToastPrimitive.Root.displayName
|
||||
|
||||
const ToastAction = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitive.Action>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitive.Action>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitive.Action
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"text-[0.65rem] font-medium text-zinc-600 hover:text-zinc-900",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastAction.displayName = ToastPrimitive.Action.displayName
|
||||
|
||||
const ToastTitle = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn("text-[0.7rem] font-medium text-zinc-900", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastTitle.displayName = ToastPrimitive.Title.displayName
|
||||
|
||||
const ToastDescription = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-[0.65rem] text-zinc-600", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastDescription.displayName = ToastPrimitive.Description.displayName
|
||||
|
||||
export type { ToastProps, ToastVariant }
|
||||
export {
|
||||
ToastProvider,
|
||||
ToastViewport,
|
||||
Toast,
|
||||
ToastAction,
|
||||
ToastTitle,
|
||||
ToastDescription
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
import { createContext, useContext } from "react"
|
||||
|
||||
type ToastVariant = "neutral" | "success" | "error"
|
||||
|
||||
interface ToastContextType {
|
||||
showToast: (title: string, description: string, variant: ToastVariant) => void
|
||||
}
|
||||
|
||||
export const ToastContext = createContext<ToastContextType | undefined>(
|
||||
undefined
|
||||
)
|
||||
|
||||
export function useToast() {
|
||||
const context = useContext(ToastContext)
|
||||
if (!context) {
|
||||
throw new Error("useToast must be used within a ToastProvider")
|
||||
}
|
||||
return context
|
||||
}
|
||||
@ -0,0 +1,76 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
import { ToastMessage } from "./components/ui/toast"
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_SUPABASE_URL: string
|
||||
readonly VITE_SUPABASE_ANON_KEY: string
|
||||
readonly NODE_ENV: string
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv
|
||||
}
|
||||
|
||||
interface ElectronAPI {
|
||||
openSubscriptionPortal: (authData: {
|
||||
id: string
|
||||
email: string
|
||||
}) => Promise<{ success: boolean; error?: string }>
|
||||
updateContentDimensions: (dimensions: {
|
||||
width: number
|
||||
height: number
|
||||
}) => Promise<void>
|
||||
clearStore: () => Promise<{ success: boolean; error?: string }>
|
||||
getScreenshots: () => Promise<{
|
||||
success: boolean
|
||||
previews?: Array<{ path: string; preview: string }> | null
|
||||
error?: string
|
||||
}>
|
||||
deleteScreenshot: (
|
||||
path: string
|
||||
) => Promise<{ success: boolean; error?: string }>
|
||||
onScreenshotTaken: (
|
||||
callback: (data: { path: string; preview: string }) => void
|
||||
) => () => void
|
||||
onResetView: (callback: () => void) => () => void
|
||||
onSolutionStart: (callback: () => void) => () => void
|
||||
onDebugStart: (callback: () => void) => () => void
|
||||
onDebugSuccess: (callback: (data: any) => void) => () => void
|
||||
onSolutionError: (callback: (error: string) => void) => () => void
|
||||
onProcessingNoScreenshots: (callback: () => void) => () => void
|
||||
onProblemExtracted: (callback: (data: any) => void) => () => void
|
||||
onSolutionSuccess: (callback: (data: any) => void) => () => void
|
||||
onUnauthorized: (callback: () => void) => () => void
|
||||
onDebugError: (callback: (error: string) => void) => () => void
|
||||
openExternal: (url: string) => void
|
||||
toggleMainWindow: () => Promise<{ success: boolean; error?: string }>
|
||||
triggerScreenshot: () => Promise<{ success: boolean; error?: string }>
|
||||
triggerProcessScreenshots: () => Promise<{ success: boolean; error?: string }>
|
||||
triggerReset: () => Promise<{ success: boolean; error?: string }>
|
||||
triggerMoveLeft: () => Promise<{ success: boolean; error?: string }>
|
||||
triggerMoveRight: () => Promise<{ success: boolean; error?: string }>
|
||||
triggerMoveUp: () => Promise<{ success: boolean; error?: string }>
|
||||
triggerMoveDown: () => Promise<{ success: boolean; error?: string }>
|
||||
onSubscriptionUpdated: (callback: () => void) => () => void
|
||||
onSubscriptionPortalClosed: (callback: () => void) => () => void
|
||||
// Add update-related methods
|
||||
startUpdate: () => Promise<{ success: boolean; error?: string }>
|
||||
installUpdate: () => void
|
||||
onUpdateAvailable: (callback: (info: any) => void) => () => void
|
||||
onUpdateDownloaded: (callback: (info: any) => void) => () => void
|
||||
}
|
||||
|
||||
interface Window {
|
||||
electronAPI: ElectronAPI
|
||||
electron: {
|
||||
ipcRenderer: {
|
||||
on(channel: string, func: (...args: any[]) => void): void
|
||||
removeListener(channel: string, func: (...args: any[]) => void): void
|
||||
}
|
||||
}
|
||||
__CREDITS__: number
|
||||
__LANGUAGE__: string
|
||||
__IS_INITIALIZED__: boolean
|
||||
__AUTH_TOKEN__: string
|
||||
}
|
||||
@ -0,0 +1,70 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
/* Custom animations for UI elements */
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; transform: translate(-50%, -48%); }
|
||||
to { opacity: 0.98; transform: translate(-50%, -50%); }
|
||||
}
|
||||
|
||||
/* Dialog transition improvements */
|
||||
.settings-dialog {
|
||||
transform-origin: center;
|
||||
backface-visibility: hidden;
|
||||
will-change: opacity, transform;
|
||||
}
|
||||
|
||||
/* Custom styling for dropdowns */
|
||||
select {
|
||||
appearance: menulist;
|
||||
background-color: #000000 !important;
|
||||
color: white !important;
|
||||
}
|
||||
|
||||
option {
|
||||
background-color: #1a1a1a !important;
|
||||
color: white !important;
|
||||
padding: 8px !important;
|
||||
}
|
||||
|
||||
.frosted-glass {
|
||||
background: rgba(26, 26, 26, 0.8);
|
||||
backdrop-filter: blur(8px);
|
||||
}
|
||||
|
||||
.auth-button {
|
||||
background: rgba(252, 252, 252, 0.98);
|
||||
color: rgba(60, 60, 60, 0.9);
|
||||
transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
|
||||
.auth-button:hover {
|
||||
background: rgba(255, 255, 255, 1);
|
||||
}
|
||||
|
||||
.auth-button::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: -8px;
|
||||
background: linear-gradient(45deg, #ff000000, #0000ff00);
|
||||
z-index: -1;
|
||||
transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
border-radius: inherit;
|
||||
filter: blur(24px);
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.auth-button:hover::before {
|
||||
background: linear-gradient(
|
||||
45deg,
|
||||
rgba(255, 0, 0, 0.4),
|
||||
rgba(0, 0, 255, 0.4)
|
||||
);
|
||||
filter: blur(48px);
|
||||
inset: -16px;
|
||||
opacity: 1;
|
||||
}
|
||||
@ -0,0 +1,122 @@
|
||||
import { createClient } from "@supabase/supabase-js"
|
||||
|
||||
console.log("Supabase URL:", import.meta.env.VITE_SUPABASE_URL)
|
||||
console.log(
|
||||
"Supabase Anon Key:",
|
||||
import.meta.env.VITE_SUPABASE_ANON_KEY?.slice(0, 10) + "..."
|
||||
)
|
||||
|
||||
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
|
||||
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY
|
||||
|
||||
if (!supabaseUrl || !supabaseAnonKey) {
|
||||
throw new Error("Missing Supabase environment variables")
|
||||
}
|
||||
|
||||
export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
|
||||
auth: {
|
||||
flowType: "pkce",
|
||||
detectSessionInUrl: true,
|
||||
persistSession: true,
|
||||
autoRefreshToken: true,
|
||||
debug: true,
|
||||
storage: {
|
||||
getItem: (key) => {
|
||||
const item = localStorage.getItem(key)
|
||||
console.log("Auth storage - Getting key:", key, "Value exists:", !!item)
|
||||
return item
|
||||
},
|
||||
setItem: (key, value) => {
|
||||
console.log("Auth storage - Setting key:", key)
|
||||
localStorage.setItem(key, value)
|
||||
},
|
||||
removeItem: (key) => {
|
||||
console.log("Auth storage - Removing key:", key)
|
||||
localStorage.removeItem(key)
|
||||
}
|
||||
}
|
||||
},
|
||||
realtime: {
|
||||
params: {
|
||||
eventsPerSecond: 10
|
||||
},
|
||||
headers: {
|
||||
apikey: supabaseAnonKey
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export const signInWithGoogle = async () => {
|
||||
try {
|
||||
console.log("Initiating Google sign in...")
|
||||
const { data, error } = await supabase.auth.signInWithOAuth({
|
||||
provider: "google",
|
||||
options: {
|
||||
redirectTo: window.location.origin
|
||||
}
|
||||
})
|
||||
|
||||
if (error) {
|
||||
console.error("Google sign in error:", error)
|
||||
throw error
|
||||
}
|
||||
|
||||
console.log("Google sign in response:", data)
|
||||
return data
|
||||
} catch (error) {
|
||||
console.error("Unexpected error during Google sign in:", error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
let channel: ReturnType<typeof supabase.channel> | null = null
|
||||
|
||||
// Monitor auth state changes and manage realtime connection
|
||||
supabase.auth.onAuthStateChange((event, session) => {
|
||||
console.log("Auth state changed:", event, session?.user?.id)
|
||||
console.log("Full session data:", session)
|
||||
|
||||
if (event === "SIGNED_IN" && session) {
|
||||
// Only establish realtime connection after successful sign in
|
||||
console.log("Establishing realtime connection...")
|
||||
|
||||
// Clean up existing channel if any
|
||||
if (channel) {
|
||||
channel.unsubscribe()
|
||||
}
|
||||
|
||||
channel = supabase.channel("system", {
|
||||
config: {
|
||||
presence: {
|
||||
key: session.user.id
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
channel
|
||||
.on("system", { event: "*" }, (payload) => {
|
||||
console.log("System event:", payload)
|
||||
})
|
||||
.subscribe((status) => {
|
||||
console.log("Realtime subscription status:", status)
|
||||
if (status === "SUBSCRIBED") {
|
||||
console.log("Successfully connected to realtime system")
|
||||
}
|
||||
if (status === "CHANNEL_ERROR") {
|
||||
console.error("Realtime connection error - will retry in 5s")
|
||||
setTimeout(() => {
|
||||
channel?.subscribe()
|
||||
}, 5000)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (event === "SIGNED_OUT") {
|
||||
// Clean up realtime connection on sign out
|
||||
if (channel) {
|
||||
console.log("Cleaning up realtime connection")
|
||||
channel.unsubscribe()
|
||||
channel = null
|
||||
}
|
||||
}
|
||||
})
|
||||
@ -0,0 +1,8 @@
|
||||
// src/lib/utils.ts
|
||||
|
||||
import { type ClassValue, clsx } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
import React from "react"
|
||||
import ReactDOM from "react-dom/client"
|
||||
import App from "./App"
|
||||
import "./index.css"
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root")!).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
)
|
||||
@ -0,0 +1,83 @@
|
||||
export interface ElectronAPI {
|
||||
// Original methods
|
||||
openSubscriptionPortal: (authData: {
|
||||
id: string
|
||||
email: string
|
||||
}) => Promise<{ success: boolean; error?: string }>
|
||||
updateContentDimensions: (dimensions: {
|
||||
width: number
|
||||
height: number
|
||||
}) => Promise<void>
|
||||
clearStore: () => Promise<{ success: boolean; error?: string }>
|
||||
getScreenshots: () => Promise<{
|
||||
success: boolean
|
||||
previews?: Array<{ path: string; preview: string }> | null
|
||||
error?: string
|
||||
}>
|
||||
deleteScreenshot: (
|
||||
path: string
|
||||
) => Promise<{ success: boolean; error?: string }>
|
||||
onScreenshotTaken: (
|
||||
callback: (data: { path: string; preview: string }) => void
|
||||
) => () => void
|
||||
onResetView: (callback: () => void) => () => void
|
||||
onSolutionStart: (callback: () => void) => () => void
|
||||
onDebugStart: (callback: () => void) => () => void
|
||||
onDebugSuccess: (callback: (data: any) => void) => () => void
|
||||
onSolutionError: (callback: (error: string) => void) => () => void
|
||||
onProcessingNoScreenshots: (callback: () => void) => () => void
|
||||
onProblemExtracted: (callback: (data: any) => void) => () => void
|
||||
onSolutionSuccess: (callback: (data: any) => void) => () => void
|
||||
onUnauthorized: (callback: () => void) => () => void
|
||||
onDebugError: (callback: (error: string) => void) => () => void
|
||||
openExternal: (url: string) => void
|
||||
toggleMainWindow: () => Promise<{ success: boolean; error?: string }>
|
||||
triggerScreenshot: () => Promise<{ success: boolean; error?: string }>
|
||||
triggerProcessScreenshots: () => Promise<{ success: boolean; error?: string }>
|
||||
triggerReset: () => Promise<{ success: boolean; error?: string }>
|
||||
triggerMoveLeft: () => Promise<{ success: boolean; error?: string }>
|
||||
triggerMoveRight: () => Promise<{ success: boolean; error?: string }>
|
||||
triggerMoveUp: () => Promise<{ success: boolean; error?: string }>
|
||||
triggerMoveDown: () => Promise<{ success: boolean; error?: string }>
|
||||
onSubscriptionUpdated: (callback: () => void) => () => void
|
||||
onSubscriptionPortalClosed: (callback: () => void) => () => void
|
||||
startUpdate: () => Promise<{ success: boolean; error?: string }>
|
||||
installUpdate: () => void
|
||||
onUpdateAvailable: (callback: (info: any) => void) => () => void
|
||||
onUpdateDownloaded: (callback: (info: any) => void) => () => void
|
||||
|
||||
decrementCredits: () => Promise<void>
|
||||
setInitialCredits: (credits: number) => Promise<void>
|
||||
onCreditsUpdated: (callback: (credits: number) => void) => () => void
|
||||
onOutOfCredits: (callback: () => void) => () => void
|
||||
openSettingsPortal: () => Promise<void>
|
||||
getPlatform: () => string
|
||||
|
||||
// New methods for OpenAI integration
|
||||
getConfig: () => Promise<{ apiKey: string; model: string }>
|
||||
updateConfig: (config: { apiKey?: string; model?: string }) => Promise<boolean>
|
||||
checkApiKey: () => Promise<boolean>
|
||||
validateApiKey: (apiKey: string) => Promise<{ valid: boolean; error?: string }>
|
||||
openLink: (url: string) => void
|
||||
onApiKeyInvalid: (callback: () => void) => () => void
|
||||
removeListener: (eventName: string, callback: (...args: any[]) => void) => void
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
electronAPI: ElectronAPI
|
||||
electron: {
|
||||
ipcRenderer: {
|
||||
on: (channel: string, func: (...args: any[]) => void) => void
|
||||
removeListener: (
|
||||
channel: string,
|
||||
func: (...args: any[]) => void
|
||||
) => void
|
||||
}
|
||||
}
|
||||
__CREDITS__: number
|
||||
__LANGUAGE__: string
|
||||
__IS_INITIALIZED__: boolean
|
||||
__AUTH_TOKEN__?: string | null
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,9 @@
|
||||
interface Window {
|
||||
__IS_INITIALIZED__: boolean
|
||||
__CREDITS__: number
|
||||
__LANGUAGE__: string
|
||||
__AUTH_TOKEN__: string | null
|
||||
supabase: any // Replace with proper Supabase client type if needed
|
||||
electron: any // Replace with proper Electron type if needed
|
||||
electronAPI: any // Replace with proper Electron API type if needed
|
||||
}
|
||||
@ -0,0 +1,13 @@
|
||||
export interface Screenshot {
|
||||
id: string
|
||||
path: string
|
||||
timestamp: number
|
||||
thumbnail: string // Base64 thumbnail
|
||||
}
|
||||
|
||||
export interface Solution {
|
||||
initial_thoughts: string[]
|
||||
thought_steps: string[]
|
||||
description: string
|
||||
code: string
|
||||
}
|
||||
@ -0,0 +1,4 @@
|
||||
export interface Screenshot {
|
||||
path: string
|
||||
preview: string
|
||||
}
|
||||
@ -0,0 +1,30 @@
|
||||
export interface Solution {
|
||||
initial_thoughts: string[]
|
||||
thought_steps: string[]
|
||||
description: string
|
||||
code: string
|
||||
}
|
||||
|
||||
export interface SolutionsResponse {
|
||||
[key: string]: Solution
|
||||
}
|
||||
|
||||
export interface ProblemStatementData {
|
||||
problem_statement: string
|
||||
input_format: {
|
||||
description: string
|
||||
parameters: any[]
|
||||
}
|
||||
output_format: {
|
||||
description: string
|
||||
type: string
|
||||
subtype: string
|
||||
}
|
||||
complexity: {
|
||||
time: string
|
||||
space: string
|
||||
}
|
||||
test_cases: any[]
|
||||
validation_type: string
|
||||
difficulty: string
|
||||
}
|
||||
@ -0,0 +1,17 @@
|
||||
// Get the platform safely
|
||||
const getPlatform = () => {
|
||||
try {
|
||||
return window.electronAPI?.getPlatform() || 'win32' // Default to win32 if API is not available
|
||||
} catch {
|
||||
return 'win32' // Default to win32 if there's an error
|
||||
}
|
||||
}
|
||||
|
||||
// Platform-specific command key symbol
|
||||
export const COMMAND_KEY = getPlatform() === 'darwin' ? '⌘' : 'Ctrl'
|
||||
|
||||
// Helper to check if we're on Windows
|
||||
export const isWindows = getPlatform() === 'win32'
|
||||
|
||||
// Helper to check if we're on macOS
|
||||
export const isMacOS = getPlatform() === 'darwin'
|
||||
@ -0,0 +1,11 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_SUPABASE_URL: string
|
||||
|
||||
readonly VITE_SUPABASE_ANON_KEY: string
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv
|
||||
}
|
||||
@ -0,0 +1,37 @@
|
||||
@echo off
|
||||
echo === Interview Coder - Invisible Edition (No Paywall) ===
|
||||
echo.
|
||||
echo IMPORTANT: This app is designed to be INVISIBLE by default!
|
||||
echo Use the keyboard shortcuts to control it:
|
||||
echo.
|
||||
echo - Toggle Visibility: Ctrl+B (or Cmd+B on Mac)
|
||||
echo - Take Screenshot: Ctrl+H
|
||||
echo - Process Screenshots: Ctrl+Enter
|
||||
echo - Move Window: Ctrl+Arrows (Left/Right/Up/Down)
|
||||
echo - Adjust Opacity: Ctrl+[ (decrease) / Ctrl+] (increase)
|
||||
echo - Reset View: Ctrl+R
|
||||
echo - Quit App: Ctrl+Q
|
||||
echo.
|
||||
echo When you press Ctrl+B, the window will toggle between visible and invisible.
|
||||
echo If movement shortcuts aren't working, try making the window visible first with Ctrl+B.
|
||||
echo.
|
||||
|
||||
cd /D "%~dp0"
|
||||
|
||||
echo 1. Creating required directories...
|
||||
mkdir "%APPDATA%\interview-coder-v1\temp" 2>nul
|
||||
mkdir "%APPDATA%\interview-coder-v1\cache" 2>nul
|
||||
mkdir "%APPDATA%\interview-coder-v1\screenshots" 2>nul
|
||||
mkdir "%APPDATA%\interview-coder-v1\extra_screenshots" 2>nul
|
||||
|
||||
echo 2. Building application...
|
||||
call npm run build
|
||||
|
||||
echo 3. Launching in stealth mode...
|
||||
echo Remember: Press Ctrl+B to make it visible, Ctrl+[ and Ctrl+] to adjust opacity!
|
||||
echo.
|
||||
set NODE_ENV=production
|
||||
start /B cmd /c "npx electron ./dist-electron/main.js"
|
||||
|
||||
echo App is now running invisibly! Press Ctrl+B to make it visible.
|
||||
echo.
|
||||
@ -0,0 +1,49 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
export default {
|
||||
content: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"],
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ["Inter", "system-ui", "sans-serif"]
|
||||
},
|
||||
animation: {
|
||||
in: "in 0.2s ease-out",
|
||||
out: "out 0.2s ease-in",
|
||||
pulse: "pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",
|
||||
shimmer: "shimmer 2s linear infinite",
|
||||
"text-gradient-wave": "textGradientWave 2s infinite ease-in-out"
|
||||
},
|
||||
keyframes: {
|
||||
textGradientWave: {
|
||||
"0%": { backgroundPosition: "0% 50%" },
|
||||
"100%": { backgroundPosition: "200% 50%" }
|
||||
},
|
||||
shimmer: {
|
||||
"0%": {
|
||||
backgroundPosition: "200% 0"
|
||||
},
|
||||
"100%": {
|
||||
backgroundPosition: "-200% 0"
|
||||
}
|
||||
},
|
||||
in: {
|
||||
"0%": { transform: "translateY(100%)", opacity: 0 },
|
||||
"100%": { transform: "translateY(0)", opacity: 1 }
|
||||
},
|
||||
out: {
|
||||
"0%": { transform: "translateY(0)", opacity: 1 },
|
||||
"100%": { transform: "translateY(100%)", opacity: 0 }
|
||||
},
|
||||
pulse: {
|
||||
"0%, 100%": {
|
||||
opacity: 1
|
||||
},
|
||||
"50%": {
|
||||
opacity: 0.5
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
plugins: []
|
||||
}
|
||||
@ -0,0 +1,20 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"module": "CommonJS",
|
||||
"moduleResolution": "node",
|
||||
"skipLibCheck": true,
|
||||
"strict": false,
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"outDir": "dist-electron",
|
||||
"esModuleInterop": true,
|
||||
"noImplicitAny": false,
|
||||
"strictNullChecks": false,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"main": ["electron/main.ts"]
|
||||
}
|
||||
},
|
||||
"include": ["electron/**/*"]
|
||||
}
|
||||
@ -0,0 +1,24 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ES2020",
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"allowJs": true,
|
||||
"esModuleInterop": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"types": ["vite/client"]
|
||||
},
|
||||
"include": ["electron/**/*", "src/**/*"],
|
||||
"references": [{ "path": "./tsconfig.node.json" }]
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"skipLibCheck": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"allowSyntheticDefaultImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@ -0,0 +1,58 @@
|
||||
// vite.config.ts
|
||||
import { defineConfig } from "vite"
|
||||
import electron from "vite-plugin-electron"
|
||||
import react from "@vitejs/plugin-react"
|
||||
import path from "path"
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
react(),
|
||||
electron([
|
||||
{
|
||||
// main.ts
|
||||
entry: "electron/main.ts",
|
||||
vite: {
|
||||
build: {
|
||||
outDir: "dist-electron",
|
||||
sourcemap: true,
|
||||
minify: false,
|
||||
rollupOptions: {
|
||||
external: ["electron"]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
// preload.ts
|
||||
entry: "electron/preload.ts",
|
||||
vite: {
|
||||
build: {
|
||||
outDir: "dist-electron",
|
||||
sourcemap: true,
|
||||
rollupOptions: {
|
||||
external: ["electron"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
])
|
||||
],
|
||||
base: process.env.NODE_ENV === "production" ? "./" : "/",
|
||||
server: {
|
||||
port: 54321,
|
||||
strictPort: true,
|
||||
watch: {
|
||||
usePolling: true
|
||||
}
|
||||
},
|
||||
build: {
|
||||
outDir: "dist",
|
||||
emptyOutDir: true,
|
||||
sourcemap: true
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
"@": path.resolve(__dirname, "./src")
|
||||
}
|
||||
}
|
||||
})
|
||||
Loading…
Reference in new issue