diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9581897..d642f0a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -37,7 +37,6 @@ npm run dev # browser preview: no filesystem, Git or account actions | `desktop/` | React and TypeScript interface, typed native bridge, and its tests (`*.test.ts`, `*.test.tsx`) | | `src-tauri/src/` | Rust services: workspace, GitHub, cloud account and API, local analysis | | `desktop/platform-schema.d.ts` | Generated from the cloud platform's API contract: do not edit it by hand | -| `src/`, `tests/` | The old Electron implementation, kept as a reference: do not change it | The interface is in French: write new labels and messages in French. diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md deleted file mode 100644 index d7f7a83..0000000 --- a/DOCUMENTATION.md +++ /dev/null @@ -1,173 +0,0 @@ -# CTrace GUI - Developer Guide - -## 📋 Documentation Overview - -This project uses **JSDoc** for comprehensive API documentation. The documentation is automatically generated from comments in the source code and provides detailed information about all classes, methods, and functions. - -## 🚀 Generating Documentation - -### Install Dependencies -```bash -npm install -``` - -### Generate Documentation -```bash -npm run docs -``` - -### Watch Mode (Auto-regenerate) -```bash -npm run docs:watch -``` - -## 📁 Documentation Structure - -The generated documentation is organized as follows: - -- **`docs/overview.html`** - Project overview and navigation -- **`docs/index.html`** - Main JSDoc documentation index -- **`docs/UIController.html`** - Main UI controller documentation -- **`docs/FileOperationsManager.html`** - File operations documentation -- **`docs/TabManager.html`** - Tab management documentation -- **`docs/SearchManager.html`** - Search functionality documentation -- **`docs/EditorManager.html`** - Editor management documentation -- **`docs/NotificationManager.html`** - Notification system documentation - -## 🏗️ Architecture Documentation - -### Main Process (`src/main/`) -- **`main.js`** - Application entry point -- **`ipc/fileHandlers.js`** - File system IPC handlers -- **`ipc/ctraceHandlers.js`** - CTrace execution handlers -- **`ipc/editorHandlers.js`** - Editor-related handlers -- **`utils/fileUtils.js`** - File system utilities - -### Renderer Process (`src/renderer/`) -- **`UIController.js`** - Main UI coordinator -- **`managers/`** - Specialized manager classes -- **`utils/`** - Renderer utilities - -## 📝 JSDoc Standards - -### Class Documentation -```javascript -/** - * Brief description of the class. - * - * Detailed description explaining the purpose and functionality. - * - * @class ClassName - * @author CTrace GUI Team - * @version 1.0.0 - * - * @example - * const instance = new ClassName(param1, param2); - */ -class ClassName { - // ... -} -``` - -### Method Documentation -```javascript -/** - * Brief description of the method. - * - * Detailed description of what the method does. - * - * @async - * @memberof ClassName - * @param {string} param1 - Description of parameter 1 - * @param {Object} param2 - Description of parameter 2 - * @returns {Promise} Description of return value - * - * @example - * const result = await instance.methodName('value', {option: true}); - */ -async methodName(param1, param2) { - // ... -} -``` - -### Property Documentation -```javascript -/** - * Description of the property - * @type {string} - * @private - */ -this.propertyName = 'value'; -``` - -## 🔧 Configuration - -### JSDoc Configuration (`jsdoc.conf.json`) -```json -{ - "source": { - "include": ["./src/", "./README.md"], - "includePattern": "\\.(js)$", - "exclude": ["./node_modules/", "./dist/", "./build/"] - }, - "opts": { - "destination": "./docs/", - "recurse": true, - "readme": "./README.md" - }, - "plugins": ["plugins/markdown"], - "metadata": { - "title": "CTrace GUI Documentation", - "description": "Complete documentation for the CTrace GUI Electron application" - } -} -``` - -## 📊 Coverage Guidelines - -Aim for documentation coverage of: -- ✅ **All public classes** - Complete with examples -- ✅ **All public methods** - Parameters, return values, examples -- ✅ **Key private methods** - Internal functionality -- ✅ **Complex algorithms** - Detailed explanations -- ✅ **Configuration objects** - Property descriptions - -## 🎯 Best Practices - -1. **Use descriptive summaries** - First line should clearly explain the purpose -2. **Include examples** - Show how to use classes and methods -3. **Document parameters thoroughly** - Include types and descriptions -4. **Explain return values** - What does the method return? -5. **Use @memberof** - Clearly associate methods with classes -6. **Mark async methods** - Use @async for Promise-returning methods -7. **Private vs Public** - Use @private for internal methods - -## 🔗 Useful Links - -- [JSDoc Official Documentation](https://jsdoc.app/) -- [JSDoc Tags Reference](https://jsdoc.app/index.html#block-tags) -- [Electron Documentation](https://www.electronjs.org/docs) - -## 📈 Viewing Documentation - -1. Generate docs: `npm run docs` -2. Open `docs/overview.html` for project overview -3. Open `docs/index.html` for complete API documentation -4. Navigate using the sidebar or search functionality - -The documentation is fully self-contained HTML and can be: -- Viewed locally in any web browser -- Hosted on a web server -- Included in project releases -- Shared with team members - -## 🤝 Contributing - -When adding new code: -1. Add comprehensive JSDoc comments -2. Include usage examples where appropriate -3. Regenerate documentation: `npm run docs` -4. Verify documentation renders correctly -5. Update this guide if needed - -Happy documenting! 📚 \ No newline at end of file diff --git a/QUICK_START_LLM.md b/QUICK_START_LLM.md deleted file mode 100644 index 1016732..0000000 --- a/QUICK_START_LLM.md +++ /dev/null @@ -1,141 +0,0 @@ -# Quick Start: Using External LLM Providers - -## 🚀 Get Started in 3 Steps - -### 1. Open Assistant Settings -- Click the **Assistant** icon in the activity bar (left side) -- Click the **Settings** button in the assistant panel - -### 2. Choose Your Provider -Select "External API" and pick from: - -| Provider | Best For | API Key From | -|----------|----------|--------------| -| **OpenAI** | General purpose, highest quality | [platform.openai.com](https://platform.openai.com/api-keys) | -| **Deepseek** | Coding, cost-effective | [platform.deepseek.com](https://platform.deepseek.com/api-keys) | -| **Claude** | Advanced reasoning | [console.anthropic.com](https://console.anthropic.com/settings/keys) | -| **Groq** | Ultra-fast responses | [console.groq.com](https://console.groq.com/keys) | -| **Perplexity** | Current info + search | [perplexity.ai/settings/api](https://www.perplexity.ai/settings/api) | -| **Generic** | Any OpenAI-compatible API | Varies by service | - -### 3. Enter Your API Key & Save -- Paste your API key -- Select your preferred model -- Click **Save** - -## 💡 Quick Tips - -### Free Tiers & Trials -- **Groq**: Free tier with generous limits -- **OpenAI**: $5 free credit for new accounts -- **Perplexity**: Limited free requests -- **Deepseek**: Very affordable pricing - -### Best Models for Coding -``` -OpenAI: gpt-4 or gpt-4-turbo -Deepseek: deepseek-coder -Claude: claude-3-5-sonnet-20241022 -Groq: mixtral-8x7b-32768 -``` - -### Customize Behavior -Add a system prompt like: -``` -You are an expert C++ developer. -Provide concise, secure code examples. -Always explain your reasoning. -``` - -### Temperature Guide -- **0.0-0.3**: Precise, deterministic (for code generation) -- **0.7**: Balanced (default, recommended) -- **1.0-2.0**: Creative (for brainstorming) - -## 🔧 Using Local/Private Models - -### LM Studio (Local) -``` -Provider: Custom Provider -Name: LM Studio -Endpoint: http://localhost:1234/v1/chat/completions -API Key: (leave blank) -Model: (whatever you loaded in LM Studio) -``` - -### Together AI -``` -Provider: Custom Provider -Name: Together AI -Endpoint: https://api.together.xyz/v1/chat/completions -API Key: (your Together AI key) -Model: mistralai/Mixtral-8x7B-Instruct-v0.1 -``` - -### Ollama (with OpenAI compatibility) -``` -Provider: Custom Provider -Name: Ollama -Endpoint: http://localhost:11434/v1/chat/completions -API Key: (leave blank) -Model: llama2 -``` - -## ❓ Common Issues - -**"API key is required"** -→ Make sure you entered your API key and saved - -**"Invalid API response"** -→ Check your API key is valid and has credits -→ Verify endpoint URL is correct - -**"Connection timeout"** -→ Check internet connection -→ For local models, ensure server is running - -## 💰 Cost Comparison (Approximate) - -| Provider | Input | Output | Notes | -|----------|-------|--------|-------| -| OpenAI GPT-4 | $30/1M | $60/1M | Highest quality | -| Claude Sonnet 3.5 | $3/1M | $15/1M | Great balance | -| Deepseek | $0.14/1M | $0.28/1M | Very affordable | -| Groq | Free tier | Free tier | Limited free usage | - -*Prices in USD per million tokens (approximate, check provider websites)* - -## 🎯 Feature Support - -| Feature | All Providers | Notes | -|---------|---------------|-------| -| Chat | ✅ | Core functionality | -| Code context | ✅ | Select code → ask question | -| System prompts | ✅ | Customize behavior | -| Temperature | ✅ | Control creativity | -| Streaming | ❌ | Coming soon | -| Function calling | ❌ | Provider-specific | - -## 🔐 Privacy & Security - -✅ API keys stored locally only -✅ No data sent to CTrace servers -✅ Direct provider communication -✅ You control your data - -## 📚 Learn More - -- Full documentation: `EXTERNAL_LLM_PROVIDERS.md` -- Implementation details: `LLM_INTEGRATION_SUMMARY.md` -- Add your own provider: See documentation - -## 🆘 Need Help? - -1. Check provider documentation for API key setup -2. Verify your API key has credits/quota -3. Try the "Generic" provider for maximum flexibility -4. Open an issue on GitHub with error details - ---- - -**Tip**: Start with Groq's free tier to test the assistant features, then upgrade to your preferred provider for production use! diff --git a/README.md b/README.md index 933b814..7d18ec4 100644 --- a/README.md +++ b/README.md @@ -41,9 +41,8 @@ production credentials are embedded in the preview. workspace. Retrying an uncertain submission keeps its idempotency key until inputs change or submission succeeds. Local edits are not uploaded by this workflow. - **Local analysis:** Select your installed native `ctrace` executable in Settings, - with its analysis tools installed. Open a source file, save it and run static analysis. - SARIF findings, stdout/stderr and cancellation are available. The existing Linux - `bin/ctrace` cannot run directly on Windows. + with its analysis tools installed. Open a source file or a folder and run static + analysis. SARIF findings, stdout/stderr and cancellation are available. Settings also accepts a tool configuration (`--config`) and the project's `compile_commands.json` (`--compile-commands`). The packaged configuration is selected automatically next to a CoreTrace distribution. With a configuration, its tool @@ -74,9 +73,8 @@ npm run dist ``` Windows executable: `src-tauri/target/release/coretrace-desktop.exe`. -`npm run dist` builds installers. Builds are unsigned; the CI validates Windows, -macOS and Linux and retains tag installers as artifacts. No automatic publication, -signing or replacement update service is configured by this migration. +`npm run dist` builds installers. CI validates Windows, macOS and Linux. Version +tags build and publish installers and signed update artifacts to GitHub Releases. ## Architecture and current boundaries @@ -92,12 +90,9 @@ signing or replacement update service is configured by this migration. before retrying. Workspace tabs and the analyser choice last for the session. - The IDE includes exploration, syntax colouring, tabs, search, editing and findings navigation. Terminal, debugger, LSP, extensions, Git commit/push UI, WSL bridging and - local LLM integrations are not included. Local analysis targets the active source - file; cloud analysis targets connected GitHub commits. Uploading arbitrary local - folders to the cloud is not implemented. + local LLM integrations are not included. Local analysis can run on the active + file or open folder. Cloud analysis can run on a connected GitHub commit or + upload the open folder after you confirm the CTU quote. -See [migration/rollback](docs/tauri-migration.md) and -[validation evidence](docs/desktop-validation.md). The old Electron implementation stays -in `src/` as reference, with its [README](docs/electron-readme.md), -[manifest](docs/electron-package.json) and `tests/`. It is not the new runtime; recover it -in a separate clean worktree at `807e2c9` when needed. Existing user changes are preserved. +See the [migration and rollback guide](docs/tauri-migration.md) for the Electron +archive and the [original validation report](docs/desktop-validation.md). diff --git a/assets/ctrace.png b/assets/ctrace.png deleted file mode 100644 index 16b67f4..0000000 Binary files a/assets/ctrace.png and /dev/null differ diff --git a/assets/icons/devicon/LICENSE b/assets/icons/devicon/LICENSE deleted file mode 100644 index fcc9b66..0000000 --- a/assets/icons/devicon/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 konpa - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/assets/icons/devicon/bash-original.svg b/assets/icons/devicon/bash-original.svg deleted file mode 100644 index 8aade9d..0000000 --- a/assets/icons/devicon/bash-original.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/assets/icons/devicon/c-original.svg b/assets/icons/devicon/c-original.svg deleted file mode 100644 index 5197f2a..0000000 --- a/assets/icons/devicon/c-original.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/assets/icons/devicon/cplusplus-original.svg b/assets/icons/devicon/cplusplus-original.svg deleted file mode 100644 index 6cae222..0000000 --- a/assets/icons/devicon/cplusplus-original.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/assets/icons/devicon/css3-original.svg b/assets/icons/devicon/css3-original.svg deleted file mode 100644 index ff5b6ce..0000000 --- a/assets/icons/devicon/css3-original.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/assets/icons/devicon/go-original.svg b/assets/icons/devicon/go-original.svg deleted file mode 100644 index 4337780..0000000 --- a/assets/icons/devicon/go-original.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/assets/icons/devicon/html5-original.svg b/assets/icons/devicon/html5-original.svg deleted file mode 100644 index c2dda3a..0000000 --- a/assets/icons/devicon/html5-original.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/assets/icons/devicon/java-original.svg b/assets/icons/devicon/java-original.svg deleted file mode 100644 index 051bf25..0000000 --- a/assets/icons/devicon/java-original.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/assets/icons/devicon/javascript-original.svg b/assets/icons/devicon/javascript-original.svg deleted file mode 100644 index 7975261..0000000 --- a/assets/icons/devicon/javascript-original.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/assets/icons/devicon/json-original.svg b/assets/icons/devicon/json-original.svg deleted file mode 100644 index 90bb4d3..0000000 --- a/assets/icons/devicon/json-original.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/assets/icons/devicon/markdown-original.svg b/assets/icons/devicon/markdown-original.svg deleted file mode 100644 index 0d0a31f..0000000 --- a/assets/icons/devicon/markdown-original.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/assets/icons/devicon/php-original.svg b/assets/icons/devicon/php-original.svg deleted file mode 100644 index 32b7a5b..0000000 --- a/assets/icons/devicon/php-original.svg +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/assets/icons/devicon/python-original.svg b/assets/icons/devicon/python-original.svg deleted file mode 100644 index e0e096a..0000000 --- a/assets/icons/devicon/python-original.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/assets/icons/devicon/rust-plain.svg b/assets/icons/devicon/rust-plain.svg deleted file mode 100644 index 99525ba..0000000 --- a/assets/icons/devicon/rust-plain.svg +++ /dev/null @@ -1 +0,0 @@ -Package size exceeded the configured limit of 50 MB. Try https://github.com/devicons/devicon/tree/v2.17.0/icons/rust/rust-plain.svg instead. \ No newline at end of file diff --git a/assets/icons/devicon/typescript-original.svg b/assets/icons/devicon/typescript-original.svg deleted file mode 100644 index e1db5f1..0000000 --- a/assets/icons/devicon/typescript-original.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/bin/ctrace b/bin/ctrace deleted file mode 100755 index 49c22d0..0000000 Binary files a/bin/ctrace and /dev/null differ diff --git a/build/entitlements.mac.plist b/build/entitlements.mac.plist deleted file mode 100644 index 6bc22e9..0000000 --- a/build/entitlements.mac.plist +++ /dev/null @@ -1,14 +0,0 @@ - - - - - com.apple.security.cs.allow-jit - - com.apple.security.cs.allow-unsigned-executable-memory - - com.apple.security.cs.allow-dyld-environment-variables - - com.apple.security.cs.disable-library-validation - - - diff --git a/docs/AnthropicProvider.html b/docs/AnthropicProvider.html deleted file mode 100644 index 4702bc1..0000000 --- a/docs/AnthropicProvider.html +++ /dev/null @@ -1,881 +0,0 @@ - - - - - JSDoc: Class: AnthropicProvider - - - - - - - - - - -
- -

Class: AnthropicProvider

- - - - - - -
- -
- -

AnthropicProvider()

- -

Anthropic API Provider

- - -
- -
-
- - - - -

Constructor

- - - -

new AnthropicProvider()

- - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - -
- - -

Extends

- - - - - - - - - - - - - - - - - - - - - - -

Methods

- - - - - - - -

(async, abstract) chat(message, options) → {Promise.<Object>}

- - - - - - -
-

Send a chat message to the LLM

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
message - - -string - - - -

User message

options - - -Object - - - -

Additional options (systemPrompt, temperature, etc.)

- - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

{ success: boolean, reply?: string, error?: string }

-
- - - -
-
- Type -
-
- -Promise.<Object> - - -
-
- - - - - - - - - - - - - -

(abstract) getConfigFields() → {Array.<Object>}

- - - - - - -
-

Get required configuration fields

-
- - - - - - - - - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Array of field definitions with { name, label, type, required, placeholder, default }

-
- - - -
-
- Type -
-
- -Array.<Object> - - -
-
- - - - - - - - - - - - - -

(abstract) getName() → {string}

- - - - - - -
-

Get provider name

-
- - - - - - - - - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Provider name

-
- - - -
-
- Type -
-
- -string - - -
-
- - - - - - - - - - - - - -

(async) testConnection() → {Promise.<Object>}

- - - - - - -
-

Test provider connection

-
- - - - - - - - - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

{ success: boolean, error?: string }

-
- - - -
-
- Type -
-
- -Promise.<Object> - - -
-
- - - - - - - - - - - - - -

validateConfig(config) → {Object}

- - - - - - -
-

Validate configuration

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
config - - -Object - - - -

Configuration to validate

- - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

{ valid: boolean, errors: Array }

-
- - - -
-
- Type -
-
- -Object - - -
-
- - - - - - - - - - - - - -
- -
- - - - -
- - - -
- - - - - - - \ No newline at end of file diff --git a/docs/BaseProvider.html b/docs/BaseProvider.html deleted file mode 100644 index 8773c3d..0000000 --- a/docs/BaseProvider.html +++ /dev/null @@ -1,898 +0,0 @@ - - - - - JSDoc: Class: BaseProvider - - - - - - - - - - -
- -

Class: BaseProvider

- - - - - - -
- -
- -

(abstract) BaseProvider(config)

- -

Base class for all LLM providers

- - -
- -
-
- - - - -

Constructor

- - - -

(abstract) new BaseProvider(config)

- - - - - - -
-

Create a provider instance

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
config - - -Object - - - -

Provider configuration

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - -

Methods

- - - - - - - -

(async, abstract) chat(message, options) → {Promise.<Object>}

- - - - - - -
-

Send a chat message to the LLM

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
message - - -string - - - -

User message

options - - -Object - - - -

Additional options (systemPrompt, temperature, etc.)

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

{ success: boolean, reply?: string, error?: string }

-
- - - -
-
- Type -
-
- -Promise.<Object> - - -
-
- - - - - - - - - - - - - -

(abstract) getConfigFields() → {Array.<Object>}

- - - - - - -
-

Get required configuration fields

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Array of field definitions with { name, label, type, required, placeholder, default }

-
- - - -
-
- Type -
-
- -Array.<Object> - - -
-
- - - - - - - - - - - - - -

(abstract) getName() → {string}

- - - - - - -
-

Get provider name

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Provider name

-
- - - -
-
- Type -
-
- -string - - -
-
- - - - - - - - - - - - - -

(async) testConnection() → {Promise.<Object>}

- - - - - - -
-

Test provider connection

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

{ success: boolean, error?: string }

-
- - - -
-
- Type -
-
- -Promise.<Object> - - -
-
- - - - - - - - - - - - - -

validateConfig(config) → {Object}

- - - - - - -
-

Validate configuration

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
config - - -Object - - - -

Configuration to validate

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

{ valid: boolean, errors: Array }

-
- - - -
-
- Type -
-
- -Object - - -
-
- - - - - - - - - - - - - -
- -
- - - - -
- - - -
- - - - - - - \ No newline at end of file diff --git a/docs/DeepseekProvider.html b/docs/DeepseekProvider.html deleted file mode 100644 index 67fc50a..0000000 --- a/docs/DeepseekProvider.html +++ /dev/null @@ -1,881 +0,0 @@ - - - - - JSDoc: Class: DeepseekProvider - - - - - - - - - - -
- -

Class: DeepseekProvider

- - - - - - -
- -
- -

DeepseekProvider()

- -

Deepseek API Provider

- - -
- -
-
- - - - -

Constructor

- - - -

new DeepseekProvider()

- - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - -
- - -

Extends

- - - - - - - - - - - - - - - - - - - - - - -

Methods

- - - - - - - -

(async, abstract) chat(message, options) → {Promise.<Object>}

- - - - - - -
-

Send a chat message to the LLM

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
message - - -string - - - -

User message

options - - -Object - - - -

Additional options (systemPrompt, temperature, etc.)

- - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

{ success: boolean, reply?: string, error?: string }

-
- - - -
-
- Type -
-
- -Promise.<Object> - - -
-
- - - - - - - - - - - - - -

(abstract) getConfigFields() → {Array.<Object>}

- - - - - - -
-

Get required configuration fields

-
- - - - - - - - - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Array of field definitions with { name, label, type, required, placeholder, default }

-
- - - -
-
- Type -
-
- -Array.<Object> - - -
-
- - - - - - - - - - - - - -

(abstract) getName() → {string}

- - - - - - -
-

Get provider name

-
- - - - - - - - - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Provider name

-
- - - -
-
- Type -
-
- -string - - -
-
- - - - - - - - - - - - - -

(async) testConnection() → {Promise.<Object>}

- - - - - - -
-

Test provider connection

-
- - - - - - - - - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

{ success: boolean, error?: string }

-
- - - -
-
- Type -
-
- -Promise.<Object> - - -
-
- - - - - - - - - - - - - -

validateConfig(config) → {Object}

- - - - - - -
-

Validate configuration

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
config - - -Object - - - -

Configuration to validate

- - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

{ valid: boolean, errors: Array }

-
- - - -
-
- Type -
-
- -Object - - -
-
- - - - - - - - - - - - - -
- -
- - - - -
- - - -
- - - - - - - \ No newline at end of file diff --git a/docs/EditorManager.html b/docs/EditorManager.html deleted file mode 100644 index 4460574..0000000 --- a/docs/EditorManager.html +++ /dev/null @@ -1,1176 +0,0 @@ - - - - - JSDoc: Class: EditorManager - - - - - - - - - - -
- -

Class: EditorManager

- - - - - - -
- -
- -

EditorManager()

- -

Editor Manager - Handles editor functionality like gutter, status bar, formatting

- - -
- -
-
- - - - -

Constructor

- - - -

new EditorManager()

- - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - -

Methods

- - - - - - - -

focus()

- - - - - - -
-

Focus the editor

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

formatCode()

- - - - - - -
-

Enhanced formatting

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

getContent() → {string}

- - - - - - -
-

Get editor content

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • Current editor content
  • -
-
- - - -
-
- Type -
-
- -string - - -
-
- - - - - - - - - - - - - -

jumpToLine(lineNumber)

- - - - - - -
-

Jump to specific line in editor

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
lineNumber - - -number - - - -

Line number to jump to

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

setContent(content)

- - - - - - -
-

Set editor content

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
content - - -string - - - -

Content to set

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

syncScroll()

- - - - - - -
-

Sync gutter scroll with editor

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

toggleWordWrap()

- - - - - - -
-

Toggle word wrap

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

updateAll()

- - - - - - -
-

Update all editor components

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

updateGutter()

- - - - - - -
-

Enhanced gutter line numbers with proper formatting (like VS Code)

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

updateStatusBar()

- - - - - - -
-

Enhanced status bar with cursor position tracking

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - -
- - - -
- - - - - - - \ No newline at end of file diff --git a/docs/FileOperationsManager.FileOperationsManager.html b/docs/FileOperationsManager.FileOperationsManager.html deleted file mode 100644 index a1928a7..0000000 --- a/docs/FileOperationsManager.FileOperationsManager.html +++ /dev/null @@ -1,243 +0,0 @@ - - - - - JSDoc: Class: FileOperationsManager - - - - - - - - - - -
- -

Class: FileOperationsManager

- - - - - - -
- -
- -

- FileOperationsManager.FileOperationsManager(tabManager, notificationManager)

- - -
- -
-
- - - - - - -

new FileOperationsManager(tabManager, notificationManager)

- - - - - - -
-

Creates an instance of FileOperationsManager.

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
tabManager - - -TabManager - - - -

Tab manager instance for handling file tabs

notificationManager - - -NotificationManager - - - -

Notification manager for user feedback

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - -
- -
- - - - -
- - - -
- - - - - - - \ No newline at end of file diff --git a/docs/FileOperationsManager.html b/docs/FileOperationsManager.html deleted file mode 100644 index 658eec7..0000000 --- a/docs/FileOperationsManager.html +++ /dev/null @@ -1,1859 +0,0 @@ - - - - - JSDoc: Class: FileOperationsManager - - - - - - - - - - -
- -

Class: FileOperationsManager

- - - - - - -
- -
- -

FileOperationsManager()

- - -
- -
-
- - - - - - -

new FileOperationsManager()

- - - - - - -
-

File Operations Manager - Handles all file operations via IPC communication.

-

This manager provides a high-level interface for file and workspace operations, -including opening files/workspaces, saving files, and managing the file tree. -It communicates with the main process through IPC to perform actual file system operations.

-
- - - - - - - - - - - - - -
- - -
Version:
-
  • 1.0.0
- - - - - - - - - - - - - - - - - -
Author:
-
-
    -
  • CTrace GUI Team
  • -
-
- - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - -
Example
- -
const fileOpsManager = new FileOperationsManager(tabManager, notificationManager);
await fileOpsManager.openWorkspace();
- - - - -
- - - - - - -

Classes

- -
-
FileOperationsManager
-
-
- - - - - - - - - - - -

Methods

- - - - - - - -

formatFileSize(bytes) → {string}

- - - - - - -
-

Format file size for display

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
bytes - - -number - - - -

File size in bytes

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • Formatted file size
  • -
-
- - - -
-
- Type -
-
- -string - - -
-
- - - - - - - - - - - - - -

getCurrentWorkspacePath() → {string|null}

- - - - - - -
-

Get current workspace path

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • Current workspace path
  • -
-
- - - -
-
- Type -
-
- -string -| - -null - - -
-
- - - - - - - - - - - - - -

getFileIcon(filename) → {string}

- - - - - - -
-

Get file icon based on extension

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
filename - - -string - - - -

Filename

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • File icon emoji
  • -
-
- - - -
-
- Type -
-
- -string - - -
-
- - - - - - - - - - - - - -

(async) loadFullFile(filePath)

- - - - - - -
-

Load full file (for partially loaded large files)

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
filePath - - -string - - - -

File path

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

(async) openFile()

- - - - - - -
-

Open single file

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

openFileInTab(filePath, content, fileName, fileInfo)

- - - - - - -
-

Open file in tab

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
filePath - - -string - - - -

File path

content - - -string - - - -

File content

fileName - - -string - - - -

File name

fileInfo - - -Object - - - -

File metadata

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

(async) openWorkspace() → {Promise.<(Object|undefined)>}

- - - - - - -
-

Opens a workspace folder dialog and loads the selected folder.

-

This method displays a folder selection dialog to the user, and if a folder -is selected, it loads the folder structure and updates the UI to display -the file tree. It also starts watching the workspace for file changes.

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Result object with folder info, or undefined if canceled

-
- - - -
-
- Type -
-
- -Promise.<(Object|undefined)> - - -
-
- - - - - - -
Example
- -
const result = await fileOpsManager.openWorkspace();
if (result && result.success) {
  console.log('Workspace opened:', result.folderPath);
}
- - - - - - - - - -

(async) readFileFromTree(filePath)

- - - - - - -
-

Read file from file tree

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
filePath - - -string - - - -

File path to read

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

renderFileTree(tree, container, level)

- - - - - - -
-

Render file tree

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDefaultDescription
tree - - -Array - - - - - -

File tree structure

container - - -Element - - - - - - null - -

Container element

level - - -number - - - - - - 0 - -

Nesting level

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

(async) saveAsFile()

- - - - - - -
-

Save file as

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

(async) saveFile()

- - - - - - -
-

Save current file

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

updateWorkspaceUI(folderName, fileTree)

- - - - - - -
-

Update workspace UI

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
folderName - - -string - - - -

Folder name

fileTree - - -Array - - - -

File tree structure

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - -
- - - -
- - - - - - - \ No newline at end of file diff --git a/docs/GenericOpenAIProvider.html b/docs/GenericOpenAIProvider.html deleted file mode 100644 index 27ff7d9..0000000 --- a/docs/GenericOpenAIProvider.html +++ /dev/null @@ -1,881 +0,0 @@ - - - - - JSDoc: Class: GenericOpenAIProvider - - - - - - - - - - -
- -

Class: GenericOpenAIProvider

- - - - - - -
- -
- -

GenericOpenAIProvider()

- -

Generic OpenAI-Compatible Provider

- - -
- -
-
- - - - -

Constructor

- - - -

new GenericOpenAIProvider()

- - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - -
- - -

Extends

- - - - - - - - - - - - - - - - - - - - - - -

Methods

- - - - - - - -

(async, abstract) chat(message, options) → {Promise.<Object>}

- - - - - - -
-

Send a chat message to the LLM

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
message - - -string - - - -

User message

options - - -Object - - - -

Additional options (systemPrompt, temperature, etc.)

- - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

{ success: boolean, reply?: string, error?: string }

-
- - - -
-
- Type -
-
- -Promise.<Object> - - -
-
- - - - - - - - - - - - - -

(abstract) getConfigFields() → {Array.<Object>}

- - - - - - -
-

Get required configuration fields

-
- - - - - - - - - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Array of field definitions with { name, label, type, required, placeholder, default }

-
- - - -
-
- Type -
-
- -Array.<Object> - - -
-
- - - - - - - - - - - - - -

(abstract) getName() → {string}

- - - - - - -
-

Get provider name

-
- - - - - - - - - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Provider name

-
- - - -
-
- Type -
-
- -string - - -
-
- - - - - - - - - - - - - -

(async) testConnection() → {Promise.<Object>}

- - - - - - -
-

Test provider connection

-
- - - - - - - - - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

{ success: boolean, error?: string }

-
- - - -
-
- Type -
-
- -Promise.<Object> - - -
-
- - - - - - - - - - - - - -

validateConfig(config) → {Object}

- - - - - - -
-

Validate configuration

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
config - - -Object - - - -

Configuration to validate

- - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

{ valid: boolean, errors: Array }

-
- - - -
-
- Type -
-
- -Object - - -
-
- - - - - - - - - - - - - -
- -
- - - - -
- - - -
- - - - - - - \ No newline at end of file diff --git a/docs/GroqProvider.html b/docs/GroqProvider.html deleted file mode 100644 index 587bda2..0000000 --- a/docs/GroqProvider.html +++ /dev/null @@ -1,881 +0,0 @@ - - - - - JSDoc: Class: GroqProvider - - - - - - - - - - -
- -

Class: GroqProvider

- - - - - - -
- -
- -

GroqProvider()

- -

Groq API Provider - Ultra-fast LLM inference

- - -
- -
-
- - - - -

Constructor

- - - -

new GroqProvider()

- - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - -
- - -

Extends

- - - - - - - - - - - - - - - - - - - - - - -

Methods

- - - - - - - -

(async, abstract) chat(message, options) → {Promise.<Object>}

- - - - - - -
-

Send a chat message to the LLM

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
message - - -string - - - -

User message

options - - -Object - - - -

Additional options (systemPrompt, temperature, etc.)

- - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

{ success: boolean, reply?: string, error?: string }

-
- - - -
-
- Type -
-
- -Promise.<Object> - - -
-
- - - - - - - - - - - - - -

(abstract) getConfigFields() → {Array.<Object>}

- - - - - - -
-

Get required configuration fields

-
- - - - - - - - - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Array of field definitions with { name, label, type, required, placeholder, default }

-
- - - -
-
- Type -
-
- -Array.<Object> - - -
-
- - - - - - - - - - - - - -

(abstract) getName() → {string}

- - - - - - -
-

Get provider name

-
- - - - - - - - - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Provider name

-
- - - -
-
- Type -
-
- -string - - -
-
- - - - - - - - - - - - - -

(async) testConnection() → {Promise.<Object>}

- - - - - - -
-

Test provider connection

-
- - - - - - - - - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

{ success: boolean, error?: string }

-
- - - -
-
- Type -
-
- -Promise.<Object> - - -
-
- - - - - - - - - - - - - -

validateConfig(config) → {Object}

- - - - - - -
-

Validate configuration

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
config - - -Object - - - -

Configuration to validate

- - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

{ valid: boolean, errors: Array }

-
- - - -
-
- Type -
-
- -Object - - -
-
- - - - - - - - - - - - - -
- -
- - - - -
- - - -
- - - - - - - \ No newline at end of file diff --git a/docs/NotificationManager.html b/docs/NotificationManager.html deleted file mode 100644 index fe5af4d..0000000 --- a/docs/NotificationManager.html +++ /dev/null @@ -1,1319 +0,0 @@ - - - - - JSDoc: Class: NotificationManager - - - - - - - - - - -
- -

Class: NotificationManager

- - - - - - -
- -
- -

NotificationManager()

- -

Notification Manager - Handles user notifications and messages

- - -
- -
-
- - - - -

Constructor

- - - -

new NotificationManager()

- - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - -

Methods

- - - - - - - -

clearAll()

- - - - - - -
-

Clear all notifications

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

showConfirmDialog(message, title) → {Promise.<boolean>}

- - - - - - -
-

Show confirmation dialog

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDefaultDescription
message - - -string - - - - - -

Message to display

title - - -string - - - - - - Confirm - -

Dialog title

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • User confirmation
  • -
-
- - - -
-
- Type -
-
- -Promise.<boolean> - - -
-
- - - - - - - - - - - - - -

showEncodingWarningDialog() → {Promise.<string>}

- - - - - - -
-

Show encoding warning dialog

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • User choice ('yes' or 'no')
  • -
-
- - - -
-
- Type -
-
- -Promise.<string> - - -
-
- - - - - - - - - - - - - -

showError(message)

- - - - - - -
-

Show error notification

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
message - - -string - - - -

Message to display

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

showInfo(message)

- - - - - - -
-

Show info notification

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
message - - -string - - - -

Message to display

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

showNotification(message, type, duration)

- - - - - - -
-

Show notification

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDefaultDescription
message - - -string - - - - - -

Message to display

type - - -string - - - - - - info - -

Notification type (success, error, info, warning)

duration - - -number - - - - - - 4000 - -

Duration in milliseconds (default 4000)

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

showSuccess(message)

- - - - - - -
-

Show success notification

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
message - - -string - - - -

Message to display

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

showWarning(message)

- - - - - - -
-

Show warning notification

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
message - - -string - - - -

Message to display

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - -
- - - -
- - - - - - - \ No newline at end of file diff --git a/docs/OpenAIProvider.html b/docs/OpenAIProvider.html deleted file mode 100644 index 144506b..0000000 --- a/docs/OpenAIProvider.html +++ /dev/null @@ -1,881 +0,0 @@ - - - - - JSDoc: Class: OpenAIProvider - - - - - - - - - - -
- -

Class: OpenAIProvider

- - - - - - -
- -
- -

OpenAIProvider()

- -

OpenAI API Provider

- - -
- -
-
- - - - -

Constructor

- - - -

new OpenAIProvider()

- - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - -
- - -

Extends

- - - - - - - - - - - - - - - - - - - - - - -

Methods

- - - - - - - -

(async, abstract) chat(message, options) → {Promise.<Object>}

- - - - - - -
-

Send a chat message to the LLM

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
message - - -string - - - -

User message

options - - -Object - - - -

Additional options (systemPrompt, temperature, etc.)

- - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

{ success: boolean, reply?: string, error?: string }

-
- - - -
-
- Type -
-
- -Promise.<Object> - - -
-
- - - - - - - - - - - - - -

(abstract) getConfigFields() → {Array.<Object>}

- - - - - - -
-

Get required configuration fields

-
- - - - - - - - - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Array of field definitions with { name, label, type, required, placeholder, default }

-
- - - -
-
- Type -
-
- -Array.<Object> - - -
-
- - - - - - - - - - - - - -

(abstract) getName() → {string}

- - - - - - -
-

Get provider name

-
- - - - - - - - - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Provider name

-
- - - -
-
- Type -
-
- -string - - -
-
- - - - - - - - - - - - - -

(async) testConnection() → {Promise.<Object>}

- - - - - - -
-

Test provider connection

-
- - - - - - - - - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

{ success: boolean, error?: string }

-
- - - -
-
- Type -
-
- -Promise.<Object> - - -
-
- - - - - - - - - - - - - -

validateConfig(config) → {Object}

- - - - - - -
-

Validate configuration

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
config - - -Object - - - -

Configuration to validate

- - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

{ valid: boolean, errors: Array }

-
- - - -
-
- Type -
-
- -Object - - -
-
- - - - - - - - - - - - - -
- -
- - - - -
- - - -
- - - - - - - \ No newline at end of file diff --git a/docs/PerplexityProvider.html b/docs/PerplexityProvider.html deleted file mode 100644 index a15daf7..0000000 --- a/docs/PerplexityProvider.html +++ /dev/null @@ -1,881 +0,0 @@ - - - - - JSDoc: Class: PerplexityProvider - - - - - - - - - - -
- -

Class: PerplexityProvider

- - - - - - -
- -
- -

PerplexityProvider()

- -

Perplexity API Provider - Search-augmented responses

- - -
- -
-
- - - - -

Constructor

- - - -

new PerplexityProvider()

- - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - -
- - -

Extends

- - - - - - - - - - - - - - - - - - - - - - -

Methods

- - - - - - - -

(async, abstract) chat(message, options) → {Promise.<Object>}

- - - - - - -
-

Send a chat message to the LLM

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
message - - -string - - - -

User message

options - - -Object - - - -

Additional options (systemPrompt, temperature, etc.)

- - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

{ success: boolean, reply?: string, error?: string }

-
- - - -
-
- Type -
-
- -Promise.<Object> - - -
-
- - - - - - - - - - - - - -

(abstract) getConfigFields() → {Array.<Object>}

- - - - - - -
-

Get required configuration fields

-
- - - - - - - - - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Array of field definitions with { name, label, type, required, placeholder, default }

-
- - - -
-
- Type -
-
- -Array.<Object> - - -
-
- - - - - - - - - - - - - -

(abstract) getName() → {string}

- - - - - - -
-

Get provider name

-
- - - - - - - - - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Provider name

-
- - - -
-
- Type -
-
- -string - - -
-
- - - - - - - - - - - - - -

(async) testConnection() → {Promise.<Object>}

- - - - - - -
-

Test provider connection

-
- - - - - - - - - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

{ success: boolean, error?: string }

-
- - - -
-
- Type -
-
- -Promise.<Object> - - -
-
- - - - - - - - - - - - - -

validateConfig(config) → {Object}

- - - - - - -
-

Validate configuration

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
config - - -Object - - - -

Configuration to validate

- - - - - - -
- - - - - - - - -
Overrides:
-
- - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

{ valid: boolean, errors: Array }

-
- - - -
-
- Type -
-
- -Object - - -
-
- - - - - - - - - - - - - -
- -
- - - - -
- - - -
- - - - - - - \ No newline at end of file diff --git a/docs/ProviderRegistry.html b/docs/ProviderRegistry.html deleted file mode 100644 index c273f2f..0000000 --- a/docs/ProviderRegistry.html +++ /dev/null @@ -1,869 +0,0 @@ - - - - - JSDoc: Class: ProviderRegistry - - - - - - - - - - -
- -

Class: ProviderRegistry

- - - - - - -
- -
- -

ProviderRegistry()

- -

Registry of available LLM providers

- - -
- -
-
- - - - -

Constructor

- - - -

new ProviderRegistry()

- - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - -

Methods

- - - - - - - -

createProvider(id, config) → {BaseProvider}

- - - - - - -
-

Create a provider instance

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
id - - -string - - - -

Provider identifier

config - - -Object - - - -

Provider configuration

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Provider instance

-
- - - -
-
- Type -
-
- -BaseProvider - - -
-
- - - - - - - - - - - - - -

getAllProviders() → {Array.<Object>}

- - - - - - -
-

Get all available providers

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Array of provider info { id, name, fields }

-
- - - -
-
- Type -
-
- -Array.<Object> - - -
-
- - - - - - - - - - - - - -

hasProvider(id) → {boolean}

- - - - - - -
-

Check if a provider exists

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
id - - -string - - - -

Provider identifier

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -boolean - - -
-
- - - - - - - - - - - - - -

register(id, ProviderClass)

- - - - - - -
-

Register a provider class

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
id - - -string - - - -

Unique provider identifier

ProviderClass - - -function - - - -

Provider class constructor

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

registerDefaultProviders()

- - - - - - -
-

Register default built-in providers

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - -
- - - -
- - - - - - - \ No newline at end of file diff --git a/docs/SearchManager.html b/docs/SearchManager.html deleted file mode 100644 index fb0c0aa..0000000 --- a/docs/SearchManager.html +++ /dev/null @@ -1,2225 +0,0 @@ - - - - - JSDoc: Class: SearchManager - - - - - - - - - - -
- -

Class: SearchManager

- - - - - - -
- -
- -

SearchManager()

- -

Search Manager - Handles search functionality

- - -
- -
-
- - - - -

Constructor

- - - -

new SearchManager()

- - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - -

Methods

- - - - - - - -

clearSearchHighlights()

- - - - - - -
-

Clear search highlights

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

clearSearchResults()

- - - - - - -
-

Clear search results

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

closeGoToLineDialog()

- - - - - - -
-

Close go to line dialog

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

closeSearchWidget()

- - - - - - -
-

Close search widget

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

displaySearchResults(results, searchTerm)

- - - - - - -
-

Display search results in sidebar

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
results - - -Array - - - -

Search results

searchTerm - - -string - - - -

Search term

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

focusOnCurrentMatch()

- - - - - - -
-

Focus on current match

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

highlightAllMatches()

- - - - - - -
-

Highlight all matches

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

(async) openSearchResult(filePath, lineNumber)

- - - - - - -
-

Open search result (to be implemented by parent controller)

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
filePath - - -string - - - -

File path

lineNumber - - -number - - - -

Line number

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

performGoToLine()

- - - - - - -
-

Perform go to line

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

performLiveSearch(searchText)

- - - - - - -
-

Perform live search in current document

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
searchText - - -string - - - -

Text to search for

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

(async) performWorkspaceSearch(searchTerm)

- - - - - - -
-

Perform workspace search

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
searchTerm - - -string - - - -

Term to search for

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

searchNext()

- - - - - - -
-

Search next match

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

searchPrev()

- - - - - - -
-

Search previous match

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

setWorkspacePath(workspacePath)

- - - - - - -
-

Set current workspace path

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
workspacePath - - -string - - - -

Workspace path

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

setupGoToLineDialog()

- - - - - - -
-

Setup go to line dialog

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

setupSearchWidget()

- - - - - - -
-

Setup search widget functionality

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

setupSidebarSearch()

- - - - - - -
-

Setup sidebar search

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

showFindDialog()

- - - - - - -
-

Show find dialog

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

showGoToLineDialog()

- - - - - - -
-

Show go to line dialog

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

updateSearchResults()

- - - - - - -
-

Update search results display

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - -
- - - -
- - - - - - - \ No newline at end of file diff --git a/docs/TabManager.TabManager.html b/docs/TabManager.TabManager.html deleted file mode 100644 index bb3b282..0000000 --- a/docs/TabManager.TabManager.html +++ /dev/null @@ -1,243 +0,0 @@ - - - - - JSDoc: Class: TabManager - - - - - - - - - - -
- -

Class: TabManager

- - - - - - -
- -
- -

- TabManager.TabManager(editorManager, notificationManager)

- - -
- -
-
- - - - - - -

new TabManager(editorManager, notificationManager)

- - - - - - -
-

Creates an instance of TabManager.

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
editorManager - - -EditorManager - - - -

Editor manager instance for content management

notificationManager - - -NotificationManager - - - -

Notification manager for user feedback

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - -
- -
- - - - -
- - - -
- - - - - - - \ No newline at end of file diff --git a/docs/TabManager.html b/docs/TabManager.html deleted file mode 100644 index b2c358b..0000000 --- a/docs/TabManager.html +++ /dev/null @@ -1,2620 +0,0 @@ - - - - - JSDoc: Class: TabManager - - - - - - - - - - -
- -

Class: TabManager

- - - - - - -
- -
- -

TabManager()

- - -
- -
-
- - - - - - -

new TabManager()

- - - - - - -
-

Tab Manager - Handles all tab operations including creation, switching, and closing.

-

This manager provides a complete tab interface similar to modern code editors, -allowing users to work with multiple files simultaneously. It manages tab state, -coordinates with the editor manager, and handles file modifications tracking.

-
- - - - - - - - - - - - - -
- - -
Version:
-
  • 1.0.0
- - - - - - - - - - - - - - - - - -
Author:
-
-
    -
  • CTrace GUI Team
  • -
-
- - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - -
Example
- -
const tabManager = new TabManager(editorManager, notificationManager);
const tabId = tabManager.createTab('example.js', '/path/to/example.js', 'console.log("Hello")');
- - - - -
- - - - - - -

Classes

- -
-
TabManager
-
-
- - - - - - - - - -

Members

- - - -

activeTabId :string|null

- - - - -
-

Currently active tab ID

-
- - - -
Type:
-
    -
  • - -string -| - -null - - -
  • -
- - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - -

Methods

- - - - - - - -

closeTab(event, tabId)

- - - - - - -
-

Close a tab

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
event - - -Event - - - -

Click event

tabId - - -string - - - -

Tab ID to close

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

createNewFile() → {string}

- - - - - - -
-

Create a new untitled file tab

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • New tab ID
  • -
-
- - - -
-
- Type -
-
- -string - - -
-
- - - - - - - - - - - - - -

createTab(fileName, filePath, content, fileInfo) → {string}

- - - - - - -
-

Create a new tab

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDefaultDescription
fileName - - -string - - - - - -

Tab file name

filePath - - -string - - - - - - null - -

File path (optional)

content - - -string - - - - - -

File content

fileInfo - - -Object - - - - - -

File metadata

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • Tab ID
  • -
-
- - - -
-
- Type -
-
- -string - - -
-
- - - - - - - - - - - - - -

findTabByPath(filePath) → {string|null}

- - - - - - -
-

Check if file is already open in a tab

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
filePath - - -string - - - -

File path to check

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • Tab ID if found, null otherwise
  • -
-
- - - -
-
- Type -
-
- -string -| - -null - - -
-
- - - - - - - - - - - - - -

getActiveTab() → {Object|null}

- - - - - - -
-

Get current active tab

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • Active tab data or null
  • -
-
- - - -
-
- Type -
-
- -Object -| - -null - - -
-
- - - - - - - - - - - - - -

getTabCount() → {number}

- - - - - - -
-

Get all open tabs count

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • Number of open tabs
  • -
-
- - - -
-
- Type -
-
- -number - - -
-
- - - - - - - - - - - - - -

handleContentChange(tabId, newContent)

- - - - - - -
-

Handle tab content changes (for modification tracking)

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
tabId - - -string - - - -

Tab ID

newContent - - -string - - - -

New content

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

markTabClean(tabId)

- - - - - - -
-

Mark tab as clean (not modified)

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
tabId - - -string - - - -

Tab ID

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

markTabModified(tabId)

- - - - - - -
-

Mark tab as modified

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
tabId - - -string - - - -

Tab ID

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

onLoadFullFile(filePath)

- - - - - - -
-

Callback for loading full file (to be implemented by parent)

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
filePath - - -string - - - -

File path to load

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

onTabSwitch(tabData)

- - - - - - -
-

Callback for when tab switches (for other components to listen to)

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
tabData - - -Object - - - -

Tab data

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

showEditor()

- - - - - - -
-

Show editor

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

showWelcomeScreen()

- - - - - - -
-

Show welcome screen

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

switchToNextTab()

- - - - - - -
-

Switch to next tab

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

switchToTab(tabId)

- - - - - - -
-

Switch to a specific tab

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
tabId - - -string - - - -

Tab ID to switch to

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

updateFileStatus(tabData)

- - - - - - -
-

Update file status indicator

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
tabData - - -Object - - - -

Tab data

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

updateTabFile(tabId, filePath, fileName)

- - - - - - -
-

Update tab file info (for file operations)

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
tabId - - -string - - - -

Tab ID

filePath - - -string - - - -

New file path

fileName - - -string - - - -

New file name

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - -
- - - -
- - - - - - - \ No newline at end of file diff --git a/docs/UIController.UIController.html b/docs/UIController.UIController.html deleted file mode 100644 index 5458db3..0000000 --- a/docs/UIController.UIController.html +++ /dev/null @@ -1,171 +0,0 @@ - - - - - JSDoc: Class: UIController - - - - - - - - - - -
- -

Class: UIController

- - - - - - -
- -
- -

- UIController.UIController()

- - -
- -
-
- - - - - - -

new UIController()

- - - - - - -
-

Creates an instance of UIController and initializes all managers.

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - -
- -
- - - - -
- - - -
- - - - - - - \ No newline at end of file diff --git a/docs/UIController.html b/docs/UIController.html deleted file mode 100644 index c1d6ab2..0000000 --- a/docs/UIController.html +++ /dev/null @@ -1,2500 +0,0 @@ - - - - - JSDoc: Class: UIController - - - - - - - - - - -
- -

Class: UIController

- - - - - - -
- -
- -

UIController()

- - -
- -
-
- - - - - - -

new UIController()

- - - - - - -
-

Main UI Controller - Coordinates all managers and components

-

This is the central coordinator for the entire application UI. It manages -the interaction between different managers and handles global UI state.

-
- - - - - - - - - - - - - -
- - -
Version:
-
  • 1.0.0
- - - - - - - - - - - - - - - - - -
Author:
-
-
    -
  • CTrace GUI Team
  • -
-
- - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - -
Example
- -
// UIController is automatically instantiated in the HTML
const uiController = new UIController();
- - - - -
- - - - - - -

Classes

- -
-
UIController
-
-
- - - - - - - - - - - -

Methods

- - - - - - - -

connectManagers()

- - - - - - -
-

Connect managers and set up inter-manager communication

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

(async) ensureAssistantConfigured()

- - - - - - -
-

Ensure assistant is configured; if not, show guided setup modal

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

getAssistantConfig() → {Object|null}

- - - - - - -
-

Retrieve assistant configuration from localStorage

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -Object -| - -null - - -
-
- - - - - - - - - - - - - -

(async) openSearchResult(filePath, lineNumber)

- - - - - - -
-

Open search result with proper line navigation

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
filePath - - -string - - - -

File path

lineNumber - - -number - - - -

Line number

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

(async) openWorkspace()

- - - - - - -
-

Open workspace and update search manager

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

(async) refreshFileTree()

- - - - - - -
-

Refreshes the file tree in the explorer view.

-

This method manually triggers a refresh of the file tree to show any -new files or folders that may have been added to the workspace. It -communicates with the main process to get an updated file tree structure.

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - -
Throws:
- - - -
-
-
-

When file tree refresh fails

-
-
-
-
-
-
- Type -
-
- -Error - - -
-
-
-
-
- - - - - - - - - -
Example
- -
// Refresh is typically triggered by the refresh button
await uiController.refreshFileTree();
- - - - - - - - - -

renderAssistantUI()

- - - - - - -
-

Inject a simple chat UI into the tools panel (like VSCode Copilot sidebar)

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

saveAssistantConfig(cfg)

- - - - - - -
-

Save assistant configuration to localStorage

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
cfg - - -Object - - - -
- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

setActiveActivity()

- - - - - - -
-

Activity bar management

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

setupEventListeners()

- - - - - - -
-

Setup event listeners for UI components

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

setupFileTreeWatcher()

- - - - - - -
-

Set up file system watcher to auto-refresh file tree

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

setupFileTreeWatcher()

- - - - - - -
-

Setup file tree watcher to listen for automatic updates

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

setupKeyboardShortcuts()

- - - - - - -
-

Setup keyboard shortcuts

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

setupMenus()

- - - - - - -
-

Setup menu functionality

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

setupResizing()

- - - - - - -
-

Setup resizing functionality

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

setupUIComponents()

- - - - - - -
-

Setup UI component functions

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

setupWSLStatusListener()

- - - - - - -
-

Setup WSL status listener to handle WSL availability updates

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

showAssistantSetupGuide()

- - - - - - -
-

Render a first-time setup modal for Assistant configuration. -Calls the done callback with saved config or null if cancelled.

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

showToolsPanel()

- - - - - - -
-

Tools panel management

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

showWSLSetupDialog(wslStatus)

- - - - - - -
-

Show WSL setup dialog with detailed instructions

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
wslStatus - - -Object - - - -

Current WSL status

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

toggleSidebar()

- - - - - - -
-

Sidebar toggle

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

toggleVisualyzerPanel()

- - - - - - -
-

Visualyzer panel management

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

updateWSLStatusIndicator(wslStatus)

- - - - - - -
-

Update WSL status indicator in the UI

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
wslStatus - - -Object - - - -

WSL status object with available, hasDistros, and error properties

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - -
- - - -
- - - - - - - \ No newline at end of file diff --git a/docs/VisualyzerManager.html b/docs/VisualyzerManager.html deleted file mode 100644 index 7a16ea7..0000000 --- a/docs/VisualyzerManager.html +++ /dev/null @@ -1,3838 +0,0 @@ - - - - - JSDoc: Class: VisualyzerManager - - - - - - - - - - -
- -

Class: VisualyzerManager

- - - - - - -
- -
- -

VisualyzerManager()

- -

Visualyzer Manager - Interactive Graph Visualization -Uses D3.js for force-directed graph rendering

- - -
- -
-
- - - - -

Constructor

- - - -

new VisualyzerManager()

- - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - -

Methods

- - - - - - - -

clear() → {void}

- - - - - - -
-

Clear the graph and return to dropzone

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -void - - -
-
- - - - - - - - - - - - - -

collapseNode(node) → {void}

- - - - - - -
-

Collapse node and hide its children recursively

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
node - - -Object - - - -

Node to collapse

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -void - - -
-
- - - - - - - - - - - - - -

createForceGraph(data, filename) → {void}

- - - - - - -
-

Create D3.js force-directed graph visualization

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
data - - -Object - - - -

Graph data with nodes and edges

filename - - -string - - - -

Name of the DOT file

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -void - - -
-
- - - - - - - - - - - - - -

createLegend(svg) → {void}

- - - - - - -
-

Create legend showing node type colors

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
svg - - -Object - - - -

D3.js SVG selection

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -void - - -
-
- - - - - - - - - - - - - -

dragEnded(event, d, simulation) → {void}

- - - - - - -
-

Handle drag end event for node

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
event - - -Object - - - -

D3 drag event

d - - -Object - - - -

Node data

simulation - - -Object - - - -

D3 simulation

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -void - - -
-
- - - - - - - - - - - - - -

dragStarted(event, d, simulation) → {void}

- - - - - - -
-

Handle drag start event for node

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
event - - -Object - - - -

D3 drag event

d - - -Object - - - -

Node data

simulation - - -Object - - - -

D3 simulation

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -void - - -
-
- - - - - - - - - - - - - -

dragged(event, d) → {void}

- - - - - - -
-

Handle drag event for node

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
event - - -Object - - - -

D3 drag event

d - - -Object - - - -

Node data

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -void - - -
-
- - - - - - - - - - - - - -

expandNode(node) → {void}

- - - - - - -
-

Expand node to show its children

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
node - - -Object - - - -

Node to expand

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -void - - -
-
- - - - - - - - - - - - - -

getNodeColor(node) → {Object}

- - - - - - -
-

Get node color based on type

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
node - - -Object - - - -

Node data

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Color object with fill and stroke

-
- - - -
-
- Type -
-
- -Object - - -
-
- - - - - - - - - - - - - -

(async) handleFile(file) → {Promise.<void>}

- - - - - - -
-

Handle dropped or selected file

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
file - - -File - - - -

DOT file

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -Promise.<void> - - -
-
- - - - - - - - - - - - - -

hasUnexpandedChildren(node) → {boolean}

- - - - - - -
-

Check if node has children that haven't been expanded

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
node - - -Object - - - -

Node to check

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

True if node has unexpanded children

-
- - - -
-
- Type -
-
- -boolean - - -
-
- - - - - - - - - - - - - -

initializeElements()

- - - - - - -
-

Initialize DOM elements

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

parseDotContent(dotContent) → {Object}

- - - - - - -
-

Parse DOT content into graph data

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
dotContent - - -string - - - -

DOT file content

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Parsed graph data

-
- - - -
-
- Type -
-
- -Object - - -
-
- - - - - - - - - - - - - -

parseLabel(label) → {Object}

- - - - - - -
-

Parse node label text

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
label - - -string - - - -

Label text to parse

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Parsed label with title and fields

-
- - - -
-
- Type -
-
- -Object - - -
-
- - - - - - - - - - - - - -

parseRecordLabel(label) → {Object}

- - - - - - -
-

Parse record-style label into structured fields

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
label - - -string - - - -

Record label text

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Object with title and fields array

-
- - - -
-
- Type -
-
- -Object - - -
-
- - - - - - - - - - - - - -

readFile(file) → {Promise.<string>}

- - - - - - -
-

Read file content

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
file - - -File - - - -

File to read

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

File content

-
- - - -
-
- Type -
-
- -Promise.<string> - - -
-
- - - - - - - - - - - - - -

(async) renderGraph(dotContent, filename)

- - - - - - -
-

Render interactive graph using D3.js

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
dotContent - - -string - - - -

DOT file content

filename - - -string - - - -

File name

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

resetZoom() → {void}

- - - - - - -
-

Reset zoom to default level

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -void - - -
-
- - - - - - - - - - - - - -

setupEventListeners()

- - - - - - -
-

Setup event listeners

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

showError(message) → {void}

- - - - - - -
-

Display error message to user

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
message - - -string - - - -

Error message to display

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -void - - -
-
- - - - - - - - - - - - - -

showNodeMetadata(node) → {void}

- - - - - - -
-

Display node metadata in the info panel

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
node - - -Object - - - -

Node whose metadata to display

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -void - - -
-
- - - - - - - - - - - - - -

toggleNodeExpansion(node) → {void}

- - - - - - -
-

Toggle node expansion state (expand/collapse children)

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
node - - -Object - - - -

Node to toggle

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -void - - -
-
- - - - - - - - - - - - - -

updateGraph() → {void}

- - - - - - -
-

Update graph visualization with current visible nodes and edges

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -void - - -
-
- - - - - - - - - - - - - -

zoomIn() → {void}

- - - - - - -
-

Zoom in on the graph

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -void - - -
-
- - - - - - - - - - - - - -

zoomOut() → {void}

- - - - - - -
-

Zoom out on the graph

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -void - - -
-
- - - - - - - - - - - - - -
- -
- - - - -
- - - -
- - - - - - - \ No newline at end of file diff --git a/docs/electron-package.json b/docs/electron-package.json deleted file mode 100644 index 603a480..0000000 --- a/docs/electron-package.json +++ /dev/null @@ -1,103 +0,0 @@ -{ - "name": "ctrace-gui", - "version": "5.1.0", - "description": "A modern Electron-based GUI for CTrace static analysis tool", - "main": "src/main.js", - "scripts": { - "build:renderer": "node scripts/build-renderer-bundle.js", - "build:renderer:dev": "node scripts/build-renderer-bundle.js --dev", - "prestart": "npm run build:renderer:dev", - "predist": "npm run build:renderer", - "predist:publish": "npm run build:renderer", - "predist:win": "npm run build:renderer", - "predist:mac": "npm run build:renderer", - "predist:linux": "npm run build:renderer", - "test": "node --test", - "test:wsl": "node src/main/utils/wslTest.js", - "start": "electron .", - "release:ship": "bash ./scripts/release.sh", - "dist": "electron-builder", - "dist:publish": "electron-builder --publish always", - "dist:win": "electron-builder --win", - "dist:mac": "electron-builder --mac", - "dist:linux": "electron-builder --linux", - "build:verify": "./scripts/build-verify.sh", - "docs": "jsdoc -c jsdoc.conf.json", - "docs:watch": "jsdoc -c jsdoc.conf.json --watch", - "postinstall": "node scripts/patch-node-pty-spectre.js" - }, - "keywords": [ - "ctrace", - "static-analysis", - "cpp", - "c", - "development", - "gui", - "electron" - ], - "author": "CTrace GUI Team", - "license": "Apache-2.0", - "dependencies": { - "chokidar": "^5.0.0", - "electron-updater": "^6.8.9", - "ignore": "^7.0.5", - "monaco-editor": "^0.52.2", - "node-llama-cpp": "^3.18.1", - "node-pty": "^1.1.0", - "tar": "^7.5.22", - "uuid": "^14.0.0", - "@coretrace/cli-core": "file:../coretrace-cli/packages/cli-core" - }, - "devDependencies": { - "electron": "^41.10.7", - "electron-builder": "^26.8.1", - "electron-reload": "^2.0.0-alpha.1", - "esbuild": "^0.28.0", - "jsdoc": "^4.0.4" - }, - "build": { - "publish": [ - { - "provider": "github", - "owner": "CoreTrace", - "repo": "coretrace-gui", - "releaseType": "release" - } - ], - "asar": true, - "extraResources": [ - { - "from": "bin/ctrace", - "to": "bin/ctrace" - } - ], - "asarUnpack": [], - "afterPack": "./scripts/remove-locales.js", - "appId": "com.coretrace.ctracegui", - "compression": "normal", - "productName": "CtraceGUI", - "win": { - "target": "nsis", - "icon": "assets/ctrace.ico" - }, - "mac": { - "target": [ - "dmg", - "zip" - ], - "icon": "assets/ctrace.icns", - "category": "public.app-category.developer-tools", - "identity": null, - "hardenedRuntime": false, - "gatekeeperAssess": false, - "notarize": false - }, - "linux": { - "target": "AppImage", - "icon": "assets/ctrace.png", - "category": "Development", - "synopsis": "Static analysis tool for C/C++ code", - "description": "A modern Electron-based GUI application that provides an intuitive interface for running CTrace static analysis on C/C++ code." - } - } -} diff --git a/docs/electron-readme.md b/docs/electron-readme.md deleted file mode 100644 index b5dcb7e..0000000 --- a/docs/electron-readme.md +++ /dev/null @@ -1,162 +0,0 @@ -# CTrace GUI - -A modern Electron-based GUI application for running CTrace analysis on C/C++ code. - -## Overview - -CTrace GUI provides an intuitive interface for analyzing C/C++ source code using the CTrace static analysis tool. The application features a VS Code-like interface with file management, syntax highlighting, and integrated analysis results. - -## Features - -- **File Management**: Open individual files or entire workspaces -- **File Tree Explorer**: Navigate project structure with refresh and auto-watch capabilities -- **Code Editor**: Syntax-highlighted editor with line numbers and search functionality -- **Tab Management**: Multi-file editing with tab interface -- **CTrace Integration**: Run static analysis directly from the GUI -- **Search**: Global search across workspace files -- **AI Assistant**: Chat with local or cloud LLM models about your code -- **Notifications**: User-friendly notification system -- **Work Loss Prevention**: Automatic session saving and restoration - -## Architecture - -The application follows a modular architecture with separate managers for different concerns: - -- **UIController**: Main coordinator for all UI components -- **FileOperationsManager**: Handles file I/O operations via IPC -- **TabManager**: Manages editor tabs and file switching -- **EditorManager**: Controls the Monaco code editor -- **SearchManager**: Handles search operations (widget and sidebar) -- **NotificationManager**: Manages user notifications -- **StateManager**: Handles session persistence (work loss prevention) -- **DiagnosticsManager**: Manages CTrace analysis results and visualization - -The renderer process communicates with the main process exclusively through a typed IPC bridge defined in `src/preload.js`. All IPC channels are whitelisted — the renderer cannot call anything not on the list. - ---- - -## Getting Started - -### Prerequisites - -| Requirement | Version | Notes | -|---|---|---| -| Node.js | v18 or later | Required for the build toolchain | -| npm | bundled with Node.js | Used to install dependencies | -| CTrace binary | any | Must be placed at `bin/ctrace` (see below) | - -> **Windows users:** CTrace is a Linux binary. It runs inside WSL (Windows Subsystem for Linux). The application will detect WSL on startup and guide you through installation if it is missing. - -### Installation - -```bash -npm install -``` - -This installs all Node.js dependencies including Electron and Monaco Editor. - -### CTrace Binary Setup - -The CTrace binary must be present before you can run analyses. Place it at: - -``` -bin/ctrace # Linux -bin/ctrace # Windows (the binary itself runs inside WSL) -bin/ctrace-darwin-arm64 # macOS, Apple Silicon -bin/ctrace-darwin-x64 # macOS, Intel -``` - -The `bin/` directory is at the root of the repository (same level as `package.json`). Create it if it doesn't exist. - -If the binary is missing, the application will still launch, but the **Run Analysis** button will return an error. - -> **macOS users:** the `ctrace` shipped in the release artifacts is a Linux ELF and cannot run on macOS. The app detects this and tells you so instead of failing with an opaque spawn error. Supply a native Mach-O build either by naming it `ctrace-darwin-` next to the bundled one, or by selecting it from **File → Backend Settings**. Everything else — editor, explorer, search, terminal, assistant — works without it. - -### Running in Development - -```bash -npm start -``` - -This automatically rebuilds the renderer bundle (`src/renderer/bundle.js`) before launching Electron. You must rerun `npm start` (or `npm run build:renderer`) any time you edit files under `src/renderer/`. - -### Security notes - -- The renderer runs sandboxed (`sandbox: true`, `contextIsolation: true`) behind a strict Content-Security-Policy: no inline script, no remote scripts, and no navigation away from `index.html`. New UI code must attach listeners with `addEventListener` (or the `data-action` attributes in `index.html`) and pass every external string (file names, tool output, error messages) through `escapeHtml()` before inserting it as HTML. -- DevTools shortcuts (F12, Ctrl/Cmd+Shift+I) are only active in development. Set `CTRACE_DEVTOOLS=1` to enable them in a packaged build. -- File-system IPC only accepts paths that came from a native dialog, the restored session, or the currently opened workspace. -- The assistant API key is encrypted with the OS credential store and never leaves the main process; keyed requests only go to `https:` endpoints (or `http://localhost`). -- App updates download automatically but are only installed after the user chooses "restart to apply". Builds are not code-signed yet, so keep it that way until signing is in place. - -### Building for Distribution - -| Platform | Command | Output | -|---|---|---| -| Current platform | `npm run dist` | `dist/` | -| Linux (AppImage) | `npm run dist:linux` | `dist/*.AppImage` | -| Windows (NSIS installer) | `npm run dist:win` | `dist/*.exe` | -| macOS (DMG + ZIP) | `npm run dist:mac` | `dist/*.dmg`, `dist/*.zip` | - -macOS builds are **unsigned and un-notarized** (signing requires a paid Apple Developer account). Gatekeeper blocks the first launch, so open the app once with right-click → **Open**, or clear the quarantine attribute: - -```bash -xattr -cr /Applications/CtraceGUI.app -``` - -CI builds macOS twice — `macos-latest` for arm64 and `macos-13` for x64 — because `node-pty` and `node-llama-cpp` are native modules and each architecture is compiled on a runner of that architecture. To sign later, restore an Apple certificate step in `.github/workflows/release.yml` and set `identity`, `hardenedRuntime` and `notarize` in the `mac` block of `package.json` (`build/entitlements.mac.plist` is kept for that purpose). - -### Releases and versioning - -Versions are semver, and the git tag is always `v`: - -| Channel | Version shape | Update manifest | Example | -|---|---|---|---| -| stable (`main` in the app) | `X.Y.Z` | `latest*.yml` | `5.1.0` | -| beta | `X.Y.Z-beta.N` | `beta*.yml` | `5.2.0-beta.1` | - -`-beta.N` is the **only** accepted prerelease form. electron-builder names the update manifest after the prerelease identifier, so a version like `5.0.1-a` produces an `a.yml` that neither channel reads — the release becomes invisible to the updater. `scripts/release.sh` and the release workflow both reject it, and `tests/version.test.js` pins the rule. - -Cut a release from `master` with a clean tree: - -```bash -./scripts/release.sh minor # 5.1.0 -> 5.2.0 -./scripts/release.sh 5.2.0-beta.1 # beta channel -./scripts/release.sh prerelease # 5.2.0-beta.1 -> 5.2.0-beta.2 -``` - -The script bumps `package.json`, tags, and pushes. **Only the tag triggers a build**: pushes to `master` and pull requests run the test suite and nothing else, so merging a PR never republishes a release. CI verifies the tag matches `package.json` before publishing, and marks the GitHub release as a prerelease when the version carries `-beta.N`. - -### Running Tests - -```bash -npm test -``` - -Uses Node.js's built-in test runner (`node --test`). No extra test framework is required. - -### Generating Documentation - -```bash -npm run docs -``` - -Generates JSDoc API docs. Hosted version: https://coretrace.github.io/coretrace-gui/ - ---- - -## Documentation - -Complete API documentation is available [here](https://coretrace.github.io/coretrace-gui/) - -IPC channel reference (all renderer ↔ main channels): [docs/ipc-channels.md](docs/ipc-channels.md) - - ---- - -## License - -Licensed under the Apache License, Version 2.0. - -You may obtain a copy of the License in this repository at [LICENSE](LICENSE) or at: - -http://www.apache.org/licenses/LICENSE-2.0 diff --git a/docs/fonts/OpenSans-Bold-webfont.eot b/docs/fonts/OpenSans-Bold-webfont.eot deleted file mode 100644 index 5d20d91..0000000 Binary files a/docs/fonts/OpenSans-Bold-webfont.eot and /dev/null differ diff --git a/docs/fonts/OpenSans-Bold-webfont.svg b/docs/fonts/OpenSans-Bold-webfont.svg deleted file mode 100644 index 3ed7be4..0000000 --- a/docs/fonts/OpenSans-Bold-webfont.svg +++ /dev/null @@ -1,1830 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/docs/fonts/OpenSans-Bold-webfont.woff b/docs/fonts/OpenSans-Bold-webfont.woff deleted file mode 100644 index 1205787..0000000 Binary files a/docs/fonts/OpenSans-Bold-webfont.woff and /dev/null differ diff --git a/docs/fonts/OpenSans-BoldItalic-webfont.eot b/docs/fonts/OpenSans-BoldItalic-webfont.eot deleted file mode 100644 index 1f639a1..0000000 Binary files a/docs/fonts/OpenSans-BoldItalic-webfont.eot and /dev/null differ diff --git a/docs/fonts/OpenSans-BoldItalic-webfont.svg b/docs/fonts/OpenSans-BoldItalic-webfont.svg deleted file mode 100644 index 6a2607b..0000000 --- a/docs/fonts/OpenSans-BoldItalic-webfont.svg +++ /dev/null @@ -1,1830 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/docs/fonts/OpenSans-BoldItalic-webfont.woff b/docs/fonts/OpenSans-BoldItalic-webfont.woff deleted file mode 100644 index ed760c0..0000000 Binary files a/docs/fonts/OpenSans-BoldItalic-webfont.woff and /dev/null differ diff --git a/docs/fonts/OpenSans-Italic-webfont.eot b/docs/fonts/OpenSans-Italic-webfont.eot deleted file mode 100644 index 0c8a0ae..0000000 Binary files a/docs/fonts/OpenSans-Italic-webfont.eot and /dev/null differ diff --git a/docs/fonts/OpenSans-Italic-webfont.svg b/docs/fonts/OpenSans-Italic-webfont.svg deleted file mode 100644 index e1075dc..0000000 --- a/docs/fonts/OpenSans-Italic-webfont.svg +++ /dev/null @@ -1,1830 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/docs/fonts/OpenSans-Italic-webfont.woff b/docs/fonts/OpenSans-Italic-webfont.woff deleted file mode 100644 index ff652e6..0000000 Binary files a/docs/fonts/OpenSans-Italic-webfont.woff and /dev/null differ diff --git a/docs/fonts/OpenSans-Light-webfont.eot b/docs/fonts/OpenSans-Light-webfont.eot deleted file mode 100644 index 1486840..0000000 Binary files a/docs/fonts/OpenSans-Light-webfont.eot and /dev/null differ diff --git a/docs/fonts/OpenSans-Light-webfont.svg b/docs/fonts/OpenSans-Light-webfont.svg deleted file mode 100644 index 11a472c..0000000 --- a/docs/fonts/OpenSans-Light-webfont.svg +++ /dev/null @@ -1,1831 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/docs/fonts/OpenSans-Light-webfont.woff b/docs/fonts/OpenSans-Light-webfont.woff deleted file mode 100644 index e786074..0000000 Binary files a/docs/fonts/OpenSans-Light-webfont.woff and /dev/null differ diff --git a/docs/fonts/OpenSans-LightItalic-webfont.eot b/docs/fonts/OpenSans-LightItalic-webfont.eot deleted file mode 100644 index 8f44592..0000000 Binary files a/docs/fonts/OpenSans-LightItalic-webfont.eot and /dev/null differ diff --git a/docs/fonts/OpenSans-LightItalic-webfont.svg b/docs/fonts/OpenSans-LightItalic-webfont.svg deleted file mode 100644 index 431d7e3..0000000 --- a/docs/fonts/OpenSans-LightItalic-webfont.svg +++ /dev/null @@ -1,1835 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/docs/fonts/OpenSans-LightItalic-webfont.woff b/docs/fonts/OpenSans-LightItalic-webfont.woff deleted file mode 100644 index 43e8b9e..0000000 Binary files a/docs/fonts/OpenSans-LightItalic-webfont.woff and /dev/null differ diff --git a/docs/fonts/OpenSans-Regular-webfont.eot b/docs/fonts/OpenSans-Regular-webfont.eot deleted file mode 100644 index 6bbc3cf..0000000 Binary files a/docs/fonts/OpenSans-Regular-webfont.eot and /dev/null differ diff --git a/docs/fonts/OpenSans-Regular-webfont.svg b/docs/fonts/OpenSans-Regular-webfont.svg deleted file mode 100644 index 25a3952..0000000 --- a/docs/fonts/OpenSans-Regular-webfont.svg +++ /dev/null @@ -1,1831 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/docs/fonts/OpenSans-Regular-webfont.woff b/docs/fonts/OpenSans-Regular-webfont.woff deleted file mode 100644 index e231183..0000000 Binary files a/docs/fonts/OpenSans-Regular-webfont.woff and /dev/null differ diff --git a/docs/global.html b/docs/global.html deleted file mode 100644 index cf88ccd..0000000 --- a/docs/global.html +++ /dev/null @@ -1,5554 +0,0 @@ - - - - - JSDoc: Global - - - - - - - - - - -
- -

Global

- - - - - - -
- -
- -

- - -
- -
-
- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - -
- - - - - - - - - - - - - - - - -

Methods

- - - - - - - -

applySyntaxHighlight(code, fileType) → {string}

- - - - - - -
-

Apply syntax highlighting to editor based on file type

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
code - - -string - - - -

The code to highlight

fileType - - -string - - - -

The detected file type

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • HTML with syntax highlighting
  • -
-
- - - -
-
- Type -
-
- -string - - -
-
- - - - - - - - - - - - - -

(async) buildFileTree(dirPath, maxDepth, currentDepth) → {Array}

- - - - - - -
-

Build file tree for directory

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDefaultDescription
dirPath - - -string - - - - - -

Directory path

maxDepth - - -number - - - - - - 3 - -

Maximum depth to traverse

currentDepth - - -number - - - - - - 0 - -

Current depth (internal use)

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • File tree structure
  • -
-
- - - -
-
- Type -
-
- -Array - - -
-
- - - - - - - - - - - - - -

(async) checkWSLAvailability() → {Promise.<Object>}

- - - - - - -
-

Check if WSL is available and has distributions installed

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

WSL status object with properties: available (boolean), hasDistros (boolean), error (string)

-
- - - -
-
- Type -
-
- -Promise.<Object> - - -
-
- - - - - - - - - - - - - -

createVisualizerWindow() → {BrowserWindow}

- - - - - - -
-

Creates the Visualyzer window as a separate, movable window

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

The created visualyzer window instance

-
- - - -
-
- Type -
-
- -BrowserWindow - - -
-
- - - - - - - - - - - - - -

createWindow() → {BrowserWindow}

- - - - - - -
-

Creates and configures the main application window.

-

This function sets up the BrowserWindow with appropriate dimensions, -icon, and security settings. It loads the main HTML file and configures -the window appearance.

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

The created main window instance

-
- - - -
-
- Type -
-
- -BrowserWindow - - -
-
- - - - - - -
Example
- -
const mainWindow = createWindow();
- - - - - - - - - -

(async) detectFileEncoding(filePath) → {Object}

- - - - - - -
-

Detect file encoding

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
filePath - - -string - - - -

Path to the file

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • File info with encoding and size data
  • -
-
- - - -
-
- Type -
-
- -Object - - -
-
- - - - - - - - - - - - - -

detectFileType(filename) → {string}

- - - - - - -
-

Detect file type based on file extension

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
filename - - -string - - - -

The filename to analyze

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • The detected file type
  • -
-
- - - -
-
- Type -
-
- -string - - -
-
- - - - - - - - - - - - - -

(async) detectWSL() → {Promise.<boolean>}

- - - - - - -
-

Detects if WSL (Windows Subsystem for Linux) is available on Windows.

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

True if WSL is available, false otherwise

-
- - - -
-
- Type -
-
- -Promise.<boolean> - - -
-
- - - - - - - - - - - - - -

(async) detectWSL() → {Promise.<boolean>}

- - - - - - -
-

Legacy function for backward compatibility

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -Promise.<boolean> - - -
-
- - - - - - - - - - - - - -

(async) detectWSLStatus() → {Promise.<Object>}

- - - - - - -
-

Comprehensive WSL status detection

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Object with available, hasDistros, error, and distributions properties

-
- - - -
-
- Type -
-
- -Promise.<Object> - - -
-
- - - - - - - - - - - - - -

escapeHtml(text) → {string}

- - - - - - -
-

Escape HTML special characters

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
text - - -string - - - -

Text to escape

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

Escaped HTML string

-
- - - -
-
- Type -
-
- -string - - -
-
- - - - - - - - - - - - - -

formatFileSize(bytes) → {string}

- - - - - - -
-

Format file size for display

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
bytes - - -number - - - -

File size in bytes

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • Formatted file size
  • -
-
- - - -
-
- Type -
-
- -string - - -
-
- - - - - - - - - - - - - -

getFileIcon(filename) → {string}

- - - - - - -
-

Get file icon based on extension

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
filename - - -string - - - -

The filename

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • Unicode emoji for file icon
  • -
-
- - - -
-
- Type -
-
- -string - - -
-
- - - - - - - - - - - - - -

getLanguageConfig(fileType) → {Object}

- - - - - - -
-

Get language configuration

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
fileType - - -string - - - -

The file type

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • Language configuration
  • -
-
- - - -
-
- Type -
-
- -Object - - -
-
- - - - - - - - - - - - - -

(async) handleLocalChat(message, config) → {Promise.<Object>}

- - - - - - -
-

Handle local GGUF model chat using node-llama-cpp

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
message - - -string - - - -

User message

config - - -Object - - - -

Config with localModelPath and gpuLayers

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -Promise.<Object> - - -
-
- - - - - - - - - - - - - -

(async) handleModularProvider(message, config) → {Promise.<Object>}

- - - - - - -
-

Handle external API chat using modular provider system

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
message - - -string - - - -

User message

config - - -Object - - - -

Config with providerId and provider-specific settings

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -Promise.<Object> - - -
-
- - - - - - - - - - - - - -

(async) handleOllamaChat(message, config) → {Promise.<Object>}

- - - - - - -
-

Handle Ollama chat request

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
message - - -string - - - -

User message

config - - -Object - - - -

Config with ollamaHost

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - - - -
-
- Type -
-
- -Promise.<Object> - - -
-
- - - - - - - - - - - - - -

highlightCppSyntax(code, fileType) → {string}

- - - - - - -
-

Highlight C/C++ syntax (optimized version)

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
code - - -string - - - -

The code to highlight

fileType - - -string - - - -

The file type

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • HTML with syntax highlighting
  • -
-
- - - -
-
- Type -
-
- -string - - -
-
- - - - - - - - - - - - - -

(async) installWSLAutomatically()

- - - - - - -
-

Install WSL automatically using PowerShell

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

(async) installWSLDistribution()

- - - - - - -
-

Install a specific WSL distribution

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

isValidUTF8(buffer) → {boolean}

- - - - - - -
-

Check if file is UTF-8 encoded

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
buffer - - -Buffer - - - -

File buffer to check

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • True if file is UTF-8
  • -
-
- - - -
-
- Type -
-
- -boolean - - -
-
- - - - - - - - - - - - - -

(async) searchInDirectory(dirPath, searchTerm, maxResults) → {Array}

- - - - - - -
-

Search in files within directory

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDefaultDescription
dirPath - - -string - - - - - -

Directory path to search

searchTerm - - -string - - - - - -

Search term

maxResults - - -number - - - - - - 100 - -

Maximum results to return

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • Search results
  • -
-
- - - -
-
- Type -
-
- -Array - - -
-
- - - - - - - - - - - - - -

setupAssistantHandlers(mainWindow)

- - - - - - -
-

Setup IPC handlers for assistant chat

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
mainWindow - - -BrowserWindow - - - -

Main window reference

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

setupCtraceHandlers()

- - - - - - -
-

Setup IPC handlers for running the ctrace binary

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

setupEditorHandlers()

- - - - - - -
-

Setup IPC handlers for editor operations

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

setupFileHandlers(mainWindow)

- - - - - - -
-

Sets up all IPC handlers for file operations.

-

This function registers all IPC handlers that the renderer process can invoke -for file operations. It handles folder dialogs, file dialogs, saving files, -reading files, and file tree operations.

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
mainWindow - - -BrowserWindow - - - -

Main window reference for dialogs

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - -
Example
- -
setupFileHandlers(mainWindow);
- - - - - - - - - -

setupWindowControls(window)

- - - - - - -
-

Sets up IPC handlers for custom window controls.

-

This function handles window minimize, maximize, and close operations -for the custom frameless window title bar.

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
window - - -BrowserWindow - - - -

The main window instance

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

shouldHighlight(fileType) → {boolean}

- - - - - - -
-

Check if file type should have syntax highlighting

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
fileType - - -string - - - -

The file type to check

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • True if highlighting should be applied
  • -
-
- - - -
-
- Type -
-
- -boolean - - -
-
- - - - - - - - - - - - - -

(async) showDistributionOptions()

- - - - - - -
-

Show available WSL distributions for installation

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

(async) showLimitedFunctionalityDialog()

- - - - - - -
-

Show limited functionality dialog

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

showManualInstallationInstructions()

- - - - - - -
-

Show manual installation instructions

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

(async) showWSLSetupDialog(wslStatus) → {Promise.<boolean>}

- - - - - - -
-

Shows enhanced WSL installation dialog based on WSL status

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
wslStatus - - -Object - - - -

Current WSL status

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-

True if user wants to proceed, false otherwise

-
- - - -
-
- Type -
-
- -Promise.<boolean> - - -
-
- - - - - - - - - - - - - -

startWatchingWorkspace(workspacePath, mainWindow)

- - - - - - -
-

Start watching workspace for file changes

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
workspacePath - - -string - - - -

Path to watch

mainWindow - - -BrowserWindow - - - -

Main window reference

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

stopWatchingWorkspace()

- - - - - - -
-

Stop watching current workspace

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

testEmojiSupport()

- - - - - - -
-

Test emoji rendering and font availability

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

(async) testWSLAndCTrace()

- - - - - - -
-

Test WSL availability and CTrace execution

-
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -

tokenizeCpp(code, langConfig) → {Array}

- - - - - - -
-

Tokenize C/C++ code for highlighting

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
code - - -string - - - -

The code to tokenize

langConfig - - -Object - - - -

Language configuration

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • Array of tokens with type and value
  • -
-
- - - -
-
- Type -
-
- -Array - - -
-
- - - - - - - - - - - - - -

tokensToHtml(tokens, langConfig) → {string}

- - - - - - -
-

Convert tokens to HTML

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
tokens - - -Array - - - -

Array of tokens

langConfig - - -Object - - - -

Language configuration

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - -
Returns:
- - -
-
    -
  • HTML string
  • -
-
- - - -
-
- Type -
-
- -string - - -
-
- - - - - - - - - - - - - -

updateFileTypeStatus(filename)

- - - - - - -
-

Update file type status in the status bar

-
- - - - - - - - - -
Parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
filename - - -string - - - -

The filename to analyze

- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Source:
-
- - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - \ No newline at end of file diff --git a/docs/index.html b/docs/index.html deleted file mode 100644 index 57d87b4..0000000 --- a/docs/index.html +++ /dev/null @@ -1,1277 +0,0 @@ - - - - - JSDoc: Home - - - - - - - - - - -
- -

Home

- - - - - - - - -

- - - - - - - - - - - - - - - -
-

CTrace GUI

-

A modern Electron-based GUI application for running CTrace analysis on C/C++ code.

-

Overview

-

CTrace GUI provides an intuitive interface for analyzing C/C++ source code using the CTrace analysis tool. The application features a VS Code-like interface with file management, syntax highlighting, and integrated analysis results.

-

Features

-
    -
  • File Management: Open individual files or entire workspaces
  • -
  • File Tree Explorer: Navigate project structure with refresh and auto-watch capabilities
  • -
  • Code Editor: Syntax-highlighted editor with line numbers and search functionality
  • -
  • Tab Management: Multi-file editing with tab interface
  • -
  • CTrace Integration: Run static analysis directly from the GUI
  • -
  • Search: Global search across workspace files
  • -
  • Notifications: User-friendly notification system
  • -
-

Architecture

-

The application follows a modular architecture with separate managers for different concerns:

-
    -
  • UIController: Main coordinator for all UI components
  • -
  • FileOperationsManager: Handles file I/O operations
  • -
  • TabManager: Manages editor tabs and file switching
  • -
  • EditorManager: Controls the code editor functionality
  • -
  • SearchManager: Handles search operations
  • -
  • NotificationManager: Manages user notifications
  • -
-

Getting Started

-

Prerequisites

-
    -
  • Node.js (v18+)
  • -
  • npm
  • -
  • Electron
  • -
  • CTrace binary
  • -
-

Installation

-
npm install
-
-

Running the Application

-
npm start
-
-

Building the Application

-
npm run dist
-
-

Generating Documentation

-
npm run docs
-
-

Documentation

-

Complete API documentation is available in the docs/ directory after running npm run docs.

-

License

-

// To determine

-
- - - - - - - - - -
- -
- -

src/main.js

- - -
- -
-
- - -

Main entry point for the CTrace GUI Electron application.

-

This file initializes the Electron app, creates the main window, and sets up -all IPC handlers for communication between the main and renderer processes.

- - - - - -
- - -
Version:
-
  • 1.0.0
- - - - - - - - - - - - - - - - - -
Author:
-
-
    -
  • CTrace GUI Team
  • -
-
- - - - - - - - - -
Source:
-
- - - - - - - -
- - - - -
- - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - - -
- -
- -

src/main/external_llm/AnthropicProvider.js

- - -
- -
-
- - -

Anthropic API Provider (Claude)

-

Implements Anthropic's messages API for Claude models.

- - - - - -
- - -
Version:
-
  • 1.0.0
- - - - - - - - - - - - - - - - - -
Author:
-
-
    -
  • CTrace GUI Team
  • -
-
- - - - - - - - - -
Source:
-
- - - - - - - -
- - - - -
- - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - - -
- -
- -

src/main/external_llm/BaseProvider.js

- - -
- -
-
- - -

Base class for LLM providers

-

This defines the interface that all LLM providers must implement, -ensuring consistent behavior across different services.

- - - - - -
- - -
Version:
-
  • 1.0.0
- - - - - - - - - - - - - - - - - -
Author:
-
-
    -
  • CTrace GUI Team
  • -
-
- - - - - - - - - -
Source:
-
- - - - - - - -
- - - - -
- - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - - -
- -
- -

src/main/external_llm/DeepseekProvider.js

- - -
- -
-
- - -

Deepseek API Provider

-

Implements Deepseek's chat completions API.

- - - - - -
- - -
Version:
-
  • 1.0.0
- - - - - - - - - - - - - - - - - -
Author:
-
-
    -
  • CTrace GUI Team
  • -
-
- - - - - - - - - -
Source:
-
- - - - - - - -
- - - - -
- - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - - -
- -
- -

src/main/external_llm/GenericOpenAIProvider.js

- - -
- -
-
- - -

Generic OpenAI-Compatible Provider

-

A flexible provider for any LLM service that implements the OpenAI chat completions API. -This includes services like:

-
    -
  • Together AI
  • -
  • Groq
  • -
  • Perplexity
  • -
  • Local deployments (LM Studio, Ollama with OpenAI compatibility)
  • -
  • Azure OpenAI
  • -
  • And many others
  • -
- - - - - -
- - -
Version:
-
  • 1.0.0
- - - - - - - - - - - - - - - - - -
Author:
-
-
    -
  • CTrace GUI Team
  • -
-
- - - - - - - - - -
Source:
-
- - - - - - - -
- - - - -
- - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - - -
- -
- -

src/main/external_llm/GroqProvider.js

- - -
- -
-
- - -

Groq API Provider (Example)

-

This is an example provider showing how easy it is to add support -for new LLM services. Groq offers extremely fast inference.

- - - - - -
- - -
Version:
-
  • 1.0.0
- - - - - - - - - - - - - - - - - -
Author:
-
-
    -
  • CTrace GUI Team
  • -
-
- - - - - - - - - -
Source:
-
- - - - - - - -
- - - - -
- - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - - -
- -
- -

src/main/external_llm/OpenAIProvider.js

- - -
- -
-
- - -

OpenAI API Provider (ChatGPT, GPT-4, etc.)

-

Implements OpenAI's chat completions API for GPT models.

- - - - - -
- - -
Version:
-
  • 1.0.0
- - - - - - - - - - - - - - - - - -
Author:
-
-
    -
  • CTrace GUI Team
  • -
-
- - - - - - - - - -
Source:
-
- - - - - - - -
- - - - -
- - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - - -
- -
- -

src/main/external_llm/PerplexityProvider.js

- - -
- -
-
- - -

Perplexity API Provider (Example)

-

Perplexity offers LLMs with real-time internet search capabilities, -perfect for getting up-to-date information and current best practices.

- - - - - -
- - -
Version:
-
  • 1.0.0
- - - - - - - - - - - - - - - - - -
Author:
-
-
    -
  • CTrace GUI Team
  • -
-
- - - - - - - - - -
Source:
-
- - - - - - - -
- - - - -
- - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - - -
- -
- -

src/main/external_llm/ProviderRegistry.js

- - -
- -
-
- - -

Provider Registry

-

Central registry for all available LLM providers. -Handles provider registration, instantiation, and discovery.

- - - - - -
- - -
Version:
-
  • 1.0.0
- - - - - - - - - - - - - - - - - -
Author:
-
-
    -
  • CTrace GUI Team
  • -
-
- - - - - - - - - -
Source:
-
- - - - - - - -
- - - - -
- - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - - -
- -
- -

src/main/ipc/assistantHandlers.js

- - -
- -
-
- - -

IPC handlers for AI assistant (Ollama, External API, Local GGUF)

-

This module provides IPC handlers for chatting with various LLM providers. -Now uses a modular provider system for easy extensibility.

- - - - - -
- - -
Version:
-
  • 1.0.0
- - - - - - - - - - - - - - - - - -
Author:
-
-
    -
  • CTrace GUI Team
  • -
-
- - - - - - - - - -
Source:
-
- - - - - - - -
- - - - -
- - - - - - - - - - - - - - - - - - - - -
- -
- - - - - - - -
- -
- -

src/main/ipc/fileHandlers.js

- - -
- -
-
- - -

IPC handlers for file operations in the main process.

-

This module provides all IPC handlers for file system operations including -opening files/folders, saving files, reading file content, and managing -file system watching for automatic UI updates.

- - - - - -
- - -
Version:
-
  • 1.0.0
- - - - - - - - - - - - - - - - - -
Author:
-
-
    -
  • CTrace GUI Team
  • -
-
- - - - - - - - - -
Source:
-
- - - - - - - -
- - - - -
- - - - - - - - - - - - - - - - - - - - -
- -
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - \ No newline at end of file diff --git a/docs/ipc-channels.md b/docs/ipc-channels.md deleted file mode 100644 index 5daf3c1..0000000 --- a/docs/ipc-channels.md +++ /dev/null @@ -1,506 +0,0 @@ -# IPC Channel Reference - -Electron apps have two separate JavaScript environments: - -- **Main process** (`src/main.js` and `src/main/`) — runs Node.js, has full OS access (file system, child processes, dialogs). -- **Renderer process** (`src/renderer/`) — runs in a sandboxed browser window, has no direct Node.js access. - -These two environments talk to each other through **IPC (Inter-Process Communication)**. The bridge is defined in `src/preload.js` and exposed on `window.api` in the renderer. - -## How to Call IPC from the Renderer - -There are three communication patterns, all accessed through `window.api`: - -### `window.api.invoke(channel, ...args)` — Request / Response - -Use this when you need a result back. Returns a `Promise`. - -```js -// Example: read a file -const result = await window.api.invoke('read-file', '/path/to/file.c'); -if (result.success) { - console.log(result.content); -} else { - console.error(result.error); -} -``` - -All invoke handlers return an object with at minimum `{ success: boolean }`. On failure they include `{ success: false, error: string }`. - -### `window.api.send(channel, ...args)` — Fire and Forget - -Use this when you want to trigger an action in the main process but don't need a response. - -```js -// Example: minimize the window -window.api.send('window-minimize'); -``` - -### `window.api.on(channel, callback)` — Listen for Main → Renderer Events - -Use this when the main process needs to push data to the renderer unprompted (e.g. a file was changed on disk). - -```js -// Example: react to file system changes -const sub = window.api.on('workspace-changed', (data) => { - console.log('Files changed:', data.changedPath); -}); - -// Later, when you no longer need it: -window.api.removeListener('workspace-changed', sub); -``` - ---- - -## File Operations - -These channels handle all file system interactions: opening files, saving, creating, deleting, and watching for changes. - ---- - -**`get-file-tree`** `invoke(channel, folderPath)` - -Reads a directory and returns its immediate children (lazy mode — subdirectory contents are not loaded). Use this to refresh the file tree sidebar after a change. - -- **`folderPath`** `string` — Absolute path to the directory. -- **Returns** `{ success, fileTree }` — `fileTree` is an array of `{ name, path, type: 'file'|'directory', hasChildren, children }` objects. Directories have `children: null` (lazy) unless already loaded. - -Also fires `workspace-loading` events (`start` then `end`) on the main window while running. - ---- - -**`open-folder-dialog`** `invoke(channel)` - -Opens the OS folder picker dialog and loads the selected folder as the workspace. Automatically starts watching the folder for file changes. - -- **Returns** `{ success, folderPath, fileTree }` on selection, or `{ success: false, canceled: true }` if the user dismissed the dialog. - ---- - -**`open-file-dialog`** `invoke(channel)` - -Opens the OS file picker dialog and reads the selected file. - -- **Returns** on success: `{ success, filePath, fileName, content, isPartial, totalSize, loadedSize }`. If the file exceeds 1 MB, only the first 1 MB is returned and `isPartial` is `true`. If the file is not UTF-8, returns `{ success: true, warning: 'encoding', filePath, fileName, message }` without content. - ---- - -**`read-file`** `invoke(channel, filePath)` - -Reads a file at a known path without opening a dialog. Applies the same 1 MB and encoding checks as `open-file-dialog`. - -- **`filePath`** `string` — Absolute path to the file. -- **Returns** `{ success, content, fileName, isPartial, totalSize, loadedSize }` or `{ success: true, warning: 'encoding', ... }` for non-UTF-8 files. - ---- - -**`force-open-file`** `invoke(channel, filePath)` - -Opens a file and forces reading it as UTF-8 even if it appears to be binary or non-UTF-8. Characters that can't be decoded appear as replacement characters (`?`). Also respects the 1 MB partial-load limit. - -- **`filePath`** `string` — Absolute path to the file. -- **Returns** `{ success, content, fileName, isPartial, totalSize, loadedSize, encodingWarning }`. - ---- - -**`force-load-full-file`** `invoke(channel, filePath)` - -Reads an entire file as UTF-8, bypassing the 1 MB size limit. Use this when the user explicitly wants to load a large file in full. - -- **`filePath`** `string` — Absolute path to the file. -- **Returns** `{ success, content, fileName, totalSize }`. - ---- - -**`get-directory-contents`** `invoke(channel, dirPath)` - -Lazily loads the immediate children of a single directory. Use this when the user expands a folder in the file tree that hasn't been loaded yet. - -- **`dirPath`** `string` — Absolute path to the directory. -- **Returns** `{ success, contents }` — `contents` is the same array format as `fileTree` from `get-file-tree`. - ---- - -**`save-file`** `invoke(channel, filePath, content)` - -Writes content to an existing file path without showing a dialog. Used for Ctrl+S saves. - -- **`filePath`** `string` — Absolute path. -- **`content`** `string` — New file content. -- **Returns** `{ success }`. - ---- - -**`save-file-as`** `invoke(channel, content)` - -Opens the OS save dialog and writes content to the chosen path. Used for Ctrl+Shift+S. - -- **`content`** `string` — File content to save. -- **Returns** `{ success, filePath, fileName }` or `{ success: false, canceled: true }`. - ---- - -**`create-file`** `invoke(channel, directoryPath, fileName)` - -Creates a new empty file inside `directoryPath`. Fails if the file already exists (`EEXIST`). - -- **`directoryPath`** `string` — Parent directory. -- **`fileName`** `string` — Name only (no path separators allowed). -- **Returns** `{ success, path, name }`. - ---- - -**`create-folder`** `invoke(channel, directoryPath, folderName)` - -Creates a new folder inside `directoryPath`. - -- **`directoryPath`** `string` — Parent directory. -- **`folderName`** `string` — Name only (no path separators allowed). -- **Returns** `{ success, path, name }`. - ---- - -**`rename-path`** `invoke(channel, targetPath, newName)` - -Renames a file or folder. The new name must not contain path separators. - -- **`targetPath`** `string` — Absolute path to the file or folder. -- **`newName`** `string` — New name (basename only). -- **Returns** `{ success, newPath, name, isFile }`. - ---- - -**`delete-path`** `invoke(channel, targetPath)` - -Deletes a file or recursively deletes a folder. - -- **`targetPath`** `string` — Absolute path. -- **Returns** `{ success }`. - ---- - -**`search-in-files`** `invoke(channel, searchTerm, folderPath)` - -Searches all text files under `folderPath` for `searchTerm` (case-insensitive regex). Recurses up to 5 directory levels deep, returns at most 100 matches. - -- **`searchTerm`** `string` — Search query (treated as a regex). -- **`folderPath`** `string` — Workspace root to search under. -- **Returns** `{ success, results }` — `results` is an array of `{ file, fileName, line, content, matches }`. - ---- - -**`watch-workspace`** `invoke(channel, folderPath)` - -Starts watching `folderPath` for file system changes using chokidar. Any add/remove event (debounced 750 ms) triggers a `workspace-changed` push event to the renderer. Replaces any previously active watcher. - -- **`folderPath`** `string` — Directory to watch. -- **Returns** `{ success }`. - ---- - -**`select-llm-file`** `invoke(channel)` - -Opens the OS file picker filtered to GGUF/ONNX model files. Used in the AI assistant settings to choose a local model. - -- **Returns** `{ success, filePath }` or `{ success: false, canceled: true }`. - ---- - -## CTrace Analysis - ---- - -**`run-ctrace`** `invoke(channel, args)` - -Runs the CTrace static analysis engine on a C/C++ file. Starts the ctrace server process if it isn't already running, sends the analysis request to it, and waits for results. - -- **`args`** `string[]` — CLI-style arguments, e.g. `['--input=/path/to/file.c', '--static_analysis=true']`. Supported flags: - - `--input=` (required) — file to analyze - - `--static_analysis=true|false` (default: `true`) - - `--dynamic_analysis=true|false` (default: `false`) - - `--invoke=` — optional tool to invoke (e.g. `ctrace_stack_analyzer`) - - `--sarif_format=true|false` — request SARIF output -- **Returns** `{ success, output }` where `output` is a JSON string in either SARIF format or the CTrace stack-analyzer format (`{ meta, functions, diagnostics }`). - -> **Note:** On Windows, the ctrace binary runs inside WSL. The application checks WSL availability on startup. If WSL is missing, the run will fail with a descriptive error. - ---- - -**`open-editor`** `invoke(channel)` - -Opens the system's default plain-text editor (Notepad on Windows, TextEdit on macOS, nano in a terminal on Linux). Used for quick edits outside the app. - -- **Returns** nothing meaningful — opens the editor as a fire-and-forget subprocess. - ---- - -## AI Assistant - -The assistant supports three providers: **Ollama** (local server), **external** (cloud APIs like OpenAI/Anthropic/Groq), and **local** (a GGUF file loaded directly into the process via `node-llama-cpp`). - ---- - -**`assistant-chat`** `invoke(channel, { provider, message, config })` - -Sends a message to the configured AI provider and returns the response. - -- **`provider`** `'ollama' | 'external' | 'local'` -- **`message`** `string` — The user's message. -- **`config`** `object` — Provider-specific options: - - Ollama: `{ ollamaHost, systemPrompt }` - - External: `{ providerId, apiKey, model, systemPrompt, temperature, maxTokens, ... }` - - Local: `{ localModelPath, gpuLayers, contextSize, systemPrompt }` -- **Returns** `{ success, reply }` — `reply` is the assistant's response text. - ---- - -**`assistant-get-providers`** `invoke(channel)` - -Returns the list of all registered external API providers (OpenAI, Anthropic, Groq, Deepseek, Perplexity, etc.). - -- **Returns** `{ success, providers }` — `providers` is an array of provider descriptor objects. - ---- - -**`assistant-test-provider`** `invoke(channel, { providerId, config })` - -Tests connectivity to a provider without sending a real message. Useful for validating API keys in the settings UI. - -- **`providerId`** `string` — Provider identifier (e.g. `'openai'`). -- **`config`** `object` — Provider config including API key. -- **Returns** `{ success }` or `{ success: false, error }`. - ---- - -**`assistant-unload-local`** `invoke(channel)` - -Disposes the currently loaded local GGUF model and frees its memory. Call this when the user changes model settings or closes the assistant panel. - -- **Returns** `{ success }`. - ---- - -## Session State - -The app automatically saves and restores its state (open tabs, editor positions, diagnostics) to prevent work loss. State is stored as JSON in the Electron `userData` directory. - ---- - -**`save-app-state`** `invoke(channel, state)` - -Serializes and saves the current application state. A backup of the previous state file is kept alongside it. - -- **`state`** `object` — Arbitrary state object (typically `{ version, timestamp, tabs, diagnostics, ... }`). -- **Returns** `{ success }`. - ---- - -**`load-app-state`** `invoke(channel)` - -Loads the last saved state. Falls back to the backup file if the main file is corrupted. - -- **Returns** `{ success, state }` or `{ success: false, error: 'No valid state found' }`. - ---- - -**`clear-app-state`** `invoke(channel)` - -Deletes both the main and backup state files. Use this to reset the application to a clean start. - -- **Returns** `{ success }`. - ---- - -**`get-state-info`** `invoke(channel)` - -Returns metadata about the saved state without loading its full contents. Useful for showing "restore session?" prompts without deserializing everything. - -- **Returns** `{ success, info }` — `info` is `{ exists, size, modified, version, timestamp, tabCount, hasDiagnostics }` when a state file exists, or `{ exists: false }` when it does not. - ---- - -## Auto-Updater - -The app uses `electron-updater` to deliver automatic updates. Two update channels are supported: **main** (stable releases) and **beta** (pre-releases). Update preferences are stored in the `userData` directory. - ---- - -**`updater-get-settings`** `invoke(channel)` - -Reads the saved update channel preference and applies it to the updater. - -- **Returns** `{ success, settings: { channel }, isPackaged }` — `isPackaged` is `false` in development, which disables actual update checks. - ---- - -**`updater-set-channel`** `invoke(channel, channel)` - -Changes the update channel and persists the selection. - -- **`channel`** `'main' | 'beta'` -- **Returns** `{ success, settings: { channel } }`. - ---- - -**`updater-check-now`** `invoke(channel)` - -Triggers an immediate update check. Only works in packaged builds (`app.isPackaged === true`). - -- **Returns** `{ success, updateInfo }` or `{ success: false, error }`. - ---- - -**`updater-install-update`** `invoke(channel)` - -Quits the application and installs a previously downloaded update. Only works in packaged builds. - -- **Returns** `{ success }` (the app will quit immediately after). - ---- - -**`backend-get-status`** `invoke(channel)` - -Returns the most recent backend (ctrace binary) update status recorded by the updater background task. - -- **Returns** `{ success, status }` — `status` is a `{ type, ... }` object mirroring the `updater-status` event types, or `null` if no check has run yet. - ---- - -## Window Controls - -These `send` channels control the application window. They fire and forget — no response is returned. - ---- - -**`window-minimize`** `send(channel)` -Minimizes the main window. - -**`window-maximize-toggle`** `send(channel)` -Maximizes the window if it is not maximized, or restores it if it is. - -**`window-close`** `send(channel)` -Closes the main window (triggers the normal close flow including state save). - -**`open-visualyzer`** `send(channel)` -Opens the CTrace Visualizer in a separate window. - ---- - -## Startup & WSL - ---- - -**`startup-ready`** `send(channel, { restored, timestamp, elapsedMs })` - -Sent by the renderer once it has finished loading and (optionally) restoring a previous session. Triggers deferred post-startup tasks in the main process (updater initialization, ctrace server warm-up). - -- **`restored`** `boolean` — Whether a previous session was restored. -- **`timestamp`** `number` — `Date.now()` at the moment the renderer became ready. -- **`elapsedMs`** `number` — Time in milliseconds from renderer process start to ready. - ---- - -**`check-wsl-status`** `send(channel)` - -Asks the main process to detect whether WSL is installed and has a usable Linux distribution. The result is pushed back via the `wsl-status` receive channel. On non-Windows platforms the response is always `{ available: true }`. - ---- - -**`install-wsl`** `send(channel)` - -Triggers automatic WSL installation (Windows only, requires administrator privileges). Progress is reported through the `wsl-install-response` receive channel. - ---- - -**`install-wsl-distro`** `send(channel, distroName)` - -Installs a specific WSL Linux distribution. Defaults to `'Ubuntu'` if `distroName` is empty. - -- **`distroName`** `string` — e.g. `'Ubuntu'`, `'Debian'`. - ---- - -**`show-wsl-setup`** `send(channel)` - -Opens the WSL setup dialog from within the main process (Windows only). The dialog guides the user through enabling WSL. - ---- - -## Configuration Updates - -**`assistant-config-updated`** `send(channel, config)` - -Notifies the main process that the AI assistant configuration has changed (provider, API key, model path, etc.). The main process uses this to update its cached provider settings. - -- **`config`** `object` — The updated assistant configuration object. - ---- - -## Main → Renderer Events - -These are events the main process pushes to the renderer without being asked. Listen for them with `window.api.on(channel, callback)`. - ---- - -**`workspace-changed`** `on(channel, callback(data))` - -Fired when a file or folder is added or removed inside the currently watched workspace. The renderer should refresh the file tree in response. - -- **`data`** `{ success: true, folderPath, changedPath }` — `changedPath` is the file/folder that triggered the event. - ---- - -**`workspace-loading`** `on(channel, callback(data))` - -Fired at the start and end of a workspace load or refresh operation. Use it to show/hide a loading indicator. - -- **`data`** `{ status: 'start'|'end', operation: 'open'|'refresh', folderPath, requestId, success?, error? }` — `success` and `error` are only present on `status: 'end'`. - ---- - -**`wsl-status`** `on(channel, callback(data))` - -Response to a `check-wsl-status` send. Reports WSL availability. - -- **`data`** `{ available: boolean, hasDistros: boolean, platform: string, distros?: string[] }` - ---- - -**`wsl-install-response`** `on(channel, callback(data))` - -Progress and result updates from a `install-wsl` or `install-wsl-distro` send. - -- **`data`** — Format varies by installation step; contains at minimum `{ success: boolean }`. - ---- - -**`updater-status`** `on(channel, callback(data))` - -Pushed whenever the updater state changes. The `type` field identifies the event: - -| `type` | When | -|---|---| -| `checking-for-update` | Update check started | -| `update-available` | A newer version was found (includes `info`) | -| `update-not-available` | Already on the latest version | -| `download-progress` | Download in progress (includes `progress: { percent, transferred, total, bytesPerSecond }`) | -| `update-downloaded` | Download complete, ready to install (includes `info`) | -| `error` | Updater error (includes `message`) | -| `backend-checking-for-update` | Backend binary check started | -| `backend-update-installed` | Backend binary was updated (includes `info`) | -| `backend-update-not-available` | Backend binary already up to date | -| `backend-error` | Backend update check failed (includes `message`) | - ---- - -**`window-maximized`** `on(channel, callback(isMaximized))` - -Fired when the window is maximized or restored. Use it to update the maximize/restore button icon in the custom title bar. - -- **`isMaximized`** `boolean` - ---- - -**`app-before-quit`** `on(channel, callback())` - -Fired just before the application exits. The renderer must synchronously (or via a brief async pause) save the current session state before returning, so no work is lost. diff --git a/docs/main.js.html b/docs/main.js.html deleted file mode 100644 index 1db958c..0000000 --- a/docs/main.js.html +++ /dev/null @@ -1,631 +0,0 @@ - - - - - JSDoc: Source: main.js - - - - - - - - - - -
- -

Source: main.js

- - - - - - -
-
-
/**
- * @fileoverview Main entry point for the CTrace GUI Electron application.
- * 
- * This file initializes the Electron app, creates the main window, and sets up
- * all IPC handlers for communication between the main and renderer processes.
- * 
- * @author CTrace GUI Team
- * @version 1.0.0
- */
-
-const { app, BrowserWindow, nativeImage, dialog, shell } = require('electron');
-const path = require('path');
-const os = require('os');
-const { spawn } = require('child_process');
-
-// Import IPC handlers
-const { setupFileHandlers } = require('./main/ipc/fileHandlers');
-const { setupEditorHandlers } = require('./main/ipc/editorHandlers');
-const { setupCtraceHandlers } = require('./main/ipc/ctraceHandlers');
-const { setupAssistantHandlers } = require('./main/ipc/assistantHandlers');
-
-/**
- * Creates and configures the main application window.
- * 
- * This function sets up the BrowserWindow with appropriate dimensions,
- * icon, and security settings. It loads the main HTML file and configures
- * the window appearance.
- * 
- * @function createWindow
- * @returns {BrowserWindow} The created main window instance
- * 
- * @example
- * const mainWindow = createWindow();
- */
-function createWindow () {
-  const iconPath = path.join(__dirname, '../assets/ctrace.png');
-  const iconApp = nativeImage.createFromPath(iconPath);
-
-  const win = new BrowserWindow({
-    width: 1200,
-    height: 800,
-    minWidth: 800,
-    minHeight: 600,
-    icon: iconApp,
-    frame: false,               // Custom frame for consistency across platforms
-    titleBarStyle: 'hidden',    // Hide native title bar
-    titleBarOverlay: {
-      color: '#0d1117',         // Match VS Code dark theme
-      symbolColor: '#ffffff',
-      height: 30
-    },
-    webPreferences: {
-      nodeIntegration: true,      // allows require() in renderer
-      contextIsolation: false,    // disables security isolation
-      webSecurity: false          // For loading local fonts
-    }
-  });
-
-  win.loadFile('src/index.html');
-  
-  // Custom window controls for frameless window
-  win.on('maximize', () => {
-    win.webContents.send('window-maximized', true);
-  });
-  
-  win.on('unmaximize', () => {
-    win.webContents.send('window-maximized', false);
-  });
-  
-  return win;
-}
-
-/**
- * Creates the Visualyzer window as a separate, movable window
- * @returns {BrowserWindow} The created visualyzer window instance
- */
-function createVisualizerWindow() {
-  const iconPath = path.join(__dirname, '../assets/ctrace.png');
-  const iconApp = nativeImage.createFromPath(iconPath);
-
-  const vizWin = new BrowserWindow({
-    width: 1000,
-    height: 700,
-    minWidth: 600,
-    minHeight: 500,
-    icon: iconApp,
-    title: 'CTrace Visualyzer',
-    backgroundColor: '#0d1117',
-    autoHideMenuBar: true,
-    webPreferences: {
-      nodeIntegration: true,
-      contextIsolation: false,
-      webSecurity: false
-    }
-  });
-
-  vizWin.loadFile('src/visualyzer.html');
-  vizWin.setMenuBarVisibility(false);
-  
-  // Open DevTools in development (optional)
-  // vizWin.webContents.openDevTools();
-  
-  return vizWin;
-}
-
-/**
- * Detects if WSL (Windows Subsystem for Linux) is available on Windows.
- * 
- * @async
- * @function detectWSL
- * @returns {Promise<boolean>} True if WSL is available, false otherwise
- */
-/**
- * Comprehensive WSL status detection
- * @returns {Promise<Object>} Object with available, hasDistros, error, and distributions properties
- */
-async function detectWSLStatus() {
-  return new Promise((resolve) => {
-    if (os.platform() !== 'win32') {
-      resolve({ available: true, hasDistros: true, distributions: ['linux'] });
-      return;
-    }
-
-    // First check if WSL command exists
-    const statusChild = spawn('wsl', ['--status'], { stdio: 'pipe', windowsHide: true });
-    
-    let statusOutput = '';
-    let statusError = '';
-    
-    statusChild.stdout.on('data', (data) => {
-      statusOutput += data.toString();
-    });
-    
-    statusChild.stderr.on('data', (data) => {
-      statusError += data.toString();
-    });
-    
-    statusChild.on('error', () => {
-      resolve({ available: false, hasDistros: false, error: 'WSL is not installed' });
-    });
-    
-    statusChild.on('close', (statusCode) => {
-      if (statusCode !== 0) {
-        resolve({ available: false, hasDistros: false, error: 'WSL is not available' });
-        return;
-      }
-      
-      // WSL exists, now check for installed distributions
-      const listChild = spawn('wsl', ['--list', '--quiet'], { stdio: 'pipe', windowsHide: true });
-      
-      let listOutput = '';
-      
-      listChild.stdout.on('data', (data) => {
-        listOutput += data.toString();
-      });
-      
-      listChild.on('error', () => {
-        resolve({ available: true, hasDistros: false, error: 'Cannot check WSL distributions' });
-      });
-      
-      listChild.on('close', (listCode) => {
-        const distributions = listOutput.trim().split('\n')
-          .map(line => line.trim())
-          .filter(line => line.length > 0 && !line.includes('Windows Subsystem'))
-          .filter(line => !line.toLowerCase().includes('docker'));
-        
-        const hasDistros = distributions.length > 0 && !statusError.includes('no installed distributions');
-        
-        if (!hasDistros) {
-          const errorMsg = statusError.includes('no installed distributions') || listOutput.includes('no installed distributions')
-            ? 'WSL is installed but no Linux distributions are available'
-            : 'No WSL distributions found';
-          resolve({ available: true, hasDistros: false, error: errorMsg, distributions: [] });
-        } else {
-          resolve({ available: true, hasDistros: true, distributions });
-        }
-      });
-      
-      // Timeout for list command
-      setTimeout(() => {
-        listChild.kill();
-        resolve({ available: true, hasDistros: false, error: 'Timeout checking WSL distributions', distributions: [] });
-      }, 10000);
-    });
-    
-    // Timeout for status command
-    setTimeout(() => {
-      statusChild.kill();
-      resolve({ available: false, hasDistros: false, error: 'Timeout checking WSL status' });
-    }, 10000);
-  });
-}
-
-/**
- * Legacy function for backward compatibility
- * @returns {Promise<boolean>}
- */
-async function detectWSL() {
-  const status = await detectWSLStatus();
-  return status.available && status.hasDistros;
-}
-
-/**
- * Shows enhanced WSL installation dialog based on WSL status
- * @param {Object} wslStatus - Current WSL status
- * @returns {Promise<boolean>} True if user wants to proceed, false otherwise
- */
-async function showWSLSetupDialog(wslStatus) {
-  if (!wslStatus.available) {
-    // WSL not installed at all
-    const result = await dialog.showMessageBox({
-      type: 'warning',
-      title: 'WSL Required for CTrace',
-      message: 'Windows Subsystem for Linux (WSL) is required for CTrace functionality.',
-      detail: 'CTrace uses a Linux binary that requires WSL to run on Windows.\n\nWould you like to install WSL now? This requires administrator privileges and a system restart.',
-      buttons: ['Install WSL Automatically', 'Install Manually', 'Continue Without WSL', 'Exit Application'],
-      defaultId: 0,
-      cancelId: 3,
-      icon: nativeImage.createFromPath(path.join(__dirname, '../assets/ctrace.png'))
-    });
-    
-    if (result.response === 0) {
-      // Automatic installation
-      await installWSLAutomatically();
-      return true;
-    } else if (result.response === 1) {
-      // Manual installation
-      showManualInstallationInstructions();
-      return true;
-    } else if (result.response === 2) {
-      // Continue without WSL
-      await showLimitedFunctionalityDialog();
-      return true;
-    } else {
-      // Exit application
-      return false;
-    }
-    
-  } else if (!wslStatus.hasDistros) {
-    // WSL installed but no distributions
-    const result = await dialog.showMessageBox({
-      type: 'info',
-      title: 'WSL Distribution Required',
-      message: 'WSL is installed but no Linux distributions are available.',
-      detail: 'CTrace requires a Linux distribution to run. Ubuntu is recommended.\n\nWould you like to install Ubuntu now?',
-      buttons: ['Install Ubuntu', 'Choose Different Distribution', 'Continue Without CTrace', 'Exit Application'],
-      defaultId: 0,
-      cancelId: 3,
-      icon: nativeImage.createFromPath(path.join(__dirname, '../assets/ctrace.png'))
-    });
-    
-    if (result.response === 0) {
-      // Install Ubuntu
-      await installWSLDistribution('Ubuntu');
-      return true;
-    } else if (result.response === 1) {
-      // Show distribution options
-      await showDistributionOptions();
-      return true;
-    } else if (result.response === 2) {
-      // Continue without CTrace
-      await showLimitedFunctionalityDialog();
-      return true;
-    } else {
-      // Exit application
-      return false;
-    }
-  }
-  
-  return true; // WSL is fully available
-}
-
-/**
- * Install WSL automatically using PowerShell
- */
-async function installWSLAutomatically() {
-  try {
-    console.log('Attempting to install WSL automatically...');
-    
-    // Show progress dialog
-    dialog.showMessageBox({
-      type: 'info',
-      title: 'Installing WSL',
-      message: 'Installing Windows Subsystem for Linux...',
-      detail: 'This may take a few minutes. Please wait and follow any prompts that appear.',
-      buttons: ['OK']
-    });
-    
-    // Run WSL installation command with Ubuntu
-    const child = spawn('powershell', [
-      '-Command',
-      'Start-Process',
-      'powershell',
-      '-ArgumentList', '"wsl --install Ubuntu"',
-      '-Verb', 'RunAs'
-    ], { stdio: 'pipe', windowsHide: true });
-    
-    child.on('error', (err) => {
-      console.error('Failed to start WSL installation:', err);
-      dialog.showErrorBox(
-        'Installation Failed',
-        `Failed to start WSL installation: ${err.message}\n\nPlease try manual installation instead.`
-      );
-    });
-    
-    child.on('close', (code) => {
-      console.log(`WSL installation completed with code: ${code}`);
-      
-      dialog.showMessageBox({
-        type: 'info',
-        title: 'WSL Installation Started',
-        message: 'WSL and Ubuntu installation has been initiated!',
-        detail: 'Please follow any prompts that appear. You may need to:\n\n1. Allow administrator access\n2. Restart your computer when prompted\n3. Complete Ubuntu setup (username/password)\n4. Restart this application\n\nThe installation will continue in the background.',
-        buttons: ['Got it!']
-      });
-    });
-    
-  } catch (error) {
-    console.error('Error during WSL installation:', error);
-    dialog.showErrorBox(
-      'Installation Error',
-      `Failed to install WSL: ${error.message}\n\nPlease try manual installation instead.`
-    );
-  }
-}
-
-/**
- * Show manual installation instructions
- */
-function showManualInstallationInstructions() {
-  dialog.showMessageBox({
-    type: 'info',
-    title: 'Manual WSL Installation',
-    message: 'Manual Installation Instructions',
-    detail: `To install WSL manually:\n\n` +
-           `1. Open PowerShell as Administrator\n` +
-           `   (Right-click Start → "Windows PowerShell (Admin)")\n\n` +
-           `2. Run: wsl --install Ubuntu\n\n` +
-           `3. Restart your computer when prompted\n\n` +
-           `4. Complete Ubuntu setup (create username/password)\n\n` +
-           `5. Restart this application\n\n` +
-           `For more details, the Microsoft documentation will open next.`,
-    buttons: ['Open Documentation', 'Got it']
-  }).then((result) => {
-    if (result.response === 0) {
-      shell.openExternal('https://docs.microsoft.com/en-us/windows/wsl/install');
-    }
-  });
-}
-
-/**
- * Install a specific WSL distribution
- */
-async function installWSLDistribution(distroName) {
-  try {
-    console.log(`Installing WSL distribution: ${distroName}`);
-    
-    const child = spawn('powershell', [
-      '-Command',
-      'Start-Process',
-      'powershell',
-      '-ArgumentList', `"wsl --install ${distroName}"`,
-      '-Verb', 'RunAs'
-    ], { stdio: 'ignore', windowsHide: true });
-    
-    child.on('error', (err) => {
-      console.error(`Failed to install ${distroName}:`, err);
-      dialog.showErrorBox(
-        'Installation Failed',
-        `Failed to install ${distroName}. Please try installing manually:\n\n1. Open PowerShell as Administrator\n2. Run: wsl --install ${distroName}`
-      );
-    });
-    
-    child.on('close', (code) => {
-      console.log(`${distroName} installation completed with code: ${code}`);
-      dialog.showMessageBox({
-        type: 'info',
-        title: 'Distribution Installation',
-        message: `${distroName} installation has been initiated.`,
-        detail: 'Please follow the setup instructions when they appear. After setup is complete, restart this application to use CTrace.'
-      });
-    });
-    
-  } catch (error) {
-    console.error(`Error installing ${distroName}:`, error);
-    dialog.showErrorBox(
-      'Installation Error',
-      `Failed to install ${distroName}: ${error.message}`
-    );
-  }
-}
-
-/**
- * Show available WSL distributions for installation
- */
-async function showDistributionOptions() {
-  try {
-    // Get list of available distributions
-    const child = spawn('wsl', ['--list', '--online'], { stdio: 'pipe', windowsHide: true });
-    
-    let output = '';
-    
-    child.stdout.on('data', (data) => {
-      output += data.toString();
-    });
-    
-    child.on('close', (code) => {
-      if (code === 0 && output) {
-        dialog.showMessageBox({
-          type: 'info',
-          title: 'Available WSL Distributions',
-          message: 'Available Linux Distributions',
-          detail: `${output}\n\nRecommended: Ubuntu\n\nTo install a distribution:\n1. Open PowerShell\n2. Run: wsl --install <DistributionName>\n3. Follow setup instructions`,
-          buttons: ['Install Ubuntu', 'Install Manually', 'Cancel']
-        }).then((result) => {
-          if (result.response === 0) {
-            installWSLDistribution('Ubuntu');
-          } else if (result.response === 1) {
-            showManualInstallationInstructions();
-          }
-        });
-      } else {
-        dialog.showErrorBox(
-          'Cannot List Distributions',
-          'Unable to get list of available distributions. Please install Ubuntu manually with:\n\nwsl --install Ubuntu'
-        );
-      }
-    });
-    
-  } catch (error) {
-    dialog.showErrorBox(
-      'Error',
-      `Failed to get distribution list: ${error.message}`
-    );
-  }
-}
-
-/**
- * Show limited functionality dialog
- */
-async function showLimitedFunctionalityDialog() {
-  await dialog.showMessageBox({
-    type: 'info',
-    title: 'Limited Functionality - CTrace GUI',
-    message: 'Running without WSL',
-    detail: 'CTrace GUI will run with limited functionality:\n\n✅ File editing and management\n✅ Syntax highlighting\n✅ Project navigation\n❌ CTrace static analysis\n❌ Code analysis reports\n\nTo enable full functionality, install WSL and restart the application.',
-    buttons: ['Continue'],
-    defaultId: 0
-  });
-}
-
-//hot reload
-try {
-  require('electron-reload')(__dirname, {
-  electron: require(path.join(__dirname, '../node_modules/electron')),
-  hardResetMethod: 'exit'
-  });
-} catch (e) {
-  console.log("electron-reload not active");
-}
-
-/**
- * Sets up IPC handlers for custom window controls.
- * 
- * This function handles window minimize, maximize, and close operations
- * for the custom frameless window title bar.
- * 
- * @function setupWindowControls
- * @param {BrowserWindow} window - The main window instance
- */
-function setupWindowControls(window) {
-  const { ipcMain } = require('electron');
-  
-  // Window minimize
-  ipcMain.on('window-minimize', () => {
-    window.minimize();
-  });
-  
-  // Window maximize/restore toggle
-  ipcMain.on('window-maximize-toggle', () => {
-    if (window.isMaximized()) {
-      window.unmaximize();
-    } else {
-      window.maximize();
-    }
-  });
-  
-  // Window close
-  ipcMain.on('window-close', () => {
-    window.close();
-  });
-
-  // Open Visualyzer window
-  ipcMain.on('open-visualyzer', () => {
-    createVisualizerWindow();
-  });
-
-  // WSL status check handler
-  ipcMain.on('check-wsl-status', async (event) => {
-    if (os.platform() === 'win32') {
-      const wslStatus = await detectWSLStatus();
-      event.sender.send('wsl-status', wslStatus);
-    } else {
-      event.sender.send('wsl-status', {
-        available: true,
-        hasDistros: true,
-        platform: os.platform()
-      });
-    }
-  });
-  
-  // Handle manual WSL installation request from renderer
-  ipcMain.on('install-wsl', async () => {
-    if (os.platform() === 'win32') {
-      await installWSLAutomatically();
-    }
-  });
-  
-  // Handle WSL distribution installation request
-  ipcMain.on('install-wsl-distro', async (event, distroName) => {
-    if (os.platform() === 'win32') {
-      await installWSLDistribution(distroName || 'Ubuntu');
-    }
-  });
-  
-  // Handle WSL setup dialog request
-  ipcMain.on('show-wsl-setup', async () => {
-    if (os.platform() === 'win32') {
-      const wslStatus = await detectWSLStatus();
-      await showWSLSetupDialog(wslStatus);
-    }
-  });
-}
-
-// Global reference to main window
-let mainWindow;
-
-app.whenReady().then(async () => {
-  // Create window first
-  mainWindow = createWindow();
-  
-  // Setup IPC handlers
-  setupFileHandlers(mainWindow);
-  setupEditorHandlers();
-  setupCtraceHandlers();
-  setupAssistantHandlers(mainWindow);
-  setupWindowControls(mainWindow);
-  
-  // Check WSL status on Windows after window is ready
-  if (os.platform() === 'win32') {
-    // Give the window time to load, then check WSL
-    setTimeout(async () => {
-      const wslStatus = await detectWSLStatus();
-      console.log('WSL Status detected:', wslStatus);
-      
-      // Send status to renderer
-      if (mainWindow && mainWindow.webContents) {
-        mainWindow.webContents.send('wsl-status', wslStatus);
-      }
-      
-      // Show setup dialog if WSL is not fully ready
-      if (!wslStatus.available || !wslStatus.hasDistros) {
-        const shouldContinue = await showWSLSetupDialog(wslStatus);
-        if (!shouldContinue) {
-          app.quit();
-          return;
-        }
-      }
-    }, 2000);
-  } else {
-    // On non-Windows platforms, send ready status
-    mainWindow.webContents.once('did-finish-load', () => {
-      mainWindow.webContents.send('wsl-status', {
-        available: true,
-        hasDistros: true,
-        platform: os.platform()
-      });
-    });
-  }
-});
-
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/main_external_llm_AnthropicProvider.js.html b/docs/main_external_llm_AnthropicProvider.js.html deleted file mode 100644 index 27d9570..0000000 --- a/docs/main_external_llm_AnthropicProvider.js.html +++ /dev/null @@ -1,184 +0,0 @@ - - - - - JSDoc: Source: main/external_llm/AnthropicProvider.js - - - - - - - - - - -
- -

Source: main/external_llm/AnthropicProvider.js

- - - - - - -
-
-
/**
- * @fileoverview Anthropic API Provider (Claude)
- * 
- * Implements Anthropic's messages API for Claude models.
- * 
- * @author CTrace GUI Team
- * @version 1.0.0
- */
-
-const https = require('https');
-const BaseProvider = require('./BaseProvider');
-
-/**
- * Anthropic API Provider
- * @extends BaseProvider
- */
-class AnthropicProvider extends BaseProvider {
-  constructor(config) {
-    super(config);
-    this.endpoint = config.endpoint || 'https://api.anthropic.com/v1/messages';
-    this.model = config.model || 'claude-3-5-sonnet-20241022';
-    this.apiKey = config.apiKey;
-  }
-
-  getName() {
-    return 'Anthropic (Claude)';
-  }
-
-  getConfigFields() {
-    return [
-      {
-        name: 'apiKey',
-        label: 'API Key',
-        type: 'password',
-        required: true,
-        placeholder: 'sk-ant-...',
-        help: 'Get your API key from https://console.anthropic.com/settings/keys'
-      },
-      {
-        name: 'model',
-        label: 'Model',
-        type: 'select',
-        required: true,
-        default: 'claude-3-5-sonnet-20241022',
-        options: [
-          { value: 'claude-3-5-sonnet-20241022', label: 'Claude 3.5 Sonnet' },
-          { value: 'claude-3-opus-20240229', label: 'Claude 3 Opus' },
-          { value: 'claude-3-sonnet-20240229', label: 'Claude 3 Sonnet' },
-          { value: 'claude-3-haiku-20240307', label: 'Claude 3 Haiku' }
-        ],
-        help: 'Choose the Claude model to use'
-      },
-      {
-        name: 'endpoint',
-        label: 'API Endpoint (Advanced)',
-        type: 'text',
-        required: false,
-        default: 'https://api.anthropic.com/v1/messages',
-        placeholder: 'https://api.anthropic.com/v1/messages',
-        help: 'Custom endpoint URL'
-      }
-    ];
-  }
-
-  async chat(message, options = {}) {
-    if (!this.apiKey) {
-      return { success: false, error: 'API key is required' };
-    }
-
-    // Anthropic uses a different format - system prompt is separate
-    const systemPrompt = options.systemPrompt || 'You are a helpful coding assistant.';
-
-    const body = JSON.stringify({
-      model: this.model,
-      max_tokens: options.maxTokens || 2000,
-      system: systemPrompt,
-      messages: [
-        { role: 'user', content: message }
-      ],
-      temperature: options.temperature !== undefined ? options.temperature : 0.7
-    });
-
-    return new Promise((resolve) => {
-      const url = new URL(this.endpoint);
-      const requestOptions = {
-        hostname: url.hostname,
-        port: 443,
-        path: url.pathname + url.search,
-        method: 'POST',
-        headers: {
-          'Content-Type': 'application/json',
-          'x-api-key': this.apiKey,
-          'anthropic-version': '2023-06-01',
-          'Content-Length': Buffer.byteLength(body)
-        },
-        timeout: 60000
-      };
-
-      const req = https.request(requestOptions, (res) => {
-        let data = '';
-        res.on('data', (chunk) => { data += chunk; });
-        res.on('end', () => {
-          try {
-            const parsed = JSON.parse(data);
-            if (parsed.content && parsed.content[0] && parsed.content[0].text) {
-              resolve({ success: true, reply: parsed.content[0].text });
-            } else if (parsed.error) {
-              resolve({ success: false, error: parsed.error.message || 'API error' });
-            } else {
-              resolve({ success: false, error: 'Invalid API response' });
-            }
-          } catch (err) {
-            resolve({ success: false, error: 'Failed to parse API response: ' + err.message });
-          }
-        });
-      });
-
-      req.on('error', (err) => {
-        resolve({ success: false, error: 'API request failed: ' + err.message });
-      });
-
-      req.on('timeout', () => {
-        req.destroy();
-        resolve({ success: false, error: 'API request timed out' });
-      });
-
-      req.write(body);
-      req.end();
-    });
-  }
-}
-
-module.exports = AnthropicProvider;
-
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/main_external_llm_BaseProvider.js.html b/docs/main_external_llm_BaseProvider.js.html deleted file mode 100644 index fece74b..0000000 --- a/docs/main_external_llm_BaseProvider.js.html +++ /dev/null @@ -1,148 +0,0 @@ - - - - - JSDoc: Source: main/external_llm/BaseProvider.js - - - - - - - - - - -
- -

Source: main/external_llm/BaseProvider.js

- - - - - - -
-
-
/**
- * @fileoverview Base class for LLM providers
- * 
- * This defines the interface that all LLM providers must implement,
- * ensuring consistent behavior across different services.
- * 
- * @author CTrace GUI Team
- * @version 1.0.0
- */
-
-/**
- * Base class for all LLM providers
- * @abstract
- */
-class BaseProvider {
-  /**
-   * Create a provider instance
-   * @param {Object} config - Provider configuration
-   */
-  constructor(config) {
-    if (new.target === BaseProvider) {
-      throw new Error('BaseProvider is abstract and cannot be instantiated directly');
-    }
-    this.config = config;
-  }
-
-  /**
-   * Get provider name
-   * @abstract
-   * @returns {string} Provider name
-   */
-  getName() {
-    throw new Error('getName() must be implemented by provider');
-  }
-
-  /**
-   * Get required configuration fields
-   * @abstract
-   * @returns {Array<Object>} Array of field definitions with { name, label, type, required, placeholder, default }
-   */
-  getConfigFields() {
-    throw new Error('getConfigFields() must be implemented by provider');
-  }
-
-  /**
-   * Validate configuration
-   * @param {Object} config - Configuration to validate
-   * @returns {Object} { valid: boolean, errors: Array<string> }
-   */
-  validateConfig(config) {
-    const errors = [];
-    const fields = this.getConfigFields();
-
-    for (const field of fields) {
-      if (field.required && !config[field.name]) {
-        errors.push(`${field.label} is required`);
-      }
-    }
-
-    return {
-      valid: errors.length === 0,
-      errors
-    };
-  }
-
-  /**
-   * Send a chat message to the LLM
-   * @abstract
-   * @param {string} message - User message
-   * @param {Object} options - Additional options (systemPrompt, temperature, etc.)
-   * @returns {Promise<Object>} { success: boolean, reply?: string, error?: string }
-   */
-  async chat(message, options = {}) {
-    throw new Error('chat() must be implemented by provider');
-  }
-
-  /**
-   * Test provider connection
-   * @returns {Promise<Object>} { success: boolean, error?: string }
-   */
-  async testConnection() {
-    try {
-      const result = await this.chat('Hello', { temperature: 0.1 });
-      return {
-        success: result.success,
-        error: result.error
-      };
-    } catch (error) {
-      return {
-        success: false,
-        error: error.message
-      };
-    }
-  }
-}
-
-module.exports = BaseProvider;
-
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/main_external_llm_DeepseekProvider.js.html b/docs/main_external_llm_DeepseekProvider.js.html deleted file mode 100644 index 484509c..0000000 --- a/docs/main_external_llm_DeepseekProvider.js.html +++ /dev/null @@ -1,182 +0,0 @@ - - - - - JSDoc: Source: main/external_llm/DeepseekProvider.js - - - - - - - - - - -
- -

Source: main/external_llm/DeepseekProvider.js

- - - - - - -
-
-
/**
- * @fileoverview Deepseek API Provider
- * 
- * Implements Deepseek's chat completions API.
- * 
- * @author CTrace GUI Team
- * @version 1.0.0
- */
-
-const https = require('https');
-const BaseProvider = require('./BaseProvider');
-
-/**
- * Deepseek API Provider
- * @extends BaseProvider
- */
-class DeepseekProvider extends BaseProvider {
-  constructor(config) {
-    super(config);
-    this.endpoint = config.endpoint || 'https://api.deepseek.com/v1/chat/completions';
-    this.model = config.model || 'deepseek-chat';
-    this.apiKey = config.apiKey;
-  }
-
-  getName() {
-    return 'Deepseek';
-  }
-
-  getConfigFields() {
-    return [
-      {
-        name: 'apiKey',
-        label: 'API Key',
-        type: 'password',
-        required: true,
-        placeholder: 'sk-...',
-        help: 'Get your API key from https://platform.deepseek.com/api-keys'
-      },
-      {
-        name: 'model',
-        label: 'Model',
-        type: 'select',
-        required: true,
-        default: 'deepseek-chat',
-        options: [
-          { value: 'deepseek-chat', label: 'Deepseek Chat' },
-          { value: 'deepseek-coder', label: 'Deepseek Coder' }
-        ],
-        help: 'Choose the Deepseek model to use'
-      },
-      {
-        name: 'endpoint',
-        label: 'API Endpoint (Advanced)',
-        type: 'text',
-        required: false,
-        default: 'https://api.deepseek.com/v1/chat/completions',
-        placeholder: 'https://api.deepseek.com/v1/chat/completions',
-        help: 'Custom endpoint URL'
-      }
-    ];
-  }
-
-  async chat(message, options = {}) {
-    if (!this.apiKey) {
-      return { success: false, error: 'API key is required' };
-    }
-
-    const messages = [];
-    
-    // Add system prompt
-    const systemPrompt = options.systemPrompt || 'You are a helpful coding assistant.';
-    messages.push({ role: 'system', content: systemPrompt });
-    messages.push({ role: 'user', content: message });
-
-    const body = JSON.stringify({
-      model: this.model,
-      messages: messages,
-      temperature: options.temperature !== undefined ? options.temperature : 0.7,
-      max_tokens: options.maxTokens || 2000
-    });
-
-    return new Promise((resolve) => {
-      const url = new URL(this.endpoint);
-      const requestOptions = {
-        hostname: url.hostname,
-        port: 443,
-        path: url.pathname + url.search,
-        method: 'POST',
-        headers: {
-          'Content-Type': 'application/json',
-          'Authorization': `Bearer ${this.apiKey}`,
-          'Content-Length': Buffer.byteLength(body)
-        },
-        timeout: 60000
-      };
-
-      const req = https.request(requestOptions, (res) => {
-        let data = '';
-        res.on('data', (chunk) => { data += chunk; });
-        res.on('end', () => {
-          try {
-            const parsed = JSON.parse(data);
-            if (parsed.choices && parsed.choices[0] && parsed.choices[0].message) {
-              resolve({ success: true, reply: parsed.choices[0].message.content });
-            } else if (parsed.error) {
-              resolve({ success: false, error: parsed.error.message || 'API error' });
-            } else {
-              resolve({ success: false, error: 'Invalid API response' });
-            }
-          } catch (err) {
-            resolve({ success: false, error: 'Failed to parse API response: ' + err.message });
-          }
-        });
-      });
-
-      req.on('error', (err) => {
-        resolve({ success: false, error: 'API request failed: ' + err.message });
-      });
-
-      req.on('timeout', () => {
-        req.destroy();
-        resolve({ success: false, error: 'API request timed out' });
-      });
-
-      req.write(body);
-      req.end();
-    });
-  }
-}
-
-module.exports = DeepseekProvider;
-
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/main_external_llm_GenericOpenAIProvider.js.html b/docs/main_external_llm_GenericOpenAIProvider.js.html deleted file mode 100644 index ded1fe7..0000000 --- a/docs/main_external_llm_GenericOpenAIProvider.js.html +++ /dev/null @@ -1,205 +0,0 @@ - - - - - JSDoc: Source: main/external_llm/GenericOpenAIProvider.js - - - - - - - - - - -
- -

Source: main/external_llm/GenericOpenAIProvider.js

- - - - - - -
-
-
/**
- * @fileoverview Generic OpenAI-Compatible Provider
- * 
- * A flexible provider for any LLM service that implements the OpenAI chat completions API.
- * This includes services like:
- * - Together AI
- * - Groq
- * - Perplexity
- * - Local deployments (LM Studio, Ollama with OpenAI compatibility)
- * - Azure OpenAI
- * - And many others
- * 
- * @author CTrace GUI Team
- * @version 1.0.0
- */
-
-const https = require('https');
-const http = require('http');
-const BaseProvider = require('./BaseProvider');
-
-/**
- * Generic OpenAI-Compatible Provider
- * @extends BaseProvider
- */
-class GenericOpenAIProvider extends BaseProvider {
-  constructor(config) {
-    super(config);
-    this.endpoint = config.endpoint;
-    this.model = config.model;
-    this.apiKey = config.apiKey;
-    this.name = config.name || 'Custom Provider';
-  }
-
-  getName() {
-    return this.name;
-  }
-
-  getConfigFields() {
-    return [
-      {
-        name: 'name',
-        label: 'Provider Name',
-        type: 'text',
-        required: true,
-        placeholder: 'My Custom LLM',
-        help: 'A friendly name for this provider'
-      },
-      {
-        name: 'endpoint',
-        label: 'API Endpoint',
-        type: 'text',
-        required: true,
-        placeholder: 'https://api.example.com/v1/chat/completions',
-        help: 'Full URL to the chat completions endpoint'
-      },
-      {
-        name: 'apiKey',
-        label: 'API Key',
-        type: 'password',
-        required: false,
-        placeholder: 'Optional API key',
-        help: 'API key if required by the service (leave blank for local/public endpoints)'
-      },
-      {
-        name: 'model',
-        label: 'Model Name',
-        type: 'text',
-        required: true,
-        placeholder: 'gpt-3.5-turbo',
-        help: 'Model identifier (e.g., "mistralai/Mixtral-8x7B-Instruct-v0.1" for Together AI)'
-      }
-    ];
-  }
-
-  async chat(message, options = {}) {
-    if (!this.endpoint) {
-      return { success: false, error: 'API endpoint is required' };
-    }
-
-    if (!this.model) {
-      return { success: false, error: 'Model name is required' };
-    }
-
-    const messages = [];
-    
-    // Add system prompt
-    const systemPrompt = options.systemPrompt || 'You are a helpful coding assistant.';
-    messages.push({ role: 'system', content: systemPrompt });
-    messages.push({ role: 'user', content: message });
-
-    const body = JSON.stringify({
-      model: this.model,
-      messages: messages,
-      temperature: options.temperature !== undefined ? options.temperature : 0.7,
-      max_tokens: options.maxTokens || 2000
-    });
-
-    return new Promise((resolve) => {
-      const url = new URL(this.endpoint);
-      const isHttps = url.protocol === 'https:';
-      const protocol = isHttps ? https : http;
-      
-      const requestOptions = {
-        hostname: url.hostname,
-        port: url.port || (isHttps ? 443 : 80),
-        path: url.pathname + url.search,
-        method: 'POST',
-        headers: {
-          'Content-Type': 'application/json',
-          'Content-Length': Buffer.byteLength(body)
-        },
-        timeout: 60000
-      };
-
-      // Add authorization header if API key is provided
-      if (this.apiKey) {
-        requestOptions.headers['Authorization'] = `Bearer ${this.apiKey}`;
-      }
-
-      const req = protocol.request(requestOptions, (res) => {
-        let data = '';
-        res.on('data', (chunk) => { data += chunk; });
-        res.on('end', () => {
-          try {
-            const parsed = JSON.parse(data);
-            if (parsed.choices && parsed.choices[0] && parsed.choices[0].message) {
-              resolve({ success: true, reply: parsed.choices[0].message.content });
-            } else if (parsed.error) {
-              resolve({ success: false, error: parsed.error.message || 'API error' });
-            } else {
-              resolve({ success: false, error: 'Invalid API response' });
-            }
-          } catch (err) {
-            resolve({ success: false, error: 'Failed to parse API response: ' + err.message });
-          }
-        });
-      });
-
-      req.on('error', (err) => {
-        resolve({ success: false, error: 'API request failed: ' + err.message });
-      });
-
-      req.on('timeout', () => {
-        req.destroy();
-        resolve({ success: false, error: 'API request timed out' });
-      });
-
-      req.write(body);
-      req.end();
-    });
-  }
-}
-
-module.exports = GenericOpenAIProvider;
-
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/main_external_llm_GroqProvider.js.html b/docs/main_external_llm_GroqProvider.js.html deleted file mode 100644 index fdb9b02..0000000 --- a/docs/main_external_llm_GroqProvider.js.html +++ /dev/null @@ -1,174 +0,0 @@ - - - - - JSDoc: Source: main/external_llm/GroqProvider.js - - - - - - - - - - -
- -

Source: main/external_llm/GroqProvider.js

- - - - - - -
-
-
/**
- * @fileoverview Groq API Provider (Example)
- * 
- * This is an example provider showing how easy it is to add support
- * for new LLM services. Groq offers extremely fast inference.
- * 
- * @author CTrace GUI Team
- * @version 1.0.0
- */
-
-const https = require('https');
-const BaseProvider = require('./BaseProvider');
-
-/**
- * Groq API Provider - Ultra-fast LLM inference
- * @extends BaseProvider
- */
-class GroqProvider extends BaseProvider {
-  constructor(config) {
-    super(config);
-    this.endpoint = 'https://api.groq.com/openai/v1/chat/completions';
-    this.model = config.model || 'mixtral-8x7b-32768';
-    this.apiKey = config.apiKey;
-  }
-
-  getName() {
-    return 'Groq (Fast Inference)';
-  }
-
-  getConfigFields() {
-    return [
-      {
-        name: 'apiKey',
-        label: 'API Key',
-        type: 'password',
-        required: true,
-        placeholder: 'gsk_...',
-        help: 'Get your API key from https://console.groq.com/keys'
-      },
-      {
-        name: 'model',
-        label: 'Model',
-        type: 'select',
-        required: true,
-        default: 'mixtral-8x7b-32768',
-        options: [
-          { value: 'mixtral-8x7b-32768', label: 'Mixtral 8x7B (32K context)' },
-          { value: 'llama2-70b-4096', label: 'LLaMA2 70B (4K context)' },
-          { value: 'gemma-7b-it', label: 'Gemma 7B (8K context)' }
-        ],
-        help: 'Choose the Groq model to use'
-      }
-    ];
-  }
-
-  async chat(message, options = {}) {
-    if (!this.apiKey) {
-      return { success: false, error: 'API key is required' };
-    }
-
-    const messages = [];
-    
-    // Add system prompt
-    const systemPrompt = options.systemPrompt || 'You are a helpful coding assistant.';
-    messages.push({ role: 'system', content: systemPrompt });
-    messages.push({ role: 'user', content: message });
-
-    const body = JSON.stringify({
-      model: this.model,
-      messages: messages,
-      temperature: options.temperature !== undefined ? options.temperature : 0.7,
-      max_tokens: options.maxTokens || 2000
-    });
-
-    return new Promise((resolve) => {
-      const requestOptions = {
-        hostname: 'api.groq.com',
-        port: 443,
-        path: '/openai/v1/chat/completions',
-        method: 'POST',
-        headers: {
-          'Content-Type': 'application/json',
-          'Authorization': `Bearer ${this.apiKey}`,
-          'Content-Length': Buffer.byteLength(body)
-        },
-        timeout: 60000
-      };
-
-      const req = https.request(requestOptions, (res) => {
-        let data = '';
-        res.on('data', (chunk) => { data += chunk; });
-        res.on('end', () => {
-          try {
-            const parsed = JSON.parse(data);
-            if (parsed.choices && parsed.choices[0] && parsed.choices[0].message) {
-              resolve({ success: true, reply: parsed.choices[0].message.content });
-            } else if (parsed.error) {
-              resolve({ success: false, error: parsed.error.message || 'API error' });
-            } else {
-              resolve({ success: false, error: 'Invalid API response' });
-            }
-          } catch (err) {
-            resolve({ success: false, error: 'Failed to parse API response: ' + err.message });
-          }
-        });
-      });
-
-      req.on('error', (err) => {
-        resolve({ success: false, error: 'API request failed: ' + err.message });
-      });
-
-      req.on('timeout', () => {
-        req.destroy();
-        resolve({ success: false, error: 'API request timed out' });
-      });
-
-      req.write(body);
-      req.end();
-    });
-  }
-}
-
-module.exports = GroqProvider;
-
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/main_external_llm_OpenAIProvider.js.html b/docs/main_external_llm_OpenAIProvider.js.html deleted file mode 100644 index 393c4fc..0000000 --- a/docs/main_external_llm_OpenAIProvider.js.html +++ /dev/null @@ -1,185 +0,0 @@ - - - - - JSDoc: Source: main/external_llm/OpenAIProvider.js - - - - - - - - - - -
- -

Source: main/external_llm/OpenAIProvider.js

- - - - - - -
-
-
/**
- * @fileoverview OpenAI API Provider (ChatGPT, GPT-4, etc.)
- * 
- * Implements OpenAI's chat completions API for GPT models.
- * 
- * @author CTrace GUI Team
- * @version 1.0.0
- */
-
-const https = require('https');
-const BaseProvider = require('./BaseProvider');
-
-/**
- * OpenAI API Provider
- * @extends BaseProvider
- */
-class OpenAIProvider extends BaseProvider {
-  constructor(config) {
-    super(config);
-    this.endpoint = config.endpoint || 'https://api.openai.com/v1/chat/completions';
-    this.model = config.model || 'gpt-4';
-    this.apiKey = config.apiKey;
-  }
-
-  getName() {
-    return 'OpenAI (ChatGPT)';
-  }
-
-  getConfigFields() {
-    return [
-      {
-        name: 'apiKey',
-        label: 'API Key',
-        type: 'password',
-        required: true,
-        placeholder: 'sk-...',
-        help: 'Get your API key from https://platform.openai.com/api-keys'
-      },
-      {
-        name: 'model',
-        label: 'Model',
-        type: 'select',
-        required: true,
-        default: 'gpt-4',
-        options: [
-          { value: 'gpt-4', label: 'GPT-4' },
-          { value: 'gpt-4-turbo', label: 'GPT-4 Turbo' },
-          { value: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo' },
-          { value: 'gpt-4o', label: 'GPT-4o' },
-          { value: 'gpt-4o-mini', label: 'GPT-4o Mini' }
-        ],
-        help: 'Choose the OpenAI model to use'
-      },
-      {
-        name: 'endpoint',
-        label: 'API Endpoint (Advanced)',
-        type: 'text',
-        required: false,
-        default: 'https://api.openai.com/v1/chat/completions',
-        placeholder: 'https://api.openai.com/v1/chat/completions',
-        help: 'Custom endpoint URL (for proxies or alternative deployments)'
-      }
-    ];
-  }
-
-  async chat(message, options = {}) {
-    if (!this.apiKey) {
-      return { success: false, error: 'API key is required' };
-    }
-
-    const messages = [];
-    
-    // Add system prompt
-    const systemPrompt = options.systemPrompt || 'You are a helpful coding assistant.';
-    messages.push({ role: 'system', content: systemPrompt });
-    messages.push({ role: 'user', content: message });
-
-    const body = JSON.stringify({
-      model: this.model,
-      messages: messages,
-      temperature: options.temperature !== undefined ? options.temperature : 0.7,
-      max_tokens: options.maxTokens || 2000
-    });
-
-    return new Promise((resolve) => {
-      const url = new URL(this.endpoint);
-      const requestOptions = {
-        hostname: url.hostname,
-        port: 443,
-        path: url.pathname + url.search,
-        method: 'POST',
-        headers: {
-          'Content-Type': 'application/json',
-          'Authorization': `Bearer ${this.apiKey}`,
-          'Content-Length': Buffer.byteLength(body)
-        },
-        timeout: 60000
-      };
-
-      const req = https.request(requestOptions, (res) => {
-        let data = '';
-        res.on('data', (chunk) => { data += chunk; });
-        res.on('end', () => {
-          try {
-            const parsed = JSON.parse(data);
-            if (parsed.choices && parsed.choices[0] && parsed.choices[0].message) {
-              resolve({ success: true, reply: parsed.choices[0].message.content });
-            } else if (parsed.error) {
-              resolve({ success: false, error: parsed.error.message || 'API error' });
-            } else {
-              resolve({ success: false, error: 'Invalid API response' });
-            }
-          } catch (err) {
-            resolve({ success: false, error: 'Failed to parse API response: ' + err.message });
-          }
-        });
-      });
-
-      req.on('error', (err) => {
-        resolve({ success: false, error: 'API request failed: ' + err.message });
-      });
-
-      req.on('timeout', () => {
-        req.destroy();
-        resolve({ success: false, error: 'API request timed out' });
-      });
-
-      req.write(body);
-      req.end();
-    });
-  }
-}
-
-module.exports = OpenAIProvider;
-
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/main_external_llm_PerplexityProvider.js.html b/docs/main_external_llm_PerplexityProvider.js.html deleted file mode 100644 index 80f9085..0000000 --- a/docs/main_external_llm_PerplexityProvider.js.html +++ /dev/null @@ -1,176 +0,0 @@ - - - - - JSDoc: Source: main/external_llm/PerplexityProvider.js - - - - - - - - - - -
- -

Source: main/external_llm/PerplexityProvider.js

- - - - - - -
-
-
/**
- * @fileoverview Perplexity API Provider (Example)
- * 
- * Perplexity offers LLMs with real-time internet search capabilities,
- * perfect for getting up-to-date information and current best practices.
- * 
- * @author CTrace GUI Team
- * @version 1.0.0
- */
-
-const https = require('https');
-const BaseProvider = require('./BaseProvider');
-
-/**
- * Perplexity API Provider - Search-augmented responses
- * @extends BaseProvider
- */
-class PerplexityProvider extends BaseProvider {
-  constructor(config) {
-    super(config);
-    this.endpoint = 'https://api.perplexity.ai/chat/completions';
-    this.model = config.model || 'llama-3.1-sonar-small-128k-online';
-    this.apiKey = config.apiKey;
-  }
-
-  getName() {
-    return 'Perplexity (Search-Augmented)';
-  }
-
-  getConfigFields() {
-    return [
-      {
-        name: 'apiKey',
-        label: 'API Key',
-        type: 'password',
-        required: true,
-        placeholder: 'pplx-...',
-        help: 'Get your API key from https://www.perplexity.ai/settings/api'
-      },
-      {
-        name: 'model',
-        label: 'Model',
-        type: 'select',
-        required: true,
-        default: 'llama-3.1-sonar-small-128k-online',
-        options: [
-          { value: 'llama-3.1-sonar-small-128k-online', label: 'Sonar Small (Online, 128K)' },
-          { value: 'llama-3.1-sonar-large-128k-online', label: 'Sonar Large (Online, 128K)' },
-          { value: 'llama-3.1-sonar-huge-128k-online', label: 'Sonar Huge (Online, 128K)' },
-          { value: 'llama-3.1-8b-instruct', label: 'LLaMA 3.1 8B (Offline)' },
-          { value: 'llama-3.1-70b-instruct', label: 'LLaMA 3.1 70B (Offline)' }
-        ],
-        help: 'Online models have internet search, offline models don\'t'
-      }
-    ];
-  }
-
-  async chat(message, options = {}) {
-    if (!this.apiKey) {
-      return { success: false, error: 'API key is required' };
-    }
-
-    const messages = [];
-    
-    // Add system prompt
-    const systemPrompt = options.systemPrompt || 'You are a helpful coding assistant with access to current information.';
-    messages.push({ role: 'system', content: systemPrompt });
-    messages.push({ role: 'user', content: message });
-
-    const body = JSON.stringify({
-      model: this.model,
-      messages: messages,
-      temperature: options.temperature !== undefined ? options.temperature : 0.7,
-      max_tokens: options.maxTokens || 2000
-    });
-
-    return new Promise((resolve) => {
-      const requestOptions = {
-        hostname: 'api.perplexity.ai',
-        port: 443,
-        path: '/chat/completions',
-        method: 'POST',
-        headers: {
-          'Content-Type': 'application/json',
-          'Authorization': `Bearer ${this.apiKey}`,
-          'Content-Length': Buffer.byteLength(body)
-        },
-        timeout: 60000
-      };
-
-      const req = https.request(requestOptions, (res) => {
-        let data = '';
-        res.on('data', (chunk) => { data += chunk; });
-        res.on('end', () => {
-          try {
-            const parsed = JSON.parse(data);
-            if (parsed.choices && parsed.choices[0] && parsed.choices[0].message) {
-              resolve({ success: true, reply: parsed.choices[0].message.content });
-            } else if (parsed.error) {
-              resolve({ success: false, error: parsed.error.message || 'API error' });
-            } else {
-              resolve({ success: false, error: 'Invalid API response' });
-            }
-          } catch (err) {
-            resolve({ success: false, error: 'Failed to parse API response: ' + err.message });
-          }
-        });
-      });
-
-      req.on('error', (err) => {
-        resolve({ success: false, error: 'API request failed: ' + err.message });
-      });
-
-      req.on('timeout', () => {
-        req.destroy();
-        resolve({ success: false, error: 'API request timed out' });
-      });
-
-      req.write(body);
-      req.end();
-    });
-  }
-}
-
-module.exports = PerplexityProvider;
-
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/main_external_llm_ProviderRegistry.js.html b/docs/main_external_llm_ProviderRegistry.js.html deleted file mode 100644 index 45a506c..0000000 --- a/docs/main_external_llm_ProviderRegistry.js.html +++ /dev/null @@ -1,145 +0,0 @@ - - - - - JSDoc: Source: main/external_llm/ProviderRegistry.js - - - - - - - - - - -
- -

Source: main/external_llm/ProviderRegistry.js

- - - - - - -
-
-
/**
- * @fileoverview Provider Registry
- * 
- * Central registry for all available LLM providers.
- * Handles provider registration, instantiation, and discovery.
- * 
- * @author CTrace GUI Team
- * @version 1.0.0
- */
-
-const OpenAIProvider = require('./OpenAIProvider');
-const DeepseekProvider = require('./DeepseekProvider');
-const AnthropicProvider = require('./AnthropicProvider');
-const GenericOpenAIProvider = require('./GenericOpenAIProvider');
-const GroqProvider = require('./GroqProvider');
-const PerplexityProvider = require('./PerplexityProvider');
-
-/**
- * Registry of available LLM providers
- */
-class ProviderRegistry {
-  constructor() {
-    this.providers = new Map();
-    this.registerDefaultProviders();
-  }
-
-  /**
-   * Register default built-in providers
-   */
-  registerDefaultProviders() {
-    this.register('openai', OpenAIProvider);
-    this.register('deepseek', DeepseekProvider);
-    this.register('anthropic', AnthropicProvider);
-    this.register('groq', GroqProvider);
-    this.register('perplexity', PerplexityProvider);
-    this.register('generic', GenericOpenAIProvider);
-  }
-
-  /**
-   * Register a provider class
-   * @param {string} id - Unique provider identifier
-   * @param {Function} ProviderClass - Provider class constructor
-   */
-  register(id, ProviderClass) {
-    this.providers.set(id, ProviderClass);
-  }
-
-  /**
-   * Get all available providers
-   * @returns {Array<Object>} Array of provider info { id, name, fields }
-   */
-  getAllProviders() {
-    const providers = [];
-    for (const [id, ProviderClass] of this.providers.entries()) {
-      try {
-        const instance = new ProviderClass({});
-        providers.push({
-          id: id,
-          name: instance.getName(),
-          fields: instance.getConfigFields()
-        });
-      } catch (err) {
-        console.error(`Error getting info for provider ${id}:`, err);
-      }
-    }
-    return providers;
-  }
-
-  /**
-   * Create a provider instance
-   * @param {string} id - Provider identifier
-   * @param {Object} config - Provider configuration
-   * @returns {BaseProvider} Provider instance
-   */
-  createProvider(id, config) {
-    const ProviderClass = this.providers.get(id);
-    if (!ProviderClass) {
-      throw new Error(`Provider not found: ${id}`);
-    }
-    return new ProviderClass(config);
-  }
-
-  /**
-   * Check if a provider exists
-   * @param {string} id - Provider identifier
-   * @returns {boolean}
-   */
-  hasProvider(id) {
-    return this.providers.has(id);
-  }
-}
-
-// Export singleton instance
-module.exports = new ProviderRegistry();
-
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/main_ipc_assistantHandlers.js.html b/docs/main_ipc_assistantHandlers.js.html deleted file mode 100644 index 77c50b4..0000000 --- a/docs/main_ipc_assistantHandlers.js.html +++ /dev/null @@ -1,403 +0,0 @@ - - - - - JSDoc: Source: main/ipc/assistantHandlers.js - - - - - - - - - - -
- -

Source: main/ipc/assistantHandlers.js

- - - - - - -
-
-
/**
- * @fileoverview IPC handlers for AI assistant (Ollama, External API, Local GGUF)
- * 
- * This module provides IPC handlers for chatting with various LLM providers.
- * Now uses a modular provider system for easy extensibility.
- * 
- * @author CTrace GUI Team
- * @version 1.0.0
- */
-
-const { ipcMain } = require('electron');
-const https = require('https');
-const http = require('http');
-const providerRegistry = require('../external_llm/ProviderRegistry');
-
-// Local GGUF state
-let localLLM = null;
-let loadedModelPath = null;
-let loadedGpuLayers = null;
-
-/**
- * Setup IPC handlers for assistant chat
- * @param {BrowserWindow} mainWindow - Main window reference
- */
-function setupAssistantHandlers(mainWindow) {
-  /**
-   * Handle assistant chat request
-   * Input: { provider, message, config }
-   * config contains: provider-specific configuration
-   */
-  ipcMain.handle('assistant-chat', async (event, { provider, message, config }) => {
-    try {
-      if (provider === 'ollama') {
-        return await handleOllamaChat(message, config);
-      } else if (provider === 'external') {
-        // Use modular provider system for external APIs
-        return await handleModularProvider(message, config);
-      } else if (provider === 'local') {
-        return await handleLocalChat(message, config);
-      } else {
-        return {
-          success: false,
-          error: 'Unknown provider or assistant not configured'
-        };
-      }
-    } catch (error) {
-      console.error('Error in assistant-chat handler:', error);
-      return {
-        success: false,
-        error: error.message || 'Unknown error'
-      };
-    }
-  });
-
-  /**
-   * Get list of available providers
-   */
-  ipcMain.handle('assistant-get-providers', async () => {
-    try {
-      return {
-        success: true,
-        providers: providerRegistry.getAllProviders()
-      };
-    } catch (error) {
-      console.error('Error getting providers:', error);
-      return {
-        success: false,
-        error: error.message
-      };
-    }
-  });
-
-  /**
-   * Test a provider connection
-   */
-  ipcMain.handle('assistant-test-provider', async (event, { providerId, config }) => {
-    try {
-      const provider = providerRegistry.createProvider(providerId, config);
-      return await provider.testConnection();
-    } catch (error) {
-      console.error('Error testing provider:', error);
-      return {
-        success: false,
-        error: error.message
-      };
-    }
-  });
-
-  /**
-   * Unload local model when requested
-   */
-  ipcMain.handle('assistant-unload-local', async () => {
-    try {
-      if (localLLM) {
-        if (localLLM.context) await localLLM.context.dispose();
-        if (localLLM.model) await localLLM.model.dispose();
-        localLLM = null;
-        loadedModelPath = null;
-        loadedGpuLayers = null;
-        return { success: true };
-      }
-      return { success: true };
-    } catch (error) {
-      console.error('Error unloading local model:', error);
-      return { success: false, error: error.message };
-    }
-  });
-}
-
-/**
- * Handle Ollama chat request
- * @param {string} message - User message
- * @param {Object} config - Config with ollamaHost
- * @returns {Promise<Object>}
- */
-async function handleOllamaChat(message, config) {
-  const host = config.ollamaHost || 'http://localhost:11434';
-  const url = new URL('/api/chat', host);
-  
-  const messages = [];
-  
-  // Add system prompt if provided
-  if (config.systemPrompt) {
-    messages.push({ role: 'system', content: config.systemPrompt });
-  }
-  
-  messages.push({ role: 'user', content: message });
-  
-  const body = JSON.stringify({
-    model: 'llama2', // default model, can be made configurable
-    messages: messages,
-    stream: false
-  });
-
-  return new Promise((resolve) => {
-    const protocol = url.protocol === 'https:' ? https : http;
-    const options = {
-      hostname: url.hostname,
-      port: url.port || (url.protocol === 'https:' ? 443 : 80),
-      path: url.pathname,
-      method: 'POST',
-      headers: {
-        'Content-Type': 'application/json',
-        'Content-Length': Buffer.byteLength(body)
-      },
-      timeout: 60000
-    };
-
-    const req = protocol.request(options, (res) => {
-      let data = '';
-      res.on('data', (chunk) => { data += chunk; });
-      res.on('end', () => {
-        try {
-          const parsed = JSON.parse(data);
-          if (parsed.message && parsed.message.content) {
-            resolve({ success: true, reply: parsed.message.content });
-          } else {
-            resolve({ success: false, error: 'Invalid response from Ollama' });
-          }
-        } catch (err) {
-          resolve({ success: false, error: 'Failed to parse Ollama response: ' + err.message });
-        }
-      });
-    });
-
-    req.on('error', (err) => {
-      resolve({ success: false, error: 'Ollama request failed: ' + err.message });
-    });
-
-    req.on('timeout', () => {
-      req.destroy();
-      resolve({ success: false, error: 'Ollama request timed out' });
-    });
-
-    req.write(body);
-    req.end();
-  });
-}
-
-/**
- * Handle external API chat using modular provider system
- * @param {string} message - User message
- * @param {Object} config - Config with providerId and provider-specific settings
- * @returns {Promise<Object>}
- */
-async function handleModularProvider(message, config) {
-  const providerId = config.providerId || 'openai';
-  
-  try {
-    // Create provider instance
-    const provider = providerRegistry.createProvider(providerId, config);
-    
-    // Validate configuration
-    const validation = provider.validateConfig(config);
-    if (!validation.valid) {
-      return {
-        success: false,
-        error: 'Configuration error: ' + validation.errors.join(', ')
-      };
-    }
-    
-    // Send chat message
-    return await provider.chat(message, {
-      systemPrompt: config.systemPrompt,
-      temperature: config.temperature,
-      maxTokens: config.maxTokens
-    });
-  } catch (error) {
-    console.error('Error with modular provider:', error);
-    return {
-      success: false,
-      error: error.message || 'Provider error'
-    };
-  }
-}
-
-/**
- * Handle local GGUF model chat using node-llama-cpp
- * @param {string} message - User message
- * @param {Object} config - Config with localModelPath and gpuLayers
- * @returns {Promise<Object>}
- */
-async function handleLocalChat(message, config) {
-  const modelPath = config.localModelPath;
-
-  if (!modelPath) {
-    return { success: false, error: 'Local model path is required' };
-  }
-
-  try {
-    // Dynamic import of node-llama-cpp (ESM module)
-    const { getLlama, LlamaChatSession } = await import('node-llama-cpp');
-
-    // Get GPU layers setting (default to 0 if not specified)
-    const gpuLayers = config.gpuLayers !== undefined && config.gpuLayers !== null ? config.gpuLayers : 0;
-    
-    // Get context size setting (default to 8192 if not specified)
-    const contextSize = config.contextSize !== undefined && config.contextSize !== null ? config.contextSize : 8192;
-
-    // Load model if not loaded, if path changed, OR if GPU layers setting changed
-    if (!localLLM || loadedModelPath !== modelPath || loadedGpuLayers !== gpuLayers) {
-      console.log('Loading local GGUF model from:', modelPath);
-      
-      // Dispose old instance if any
-      if (localLLM) {
-        console.log('Disposing previous model instance...');
-        try {
-          if (localLLM.context) await localLLM.context.dispose();
-          if (localLLM.model) await localLLM.model.dispose();
-        } catch (disposeErr) {
-          console.warn('Error during disposal:', disposeErr);
-        }
-        localLLM = null;
-      }
-
-      // Initialize llama
-      const llama = await getLlama({
-        // Enable verbose logging to see GPU initialization
-        logLevel: 'debug'
-      });
-      
-      console.log('=== GPU Detection ===');
-      console.log('Attempting to load model with GPU layers:', gpuLayers);
-      
-      if (gpuLayers === -1) {
-        console.log('Mode: Offloading ALL layers to GPU');
-      } else if (gpuLayers === 0) {
-        console.log('Mode: CPU only (no GPU acceleration)');
-      } else {
-        console.log(`Mode: Offloading ${gpuLayers} layers to GPU`);
-      }
-      
-      console.log('Note: Watch for [node-llama-cpp] logs below for GPU/Vulkan device info');
-      console.log('=====================');
-      
-      // Load the model with GPU configuration
-      // The underlying llama.cpp will log GPU information like:
-      // "ggml_vulkan: Using Vulkan1 (NVIDIA GeForce RTX 4070) | vulkan"
-      const model = await llama.loadModel({
-        modelPath: modelPath,
-        gpuLayers: gpuLayers, // 0 = CPU only, -1 = all layers, or specific number
-        // Try to enable verbose output
-        onLoadProgress: (progress) => {
-          console.log(`Loading model: ${(progress * 100).toFixed(1)}%`);
-        }
-      });
-      
-      console.log('✓ Model loaded');
-      console.log('  GPU layers used:', gpuLayers === -1 ? 'All layers' : gpuLayers);
-      console.log('  Model size:', model.size, 'parameters');
-      console.log('  Model default context:', model.trainContextSize, 'tokens');
-      console.log('  Using context size:', contextSize, 'tokens (saves VRAM)');
-
-      // Create context with custom size to reduce VRAM usage
-      const context = await model.createContext({
-        contextSize: contextSize // Use configured context size instead of model default (40960)
-      });
-      
-      // Create chat session
-      const session = new LlamaChatSession({
-        contextSequence: context.getSequence()
-      });
-
-      localLLM = { model, context, session };
-      loadedModelPath = modelPath;
-      loadedGpuLayers = gpuLayers;
-      console.log('✓ Model ready for inference');
-      console.log('=====================');
-    } else {
-      console.log('Using cached model (same path and GPU layers)');
-    }
-
-    // Generate response
-    console.log('Generating response for:', message);
-    
-    // Prepend system prompt to the message if provided
-    let fullMessage = message;
-    if (config.systemPrompt) {
-      fullMessage = `System: ${config.systemPrompt}\n\nUser: ${message}`;
-    }
-    
-    const response = await localLLM.session.prompt(fullMessage);
-    
-    return {
-      success: true,
-      reply: response || '(no response)'
-    };
-  } catch (error) {
-    console.error('Error with local GGUF model:', error);
-    console.error('Error stack:', error.stack);
-    
-    // Clean up on error
-    if (localLLM) {
-      try {
-        await localLLM.context?.dispose();
-        await localLLM.model?.dispose();
-      } catch (disposeError) {
-        console.error('Error disposing model:', disposeError);
-      }
-    }
-    localLLM = null;
-    loadedModelPath = null;
-    loadedGpuLayers = null;
-
-    return {
-      success: false,
-      error: 'Local model error: ' + error.message
-    };
-  }
-}
-
-module.exports = { setupAssistantHandlers };
-
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/main_ipc_ctraceHandlers.js.html b/docs/main_ipc_ctraceHandlers.js.html deleted file mode 100644 index b4c2bd9..0000000 --- a/docs/main_ipc_ctraceHandlers.js.html +++ /dev/null @@ -1,286 +0,0 @@ - - - - - JSDoc: Source: main/ipc/ctraceHandlers.js - - - - - - - - - - -
- -

Source: main/ipc/ctraceHandlers.js

- - - - - - -
-
-
const { ipcMain } = require('electron');
-const { spawn } = require('child_process');
-const path = require('path');
-const fs = require('fs').promises;
-const os = require('os');
-
-/**
- * Check if WSL is available and has distributions installed
- * @returns {Promise<Object>} WSL status object with properties: available (boolean), hasDistros (boolean), error (string)
- */
-async function checkWSLAvailability() {
-  return new Promise((resolve) => {
-    // First check if WSL command exists
-    const statusChild = spawn('wsl', ['--status'], { stdio: 'pipe' });
-    
-    let statusOutput = '';
-    let statusError = '';
-    
-    statusChild.stdout.on('data', (data) => {
-      statusOutput += data.toString();
-    });
-    
-    statusChild.stderr.on('data', (data) => {
-      statusError += data.toString();
-    });
-    
-    statusChild.on('error', () => {
-      resolve({ available: false, hasDistros: false, error: 'WSL is not installed' });
-    });
-    
-    statusChild.on('close', (statusCode) => {
-      if (statusCode !== 0) {
-        resolve({ available: false, hasDistros: false, error: 'WSL is not available' });
-        return;
-      }
-      
-      // WSL exists, now check for installed distributions
-      const listChild = spawn('wsl', ['--list', '--quiet'], { stdio: 'pipe' });
-      
-      let listOutput = '';
-      
-      listChild.stdout.on('data', (data) => {
-        listOutput += data.toString();
-      });
-      
-      listChild.on('error', () => {
-        resolve({ available: true, hasDistros: false, error: 'Cannot check WSL distributions' });
-      });
-      
-      listChild.on('close', (listCode) => {
-        const distributions = listOutput.trim().split('\n').filter(line => line.trim().length > 0);
-        const hasDistros = distributions.length > 0 && !listOutput.includes('no installed distributions');
-        
-        if (!hasDistros) {
-          const errorMsg = statusError.includes('no installed distributions') || listOutput.includes('no installed distributions')
-            ? 'WSL is installed but no Linux distributions are available'
-            : 'No WSL distributions found';
-          resolve({ available: true, hasDistros: false, error: errorMsg });
-        } else {
-          resolve({ available: true, hasDistros: true });
-        }
-      });
-      
-      // Timeout for list command
-      setTimeout(() => {
-        listChild.kill();
-        resolve({ available: true, hasDistros: false, error: 'Timeout checking WSL distributions' });
-      }, 5000);
-    });
-    
-    // Timeout for status command
-    setTimeout(() => {
-      statusChild.kill();
-      resolve({ available: false, hasDistros: false, error: 'Timeout checking WSL status' });
-    }, 5000);
-  });
-}
-
-/**
- * Setup IPC handlers for running the ctrace binary
- */
-function setupCtraceHandlers() {
-  ipcMain.handle('run-ctrace', async (event, args = []) => {
-    // Always use the Linux binary 'ctrace' (no .exe extension)
-    // On Windows, this will be executed through WSL
-    const binaryName = 'ctrace';
-    
-    // Resolve binary in dev and production (packaged) locations
-    let binPath;
-    
-    if (process.resourcesPath) {
-      // In packaged app, binary is in extraResources
-      binPath = path.join(process.resourcesPath, 'bin', binaryName);
-    } else {
-      // In development, binary is in the project bin directory
-      // __dirname is .../src/main/ipc, so project root bin is ../../../bin/ctrace
-      binPath = path.join(__dirname, '../../../bin', binaryName);
-    }
-
-    async function resolveBinary() {
-      try {
-        await fs.access(binPath);
-        return binPath;
-      } catch (error) {
-        console.error(`Binary not found at ${binPath}:`, error.message);
-        return null;
-      }
-    }
-
-    try {
-      const resolvedBinPath = await resolveBinary();
-      if (!resolvedBinPath) {
-        const platform = os.platform();
-        const platformInfo = platform === 'win32' ? ' (Linux binary executed via WSL)' : '';
-        const checkedPath = process.resourcesPath ? 
-          path.join(process.resourcesPath, 'bin', binaryName) : 
-          path.join(__dirname, '../../../bin', binaryName);
-        return { 
-          success: false, 
-          error: `ctrace binary not found at: ${checkedPath}${platformInfo}` 
-        };
-      }
-
-      // On Windows, check if WSL is available before proceeding
-      if (os.platform() === 'win32') {
-        const wslStatus = await checkWSLAvailability();
-        if (!wslStatus.available || !wslStatus.hasDistros) {
-          let errorMessage = 'CTrace requires WSL (Windows Subsystem for Linux) to run on Windows.\n\n';
-          
-          if (!wslStatus.available) {
-            errorMessage += 'WSL is not installed. Please install WSL by running:\n';
-            errorMessage += '• Open PowerShell as Administrator\n';
-            errorMessage += '• Run: wsl --install\n';
-            errorMessage += '• Restart your computer when prompted\n\n';
-          } else if (!wslStatus.hasDistros) {
-            errorMessage += 'WSL is installed but no Linux distributions are available.\n\n';
-            errorMessage += 'To fix this:\n';
-            errorMessage += '• Run: wsl --list --online (to see available distributions)\n';
-            errorMessage += '• Run: wsl --install Ubuntu (or another distribution)\n';
-            errorMessage += '• Follow the setup instructions\n\n';
-          }
-          
-          errorMessage += 'After setup, restart the application to use CTrace.';
-          
-          if (wslStatus.error) {
-            errorMessage += `\n\nDetailed error: ${wslStatus.error}`;
-          }
-          
-          return { 
-            success: false, 
-            error: errorMessage
-          };
-        }
-      }
-
-      return await new Promise((resolve) => {
-        console.log('args', args);
-        
-        let command, commandArgs;
-        
-        // Check if we're on Windows (we always have a Linux binary now)
-        if (os.platform() === 'win32') {
-          // On Windows, use WSL to execute the Linux binary
-          console.log('Windows detected, using WSL to execute ctrace');
-          console.log('Binary path:', resolvedBinPath);
-          
-          // Convert Windows path to WSL path
-          const wslPath = resolvedBinPath.replace(/\\/g, '/').replace(/^([A-Z]):/, (match, drive) => `/mnt/${drive.toLowerCase()}`);
-          command = 'wsl';
-          
-          // Convert arguments with Windows paths to WSL paths
-          const convertedArgs = (Array.isArray(args) ? args : []).map(arg => {
-            // Convert paths in arguments like --input=C:\path\to\file
-            if (typeof arg === 'string' && arg.includes(':\\')) {
-              return arg.replace(/([A-Z]):\\/g, (match, drive) => `/mnt/${drive.toLowerCase()}/`).replace(/\\/g, '/');
-            }
-            return arg;
-          });
-          
-          commandArgs = [wslPath, ...convertedArgs];
-          console.log('WSL command:', command, commandArgs);
-        } else {
-          // On Linux/Mac, use the binary directly
-          command = resolvedBinPath;
-          commandArgs = Array.isArray(args) ? args : [];
-          console.log('Direct execution:', command, commandArgs);
-        }
-        
-        const child = spawn(command, commandArgs, {
-          stdio: ['ignore', 'pipe', 'pipe']
-        });
-
-        let stdout = '';
-        let stderr = '';
-
-        child.stdout.on('data', (data) => {
-          stdout += data.toString();
-        });
-
-        child.stderr.on('data', (data) => {
-          stderr += data.toString();
-        });
-
-        child.on('error', (err) => {
-          let errorMessage = err.message;
-          
-          // Provide more helpful error messages for WSL-related issues
-          if (os.platform() === 'win32' && command === 'wsl') {
-            if (err.code === 'ENOENT') {
-              errorMessage = 'WSL (Windows Subsystem for Linux) is not installed or not available in PATH. Please install WSL to use CTrace.';
-            } else if (err.code === 'EACCES') {
-              errorMessage = 'Permission denied when trying to execute WSL. Please check WSL installation and permissions.';
-            } else {
-              errorMessage = `WSL execution failed: ${err.message}`;
-            }
-          }
-          
-          resolve({ success: false, error: errorMessage });
-        });
-
-        child.on('close', (code) => {
-          if (code === 0) {
-            resolve({ success: true, output: stdout, exitCode: code });
-          } else {
-            resolve({ success: false, error: `ctrace exited with code ${code}`, stderr, output: stdout, exitCode: code });
-          }
-        });
-      });
-    } catch (error) {
-      return { success: false, error: error.message };
-    }
-  });
-}
-
-module.exports = { setupCtraceHandlers };
-
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/main_ipc_editorHandlers.js.html b/docs/main_ipc_editorHandlers.js.html deleted file mode 100644 index 06d8a08..0000000 --- a/docs/main_ipc_editorHandlers.js.html +++ /dev/null @@ -1,86 +0,0 @@ - - - - - JSDoc: Source: main/ipc/editorHandlers.js - - - - - - - - - - -
- -

Source: main/ipc/editorHandlers.js

- - - - - - -
-
-
const { ipcMain } = require('electron');
-const { exec } = require('child_process');
-
-/**
- * Setup IPC handlers for editor operations
- */
-function setupEditorHandlers() {
-  // Open editor listener
-  ipcMain.on('open-editor', () => {
-    console.log("button clicked !");
-    let command;
-
-    switch (process.platform) {
-      case 'win32': // Windows
-        command = 'notepad';
-        break;
-      case 'darwin': // macOS
-        command = 'open -a TextEdit';
-        break;
-      case 'linux': // Linux
-        command = 'x-terminal-emulator -e nano'; // or just 'nano' if terminal already open
-        break;
-      default:
-        console.log('Unsupported OS');
-        return;
-    }
-
-    exec(command, (err) => {
-      if (err) {
-        console.error('Failed to open editor:', err);
-      }
-    });
-  });
-}
-
-module.exports = { setupEditorHandlers };
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/main_ipc_fileHandlers.js.html b/docs/main_ipc_fileHandlers.js.html deleted file mode 100644 index 41bc034..0000000 --- a/docs/main_ipc_fileHandlers.js.html +++ /dev/null @@ -1,467 +0,0 @@ - - - - - JSDoc: Source: main/ipc/fileHandlers.js - - - - - - - - - - -
- -

Source: main/ipc/fileHandlers.js

- - - - - - -
-
-
/**
- * @fileoverview IPC handlers for file operations in the main process.
- * 
- * This module provides all IPC handlers for file system operations including
- * opening files/folders, saving files, reading file content, and managing
- * file system watching for automatic UI updates.
- * 
- * @author CTrace GUI Team
- * @version 1.0.0
- */
-
-const { ipcMain, dialog } = require('electron');
-const fs = require('fs').promises;
-const path = require('path');
-const chokidar = require('chokidar');
-const { detectFileEncoding, buildFileTree, searchInDirectory, FILE_SIZE_LIMIT } = require('../utils/fileUtils');
-
-/**
- * File watcher instance for monitoring workspace changes
- * @type {chokidar.FSWatcher|null}
- * @private
- */
-let fileWatcher = null;
-
-/**
- * Currently watched workspace path
- * @type {string|null}
- * @private
- */
-let currentWatchPath = null;
-
-/**
- * Sets up all IPC handlers for file operations.
- * 
- * This function registers all IPC handlers that the renderer process can invoke
- * for file operations. It handles folder dialogs, file dialogs, saving files,
- * reading files, and file tree operations.
- * 
- * @function setupFileHandlers
- * @param {BrowserWindow} mainWindow - Main window reference for dialogs
- * 
- * @example
- * setupFileHandlers(mainWindow);
- */
-function setupFileHandlers(mainWindow) {
-  // Open folder dialog
-  ipcMain.handle('open-folder-dialog', async () => {
-    const result = await dialog.showOpenDialog(mainWindow, {
-      properties: ['openDirectory']
-    });
-    
-    if (!result.canceled && result.filePaths.length > 0) {
-      const folderPath = result.filePaths[0];
-      try {
-        const fileTree = await buildFileTree(folderPath);
-        
-        // Start watching the workspace for changes
-        startWatchingWorkspace(folderPath, mainWindow);
-        
-        return {
-          success: true,
-          folderPath,
-          fileTree
-        };
-      } catch (error) {
-        return {
-          success: false,
-          error: error.message
-        };
-      }
-    }
-    
-    return { success: false, canceled: true };
-  });
-
-  // Get file tree for refresh
-  ipcMain.handle('get-file-tree', async (event, folderPath) => {
-    try {
-      const fileTree = await buildFileTree(folderPath);
-      return {
-        success: true,
-        fileTree
-      };
-    } catch (error) {
-      return {
-        success: false,
-        error: error.message
-      };
-    }
-  });
-
-  // Open file dialog
-  ipcMain.handle('open-file-dialog', async () => {
-    const result = await dialog.showOpenDialog(mainWindow, {
-      properties: ['openFile'],
-      filters: [
-        { name: 'All Files', extensions: ['*'] },
-        { name: 'Text Files', extensions: ['txt', 'md', 'json', 'js', 'ts', 'html', 'css', 'py', 'cpp', 'c', 'h'] }
-      ]
-    });
-    
-    if (!result.canceled && result.filePaths.length > 0) {
-      const filePath = result.filePaths[0];
-      try {
-        const fileInfo = await detectFileEncoding(filePath);
-        
-        if (!fileInfo.isUTF8) {
-          // File is not UTF-8, return warning info
-          return {
-            success: true,
-            warning: 'encoding',
-            filePath,
-            fileName: path.basename(filePath),
-            message: 'This file appears to contain non-UTF8 characters. Opening it may cause display issues or data corruption.'
-          };
-        }
-        
-        let content;
-        let isPartial = false;
-        
-        if (fileInfo.size > FILE_SIZE_LIMIT) {
-          // File is large, load only first part
-          const partialBuffer = fileInfo.buffer.slice(0, FILE_SIZE_LIMIT);
-          content = partialBuffer.toString('utf8');
-          isPartial = true;
-        } else {
-          // File is small enough, load entirely
-          content = fileInfo.buffer.toString('utf8');
-        }
-        
-        return {
-          success: true,
-          filePath,
-          content,
-          fileName: path.basename(filePath),
-          isPartial,
-          totalSize: fileInfo.size,
-          loadedSize: isPartial ? FILE_SIZE_LIMIT : fileInfo.size
-        };
-      } catch (error) {
-        return {
-          success: false,
-          error: error.message
-        };
-      }
-    }
-    
-    return { success: false, canceled: true };
-  });
-
-  // Select local LLM (GGUF) model file
-  ipcMain.handle('select-llm-file', async () => {
-    const result = await dialog.showOpenDialog(mainWindow, {
-      properties: ['openFile'],
-      filters: [
-        { name: 'GGUF / Model Files', extensions: ['gguf', 'bin', 'pt', 'ggml', 'onnx'] },
-        { name: 'All Files', extensions: ['*'] }
-      ]
-    });
-
-    if (!result.canceled && result.filePaths.length > 0) {
-      return { success: true, filePath: result.filePaths[0] };
-    }
-
-    return { success: false, canceled: true };
-  });
-
-  // Save file
-  ipcMain.handle('save-file', async (event, filePath, content) => {
-    try {
-      await fs.writeFile(filePath, content, 'utf8');
-      return { success: true };
-    } catch (error) {
-      return { success: false, error: error.message };
-    }
-  });
-
-  // Save file as
-  ipcMain.handle('save-file-as', async (event, content) => {
-    const result = await dialog.showSaveDialog(mainWindow, {
-      filters: [
-        { name: 'All Files', extensions: ['*'] },
-        { name: 'Text Files', extensions: ['txt'] },
-        { name: 'JavaScript', extensions: ['js'] },
-        { name: 'TypeScript', extensions: ['ts'] },
-        { name: 'HTML', extensions: ['html'] },
-        { name: 'CSS', extensions: ['css'] }
-      ]
-    });
-    
-    if (!result.canceled) {
-      try {
-        await fs.writeFile(result.filePath, content, 'utf8');
-        return {
-          success: true,
-          filePath: result.filePath,
-          fileName: path.basename(result.filePath)
-        };
-      } catch (error) {
-        return { success: false, error: error.message };
-      }
-    }
-    
-    return { success: false, canceled: true };
-  });
-
-  // Read file content
-  ipcMain.handle('read-file', async (event, filePath) => {
-    try {
-      const fileInfo = await detectFileEncoding(filePath);
-      
-      if (!fileInfo.isUTF8) {
-        // File is not UTF-8, return warning info
-        return {
-          success: true,
-          warning: 'encoding',
-          filePath,
-          fileName: path.basename(filePath),
-          message: 'This file appears to contain non-UTF8 characters. Opening it may cause display issues or data corruption.'
-        };
-      }
-      
-      let content;
-      let isPartial = false;
-      
-      if (fileInfo.size > FILE_SIZE_LIMIT) {
-        // File is large, load only first part
-        const partialBuffer = fileInfo.buffer.slice(0, FILE_SIZE_LIMIT);
-        content = partialBuffer.toString('utf8');
-        isPartial = true;
-      } else {
-        // File is small enough, load entirely
-        content = fileInfo.buffer.toString('utf8');
-      }
-      
-      return {
-        success: true,
-        content,
-        fileName: path.basename(filePath),
-        isPartial,
-        totalSize: fileInfo.size,
-        loadedSize: isPartial ? FILE_SIZE_LIMIT : fileInfo.size
-      };
-    } catch (error) {
-      return { success: false, error: error.message };
-    }
-  });
-
-  // Load complete file (for large files that were partially loaded)
-  ipcMain.handle('load-complete-file', async (event, filePath) => {
-    try {
-      const fileInfo = await detectFileEncoding(filePath);
-      
-      if (!fileInfo.isUTF8) {
-        return {
-          success: false,
-          error: 'File contains non-UTF8 characters and cannot be safely loaded.'
-        };
-      }
-      
-      const content = fileInfo.buffer.toString('utf8');
-      
-      return {
-        success: true,
-        content,
-        fileName: path.basename(filePath),
-        isPartial: false,
-        totalSize: fileInfo.size,
-        loadedSize: fileInfo.size
-      };
-    } catch (error) {
-      return { success: false, error: error.message };
-    }
-  });
-
-  // Force open file (ignore encoding warnings)
-  ipcMain.handle('force-open-file', async (event, filePath) => {
-    try {
-      const fileInfo = await detectFileEncoding(filePath);
-      
-      let content;
-      let isPartial = false;
-      
-      // Try to read as UTF-8, may have some garbled characters
-      if (fileInfo.size > FILE_SIZE_LIMIT) {
-        const partialBuffer = fileInfo.buffer.slice(0, FILE_SIZE_LIMIT);
-        try {
-          content = partialBuffer.toString('utf8');
-        } catch (error) {
-          // If UTF-8 fails, try latin1 as fallback
-          content = partialBuffer.toString('latin1');
-        }
-        isPartial = true;
-      } else {
-        try {
-          content = fileInfo.buffer.toString('utf8');
-        } catch (error) {
-          // If UTF-8 fails, try latin1 as fallback
-          content = fileInfo.buffer.toString('latin1');
-        }
-      }
-      
-      return {
-        success: true,
-        content,
-        fileName: path.basename(filePath),
-        isPartial,
-        totalSize: fileInfo.size,
-        loadedSize: isPartial ? FILE_SIZE_LIMIT : fileInfo.size,
-        encodingWarning: !fileInfo.isUTF8
-      };
-    } catch (error) {
-      return { success: false, error: error.message };
-    }
-  });
-
-  // Search in files
-  ipcMain.handle('search-in-files', async (event, searchTerm, folderPath) => {
-    try {
-      const results = await searchInDirectory(folderPath, searchTerm);
-      return { success: true, results };
-    } catch (error) {
-      return { success: false, error: error.message };
-    }
-  });
-
-  // Handler to force load full file (bypass size limits)
-  ipcMain.handle('force-load-full-file', async (event, filePath) => {
-    try {
-      const buffer = await fs.readFile(filePath);
-      const content = buffer.toString('utf8');
-      
-      return {
-        success: true,
-        content,
-        totalSize: buffer.length,
-        fileName: path.basename(filePath)
-      };
-    } catch (error) {
-      console.error('Error force loading full file:', error);
-      return {
-        success: false,
-        error: error.message
-      };
-    }
-  });
-}
-
-/**
- * Start watching workspace for file changes
- * @param {string} workspacePath - Path to watch
- * @param {BrowserWindow} mainWindow - Main window reference
- */
-function startWatchingWorkspace(workspacePath, mainWindow) {
-  // Stop existing watcher if any
-  stopWatchingWorkspace();
-  
-  currentWatchPath = workspacePath;
-  
-  // Create new watcher
-  fileWatcher = chokidar.watch(workspacePath, {
-    ignoreInitial: true,
-    ignored: [
-      /(^|[\/\\])\../, // ignore hidden files
-      /node_modules/,  // ignore node_modules
-      /My Music/,      // ignore Windows system folders
-      /My Pictures/,
-      /My Videos/,
-      /\$RECYCLE\.BIN/,
-      /System Volume Information/
-    ],
-    depth: 10, // limit recursion depth
-    ignorePermissionErrors: true // ignore permission errors
-  });
-  
-  // Debounce function to avoid too many updates
-  let updateTimeout;
-  const debouncedUpdate = () => {
-    clearTimeout(updateTimeout);
-    updateTimeout = setTimeout(async () => {
-      try {
-        const fileTree = await buildFileTree(workspacePath);
-        mainWindow.webContents.send('workspace-changed', {
-          success: true,
-          fileTree,
-          folderPath: workspacePath
-        });
-      } catch (error) {
-        console.error('Error updating file tree:', error);
-      }
-    }, 300); // 300ms debounce
-  };
-  
-  // Listen for file system events
-  fileWatcher
-    .on('add', debouncedUpdate)
-    .on('unlink', debouncedUpdate)
-    .on('addDir', debouncedUpdate)
-    .on('unlinkDir', debouncedUpdate)
-    .on('error', error => console.error('File watcher error:', error));
-  
-  console.log('Started watching workspace:', workspacePath);
-}
-
-/**
- * Stop watching current workspace
- */
-function stopWatchingWorkspace() {
-  if (fileWatcher) {
-    fileWatcher.close();
-    fileWatcher = null;
-    console.log('Stopped watching workspace:', currentWatchPath);
-  }
-  currentWatchPath = null;
-}
-
-module.exports = { setupFileHandlers };
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/main_utils_fileUtils.js.html b/docs/main_utils_fileUtils.js.html deleted file mode 100644 index 1b973c6..0000000 --- a/docs/main_utils_fileUtils.js.html +++ /dev/null @@ -1,286 +0,0 @@ - - - - - JSDoc: Source: main/utils/fileUtils.js - - - - - - - - - - -
- -

Source: main/utils/fileUtils.js

- - - - - - -
-
-
const fs = require('fs').promises;
-const path = require('path');
-
-// File size limit for initial display (1MB)
-const FILE_SIZE_LIMIT = 1024 * 1024;
-
-/**
- * Check if file is UTF-8 encoded
- * @param {Buffer} buffer - File buffer to check
- * @returns {boolean} - True if file is UTF-8
- */
-function isValidUTF8(buffer) {
-  // If file is empty, consider it UTF-8
-  if (buffer.length === 0) {
-    return true;
-  }
-  
-  // Check for excessive null bytes (binary indicator)
-  let nullCount = 0;
-  const sampleSize = Math.min(buffer.length, 1024); // Check first 1KB
-  
-  for (let i = 0; i < sampleSize; i++) {
-    if (buffer[i] === 0) {
-      nullCount++;
-    }
-  }
-  
-  // If more than 1% null bytes, likely binary
-  if (nullCount / sampleSize > 0.01) {
-    console.log(`Detected binary file: ${nullCount}/${sampleSize} null bytes`);
-    return false;
-  }
-  
-  // Try to convert to UTF-8 and check for replacement characters
-  const text = buffer.toString('utf8');
-  const replacementCount = (text.match(/\uFFFD/g) || []).length;
-  
-  // If more than 1% replacement characters, likely binary/non-UTF8
-  if (replacementCount / text.length > 0.01) {
-    console.log(`Detected non-UTF8: ${replacementCount}/${text.length} replacement chars`);
-    return false;
-  }
-  
-  // Check for font file signatures
-  if (text.includes('FFTM') || text.includes('GDEF') || text.includes('glyf') || 
-      text.includes('cmap') || text.includes('fpgm') || text.includes('gasp') ||
-      text.includes('DSIG') || text.includes('GSUB') || text.includes('GPOS')) {
-    console.log('Detected font file by signature');
-    return false;
-  }
-  
-  // Check for high percentage of non-printable characters
-  let nonPrintableCount = 0;
-  const checkLength = Math.min(text.length, 1000);
-  
-  for (let i = 0; i < checkLength; i++) {
-    const code = text.charCodeAt(i);
-    // Count chars that are not printable ASCII, common whitespace, or extended ASCII
-    if (code < 32 && code !== 9 && code !== 10 && code !== 13) {
-      nonPrintableCount++;
-    }
-  }
-  
-  // If more than 10% non-printable characters, likely binary
-  if (nonPrintableCount / checkLength > 0.1) {
-    console.log(`Detected binary: ${nonPrintableCount}/${checkLength} non-printable chars`);
-    return false;
-  }
-  
-  return true;
-}
-
-/**
- * Detect file encoding
- * @param {string} filePath - Path to the file
- * @returns {Object} - File info with encoding and size data
- */
-async function detectFileEncoding(filePath) {
-  try {
-    const buffer = await fs.readFile(filePath);
-    const isUTF8 = isValidUTF8(buffer);
-    console.log(`File: ${filePath}, Size: ${buffer.length}, IsUTF8: ${isUTF8}`);
-    console.log(`First 100 bytes:`, buffer.slice(0, 100).toString('hex'));
-    return {
-      isUTF8,
-      size: buffer.length,
-      buffer
-    };
-  } catch (error) {
-    throw error;
-  }
-}
-
-/**
- * Build file tree for directory
- * @param {string} dirPath - Directory path
- * @param {number} maxDepth - Maximum depth to traverse
- * @param {number} currentDepth - Current depth (internal use)
- * @returns {Array} - File tree structure
- */
-async function buildFileTree(dirPath, maxDepth = 3, currentDepth = 0) {
-  if (currentDepth > maxDepth) return null;
-  
-  try {
-    const items = await fs.readdir(dirPath);
-    const tree = [];
-    
-    for (const item of items) {
-      // Skip hidden files, common build directories, and Windows system folders
-      if (item.startsWith('.') || 
-          ['node_modules', 'dist', 'build', '.git', 'My Music', 'My Pictures', 'My Videos', '$RECYCLE.BIN', 'System Volume Information'].includes(item)) {
-        continue;
-      }
-      
-      const itemPath = path.join(dirPath, item);
-      
-      try {
-        const stats = await fs.stat(itemPath);
-        
-        if (stats.isDirectory()) {
-          const children = await buildFileTree(itemPath, maxDepth, currentDepth + 1);
-          tree.push({
-            name: item,
-            path: itemPath,
-            type: 'directory',
-            children: children || []
-          });
-        } else {
-          tree.push({
-            name: item,
-            path: itemPath,
-            type: 'file'
-          });
-        }
-      } catch (itemError) {
-        // Skip items that cause permission errors or other access issues
-        if (itemError.code === 'EPERM' || itemError.code === 'EACCES' || itemError.code === 'ENOENT') {
-          console.warn(`Skipping inaccessible item: ${itemPath} (${itemError.code})`);
-          continue;
-        }
-        // Re-throw unexpected errors
-        throw itemError;
-      }
-    }
-    
-    return tree.sort((a, b) => {
-      // Directories first, then files
-      if (a.type === 'directory' && b.type === 'file') return -1;
-      if (a.type === 'file' && b.type === 'directory') return 1;
-      return a.name.localeCompare(b.name);
-    });
-  } catch (error) {
-    // Handle directory-level permission errors
-    if (error.code === 'EPERM' || error.code === 'EACCES') {
-      console.warn(`Permission denied accessing directory: ${dirPath}`);
-      return [];
-    }
-    console.error('Error building file tree:', error);
-    return [];
-  }
-}
-
-/**
- * Search in files within directory
- * @param {string} dirPath - Directory path to search
- * @param {string} searchTerm - Search term
- * @param {number} maxResults - Maximum results to return
- * @returns {Array} - Search results
- */
-async function searchInDirectory(dirPath, searchTerm, maxResults = 100) {
-  const results = [];
-  const searchRegex = new RegExp(searchTerm, 'gi');
-  
-  async function searchRecursively(currentPath, depth = 0) {
-    if (depth > 5 || results.length >= maxResults) return;
-    
-    try {
-      const items = await fs.readdir(currentPath);
-      
-      for (const item of items) {
-        if (results.length >= maxResults) break;
-        
-        // Skip hidden files and common build directories
-        if (item.startsWith('.') || ['node_modules', 'dist', 'build', '.git'].includes(item)) {
-          continue;
-        }
-        
-        const itemPath = path.join(currentPath, item);
-        const stats = await fs.stat(itemPath);
-        
-        if (stats.isDirectory()) {
-          await searchRecursively(itemPath, depth + 1);
-        } else if (stats.isFile()) {
-          // Only search in text files
-          const ext = path.extname(item).toLowerCase();
-          const textExtensions = ['.txt', '.js', '.ts', '.html', '.css', '.json', '.md', '.py', '.cpp', '.c', '.h', '.java', '.php', '.rb', '.go', '.rs'];
-          
-          if (textExtensions.includes(ext) || !ext) {
-            try {
-              const content = await fs.readFile(itemPath, 'utf8');
-              const lines = content.split('\n');
-              
-              lines.forEach((line, lineNumber) => {
-                const matches = line.match(searchRegex);
-                if (matches) {
-                  results.push({
-                    file: itemPath,
-                    fileName: item,
-                    line: lineNumber + 1,
-                    content: line.trim(),
-                    matches: matches.length
-                  });
-                }
-              });
-            } catch (error) {
-              // Skip files that can't be read as text
-            }
-          }
-        }
-      }
-    } catch (error) {
-      console.error('Error searching directory:', error);
-    }
-  }
-  
-  await searchRecursively(dirPath);
-  return results;
-}
-
-module.exports = {
-  detectFileEncoding,
-  buildFileTree,
-  searchInDirectory,
-  isValidUTF8,
-  FILE_SIZE_LIMIT
-};
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/main_utils_wslTest.js.html b/docs/main_utils_wslTest.js.html deleted file mode 100644 index 32fcce8..0000000 --- a/docs/main_utils_wslTest.js.html +++ /dev/null @@ -1,180 +0,0 @@ - - - - - JSDoc: Source: main/utils/wslTest.js - - - - - - - - - - -
- -

Source: main/utils/wslTest.js

- - - - - - -
-
-
// WSL and CTrace testing utility
-const { spawn } = require('child_process');
-const os = require('os');
-
-/**
- * Test WSL availability and CTrace execution
- */
-async function testWSLAndCTrace() {
-  console.log('🧪 Testing WSL and CTrace Setup');
-  console.log('================================');
-  
-  const platform = os.platform();
-  console.log(`Platform: ${platform}`);
-  
-  if (platform !== 'win32') {
-    console.log('✅ Not on Windows, WSL test not needed');
-    return true;
-  }
-  
-  // Test 1: WSL availability
-  console.log('\n1. Testing WSL availability...');
-  const wslAvailable = await testWSL();
-  
-  if (!wslAvailable) {
-    console.log('❌ WSL is not available');
-    return false;
-  }
-  
-  console.log('✅ WSL is available');
-  
-  // Test 2: CTrace binary accessibility via WSL
-  console.log('\n2. Testing CTrace binary via WSL...');
-  const ctraceAvailable = await testCTraceViaWSL();
-  
-  if (!ctraceAvailable) {
-    console.log('❌ CTrace binary is not accessible via WSL');
-    return false;
-  }
-  
-  console.log('✅ CTrace binary is accessible via WSL');
-  
-  // Test 3: WSL path conversion
-  console.log('\n3. Testing WSL path conversion...');
-  testPathConversion();
-  
-  console.log('\n🎉 All tests passed! WSL and CTrace are properly configured.');
-  return true;
-}
-
-function testWSL() {
-  return new Promise((resolve) => {
-    const child = spawn('wsl', ['--status'], { stdio: 'pipe' });
-    
-    child.on('error', (err) => {
-      console.log(`WSL test error: ${err.message}`);
-      resolve(false);
-    });
-    
-    child.on('close', (code) => {
-      console.log(`WSL status exit code: ${code}`);
-      resolve(code === 0);
-    });
-    
-    setTimeout(() => {
-      child.kill();
-      resolve(false);
-    }, 5000);
-  });
-}
-
-function testCTraceViaWSL() {
-  return new Promise((resolve) => {
-    // Test with a simple --help command
-    const child = spawn('wsl', ['/mnt/c/Users/shookapic/Electron-Test/bin/ctrace', '--help'], { 
-      stdio: 'pipe' 
-    });
-    
-    let stdout = '';
-    let stderr = '';
-    
-    child.stdout.on('data', (data) => {
-      stdout += data.toString();
-    });
-    
-    child.stderr.on('data', (data) => {
-      stderr += data.toString();
-    });
-    
-    child.on('error', (err) => {
-      console.log(`CTrace test error: ${err.message}`);
-      resolve(false);
-    });
-    
-    child.on('close', (code) => {
-      console.log(`CTrace --help exit code: ${code}`);
-      if (stdout) console.log(`Stdout: ${stdout.substring(0, 200)}...`);
-      if (stderr) console.log(`Stderr: ${stderr.substring(0, 200)}...`);
-      
-      // Even if exit code is not 0, if we got output, the binary is accessible
-      resolve(code === 0 || stdout.length > 0 || stderr.length > 0);
-    });
-    
-    setTimeout(() => {
-      child.kill();
-      resolve(false);
-    }, 10000);
-  });
-}
-
-function testPathConversion() {
-  const testPaths = [
-    'C:\\Users\\test\\file.c',
-    'C:\\Program Files\\test\\file.cpp',
-    'D:\\Projects\\test\\main.c'
-  ];
-  
-  console.log('Testing Windows to WSL path conversion:');
-  testPaths.forEach(winPath => {
-    const wslPath = winPath.replace(/([A-Z]):\\/g, (match, drive) => `/mnt/${drive.toLowerCase()}/`).replace(/\\/g, '/');
-    console.log(`  ${winPath} → ${wslPath}`);
-  });
-}
-
-// Export for use in development
-module.exports = { testWSLAndCTrace };
-
-// Auto-run when called directly
-if (require.main === module) {
-  testWSLAndCTrace().catch(console.error);
-}
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/overview.html b/docs/overview.html deleted file mode 100644 index ea65e53..0000000 --- a/docs/overview.html +++ /dev/null @@ -1,227 +0,0 @@ - - - - - - CTrace GUI - Documentation Overview - - - -
-

🔧 CTrace GUI Documentation

-

Complete API documentation for the CTrace GUI Electron application

-
- - - -
-

📁 Project Overview

-
-

CTrace GUI is an Electron-based desktop application that provides a modern, VS Code-like interface for running CTrace static analysis on C/C++ code.

- -

🏗️ Architecture

-
    -
  • Main Process: Handles file system operations, IPC communication, and system dialogs
  • -
  • Renderer Process: Manages the UI, editor, and user interactions
  • -
  • Manager Pattern: Modular architecture with specialized managers for different concerns
  • -
-
-
- -
-

🎯 Core Managers

-
-
-

🎛️ UIController

-

Central coordinator for all UI components and managers. Handles global state and manager interconnections.

- View Documentation -
- -
-

📁 FileOperationsManager

-

Manages all file and workspace operations including opening, saving, and file tree management.

- View Documentation -
- -
-

📝 EditorManager

-

Controls the code editor functionality including syntax highlighting, line numbers, and content management.

- View Documentation -
- -
-

📑 TabManager

-

Handles tab operations, creation, switching, and closing. Manages multiple file editing sessions.

- View Documentation -
- -
-

🔍 SearchManager

-

Provides search functionality both within files and across the entire workspace.

- View Documentation -
- -
-

🔔 NotificationManager

-

Manages user notifications, alerts, and feedback messages throughout the application.

- View Documentation -
-
-
- -
-

⚙️ Main Process Modules

-
-
-

🗂️ File Handlers

-

IPC handlers for file system operations, dialogs, and file watching.

- View Documentation -
- -
-

✏️ Editor Handlers

-

IPC handlers for editor-related operations and functionality.

- View Documentation -
- -
-

🔧 CTrace Handlers

-

IPC handlers for running CTrace analysis and managing binary execution.

- View Documentation -
- -
-

🛠️ File Utils

-

Utility functions for file operations, encoding detection, and file tree building.

- View Documentation -
-
-
- -
-

🚀 Getting Started

-
-

📋 Prerequisites

-
    -
  • Node.js (v18+)
  • -
  • npm
  • -
  • Electron
  • -
  • CTrace binary
  • -
- -

⚡ Quick Commands

-
    -
  • npm install - Install dependencies
  • -
  • npm start - Run the application
  • -
  • npm run dist - Build for distribution
  • -
  • npm run docs - Generate documentation
  • -
-
-
- -
-

🎨 Key Features

-
-
    -
  • 📁 File Management: Open individual files or entire workspaces
  • -
  • 🌳 File Tree Explorer: Navigate project structure with refresh and auto-watch
  • -
  • 💻 Code Editor: Syntax-highlighted editor with line numbers
  • -
  • 📑 Tab Management: Multi-file editing with tab interface
  • -
  • 🔧 CTrace Integration: Run static analysis directly from GUI
  • -
  • 🔍 Global Search: Search across workspace files
  • -
  • 🔔 Notifications: User-friendly notification system
  • -
  • ⚡ File Watching: Automatic file tree updates on changes
  • -
-
-
- -
-

Generated with JSDoc | CTrace GUI v1.0.0

-
- - \ No newline at end of file diff --git a/docs/renderer_UIController.js.html b/docs/renderer_UIController.js.html deleted file mode 100644 index 56aefb0..0000000 --- a/docs/renderer_UIController.js.html +++ /dev/null @@ -1,2065 +0,0 @@ - - - - - JSDoc: Source: renderer/UIController.js - - - - - - - - - - -
- -

Source: renderer/UIController.js

- - - - - - -
-
-
// Import manager classes
-const NotificationManager = require('./managers/NotificationManager');
-const EditorManager = require('./managers/EditorManager');
-const TabManager = require('./managers/TabManager');
-const SearchManager = require('./managers/SearchManager');
-const FileOperationsManager = require('./managers/FileOperationsManager');
-
-// Import utilities
-const fileTypeUtils = require('./utils/fileTypeUtils');
-
-/**
- * Main UI Controller - Coordinates all managers and components
- * 
- * This is the central coordinator for the entire application UI. It manages
- * the interaction between different managers and handles global UI state.
- * 
- * @class UIController
- * @author CTrace GUI Team
- * @version 1.0.0
- * 
- * @example
- * // UIController is automatically instantiated in the HTML
- * const uiController = new UIController();
- */
-class UIController {
-  /**
-   * Creates an instance of UIController and initializes all managers.
-   * 
-   * @constructor
-   * @memberof UIController
-   */
-  constructor() {
-    /**
-     * Notification manager instance
-     * @type {NotificationManager}
-     * @private
-     */
-    this.notificationManager = new NotificationManager();
-    
-    /**
-     * Editor manager instance
-     * @type {EditorManager}
-     * @private
-     */
-    this.editorManager = new EditorManager();
-    
-    /**
-     * Tab manager instance
-     * @type {TabManager}
-     * @private
-     */
-    this.tabManager = new TabManager(this.editorManager, this.notificationManager);
-    
-    /**
-     * Search manager instance
-     * @type {SearchManager}
-     * @private
-     */
-    this.searchManager = new SearchManager(this.editorManager, this.notificationManager);
-    
-    /**
-     * File operations manager instance
-     * @type {FileOperationsManager}
-     * @private
-     */
-    this.fileOpsManager = new FileOperationsManager(this.tabManager, this.notificationManager);
-
-    /**
-     * Flag indicating if UI is being resized
-     * @type {boolean}
-     * @private
-     */
-    this.isResizing = false;
-    
-    /**
-     * Type of resize operation (sidebar, toolsPanel)
-     * @type {string|null}
-     * @private
-     */
-    this.resizeType = null;
-    
-    /**
-     * Currently active menu
-     * @type {string|null}
-     * @private
-     */
-    this.activeMenu = null;
-
-    /**
-     * WSL availability status
-     * @type {boolean}
-     * @private
-     */
-    this.wslAvailable = true;
-
-    /**
-     * Current platform
-     * @type {string}
-     * @private
-     */
-    this.platform = 'unknown';
-
-    this.init();
-  }
-
-  /**
-   * Initializes the UI Controller and sets up all necessary components.
-   * 
-   * This method is called automatically by the constructor and sets up:
-   * - Event listeners for UI interactions
-   * - Keyboard shortcuts
-   * - Resizing functionality
-   * - Menu systems
-   * - UI components
-   * - Manager interconnections
-   * - File tree watcher
-   * 
-   * @memberof UIController
-   * @private
-   */
-  init() {
-    this.setupEventListeners();
-    this.setupKeyboardShortcuts();
-    this.setupResizing();
-    this.setupMenus();
-    this.setupUIComponents();
-
-    // Connect managers
-    this.connectManagers();
-
-    // Initialize with explorer view and welcome screen
-    this.showExplorer();
-    this.tabManager.showWelcomeScreen();
-
-    // Add refresh button event listener
-    const refreshBtn = document.getElementById('refresh-file-tree');
-    if (refreshBtn) {
-      refreshBtn.addEventListener('click', () => {
-        this.refreshFileTree();
-      });
-    }
-
-    // Set up file system watcher for auto-refresh
-    this.setupFileTreeWatcher();
-    
-    // Set up custom title bar controls
-    this.setupTitleBarControls();
-    
-    // Set up WSL status listener
-    this.setupWSLStatusListener();
-  }
-  /**
-   * Set up file system watcher to auto-refresh file tree
-   */
-  setupFileTreeWatcher() {
-    const workspacePath = this.fileOpsManager.getCurrentWorkspacePath();
-    if (!workspacePath) return;
-    // Listen for file system change events from main process
-    window.ipcRenderer.on('workspace-changed', (event, changedPath) => {
-      // Only refresh if the change is in the current workspace
-      if (changedPath && changedPath.startsWith(workspacePath)) {
-        this.refreshFileTree();
-      }
-    });
-    // Request main process to start watching
-    window.ipcRenderer.invoke('watch-workspace', workspacePath);
-  }
-  /**
-   * Refreshes the file tree in the explorer view.
-   * 
-   * This method manually triggers a refresh of the file tree to show any
-   * new files or folders that may have been added to the workspace. It
-   * communicates with the main process to get an updated file tree structure.
-   * 
-   * @async
-   * @memberof UIController
-   * @throws {Error} When file tree refresh fails
-   * 
-   * @example
-   * // Refresh is typically triggered by the refresh button
-   * await uiController.refreshFileTree();
-   */
-  async refreshFileTree() {
-    // Only refresh if workspace is open
-    const workspacePath = this.fileOpsManager.getCurrentWorkspacePath();
-    if (!workspacePath) {
-      this.notificationManager.showWarning('No workspace open to refresh');
-      return;
-    }
-    // Request updated file tree from main process
-    try {
-      const result = await window.ipcRenderer.invoke('get-file-tree', workspacePath);
-      if (result.success) {
-        const folderName = workspacePath.split(/[/\\]/).pop();
-        this.fileOpsManager.updateWorkspaceUI(folderName, result.fileTree);
-        this.notificationManager.showSuccess('File tree refreshed');
-      } else {
-        this.notificationManager.showError('Failed to refresh file tree: ' + (result.error || 'Unknown error'));
-      }
-    } catch (error) {
-      this.notificationManager.showError('Error refreshing file tree: ' + error.message);
-    }
-  }
-
-  /**
-   * Setup file tree watcher to listen for automatic updates
-   */
-  setupFileTreeWatcher() {
-    // Listen for workspace changes from file watcher in main process
-    window.ipcRenderer.on('workspace-changed', (event, data) => {
-      if (data.success) {
-        const folderName = data.folderPath.split(/[/\\]/).pop();
-        this.fileOpsManager.updateWorkspaceUI(folderName, data.fileTree);
-        console.log('File tree auto-refreshed due to file system changes');
-      } else {
-        console.error('Error in workspace change notification:', data.error);
-      }
-    });
-  }
-
-  /**
-   * Setup WSL status listener to handle WSL availability updates
-   */
-  setupWSLStatusListener() {
-    // Listen for WSL status updates from main process
-    window.ipcRenderer.on('wsl-status', (event, data) => {
-      this.wslAvailable = data.available && data.hasDistros;
-      
-      if (this.platform === 'win32') {
-        // Update WSL status indicator in UI
-        this.updateWSLStatusIndicator(data);
-        
-        if (!data.available) {
-          this.notificationManager.showWarning(
-            'WSL is not installed. CTrace requires WSL on Windows. Please install WSL to access all functionality.'
-          );
-          console.warn('WSL not detected on Windows platform');
-        } else if (!data.hasDistros) {
-          this.notificationManager.showWarning(
-            'WSL is installed but no Linux distributions are available. Please install a distribution (e.g., Ubuntu) to use CTrace.'
-          );
-          console.warn('WSL detected but no distributions installed');
-        } else {
-          console.log('WSL is available and ready with distributions');
-        }
-      }
-    });
-
-    // Listen for WSL installation dialog responses
-    window.ipcRenderer.on('wsl-install-response', (event, data) => {
-      if (data.action === 'install') {
-        this.notificationManager.showInfo(
-          'WSL installation initiated. Please follow the installation prompts and restart the application when complete.'
-        );
-      } else if (data.action === 'cancel') {
-        this.notificationManager.showWarning(
-          'WSL installation cancelled. Some features may be limited without WSL.'
-        );
-      }
-    });
-
-    // Request initial WSL status check
-    window.ipcRenderer.send('check-wsl-status');
-  }
-
-  /**
-   * Update WSL status indicator in the UI
-   * @param {Object} wslStatus - WSL status object with available, hasDistros, and error properties
-   */
-  updateWSLStatusIndicator(wslStatus) {
-    // Find or create WSL status indicator
-    let statusEl = document.getElementById('wsl-status-indicator');
-    if (!statusEl) {
-      statusEl = document.createElement('div');
-      statusEl.id = 'wsl-status-indicator';
-      statusEl.style.cssText = `
-        position: fixed;
-        bottom: 20px;
-        right: 20px;
-        padding: 8px 12px;
-        border-radius: 6px;
-        font-size: 12px;
-        font-weight: bold;
-        color: white;
-        z-index: 1000;
-        cursor: pointer;
-        transition: all 0.3s ease;
-      `;
-      document.body.appendChild(statusEl);
-    }
-
-    // Update status based on WSL state
-    if (!wslStatus.available) {
-      statusEl.textContent = '❌ WSL Not Installed';
-      statusEl.style.backgroundColor = '#ff4757';
-      statusEl.title = 'WSL is not installed. Click for installation instructions.';
-    } else if (!wslStatus.hasDistros) {
-      statusEl.textContent = '⚠️ WSL No Distributions';
-      statusEl.style.backgroundColor = '#ffa502';
-      statusEl.title = 'WSL is installed but no Linux distributions are available. Click for setup instructions.';
-    } else {
-      statusEl.textContent = '✅ WSL Ready';
-      statusEl.style.backgroundColor = '#2ed573';
-      statusEl.title = 'WSL is ready and available for CTrace';
-      
-      // Auto-hide the indicator after 3 seconds if everything is working
-      setTimeout(() => {
-        if (statusEl && statusEl.textContent.includes('✅')) {
-          statusEl.style.opacity = '0.3';
-        }
-      }, 3000);
-    }
-
-    // Add click handler for help
-    statusEl.onclick = () => {
-      if (!wslStatus.available || !wslStatus.hasDistros) {
-        this.showWSLSetupDialog(wslStatus);
-      }
-    };
-  }
-
-  /**
-   * Show WSL setup dialog with detailed instructions
-   * @param {Object} wslStatus - Current WSL status
-   */
-  showWSLSetupDialog(wslStatus) {
-    const modal = document.createElement('div');
-    modal.style.cssText = `
-      position: fixed;
-      top: 0;
-      left: 0;
-      width: 100%;
-      height: 100%;
-      background: rgba(0, 0, 0, 0.7);
-      display: flex;
-      justify-content: center;
-      align-items: center;
-      z-index: 10000;
-    `;
-
-    const dialog = document.createElement('div');
-    dialog.style.cssText = `
-      background: white;
-      padding: 30px;
-      border-radius: 10px;
-      max-width: 600px;
-      max-height: 80vh;
-      overflow-y: auto;
-      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
-    `;
-
-    let instructions = '';
-    if (!wslStatus.available) {
-      instructions = `
-        <h3>🔧 Install WSL (Windows Subsystem for Linux)</h3>
-        <p>CTrace requires WSL to run on Windows. Follow these steps:</p>
-        <ol>
-          <li><strong>Open PowerShell as Administrator</strong>
-            <br><small>Right-click Start button → "Windows PowerShell (Admin)"</small>
-          </li>
-          <li><strong>Run the installation command:</strong>
-            <br><code style="background: #f0f0f0; padding: 4px 8px; border-radius: 3px; font-family: monospace;">wsl --install</code>
-          </li>
-          <li><strong>Restart your computer</strong> when prompted</li>
-          <li><strong>Follow the Ubuntu setup</strong> (create username/password)</li>
-          <li><strong>Restart this application</strong> to use CTrace</li>
-        </ol>
-      `;
-    } else {
-      instructions = `
-        <h3>📦 Install a Linux Distribution</h3>
-        <p>WSL is installed but you need a Linux distribution to run CTrace:</p>
-        <ol>
-          <li><strong>Open PowerShell</strong> (no need for Admin)</li>
-          <li><strong>List available distributions:</strong>
-            <br><code style="background: #f0f0f0; padding: 4px 8px; border-radius: 3px; font-family: monospace;">wsl --list --online</code>
-          </li>
-          <li><strong>Install Ubuntu (recommended):</strong>
-            <br><code style="background: #f0f0f0; padding: 4px 8px; border-radius: 3px; font-family: monospace;">wsl --install Ubuntu</code>
-          </li>
-          <li><strong>Follow the setup instructions</strong> (create username/password)</li>
-          <li><strong>Restart this application</strong> to use CTrace</li>
-        </ol>
-      `;
-    }
-
-    dialog.innerHTML = `
-      ${instructions}
-      <div style="margin-top: 20px; text-align: right;">
-        ${!wslStatus.available ? `
-          <button id="auto-install-wsl" style="
-            padding: 10px 20px;
-            background: #28a745;
-            color: white;
-            border: none;
-            border-radius: 5px;
-            cursor: pointer;
-            font-size: 14px;
-            margin-right: 10px;
-          ">Install Automatically</button>
-        ` : wslStatus.available && !wslStatus.hasDistros ? `
-          <button id="install-ubuntu" style="
-            padding: 10px 20px;
-            background: #28a745;
-            color: white;
-            border: none;
-            border-radius: 5px;
-            cursor: pointer;
-            font-size: 14px;
-            margin-right: 10px;
-          ">Install Ubuntu</button>
-        ` : ''}
-        <button id="close-wsl-dialog" style="
-          padding: 10px 20px;
-          background: #007acc;
-          color: white;
-          border: none;
-          border-radius: 5px;
-          cursor: pointer;
-          font-size: 14px;
-        ">Got it!</button>
-      </div>
-    `;
-
-    modal.appendChild(dialog);
-    document.body.appendChild(modal);
-
-    // Close dialog handlers
-    const closeDialog = () => {
-      document.body.removeChild(modal);
-    };
-
-    document.getElementById('close-wsl-dialog').onclick = closeDialog;
-    modal.onclick = (e) => {
-      if (e.target === modal) closeDialog();
-    };
-
-    // Installation button handlers
-    const autoInstallBtn = document.getElementById('auto-install-wsl');
-    if (autoInstallBtn) {
-      autoInstallBtn.onclick = () => {
-        window.ipcRenderer.send('install-wsl');
-        closeDialog();
-        this.notificationManager.showInfo('WSL installation started. Please follow any prompts that appear.');
-      };
-    }
-
-    const installUbuntuBtn = document.getElementById('install-ubuntu');
-    if (installUbuntuBtn) {
-      installUbuntuBtn.onclick = () => {
-        window.ipcRenderer.send('install-wsl-distro', 'Ubuntu');
-        closeDialog();
-        this.notificationManager.showInfo('Ubuntu installation started. Please follow the setup instructions.');
-      };
-    }
-  }
-
-  /**
-   * Setup custom title bar controls for frameless window.
-   * 
-   * This method handles the custom window controls (minimize, maximize, close)
-   * and window state management for the frameless window.
-   * 
-   * @memberof UIController
-   * @private
-   */
-  setupTitleBarControls() {
-    const { remote } = require('electron');
-    const currentWindow = remote ? remote.getCurrentWindow() : require('electron').remote?.getCurrentWindow();
-    
-    // If remote is not available, use IPC
-    if (!currentWindow) {
-      // Setup IPC-based window controls
-      const minimizeBtn = document.getElementById('minimize-btn');
-      const maximizeBtn = document.getElementById('maximize-btn');
-      const closeBtn = document.getElementById('close-btn');
-      
-      if (minimizeBtn) {
-        minimizeBtn.addEventListener('click', () => {
-          window.ipcRenderer.send('window-minimize');
-        });
-      }
-      
-      if (maximizeBtn) {
-        maximizeBtn.addEventListener('click', () => {
-          window.ipcRenderer.send('window-maximize-toggle');
-        });
-      }
-      
-      if (closeBtn) {
-        closeBtn.addEventListener('click', () => {
-          window.ipcRenderer.send('window-close');
-        });
-      }
-      
-      // Listen for window state changes
-      window.ipcRenderer.on('window-maximized', (event, isMaximized) => {
-        document.body.classList.toggle('window-maximized', isMaximized);
-      });
-      
-      return;
-    }
-    
-    // Direct window control (if remote is available)
-    const minimizeBtn = document.getElementById('minimize-btn');
-    const maximizeBtn = document.getElementById('maximize-btn');
-    const closeBtn = document.getElementById('close-btn');
-    
-    if (minimizeBtn) {
-      minimizeBtn.addEventListener('click', () => {
-        currentWindow.minimize();
-      });
-    }
-    
-    if (maximizeBtn) {
-      maximizeBtn.addEventListener('click', () => {
-        if (currentWindow.isMaximized()) {
-          currentWindow.unmaximize();
-        } else {
-          currentWindow.maximize();
-        }
-      });
-    }
-    
-    if (closeBtn) {
-      closeBtn.addEventListener('click', () => {
-        currentWindow.close();
-      });
-    }
-    
-    // Update maximize button icon based on window state
-    const updateMaximizeButton = () => {
-      document.body.classList.toggle('window-maximized', currentWindow.isMaximized());
-    };
-    
-    currentWindow.on('maximize', updateMaximizeButton);
-    currentWindow.on('unmaximize', updateMaximizeButton);
-    
-    // Initial state
-    updateMaximizeButton();
-  }
-
-  /**
-   * Connect managers and set up inter-manager communication
-   */
-  connectManagers() {
-    // Set up tab manager callbacks
-    this.tabManager.onLoadFullFile = (filePath) => {
-      this.fileOpsManager.loadFullFile(filePath);
-    };
-
-    // Set up search manager callbacks
-    this.searchManager.openSearchResult = async (filePath, lineNumber) => {
-      await this.openSearchResult(filePath, lineNumber);
-    };
-
-    // Update search manager with workspace path when workspace changes
-    this.searchManager.setWorkspacePath(this.fileOpsManager.getCurrentWorkspacePath());
-
-    // Set up editor content change tracking
-    this.editorManager.editor.addEventListener('input', () => {
-      if (this.tabManager.activeTabId) {
-        const newContent = this.editorManager.getContent();
-        this.tabManager.handleContentChange(this.tabManager.activeTabId, newContent);
-      }
-    });
-  }
-
-  /**
-   * Setup event listeners for UI components
-   */
-  setupEventListeners() {
-    // Close dialogs when clicking outside
-    document.addEventListener('click', (e) => {
-      const searchWidget = document.getElementById('search-widget');
-      const gotoDialog = document.getElementById('goto-dialog');
-      
-      if (searchWidget.classList.contains('visible') && 
-          !searchWidget.contains(e.target)) {
-        this.searchManager.closeSearchWidget();
-      }
-      
-      if (gotoDialog.classList.contains('visible') && 
-          !gotoDialog.contains(e.target)) {
-        this.searchManager.closeGoToLineDialog();
-      }
-    });
-
-    // Close menus when clicking outside
-    document.addEventListener('click', (e) => {
-      if (!e.target.closest('.menu-item')) {
-        this.hideAllMenus();
-      }
-    });
-  }
-
-  /**
-   * Setup keyboard shortcuts
-   */
-  setupKeyboardShortcuts() {
-    document.addEventListener('keydown', (e) => {
-      const searchWidget = document.getElementById('search-widget');
-      const gotoDialog = document.getElementById('goto-dialog');
-      const isSearchVisible = searchWidget.classList.contains('visible');
-      const isGotoVisible = gotoDialog.classList.contains('visible');
-
-      // Handle Enter key
-      if (e.key === 'Enter') {
-        if (isSearchVisible) {
-          e.preventDefault();
-          this.searchManager.searchNext();
-        } else if (isGotoVisible) {
-          e.preventDefault();
-          this.searchManager.performGoToLine();
-        }
-      }
-      
-      // Handle Escape key
-      if (e.key === 'Escape') {
-        if (isSearchVisible) {
-          e.preventDefault();
-          this.searchManager.closeSearchWidget();
-        } else if (isGotoVisible) {
-          e.preventDefault();
-          this.searchManager.closeGoToLineDialog();
-        }
-      }
-
-      // Handle F3/Shift+F3 for search navigation
-      if (e.key === 'F3' && isSearchVisible) {
-        e.preventDefault();
-        if (e.shiftKey) {
-          this.searchManager.searchPrev();
-        } else {
-          this.searchManager.searchNext();
-        }
-      }
-
-      // File operations
-      if (e.ctrlKey && e.key === 's') {
-        e.preventDefault();
-        this.fileOpsManager.saveFile();
-      }
-      
-      if (e.ctrlKey && e.key === 'o') {
-        e.preventDefault();
-        this.fileOpsManager.openFile();
-      }
-      
-      if (e.ctrlKey && e.shiftKey && e.key === 'O') {
-        e.preventDefault();
-        this.fileOpsManager.openWorkspace();
-      }
-      
-      if (e.ctrlKey && e.key === 'n') {
-        e.preventDefault();
-        this.tabManager.createNewFile();
-      }
-      
-      if (e.ctrlKey && e.shiftKey && e.key === 'S') {
-        e.preventDefault();
-        this.fileOpsManager.saveAsFile();
-      }
-      
-      // UI navigation
-      if (e.ctrlKey && e.key === 'b') {
-        e.preventDefault();
-        this.toggleSidebar();
-      }
-      
-      if (e.altKey && e.key === 'z') {
-        e.preventDefault();
-        this.editorManager.toggleWordWrap();
-      }
-      
-      if (e.shiftKey && e.altKey && e.key === 'F') {
-        e.preventDefault();
-        const formatted = this.editorManager.formatCode();
-        if (this.tabManager.activeTabId) {
-          this.tabManager.handleContentChange(this.tabManager.activeTabId, formatted);
-        }
-      }
-      
-      if (e.ctrlKey && e.key === 'w') {
-        e.preventDefault();
-        if (this.tabManager.activeTabId) {
-          this.tabManager.closeTab(e, this.tabManager.activeTabId);
-        }
-      }
-      
-      if (e.ctrlKey && e.key === 'f') {
-        e.preventDefault();
-        this.searchManager.showFindDialog();
-      }
-      
-      if (e.ctrlKey && e.key === 'g') {
-        e.preventDefault();
-        this.searchManager.showGoToLineDialog();
-      }
-      
-      if (e.ctrlKey && e.key === 'Tab') {
-        e.preventDefault();
-        this.tabManager.switchToNextTab();
-      }
-      
-      if (e.ctrlKey && e.key === '`') {
-        e.preventDefault();
-        this.toggleToolsPanel();
-      }
-      
-      if (e.ctrlKey && e.shiftKey && e.key === 'F') {
-        e.preventDefault();
-        this.showSearch();
-      }
-      
-      if (e.ctrlKey && e.shiftKey && e.key === 'E') {
-        e.preventDefault();
-        this.showExplorer();
-      }
-    });
-  }
-
-  /**
-   * Setup resizing functionality
-   */
-  setupResizing() {
-    const sidebar = document.getElementById('sidebar');
-    const toolsPanel = document.getElementById('toolsPanel');
-
-    const startResize = (e, type) => {
-      this.isResizing = true;
-      this.resizeType = type;
-      
-      if (type === 'sidebar') {
-        sidebar.style.transition = 'none';
-      } else if (type === 'toolsPanel') {
-        toolsPanel.style.transition = 'none';
-      }
-      
-      document.addEventListener('mousemove', this.doResize.bind(this));
-      document.addEventListener('mouseup', this.stopResize.bind(this));
-      e.preventDefault();
-      
-      document.body.style.userSelect = 'none';
-    };
-
-    window.initSidebarResize = (e) => startResize(e, 'sidebar');
-    window.initToolsPanelResize = (e) => startResize(e, 'toolsPanel');
-  }
-
-  doResize(e) {
-    if (!this.isResizing) return;
-    
-    const sidebar = document.getElementById('sidebar');
-    const toolsPanel = document.getElementById('toolsPanel');
-    
-    requestAnimationFrame(() => {
-      if (this.resizeType === 'sidebar') {
-        const containerRect = sidebar.parentElement.getBoundingClientRect();
-        const newWidth = e.clientX - containerRect.left;
-        const minWidth = 180;
-        const maxWidth = window.innerWidth * 0.5;
-        
-        if (newWidth >= minWidth && newWidth <= maxWidth) {
-          sidebar.style.width = newWidth + 'px';
-        }
-      } else if (this.resizeType === 'toolsPanel') {
-        const containerRect = toolsPanel.parentElement.getBoundingClientRect();
-        const newWidth = containerRect.right - e.clientX;
-        const minWidth = 200;
-        const maxWidth = window.innerWidth * 0.6;
-        
-        if (newWidth >= minWidth && newWidth <= maxWidth) {
-          toolsPanel.style.width = newWidth + 'px';
-        }
-      }
-    });
-  }
-
-  stopResize() {
-    this.isResizing = false;
-    
-    const sidebar = document.getElementById('sidebar');
-    const toolsPanel = document.getElementById('toolsPanel');
-    
-    if (this.resizeType === 'sidebar') {
-      sidebar.style.transition = '';
-    } else if (this.resizeType === 'toolsPanel') {
-      toolsPanel.style.transition = '';
-    }
-    
-    document.body.style.userSelect = '';
-    
-    document.removeEventListener('mousemove', this.doResize.bind(this));
-    document.removeEventListener('mouseup', this.stopResize.bind(this));
-    
-    this.resizeType = null;
-  }
-
-  /**
-   * Setup menu functionality
-   */
-  setupMenus() {
-    window.toggleMenu = (menuId) => {
-      const menu = document.getElementById(menuId);
-      const dropdown = menu.querySelector('.dropdown-menu');
-      
-      if (this.activeMenu && this.activeMenu !== menuId) {
-        this.hideAllMenus();
-      }
-      
-      if (dropdown.classList.contains('show')) {
-        this.hideAllMenus();
-      } else {
-        dropdown.classList.add('show');
-        menu.classList.add('active');
-        this.activeMenu = menuId;
-      }
-    };
-
-    window.hideAllMenus = () => this.hideAllMenus();
-    
-    // Add click handlers to all dropdown items to stop propagation
-    document.querySelectorAll('.dropdown-item').forEach(item => {
-      item.addEventListener('click', (e) => {
-        e.stopPropagation();
-        // hideAllMenus will be called by the onclick handler in HTML
-      });
-    });
-  }
-
-  hideAllMenus() {
-    document.querySelectorAll('.dropdown-menu').forEach(menu => {
-      menu.classList.remove('show');
-    });
-    document.querySelectorAll('.menu-item').forEach(item => {
-      item.classList.remove('active');
-    });
-    this.activeMenu = null;
-  }
-
-  /**
-   * Setup UI component functions
-   */
-  setupUIComponents() {
-    // Activity bar functions
-    window.showExplorer = () => this.showExplorer();
-    window.showSearch = () => this.showSearch();
-
-    // File operations
-    window.createNewFile = () => this.tabManager.createNewFile();
-    window.openFile = () => this.fileOpsManager.openFile();
-    window.openWorkspace = () => this.openWorkspace();
-    window.saveFile = () => this.fileOpsManager.saveFile();
-    window.saveAsFile = () => this.fileOpsManager.saveAsFile();
-    window.closeCurrentTab = () => {
-      if (this.tabManager.activeTabId) {
-        this.tabManager.closeTab(new Event('click'), this.tabManager.activeTabId);
-      }
-    };
-
-    // Editor operations
-    window.formatCode = () => {
-      const formatted = this.editorManager.formatCode();
-      if (this.tabManager.activeTabId) {
-        this.tabManager.handleContentChange(this.tabManager.activeTabId, formatted);
-      }
-    };
-    window.toggleWordWrap = () => this.editorManager.toggleWordWrap();
-
-    // Search operations
-    window.showFindDialog = () => this.searchManager.showFindDialog();
-    window.closeSearchWidget = () => this.searchManager.closeSearchWidget();
-    window.searchNext = () => this.searchManager.searchNext();
-    window.searchPrev = () => this.searchManager.searchPrev();
-    window.showGoToLineDialog = () => this.searchManager.showGoToLineDialog();
-    window.closeGoToLineDialog = () => this.searchManager.closeGoToLineDialog();
-    window.performGoToLine = () => this.searchManager.performGoToLine();
-
-    // UI navigation
-    window.toggleSidebar = () => this.toggleSidebar();
-    window.toggleToolsPanel = () => this.toggleToolsPanel();
-    window.showToolsPanel = () => this.showToolsPanel();
-    window.hideToolsPanel = () => this.hideToolsPanel();
-  window.openAssistantPanel = () => this.openAssistantPanel();
-
-    // Visualyzer operations
-    window.toggleVisualyzerPanel = () => this.toggleVisualyzerPanel();
-
-    // CTrace helpers
-    const stripAnsi = (input) => {
-      if (!input || typeof input !== 'string') return input;
-      const ansiRegex = /\x1b\[[0-9;]*m/g;
-      return input.replace(ansiRegex, '');
-    };
-
-    window.runCTrace = async () => {
-      const outEl = document.getElementById('ctrace-output');
-      this.showToolsPanel();
-      if (!outEl) {
-        this.notificationManager.showError('CTrace output panel not found');
-        return;
-      }
-
-      const active = this.tabManager.getActiveTab();
-      const currentFilePath = active && active.filePath ? active.filePath : null;
-      if (!currentFilePath) {
-        outEl.textContent = 'No active file to analyze. Open a file first.';
-        this.notificationManager.showWarning('Open a file to analyze with CTrace');
-        return;
-      }
-
-      outEl.textContent = `Running ctrace on: ${currentFilePath}`;
-      try {
-        let args = [];
-        args.push(`--input=${currentFilePath}`);
-        args.push("--static");
-        args.push("--sarif-format");
-        const result = await window.ipcRenderer.invoke('run-ctrace', args);
-        if (result && result.success) {
-          outEl.textContent = stripAnsi(result.output || '(no output)');
-          this.notificationManager.showSuccess('CTrace completed successfully');
-        } else {
-          const details = (result && (result.stderr || result.output || result.error)) || 'Unknown error';
-          
-          // Check if this is a WSL setup error and provide helpful UI
-          if (details.includes('WSL') && details.includes('distributions')) {
-            outEl.innerHTML = `
-              <div style="color: #ff6b6b; font-weight: bold; margin-bottom: 10px;">⚠️ WSL Setup Required</div>
-              <div style="white-space: pre-wrap; font-family: monospace; font-size: 12px; line-height: 1.4;">${stripAnsi(details)}</div>
-              <div style="margin-top: 15px; padding: 10px; background: #f0f8ff; border: 1px solid #007acc; border-radius: 4px;">
-                <div style="font-weight: bold; color: #007acc; margin-bottom: 5px;">Quick Setup:</div>
-                <div style="font-size: 12px; color: #333;">
-                  1. Open PowerShell as Administrator<br>
-                  2. Run: <code style="background: #e6e6e6; padding: 2px 4px; border-radius: 2px;">wsl --install Ubuntu</code><br>
-                  3. Restart when prompted and follow setup instructions<br>
-                  4. Restart this application
-                </div>
-              </div>
-            `;
-            this.notificationManager.showWarning('WSL setup required - see output panel for instructions');
-          } else {
-            outEl.textContent = `Error running ctrace:\n${stripAnsi(details)}`;
-            this.notificationManager.showError('Failed to run CTrace');
-          }
-        }
-        // Auto-scroll to bottom
-        outEl.scrollTop = outEl.scrollHeight;
-      } catch (err) {
-        outEl.textContent = `Exception: ${err.message}`;
-        this.notificationManager.showError('Error invoking CTrace');
-      }
-    };
-
-    window.clearCTraceOutput = () => {
-      const outEl = document.getElementById('ctrace-output');
-      if (outEl) outEl.textContent = '';
-    };
-
-    window.copyCTraceOutput = () => {
-      const outEl = document.getElementById('ctrace-output');
-      if (!outEl) return;
-      const text = outEl.textContent || '';
-      try {
-        // Prefer Electron clipboard if available via require
-        const { clipboard } = require('electron');
-        clipboard.writeText(text);
-        this.notificationManager.showSuccess('Output copied to clipboard');
-      } catch (_) {
-        if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
-          navigator.clipboard.writeText(text)
-            .then(() => this.notificationManager.showSuccess('Output copied to clipboard'))
-            .catch(() => this.notificationManager.showError('Failed to copy output'));
-        } else {
-          this.notificationManager.showError('Clipboard not available');
-        }
-      }
-    };
-
-    // Tab manager reference for global access
-    window.tabManager = this.tabManager;
-    window.searchManager = this.searchManager;
-  }
-
-  /**
-   * Activity bar management
-   */
-  setActiveActivity(activityId) {
-    document.querySelectorAll('.activity-item').forEach(item => {
-      item.classList.remove('active');
-    });
-    const element = document.getElementById(activityId);
-    if (element) {
-      element.classList.add('active');
-    }
-  }
-
-  showExplorer() {
-    this.setActiveActivity('explorer-activity');
-    const sidebarTitle = document.getElementById('sidebar-title');
-    const explorerView = document.getElementById('explorer-view');
-    const searchView = document.getElementById('search-view');
-    const sidebar = document.getElementById('sidebar');
-    
-    if (sidebarTitle) sidebarTitle.textContent = 'Explorer';
-    if (explorerView) explorerView.style.display = 'block';
-    if (searchView) searchView.style.display = 'none';
-    if (sidebar && sidebar.style.display === 'none') {
-      sidebar.style.display = 'flex';
-    }
-  }
-
-  showSearch() {
-    this.setActiveActivity('search-activity');
-    const sidebarTitle = document.getElementById('sidebar-title');
-    const explorerView = document.getElementById('explorer-view');
-    const searchView = document.getElementById('search-view');
-    const sidebar = document.getElementById('sidebar');
-    const searchInput = document.getElementById('sidebar-search-input');
-    
-    if (sidebarTitle) sidebarTitle.textContent = 'Search';
-    if (explorerView) explorerView.style.display = 'none';
-    if (searchView) searchView.style.display = 'block';
-    if (sidebar && sidebar.style.display === 'none') {
-      sidebar.style.display = 'flex';
-    }
-    setTimeout(() => searchInput && searchInput.focus(), 100);
-  }
-
-  /**
-   * Sidebar toggle
-   */
-  toggleSidebar() {
-    const sidebar = document.getElementById('sidebar');
-    if (!sidebar) return;
-
-    if (sidebar.style.width === '0px' || sidebar.style.display === 'none') {
-      sidebar.style.width = '280px';
-      sidebar.style.display = 'flex';
-    } else {
-      sidebar.style.width = '0px';
-      setTimeout(() => {
-        sidebar.style.display = 'none';
-      }, 200);
-    }
-  }
-
-  /**
-   * Tools panel management
-   */
-  showToolsPanel() {
-    const toolsPanel = document.getElementById('toolsPanel');
-    if (toolsPanel) {
-      toolsPanel.style.display = 'flex';
-      toolsPanel.offsetHeight; // Force reflow
-      toolsPanel.classList.add('active');
-    }
-  }
-
-  hideToolsPanel() {
-    const toolsPanel = document.getElementById('toolsPanel');
-    if (toolsPanel) {
-      toolsPanel.classList.remove('active');
-      setTimeout(() => {
-        toolsPanel.style.display = 'none';
-      }, 200);
-    }
-  }
-
-  toggleToolsPanel() {
-    const toolsPanel = document.getElementById('toolsPanel');
-    if (toolsPanel) {
-      if (toolsPanel.style.display === 'none' || !toolsPanel.classList.contains('active')) {
-        this.showToolsPanel();
-      } else {
-        this.hideToolsPanel();
-      }
-    }
-  }
-
-  /**
-   * Visualyzer panel management
-   */
-  toggleVisualyzerPanel() {
-    // Open visualyzer in a separate window
-    window.ipcRenderer.send('open-visualyzer');
-  }
-
-  closeVisualyzer() {
-    // This method is no longer needed since visualyzer is in separate window
-    // Kept for backward compatibility
-  }
-
-  toggleToolsPanel() {
-    const toolsPanel = document.getElementById('toolsPanel');
-    if (toolsPanel) {
-      if (toolsPanel.classList.contains('active')) {
-        this.hideToolsPanel();
-      } else {
-        this.showToolsPanel();
-      }
-    }
-  }
-
-  openAssistantPanel() {
-    const toolsPanel = document.getElementById('toolsPanel');
-    // Ensure assistant is configured at least once before opening
-    const ensure = this.ensureAssistantConfigured();
-    Promise.resolve(ensure).then(() => {
-      if (toolsPanel) {
-        this.showToolsPanel();
-        // Inject assistant chat UI into tools panel
-        this.renderAssistantUI();
-      }
-    });
-  }
-
-  /**
-   * Inject a simple chat UI into the tools panel (like VSCode Copilot sidebar)
-   */
-  renderAssistantUI() {
-    const toolsPanel = document.getElementById('toolsPanel');
-    if (!toolsPanel) return;
-
-    // Save original content so we can restore it later
-    if (!this._toolsPanelOriginal) {
-      const header = toolsPanel.querySelector('.tools-panel-header');
-      const content = toolsPanel.querySelector('.tools-panel-content');
-      this._toolsPanelOriginal = {
-        headerHTML: header ? header.innerHTML : null,
-        contentHTML: content ? content.innerHTML : null
-      };
-    }
-
-    const header = toolsPanel.querySelector('.tools-panel-header');
-    const content = toolsPanel.querySelector('.tools-panel-content');
-    if (!header || !content) return;
-
-    // Update header title
-    const titleSpan = header.querySelector('span');
-    if (titleSpan) titleSpan.textContent = 'Assistant';
-
-    // Build assistant UI
-    const cfg = this.getAssistantConfig() || { provider: 'none' };
-    
-    // Get display name for the assistant
-    let displayName = 'Not configured';
-    if (cfg.provider === 'local' && cfg.localModelPath) {
-      // Extract filename from path and remove .gguf extension
-      const pathParts = cfg.localModelPath.replace(/\\/g, '/').split('/');
-      const filename = pathParts[pathParts.length - 1];
-      displayName = filename.replace(/\.gguf$/i, '');
-    } else if (cfg.provider === 'external') {
-      displayName = cfg.externalProvider || 'External';
-    } else if (cfg.provider === 'ollama') {
-      displayName = 'Ollama';
-    } else if (cfg.provider !== 'none') {
-      displayName = cfg.provider;
-    }
-
-    content.innerHTML = `
-      <div style="display:flex; flex-direction:column; height:100%;">
-        <div style="padding:8px 12px; border-bottom:1px solid rgba(255,255,255,0.03); display:flex; align-items:center; justify-content:space-between">
-          <div style="font-size:13px; color:#c9d1d9">Assistant — ${displayName}</div>
-          <div style="display:flex; gap:8px; align-items:center">
-            <button id="assistant-settings" style="padding:6px 8px; background:#21262d; border:1px solid #30363d; color:#f0f6fc; border-radius:6px; cursor:pointer; font-size:12px">Settings</button>
-          </div>
-        </div>
-        <div id="assistant-messages" style="flex:1; padding:12px; overflow:auto; background:linear-gradient(#0b0f14, #051018);">
-          <!-- messages go here -->
-        </div>
-        <div style="padding:10px; border-top:1px solid rgba(255,255,255,0.03);">
-          <div id="context-indicator" style="display:none; padding:6px 8px; margin-bottom:8px; background:#1a1f2e; border:1px solid #2b3036; border-radius:4px; font-size:11px; color:#8b949e; font-family:monospace;">
-            <span id="context-text"></span>
-            <button id="context-clear" style="margin-left:8px; padding:2px 6px; background:transparent; border:1px solid #30363d; color:#8b949e; border-radius:3px; cursor:pointer; font-size:10px;">✕</button>
-          </div>
-          <div style="display:flex; gap:8px; align-items:flex-end">
-            <textarea id="assistant-input" placeholder="Ask the assistant..." style="flex:1; min-height:44px; max-height:120px; resize:none; padding:8px; border-radius:6px; border:1px solid #2b3036; background:#0d1117; color:#fff"></textarea>
-            <button id="assistant-send" style="padding:10px; background:transparent; color:#8b949e; border:none; cursor:pointer; display:flex; align-items:center; justify-content:center; transition:color 0.2s;" title="Send message (Enter)" onmouseover="this.style.color='#c9d1d9'" onmouseout="this.style.color='#8b949e'">
-              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
-                <path d="M2 21L23 12L2 3V10L17 12L2 14V21Z" fill="currentColor"/>
-              </svg>
-            </button>
-          </div>
-        </div>
-      </div>
-    `;
-
-    // Helper to append messages with typing effect
-    const addMessage = (who, text, options = {}) => {
-      const container = document.getElementById('assistant-messages');
-      if (!container) return;
-      const wrap = document.createElement('div');
-      wrap.style.marginBottom = '12px';
-      const bubble = document.createElement('div');
-      bubble.style.padding = '10px 12px';
-      bubble.style.borderRadius = '8px';
-      bubble.style.maxWidth = '90%';
-      bubble.style.lineHeight = '1.4';
-      
-      if (who === 'user') {
-        bubble.style.background = '#0b5fff';
-        bubble.style.color = '#fff';
-        bubble.style.marginLeft = 'auto';
-        bubble.style.whiteSpace = 'pre-wrap';
-        bubble.textContent = text;
-        wrap.appendChild(bubble);
-        container.appendChild(wrap);
-        container.scrollTop = container.scrollHeight;
-      } else {
-        bubble.style.background = '#111319';
-        bubble.style.color = '#e6edf3';
-        bubble.style.marginRight = 'auto';
-        wrap.appendChild(bubble);
-        container.appendChild(wrap);
-        
-        // Return the bubble element for typing effects
-        if (options.typing) {
-          return bubble;
-        }
-        
-        // Render markdown for assistant messages
-        bubble.innerHTML = renderMarkdown(text);
-        container.scrollTop = container.scrollHeight;
-      }
-    };
-
-    // Typing effect for assistant messages
-    const typeMessage = async (bubble, text, speed = 0.1) => { // Changed from 20 to 10ms (faster). Increase for slower, decrease for faster
-      const container = document.getElementById('assistant-messages');
-      let currentText = '';
-      
-      for (let i = 0; i < text.length; i++) {
-        currentText += text[i];
-        bubble.innerHTML = renderMarkdown(currentText);
-        if (container) container.scrollTop = container.scrollHeight;
-        await new Promise(resolve => setTimeout(resolve, speed));
-      }
-    };
-
-    // Animated thinking indicator
-    const addThinkingMessage = () => {
-      const bubble = addMessage('assistant', '', { typing: true });
-      if (!bubble) return null;
-      
-      let dotCount = 0;
-      const thinkingInterval = setInterval(() => {
-        dotCount = (dotCount % 3) + 1;
-        bubble.textContent = 'Thinking' + '.'.repeat(dotCount);
-        const container = document.getElementById('assistant-messages');
-        if (container) container.scrollTop = container.scrollHeight;
-      }, 400);
-      
-      return { bubble, interval: thinkingInterval };
-    };
-
-    // Remove thinking message
-    const removeThinkingMessage = (thinkingData) => {
-      if (!thinkingData) return;
-      clearInterval(thinkingData.interval);
-      const container = document.getElementById('assistant-messages');
-      if (container && thinkingData.bubble && thinkingData.bubble.parentElement) {
-        container.removeChild(thinkingData.bubble.parentElement);
-      }
-    };
-
-    // Simple markdown renderer
-    const renderMarkdown = (text) => {
-      // Trim leading/trailing whitespace to avoid extra newlines
-      text = text.trim();
-      
-      // Store original code blocks before any processing
-      const codeBlocks = [];
-      let codeIndex = 0;
-      
-      // Extract and store original code blocks with language info
-      const textWithPlaceholders = text.replace(/```(\w+)?\n([\s\S]*?)```/g, (match, lang, code) => {
-        const trimmedCode = code.trim();
-        codeBlocks.push({ code: trimmedCode, lang: lang || '' });
-        return `__CODE_BLOCK_${codeIndex++}__`;
-      });
-      
-      // Escape HTML
-      let html = textWithPlaceholders.replace(/&/g, '&amp;')
-                                     .replace(/</g, '&lt;')
-                                     .replace(/>/g, '&gt;');
-      
-      // Replace code block placeholders with rendered HTML
-      codeIndex = 0;
-      html = html.replace(/__CODE_BLOCK_(\d+)__/g, (match, index) => {
-        const blockData = codeBlocks[parseInt(index)];
-        const originalCode = blockData.code;
-        const lang = blockData.lang.toLowerCase();
-        
-        // Store original code in base64 to avoid any escaping issues
-        const base64Code = btoa(unescape(encodeURIComponent(originalCode)));
-        
-        // Apply syntax highlighting for C/C++ code
-        let displayCode;
-        if (lang === 'c' || lang === 'cpp' || lang === 'c++') {
-          // Use syntax highlighter
-          const { applySyntaxHighlight } = window.syntaxHighlighter;
-          const fileType = lang === 'c' ? 'C' : 'C++';
-          displayCode = applySyntaxHighlight(originalCode, fileType);
-        } else {
-          // No highlighting - just escape HTML
-          displayCode = originalCode.replace(/&/g, '&amp;')
-                                     .replace(/</g, '&lt;')
-                                     .replace(/>/g, '&gt;');
-        }
-        
-        const langLabel = lang ? `<span style="position:absolute; top:8px; left:12px; font-size:10px; color:#7d8590; text-transform:uppercase; font-weight:600;">${lang}</span>` : '';
-        
-        return `<div style="position:relative; margin:8px 0;">
-          ${langLabel}
-          <div style="position:absolute; top:8px; right:8px; display:flex; gap:6px;">
-            <button class="code-copy-btn" data-code-b64="${base64Code}" style="padding:4px 8px; background:#21262d; border:1px solid #30363d; color:#f0f6fc; border-radius:4px; cursor:pointer; font-size:11px;">Copy</button>
-            <button class="code-replace-btn" data-code-b64="${base64Code}" style="padding:4px 8px; background:#238636; border:1px solid #2ea043; color:#fff; border-radius:4px; cursor:pointer; font-size:11px;">Replace</button>
-          </div>
-          <pre style="background:#0d1117; padding:12px; border-radius:6px; overflow-x:auto; padding-top:${lang ? '28px' : '12px'};"><code style="font-family:Consolas,Monaco,'Courier New',monospace; font-size:13px; color:#c9d1d9;">${displayCode}</code></pre>
-        </div>`;
-      });
-      
-      // Inline code (`code`)
-      html = html.replace(/`([^`]+)`/g, '<code style="background:#21262d; padding:2px 6px; border-radius:3px; font-family:Consolas,Monaco,monospace; font-size:13px; color:#f0f6fc;">$1</code>');
-      
-      // Bold (**text** or __text__)
-      html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
-      html = html.replace(/__([^_]+)__/g, '<strong>$1</strong>');
-      
-      // Italic (*text* or _text_)
-      html = html.replace(/\*([^*]+)\*/g, '<em>$1</em>');
-      html = html.replace(/_([^_]+)_/g, '<em>$1</em>');
-      
-      // Headers (### text)
-      html = html.replace(/^### (.+)$/gm, '<h3 style="margin:12px 0 8px 0; font-size:16px; font-weight:600; color:#f0f6fc;">$1</h3>');
-      html = html.replace(/^## (.+)$/gm, '<h2 style="margin:14px 0 10px 0; font-size:18px; font-weight:600; color:#f0f6fc;">$1</h2>');
-      html = html.replace(/^# (.+)$/gm, '<h1 style="margin:16px 0 12px 0; font-size:20px; font-weight:600; color:#f0f6fc;">$1</h1>');
-      
-      // Lists (- item or * item or 1. item)
-      html = html.replace(/^- (.+)$/gm, '<li style="margin-left:20px;">$1</li>');
-      html = html.replace(/^\* (.+)$/gm, '<li style="margin-left:20px;">$1</li>');
-      html = html.replace(/^\d+\. (.+)$/gm, '<li style="margin-left:20px; list-style-type:decimal;">$1</li>');
-      
-      // Wrap consecutive <li> in <ul>
-      html = html.replace(/(<li[^>]*>.*<\/li>\n?)+/g, (match) => {
-        return `<ul style="margin:8px 0; padding-left:0;">${match}</ul>`;
-      });
-      
-      // Line breaks (preserve double newlines as paragraphs)
-      html = html.replace(/\n\n/g, '<br><br>');
-      
-      return html;
-    };
-
-    // Prefill a small welcome message with typing effect (only first time)
-    const providerName = cfg.provider === 'external' ? (cfg.externalProvider || 'External') : cfg.provider;
-    const welcomeText = `Hi — I'm your assistant. Using: ${providerName}. Ask me something or open Settings to change providers.`;
-    
-    // Check if welcome message has been shown before
-    const hasShownWelcome = sessionStorage.getItem('assistantWelcomeShown');
-    
-    if (!hasShownWelcome) {
-      // First time - show typing effect (faster speed: 8ms per character)
-      const welcomeBubble = addMessage('assistant', '', { typing: true });
-      if (welcomeBubble) {
-        typeMessage(welcomeBubble, welcomeText, 8);
-      }
-      sessionStorage.setItem('assistantWelcomeShown', 'true');
-    } else {
-      // Already shown - display instantly
-      addMessage('assistant', welcomeText);
-    }
-
-    // Wire up send button
-    const sendBtn = document.getElementById('assistant-send');
-    const inputEl = document.getElementById('assistant-input');
-    const settingsBtn = document.getElementById('assistant-settings');
-    const contextIndicator = document.getElementById('context-indicator');
-    const contextText = document.getElementById('context-text');
-    const contextClearBtn = document.getElementById('context-clear');
-
-    // Capture selection before it's lost when user clicks on input
-    let capturedSelection = '';
-    let capturedLineInfo = '';
-    
-    inputEl.addEventListener('focus', () => {
-      const editor = this.editorManager.editor;
-      const start = editor.selectionStart;
-      const end = editor.selectionEnd;
-      const selection = editor.value.substring(start, end);
-      
-      if (selection) {
-        capturedSelection = selection;
-        
-        // Calculate line numbers
-        const textBeforeStart = editor.value.substring(0, start);
-        const textBeforeEnd = editor.value.substring(0, end);
-        const startLine = (textBeforeStart.match(/\n/g) || []).length + 1;
-        const endLine = (textBeforeEnd.match(/\n/g) || []).length + 1;
-        
-        // Get current file name
-        const activeTab = this.tabManager.getActiveTab();
-        const fileName = activeTab && activeTab.fileName ? activeTab.fileName : 'Untitled';
-        
-        // Format context info
-        if (startLine === endLine) {
-          capturedLineInfo = `${fileName}: ${startLine}`;
-        } else {
-          capturedLineInfo = `${fileName}: ${startLine}-${endLine}`;
-        }
-        
-        // Show context indicator
-        contextText.textContent = capturedLineInfo;
-        contextIndicator.style.display = 'block';
-      }
-    });
-
-    // Handle Enter key to send message (Shift+Enter for new line)
-    inputEl.addEventListener('keydown', (e) => {
-      if (e.key === 'Enter' && !e.shiftKey) {
-        e.preventDefault();
-        sendBtn.click();
-      }
-    });
-
-    // Clear captured selection when input loses focus without sending
-    inputEl.addEventListener('blur', () => {
-      // Small delay to allow send button click to process
-      setTimeout(() => {
-        if (!inputEl.value.trim()) {
-          capturedSelection = '';
-          capturedLineInfo = '';
-          contextIndicator.style.display = 'none';
-        }
-      }, 200);
-    });
-
-    // Clear button handler
-    contextClearBtn.onclick = () => {
-      capturedSelection = '';
-      capturedLineInfo = '';
-      contextIndicator.style.display = 'none';
-    };
-
-    sendBtn.onclick = async () => {
-      const text = (inputEl.value || '').trim();
-      if (!text) return;
-      
-      // Use captured selection as context
-      let context = '';
-      if (capturedSelection) {
-        context = `\n\n[Context - Selected Code]:\n\`\`\`\n${capturedSelection}\n\`\`\`\n\n`;
-      }
-      
-      // Clear captured selection and hide indicator after using it
-      capturedSelection = '';
-      capturedLineInfo = '';
-      contextIndicator.style.display = 'none';
-      
-      // Combine user message with context
-      const fullMessage = context ? context + text : text;
-      
-      // Display only user's text in UI
-      addMessage('user', text);
-      inputEl.value = '';
-
-      // Get current assistant config
-      const cfg = this.getAssistantConfig();
-      if (!cfg || cfg.provider === 'none' || cfg.skipped) {
-        const bubble = addMessage('assistant', '', { typing: true });
-        if (bubble) {
-          await typeMessage(bubble, 'Assistant not configured. Please click the settings icon ⚙️ to set up your provider.', 15);
-        }
-        return;
-      }
-
-      // Show animated thinking indicator
-      const thinkingData = addThinkingMessage();
-
-      try {
-        // All providers go through IPC (main process)
-        const result = await window.ipcRenderer.invoke('assistant-chat', {
-          provider: cfg.provider,
-          message: fullMessage,
-          config: cfg
-        });
-
-        // Remove the thinking message
-        removeThinkingMessage(thinkingData);
-
-        if (result && result.success) {
-          const bubble = addMessage('assistant', '', { typing: true });
-          if (bubble) {
-            await typeMessage(bubble, result.reply, 20);
-            
-            // Attach event listeners to code action buttons after rendering
-            setTimeout(() => {
-              attachCodeActionListeners();
-            }, 100);
-          }
-        } else {
-          const errorMsg = result && result.error ? result.error : 'Unknown error occurred';
-          const bubble = addMessage('assistant', '', { typing: true });
-          if (bubble) {
-            await typeMessage(bubble, `❌ Error: ${errorMsg}`, 15);
-          }
-        }
-      } catch (err) {
-        // Remove thinking message
-        removeThinkingMessage(thinkingData);
-        
-        console.error('Assistant chat error:', err);
-        const bubble = addMessage('assistant', '', { typing: true });
-        if (bubble) {
-          await typeMessage(bubble, `❌ Error: ${err.message || 'Failed to communicate with assistant'}`, 15);
-        }
-      }
-    };
-
-    // Helper to attach event listeners to code action buttons
-    const attachCodeActionListeners = () => {
-      const container = document.getElementById('assistant-messages');
-      if (!container) return;
-      
-      // Copy button handlers
-      container.querySelectorAll('.code-copy-btn').forEach(btn => {
-        btn.onclick = () => {
-          const base64Code = btn.getAttribute('data-code-b64');
-          const code = decodeURIComponent(escape(atob(base64Code)));
-          
-          try {
-            const { clipboard } = require('electron');
-            clipboard.writeText(code);
-            btn.textContent = 'Copied!';
-            setTimeout(() => btn.textContent = 'Copy', 2000);
-          } catch (_) {
-            if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
-              navigator.clipboard.writeText(code)
-                .then(() => {
-                  btn.textContent = 'Copied!';
-                  setTimeout(() => btn.textContent = 'Copy', 2000);
-                })
-                .catch(() => alert('Failed to copy code'));
-            }
-          }
-        };
-      });
-      
-      // Replace button handlers
-      container.querySelectorAll('.code-replace-btn').forEach(btn => {
-        btn.onclick = () => {
-          const base64Code = btn.getAttribute('data-code-b64');
-          const code = decodeURIComponent(escape(atob(base64Code)));
-          
-          const editor = this.editorManager.editor;
-          const start = editor.selectionStart;
-          const end = editor.selectionEnd;
-          
-          if (start !== end) {
-            // Replace selected text
-            const before = editor.value.substring(0, start);
-            const after = editor.value.substring(end);
-            editor.value = before + code + after;
-            
-            // Update tab state
-            if (this.tabManager.activeTabId) {
-              this.tabManager.handleContentChange(this.tabManager.activeTabId, editor.value);
-            }
-            
-            btn.textContent = 'Replaced!';
-            setTimeout(() => btn.textContent = 'Replace', 2000);
-          } else {
-            // Insert at cursor position
-            const before = editor.value.substring(0, start);
-            const after = editor.value.substring(start);
-            editor.value = before + code + after;
-            
-            // Update tab state
-            if (this.tabManager.activeTabId) {
-              this.tabManager.handleContentChange(this.tabManager.activeTabId, editor.value);
-            }
-            
-            btn.textContent = 'Inserted!';
-            setTimeout(() => btn.textContent = 'Replace', 2000);
-          }
-          
-          // Focus editor
-          editor.focus();
-        };
-      });
-    };
-
-    settingsBtn.onclick = () => {
-      // Open the assistant setup modal for reconfiguration
-      this.showAssistantSetupGuide((cfg) => {
-        // Re-render assistant UI to reflect changes
-        this.renderAssistantUI();
-      });
-    };
-  }
-
-  /**
-   * Retrieve assistant configuration from localStorage
-   * @returns {Object|null}
-   */
-  getAssistantConfig() {
-    try {
-      const raw = localStorage.getItem('assistantConfig');
-      if (!raw) return null;
-      return JSON.parse(raw);
-    } catch (err) {
-      console.error('Failed to parse assistantConfig from localStorage', err);
-      return null;
-    }
-  }
-
-  /**
-   * Save assistant configuration to localStorage
-   * @param {Object} cfg
-   */
-  saveAssistantConfig(cfg) {
-    try {
-      localStorage.setItem('assistantConfig', JSON.stringify(cfg));
-      this.notificationManager.showSuccess('Assistant settings saved');
-    } catch (err) {
-      console.error('Failed to save assistantConfig', err);
-      this.notificationManager.showError('Failed to save assistant settings');
-    }
-  }
-
-  /**
-   * Ensure assistant is configured; if not, show guided setup modal
-   */
-  async ensureAssistantConfigured() {
-    const cfg = this.getAssistantConfig();
-    if (cfg && cfg.provider) return cfg;
-    // Show setup guide modal and wait for user to complete or cancel
-    return new Promise((resolve) => {
-      this.showAssistantSetupGuide(resolve);
-    });
-  }
-
-  /**
-   * Render a first-time setup modal for Assistant configuration.
-   * Calls the done callback with saved config or null if cancelled.
-   */
-  showAssistantSetupGuide(done) {
-    // Load existing config to pre-fill form
-    const existingConfig = this.getAssistantConfig() || {};
-    
-    // Modal overlay
-    const modal = document.createElement('div');
-    modal.style.cssText = `
-      position: fixed; top:0; left:0; width:100%; height:100%;
-      background: rgba(0,0,0,0.6); display:flex; align-items:center; justify-content:center; z-index:10001;
-    `;
-
-    const dialog = document.createElement('div');
-    dialog.style.cssText = `
-      width: 720px; max-width: 95%; background: #fff; border-radius:8px; padding:20px; box-shadow:0 8px 30px rgba(0,0,0,0.3);
-      font-family: sans-serif; color: #222;
-    `;
-
-    dialog.innerHTML = `
-      <h2 style="margin-top:0">Assistant setup</h2>
-      <p>Choose how you'd like to connect the Assistant. You can use Ollama, an external API (ChatGPT5, Deepseek, or other), or point to a local GGUF model on your machine.</p>
-      <div style="display:flex; gap:12px; margin-top:12px;">
-        <label style="flex:1; border:1px solid #e2e2e2; padding:12px; border-radius:6px; cursor:pointer;" id="assist-opt-ollama">
-          <input type="radio" name="assist-provider" value="ollama" style="margin-right:8px"> Ollama (local or remote)
-          <div style="font-size:12px; color:#555; margin-top:6px">Connect to an Ollama server (default: http://localhost:11434)</div>
-        </label>
-        <label style="flex:1; border:1px solid #e2e2e2; padding:12px; border-radius:6px; cursor:pointer;" id="assist-opt-external">
-          <input type="radio" name="assist-provider" value="external" style="margin-right:8px"> External API
-          <div style="font-size:12px; color:#555; margin-top:6px">Use ChatGPT5, Deepseek or other hosted APIs (requires API key)</div>
-        </label>
-        <label style="flex:1; border:1px solid #e2e2e2; padding:12px; border-radius:6px; cursor:pointer;" id="assist-opt-local">
-          <input type="radio" name="assist-provider" value="local" style="margin-right:8px"> Local GGUF model
-          <div style="font-size:12px; color:#555; margin-top:6px">Point to a GGUF model file on your computer</div>
-        </label>
-      </div>
-
-      <div id="assist-extra" style="margin-top:16px"></div>
-
-      <div style="display:flex; justify-content:flex-end; gap:8px; margin-top:18px;">
-        <button id="assist-skip" style="padding:8px 12px; background:transparent; border:1px solid #cfcfcf; border-radius:6px; cursor:pointer">Skip for now</button>
-        <button id="assist-cancel" style="padding:8px 12px; background:#ddd; border:none; border-radius:6px; cursor:pointer">Cancel</button>
-        <button id="assist-save" style="padding:8px 12px; background:#007acc; color:white; border:none; border-radius:6px; cursor:pointer">Save</button>
-      </div>
-    `;
-
-    modal.appendChild(dialog);
-    document.body.appendChild(modal);
-
-    const extra = dialog.querySelector('#assist-extra');
-
-    const clearExtra = () => { extra.innerHTML = ''; };
-
-    const makeInputRow = (labelText, inputId, placeholder = '') => {
-      const row = document.createElement('div');
-      row.style.cssText = 'display:flex; flex-direction:column; gap:6px; margin-top:8px;';
-      row.innerHTML = `
-        <label style="font-size:13px; color:#333">${labelText}</label>
-        <input id="${inputId}" style="padding:8px; border:1px solid #e2e2e2; border-radius:4px; font-size:13px" placeholder="${placeholder}">
-      `;
-      return row;
-    };
-
-    const providerRadios = dialog.querySelectorAll('input[name="assist-provider"]');
-    const optOllama = dialog.querySelector('#assist-opt-ollama');
-    const optExternal = dialog.querySelector('#assist-opt-external');
-    const optLocal = dialog.querySelector('#assist-opt-local');
-
-    const selectProvider = (value) => {
-      providerRadios.forEach(r => r.checked = (r.value === value));
-      optOllama.style.borderColor = value === 'ollama' ? '#007acc' : '#e2e2e2';
-      optExternal.style.borderColor = value === 'external' ? '#007acc' : '#e2e2e2';
-      optLocal.style.borderColor = value === 'local' ? '#007acc' : '#e2e2e2';
-
-      clearExtra();
-      if (value === 'ollama') {
-        extra.appendChild(makeInputRow('Ollama host (include protocol)', 'ollama-host', 'http://localhost:11434'));
-        extra.appendChild(makeInputRow('System prompt (optional)', 'system-prompt', 'You are a helpful assistant...'));
-        
-        // Pre-fill with saved values
-        setTimeout(() => {
-          const hostInput = document.getElementById('ollama-host');
-          const systemInput = document.getElementById('system-prompt');
-          if (hostInput && existingConfig.ollamaHost) {
-            hostInput.value = existingConfig.ollamaHost;
-          }
-          if (systemInput && existingConfig.systemPrompt) {
-            systemInput.value = existingConfig.systemPrompt;
-          }
-        }, 0);
-      } else if (value === 'external') {
-        const selRow = document.createElement('div');
-        selRow.style.cssText = 'display:flex; gap:8px; align-items:center; margin-top:8px;';
-        selRow.innerHTML = `
-          <label style="font-size:13px">Provider</label>
-          <select id="external-provider" style="padding:6px; border:1px solid #e2e2e2; border-radius:4px">
-            <option value="ChatGPT5">ChatGPT5</option>
-            <option value="Deepseek">Deepseek</option>
-            <option value="Other">Other</option>
-          </select>
-        `;
-        extra.appendChild(selRow);
-        extra.appendChild(makeInputRow('API Key', 'external-api-key', 'sk-...'));
-        extra.appendChild(makeInputRow('System prompt (optional)', 'system-prompt', 'You are a helpful assistant...'));
-        
-        // Pre-fill with saved values
-        setTimeout(() => {
-          const providerSelect = document.getElementById('external-provider');
-          const apiKeyInput = document.getElementById('external-api-key');
-          const systemInput = document.getElementById('system-prompt');
-          if (providerSelect && existingConfig.externalProvider) {
-            providerSelect.value = existingConfig.externalProvider;
-          }
-          if (apiKeyInput && existingConfig.apiKey) {
-            apiKeyInput.value = existingConfig.apiKey;
-          }
-          if (systemInput && existingConfig.systemPrompt) {
-            systemInput.value = existingConfig.systemPrompt;
-          }
-        }, 0);
-      } else if (value === 'local') {
-        const row = document.createElement('div');
-        row.style.cssText = 'display:flex; gap:8px; align-items:center; margin-top:8px;';
-        row.innerHTML = `
-          <input id="local-model-path" placeholder="Select GGUF model file..." style="flex:1; padding:8px; border:1px solid #e2e2e2; border-radius:4px" readonly>
-          <button id="local-browse" style="padding:8px 10px; border-radius:4px; border:none; background:#007acc; color:white; cursor:pointer">Browse</button>
-        `;
-        extra.appendChild(row);
-
-        // Browse handler using IPC
-        setTimeout(() => {
-          const browseBtn = document.getElementById('local-browse');
-          const pathInput = document.getElementById('local-model-path');
-          
-          // Pre-fill with saved value
-          if (pathInput && existingConfig.localModelPath) {
-            pathInput.value = existingConfig.localModelPath;
-          }
-          
-          if (browseBtn) {
-            browseBtn.onclick = async () => {
-              try {
-                const result = await window.ipcRenderer.invoke('select-llm-file');
-                if (result && result.filePath) {
-                  pathInput.value = result.filePath;
-                }
-              } catch (err) {
-                console.error('Error selecting model file', err);
-                this.notificationManager.showError('Unable to open file selector');
-              }
-            };
-          }
-        }, 0);
-        
-        // Add context size configuration
-        const contextRow = document.createElement('div');
-        contextRow.style.cssText = 'margin-top:12px;';
-        contextRow.innerHTML = `
-          <label style="display:block; margin-bottom:4px; color:#333; font-size:13px">Context Size (tokens):</label>
-          <input id="context-size" type="number" placeholder="8192" style="width:100%; padding:8px; border:1px solid #e2e2e2; border-radius:4px" value="8192" min="512" max="32768">
-          <div style="margin-top:4px; font-size:11px; color:#666">Lower values use less VRAM. Recommended: 2048-8192. Default model max: 40960</div>
-        `;
-        extra.appendChild(contextRow);
-        
-        // Add GPU layers configuration
-        const gpuRow = document.createElement('div');
-        gpuRow.style.cssText = 'margin-top:12px;';
-        gpuRow.innerHTML = `
-          <label style="display:block; margin-bottom:4px; color:#333; font-size:13px">GPU Layers (0 = CPU only, -1 = all layers):</label>
-          <input id="gpu-layers" type="number" placeholder="0" style="width:100%; padding:8px; border:1px solid #e2e2e2; border-radius:4px" value="0">
-          <div style="margin-top:4px; font-size:11px; color:#666">Higher values offload more layers to GPU for faster inference. Use -1 to offload all layers.</div>
-        `;
-        extra.appendChild(gpuRow);
-        
-        // Add system prompt field for local models too
-        extra.appendChild(makeInputRow('System prompt (optional)', 'system-prompt', 'You are a helpful assistant...'));
-        
-        // Pre-fill all settings
-        setTimeout(() => {
-          const systemInput = document.getElementById('system-prompt');
-          const gpuLayersInput = document.getElementById('gpu-layers');
-          const contextSizeInput = document.getElementById('context-size');
-          
-          if (systemInput && existingConfig.systemPrompt) {
-            systemInput.value = existingConfig.systemPrompt;
-          }
-          if (gpuLayersInput && existingConfig.gpuLayers !== undefined) {
-            gpuLayersInput.value = existingConfig.gpuLayers;
-          }
-          if (contextSizeInput && existingConfig.contextSize !== undefined) {
-            contextSizeInput.value = existingConfig.contextSize;
-          }
-        }, 0);
-      }
-    };
-
-    // Click handlers for the option cards as well
-    optOllama.onclick = () => selectProvider('ollama');
-    optExternal.onclick = () => selectProvider('external');
-    optLocal.onclick = () => selectProvider('local');
-
-    // Pre-select provider based on saved config, or default to external
-    const savedProvider = existingConfig.provider && existingConfig.provider !== 'none' 
-      ? existingConfig.provider 
-      : 'external';
-    selectProvider(savedProvider);
-
-    // Buttons
-    const btnSave = dialog.querySelector('#assist-save');
-    const btnCancel = dialog.querySelector('#assist-cancel');
-    const btnSkip = dialog.querySelector('#assist-skip');
-
-    const closeModal = (result) => {
-      try { document.body.removeChild(modal); } catch (_) {}
-      if (done) done(result);
-    };
-
-    btnCancel.onclick = () => closeModal(null);
-    btnSkip.onclick = () => {
-      // Save a lightweight config indicating user skipped
-      const cfg = { provider: 'none', skipped: true };
-      this.saveAssistantConfig(cfg);
-      closeModal(cfg);
-    };
-
-    btnSave.onclick = () => {
-      const selected = Array.from(providerRadios).find(r => r.checked);
-      if (!selected) {
-        this.notificationManager.showError('Please select a provider');
-        return;
-      }
-      const provider = selected.value;
-      const cfg = { provider };
-      
-      // Get system prompt if it exists
-      const systemPromptEl = document.getElementById('system-prompt');
-      if (systemPromptEl && systemPromptEl.value.trim()) {
-        cfg.systemPrompt = systemPromptEl.value.trim();
-      }
-      
-      if (provider === 'ollama') {
-        const hostEl = document.getElementById('ollama-host');
-        cfg.ollamaHost = hostEl && hostEl.value ? hostEl.value.trim() : 'http://localhost:11434';
-      } else if (provider === 'external') {
-        const prov = document.getElementById('external-provider');
-        const key = document.getElementById('external-api-key');
-        cfg.externalProvider = prov ? prov.value : 'ChatGPT5';
-        cfg.apiKey = key ? key.value.trim() : '';
-        if (!cfg.apiKey) {
-          this.notificationManager.showError('Please enter an API key for the external provider');
-          return;
-        }
-      } else if (provider === 'local') {
-        const pathEl = document.getElementById('local-model-path');
-        const gpuLayersEl = document.getElementById('gpu-layers');
-        const contextSizeEl = document.getElementById('context-size');
-        
-        cfg.localModelPath = pathEl ? pathEl.value : '';
-        if (!cfg.localModelPath) {
-          this.notificationManager.showError('Please choose a local GGUF model file');
-          return;
-        }
-        
-        // Save GPU layers setting (default to 0 if not specified)
-        cfg.gpuLayers = gpuLayersEl && gpuLayersEl.value !== '' ? parseInt(gpuLayersEl.value, 10) : 0;
-        
-        // Save context size setting (default to 8192 if not specified)
-        cfg.contextSize = contextSizeEl && contextSizeEl.value !== '' ? parseInt(contextSizeEl.value, 10) : 8192;
-      }
-
-      // Persist and close
-      this.saveAssistantConfig(cfg);
-      // Notify main process in case it needs to warm things up
-      try { window.ipcRenderer.send('assistant-config-updated', cfg); } catch (_) {}
-      closeModal(cfg);
-    };
-
-    // Dismiss modal when clicking outside the dialog
-    modal.onclick = (e) => { if (e.target === modal) closeModal(null); };
-  }
-  /**
-   * Open workspace and update search manager
-   */
-  async openWorkspace() {
-    const result = await this.fileOpsManager.openWorkspace();
-    if (result && result.success) {
-      this.searchManager.setWorkspacePath(result.folderPath);
-    }
-  }
-
-  /**
-   * Open search result with proper line navigation
-   * @param {string} filePath - File path
-   * @param {number} lineNumber - Line number
-   */
-  async openSearchResult(filePath, lineNumber) {
-    console.log('Opening search result:', filePath, 'at line', lineNumber);
-    
-    try {
-      const normalizedPath = filePath.replace(/\\\\/g, '\\');
-      
-      const result = await window.ipcRenderer.invoke('read-file', normalizedPath);
-      console.log('Search result read result:', result);
-      
-      if (result.success) {
-        let tabId;
-        
-        if (result.warning === 'encoding') {
-          console.log('Search result: Encoding warning detected, showing dialog...');
-          const userChoice = await this.notificationManager.showEncodingWarningDialog();
-          console.log('Search result: User choice:', userChoice);
-          
-          if (userChoice === 'no') {
-            console.log('Search result: User chose not to open file');
-            return;
-          } else if (userChoice === 'yes') {
-            console.log('Search result: User chose to open file anyway');
-            const forceResult = await window.ipcRenderer.invoke('force-open-file', normalizedPath);
-            console.log('Search result: Force open result:', forceResult);
-            
-            if (forceResult.success) {
-              tabId = this.fileOpsManager.openFileInTab(normalizedPath, forceResult.content, forceResult.fileName, {
-                isPartial: forceResult.isPartial,
-                totalSize: forceResult.totalSize,
-                loadedSize: forceResult.loadedSize,
-                encodingWarning: forceResult.encodingWarning
-              });
-              
-              this.notificationManager.showWarning(`Opened ${forceResult.fileName} at line ${lineNumber} with encoding warnings`);
-            } else {
-              this.notificationManager.showError('Failed to open file: ' + forceResult.error);
-              return;
-            }
-          }
-        } else {
-          console.log('Search result: No warnings, opening file normally');
-          tabId = this.fileOpsManager.openFileInTab(normalizedPath, result.content, result.fileName, {
-            isPartial: result.isPartial,
-            totalSize: result.totalSize,
-            loadedSize: result.loadedSize,
-            encodingWarning: result.encodingWarning
-          });
-          
-          this.notificationManager.showSuccess(`Opened ${result.fileName} at line ${lineNumber}`);
-        }
-        
-        // Switch to explorer view and wait for editor to be ready
-        this.showExplorer();
-        
-        // Wait for the tab to switch and editor to update, then jump to line
-        setTimeout(() => {
-          this.editorManager.jumpToLine(lineNumber);
-        }, 200);
-        
-      } else {
-        this.notificationManager.showError('Error opening file: ' + (result.error || 'Unknown error'));
-      }
-    } catch (error) {
-      console.error('Error opening search result:', error);
-      this.notificationManager.showError('Error opening search result: ' + error.message);
-    }
-  }
-}
-
-// Initialize when DOM is loaded
-document.addEventListener('DOMContentLoaded', () => {
-  window.uiController = new UIController();
-});
-
-module.exports = UIController;
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/renderer_managers_EditorManager.js.html b/docs/renderer_managers_EditorManager.js.html deleted file mode 100644 index f328514..0000000 --- a/docs/renderer_managers_EditorManager.js.html +++ /dev/null @@ -1,628 +0,0 @@ - - - - - JSDoc: Source: renderer/managers/EditorManager.js - - - - - - - - - - -
- -

Source: renderer/managers/EditorManager.js

- - - - - - -
-
-
/**
- * Editor Manager - Handles editor functionality like gutter, status bar, formatting
- */
-
-// Import syntax highlighter
-const { highlightCppSyntax, applySyntaxHighlight, shouldHighlight } = require('../utils/syntaxHighlighter');
-const { detectFileType } = require('../utils/fileTypeUtils');
-
-class EditorManager {
-  constructor() {
-    this.editor = document.getElementById('editor');
-    this.gutter = document.getElementById('gutter');
-    this.lineCounter = document.getElementById('lineCounter');
-    this.currentFileType = 'Plain Text';
-    this.highlightEnabled = false;
-    this.updateTimer = null;
-    this.isUpdating = false;
-    this.init();
-  }
-
-  init() {
-    if (!this.editor || !this.gutter || !this.lineCounter) return;
-
-    // Maintain visual selection when editor loses focus
-    this.setupPersistentSelection();
-
-    // Make TAB key insert tab character in editor
-    this.editor.addEventListener('keydown', (e) => {
-      if (e.key === 'Tab') {
-        e.preventDefault();
-        document.execCommand('insertText', false, '\t');
-      } else if (e.key === 'Enter') {
-        e.preventDefault();
-        document.execCommand('insertLineBreak');
-      }
-    });
-
-    // Enhanced input handler with debounced syntax highlighting
-    this.editor.addEventListener('input', (e) => {
-      if (!this.isUpdating) {
-        this.updateGutter();
-        this.updateStatusBar();
-        this.debouncedHighlightUpdate();
-      }
-    });
-
-    this.editor.addEventListener('scroll', () => {
-      this.syncScroll();
-    });
-    this.editor.addEventListener('click', () => {
-      this.updateStatusBar();
-      this.updateGutter();
-    });
-    this.editor.addEventListener('keyup', () => {
-      this.updateStatusBar();
-      this.updateGutter();
-    });
-    
-    // Initialize
-    this.updateGutter();
-    this.updateStatusBar();
-  }
-
-  /**
-   * Save current cursor position
-   */
-  saveCursorPosition() {
-    const selection = window.getSelection();
-    if (!selection.rangeCount) return null;
-    
-    const range = selection.getRangeAt(0);
-    const preCaretRange = range.cloneRange();
-    preCaretRange.selectNodeContents(this.editor);
-    preCaretRange.setEnd(range.endContainer, range.endOffset);
-    
-    return preCaretRange.toString().length;
-  }
-
-  /**
-   * Restore cursor position
-   */
-  restoreCursorPosition(offset) {
-    if (offset === null || offset === undefined) return;
-    
-    const selection = window.getSelection();
-    const range = document.createRange();
-    
-    let currentOffset = 0;
-    const walker = document.createTreeWalker(
-      this.editor,
-      NodeFilter.SHOW_TEXT,
-      null,
-      false
-    );
-    
-    let node;
-    while (node = walker.nextNode()) {
-      const nodeLength = node.textContent.length;
-      if (currentOffset + nodeLength >= offset) {
-        const targetOffset = offset - currentOffset;
-        range.setStart(node, Math.min(targetOffset, node.textContent.length));
-        range.collapse(true);
-        selection.removeAllRanges();
-        selection.addRange(range);
-        return;
-      }
-      currentOffset += nodeLength;
-    }
-    
-    // If we didn't find the position, place cursor at end
-    if (this.editor.lastChild) {
-      range.selectNodeContents(this.editor);
-      range.collapse(false);
-      selection.removeAllRanges();
-      selection.addRange(range);
-    }
-  }
-
-  /**
-   * Update syntax highlighting with debouncing
-   */
-  debouncedHighlightUpdate() {
-    if (this.updateTimer) {
-      clearTimeout(this.updateTimer);
-    }
-    this.updateTimer = setTimeout(() => {
-      this.updateSyntaxHighlight();
-    }, 150);
-  }
-
-  /**
-   * Update syntax highlighting directly in editor
-   */
-  updateSyntaxHighlight() {
-    if (!this.editor || this.isUpdating) return;
-
-    this.isUpdating = true;
-    const savedOffset = this.saveCursorPosition();
-    
-    // Get plain text content
-    const text = this.getContent();
-    
-    // Apply syntax highlighting if enabled
-    if (this.highlightEnabled && shouldHighlight(this.currentFileType)) {
-      const highlighted = applySyntaxHighlight(text, this.currentFileType);
-      this.editor.innerHTML = highlighted;
-    } else {
-      this.editor.textContent = text;
-    }
-    
-    // Restore cursor position
-    this.restoreCursorPosition(savedOffset);
-    this.isUpdating = false;
-  }
-
-  /**
-   * Sync gutter scroll with editor
-   */
-  syncScroll() {
-    if (this.gutter && this.editor) {
-      this.gutter.scrollTop = this.editor.scrollTop;
-    }
-  }
-
-  /**
-   * Enhanced gutter line numbers with proper formatting (like VS Code)
-   */
-  updateGutter() {
-    if (!this.editor || !this.gutter) return;
-    
-    const text = this.getContent();
-    // Count lines properly - if text ends with newline, don't count it as extra line
-    let lines = 1;
-    if (text) {
-      const splitLines = text.split('\n');
-      lines = splitLines.length;
-      // If last element is empty string (trailing newline), don't count it
-      if (splitLines[splitLines.length - 1] === '') {
-        lines = Math.max(1, lines - 1);
-      }
-    }
-    
-    // Get current line number for highlighting
-    const currentLine = this.getCurrentLineNumber();
-    
-    const maxDigits = Math.max(2, lines.toString().length);
-    
-    // Clear gutter and rebuild with styled line numbers
-    this.gutter.innerHTML = '';
-    
-    // Create line numbers with current line highlighted
-    for (let i = 1; i <= lines; i++) {
-      const lineSpan = document.createElement('div');
-      lineSpan.textContent = i.toString().padStart(maxDigits, ' ');
-      lineSpan.style.lineHeight = '20px';
-      
-      if (i === currentLine) {
-        lineSpan.style.color = '#f0f6fc';
-        lineSpan.style.fontWeight = 'bold';
-        lineSpan.style.fontSize = '13px';
-      } else {
-        lineSpan.style.color = '#6e7681';
-        lineSpan.style.fontSize = '12px';
-      }
-      
-      this.gutter.appendChild(lineSpan);
-    }
-    
-    // Update gutter width based on content
-    const charWidth = 8; // Approximate character width in monospace font
-    this.gutter.style.width = Math.max(60, (maxDigits + 2) * charWidth) + 'px';
-  }
-  
-  /**
-   * Get current line number where cursor is
-   */
-  getCurrentLineNumber() {
-    if (!this.editor) return 1;
-    
-    const selection = window.getSelection();
-    if (!selection.rangeCount) return 1;
-    
-    const range = selection.getRangeAt(0);
-    const preCaretRange = range.cloneRange();
-    preCaretRange.selectNodeContents(this.editor);
-    preCaretRange.setEnd(range.endContainer, range.endOffset);
-    
-    const textBeforeCursor = preCaretRange.toString();
-    const lines = textBeforeCursor.split('\n');
-    return lines.length;
-  }
-
-  /**
-   * Enhanced status bar with cursor position tracking
-   */
-  updateStatusBar() {
-    if (!this.editor || !this.lineCounter) return;
-    
-    const selection = window.getSelection();
-    if (!selection.rangeCount) return;
-    
-    const range = selection.getRangeAt(0);
-    const preCaretRange = range.cloneRange();
-    preCaretRange.selectNodeContents(this.editor);
-    preCaretRange.setEnd(range.endContainer, range.endOffset);
-    
-    const textBeforeCursor = preCaretRange.toString();
-    const lines = textBeforeCursor.split('\n');
-    const line = lines.length;
-    const col = lines[lines.length - 1].length + 1;
-    
-    if (range.toString().length > 0) {
-      const selectedText = range.toString();
-      const selectedLines = selectedText.split('\n').length;
-      this.lineCounter.textContent = `Ln ${line}, Col ${col} (${selectedText.length} chars, ${selectedLines} lines selected)`;
-    } else {
-      this.lineCounter.textContent = `Ln ${line}, Col ${col}`;
-    }
-  }
-
-  /**
-   * Jump to specific line in editor
-   * @param {number} lineNumber - Line number to jump to
-   */
-  jumpToLine(lineNumber) {
-    console.log('Jumping to line:', lineNumber);
-    
-    if (!this.editor) {
-      console.error('Editor not found');
-      return;
-    }
-    
-    const text = this.getContent();
-    const lines = text.split('\n');
-    console.log('Total lines in editor:', lines.length);
-    
-    if (lineNumber > lines.length) {
-      console.warn('Line number exceeds file length');
-      return;
-    }
-    
-    // Calculate character position
-    let position = 0;
-    for (let i = 0; i < lineNumber - 1 && i < lines.length; i++) {
-      position += lines[i].length + 1; // +1 for newline
-    }
-    
-    console.log('Calculated position:', position);
-    
-    // Create range and set cursor
-    const range = document.createRange();
-    const sel = window.getSelection();
-    
-    let currentPos = 0;
-    let targetNode = null;
-    let targetOffset = 0;
-    
-    // Find the text node and offset
-    const walker = document.createTreeWalker(
-      this.editor,
-      NodeFilter.SHOW_TEXT,
-      null,
-      false
-    );
-    
-    let node;
-    while (node = walker.nextNode()) {
-      const nodeLength = node.textContent.length;
-      if (currentPos + nodeLength >= position) {
-        targetNode = node;
-        targetOffset = position - currentPos;
-        break;
-      }
-      currentPos += nodeLength;
-    }
-    
-    if (targetNode) {
-      range.setStart(targetNode, targetOffset);
-      range.collapse(true);
-      sel.removeAllRanges();
-      sel.addRange(range);
-      
-      // Scroll into view
-      const lineHeight = 20;
-      const targetScrollTop = Math.max(0, (lineNumber - 10) * lineHeight);
-      this.editor.scrollTop = targetScrollTop;
-    }
-    
-    this.editor.focus();
-    this.updateStatusBar();
-    
-    console.log('Successfully jumped to line:', lineNumber);
-  }
-
-  /**
-   * Enhanced formatting
-   */
-  formatCode() {
-    if (!this.editor) return;
-    
-    const text = this.getContent();
-    const lines = text.split('\n');
-    let indentLevel = 0;
-    const formatted = lines.map(line => {
-      const trimmed = line.trim();
-      if (trimmed.endsWith('{') || trimmed.endsWith(':')) {
-        const result = '  '.repeat(indentLevel) + trimmed;
-        indentLevel++;
-        return result;
-      } else if (trimmed.startsWith('}')) {
-        indentLevel = Math.max(0, indentLevel - 1);
-        return '  '.repeat(indentLevel) + trimmed;
-      } else {
-        return '  '.repeat(indentLevel) + trimmed;
-      }
-    }).join('\n');
-    
-    this.setContent(formatted);
-    
-    return formatted;
-  }
-
-  /**
-   * Toggle word wrap
-   */
-  toggleWordWrap() {
-    if (!this.editor) return;
-    
-    this.editor.style.whiteSpace = this.editor.style.whiteSpace === 'pre-wrap' ? 'pre' : 'pre-wrap';
-  }
-
-  /**
-   * Get editor content
-   * @returns {string} - Current editor content
-   */
-  getContent() {
-    if (!this.editor) return '';
-    // Replace <br> tags with newlines and get text content
-    return this.editor.textContent || '';
-  }
-
-  /**
-   * Set editor content
-   * @param {string} content - Content to set
-   */
-  setContent(content) {
-    if (this.editor) {
-      this.editor.textContent = content;
-      this.updateGutter();
-      this.updateStatusBar();
-      this.updateSyntaxHighlight();
-    }
-  }
-
-  /**
-   * Set file type (placeholder for future use)
-   * @param {string} filename - The filename to detect type from
-   */
-  setFileType(filename) {
-    this.currentFileType = detectFileType(filename);
-    
-    // Enable syntax highlighting for C/C++ files
-    this.highlightEnabled = shouldHighlight(this.currentFileType);
-    
-    // Update highlighting immediately
-    this.updateSyntaxHighlight();
-  }
-
-  /**
-   * Setup persistent selection highlighting (like VS Code)
-   * Keeps selection visually highlighted even when editor loses focus
-   */
-  setupPersistentSelection() {
-    // Create a canvas to measure text and draw highlights
-    const editorArea = document.getElementById('editor-area');
-    if (!editorArea) return;
-    
-    const canvas = document.createElement('canvas');
-    const ctx = canvas.getContext('2d');
-    ctx.font = '12px JetBrains Mono, monospace';
-    
-    // Create highlight overlay that will contain absolute positioned divs
-    const highlightOverlay = document.createElement('div');
-    highlightOverlay.id = 'selection-highlight-overlay';
-    highlightOverlay.style.cssText = `
-      position: absolute;
-      top: 0;
-      left: 0;
-      right: 0;
-      bottom: 0;
-      pointer-events: none;
-      z-index: 0;
-      overflow: hidden;
-    `;
-    
-    // Insert overlay after gutter but before editor
-    const gutter = document.getElementById('gutter');
-    if (gutter && gutter.nextSibling) {
-      editorArea.insertBefore(highlightOverlay, gutter.nextSibling);
-    } else {
-      editorArea.appendChild(highlightOverlay);
-    }
-    
-    // Make editor background transparent so overlay shows through
-    this.editor.style.position = 'relative';
-    this.editor.style.zIndex = '1';
-    this.editor.style.background = 'transparent';
-    
-    let savedSelection = null;
-    
-    const updateHighlight = () => {
-      highlightOverlay.innerHTML = '';
-      
-      if (!savedSelection || !this.editor.value) {
-        return;
-      }
-      
-      const { start, end } = savedSelection;
-      const text = this.editor.value;
-      const lines = text.split('\n');
-      
-      // Get editor dimensions and position
-      const editorRect = this.editor.getBoundingClientRect();
-      const editorAreaRect = editorArea.getBoundingClientRect();
-      const gutterWidth = 61; // gutter width + border
-      const lineHeight = 20;
-      const paddingLeft = 20;
-      const paddingTop = 20;
-      
-      // Calculate which lines contain the selection
-      let charCount = 0;
-      let startLine = -1, startCol = -1;
-      let endLine = -1, endCol = -1;
-      
-      for (let i = 0; i < lines.length; i++) {
-        const lineLength = lines[i].length;
-        
-        if (startLine === -1 && charCount + lineLength >= start) {
-          startLine = i;
-          startCol = start - charCount;
-        }
-        
-        if (endLine === -1 && charCount + lineLength >= end) {
-          endLine = i;
-          endCol = end - charCount;
-          break;
-        }
-        
-        charCount += lineLength + 1; // +1 for newline
-      }
-      
-      if (startLine === -1 || endLine === -1) return;
-      
-      // Draw highlight rectangles for each line in selection
-      for (let line = startLine; line <= endLine; line++) {
-        const lineText = lines[line];
-        let colStart = (line === startLine) ? startCol : 0;
-        let colEnd = (line === endLine) ? endCol : lineText.length;
-        
-        // Measure text width to get exact position
-        const beforeText = lineText.substring(0, colStart);
-        const selectedText = lineText.substring(colStart, colEnd);
-        
-        const startX = ctx.measureText(beforeText).width;
-        const width = ctx.measureText(selectedText).width;
-        
-        // Create highlight div for this line
-        const highlight = document.createElement('div');
-        highlight.style.cssText = `
-          position: absolute;
-          left: ${gutterWidth + paddingLeft + startX}px;
-          top: ${paddingTop + (line * lineHeight) - this.editor.scrollTop}px;
-          width: ${width + 2}px;
-          height: ${lineHeight}px;
-          background: #3a3d41;
-          pointer-events: none;
-        `;
-        
-        highlightOverlay.appendChild(highlight);
-      }
-    };
-    
-    // Save selection when editor loses focus
-    this.editor.addEventListener('blur', () => {
-      const start = this.editor.selectionStart;
-      const end = this.editor.selectionEnd;
-      if (start !== end) {
-        savedSelection = { start, end };
-        updateHighlight();
-      }
-    });
-    
-    // Clear highlight when editor gains focus
-    this.editor.addEventListener('focus', () => {
-      if (savedSelection) {
-        // Restore the selection
-        this.editor.setSelectionRange(savedSelection.start, savedSelection.end);
-      }
-      savedSelection = null;
-      highlightOverlay.innerHTML = '';
-    });
-    
-    // Update highlight position on scroll
-    this.editor.addEventListener('scroll', () => {
-      if (savedSelection) {
-        updateHighlight();
-      }
-    });
-    
-    // Clear on text change
-    this.editor.addEventListener('input', () => {
-      if (savedSelection) {
-        savedSelection = null;
-        highlightOverlay.innerHTML = '';
-      }
-    });
-  }
-  
-  escapeHtml(text) {
-    return text
-      .replace(/&/g, '&amp;')
-      .replace(/</g, '&lt;')
-      .replace(/>/g, '&gt;')
-      .replace(/"/g, '&quot;')
-      .replace(/'/g, '&#039;');
-  }
-
-  /**
-   * Focus the editor
-   */
-  focus() {
-    if (this.editor) {
-      this.editor.focus();
-    }
-  }
-}
-
-module.exports = EditorManager;
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/renderer_managers_FileOperationsManager.js.html b/docs/renderer_managers_FileOperationsManager.js.html deleted file mode 100644 index f216cc2..0000000 --- a/docs/renderer_managers_FileOperationsManager.js.html +++ /dev/null @@ -1,533 +0,0 @@ - - - - - JSDoc: Source: renderer/managers/FileOperationsManager.js - - - - - - - - - - -
- -

Source: renderer/managers/FileOperationsManager.js

- - - - - - -
-
-
/**
- * File Operations Manager - Handles all file operations via IPC communication.
- * 
- * This manager provides a high-level interface for file and workspace operations,
- * including opening files/workspaces, saving files, and managing the file tree.
- * It communicates with the main process through IPC to perform actual file system operations.
- * 
- * @class FileOperationsManager
- * @author CTrace GUI Team
- * @version 1.0.0
- * 
- * @example
- * const fileOpsManager = new FileOperationsManager(tabManager, notificationManager);
- * await fileOpsManager.openWorkspace();
- */
-class FileOperationsManager {
-  /**
-   * Creates an instance of FileOperationsManager.
-   * 
-   * @constructor
-   * @memberof FileOperationsManager
-   * @param {TabManager} tabManager - Tab manager instance for handling file tabs
-   * @param {NotificationManager} notificationManager - Notification manager for user feedback
-   */
-  constructor(tabManager, notificationManager) {
-    /**
-     * Tab manager instance
-     * @type {TabManager}
-     * @private
-     */
-    this.tabManager = tabManager;
-    
-    /**
-     * Notification manager instance
-     * @type {NotificationManager}
-     * @private
-     */
-    this.notificationManager = notificationManager;
-    
-    /**
-     * Currently opened workspace path
-     * @type {string|null}
-     * @private
-     */
-    this.currentWorkspacePath = null;
-  }
-
-  /**
-   * Opens a workspace folder dialog and loads the selected folder.
-   * 
-   * This method displays a folder selection dialog to the user, and if a folder
-   * is selected, it loads the folder structure and updates the UI to display
-   * the file tree. It also starts watching the workspace for file changes.
-   * 
-   * @async
-   * @memberof FileOperationsManager
-   * @returns {Promise<Object|undefined>} Result object with folder info, or undefined if canceled
-   * 
-   * @example
-   * const result = await fileOpsManager.openWorkspace();
-   * if (result && result.success) {
-   *   console.log('Workspace opened:', result.folderPath);
-   * }
-   */
-  async openWorkspace() {
-    try {
-      const result = await window.ipcRenderer.invoke('open-folder-dialog');
-      
-      if (result.success) {
-        this.currentWorkspacePath = result.folderPath;
-        const folderName = result.folderPath.split(/[/\\]/).pop();
-        
-        // Update workspace UI
-        this.updateWorkspaceUI(folderName, result.fileTree);
-        
-        this.notificationManager.showSuccess(`Workspace "${folderName}" opened successfully`);
-        
-        return result;
-      } else if (!result.canceled) {
-        this.notificationManager.showError('Failed to open workspace: ' + (result.error || 'Unknown error'));
-      }
-    } catch (error) {
-      this.notificationManager.showError('Error opening workspace: ' + error.message);
-    }
-  }
-
-  /**
-   * Open single file
-   */
-  async openFile() {
-    try {
-      console.log('Opening file dialog...');
-      const result = await window.ipcRenderer.invoke('open-file-dialog');
-      console.log('Open file result:', result);
-      
-      if (result.success) {
-        console.log('File opened successfully, checking for warnings...');
-        if (result.warning === 'encoding') {
-          console.log('Encoding warning detected, showing dialog...');
-          const userChoice = await this.notificationManager.showEncodingWarningDialog();
-          console.log('User choice:', userChoice);
-          
-          if (userChoice === 'no') {
-            console.log('User chose not to open file');
-            return;
-          } else if (userChoice === 'yes') {
-            console.log('User chose to open file anyway');
-            const forceResult = await window.ipcRenderer.invoke('force-open-file', result.filePath);
-            console.log('Force open result:', forceResult);
-            
-            if (forceResult.success) {
-              this.openFileInTab(forceResult.filePath, forceResult.content, forceResult.fileName, {
-                isPartial: forceResult.isPartial,
-                totalSize: forceResult.totalSize,
-                loadedSize: forceResult.loadedSize,
-                encodingWarning: forceResult.encodingWarning
-              });
-              this.notificationManager.showWarning(`File "${forceResult.fileName}" opened with encoding warnings`);
-            } else {
-              this.notificationManager.showError('Failed to open file: ' + forceResult.error);
-            }
-          }
-        } else {
-          console.log('No warnings, opening file normally');
-          this.openFileInTab(result.filePath, result.content, result.fileName, {
-            isPartial: result.isPartial,
-            totalSize: result.totalSize,
-            loadedSize: result.loadedSize
-          });
-          
-          if (result.isPartial) {
-            this.notificationManager.showInfo(`Large file "${result.fileName}" partially loaded (${this.formatFileSize(result.loadedSize)} of ${this.formatFileSize(result.totalSize)})`);
-          } else {
-            this.notificationManager.showSuccess(`File "${result.fileName}" opened successfully`);
-          }
-        }
-        
-        return result;
-      } else if (!result.canceled) {
-        this.notificationManager.showError('Failed to open file: ' + (result.error || 'Unknown error'));
-      }
-    } catch (error) {
-      this.notificationManager.showError('Error opening file: ' + error.message);
-    }
-  }
-
-  /**
-   * Open file in tab
-   * @param {string} filePath - File path
-   * @param {string} content - File content
-   * @param {string} fileName - File name
-   * @param {Object} fileInfo - File metadata
-   */
-  openFileInTab(filePath, content, fileName, fileInfo = {}) {
-    // Check if file is already open
-    const existingTabId = this.tabManager.findTabByPath(filePath);
-    if (existingTabId) {
-      this.tabManager.switchToTab(existingTabId);
-      return existingTabId;
-    }
-    
-    // Create new tab
-    const tabId = this.tabManager.createTab(fileName, filePath, content, fileInfo);
-    this.tabManager.switchToTab(tabId);
-    return tabId;
-  }
-
-  /**
-   * Save current file
-   */
-  async saveFile() {
-    try {
-      const currentTab = this.tabManager.getActiveTab();
-      if (!currentTab) {
-        // Create a new file if none exists
-        this.tabManager.createNewFile();
-        await new Promise(resolve => setTimeout(resolve, 100));
-        return await this.saveFile();
-      }
-      
-      // Update current tab content from editor
-      currentTab.content = this.tabManager.editorManager.getContent();
-      
-      if (currentTab.filePath) {
-        const result = await window.ipcRenderer.invoke('save-file', currentTab.filePath, currentTab.content);
-        if (result.success) {
-          this.tabManager.markTabClean(this.tabManager.activeTabId);
-          this.notificationManager.showSuccess('File saved successfully');
-          return result;
-        } else {
-          this.notificationManager.showError('Failed to save file: ' + result.error);
-        }
-      } else {
-        // Save as new file (untitled -> actual file)
-        const result = await this.saveAsFile();
-        // Syntax highlighting is already updated in saveAsFile
-        return result;
-      }
-    } catch (error) {
-      this.notificationManager.showError('Error saving file: ' + error.message);
-    }
-  }
-
-  /**
-   * Save file as
-   */
-  async saveAsFile() {
-    try {
-      const currentTab = this.tabManager.getActiveTab();
-      if (!currentTab) {
-        this.notificationManager.showWarning('No file to save');
-        return;
-      }
-      
-      currentTab.content = this.tabManager.editorManager.getContent();
-      
-      const result = await window.ipcRenderer.invoke('save-file-as', currentTab.content);
-      if (result.success) {
-        this.tabManager.updateTabFile(this.tabManager.activeTabId, result.filePath, result.fileName);
-        this.tabManager.markTabClean(this.tabManager.activeTabId);
-        
-        // Update file type and trigger syntax highlighting
-        this.tabManager.editorManager.setFileType(result.fileName);
-        
-        this.notificationManager.showSuccess(`File saved as "${result.fileName}"`);
-        return result;
-      } else if (!result.canceled) {
-        this.notificationManager.showError('Failed to save file: ' + result.error);
-      }
-    } catch (error) {
-      this.notificationManager.showError('Error saving file: ' + error.message);
-    }
-  }
-
-  /**
-   * Read file from file tree
-   * @param {string} filePath - File path to read
-   */
-  async readFileFromTree(filePath) {
-    try {
-      console.log('Reading file from tree:', filePath);
-      const result = await window.ipcRenderer.invoke('read-file', filePath);
-      console.log('File tree read result:', result);
-      
-      if (result.success) {
-        if (result.warning === 'encoding') {
-          console.log('File tree: Encoding warning detected, showing dialog...');
-          const userChoice = await this.notificationManager.showEncodingWarningDialog();
-          console.log('File tree: User choice:', userChoice);
-          
-          if (userChoice === 'no') {
-            console.log('File tree: User chose not to open file');
-            return;
-          } else if (userChoice === 'yes') {
-            console.log('File tree: User chose to open file anyway');
-            const forceResult = await window.ipcRenderer.invoke('force-open-file', filePath);
-            console.log('File tree: Force open result:', forceResult);
-            
-            if (forceResult.success) {
-              const tabId = this.openFileInTab(filePath, forceResult.content, forceResult.fileName, {
-                isPartial: forceResult.isPartial,
-                totalSize: forceResult.totalSize,
-                loadedSize: forceResult.loadedSize,
-                encodingWarning: forceResult.encodingWarning
-              });
-              
-              this.notificationManager.showWarning(`File "${forceResult.fileName}" opened with encoding warnings`);
-              return tabId;
-            } else {
-              this.notificationManager.showError('Failed to open file: ' + forceResult.error);
-            }
-          }
-        } else {
-          // Normal file opening - no encoding issues
-          console.log('File tree: No warnings, opening file normally');
-          const tabId = this.openFileInTab(filePath, result.content, result.fileName, {
-            isPartial: result.isPartial,
-            totalSize: result.totalSize,
-            loadedSize: result.loadedSize,
-            encodingWarning: result.encodingWarning
-          });
-          
-          return tabId;
-        }
-      } else {
-        this.notificationManager.showError('Failed to open file: ' + result.error);
-      }
-    } catch (error) {
-      this.notificationManager.showError('Error opening file: ' + error.message);
-    }
-  }
-
-  /**
-   * Load full file (for partially loaded large files)
-   * @param {string} filePath - File path
-   */
-  async loadFullFile(filePath) {
-    if (!filePath || !this.tabManager.activeTabId) return;
-    
-    try {
-      this.notificationManager.showInfo('Loading full file...');
-      const result = await window.ipcRenderer.invoke('force-load-full-file', filePath);
-      
-      if (result.success) {
-        const currentTab = this.tabManager.getActiveTab();
-        if (currentTab) {
-          // Update tab content and file info
-          currentTab.content = result.content;
-          currentTab.fileInfo = {
-            ...currentTab.fileInfo,
-            isPartial: false,
-            loadedSize: result.totalSize,
-            totalSize: result.totalSize
-          };
-          
-          // Update editor content
-          this.tabManager.editorManager.setContent(result.content);
-          
-          // Update tab appearance to remove warning
-          const tabElement = document.querySelector(`[data-tab-id="${this.tabManager.activeTabId}"]`);
-          if (tabElement) {
-            const tabLabel = tabElement.querySelector('.tab-label');
-            if (tabLabel) {
-              tabLabel.innerHTML = currentTab.fileName; // Remove warning indicator
-            }
-          }
-          
-          this.notificationManager.showSuccess(`Full file loaded (${Math.round(result.totalSize / 1024)}KB)`);
-        }
-      } else {
-        this.notificationManager.showError('Failed to load full file: ' + result.error);
-      }
-    } catch (error) {
-      console.error('Error loading full file:', error);
-      this.notificationManager.showError('Error loading full file');
-    }
-  }
-
-  /**
-   * Update workspace UI
-   * @param {string} folderName - Folder name
-   * @param {Array} fileTree - File tree structure
-   */
-  updateWorkspaceUI(folderName, fileTree) {
-    const workspaceName = document.getElementById('workspace-name');
-    const workspaceFolder = document.getElementById('workspace-folder');
-    const noWorkspace = document.getElementById('no-workspace');
-    const fileTreeElement = document.getElementById('file-tree');
-    
-    if (workspaceName) {
-      workspaceName.textContent = folderName.toUpperCase();
-    }
-    
-    if (workspaceFolder) {
-      workspaceFolder.style.display = 'block';
-    }
-    
-    if (noWorkspace) {
-      noWorkspace.style.display = 'none';
-    }
-    
-    if (fileTreeElement && fileTree) {
-      this.renderFileTree(fileTree, fileTreeElement);
-    }
-  }
-
-  /**
-   * Render file tree
-   * @param {Array} tree - File tree structure
-   * @param {Element} container - Container element
-   * @param {number} level - Nesting level
-   */
-  renderFileTree(tree, container = null, level = 0) {
-    if (!container) {
-      container = document.getElementById('file-tree');
-    }
-    
-    if (!container) return;
-    
-    if (level === 0) {
-      container.innerHTML = '';
-    }
-    
-    tree.forEach(item => {
-      const itemElement = document.createElement('div');
-      itemElement.style.marginLeft = (level * 16) + 'px';
-      
-      if (item.type === 'directory') {
-        itemElement.className = 'file-tree-item';
-        itemElement.innerHTML = `
-          <span class="icon">📁</span>
-          <span class="name">${item.name}</span>
-        `;
-        
-        let expanded = false;
-        let childContainer = null;
-        
-        itemElement.addEventListener('click', () => {
-          if (!expanded && item.children) {
-            childContainer = document.createElement('div');
-            itemElement.parentNode.insertBefore(childContainer, itemElement.nextSibling);
-            this.renderFileTree(item.children, childContainer, level + 1);
-            itemElement.querySelector('.icon').textContent = '📂';
-            expanded = true;
-          } else if (expanded && childContainer) {
-            childContainer.remove();
-            itemElement.querySelector('.icon').textContent = '📁';
-            expanded = false;
-          }
-        });
-      } else {
-        itemElement.className = 'file-tree-item';
-        itemElement.setAttribute('data-file-path', item.path);
-        const fileIcon = this.getFileIcon(item.name);
-        itemElement.innerHTML = `
-          <span class="icon">${fileIcon}</span>
-          <span class="name">${item.name}</span>
-        `;
-        
-        itemElement.addEventListener('click', async () => {
-          const tabId = await this.readFileFromTree(item.path);
-          if (tabId) {
-            // Highlight selected file
-            document.querySelectorAll('.file-tree-item').forEach(el => el.classList.remove('selected'));
-            itemElement.classList.add('selected');
-          }
-        });
-      }
-      
-      container.appendChild(itemElement);
-    });
-  }
-
-  /**
-   * Get file icon based on extension
-   * @param {string} filename - Filename
-   * @returns {string} - File icon emoji
-   */
-  getFileIcon(filename) {
-    const ext = filename.split('.').pop().toLowerCase();
-    const iconMap = {
-      'js': '🟨',
-      'ts': '🔷',
-      'html': '🟧',
-      'css': '🎨',
-      'json': '📋',
-      'md': '📝',
-      'py': '🐍',
-      'cpp': '⚙️',
-      'c': '⚙️',
-      'h': '📄',
-      'java': '☕',
-      'php': '🐘',
-      'rb': '💎',
-      'go': '🐹',
-      'rs': '🦀'
-    };
-    return iconMap[ext] || '📄';
-  }
-
-  /**
-   * Format file size for display
-   * @param {number} bytes - File size in bytes
-   * @returns {string} - Formatted file size
-   */
-  formatFileSize(bytes) {
-    if (bytes === 0) return '0 Bytes';
-    const k = 1024;
-    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
-    const i = Math.floor(Math.log(bytes) / Math.log(k));
-    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
-  }
-
-  /**
-   * Get current workspace path
-   * @returns {string|null} - Current workspace path
-   */
-  getCurrentWorkspacePath() {
-    return this.currentWorkspacePath;
-  }
-}
-
-module.exports = FileOperationsManager;
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/renderer_managers_NotificationManager.js.html b/docs/renderer_managers_NotificationManager.js.html deleted file mode 100644 index a9cfc7b..0000000 --- a/docs/renderer_managers_NotificationManager.js.html +++ /dev/null @@ -1,246 +0,0 @@ - - - - - JSDoc: Source: renderer/managers/NotificationManager.js - - - - - - - - - - -
- -

Source: renderer/managers/NotificationManager.js

- - - - - - -
-
-
/**
- * Notification Manager - Handles user notifications and messages
- */
-class NotificationManager {
-  constructor() {
-    this.notifications = [];
-  }
-
-  /**
-   * Show notification
-   * @param {string} message - Message to display
-   * @param {string} type - Notification type (success, error, info, warning)
-   * @param {number} duration - Duration in milliseconds (default 4000)
-   */
-  showNotification(message, type = 'info', duration = 4000) {
-    const colors = {
-      success: '#238636',
-      error: '#f85149',
-      info: '#1f6feb',
-      warning: '#d29922'
-    };
-    
-    const icons = {
-      success: '✓',
-      error: '✗',
-      warning: '⚠',
-      info: 'ℹ'
-    };
-    
-    const notification = document.createElement('div');
-    notification.innerHTML = `
-      <div style="position: fixed; top: 60px; left: 50%; transform: translateX(-50%); background: ${colors[type]}; color: white; padding: 10px 14px; border-radius: 6px; z-index: 10000; box-shadow: 0 4px 12px rgba(0,0,0,0.3); animation: fadeIn 0.3s ease; max-width: 300px; font-size: 13px; text-align: center;">
-        ${icons[type]} ${message}
-      </div>
-      <style>
-        @keyframes fadeIn {
-          from { opacity: 0; transform: translateX(-50%) translateY(-20px); }
-          to { opacity: 1; transform: translateX(-50%) translateY(0); }
-        }
-      </style>
-    `;
-    
-    document.body.appendChild(notification);
-    this.notifications.push(notification);
-    
-    setTimeout(() => {
-      if (notification.parentNode) {
-        notification.remove();
-      }
-      this.notifications = this.notifications.filter(n => n !== notification);
-    }, duration);
-  }
-
-  /**
-   * Show success notification
-   * @param {string} message - Message to display
-   */
-  showSuccess(message) {
-    this.showNotification(message, 'success');
-  }
-
-  /**
-   * Show error notification
-   * @param {string} message - Message to display
-   */
-  showError(message) {
-    this.showNotification(message, 'error');
-  }
-
-  /**
-   * Show warning notification
-   * @param {string} message - Message to display
-   */
-  showWarning(message) {
-    this.showNotification(message, 'warning');
-  }
-
-  /**
-   * Show info notification
-   * @param {string} message - Message to display
-   */
-  showInfo(message) {
-    this.showNotification(message, 'info');
-  }
-
-  /**
-   * Clear all notifications
-   */
-  clearAll() {
-    this.notifications.forEach(notification => {
-      if (notification.parentNode) {
-        notification.remove();
-      }
-    });
-    this.notifications = [];
-  }
-
-  /**
-   * Show encoding warning dialog
-   * @returns {Promise<string>} - User choice ('yes' or 'no')
-   */
-  showEncodingWarningDialog() {
-    return new Promise((resolve) => {
-      const overlay = document.createElement('div');
-      overlay.style.cssText = `
-        position: fixed;
-        top: 0;
-        left: 0;
-        right: 0;
-        bottom: 0;
-        background: rgba(0, 0, 0, 0.6);
-        display: flex;
-        align-items: center;
-        justify-content: center;
-        z-index: 10000;
-      `;
-      
-      const dialog = document.createElement('div');
-      dialog.style.cssText = `
-        background: #1c2128;
-        border: 1px solid #30363d;
-        border-radius: 6px;
-        padding: 24px;
-        max-width: 500px;
-        color: #f0f6fc;
-        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Noto Sans', Helvetica, Arial, sans-serif;
-      `;
-      
-      dialog.innerHTML = `
-        <h3 style="margin: 0 0 16px 0; color: #f85149;">⚠️ Non-UTF8 File Detected</h3>
-        <p style="margin: 0 0 20px 0; line-height: 1.5;">The file contains non UTF8 characters it may cause improper display. Open still?</p>
-        <div style="display: flex; gap: 12px; justify-content: flex-end;">
-          <button id="no-btn" style="
-            background: #21262d;
-            border: 1px solid #30363d;
-            color: #f0f6fc;
-            padding: 8px 16px;
-            border-radius: 6px;
-            cursor: pointer;
-            font-size: 14px;
-          ">No</button>
-          <button id="yes-btn" style="
-            background: #f85149;
-            border: 1px solid #f85149;
-            color: #ffffff;
-            padding: 8px 16px;
-            border-radius: 6px;
-            cursor: pointer;
-            font-size: 14px;
-          ">Yes</button>
-        </div>
-      `;
-      
-      overlay.appendChild(dialog);
-      document.body.appendChild(overlay);
-      
-      const noBtn = dialog.querySelector('#no-btn');
-      const yesBtn = dialog.querySelector('#yes-btn');
-      
-      noBtn.addEventListener('click', () => {
-        document.body.removeChild(overlay);
-        resolve('no');
-      });
-      
-      yesBtn.addEventListener('click', () => {
-        document.body.removeChild(overlay);
-        resolve('yes');
-      });
-      
-      // Close on escape key
-      const handleKeyDown = (e) => {
-        if (e.key === 'Escape') {
-          document.body.removeChild(overlay);
-          document.removeEventListener('keydown', handleKeyDown);
-          resolve('no');
-        }
-      };
-      document.addEventListener('keydown', handleKeyDown);
-    });
-  }
-
-  /**
-   * Show confirmation dialog
-   * @param {string} message - Message to display
-   * @param {string} title - Dialog title
-   * @returns {Promise<boolean>} - User confirmation
-   */
-  showConfirmDialog(message, title = 'Confirm') {
-    return new Promise((resolve) => {
-      const result = confirm(`${title}: ${message}`);
-      resolve(result);
-    });
-  }
-}
-
-module.exports = NotificationManager;
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/renderer_managers_SearchManager.js.html b/docs/renderer_managers_SearchManager.js.html deleted file mode 100644 index 98cfdc8..0000000 --- a/docs/renderer_managers_SearchManager.js.html +++ /dev/null @@ -1,450 +0,0 @@ - - - - - JSDoc: Source: renderer/managers/SearchManager.js - - - - - - - - - - -
- -

Source: renderer/managers/SearchManager.js

- - - - - - -
-
-
/**
- * Search Manager - Handles search functionality
- */
-class SearchManager {
-  constructor(editorManager, notificationManager) {
-    this.editorManager = editorManager;
-    this.notificationManager = notificationManager;
-    this.currentSearchMatches = [];
-    this.currentMatchIndex = -1;
-    this.searchTimeout = null;
-    this.init();
-  }
-
-  init() {
-    this.setupSearchWidget();
-    this.setupGoToLineDialog();
-    this.setupSidebarSearch();
-  }
-
-  /**
-   * Setup search widget functionality
-   */
-  setupSearchWidget() {
-    const widgetSearchInput = document.getElementById('widget-search-input');
-    if (widgetSearchInput) {
-      widgetSearchInput.addEventListener('input', (e) => {
-        this.performLiveSearch(e.target.value);
-      });
-    }
-  }
-
-  /**
-   * Setup go to line dialog
-   */
-  setupGoToLineDialog() {
-    // Event handlers will be attached by the UI controller
-  }
-
-  /**
-   * Setup sidebar search
-   */
-  setupSidebarSearch() {
-    const searchInput = document.getElementById('sidebar-search-input');
-    if (searchInput) {
-      searchInput.addEventListener('input', (e) => {
-        const searchTerm = e.target.value.trim();
-        
-        if (this.searchTimeout) {
-          clearTimeout(this.searchTimeout);
-        }
-        
-        if (searchTerm.length >= 2 && this.currentWorkspacePath) {
-          this.searchTimeout = setTimeout(() => {
-            this.performWorkspaceSearch(searchTerm);
-          }, 300);
-        } else {
-          this.clearSearchResults();
-        }
-      });
-    }
-  }
-
-  /**
-   * Show find dialog
-   */
-  showFindDialog() {
-    const widget = document.getElementById('search-widget');
-    const input = document.getElementById('widget-search-input');
-    widget.classList.add('visible');
-    input.focus();
-    input.select();
-  }
-
-  /**
-   * Close search widget
-   */
-  closeSearchWidget() {
-    const widget = document.getElementById('search-widget');
-    widget.classList.remove('visible');
-    this.clearSearchHighlights();
-    this.currentSearchMatches = [];
-    this.currentMatchIndex = -1;
-    this.updateSearchResults();
-  }
-
-  /**
-   * Perform live search in current document
-   * @param {string} searchText - Text to search for
-   */
-  performLiveSearch(searchText) {
-    this.clearSearchHighlights();
-    this.currentSearchMatches = [];
-    this.currentMatchIndex = -1;
-
-    if (!searchText.trim()) {
-      this.updateSearchResults();
-      return;
-    }
-
-    const text = this.editorManager.getContent();
-    
-    if (!text) {
-      this.updateSearchResults();
-      return;
-    }
-
-    try {
-      const regex = new RegExp(searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
-      let match;
-      
-      while ((match = regex.exec(text)) !== null) {
-        this.currentSearchMatches.push({
-          start: match.index,
-          end: match.index + match[0].length,
-          text: match[0]
-        });
-        
-        // Prevent infinite loops with zero-length matches
-        if (match.index === regex.lastIndex) {
-          regex.lastIndex++;
-        }
-      }
-
-      if (this.currentSearchMatches.length > 0) {
-        this.currentMatchIndex = 0;
-        this.highlightAllMatches();
-      }
-    } catch (e) {
-      console.warn('Invalid search regex:', e);
-    }
-
-    this.updateSearchResults();
-  }
-
-  /**
-   * Search next match
-   */
-  searchNext() {
-    if (this.currentSearchMatches.length === 0) return;
-    
-    this.currentMatchIndex = (this.currentMatchIndex + 1) % this.currentSearchMatches.length;
-    this.highlightAllMatches();
-    this.focusOnCurrentMatch();
-    this.updateSearchResults();
-  }
-
-  /**
-   * Search previous match
-   */
-  searchPrev() {
-    if (this.currentSearchMatches.length === 0) return;
-    
-    this.currentMatchIndex = this.currentMatchIndex <= 0 
-      ? this.currentSearchMatches.length - 1 
-      : this.currentMatchIndex - 1;
-    this.highlightAllMatches();
-    this.focusOnCurrentMatch();
-    this.updateSearchResults();
-  }
-
-  /**
-   * Update search results display
-   */
-  updateSearchResults() {
-    const resultsText = document.getElementById('search-results-text');
-    const prevBtn = document.getElementById('search-prev');
-    const nextBtn = document.getElementById('search-next');
-
-    if (!resultsText || !prevBtn || !nextBtn) return;
-
-    if (this.currentSearchMatches.length === 0) {
-      resultsText.textContent = 'No results';
-      prevBtn.disabled = true;
-      nextBtn.disabled = true;
-    } else {
-      resultsText.textContent = `${this.currentMatchIndex + 1} of ${this.currentSearchMatches.length}`;
-      prevBtn.disabled = false;
-      nextBtn.disabled = false;
-    }
-  }
-
-  /**
-   * Focus on current match
-   */
-  focusOnCurrentMatch() {
-    if (this.currentMatchIndex >= 0 && this.currentMatchIndex < this.currentSearchMatches.length) {
-      const editor = this.editorManager.editor;
-      const match = this.currentSearchMatches[this.currentMatchIndex];
-      
-      editor.focus();
-      editor.setSelectionRange(match.start, match.end);
-      
-      // Scroll to make the match visible
-      const lines = editor.value.substring(0, match.start).split('\n');
-      const lineNumber = lines.length;
-      const approximateLineHeight = 20;
-      const targetScrollTop = (lineNumber - 5) * approximateLineHeight;
-      
-      editor.scrollTop = Math.max(0, targetScrollTop);
-      
-      setTimeout(() => {
-        if (editor.setSelectionRange) {
-          editor.setSelectionRange(match.start, match.end);
-        }
-      }, 10);
-    }
-  }
-
-  /**
-   * Highlight all matches
-   */
-  highlightAllMatches() {
-    // For now, we'll keep it simple and just highlight the current match when navigating
-  }
-
-  /**
-   * Clear search highlights
-   */
-  clearSearchHighlights() {
-    // Clear any visual highlights if implemented
-  }
-
-  /**
-   * Show go to line dialog
-   */
-  showGoToLineDialog() {
-    const dialog = document.getElementById('goto-dialog');
-    const input = document.getElementById('goto-input');
-    
-    // Set max value based on current content
-    const text = this.editorManager.getContent();
-    if (text) {
-      const lineCount = text.split('\n').length;
-      input.max = lineCount;
-    }
-    
-    dialog.classList.add('visible');
-    input.focus();
-    input.select();
-  }
-
-  /**
-   * Close go to line dialog
-   */
-  closeGoToLineDialog() {
-    const dialog = document.getElementById('goto-dialog');
-    dialog.classList.remove('visible');
-  }
-
-  /**
-   * Perform go to line
-   */
-  performGoToLine() {
-    const input = document.getElementById('goto-input');
-    const lineNumber = parseInt(input.value);
-    
-    if (!lineNumber || lineNumber < 1) {
-      this.notificationManager.showError('Please enter a valid line number');
-      return;
-    }
-    
-    const text = this.editorManager.getContent();
-    if (text) {
-      const lines = text.split('\n');
-      
-      if (lineNumber > lines.length) {
-        this.notificationManager.showError(`Line ${lineNumber} does not exist. Maximum line is ${lines.length}`);
-        return;
-      }
-      
-      this.editorManager.jumpToLine(lineNumber);
-      this.notificationManager.showSuccess(`Jumped to line ${lineNumber}`);
-    } else {
-      this.notificationManager.showError('No file is currently open');
-    }
-    
-    this.closeGoToLineDialog();
-  }
-
-  /**
-   * Perform workspace search
-   * @param {string} searchTerm - Term to search for
-   */
-  async performWorkspaceSearch(searchTerm) {
-    if (!this.currentWorkspacePath) {
-      this.displaySearchResults([], searchTerm);
-      return;
-    }
-
-    try {
-      const searchResults = document.getElementById('search-results');
-      if (searchResults) {
-        searchResults.innerHTML = '<div style="color: #7d8590; padding: 12px; text-align: center;">Searching...</div>';
-      }
-      
-      const result = await window.ipcRenderer.invoke('search-in-files', searchTerm, this.currentWorkspacePath);
-      
-      if (result.success) {
-        this.displaySearchResults(result.results, searchTerm);
-      } else {
-        const searchResults = document.getElementById('search-results');
-        if (searchResults) {
-          searchResults.innerHTML = '<div style="color: #f85149; padding: 12px;">Search failed: ' + result.error + '</div>';
-        }
-      }
-    } catch (error) {
-      const searchResults = document.getElementById('search-results');
-      if (searchResults) {
-        searchResults.innerHTML = '<div style="color: #f85149; padding: 12px;">Search error: ' + error.message + '</div>';
-      }
-    }
-  }
-
-  /**
-   * Display search results in sidebar
-   * @param {Array} results - Search results
-   * @param {string} searchTerm - Search term
-   */
-  displaySearchResults(results, searchTerm) {
-    const searchResults = document.getElementById('search-results');
-    if (!searchResults) return;
-
-    if (results.length === 0) {
-      searchResults.innerHTML = '<div style="color: #7d8590; padding: 12px; text-align: center;">No results found</div>';
-      return;
-    }
-
-    const groupedResults = {};
-    results.forEach(result => {
-      if (!groupedResults[result.file]) {
-        groupedResults[result.file] = [];
-      }
-      groupedResults[result.file].push(result);
-    });
-
-    let html = '<div style="display: flex; flex-direction: column; gap: 8px;">';
-    
-    Object.keys(groupedResults).forEach(file => {
-      const fileResults = groupedResults[file];
-      const fileName = file.split(/[/\\]/).pop();
-      const relativePath = file.replace(this.currentWorkspacePath, '').replace(/^[/\\]/, '');
-      
-      // Escape the file path properly for onclick
-      const escapedPath = file.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
-      
-      html += `<div class="search-result-item" style="display: flex; flex-direction: column;">`;
-      html += `<div class="search-result-file" onclick="window.searchManager.openSearchResult('${escapedPath}', ${fileResults[0].line})" style="margin-bottom: 4px;">${fileName}</div>`;
-      html += `<div class="search-result-line" style="margin-bottom: 6px;">${relativePath} • ${fileResults.length} result${fileResults.length > 1 ? 's' : ''}</div>`;
-      
-      // Show each line result individually in vertical layout
-      html += '<div style="display: flex; flex-direction: column; gap: 2px;">';
-      fileResults.forEach(result => {
-        const highlightedContent = result.content.replace(
-          new RegExp(searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'),
-          match => `<span class="search-highlight">${match}</span>`
-        );
-        html += `<div class="search-result-content" onclick="window.searchManager.openSearchResult('${escapedPath}', ${result.line}); event.stopPropagation();" style="display: block; margin: 2px 0; padding: 4px 6px; cursor: pointer; border-radius: 3px; background: #161b22; border-left: 2px solid #1f6feb;" onmouseover="this.style.background='#30363d'" onmouseout="this.style.background='#161b22'">`;
-        html += `<div style="color: #7d8590; font-size: 10px; margin-bottom: 2px;">Line ${result.line}:</div>`;
-        html += `<div style="font-family: monospace; font-size: 11px;">${highlightedContent}</div>`;
-        html += `</div>`;
-      });
-      html += '</div>';
-      
-      html += '</div>';
-    });
-    
-    html += '</div>';
-    searchResults.innerHTML = html;
-  }
-
-  /**
-   * Clear search results
-   */
-  clearSearchResults() {
-    const searchResults = document.getElementById('search-results');
-    if (searchResults) {
-      searchResults.innerHTML = '';
-    }
-  }
-
-  /**
-   * Open search result (to be implemented by parent controller)
-   * @param {string} filePath - File path
-   * @param {number} lineNumber - Line number
-   */
-  async openSearchResult(filePath, lineNumber) {
-    // This will be implemented by the main controller
-    console.log('Open search result requested:', filePath, 'at line', lineNumber);
-  }
-
-  /**
-   * Set current workspace path
-   * @param {string} workspacePath - Workspace path
-   */
-  setWorkspacePath(workspacePath) {
-    this.currentWorkspacePath = workspacePath;
-  }
-}
-
-module.exports = SearchManager;
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/renderer_managers_TabManager.js.html b/docs/renderer_managers_TabManager.js.html deleted file mode 100644 index d698d3b..0000000 --- a/docs/renderer_managers_TabManager.js.html +++ /dev/null @@ -1,465 +0,0 @@ - - - - - JSDoc: Source: renderer/managers/TabManager.js - - - - - - - - - - -
- -

Source: renderer/managers/TabManager.js

- - - - - - -
-
-
/**
- * Tab Manager - Handles all tab operations including creation, switching, and closing.
- * 
- * This manager provides a complete tab interface similar to modern code editors,
- * allowing users to work with multiple files simultaneously. It manages tab state,
- * coordinates with the editor manager, and handles file modifications tracking.
- * 
- * @class TabManager
- * @author CTrace GUI Team
- * @version 1.0.0
- * 
- * @example
- * const tabManager = new TabManager(editorManager, notificationManager);
- * const tabId = tabManager.createTab('example.js', '/path/to/example.js', 'console.log("Hello")');
- */
-class TabManager {
-  /**
-   * Creates an instance of TabManager.
-   * 
-   * @constructor
-   * @memberof TabManager
-   * @param {EditorManager} editorManager - Editor manager instance for content management
-   * @param {NotificationManager} notificationManager - Notification manager for user feedback
-   */
-  constructor(editorManager, notificationManager) {
-    /**
-     * Editor manager instance
-     * @type {EditorManager}
-     * @private
-     */
-    this.editorManager = editorManager;
-    
-    /**
-     * Notification manager instance
-     * @type {NotificationManager}
-     * @private
-     */
-    this.notificationManager = notificationManager;
-    
-    /**
-     * Counter for generating unique tab IDs
-     * @type {number}
-     * @private
-     */
-    this.tabIdCounter = 0;
-    
-    /**
-     * Currently active tab ID
-     * @type {string|null}
-     */
-    this.activeTabId = null;
-    
-    /**
-     * Map of open tabs with their data
-     * @type {Map<string, Object>}
-     * @private
-     */
-    this.openTabs = new Map();
-    
-    /**
-     * DOM element containing the tabs
-     * @type {HTMLElement}
-     * @private
-     */
-    this.tabsContainer = document.getElementById('tabs-container');
-    
-    /**
-     * Welcome screen DOM element
-     * @type {HTMLElement}
-     * @private
-     */
-    this.welcomeScreen = document.getElementById('welcome-screen');
-    
-    /**
-     * Editor area DOM element
-     * @type {HTMLElement}
-     * @private
-     */
-    this.editorArea = document.getElementById('editor-area');
-  }
-
-  /**
-   * Create a new tab
-   * @param {string} fileName - Tab file name
-   * @param {string} filePath - File path (optional)
-   * @param {string} content - File content
-   * @param {Object} fileInfo - File metadata
-   * @returns {string} - Tab ID
-   */
-  createTab(fileName, filePath = null, content = '', fileInfo = {}) {
-    // Show editor area if this is the first tab
-    if (this.openTabs.size === 0) {
-      this.showEditor();
-    }
-    
-    const tabId = 'tab_' + (++this.tabIdCounter);
-    
-    // Create tab data
-    this.openTabs.set(tabId, {
-      filePath: filePath,
-      content: content,
-      modified: false,
-      fileName: fileName,
-      fileInfo: fileInfo // Store file metadata
-    });
-
-    // Create tab element
-    const tabElement = document.createElement('div');
-    tabElement.className = 'tab';
-    tabElement.setAttribute('data-tab-id', tabId);
-    tabElement.setAttribute('data-file-path', filePath || '');
-    
-    // Add warning indicator if file has encoding issues or is partial
-    const warningIndicator = (fileInfo.encodingWarning || fileInfo.isPartial) ? 
-      `<span class="tab-warning" title="${fileInfo.encodingWarning ? 'Encoding Warning' : ''}${fileInfo.isPartial ? 'File Partially Loaded' : ''}">⚠️</span>` : '';
-    
-    tabElement.innerHTML = `
-      <div class="tab-label">${fileName}${warningIndicator}</div>
-      <div class="tab-close" onclick="window.tabManager.closeTab(event, '${tabId}')">×</div>
-    `;
-    
-    tabElement.addEventListener('click', (e) => {
-      if (!e.target.classList.contains('tab-close')) {
-        this.switchToTab(tabId);
-      }
-    });
-    
-    this.tabsContainer.appendChild(tabElement);
-    return tabId;
-  }
-
-  /**
-   * Switch to a specific tab
-   * @param {string} tabId - Tab ID to switch to
-   */
-  switchToTab(tabId) {
-    // Save current tab content if we have an active tab
-    if (this.activeTabId && this.openTabs.has(this.activeTabId)) {
-      const currentTab = this.openTabs.get(this.activeTabId);
-      currentTab.content = this.editorManager.getContent();
-    }
-
-    // Update active tab
-    this.activeTabId = tabId;
-    const newTab = this.openTabs.get(tabId);
-    
-    if (newTab) {
-      // Update editor
-      this.editorManager.setContent(newTab.content);
-      
-      // Set file type for syntax highlighting
-      if (newTab.fileName) {
-        this.editorManager.setFileType(newTab.fileName);
-      }
-      
-      // Update tab appearance
-      document.querySelectorAll('.tab').forEach(tab => {
-        tab.classList.remove('active');
-      });
-      const tabElement = document.querySelector(`[data-tab-id="${tabId}"]`);
-      if (tabElement) {
-        tabElement.classList.add('active');
-      }
-      
-      // Update file tree selection
-      if (newTab.filePath) {
-        document.querySelectorAll('.file-tree-item').forEach(el => el.classList.remove('selected'));
-        const fileTreeItem = document.querySelector(`[data-file-path="${newTab.filePath}"]`);
-        if (fileTreeItem) {
-          fileTreeItem.classList.add('selected');
-        }
-      }
-
-      // Emit tab switch event for other components
-      this.onTabSwitch(newTab);
-    }
-  }
-
-  /**
-   * Close a tab
-   * @param {Event} event - Click event
-   * @param {string} tabId - Tab ID to close
-   */
-  closeTab(event, tabId) {
-    event.stopPropagation();
-    
-    const tab = this.openTabs.get(tabId);
-    if (!tab) return;
-    
-    // Check if modified
-    if (tab.modified) {
-      const result = confirm(`${tab.fileName} has unsaved changes. Do you want to close it anyway?`);
-      if (!result) return;
-    }
-    
-    // Remove tab element
-    const tabElement = document.querySelector(`[data-tab-id="${tabId}"]`);
-    if (tabElement) {
-      tabElement.remove();
-    }
-    
-    // Remove from data
-    this.openTabs.delete(tabId);
-    
-    // If closing active tab, switch to another tab or show welcome screen
-    if (this.activeTabId === tabId) {
-      const remainingTabs = Array.from(this.openTabs.keys());
-      if (remainingTabs.length > 0) {
-        this.switchToTab(remainingTabs[remainingTabs.length - 1]);
-      } else {
-        // No more tabs, show welcome screen
-        this.activeTabId = null;
-        this.showWelcomeScreen();
-      }
-    }
-  }
-
-  /**
-   * Mark tab as modified
-   * @param {string} tabId - Tab ID
-   */
-  markTabModified(tabId) {
-    const tab = this.openTabs.get(tabId);
-    if (tab && !tab.modified) {
-      tab.modified = true;
-      const tabElement = document.querySelector(`[data-tab-id="${tabId}"]`);
-      if (tabElement) {
-        tabElement.classList.add('modified');
-      }
-    }
-  }
-
-  /**
-   * Mark tab as clean (not modified)
-   * @param {string} tabId - Tab ID
-   */
-  markTabClean(tabId) {
-    const tab = this.openTabs.get(tabId);
-    if (tab && tab.modified) {
-      tab.modified = false;
-      const tabElement = document.querySelector(`[data-tab-id="${tabId}"]`);
-      if (tabElement) {
-        tabElement.classList.remove('modified');
-      }
-    }
-  }
-
-  /**
-   * Check if file is already open in a tab
-   * @param {string} filePath - File path to check
-   * @returns {string|null} - Tab ID if found, null otherwise
-   */
-  findTabByPath(filePath) {
-    for (const [tabId, tab] of this.openTabs) {
-      if (tab.filePath === filePath) {
-        return tabId;
-      }
-    }
-    return null;
-  }
-
-  /**
-   * Get current active tab
-   * @returns {Object|null} - Active tab data or null
-   */
-  getActiveTab() {
-    return this.activeTabId ? this.openTabs.get(this.activeTabId) : null;
-  }
-
-  /**
-   * Update tab file info (for file operations)
-   * @param {string} tabId - Tab ID
-   * @param {string} filePath - New file path
-   * @param {string} fileName - New file name
-   */
-  updateTabFile(tabId, filePath, fileName) {
-    const tab = this.openTabs.get(tabId);
-    if (tab) {
-      tab.filePath = filePath;
-      tab.fileName = fileName;
-      
-      // Update tab label
-      const tabElement = document.querySelector(`[data-tab-id="${tabId}"]`);
-      if (tabElement) {
-        const labelElement = tabElement.querySelector('.tab-label');
-        if (labelElement) {
-          labelElement.textContent = fileName;
-        }
-        tabElement.setAttribute('data-file-path', filePath);
-      }
-    }
-  }
-
-  /**
-   * Show welcome screen
-   */
-  showWelcomeScreen() {
-    this.welcomeScreen.style.display = 'flex';
-    this.editorArea.style.display = 'none';
-    this.tabsContainer.style.display = 'none';
-  }
-
-  /**
-   * Show editor
-   */
-  showEditor() {
-    this.welcomeScreen.style.display = 'none';
-    this.editorArea.style.display = 'flex';
-    this.tabsContainer.style.display = 'flex';
-  }
-
-  /**
-   * Handle tab content changes (for modification tracking)
-   * @param {string} tabId - Tab ID
-   * @param {string} newContent - New content
-   */
-  handleContentChange(tabId, newContent) {
-    const tab = this.openTabs.get(tabId);
-    if (tab && tab.content !== newContent) {
-      tab.content = newContent;
-      this.markTabModified(tabId);
-    }
-  }
-
-  /**
-   * Callback for when tab switches (for other components to listen to)
-   * @param {Object} tabData - Tab data
-   */
-  onTabSwitch(tabData) {
-    // Update file type in status bar if file type utils are available
-    if (window.updateFileTypeStatus) {
-      window.updateFileTypeStatus(tabData.fileName);
-    }
-    
-    // Update file status
-    this.updateFileStatus(tabData);
-  }
-
-  /**
-   * Update file status indicator
-   * @param {Object} tabData - Tab data
-   */
-  updateFileStatus(tabData) {
-    const fileStatusElement = document.getElementById('fileStatus');
-    if (fileStatusElement && tabData.fileInfo) {
-      const { fileInfo } = tabData;
-      let statusText = 'UTF-8';
-      let statusStyle = '';
-      
-      if (fileInfo.encodingWarning) {
-        statusText = '⚠️ Non-UTF8';
-        statusStyle = 'color: #f85149; cursor: pointer;';
-        fileStatusElement.title = 'File may contain non-UTF8 characters';
-      } else if (fileInfo.isPartial) {
-        const loadedKB = Math.round(fileInfo.loadedSize / 1024);
-        const totalKB = Math.round(fileInfo.totalSize / 1024);
-        statusText = `📄 Partial (${loadedKB}KB/${totalKB}KB)`;
-        statusStyle = 'color: #f0883e; cursor: pointer;';
-        fileStatusElement.title = 'Click to load full file';
-        fileStatusElement.onclick = () => this.onLoadFullFile(tabData.filePath);
-      } else {
-        statusText = 'UTF-8';
-        statusStyle = '';
-        fileStatusElement.onclick = null;
-        fileStatusElement.title = '';
-      }
-      
-      fileStatusElement.textContent = statusText;
-      fileStatusElement.style.cssText = statusStyle;
-    }
-  }
-
-  /**
-   * Callback for loading full file (to be implemented by parent)
-   * @param {string} filePath - File path to load
-   */
-  onLoadFullFile(filePath) {
-    // This will be set by the main UI controller
-    console.log('Load full file requested for:', filePath);
-  }
-
-  /**
-   * Create a new untitled file tab
-   * @returns {string} - New tab ID
-   */
-  createNewFile() {
-    const fileName = 'untitled-' + (this.tabIdCounter + 1);
-    const tabId = this.createTab(fileName);
-    this.switchToTab(tabId);
-    this.editorManager.focus();
-    return tabId;
-  }
-
-  /**
-   * Switch to next tab
-   */
-  switchToNextTab() {
-    const tabIds = Array.from(this.openTabs.keys());
-    if (tabIds.length > 0 && this.activeTabId) {
-      const currentIndex = tabIds.indexOf(this.activeTabId);
-      const nextIndex = (currentIndex + 1) % tabIds.length;
-      this.switchToTab(tabIds[nextIndex]);
-    }
-  }
-
-  /**
-   * Get all open tabs count
-   * @returns {number} - Number of open tabs
-   */
-  getTabCount() {
-    return this.openTabs.size;
-  }
-}
-
-module.exports = TabManager;
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/renderer_managers_VisualyzerManager.js.html b/docs/renderer_managers_VisualyzerManager.js.html deleted file mode 100644 index 9dde487..0000000 --- a/docs/renderer_managers_VisualyzerManager.js.html +++ /dev/null @@ -1,1000 +0,0 @@ - - - - - JSDoc: Source: renderer/managers/VisualyzerManager.js - - - - - - - - - - -
- -

Source: renderer/managers/VisualyzerManager.js

- - - - - - -
-
-
/**
- * Visualyzer Manager - Interactive Graph Visualization
- * Uses D3.js for force-directed graph rendering
- */
-
-class VisualyzerManager {
-  constructor() {
-    this.currentGraph = null;
-    this.parsedData = null;
-    this.svg = null;
-    this.simulation = null;
-    this.selectedNode = null;
-    this.expandedNodes = new Set();
-    this.visibleNodes = new Set();
-    this.visibleEdges = new Set();
-    
-    // Color mapping for node types
-    this.typeColors = {
-      'container': { fill: '#ffa657', stroke: '#f0883e', label: 'Container' },
-      'F': { fill: '#58a6ff', stroke: '#1f6feb', label: 'Function' },
-      'O': { fill: '#56d364', stroke: '#238636', label: 'Object' },
-      'default': { fill: '#8b949e', stroke: '#484f58', label: 'Other' }
-    };
-    
-    this.initializeElements();
-    this.setupEventListeners();
-  }
-
-  /**
-   * Get node color based on type
-   * @param {Object} node - Node data
-   * @returns {Object} Color object with fill and stroke
-   */
-  getNodeColor(node) {
-    if (node.isContainer) {
-      return this.typeColors['container'];
-    }
-    if (node.type && this.typeColors[node.type]) {
-      return this.typeColors[node.type];
-    }
-    return this.typeColors['default'];
-  }
-
-  /**
-   * Initialize DOM elements
-   */
-  initializeElements() {
-    this.dropzone = document.querySelector('.visualyzer-dropzone');
-    this.canvas = document.querySelector('.visualyzer-canvas');
-    this.controls = document.querySelector('.visualyzer-controls');
-    this.info = document.querySelector('.visualyzer-info');
-    this.filename = document.querySelector('.visualyzer-filename');
-    this.stats = document.querySelector('.visualyzer-stats');
-  }
-
-  /**
-   * Setup event listeners
-   */
-  setupEventListeners() {
-    // Drag and drop
-    this.dropzone.addEventListener('dragover', (e) => {
-      e.preventDefault();
-      this.dropzone.classList.add('dragover');
-    });
-
-    this.dropzone.addEventListener('dragleave', () => {
-      this.dropzone.classList.remove('dragover');
-    });
-
-    this.dropzone.addEventListener('drop', (e) => {
-      e.preventDefault();
-      this.dropzone.classList.remove('dragover');
-      
-      const file = e.dataTransfer.files[0];
-      if (file && file.name.endsWith('.dot')) {
-        this.handleFile(file);
-      } else {
-        alert('Please drop a .dot file');
-      }
-    });
-
-    // File input
-    const fileInput = document.createElement('input');
-    fileInput.type = 'file';
-    fileInput.accept = '.dot';
-    fileInput.style.display = 'none';
-    fileInput.addEventListener('change', (e) => {
-      const file = e.target.files[0];
-      if (file) {
-        this.handleFile(file);
-      }
-    });
-    document.body.appendChild(fileInput);
-
-    this.dropzone.addEventListener('click', () => {
-      fileInput.click();
-    });
-  }
-
-  /**
-   * Handle dropped or selected file
-   * @param {File} file - DOT file
-   * @returns {Promise<void>}
-   */
-  async handleFile(file) {
-    try {
-      const content = await this.readFile(file);
-      await this.renderGraph(content, file.name);
-    } catch (error) {
-      this.showError(`Error rendering graph: ${error.message}`);
-      console.error('Error:', error);
-    }
-  }
-
-  /**
-   * Read file content
-   * @param {File} file - File to read
-   * @returns {Promise<string>} File content
-   */
-  readFile(file) {
-    return new Promise((resolve, reject) => {
-      const reader = new FileReader();
-      reader.onload = (e) => resolve(e.target.result);
-      reader.onerror = (e) => reject(new Error('Failed to read file'));
-      reader.readAsText(file);
-    });
-  }
-
-  /**
-   * Parse DOT content into graph data
-   * @param {string} dotContent - DOT file content
-   * @returns {Object} Parsed graph data
-   */
-  parseDotContent(dotContent) {
-    const nodes = new Map();
-    const edges = [];
-    
-    // Extract node definitions with labels
-    const nodeRegex = /(\w+)\s*\[label="({[^"]+}|[^"]+)"\]/g;
-    let match;
-    
-    while ((match = nodeRegex.exec(dotContent)) !== null) {
-      const nodeId = match[1];
-      const label = match[2];
-      
-      // Parse label
-      const parsedLabel = this.parseLabel(label);
-      
-      // Create main node
-      nodes.set(nodeId, {
-        id: nodeId,
-        label: parsedLabel.title,
-        isContainer: parsedLabel.items.length > 0,
-        type: null,
-        address: null
-      });
-      
-      // Create child nodes from fields
-      parsedLabel.items.forEach((field, index) => {
-        const childId = `${nodeId}_field_${index}`;
-        nodes.set(childId, {
-          id: childId,
-          label: field.name,
-          isContainer: false,
-          type: field.address,
-          address: field.value
-        });
-        
-        // Create edge from parent to child
-        edges.push({
-          source: nodeId,
-          target: childId
-        });
-      });
-    }
-    
-    // Extract explicit edges (connections)
-    const edgeRegex = /(\w+)\s*->\s*(\w+)/g;
-    while ((match = edgeRegex.exec(dotContent)) !== null) {
-      edges.push({
-        source: match[1],
-        target: match[2]
-      });
-    }
-    
-    return {
-      nodes: Array.from(nodes.values()),
-      edges: edges
-    };
-  }
-
-  /**
-   * Parse label into structured data
-   * @param {string} label - Node label
-   * @returns {Object} Parsed label data
-   */
-  /**
-   * Parse node label text
-   * @param {string} label - Label text to parse
-   * @returns {Object} Parsed label with title and fields
-   */
-  parseLabel(label) {
-    // Check if it's a record-style label
-    if (label.startsWith('{') && label.endsWith('}')) {
-      return this.parseRecordLabel(label);
-    }
-    
-    // Simple label
-    return {
-      title: label,
-      items: []
-    };
-  }
-
-  /**
-   * Parse record-style label into structured data
-   * @param {string} label - Record label like "{Title|{field1|value1}|{field2|value2}}"
-   * @returns {Object} Parsed label data
-   */
-  /**
-   * Parse record-style label into structured fields
-   * @param {string} label - Record label text
-   * @returns {Object} Object with title and fields array
-   */
-  parseRecordLabel(label) {
-    // Remove outer braces
-    let content = label.slice(1, -1);
-    
-    // Split by top-level pipes (not inside braces)
-    const parts = [];
-    let depth = 0;
-    let current = '';
-    
-    for (let i = 0; i < content.length; i++) {
-      const char = content[i];
-      
-      if (char === '\\' && i + 1 < content.length) {
-        // Skip escaped character
-        current += content[i + 1];
-        i++;
-        continue;
-      }
-      
-      if (char === '{') depth++;
-      else if (char === '}') depth--;
-      else if (char === '|' && depth === 0) {
-        parts.push(current);
-        current = '';
-        continue;
-      }
-      
-      current += char;
-    }
-    if (current) parts.push(current);
-    
-    const title = parts[0] || 'Unknown';
-    const items = [];
-    
-    // Parse remaining parts as field records
-    for (let i = 1; i < parts.length; i++) {
-      const part = parts[i].trim();
-      if (part.startsWith('{') && part.endsWith('}')) {
-        const fieldContent = part.slice(1, -1);
-        const fieldParts = fieldContent.split('|').map(p => p.trim());
-        
-        items.push({
-          name: fieldParts[0] || '',
-          address: fieldParts[1] || '',
-          value: fieldParts[2] || ''
-        });
-      }
-    }
-    
-    return { title, items };
-  }
-
-  /**
-   * Render interactive graph using D3.js
-   * @param {string} dotContent - DOT file content
-   * @param {string} filename - File name
-   */
-  async renderGraph(dotContent, filename) {
-    try {
-      // Check if D3 is loaded
-      if (typeof d3 === 'undefined') {
-        throw new Error('D3.js library not loaded. Please check your internet connection.');
-      }
-
-      // Basic validation
-      const trimmedContent = dotContent.trim();
-      if (!trimmedContent) {
-        throw new Error('DOT file is empty');
-      }
-
-      // Parse DOT content
-      const graphData = this.parseDotContent(dotContent);
-      
-      if (graphData.nodes.length === 0) {
-        throw new Error('No nodes found in DOT file');
-      }
-      
-      this.parsedData = graphData;
-      this.currentGraph = dotContent;
-      
-      // Create D3 force-directed graph
-      this.createForceGraph(graphData, filename);
-      
-      // Show controls and info
-      this.dropzone.style.display = 'none';
-      this.controls.style.display = 'flex';
-      this.info.style.display = 'flex';
-      
-      // Update info
-      this.filename.textContent = filename;
-      this.stats.textContent = `${graphData.nodes.length} nodes, ${graphData.edges.length} connections`;
-      
-    } catch (error) {
-      throw error;
-    }
-  }
-
-  /**
-   * Create force-directed graph with D3.js
-   * @param {Object} data - Graph data
-   * @param {string} filename - File name
-   */
-  /**
-   * Create D3.js force-directed graph visualization
-   * @param {Object} data - Graph data with nodes and edges
-   * @param {string} filename - Name of the DOT file
-   * @returns {void}
-   */
-  createForceGraph(data, filename) {
-    // Clear canvas
-    this.canvas.innerHTML = '';
-    
-    // Store full graph data
-    this.fullGraphData = data;
-    
-    // Find root nodes (nodes with no incoming edges)
-    const childNodeIds = new Set(data.edges.map(e => e.target));
-    const rootNodes = data.nodes.filter(n => !childNodeIds.has(n.id));
-    
-    // If no clear root, use first few nodes
-    if (rootNodes.length === 0) {
-      rootNodes.push(...data.nodes.slice(0, Math.min(3, data.nodes.length)));
-    }
-    
-    // Initialize visible nodes with roots
-    this.visibleNodes.clear();
-    rootNodes.forEach(n => this.visibleNodes.add(n.id));
-    
-    // Get canvas dimensions
-    const width = this.canvas.clientWidth;
-    const height = this.canvas.clientHeight;
-    
-    // Create SVG
-    const svg = d3.select(this.canvas)
-      .append('svg')
-      .attr('width', width)
-      .attr('height', height)
-      .attr('viewBox', [0, 0, width, height]);
-    
-    // Add zoom behavior
-    const g = svg.append('g');
-    
-    const zoom = d3.zoom()
-      .scaleExtent([0.1, 4])
-      .on('zoom', (event) => {
-        g.attr('transform', event.transform);
-      });
-    
-    svg.call(zoom);
-    
-    // Store zoom and svg references
-    this.zoom = zoom;
-    this.svg = svg;
-    
-    // Create arrow markers for edges
-    svg.append('defs').append('marker')
-      .attr('id', 'arrowhead')
-      .attr('viewBox', '-0 -5 10 10')
-      .attr('refX', 25)
-      .attr('refY', 0)
-      .attr('orient', 'auto')
-      .attr('markerWidth', 8)
-      .attr('markerHeight', 8)
-      .append('svg:path')
-      .attr('d', 'M 0,-5 L 10 ,0 L 0,5')
-      .attr('fill', '#848d97');
-    
-    // Store references for updates
-    this.g = g;
-    this.width = width;
-    this.height = height;
-    
-    // Create legend
-    this.createLegend(svg);
-    
-    // Initial render with only visible nodes
-    this.updateGraph();
-  }
-
-  /**
-   * Create legend for node types
-   * @param {Object} svg - SVG element
-   */
-  /**
-   * Create legend showing node type colors
-   * @param {Object} svg - D3.js SVG selection
-   * @returns {void}
-   */
-  createLegend(svg) {
-    const legend = svg.append('g')
-      .attr('class', 'legend')
-      .attr('transform', `translate(20, ${this.height - 120})`);
-    
-    // Background
-    legend.append('rect')
-      .attr('x', 0)
-      .attr('y', 0)
-      .attr('width', 120)
-      .attr('height', 100)
-      .attr('fill', '#161b22')
-      .attr('stroke', '#30363d')
-      .attr('stroke-width', 1)
-      .attr('rx', 4);
-    
-    // Title
-    legend.append('text')
-      .attr('x', 10)
-      .attr('y', 18)
-      .attr('fill', '#f0f6fc')
-      .attr('font-size', '12px')
-      .attr('font-weight', 'bold')
-      .text('Node Types');
-    
-    // Legend items
-    const items = [
-      { type: 'container', label: 'Container' },
-      { type: 'F', label: 'Function' },
-      { type: 'O', label: 'Object' },
-      { type: 'default', label: 'Other' }
-    ];
-    
-    items.forEach((item, index) => {
-      const yPos = 35 + index * 20;
-      const colors = this.typeColors[item.type];
-      
-      // Circle
-      legend.append('circle')
-        .attr('cx', 15)
-        .attr('cy', yPos)
-        .attr('r', 6)
-        .attr('fill', colors.fill)
-        .attr('stroke', colors.stroke)
-        .attr('stroke-width', 1.5);
-      
-      // Label
-      legend.append('text')
-        .attr('x', 28)
-        .attr('y', yPos + 4)
-        .attr('fill', '#c9d1d9')
-        .attr('font-size', '11px')
-        .text(item.label);
-    });
-  }
-
-  /**
-   * Update graph to show only visible nodes and edges
-   */
-  /**
-   * Update graph visualization with current visible nodes and edges
-   * @returns {void}
-   */
-  updateGraph() {
-    const data = this.fullGraphData;
-    
-    // Filter visible nodes
-    const visibleNodesData = data.nodes.filter(n => this.visibleNodes.has(n.id));
-    
-    // Filter visible edges (both source and target must be visible)
-    const visibleEdgesData = data.edges.filter(e => 
-      this.visibleNodes.has(e.source.id || e.source) && 
-      this.visibleNodes.has(e.target.id || e.target)
-    );
-    
-    // Create or update force simulation
-    if (this.simulation) {
-      this.simulation.stop();
-    }
-    
-    this.simulation = d3.forceSimulation(visibleNodesData)
-      .force('link', d3.forceLink(visibleEdgesData)
-        .id(d => d.id)
-        .distance(150))
-      .force('charge', d3.forceManyBody().strength(-400))
-      .force('center', d3.forceCenter(this.width / 2, this.height / 2))
-      .force('collision', d3.forceCollide().radius(40));
-    
-    // Update edges
-    const link = this.g.selectAll('line')
-      .data(visibleEdgesData, d => `${d.source.id || d.source}-${d.target.id || d.target}`);
-    
-    link.exit().remove();
-    
-    const linkEnter = link.enter().append('line')
-      .attr('stroke', '#848d97')
-      .attr('stroke-width', 2)
-      .attr('marker-end', 'url(#arrowhead)')
-      .attr('opacity', 0);
-    
-    const linkAll = linkEnter.merge(link);
-    
-    linkAll.transition()
-      .duration(300)
-      .attr('opacity', 1);
-    
-    // Update nodes
-    const node = this.g.selectAll('g.node')
-      .data(visibleNodesData, d => d.id);
-    
-    node.exit().remove();
-    
-    const nodeEnter = node.enter().append('g')
-      .attr('class', 'node')
-      .call(d3.drag()
-        .on('start', (event, d) => this.dragStarted(event, d, this.simulation))
-        .on('drag', (event, d) => this.dragged(event, d))
-        .on('end', (event, d) => this.dragEnded(event, d, this.simulation)));
-    
-    // Add circles to new nodes
-    nodeEnter.append('circle')
-      .attr('r', 0)
-      .attr('fill', d => this.getNodeColor(d).fill)
-      .attr('stroke', d => this.getNodeColor(d).stroke)
-      .attr('stroke-width', 2);
-    
-    // Add labels to new nodes
-    nodeEnter.append('text')
-      .text(d => d.label.length > 20 ? d.label.substring(0, 17) + '...' : d.label)
-      .attr('x', 0)
-      .attr('y', 35)
-      .attr('text-anchor', 'middle')
-      .attr('fill', '#f0f6fc')
-      .attr('font-size', '12px')
-      .style('pointer-events', 'none')
-      .attr('opacity', 0);
-    
-    // Add expand indicator for nodes with children
-    nodeEnter.each((d, i, nodes) => {
-      const hasChildren = this.hasUnexpandedChildren(d);
-      
-      if (hasChildren) {
-        // Green + for expandable nodes
-        d3.select(nodes[i]).append('circle')
-          .attr('class', 'expand-indicator')
-          .attr('r', 6)
-          .attr('cx', 18)
-          .attr('cy', -18)
-          .attr('fill', '#238636')
-          .attr('stroke', '#2ea043')
-          .attr('stroke-width', 1)
-          .attr('opacity', 0);
-        
-        d3.select(nodes[i]).append('text')
-          .attr('class', 'expand-icon')
-          .attr('x', 18)
-          .attr('y', -14)
-          .attr('text-anchor', 'middle')
-          .attr('fill', 'white')
-          .attr('font-size', '10px')
-          .attr('font-weight', 'bold')
-          .style('pointer-events', 'none')
-          .text('+')
-          .attr('opacity', 0);
-      }
-    });
-    
-    const nodeAll = nodeEnter.merge(node);
-    
-    // Animate circles
-    nodeAll.select('circle:not(.expand-indicator)')
-      .transition()
-      .duration(300)
-      .attr('r', d => this.expandedNodes.has(d.id) ? 24 : 20)
-      .attr('fill', d => {
-        if (this.expandedNodes.has(d.id)) return '#a371f7'; // Purple when expanded
-        return this.getNodeColor(d).fill;
-      })
-      .attr('stroke', d => {
-        if (this.expandedNodes.has(d.id)) return '#8957e5';
-        return this.getNodeColor(d).stroke;
-      });
-    
-    // Animate labels
-    nodeAll.select('text:not(.expand-icon)')
-      .transition()
-      .duration(300)
-      .attr('opacity', 1);
-    
-    // Update expand indicators
-    nodeAll.each((d, i, nodes) => {
-      const hasChildren = this.hasUnexpandedChildren(d);
-      const nodeGroup = d3.select(nodes[i]);
-      
-      if (hasChildren) {
-        nodeGroup.select('.expand-indicator')
-          .transition()
-          .duration(300)
-          .attr('opacity', 1);
-        
-        nodeGroup.select('.expand-icon')
-          .transition()
-          .duration(300)
-          .attr('opacity', 1);
-      } else {
-        // No children, remove indicators
-        nodeGroup.select('.expand-indicator').remove();
-        nodeGroup.select('.expand-icon').remove();
-      }
-    });
-    
-    // Add click handler to nodes
-    nodeAll.on('click', (event, d) => {
-      event.stopPropagation();
-      this.toggleNodeExpansion(d);
-    });
-    
-    // Add hover effects
-    nodeAll.on('mouseenter', function(event, d) {
-      if (!d._expanded) {
-        const baseColor = d3.select(this).select('circle:not(.expand-indicator)').attr('fill');
-        d3.select(this).select('circle:not(.expand-indicator)')
-          .attr('r', 24);
-      }
-    });
-    
-    nodeAll.on('mouseleave', function(event, d) {
-      if (!d._expanded) {
-        d3.select(this).select('circle:not(.expand-indicator)')
-          .attr('r', 20);
-      }
-    });
-    
-    // Update positions on simulation tick
-    this.simulation.on('tick', () => {
-      linkAll
-        .attr('x1', d => d.source.x)
-        .attr('y1', d => d.source.y)
-        .attr('x2', d => d.target.x)
-        .attr('y2', d => d.target.y);
-      
-      nodeAll.attr('transform', d => `translate(${d.x},${d.y})`);
-    });
-  }
-
-  /**
-   * Check if node has unexpanded children
-   * @param {Object} node - Node to check
-   * @returns {boolean} Has unexpanded children
-   */
-  /**
-   * Check if node has children that haven't been expanded
-   * @param {Object} node - Node to check
-   * @returns {boolean} True if node has unexpanded children
-   */
-  hasUnexpandedChildren(node) {
-    const children = this.fullGraphData.edges
-      .filter(e => (e.source.id || e.source) === node.id)
-      .map(e => e.target.id || e.target);
-    
-    return children.some(childId => !this.visibleNodes.has(childId));
-  }
-
-  /**
-   * Toggle node expansion
-   * @param {Object} node - Node to toggle
-   */
-  /**
-   * Toggle node expansion state (expand/collapse children)
-   * @param {Object} node - Node to toggle
-   * @returns {void}
-   */
-  toggleNodeExpansion(node) {
-    const hasChildren = this.hasUnexpandedChildren(node);
-    
-    // If node has children, expand/collapse
-    if (hasChildren || this.expandedNodes.has(node.id)) {
-      if (this.expandedNodes.has(node.id)) {
-        // Collapse: remove children
-        this.collapseNode(node);
-      } else {
-        // Expand: show children
-        this.expandNode(node);
-      }
-      
-      // Update the graph
-      this.updateGraph();
-    } 
-    // If node is a leaf (no children), show its metadata
-    else if (node.type || node.address) {
-      this.showNodeMetadata(node);
-    }
-    
-    // Update stats
-    const visibleCount = this.visibleNodes.size;
-    const totalCount = this.fullGraphData.nodes.length;
-    this.stats.textContent = `Showing ${visibleCount} of ${totalCount} nodes`;
-  }
-
-  /**
-   * Expand node to show its children
-   * @param {Object} node - Node to expand
-   */
-  /**
-   * Expand node to show its children
-   * @param {Object} node - Node to expand
-   * @returns {void}
-   */
-  expandNode(node) {
-    this.expandedNodes.add(node.id);
-    node._expanded = true;
-    
-    // Find all children
-    const children = this.fullGraphData.edges
-      .filter(e => (e.source.id || e.source) === node.id)
-      .map(e => e.target.id || e.target);
-    
-    // Add children to visible nodes
-    children.forEach(childId => this.visibleNodes.add(childId));
-  }
-
-  /**
-   * Collapse node to hide its children
-   * @param {Object} node - Node to collapse
-   */
-  /**
-   * Collapse node and hide its children recursively
-   * @param {Object} node - Node to collapse
-   * @returns {void}
-   */
-  collapseNode(node) {
-    this.expandedNodes.delete(node.id);
-    node._expanded = false;
-    
-    // Find all descendants (recursive)
-    const toRemove = new Set();
-    const findDescendants = (nodeId) => {
-      const children = this.fullGraphData.edges
-        .filter(e => (e.source.id || e.source) === nodeId)
-        .map(e => e.target.id || e.target);
-      
-      children.forEach(childId => {
-        toRemove.add(childId);
-        if (this.expandedNodes.has(childId)) {
-          findDescendants(childId);
-        }
-      });
-    };
-    
-    findDescendants(node.id);
-    
-    // Remove descendants from visible nodes
-    toRemove.forEach(nodeId => {
-      this.visibleNodes.delete(nodeId);
-      this.expandedNodes.delete(nodeId);
-    });
-  }
-
-  /**
-   * Show node metadata (type and address) as overlay
-   * @param {Object} node - Node data
-   */
-  /**
-   * Display node metadata in the info panel
-   * @param {Object} node - Node whose metadata to display
-   * @returns {void}
-   */
-  showNodeMetadata(node) {
-    // Remove existing tooltip
-    const existingTooltip = this.canvas.querySelector('.node-metadata-tooltip');
-    if (existingTooltip) {
-      existingTooltip.remove();
-    }
-    
-    // Create tooltip
-    const tooltip = document.createElement('div');
-    tooltip.className = 'node-metadata-tooltip';
-    
-    const title = document.createElement('div');
-    title.className = 'tooltip-title';
-    title.textContent = node.label;
-    tooltip.appendChild(title);
-    
-    if (node.type) {
-      const typeDiv = document.createElement('div');
-      typeDiv.className = 'tooltip-field';
-      typeDiv.innerHTML = `<span class="tooltip-label">Type:</span> <span class="tooltip-value">${node.type}</span>`;
-      tooltip.appendChild(typeDiv);
-    }
-    
-    if (node.address) {
-      const addrDiv = document.createElement('div');
-      addrDiv.className = 'tooltip-field';
-      addrDiv.innerHTML = `<span class="tooltip-label">Address:</span> <span class="tooltip-value">${node.address}</span>`;
-      tooltip.appendChild(addrDiv);
-    }
-    
-    this.canvas.appendChild(tooltip);
-    
-    // Auto-dismiss after 5 seconds
-    setTimeout(() => {
-      if (tooltip.parentNode) {
-        tooltip.remove();
-      }
-    }, 5000);
-  }
-
-  /**
-   * Drag event handlers for D3
-   */
-  /**
-   * Handle drag start event for node
-   * @param {Object} event - D3 drag event
-   * @param {Object} d - Node data
-   * @param {Object} simulation - D3 simulation
-   * @returns {void}
-   */
-  dragStarted(event, d, simulation) {
-    if (!event.active) simulation.alphaTarget(0.3).restart();
-    d.fx = d.x;
-    d.fy = d.y;
-  }
-
-  /**
-   * Handle drag event for node
-   * @param {Object} event - D3 drag event
-   * @param {Object} d - Node data
-   * @returns {void}
-   */
-  dragged(event, d) {
-    d.fx = event.x;
-    d.fy = event.y;
-  }
-
-  /**
-   * Handle drag end event for node
-   * @param {Object} event - D3 drag event
-   * @param {Object} d - Node data
-   * @param {Object} simulation - D3 simulation
-   * @returns {void}
-   */
-  dragEnded(event, d, simulation) {
-    if (!event.active) simulation.alphaTarget(0);
-    d.fx = null;
-    d.fy = null;
-  }
-
-  /**
-   * Zoom controls
-   */
-  /**
-   * Zoom in on the graph
-   * @returns {void}
-   */
-  zoomIn() {
-    if (!this.svg || !this.zoom) return;
-    this.svg.transition().duration(300).call(
-      this.zoom.scaleBy,
-      1.3
-    );
-  }
-
-  /**
-   * Zoom out on the graph
-   * @returns {void}
-   */
-  zoomOut() {
-    if (!this.svg || !this.zoom) return;
-    this.svg.transition().duration(300).call(
-      this.zoom.scaleBy,
-      0.7
-    );
-  }
-
-  /**
-   * Reset zoom to default level
-   * @returns {void}
-   */
-  resetZoom() {
-    if (!this.svg || !this.zoom) return;
-    this.svg.transition().duration(300).call(
-      this.zoom.transform,
-      d3.zoomIdentity
-    );
-  }
-
-  /**
-   * Clear current visualization
-   */
-  /**
-   * Clear the graph and return to dropzone
-   * @returns {void}
-   */
-  clear() {
-    this.canvas.innerHTML = '';
-    this.currentGraph = null;
-    this.parsedData = null;
-    this.fullGraphData = null;
-    this.svg = null;
-    this.zoom = null;
-    this.expandedNodes.clear();
-    this.visibleNodes.clear();
-    this.visibleEdges.clear();
-    
-    if (this.simulation) {
-      this.simulation.stop();
-      this.simulation = null;
-    }
-    
-    // Show dropzone again
-    if (this.dropzone) {
-      this.dropzone.style.display = 'flex';
-    }
-    
-    // Hide info panel
-    if (this.info) {
-      this.info.style.display = 'none';
-      this.info.classList.remove('error');
-    }
-  }
-
-  /**
-   * Show error message
-   * @param {string} message - Error message
-   */
-  /**
-   * Display error message to user
-   * @param {string} message - Error message to display
-   * @returns {void}
-   */
-  showError(message) {
-    this.info.classList.add('error');
-    this.stats.textContent = message;
-  }
-}
-
-module.exports = VisualyzerManager;
-
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/renderer_utils_emojiTest.js.html b/docs/renderer_utils_emojiTest.js.html deleted file mode 100644 index 1b1673f..0000000 --- a/docs/renderer_utils_emojiTest.js.html +++ /dev/null @@ -1,91 +0,0 @@ - - - - - JSDoc: Source: renderer/utils/emojiTest.js - - - - - - - - - - -
- -

Source: renderer/utils/emojiTest.js

- - - - - - -
-
-
// Emoji test utility for cross-platform rendering
-const os = require('os');
-
-/**
- * Test emoji rendering and font availability
- */
-function testEmojiSupport() {
-  const platform = os.platform();
-  const testEmojis = ['📁', '📄', '🔄', '🔍', '⚙️', '💾', '🎨', '🐍', '☕', '🦀'];
-  
-  console.log(`Testing emoji support on ${platform}:`);
-  console.log('Test emojis:', testEmojis.join(' '));
-  
-  // Test if system has color emoji support
-  const emojiTestDiv = document.createElement('div');
-  emojiTestDiv.style.fontFamily = 'Noto Color Emoji, Segoe UI Emoji, Apple Color Emoji';
-  emojiTestDiv.textContent = '📁';
-  document.body.appendChild(emojiTestDiv);
-  
-  // Check computed style
-  const computedStyle = window.getComputedStyle(emojiTestDiv);
-  console.log('Font family resolved to:', computedStyle.fontFamily);
-  
-  document.body.removeChild(emojiTestDiv);
-  
-  return {
-    platform: platform,
-    supportedEmojis: testEmojis,
-    fontFamily: computedStyle.fontFamily
-  };
-}
-
-// Export for use in development
-if (typeof module !== 'undefined' && module.exports) {
-  module.exports = { testEmojiSupport };
-}
-
-// Auto-run in browser environment
-if (typeof window !== 'undefined') {
-  window.testEmojiSupport = testEmojiSupport;
-}
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/renderer_utils_fileTypeUtils.js.html b/docs/renderer_utils_fileTypeUtils.js.html deleted file mode 100644 index 576e2e9..0000000 --- a/docs/renderer_utils_fileTypeUtils.js.html +++ /dev/null @@ -1,137 +0,0 @@ - - - - - JSDoc: Source: renderer/utils/fileTypeUtils.js - - - - - - - - - - -
- -

Source: renderer/utils/fileTypeUtils.js

- - - - - - -
-
-
/**
- * Detect file type based on file extension
- * @param {string} filename - The filename to analyze
- * @returns {string} - The detected file type
- */
-function detectFileType(filename) {
-  if (!filename) return "Plain Text";
-  const lower = filename.toLowerCase();
-  
-  if (lower === "cmakelists.txt" || lower.endsWith(".cmake")) return "CMake";
-  if (lower.endsWith(".c")) return "C";
-  if (lower.endsWith(".cpp") || lower.endsWith(".cc") || lower.endsWith(".cxx")) return "C++";
-  if (lower.endsWith(".h") || lower.endsWith(".hpp") || lower.endsWith(".hh") || lower.endsWith(".hxx")) return "C/C++ Header";
-  if (lower.endsWith(".js")) return "JavaScript";
-  if (lower.endsWith(".ts")) return "TypeScript";
-  if (lower.endsWith(".py")) return "Python";
-  if (lower.endsWith(".json")) return "JSON";
-  if (lower.endsWith(".md")) return "Markdown";
-  if (lower.endsWith(".txt")) return "Plain Text";
-  
-  return "Plain Text";
-}
-
-/**
- * Update file type status in the status bar
- * @param {string} filename - The filename to analyze
- */
-function updateFileTypeStatus(filename) {
-  const type = detectFileType(filename);
-  const el = document.getElementById("fileType");
-  if (el) el.textContent = type;
-}
-
-/**
- * Get file icon based on extension
- * @param {string} filename - The filename
- * @returns {string} - Unicode emoji for file icon
- */
-function getFileIcon(filename) {
-  const ext = filename.split('.').pop().toLowerCase();
-  const iconMap = {
-    'js': '🟨',
-    'ts': '🔷',
-    'html': '🟧',
-    'css': '🎨',
-    'json': '📋',
-    'md': '📝',
-    'py': '🐍',
-    'cpp': '⚙️',
-    'c': '⚙️',
-    'h': '📄',
-    'java': '☕',
-    'php': '🐘',
-    'rb': '💎',
-    'go': '🐹',
-    'rs': '🦀'
-  };
-  return iconMap[ext] || '📄';
-}
-
-/**
- * Format file size for display
- * @param {number} bytes - File size in bytes
- * @returns {string} - Formatted file size
- */
-function formatFileSize(bytes) {
-  if (bytes === 0) return '0 Bytes';
-  const k = 1024;
-  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
-  const i = Math.floor(Math.log(bytes) / Math.log(k));
-  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
-}
-
-// Make functions available globally for backward compatibility
-if (typeof window !== 'undefined') {
-  window.detectFileType = detectFileType;
-  window.updateFileTypeStatus = updateFileTypeStatus;
-  window.getFileIcon = getFileIcon;
-  window.formatFileSize = formatFileSize;
-}
-
-module.exports = {
-  detectFileType,
-  updateFileTypeStatus,
-  getFileIcon,
-  formatFileSize
-};
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/renderer_utils_syntaxHighlighter.js.html b/docs/renderer_utils_syntaxHighlighter.js.html deleted file mode 100644 index 1f94c7a..0000000 --- a/docs/renderer_utils_syntaxHighlighter.js.html +++ /dev/null @@ -1,348 +0,0 @@ - - - - - JSDoc: Source: renderer/utils/syntaxHighlighter.js - - - - - - - - - - -
- -

Source: renderer/utils/syntaxHighlighter.js

- - - - - - -
-
-
/**
- * Scalable Syntax Highlighter for C/C++ code
- * Provides real-time syntax highlighting with optimized performance for large files
- */
-
-// Load syntax configuration
-const syntaxConfig = require('./syntax-config.json');
-
-// Cache for language configurations
-let languageCache = {};
-
-/**
- * Get language configuration
- * @param {string} fileType - The file type
- * @returns {Object} - Language configuration
- */
-function getLanguageConfig(fileType) {
-  // Check cache first
-  if (languageCache[fileType]) {
-    return languageCache[fileType];
-  }
-  
-  // Find matching language config
-  for (const [langKey, config] of Object.entries(syntaxConfig)) {
-    if (config.fileTypes.includes(fileType)) {
-      // Convert arrays to Sets for faster lookup
-      const processedConfig = {
-        ...config,
-        keywords: new Set(config.keywords),
-        types: new Set(config.types),
-        preprocessor: new Set(config.preprocessor)
-      };
-      languageCache[fileType] = processedConfig;
-      return processedConfig;
-    }
-  }
-  
-  return null;
-}
-
-/**
- * Escape HTML special characters
- * @param {string} text - Text to escape
- * @returns {string} Escaped HTML string
- */
-function escapeHtml(text) {
-  return text
-    .replace(/&/g, '&amp;')
-    .replace(/</g, '&lt;')
-    .replace(/>/g, '&gt;')
-    .replace(/"/g, '&quot;')
-    .replace(/'/g, '&#039;');
-}
-
-/**
- * Tokenize C/C++ code for highlighting
- * @param {string} code - The code to tokenize
- * @param {Object} langConfig - Language configuration
- * @returns {Array} - Array of tokens with type and value
- */
-function tokenizeCpp(code, langConfig) {
-  const tokens = [];
-  let i = 0;
-  
-  while (i < code.length) {
-    const char = code[i];
-    
-    // Single-line comment
-    if (code.substr(i, 2) === '//') {
-      let comment = '//';
-      i += 2;
-      while (i < code.length && code[i] !== '\n') {
-        comment += code[i];
-        i++;
-      }
-      tokens.push({ type: 'comment', value: comment });
-      continue;
-    }
-    
-    // Multi-line comment
-    if (code.substr(i, 2) === '/*') {
-      let comment = '/*';
-      i += 2;
-      while (i < code.length && code.substr(i, 2) !== '*/') {
-        comment += code[i];
-        i++;
-      }
-      if (code.substr(i, 2) === '*/') {
-        comment += '*/';
-        i += 2;
-      }
-      tokens.push({ type: 'comment', value: comment });
-      continue;
-    }
-    
-    // String literals
-    if (char === '"' || char === "'") {
-      const quote = char;
-      let str = quote;
-      i++;
-      while (i < code.length) {
-        if (code[i] === '\\' && i + 1 < code.length) {
-          str += code[i] + code[i + 1];
-          i += 2;
-        } else if (code[i] === quote) {
-          str += quote;
-          i++;
-          break;
-        } else {
-          str += code[i];
-          i++;
-        }
-      }
-      tokens.push({ type: 'string', value: str });
-      continue;
-    }
-    
-    // Preprocessor directives
-    if (char === '#') {
-      let directive = '#';
-      i++;
-      while (i < code.length && /[a-zA-Z_]/.test(code[i])) {
-        directive += code[i];
-        i++;
-      }
-      tokens.push({ type: 'preprocessor', value: directive });
-      
-      // For #include, capture the file path
-      if (directive.includes('include')) {
-        while (i < code.length && /\s/.test(code[i])) {
-          tokens.push({ type: 'whitespace', value: code[i] });
-          i++;
-        }
-        if (i < code.length && (code[i] === '<' || code[i] === '"')) {
-          const endChar = code[i] === '<' ? '>' : '"';
-          let path = code[i];
-          i++;
-          while (i < code.length && code[i] !== endChar && code[i] !== '\n') {
-            path += code[i];
-            i++;
-          }
-          if (i < code.length && code[i] === endChar) {
-            path += code[i];
-            i++;
-          }
-          tokens.push({ type: 'string', value: path });
-        }
-      }
-      continue;
-    }
-    
-    // Numbers
-    if (/\d/.test(char) || (char === '.' && i + 1 < code.length && /\d/.test(code[i + 1]))) {
-      let num = char;
-      i++;
-      while (i < code.length && /[\d.xXa-fA-F]/.test(code[i])) {
-        num += code[i];
-        i++;
-      }
-      // Check for number suffixes
-      if (i < code.length && /[fFlLuU]/.test(code[i])) {
-        num += code[i];
-        i++;
-      }
-      tokens.push({ type: 'number', value: num });
-      continue;
-    }
-    
-    // Identifiers, keywords, types
-    if (/[a-zA-Z_]/.test(char)) {
-      let word = '';
-      while (i < code.length && /[a-zA-Z0-9_]/.test(code[i])) {
-        word += code[i];
-        i++;
-      }
-      
-      // Skip whitespace to check for function call
-      let j = i;
-      while (j < code.length && /\s/.test(code[j])) j++;
-      
-      const isFunction = code[j] === '(';
-      
-      if (langConfig.keywords.has(word)) {
-        tokens.push({ type: 'keyword', value: word });
-      } else if (langConfig.types.has(word)) {
-        tokens.push({ type: 'type', value: word });
-      } else if (isFunction) {
-        tokens.push({ type: 'function', value: word });
-      } else if (/^[A-Z_][A-Z0-9_]*$/.test(word)) {
-        tokens.push({ type: 'constant', value: word });
-      } else {
-        tokens.push({ type: 'identifier', value: word });
-      }
-      continue;
-    }
-    
-    // Operators
-    if ('+-*/%=<>!&|^~?:'.includes(char)) {
-      tokens.push({ type: 'operator', value: char });
-      i++;
-      continue;
-    }
-    
-    // Everything else
-    tokens.push({ type: 'plain', value: char });
-    i++;
-  }
-  
-  return tokens;
-}
-
-/**
- * Convert tokens to HTML
- * @param {Array} tokens - Array of tokens
- * @param {Object} langConfig - Language configuration
- * @returns {string} - HTML string
- */
-function tokensToHtml(tokens, langConfig) {
-  const colorMap = langConfig.colors;
-  
-  return tokens.map(token => {
-    const color = colorMap[token.type] || colorMap.plain;
-    if (token.type === 'whitespace' || token.type === 'plain') {
-      return escapeHtml(token.value);
-    }
-    return `<span style="color:${color}">${escapeHtml(token.value)}</span>`;
-  }).join('');
-}
-
-/**
- * Highlight C/C++ syntax (optimized version)
- * @param {string} code - The code to highlight
- * @param {string} fileType - The file type
- * @returns {string} - HTML with syntax highlighting
- */
-function highlightCppSyntax(code, fileType) {
-  if (!code) return '';
-  
-  const langConfig = getLanguageConfig(fileType);
-  if (!langConfig) return escapeHtml(code);
-  
-  const tokens = tokenizeCpp(code, langConfig);
-  return tokensToHtml(tokens, langConfig);
-}
-
-/**
- * Apply syntax highlighting to editor based on file type
- * @param {string} code - The code to highlight
- * @param {string} fileType - The detected file type
- * @returns {string} - HTML with syntax highlighting
- */
-function applySyntaxHighlight(code, fileType) {
-  if (!code) return '';
-  
-  const langConfig = getLanguageConfig(fileType);
-  
-  // Apply highlighting if language config found
-  if (langConfig) {
-    return highlightCppSyntax(code, fileType);
-  }
-  
-  // For other file types, return escaped HTML
-  return escapeHtml(code);
-}
-
-/**
- * Check if file type should have syntax highlighting
- * @param {string} fileType - The file type to check
- * @returns {boolean} - True if highlighting should be applied
- */
-function shouldHighlight(fileType) {
-  return getLanguageConfig(fileType) !== null;
-}
-
-// Export for use in other modules
-if (typeof module !== 'undefined' && module.exports) {
-  module.exports = {
-    highlightCppSyntax,
-    applySyntaxHighlight,
-    shouldHighlight,
-    escapeHtml,
-    tokenizeCpp,
-    tokensToHtml
-  };
-}
-
-// Make available globally
-if (typeof window !== 'undefined') {
-  window.syntaxHighlighter = {
-    highlightCppSyntax,
-    applySyntaxHighlight,
-    shouldHighlight,
-    escapeHtml,
-    tokenizeCpp,
-    tokensToHtml
-  };
-}
-
-
-
- - - - -
- - - -
- -
- Documentation generated by JSDoc 4.0.4 on Wed Nov 26 2025 15:15:41 GMT+0900 (Korean Standard Time) -
- - - - - diff --git a/docs/scripts/linenumber.js b/docs/scripts/linenumber.js deleted file mode 100644 index 4354785..0000000 --- a/docs/scripts/linenumber.js +++ /dev/null @@ -1,25 +0,0 @@ -/*global document */ -(() => { - const source = document.getElementsByClassName('prettyprint source linenums'); - let i = 0; - let lineNumber = 0; - let lineId; - let lines; - let totalLines; - let anchorHash; - - if (source && source[0]) { - anchorHash = document.location.hash.substring(1); - lines = source[0].getElementsByTagName('li'); - totalLines = lines.length; - - for (; i < totalLines; i++) { - lineNumber++; - lineId = `line${lineNumber}`; - lines[i].id = lineId; - if (lineId === anchorHash) { - lines[i].className += ' selected'; - } - } - } -})(); diff --git a/docs/scripts/prettify/Apache-License-2.0.txt b/docs/scripts/prettify/Apache-License-2.0.txt deleted file mode 100644 index d645695..0000000 --- a/docs/scripts/prettify/Apache-License-2.0.txt +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/docs/scripts/prettify/lang-css.js b/docs/scripts/prettify/lang-css.js deleted file mode 100644 index 041e1f5..0000000 --- a/docs/scripts/prettify/lang-css.js +++ /dev/null @@ -1,2 +0,0 @@ -PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\f\r ]+/,null," \t\r\n "]],[["str",/^"(?:[^\n\f\r"\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*"/,null],["str",/^'(?:[^\n\f\r'\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*'/,null],["lang-css-str",/^url\(([^"')]*)\)/i],["kwd",/^(?:url|rgb|!important|@import|@page|@media|@charset|inherit)(?=[^\w-]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*)\s*:/i],["com",/^\/\*[^*]*\*+(?:[^*/][^*]*\*+)*\//],["com", -/^(?:<\!--|--\>)/],["lit",/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],["lit",/^#[\da-f]{3,6}/i],["pln",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i],["pun",/^[^\s\w"']+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[["kwd",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[["str",/^[^"')]+/]]),["css-str"]); diff --git a/docs/scripts/prettify/prettify.js b/docs/scripts/prettify/prettify.js deleted file mode 100644 index eef5ad7..0000000 --- a/docs/scripts/prettify/prettify.js +++ /dev/null @@ -1,28 +0,0 @@ -var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; -(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a= -[],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;ci[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m), -l=[],p={},d=0,g=e.length;d=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, -q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/, -q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g, -"");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a), -a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e} -for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], -"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"], -H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], -J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+ -I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]), -["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css", -/^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}), -["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes", -hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p=0){var k=k.match(g),f,b;if(b= -!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p th:last-child { border-right: 1px solid #ddd; } - -.ancestors, .attribs { color: #999; } -.ancestors a, .attribs a -{ - color: #999 !important; - text-decoration: none; -} - -.clear -{ - clear: both; -} - -.important -{ - font-weight: bold; - color: #950B02; -} - -.yes-def { - text-indent: -1000px; -} - -.type-signature { - color: #aaa; -} - -.name, .signature { - font-family: Consolas, Monaco, 'Andale Mono', monospace; -} - -.details { margin-top: 14px; border-left: 2px solid #DDD; } -.details dt { width: 120px; float: left; padding-left: 10px; padding-top: 6px; } -.details dd { margin-left: 70px; } -.details ul { margin: 0; } -.details ul { list-style-type: none; } -.details li { margin-left: 30px; padding-top: 6px; } -.details pre.prettyprint { margin: 0 } -.details .object-value { padding-top: 0; } - -.description { - margin-bottom: 1em; - margin-top: 1em; -} - -.code-caption -{ - font-style: italic; - font-size: 107%; - margin: 0; -} - -.source -{ - border: 1px solid #ddd; - width: 80%; - overflow: auto; -} - -.prettyprint.source { - width: inherit; -} - -.source code -{ - font-size: 100%; - line-height: 18px; - display: block; - padding: 4px 12px; - margin: 0; - background-color: #fff; - color: #4D4E53; -} - -.prettyprint code span.line -{ - display: inline-block; -} - -.prettyprint.linenums -{ - padding-left: 70px; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; -} - -.prettyprint.linenums ol -{ - padding-left: 0; -} - -.prettyprint.linenums li -{ - border-left: 3px #ddd solid; -} - -.prettyprint.linenums li.selected, -.prettyprint.linenums li.selected * -{ - background-color: lightyellow; -} - -.prettyprint.linenums li * -{ - -webkit-user-select: text; - -moz-user-select: text; - -ms-user-select: text; - user-select: text; -} - -.params .name, .props .name, .name code { - color: #4D4E53; - font-family: Consolas, Monaco, 'Andale Mono', monospace; - font-size: 100%; -} - -.params td.description > p:first-child, -.props td.description > p:first-child -{ - margin-top: 0; - padding-top: 0; -} - -.params td.description > p:last-child, -.props td.description > p:last-child -{ - margin-bottom: 0; - padding-bottom: 0; -} - -.disabled { - color: #454545; -} diff --git a/docs/styles/prettify-jsdoc.css b/docs/styles/prettify-jsdoc.css deleted file mode 100644 index 5a2526e..0000000 --- a/docs/styles/prettify-jsdoc.css +++ /dev/null @@ -1,111 +0,0 @@ -/* JSDoc prettify.js theme */ - -/* plain text */ -.pln { - color: #000000; - font-weight: normal; - font-style: normal; -} - -/* string content */ -.str { - color: #006400; - font-weight: normal; - font-style: normal; -} - -/* a keyword */ -.kwd { - color: #000000; - font-weight: bold; - font-style: normal; -} - -/* a comment */ -.com { - font-weight: normal; - font-style: italic; -} - -/* a type name */ -.typ { - color: #000000; - font-weight: normal; - font-style: normal; -} - -/* a literal value */ -.lit { - color: #006400; - font-weight: normal; - font-style: normal; -} - -/* punctuation */ -.pun { - color: #000000; - font-weight: bold; - font-style: normal; -} - -/* lisp open bracket */ -.opn { - color: #000000; - font-weight: bold; - font-style: normal; -} - -/* lisp close bracket */ -.clo { - color: #000000; - font-weight: bold; - font-style: normal; -} - -/* a markup tag name */ -.tag { - color: #006400; - font-weight: normal; - font-style: normal; -} - -/* a markup attribute name */ -.atn { - color: #006400; - font-weight: normal; - font-style: normal; -} - -/* a markup attribute value */ -.atv { - color: #006400; - font-weight: normal; - font-style: normal; -} - -/* a declaration */ -.dec { - color: #000000; - font-weight: bold; - font-style: normal; -} - -/* a variable name */ -.var { - color: #000000; - font-weight: normal; - font-style: normal; -} - -/* a function name */ -.fun { - color: #000000; - font-weight: bold; - font-style: normal; -} - -/* Specify class=linenums on a pre to get line numbering */ -ol.linenums { - margin-top: 0; - margin-bottom: 0; -} diff --git a/docs/styles/prettify-tomorrow.css b/docs/styles/prettify-tomorrow.css deleted file mode 100644 index b6f92a7..0000000 --- a/docs/styles/prettify-tomorrow.css +++ /dev/null @@ -1,132 +0,0 @@ -/* Tomorrow Theme */ -/* Original theme - https://github.com/chriskempson/tomorrow-theme */ -/* Pretty printing styles. Used with prettify.js. */ -/* SPAN elements with the classes below are added by prettyprint. */ -/* plain text */ -.pln { - color: #4d4d4c; } - -@media screen { - /* string content */ - .str { - color: #718c00; } - - /* a keyword */ - .kwd { - color: #8959a8; } - - /* a comment */ - .com { - color: #8e908c; } - - /* a type name */ - .typ { - color: #4271ae; } - - /* a literal value */ - .lit { - color: #f5871f; } - - /* punctuation */ - .pun { - color: #4d4d4c; } - - /* lisp open bracket */ - .opn { - color: #4d4d4c; } - - /* lisp close bracket */ - .clo { - color: #4d4d4c; } - - /* a markup tag name */ - .tag { - color: #c82829; } - - /* a markup attribute name */ - .atn { - color: #f5871f; } - - /* a markup attribute value */ - .atv { - color: #3e999f; } - - /* a declaration */ - .dec { - color: #f5871f; } - - /* a variable name */ - .var { - color: #c82829; } - - /* a function name */ - .fun { - color: #4271ae; } } -/* Use higher contrast and text-weight for printable form. */ -@media print, projection { - .str { - color: #060; } - - .kwd { - color: #006; - font-weight: bold; } - - .com { - color: #600; - font-style: italic; } - - .typ { - color: #404; - font-weight: bold; } - - .lit { - color: #044; } - - .pun, .opn, .clo { - color: #440; } - - .tag { - color: #006; - font-weight: bold; } - - .atn { - color: #404; } - - .atv { - color: #060; } } -/* Style */ -/* -pre.prettyprint { - background: white; - font-family: Consolas, Monaco, 'Andale Mono', monospace; - font-size: 12px; - line-height: 1.5; - border: 1px solid #ccc; - padding: 10px; } -*/ - -/* Specify class=linenums on a pre to get line numbering */ -ol.linenums { - margin-top: 0; - margin-bottom: 0; } - -/* IE indents via margin-left */ -li.L0, -li.L1, -li.L2, -li.L3, -li.L4, -li.L5, -li.L6, -li.L7, -li.L8, -li.L9 { - /* */ } - -/* Alternate shading for lines */ -li.L1, -li.L3, -li.L5, -li.L7, -li.L9 { - /* */ } diff --git a/docs/tauri-migration.md b/docs/tauri-migration.md index ba2ea37..693b665 100644 --- a/docs/tauri-migration.md +++ b/docs/tauri-migration.md @@ -16,13 +16,16 @@ Cloud actions that spend CTU require an explicit user action. ## Migration and rollback -Base: `807e2c9`. The Electron source and tests remain as migration reference; its package -manifest is saved alongside this document. Tauri uses `desktop/` and `src-tauri/`, its own -application identifier and OS credential entry. Existing Electron settings and encrypted +The [pre-Tauri commit](https://github.com/CoreTrace/coretrace-gui/tree/56a6ecf6dee7e15aa1eb9d4a91c8a01383c8020b) +contains the Electron source, tests, assets and dependency lockfile. Tauri uses +`desktop/` and `src-tauri/`, a new application identifier and its own OS credential +entry. Existing Electron settings and encrypted credentials are not rewritten or implicitly imported. Sign in once in the new application. -Rollback by checking out the base revision in a separate clean worktree and installing its -dependencies. Never reset over user changes. The pre-existing `native/` directory and ATP -archive modification belong to the user and are excluded from migration commits. +To run the old app, check it out in a separate worktree and follow its README. + +```sh +git worktree add --detach ../coretrace-electron 56a6ecf6dee7e15aa1eb9d4a91c8a01383c8020b +``` ## Stages @@ -31,8 +34,8 @@ archive modification belong to the user and are excluded from migration commits. 3. Desktop UI, dashboards, IDE and analysis flows. 4. Regression checks, desktop build, CI and operating documentation. -The previous terminal, WSL manager, local LLM integrations, extension experiments and -Electron updater are not part of the requested replacement. They remain in the old source. +The pre-Tauri commit also contains the Electron terminal, WSL manager, local LLM +integrations and updater. No production deployment, paid analysis or GitHub publication is performed during validation. References: https://v2.tauri.app/start/frontend/vite/ and diff --git a/jsdoc.conf.json b/jsdoc.conf.json deleted file mode 100644 index 8c4f4b9..0000000 --- a/jsdoc.conf.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "source": { - "include": [ - "./src/", - "./README.md" - ], - "includePattern": "\\.(js)$", - "exclude": [ - "./node_modules/", - "./dist/", - "./build/" - ] - }, - "opts": { - "destination": "./docs/", - "recurse": true, - "readme": "./README.md" - }, - "plugins": [ - "plugins/markdown" - ], - "templates": { - "cleverLinks": false, - "monospaceLinks": false - }, - "sourceType": "module", - "tags": { - "allowUnknownTags": true, - "dictionaries": ["jsdoc", "closure"] - }, - "metadata": { - "title": "CTrace GUI Documentation", - "description": "Complete documentation for the CTrace GUI Electron application" - } -} \ No newline at end of file diff --git a/scripts/benchmark-startup.sh b/scripts/benchmark-startup.sh deleted file mode 100755 index 15fdeda..0000000 --- a/scripts/benchmark-startup.sh +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -if [[ $# -lt 1 ]]; then - echo "Usage: $0 [runs] [timeout-seconds]" >&2 - exit 1 -fi - -APP_PATH="$1" -RUNS="${2:-3}" -TIMEOUT_SECONDS="${3:-15}" - -if [[ ! -x "$APP_PATH" ]]; then - echo "Error: app is not executable: $APP_PATH" >&2 - exit 1 -fi - -extract_ms() { - local pattern="$1" - local file="$2" - local value - value="$(grep -m1 "$pattern" "$file" | sed -n 's/.*(\([0-9][0-9]*\)ms since process start).*/\1/p')" - if [[ -n "$value" ]]; then - printf '%s' "$value" - else - printf 'NA' - fi -} - -extract_renderer_ms() { - local file="$1" - local value - value="$(grep -m1 'restored-session-ready' "$file" | sed -n 's/.*rendererElapsedMs=\([0-9][0-9]*\)ms.*/\1/p')" - if [[ -n "$value" ]]; then - printf '%s' "$value" - else - printf 'NA' - fi -} - -echo "run,when_ready_ms,window_created_ms,ready_to_show_ms,restored_session_ready_ms,renderer_restore_ms" - -for run in $(seq 1 "$RUNS"); do - log_file="$(mktemp)" - timeout --signal=INT "${TIMEOUT_SECONDS}s" "$APP_PATH" >"$log_file" 2>&1 || true - - when_ready_ms="$(extract_ms 'app.whenReady resolved' "$log_file")" - window_created_ms="$(extract_ms 'BrowserWindow created' "$log_file")" - ready_to_show_ms="$(extract_ms 'Main window ready-to-show' "$log_file")" - restored_session_ready_ms="$(extract_ms 'restored-session-ready' "$log_file")" - renderer_restore_ms="$(extract_renderer_ms "$log_file")" - - echo "${run},${when_ready_ms},${window_created_ms},${ready_to_show_ms},${restored_session_ready_ms},${renderer_restore_ms}" - rm -f "$log_file" -done diff --git a/scripts/build-renderer-bundle.js b/scripts/build-renderer-bundle.js deleted file mode 100644 index b55af1b..0000000 --- a/scripts/build-renderer-bundle.js +++ /dev/null @@ -1,59 +0,0 @@ -const fs = require('fs'); -const path = require('path'); -const esbuild = require('esbuild'); - -const rootDir = path.resolve(__dirname, '..'); -const isDev = process.argv.includes('--dev'); - -const outfile = path.join(rootDir, 'src', 'renderer', 'bundle.js'); - -const inputFiles = [ - 'src/renderer/utils/escapeHtml.js', - 'src/renderer/utils/fileTypeUtils.js', - 'src/renderer/utils/syntaxHighlighter.js', - 'src/renderer/managers/NotificationManager.js', - 'src/renderer/managers/MonacoEditorManager.js', - 'src/renderer/managers/TabManager.js', - 'src/renderer/managers/SplitPaneManager.js', - 'src/renderer/managers/SearchManager.js', - 'src/renderer/managers/FileOperationsManager.js', - 'src/renderer/managers/DiagnosticsManager.js', - 'src/renderer/managers/StateManager.js', - 'src/renderer/managers/TerminalManager.js', - 'src/renderer/managers/PerformanceManager.js', - 'src/renderer/managers/WSLManager.js', - 'src/renderer/managers/UpdaterManager.js', - 'src/renderer/managers/ResizeManager.js', - 'src/renderer/managers/CTraceRunner.js', - 'src/renderer/managers/CloudRunManager.js', - 'src/renderer/components/ActivityBar.js', - 'src/renderer/components/FileTree.js', - 'src/renderer/components/EditorPanel.js', - 'src/renderer/components/AssistantPanel.js', - 'src/renderer/components/CloudPanel.js', - 'src/renderer/UIController.js', -]; - -// Concatenate sources in dependency order (same as before — each file is a -// self-contained IIFE that assigns its class to window.ClassName). -const header = '/* Auto-generated — do not edit. Run: npm run build:renderer */\n/* eslint-disable */\n'; -const concatenated = header + inputFiles - .map((rel) => { - const src = fs.readFileSync(path.join(rootDir, rel), 'utf8').trimEnd(); - return `// ----- ${rel} -----\n${src}\n`; - }) - .join('\n'); - -// Use esbuild *transform* (not bundle) — no module resolution, no require() -// wrapping. Just minification and source maps applied to the flat script. -const result = esbuild.transformSync(concatenated, { - loader: 'js', - minify: !isDev, - sourcemap: isDev ? 'inline' : false, - // Keep the global class names intact during minification (they are referenced - // as window.ClassName across the script, so they must not be renamed). - minifyIdentifiers: false, -}); - -fs.writeFileSync(outfile, result.code, 'utf8'); -console.log(`[build:renderer] ${isDev ? 'Dev' : 'Production'} bundle → src/renderer/bundle.js`); diff --git a/scripts/build-verify.sh b/scripts/build-verify.sh deleted file mode 100644 index 2b3df90..0000000 --- a/scripts/build-verify.sh +++ /dev/null @@ -1,56 +0,0 @@ -#!/bin/bash - -# Build verification script for CTrace GUI -# Tests building for different platforms - -echo "🚀 CTrace GUI - Build Verification Script" -echo "==========================================" - -# Check if we're in the right directory -if [ ! -f "package.json" ]; then - echo "❌ Error: package.json not found. Please run this script from the project root." - exit 1 -fi - -# Clean previous builds -echo "🧹 Cleaning previous builds..." -rm -rf dist/ - -# Build for current platform -echo "🔨 Building for current platform..." -npm run dist - -if [ $? -eq 0 ]; then - echo "✅ Build successful!" - echo "📦 Generated files:" - ls -la dist/ - - # Show build artifacts - echo "" - echo "📋 Build Summary:" - echo "- Configuration: $(ls dist/builder-effective-config.yaml 2>/dev/null && echo "✅ Found" || echo "❌ Missing")" - echo "- Linux AppImage: $(ls dist/*.AppImage 2>/dev/null && echo "✅ Found" || echo "❌ Missing")" - echo "- Windows NSIS: $(ls dist/*.exe 2>/dev/null && echo "✅ Found" || echo "❌ Missing")" - echo "- macOS DMG: $(ls dist/*.dmg 2>/dev/null && echo "✅ Found" || echo "❌ Missing")" - - # Check AppImage functionality (Linux only) - if [ -f dist/*.AppImage ]; then - echo "" - echo "🧪 Testing AppImage functionality..." - chmod +x dist/*.AppImage - echo "✅ AppImage is executable" - - # Extract and check contents - if command -v unsquashfs &> /dev/null; then - echo "🔍 Extracting AppImage contents for inspection..." - # Note: This is just a verification, not actually running the app - fi - fi - - echo "" - echo "🎉 Build verification completed successfully!" - -else - echo "❌ Build failed!" - exit 1 -fi \ No newline at end of file diff --git a/scripts/patch-node-pty-spectre.js b/scripts/patch-node-pty-spectre.js deleted file mode 100644 index 9280563..0000000 --- a/scripts/patch-node-pty-spectre.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Patches node-pty/binding.gyp to disable Spectre mitigation. - * - * node-pty sets 'SpectreMitigation': 'Spectre' in target_defaults for Windows. - * VS 2019 Build Tools ships without Spectre-mitigated libs by default, causing - * MSB8040 during electron-rebuild. Changing the value to 'false' in binding.gyp - * fixes it at the source — before node-gyp configure regenerates the vcxproj files. - * - * Run automatically via the postinstall npm script. - */ - -const fs = require('fs'); -const path = require('path'); - -const filesToPatch = [ - path.join(__dirname, '..', 'node_modules', 'node-pty', 'binding.gyp'), - path.join(__dirname, '..', 'node_modules', 'node-pty', 'deps', 'winpty', 'src', 'winpty.gyp'), -]; - -let anyPatched = false; - -for (const filePath of filesToPatch) { - const label = path.relative(path.join(__dirname, '..', 'node_modules', 'node-pty'), filePath); - - if (!fs.existsSync(filePath)) { - console.log(`[patch-node-pty] ${label} not found — skipping.`); - continue; - } - - const original = fs.readFileSync(filePath, 'utf8'); - - // Replace 'Spectre' (or any non-false value) with 'false' - const updated = original.replace( - /('SpectreMitigation'\s*:\s*)'[^']+'/g, - "$1'false'" - ); - - if (updated === original) { - console.log(`[patch-node-pty] ${label}: nothing to patch (already clean).`); - } else { - fs.writeFileSync(filePath, updated, 'utf8'); - console.log(`[patch-node-pty] ${label}: patched SpectreMitigation → false`); - anyPatched = true; - } -} - -if (!anyPatched) { - console.log('[patch-node-pty] Nothing to patch (already clean).'); -} diff --git a/scripts/release.sh b/scripts/release.sh deleted file mode 100755 index 1e73e74..0000000 --- a/scripts/release.sh +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -# Cut a release: bump package.json, tag, push. CI does the rest — the tag is the -# only thing that triggers a build and publish (see .github/workflows/release.yml). -# -# Usage: -# ./scripts/release.sh -# Examples: -# ./scripts/release.sh minor # 5.1.0 -> 5.2.0 -# ./scripts/release.sh 5.2.0-beta.1 # cut a beta on the beta channel -# ./scripts/release.sh prerelease # 5.2.0-beta.1 -> 5.2.0-beta.2 -# -# Versioning rules, enforced below and again in CI: -# - stable releases are X.Y.Z -# - prereleases are X.Y.Z-beta.N, and nothing else: electron-builder names the -# update manifest after the prerelease identifier, and `beta` is the only one -# the in-app channel selector reads (src/main/ipc/updaterHandlers.js) -# - the git tag is always v - -if [ $# -lt 1 ]; then - echo "Usage: $0 " - exit 1 -fi - -if [ ! -f "package.json" ]; then - echo "Error: run this script from the project root (package.json missing)." - exit 1 -fi - -RELEASE_INPUT="${1#v}" - -CURRENT_BRANCH="$(git rev-parse --abbrev-ref HEAD)" -if [ "$CURRENT_BRANCH" != "main" ]; then - echo "Error: release must be cut from main (current: $CURRENT_BRANCH)." - exit 1 -fi - -# Refuse to release a dirty tree. Committing stray changes on the user's behalf -# is how a release ends up containing something nobody reviewed. -if ! git diff --quiet || ! git diff --cached --quiet; then - echo "Error: working tree has uncommitted changes. Commit or stash them first." - git status --short - exit 1 -fi - -echo "Fetching tags from origin..." -git fetch --tags --quiet origin - -echo "Building renderer bundle..." -npm run build:renderer - -echo "Running tests..." -npm test - -# `npm version` prints the new version and writes package.json + a tag for us. -npm version "$RELEASE_INPUT" --message "chore(release): %s" > /dev/null - -NEW_VERSION="$(node -p "require('./package.json').version")" -TARGET_TAG="v${NEW_VERSION}" - -# Validate what npm actually produced, before anything reaches origin. -if [[ "$NEW_VERSION" == *-* ]] && [[ ! "$NEW_VERSION" =~ -beta\.[0-9]+$ ]]; then - echo "Error: prerelease versions must end in -beta.N (got ${NEW_VERSION})." - echo "Rolling back the version commit and tag." - git tag -d "$TARGET_TAG" >/dev/null 2>&1 || true - git reset --hard HEAD~1 - exit 1 -fi - -if git ls-remote --exit-code --tags origin "$TARGET_TAG" >/dev/null 2>&1; then - echo "Error: tag ${TARGET_TAG} already exists on origin." - echo "Rolling back the version commit and tag." - git tag -d "$TARGET_TAG" >/dev/null 2>&1 || true - git reset --hard HEAD~1 - exit 1 -fi - -if [[ "$NEW_VERSION" == *-beta.* ]]; then - echo "Cutting ${TARGET_TAG} on the beta channel." -else - echo "Cutting ${TARGET_TAG} on the stable channel." -fi - -echo "Pushing main and ${TARGET_TAG} to origin..." -git push origin main -git push origin "$TARGET_TAG" - -echo -echo "Done. GitHub Actions builds and publishes ${TARGET_TAG} for Windows, Linux and macOS." -echo "Watch it at: https://github.com/CoreTrace/coretrace-gui/actions" diff --git a/scripts/remove-locales.js b/scripts/remove-locales.js deleted file mode 100644 index e702d92..0000000 --- a/scripts/remove-locales.js +++ /dev/null @@ -1,19 +0,0 @@ -const fs = require("fs"); -const path = require("path"); - -module.exports = async function (context) { - const localesDir = path.join(context.appOutDir, "locales"); - - if (fs.existsSync(localesDir)) { - const files = fs.readdirSync(localesDir); - - for (const file of files) { - // Keep only English locales, delete others - if (!file.startsWith("en")) { - fs.unlinkSync(path.join(localesDir, file)); - } - } - - console.log("Removed unused locales, kept only English."); - } -}; diff --git a/src/index.html b/src/index.html deleted file mode 100644 index 511d197..0000000 --- a/src/index.html +++ /dev/null @@ -1,444 +0,0 @@ - - - - - - - - CTrace GUI - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
-
-
-
- CTrace -
- Coretrace GUI - -
-
-
-
-
-
- - - -
-
-
- -
- -
- -
-
- - - -
-
- - - -
- -
- - - -
- - -
- -
- - - - -
-
- - - - -
- - -
- - - - -
- -
- - - - -
-
- -
-

Welcome to CTraceGUI

-

Import a file to start analysis!

-
- - - -
-

- You can also use the File menu above to access all file operations. -

-
- - - -
-
- - -
-
- - -
- - -
- -
- - -
-
- -
- - - -
- - - - - - - - - -
-
- - -
-
- - -
-
- Ln 1, Col 1 - UTF-8 - Plain Text - -
-
- - CoreTrace latest: checking... - CTraceGUI v0.1.0 -
-
-
- - -
-
-
- Ctrace Tools - -
-
- -
-
- - CTrace Configuration -
- -
- - -
- -
- - -
-
- - -
-
- -
Run CTrace to analyze your code
-
Configure arguments above and click Run
-
-
-
-
-
- - diff --git a/src/main.js b/src/main.js deleted file mode 100644 index 0522e8d..0000000 --- a/src/main.js +++ /dev/null @@ -1,783 +0,0 @@ -/** - * @fileoverview Main entry point for the CTrace GUI Electron application. - * - * This file initializes the Electron app, creates the main window, and sets up - * all IPC handlers for communication between the main and renderer processes. - * - * @author CTrace GUI Team - * @version 1.0.0 - */ - -const { app, BrowserWindow, nativeImage, dialog, shell, Menu } = require('electron'); -const path = require('path'); -const os = require('os'); -const { spawn } = require('child_process'); - -const hardwareAccelerationEnabled = process.env.CTRACE_DISABLE_GPU !== '1'; - -const appLaunchStartedAt = Date.now(); -const appLaunchHrStartedAt = process.hrtime.bigint(); - -function formatStartupTimestamp(timestamp) { - return new Date(timestamp).toISOString(); -} - -function getStartupElapsedMs() { - return Number(process.hrtime.bigint() - appLaunchHrStartedAt) / 1e6; -} - -function logStartupMilestone(message) { - const now = Date.now(); - console.log( - `[StartupTiming] ${message} at ${formatStartupTimestamp(now)} ` + - `(${Math.round(getStartupElapsedMs())}ms since process start)` - ); -} - -console.log(`[StartupTiming] Main process entry at ${formatStartupTimestamp(appLaunchStartedAt)}`); - -// Keep GPU acceleration enabled by default for renderer responsiveness. -// Set CTRACE_DISABLE_GPU=1 to force software rendering when diagnosing GPU driver issues. -if (!hardwareAccelerationEnabled) { - app.disableHardwareAcceleration(); - console.log('[Rendering] Hardware acceleration disabled via CTRACE_DISABLE_GPU=1'); -} else { - console.log('[Rendering] Hardware acceleration enabled'); -} -app.commandLine.appendSwitch('disable-http-cache'); -app.commandLine.appendSwitch('disk-cache-size', '1'); -app.commandLine.appendSwitch('disable-gpu-shader-disk-cache'); - -// Import IPC handlers -const { setupFileHandlers } = require('./main/ipc/fileHandlers'); -const { setupEditorHandlers } = require('./main/ipc/editorHandlers'); -const { setupCtraceHandlers, shutdownCtraceServer } = require('./main/ipc/ctraceHandlers'); -const { setupAssistantHandlers } = require('./main/ipc/assistantHandlers'); -const { setupStateHandlers } = require('./main/ipc/stateHandlers'); -const { setupUpdaterHandlers, setupAutoUpdater } = require('./main/ipc/updaterHandlers'); -const { setupTerminalHandlers, cleanupTerminals } = require('./main/ipc/terminalHandlers'); -const { setupBackendSettingsHandlers } = require('./main/ipc/backendSettingsHandlers'); -const { setupSecureStorageHandlers } = require('./main/ipc/secureStorageHandlers'); -const { setupAppInfoHandlers } = require('./main/ipc/appInfoHandlers'); -const { setupCloudHandlers } = require('./main/ipc/cloudHandlers'); - -const MONACO_BASE_PATH = path.join(__dirname, '..', 'node_modules', 'monaco-editor', 'min', 'vs').replace(/\\/g, '/'); - -/** - * Creates and configures the main application window. - * - * This function sets up the BrowserWindow with appropriate dimensions, - * icon, and security settings. It loads the main HTML file and configures - * the window appearance. - * - * @function createWindow - * @returns {BrowserWindow} The created main window instance - * - * @example - * const mainWindow = createWindow(); - */ -function createWindow () { - logStartupMilestone('createWindow start'); - const iconPath = path.join(__dirname, '../assets/ctrace.png'); - const iconApp = nativeImage.createFromPath(iconPath); - const hiddenTitleBarStyle = process.platform === 'darwin' ? 'hiddenInset' : 'hidden'; - logStartupMilestone('Window icon loaded'); - - logStartupMilestone('Constructing BrowserWindow'); - const win = new BrowserWindow({ - width: 1200, - height: 800, - minWidth: 800, - minHeight: 600, - icon: iconApp, - backgroundColor: '#0b1017', - frame: false, - titleBarStyle: hiddenTitleBarStyle, - titleBarOverlay: false, - autoHideMenuBar: true, - webPreferences: { - nodeIntegration: false, - contextIsolation: true, - sandbox: true, - preload: path.join(__dirname, 'preload.js'), - additionalArguments: [ - `--ctrace-hardware-acceleration=${hardwareAccelerationEnabled ? 'on' : 'off'}`, - `--ctrace-monaco-base-path=${MONACO_BASE_PATH}` - ] - } - }); - - logStartupMilestone('BrowserWindow created'); - - win.once('ready-to-show', () => { - logStartupMilestone('Main window ready-to-show'); - }); - - win.webContents.once('did-finish-load', () => { - logStartupMilestone('Renderer did-finish-load'); - // Give the renderer keyboard focus immediately so shortcuts work - // without requiring the user to click inside the editor first. - win.webContents.focus(); - }); - - // Re-register DevTools shortcuts that were removed by Menu.setApplicationMenu(null). - // DevTools stay reachable in development; packaged builds need CTRACE_DEVTOOLS=1. - const devToolsAllowed = !app.isPackaged || process.env.CTRACE_DEVTOOLS === '1'; - win.webContents.on('before-input-event', (_event, input) => { - if (!devToolsAllowed || input.type !== 'keyDown') return; - const isF12 = input.key === 'F12'; - const isCtrlShiftI = (input.control || input.meta) && input.shift && input.key === 'I'; - if (isF12 || isCtrlShiftI) { - if (win.webContents.isDevToolsOpened()) { - win.webContents.closeDevTools(); - } else { - win.webContents.openDevTools(); - } - } - }); - - logStartupMilestone('Calling loadFile(src/index.html)'); - win.loadFile('src/index.html'); - - // Custom window controls for frameless window - win.on('maximize', () => { - win.webContents.send('window-maximized', true); - }); - - win.on('unmaximize', () => { - win.webContents.send('window-maximized', false); - }); - - return win; -} - - - -/** - * Locks a renderer down to the bundled UI: it must never navigate away from - * index.html, open new windows, or embed tags. The renderer holds a - * privileged IPC bridge, so any foreign document loaded into it would inherit - * that bridge. - * - * @param {Electron.WebContents} contents - */ -function hardenWebContents(contents) { - contents.on('will-navigate', (event, url) => { - console.warn('[Security] Blocked navigation to', url); - event.preventDefault(); - }); - contents.on('will-redirect', (event, url) => { - console.warn('[Security] Blocked redirect to', url); - event.preventDefault(); - }); - contents.on('will-attach-webview', (event) => { - console.warn('[Security] Blocked attachment'); - event.preventDefault(); - }); - contents.setWindowOpenHandler(({ url }) => { - console.warn('[Security] Blocked window.open to', url); - return { action: 'deny' }; - }); -} - -app.on('web-contents-created', (_event, contents) => { - hardenWebContents(contents); -}); - -/** - * Detects if WSL (Windows Subsystem for Linux) is available on Windows. - * - * @async - * @function detectWSL - * @returns {Promise} True if WSL is available, false otherwise - */ -// SOCAT is no longer required: the backend now runs in HTTP serve mode. - -/** - * Comprehensive WSL status detection - * @returns {Promise} Object with available, hasDistros, error, and distributions properties - */ -async function detectWSLStatus() { - return new Promise((resolve) => { - if (os.platform() !== 'win32') { - resolve({ available: true, hasDistros: true, distributions: ['linux'] }); - return; - } - - // First check if WSL command exists - const statusChild = spawn('wsl', ['--status'], { stdio: 'pipe', windowsHide: true }); - - let statusOutput = ''; - let statusError = ''; - - statusChild.stdout.on('data', (data) => { - statusOutput += data.toString(); - }); - - statusChild.stderr.on('data', (data) => { - statusError += data.toString(); - }); - - statusChild.on('error', () => { - resolve({ available: false, hasDistros: false, error: 'WSL is not installed' }); - }); - - statusChild.on('close', (statusCode) => { - if (statusCode !== 0) { - resolve({ available: false, hasDistros: false, error: 'WSL is not available' }); - return; - } - - // WSL exists, now check for installed distributions - const listChild = spawn('wsl', ['--list', '--quiet'], { stdio: 'pipe', windowsHide: true }); - - let listOutput = ''; - - listChild.stdout.on('data', (data) => { - listOutput += data.toString(); - }); - - listChild.on('error', () => { - resolve({ available: true, hasDistros: false, error: 'Cannot check WSL distributions' }); - }); - - listChild.on('close', (listCode) => { - const distributions = listOutput.trim().split('\n') - .map(line => line.trim()) - .filter(line => line.length > 0 && !line.includes('Windows Subsystem')) - .filter(line => !line.toLowerCase().includes('docker')); - - const hasDistros = distributions.length > 0 && !statusError.includes('no installed distributions'); - - if (!hasDistros) { - const errorMsg = statusError.includes('no installed distributions') || listOutput.includes('no installed distributions') - ? 'WSL is installed but no Linux distributions are available' - : 'No WSL distributions found'; - resolve({ available: true, hasDistros: false, error: errorMsg, distributions: [] }); - } else { - resolve({ available: true, hasDistros: true, distributions }); - } - }); - - // Timeout for list command - setTimeout(() => { - listChild.kill(); - resolve({ available: true, hasDistros: false, error: 'Timeout checking WSL distributions', distributions: [] }); - }, 10000); - }); - - // Timeout for status command - setTimeout(() => { - statusChild.kill(); - resolve({ available: false, hasDistros: false, error: 'Timeout checking WSL status' }); - }, 10000); - }); -} - -/** - * Legacy function for backward compatibility - * @returns {Promise} - */ -async function detectWSL() { - const status = await detectWSLStatus(); - return status.available && status.hasDistros; -} - -/** - * Shows enhanced WSL installation dialog based on WSL status - * @param {Object} wslStatus - Current WSL status - * @returns {Promise} True if user wants to proceed, false otherwise - */ -async function showWSLSetupDialog(wslStatus) { - if (!wslStatus.available) { - // WSL not installed at all - const result = await dialog.showMessageBox({ - type: 'warning', - title: 'WSL Required for CTrace', - message: 'Windows Subsystem for Linux (WSL) is required for CTrace functionality.', - detail: 'CTrace uses a Linux binary that requires WSL to run on Windows.\n\nWould you like to install WSL now? This requires administrator privileges and a system restart.', - buttons: ['Install WSL Automatically', 'Install Manually', 'Continue Without WSL', 'Exit Application'], - defaultId: 0, - cancelId: 3, - icon: nativeImage.createFromPath(path.join(__dirname, '../assets/ctrace.png')) - }); - - if (result.response === 0) { - // Automatic installation - await installWSLAutomatically(); - return true; - } else if (result.response === 1) { - // Manual installation - showManualInstallationInstructions(); - return true; - } else if (result.response === 2) { - // Continue without WSL - await showLimitedFunctionalityDialog(); - return true; - } else { - // Exit application - return false; - } - - } else if (!wslStatus.hasDistros) { - // WSL installed but no distributions - const result = await dialog.showMessageBox({ - type: 'info', - title: 'WSL Distribution Required', - message: 'WSL is installed but no Linux distributions are available.', - detail: 'CTrace requires a Linux distribution to run. Ubuntu is recommended.\n\nWould you like to install Ubuntu now?', - buttons: ['Install Ubuntu', 'Choose Different Distribution', 'Continue Without CTrace', 'Exit Application'], - defaultId: 0, - cancelId: 3, - icon: nativeImage.createFromPath(path.join(__dirname, '../assets/ctrace.png')) - }); - - if (result.response === 0) { - // Install Ubuntu - await installWSLDistribution('Ubuntu'); - return true; - } else if (result.response === 1) { - // Show distribution options - await showDistributionOptions(); - return true; - } else if (result.response === 2) { - // Continue without CTrace - await showLimitedFunctionalityDialog(); - return true; - } else { - // Exit application - return false; - } - } - - return true; // WSL is fully available -} - -/** - * Install WSL automatically using PowerShell - */ -async function installWSLAutomatically() { - try { - console.log('Attempting to install WSL automatically...'); - - // Show progress dialog - dialog.showMessageBox({ - type: 'info', - title: 'Installing WSL', - message: 'Installing Windows Subsystem for Linux...', - detail: 'This may take a few minutes. Please wait and follow any prompts that appear.', - buttons: ['OK'] - }); - - // Run WSL installation command with Ubuntu - const child = spawn('powershell', [ - '-Command', - 'Start-Process', - 'powershell', - '-ArgumentList', '"wsl --install Ubuntu"', - '-Verb', 'RunAs' - ], { stdio: 'pipe', windowsHide: true }); - - child.on('error', (err) => { - console.error('Failed to start WSL installation:', err); - dialog.showErrorBox( - 'Installation Failed', - `Failed to start WSL installation: ${err.message}\n\nPlease try manual installation instead.` - ); - }); - - child.on('close', (code) => { - console.log(`WSL installation completed with code: ${code}`); - - dialog.showMessageBox({ - type: 'info', - title: 'WSL Installation Started', - message: 'WSL and Ubuntu installation has been initiated!', - detail: 'Please follow any prompts that appear. You may need to:\n\n1. Allow administrator access\n2. Restart your computer when prompted\n3. Complete Ubuntu setup (username/password)\n4. Restart this application\n\nThe installation will continue in the background.', - buttons: ['Got it!'] - }); - }); - - } catch (error) { - console.error('Error during WSL installation:', error); - dialog.showErrorBox( - 'Installation Error', - `Failed to install WSL: ${error.message}\n\nPlease try manual installation instead.` - ); - } -} - -/** - * Show manual installation instructions - */ -function showManualInstallationInstructions() { - dialog.showMessageBox({ - type: 'info', - title: 'Manual WSL Installation', - message: 'Manual Installation Instructions', - detail: `To install WSL manually:\n\n` + - `1. Open PowerShell as Administrator\n` + - ` (Right-click Start → "Windows PowerShell (Admin)")\n\n` + - `2. Run: wsl --install Ubuntu\n\n` + - `3. Restart your computer when prompted\n\n` + - `4. Complete Ubuntu setup (create username/password)\n\n` + - `5. Restart this application\n\n` + - `For more details, the Microsoft documentation will open next.`, - buttons: ['Open Documentation', 'Got it'] - }).then((result) => { - if (result.response === 0) { - shell.openExternal('https://docs.microsoft.com/en-us/windows/wsl/install'); - } - }); -} - -const WSL_DISTRIBUTION = 'Ubuntu'; - -/** - * Install the supported WSL distribution through an elevated prompt. - * - * The distribution name is a constant, never renderer input: the command below - * runs with administrator rights, so nothing from the UI may be spliced into it. - */ -async function installWSLDistribution() { - const distroName = WSL_DISTRIBUTION; - try { - console.log(`Installing WSL distribution: ${distroName}`); - - const child = spawn('powershell', [ - '-NoProfile', - '-Command', - `Start-Process -FilePath wsl -ArgumentList '--install','${distroName}' -Verb RunAs` - ], { stdio: 'ignore', windowsHide: true }); - - child.on('error', (err) => { - console.error(`Failed to install ${distroName}:`, err); - dialog.showErrorBox( - 'Installation Failed', - `Failed to install ${distroName}. Please try installing manually:\n\n1. Open PowerShell as Administrator\n2. Run: wsl --install ${distroName}` - ); - }); - - child.on('close', (code) => { - console.log(`${distroName} installation completed with code: ${code}`); - dialog.showMessageBox({ - type: 'info', - title: 'Distribution Installation', - message: `${distroName} installation has been initiated.`, - detail: 'Please follow the setup instructions when they appear. After setup is complete, restart this application to use CTrace.' - }); - }); - - } catch (error) { - console.error(`Error installing ${distroName}:`, error); - dialog.showErrorBox( - 'Installation Error', - `Failed to install ${distroName}: ${error.message}` - ); - } -} - -/** - * Show available WSL distributions for installation - */ -async function showDistributionOptions() { - try { - // Get list of available distributions - const child = spawn('wsl', ['--list', '--online'], { stdio: 'pipe', windowsHide: true }); - - let output = ''; - - child.stdout.on('data', (data) => { - output += data.toString(); - }); - - child.on('close', (code) => { - if (code === 0 && output) { - dialog.showMessageBox({ - type: 'info', - title: 'Available WSL Distributions', - message: 'Available Linux Distributions', - detail: `${output}\n\nRecommended: Ubuntu\n\nTo install a distribution:\n1. Open PowerShell\n2. Run: wsl --install \n3. Follow setup instructions`, - buttons: ['Install Ubuntu', 'Install Manually', 'Cancel'] - }).then((result) => { - if (result.response === 0) { - installWSLDistribution('Ubuntu'); - } else if (result.response === 1) { - showManualInstallationInstructions(); - } - }); - } else { - dialog.showErrorBox( - 'Cannot List Distributions', - 'Unable to get list of available distributions. Please install Ubuntu manually with:\n\nwsl --install Ubuntu' - ); - } - }); - - } catch (error) { - dialog.showErrorBox( - 'Error', - `Failed to get distribution list: ${error.message}` - ); - } -} - -/** - * Show limited functionality dialog - */ -async function showLimitedFunctionalityDialog() { - await dialog.showMessageBox({ - type: 'info', - title: 'Limited Functionality - CTrace GUI', - message: 'Running without WSL', - detail: 'CTrace GUI will run with limited functionality:\n\n✅ File editing and management\n✅ Syntax highlighting\n✅ Project navigation\n❌ CTrace static analysis\n❌ Code analysis reports\n\nTo enable full functionality, install WSL and restart the application.', - buttons: ['Continue'], - defaultId: 0 - }); -} - -//hot reload -try { - if (!app.isPackaged) { - require('electron-reload')(__dirname, { - electron: require(path.join(__dirname, '../node_modules/electron')), - hardResetMethod: 'exit' - }); - } -} catch (e) { - console.log("electron-reload not active"); -} - -/** - * Sets up IPC handlers for custom window controls. - * - * This function handles window minimize, maximize, and close operations - * for the custom frameless window title bar. - * - * @function setupWindowControls - * @param {BrowserWindow} window - The main window instance - */ -function setupWindowControls(window) { - const { ipcMain } = require('electron'); - - // Window minimize - ipcMain.on('window-minimize', () => { - window.minimize(); - }); - - // Window maximize/restore toggle - ipcMain.on('window-maximize-toggle', () => { - if (window.isMaximized()) { - window.unmaximize(); - } else { - window.maximize(); - } - }); - - // Window close - ipcMain.on('window-close', () => { - window.close(); - }); - - // WSL status check handler - ipcMain.on('check-wsl-status', async (event) => { - if (os.platform() === 'win32') { - const wslStatus = await detectWSLStatus(); - event.sender.send('wsl-status', wslStatus); - } else { - event.sender.send('wsl-status', { - available: true, - hasDistros: true, - platform: os.platform() - }); - } - }); - - // Handle manual WSL installation request from renderer - ipcMain.on('install-wsl', async () => { - if (os.platform() === 'win32') { - await installWSLAutomatically(); - } - }); - - // Handle WSL distribution installation request (always installs the - // supported distribution; the renderer cannot choose what runs elevated) - ipcMain.on('install-wsl-distro', async () => { - if (os.platform() === 'win32') { - await installWSLDistribution(); - } - }); - - // Handle WSL setup dialog request - ipcMain.on('show-wsl-setup', async () => { - if (os.platform() === 'win32') { - const wslStatus = await detectWSLStatus(); - await showWSLSetupDialog(wslStatus); - } - }); - - ipcMain.on('startup-ready', (_event, payload = {}) => { - const status = payload.restored ? 'restored-session-ready' : 'app-ready-without-restored-session'; - const rendererTimestamp = payload.timestamp ? formatStartupTimestamp(payload.timestamp) : 'unknown'; - const rendererElapsedMs = typeof payload.elapsedMs === 'number' ? Math.round(payload.elapsedMs) : 'unknown'; - logStartupMilestone( - `${status}; rendererTimestamp=${rendererTimestamp}; rendererElapsedMs=${rendererElapsedMs}ms` - ); - schedulePostStartupTasks(mainWindow); - }); -} - -// Global reference to main window -let mainWindow; -let postStartupTasksScheduled = false; - -function schedulePostStartupTasks(window) { - if (postStartupTasksScheduled || !window || window.isDestroyed()) return; - postStartupTasksScheduled = true; - - logStartupMilestone('Scheduling post-startup background tasks'); - - setTimeout(async () => { - try { - logStartupMilestone('Starting deferred auto-updater setup'); - await setupAutoUpdater(window); - logStartupMilestone('Deferred auto-updater setup complete'); - } catch (error) { - console.warn('[Main] Deferred auto-updater setup failed:', error?.message || error); - } - - setTimeout(async () => { - try { - // If the user configured a direct ctrace.exe binary, probe it first. - // Only fall back to the WSL HTTP server when no direct binary is set. - const { loadBackendSettings } = require('./main/ipc/backendSettingsHandlers'); - const settings = await loadBackendSettings().catch(() => ({})); - const directBinaryPath = settings && settings.directBinaryPath; - - if (directBinaryPath) { - console.log('[Main] Direct binary configured, probing:', directBinaryPath); - await new Promise((resolve) => { - const { spawn } = require('child_process'); - const probe = spawn(directBinaryPath, ['--version'], { - stdio: 'pipe', - windowsHide: true - }); - let out = ''; - probe.stdout.on('data', d => { out += d.toString(); }); - probe.stderr.on('data', d => { out += d.toString(); }); - probe.on('error', (err) => { - console.warn('[Main] Direct binary probe failed:', err.message, '— will use WSL server instead'); - resolve(false); - }); - probe.on('close', (code) => { - if (code === 0) { - console.log('[Main] Direct binary OK:', out.trim() || '(no version output)'); - } else { - console.warn('[Main] Direct binary exited with code', code, '— will use WSL server on next run'); - } - resolve(code === 0); - }); - setTimeout(() => { try { probe.kill(); } catch (_) {} resolve(false); }, 5000); - }); - // Direct binary is available — skip server preload. - return; - } - - console.log('[Main] Preloading CTrace server...'); - const { ensureServerRunning } = require('./main/utils/ctraceServeClient'); - await ensureServerRunning(); - console.log('[Main] CTrace server preloaded successfully'); - } catch (error) { - console.warn('[Main] CTrace server preload failed (will retry on first request):', error.message); - } - }, 1000); - }, 0); -} - -let isQuitting = false; -app.on('before-quit', async (event) => { - // Ensure we call the backend shutdown route exactly once. - if (isQuitting) return; - isQuitting = true; - - // Allow shutdown to complete before exiting. - event.preventDefault(); - - try { - // Request renderer to save state before quitting - if (mainWindow && !mainWindow.isDestroyed()) { - console.log('[Main] Requesting state save before quit...'); - mainWindow.webContents.send('app-before-quit'); - - // Give renderer time to save state (max 3 seconds) - await new Promise(resolve => setTimeout(resolve, 3000)); - } - - // Shutdown ctrace server - await shutdownCtraceServer(); - cleanupTerminals(); - } catch (e) { - console.warn('Failed to shutdown ctrace server:', e?.message || e); - } finally { - app.quit(); - } -}); - -app.whenReady().then(async () => { - logStartupMilestone('app.whenReady resolved'); - // Remove the default application menu so that Electron's built-in - // Ctrl+W "Close Window" accelerator does not fire. The renderer handles - // Ctrl+W itself (closes the active editor tab). - Menu.setApplicationMenu(null); - // Create window first - mainWindow = createWindow(); - - // Setup IPC handlers - setupFileHandlers(mainWindow); - setupEditorHandlers(); - setupCtraceHandlers(); - setupAssistantHandlers(mainWindow); - setupStateHandlers(); - setupUpdaterHandlers(mainWindow); - setupTerminalHandlers(mainWindow); - setupBackendSettingsHandlers(mainWindow); - setupSecureStorageHandlers(); - setupAppInfoHandlers(); - setupCloudHandlers(mainWindow); - setupWindowControls(mainWindow); - mainWindow.once('ready-to-show', () => { - schedulePostStartupTasks(mainWindow); - }); - - // Check WSL status on Windows after window is ready - if (os.platform() === 'win32') { - // Give the window time to load, then check WSL - setTimeout(async () => { - const wslStatus = await detectWSLStatus(); - console.log('WSL Status detected:', wslStatus); - - // Send status to renderer - if (mainWindow && mainWindow.webContents) { - mainWindow.webContents.send('wsl-status', wslStatus); - } - - // Show setup dialog if WSL is not fully ready - if (!wslStatus.available || !wslStatus.hasDistros) { - const shouldContinue = await showWSLSetupDialog(wslStatus); - if (!shouldContinue) { - app.quit(); - return; - } - } - }, 2000); - } else { - // On non-Windows platforms, send ready status - mainWindow.webContents.once('did-finish-load', () => { - mainWindow.webContents.send('wsl-status', { - available: true, - hasDistros: true, - platform: os.platform() - }); - }); - } -}); diff --git a/src/main/cloud/cloudClient.js b/src/main/cloud/cloudClient.js deleted file mode 100644 index 15f8846..0000000 --- a/src/main/cloud/cloudClient.js +++ /dev/null @@ -1,170 +0,0 @@ -/** - * CloudClient wraps @coretrace/cli-core for the main process: configuration - * from the backend settings, credential resolution (environment key, then the - * safeStorage-backed session, then the core's encrypted fallback), device-flow - * sign-in, identity, tools and limits. Nothing here touches the renderer. - */ -const os = require('os'); -const path = require('path'); - -const DEFAULT_UPGRADE_URL = 'https://coretrace.dev/pricing'; -const GUI_VERSION = require('../../../package.json').version; - -class CloudClient { - /** - * @param {object} deps - * @param {() => Promise} deps.loadSettings backend settings loader - * @param {object} deps.store CredentialStore preferred (safeStorage) - * @param {string} deps.configDir directory for the core's state and fallback files - * @param {() => Promise} [deps.loadCore] injectable module loader (tests) - * @param {(line: string) => void} [deps.log] - */ - constructor(deps) { - this.deps = deps; - this.corePromise = null; - this.credential = null; - this.deviceAbort = null; - } - - core() { - if (!this.corePromise) { - this.corePromise = this.deps.loadCore ? this.deps.loadCore() : import('@coretrace/cli-core'); - } - return this.corePromise; - } - - async settings() { - const all = (await this.deps.loadSettings()) || {}; - const cloud = all.cloud || {}; - return { - baseUrl: cloud.baseUrl || process.env.CORETRACE_BASE_URL || 'https://api.coretrace.dev', - caFile: cloud.caFile || process.env.CORETRACE_CA_FILE || '', - org: cloud.org || process.env.CORETRACE_ORG || '', - upgradeUrl: cloud.upgradeUrl || DEFAULT_UPGRADE_URL, - }; - } - - async config() { - const core = await this.core(); - const s = await this.settings(); - const overrides = { baseUrl: s.baseUrl, configDir: this.deps.configDir }; - if (s.caFile) overrides.caFile = s.caFile; - if (s.org) overrides.org = s.org; - const env = { ...process.env }; - if (s.baseUrl.startsWith('http://')) env.CORETRACE_DEV_INSECURE = '1'; - const config = core.loadConfig(overrides, env); - return { core, config, upgradeUrl: s.upgradeUrl }; - } - - logger(core) { - if (!this._logger) { - this._logger = new core.Logger({ - level: process.env.CORETRACE_LOG === 'debug' ? 'debug' : 'warn', - sink: (line) => (this.deps.log ? this.deps.log(line) : console.warn(line)), - }); - } - return this._logger; - } - - async store(core, config) { - return core.selectStore(config, { preferred: this.deps.store, preference: 'auto' }); - } - - /** Resolves the credential in use; undefined when signed out. */ - async resolveCredential() { - const { core, config } = await this.config(); - const logger = this.logger(core); - const fromEnv = core.fromEnvironment(config); - if (fromEnv) return fromEnv; - const store = await this.store(core, config); - const pub = core.createApiClient({ baseUrl: config.baseUrl, userAgent: `coretrace-gui/${GUI_VERSION}`, caFile: config.caFile, logger }); - return core.resumeStoredSession(pub, config, store, { logger }); - } - - /** Authenticated client or null when signed out. */ - async client() { - const { core, config } = await this.config(); - const credential = await this.resolveCredential(); - if (!credential) return null; - const logger = this.logger(core); - const api = core.createApiClient({ - baseUrl: config.baseUrl, - userAgent: `coretrace-gui/${GUI_VERSION}`, - caFile: config.caFile, - logger, - token: () => core.bearerOf(credential), - }); - // User sessions scope organisation calls with X-Org; resolve the membership once. - const me = await core.fetchMe(api); - api.setOrg(core.selectOrg(me, config.org).slug); - return { core, config, credential, api, me }; - } - - async status(online) { - const { config, upgradeUrl } = await this.config(); - const out = { online, baseUrl: config.baseUrl, signedIn: false, storeKind: null, identity: null, upgradeUrl }; - if (!online) return out; - try { - const c = await this.client(); - if (!c) return out; - out.signedIn = true; - out.storeKind = c.credential.source; - const me = await c.core.fetchMe(c.api); - out.identity = { principal: me.principal, orgs: me.orgs, org: c.core.selectOrg(me, c.config.org).slug }; - } catch (err) { - out.error = String(err && err.message ? err.message : err); - } - return out; - } - - /** Starts the device flow; onCode receives the code, the promise resolves with the identity. */ - async loginStart(onCode) { - const { core, config } = await this.config(); - const logger = this.logger(core); - const pub = core.createApiClient({ baseUrl: config.baseUrl, userAgent: `coretrace-gui/${GUI_VERSION}`, caFile: config.caFile, logger }); - this.deviceAbort = new AbortController(); - const tokens = await core.deviceLogin(pub, { onCode, signal: this.deviceAbort.signal }); - const authed = core.createApiClient({ baseUrl: config.baseUrl, userAgent: `coretrace-gui/${GUI_VERSION}`, caFile: config.caFile, logger, token: () => tokens.access_token }); - const me = await core.fetchMe(authed); - const store = await this.store(core, config); - await core.saveSession(store, config, tokens, { userName: me.principal.name || '', orgSlug: me.orgs.length === 1 ? me.orgs[0].slug : '' }); - return { principal: me.principal, orgs: me.orgs, storeKind: store.kind }; - } - - loginCancel() { - if (this.deviceAbort) this.deviceAbort.abort(); - } - - async logout() { - const { core, config } = await this.config(); - const store = await this.store(core, config); - let client; - try { - const c = await this.client(); - if (c && c.credential.kind === 'session') client = c.api; - } catch { - client = undefined; - } - return core.logout(client, store, config.profile); - } - - async tools() { - const c = await this.client(); - if (!c) throw new Error('Not signed in'); - return c.core.fetchTools(c.api); - } - - async limits() { - const c = await this.client(); - if (!c) throw new Error('Not signed in'); - const me = await c.core.fetchMe(c.api); - const org = c.core.selectOrg(me, c.config.org); - return c.core.fetchLimits(c.api, org.slug); - } - - tempDir() { - return process.env.CORETRACE_TMPDIR || os.tmpdir(); - } -} - -module.exports = { CloudClient, DEFAULT_UPGRADE_URL, cloudConfigDir: (userDataDir) => path.join(userDataDir, 'coretrace') }; diff --git a/src/main/cloud/cloudRun.js b/src/main/cloud/cloudRun.js deleted file mode 100644 index 51e115a..0000000 --- a/src/main/cloud/cloudRun.js +++ /dev/null @@ -1,128 +0,0 @@ -/** - * CloudRun drives one "Run in cloud" job through @coretrace/cli-core's runCloud - * and translates its hooks into renderer events (contracts/gui-integration.md). - * The confirmation answer arrives later through IPC; nothing is spent until it does. - */ -const crypto = require('crypto'); - -class CloudRun { - /** - * @param {object} deps - * @param {import('./cloudClient').CloudClient} deps.cloud - * @param {(event: object) => void} deps.emit pushes `cloud-run-event` payloads to the renderer - */ - constructor(deps) { - this.cloud = deps.cloud; - this.emit = deps.emit; - this.runs = new Map(); - } - - /** Starts a run; resolves immediately with the run id, progress arrives as events. */ - async start({ rootPath, tools, allowPartial, config, failOn, confirm = true }) { - const runId = crypto.randomUUID(); - const controller = new AbortController(); - const state = { runId, controller, confirmResolve: null, result: null, error: null, view: null }; - this.runs.set(runId, state); - const emit = (type, payload) => this.emit({ runId, type, ...payload }); - (async () => { - try { - const c = await this.cloud.client(); - if (!c) throw new c.core.AuthError('Not signed in'); - const me = await c.core.fetchMe(c.api); - const org = c.core.selectOrg(me, c.config.org); - const hooks = { - onPhase: (phase, detail) => emit('phase', { phase, detail: detail || null }), - onPack: (s) => emit('pack', { fileCount: s.fileCount, expandedSize: s.expandedSize, compressedSize: s.compressedSize, excluded: Object.fromEntries([...s.excluded.entries()].map(([k, v]) => [k, v.count])) }), - onEstimate: (quote, limits, rejected) => emit('estimate', { quote: serialiseQuote(quote), remainingBudgetCtu: limits.remaining_budget_ctu, rejected }), - onView: (view) => { - state.view = view; - emit('job', serialiseView(c.core, view)); - }, - onWaitMode: (mode, detail) => emit('wait', { mode, detail: detail || null }), - confirm: (quote, limits, deadline) => - new Promise((resolve) => { - state.confirmResolve = resolve; - emit('awaiting_confirmation', { quote: serialiseQuote(quote), remainingBudgetCtu: limits.remaining_budget_ctu, confirmDeadline: deadline || null }); - }), - }; - const result = await c.core.runCloud( - c.api, - { - org: org.slug, - root: rootPath, - tools, - allowPartial: Boolean(allowPartial), - confirm: confirm !== false, - failOn: failOn || 'any', - tempDir: this.cloud.tempDir(), - timeoutMs: 30 * 60 * 1000, - wait: true, - signal: controller.signal, - cancelOnInterrupt: true, - ...(config ? { config } : {}), - }, - hooks, - ); - state.result = result; - for (const r of result.reports) { - emit('findings', { tool: r.tool, toolRunId: r.runId, outcome: r.outcome, billedCtu: r.billedCtu, findings: r.findings.map(serialiseFinding) }); - } - emit('done', { - exitCode: result.exitCode, - declined: result.declined, - conclusion: result.view.conclusion || null, - billedCtu: result.view.billedCtu, - thresholdCount: result.thresholdCount, - jobId: result.view.jobId, - sarif: JSON.stringify(c.core.toSarif(result.view, result.reports, { exitCode: result.exitCode })), - }); - } catch (err) { - state.error = err; - const code = typeof err.code === 'number' ? err.code : 4; - emit('error', { code, message: String(err && err.message ? err.message : err), reason: err && err.detail && err.detail.reason ? err.detail.reason : null }); - } finally { - this.runs.delete(runId); - } - })(); - return { runId }; - } - - confirm(runId, accept) { - const state = this.runs.get(runId); - if (!state || !state.confirmResolve) return { ok: false, error: 'no confirmation pending' }; - const resolve = state.confirmResolve; - state.confirmResolve = null; - resolve(Boolean(accept)); - return { ok: true }; - } - - cancel(runId) { - const state = this.runs.get(runId); - if (!state) return { ok: false, error: 'unknown run' }; - if (state.confirmResolve) this.confirm(runId, false); - state.controller.abort(); - return { ok: true }; - } -} - -function serialiseQuote(q) { - return { quoteId: q.quoteId, totalReservedCtu: q.totalReservedCtu, expiresAt: q.expiresAt || null, items: q.items.map((i) => ({ tool: i.tool, version: i.version, reservedCtu: i.reservedCtu })) }; -} - -function serialiseView(core, view) { - return { - jobId: view.jobId, - status: view.status, - conclusion: view.conclusion || null, - billedCtu: view.billedCtu, - confirmDeadline: view.confirmDeadline || null, - rejected: view.rejected, - runs: core.runsOf(view).map((r) => ({ id: r.id, tool: r.tool, version: r.version, status: r.status, outcome: r.outcome || null, progress: r.progressMessage || null, findingsSoFar: r.findingsSoFar ?? null, billedCtu: r.billedCtu, reservedCtu: r.reservedCtu })), - }; -} - -function serialiseFinding(f) { - return { ruleId: f.ruleId, level: f.level, message: f.message, path: f.location.path, line: f.location.line ?? null, column: f.location.column ?? null, endLine: f.location.endLine ?? null, endColumn: f.location.endColumn ?? null }; -} - -module.exports = { CloudRun, serialiseView, serialiseQuote, serialiseFinding }; diff --git a/src/main/cloud/safeStorageStore.js b/src/main/cloud/safeStorageStore.js deleted file mode 100644 index c00858b..0000000 --- a/src/main/cloud/safeStorageStore.js +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Credential store for the cloud client backed by Electron's safeStorage. - * Implements the CredentialStore interface of @coretrace/cli-core: the refresh - * token travels encrypted at rest in userData/cloud-credentials.json and is - * never exposed to the renderer. - */ -const fs = require('fs').promises; -const path = require('path'); - -function createSafeStorageStore({ safeStorage, userDataDir }) { - const file = path.join(userDataDir, 'cloud-credentials.json'); - - async function read() { - try { - const doc = JSON.parse(await fs.readFile(file, 'utf8')); - return doc && typeof doc === 'object' && doc.profiles ? doc : { v: 1, profiles: {} }; - } catch { - return { v: 1, profiles: {} }; - } - } - - async function write(doc) { - await fs.mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.tmp`; - await fs.writeFile(tmp, JSON.stringify(doc), { mode: 0o600 }); - await fs.rename(tmp, file); - } - - return { - kind: 'safe_storage', - async available() { - try { - return Boolean(safeStorage && safeStorage.isEncryptionAvailable()); - } catch { - return false; - } - }, - async load(profile) { - const doc = await read(); - const entry = doc.profiles[profile]; - if (!entry) return undefined; - try { - const plain = safeStorage.decryptString(Buffer.from(entry, 'base64')); - const session = JSON.parse(plain); - return typeof session.refreshToken === 'string' ? session : undefined; - } catch { - return undefined; - } - }, - async save(profile, session) { - const doc = await read(); - doc.profiles[profile] = safeStorage.encryptString(JSON.stringify(session)).toString('base64'); - await write(doc); - }, - async remove(profile) { - const doc = await read(); - if (!doc.profiles[profile]) return false; - delete doc.profiles[profile]; - if (Object.keys(doc.profiles).length === 0) await fs.rm(file, { force: true }); - else await write(doc); - return true; - }, - }; -} - -module.exports = { createSafeStorageStore }; diff --git a/src/main/external_llm/AnthropicProvider.js b/src/main/external_llm/AnthropicProvider.js deleted file mode 100644 index 19aef4a..0000000 --- a/src/main/external_llm/AnthropicProvider.js +++ /dev/null @@ -1,134 +0,0 @@ -/** - * @fileoverview Anthropic API Provider (Claude) - * - * Implements Anthropic's messages API for Claude models. - * - * @author CTrace GUI Team - * @version 1.0.0 - */ - -const https = require('https'); -const BaseProvider = require('./BaseProvider'); - -/** - * Anthropic API Provider - * @extends BaseProvider - */ -class AnthropicProvider extends BaseProvider { - constructor(config) { - super(config); - this.endpoint = config.endpoint || 'https://api.anthropic.com/v1/messages'; - this.model = config.model || 'claude-3-5-sonnet-20241022'; - this.apiKey = config.apiKey; - } - - getName() { - return 'Anthropic (Claude)'; - } - - getConfigFields() { - return [ - { - name: 'apiKey', - label: 'API Key', - type: 'password', - required: true, - placeholder: 'sk-ant-...', - help: 'Get your API key from https://console.anthropic.com/settings/keys' - }, - { - name: 'model', - label: 'Model', - type: 'select', - required: true, - default: 'claude-3-5-sonnet-20241022', - options: [ - { value: 'claude-3-5-sonnet-20241022', label: 'Claude 3.5 Sonnet' }, - { value: 'claude-3-opus-20240229', label: 'Claude 3 Opus' }, - { value: 'claude-3-sonnet-20240229', label: 'Claude 3 Sonnet' }, - { value: 'claude-3-haiku-20240307', label: 'Claude 3 Haiku' } - ], - help: 'Choose the Claude model to use' - }, - { - name: 'endpoint', - label: 'API Endpoint (Advanced)', - type: 'text', - required: false, - default: 'https://api.anthropic.com/v1/messages', - placeholder: 'https://api.anthropic.com/v1/messages', - help: 'Custom endpoint URL' - } - ]; - } - - async chat(message, options = {}) { - if (!this.apiKey) { - return { success: false, error: 'API key is required' }; - } - - // Anthropic uses a different format - system prompt is separate - const systemPrompt = options.systemPrompt || 'You are a helpful coding assistant.'; - - const body = JSON.stringify({ - model: this.model, - max_tokens: options.maxTokens || 2000, - system: systemPrompt, - messages: [ - ...(options.history || []), - { role: 'user', content: message } - ], - temperature: options.temperature !== undefined ? options.temperature : 0.7 - }); - - return new Promise((resolve) => { - const url = new URL(this.endpoint); - const requestOptions = { - hostname: url.hostname, - port: 443, - path: url.pathname + url.search, - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'x-api-key': this.apiKey, - 'anthropic-version': '2023-06-01', - 'Content-Length': Buffer.byteLength(body) - }, - timeout: 60000 - }; - - const req = https.request(requestOptions, (res) => { - let data = ''; - res.on('data', (chunk) => { data += chunk; }); - res.on('end', () => { - try { - const parsed = JSON.parse(data); - if (parsed.content && parsed.content[0] && parsed.content[0].text) { - resolve({ success: true, reply: parsed.content[0].text }); - } else if (parsed.error) { - resolve({ success: false, error: parsed.error.message || 'API error' }); - } else { - resolve({ success: false, error: 'Invalid API response' }); - } - } catch (err) { - resolve({ success: false, error: 'Failed to parse API response: ' + err.message }); - } - }); - }); - - req.on('error', (err) => { - resolve({ success: false, error: 'API request failed: ' + err.message }); - }); - - req.on('timeout', () => { - req.destroy(); - resolve({ success: false, error: 'API request timed out' }); - }); - - req.write(body); - req.end(); - }); - } -} - -module.exports = AnthropicProvider; diff --git a/src/main/external_llm/BaseProvider.js b/src/main/external_llm/BaseProvider.js deleted file mode 100644 index 0b50f23..0000000 --- a/src/main/external_llm/BaseProvider.js +++ /dev/null @@ -1,97 +0,0 @@ -/** - * @fileoverview Base class for LLM providers - * - * This defines the interface that all LLM providers must implement, - * ensuring consistent behavior across different services. - * - * @author CTrace GUI Team - * @version 1.0.0 - */ - -/** - * Base class for all LLM providers - * @abstract - */ -class BaseProvider { - /** - * Create a provider instance - * @param {Object} config - Provider configuration - */ - constructor(config) { - if (new.target === BaseProvider) { - throw new Error('BaseProvider is abstract and cannot be instantiated directly'); - } - this.config = config; - } - - /** - * Get provider name - * @abstract - * @returns {string} Provider name - */ - getName() { - throw new Error('getName() must be implemented by provider'); - } - - /** - * Get required configuration fields - * @abstract - * @returns {Array} Array of field definitions with { name, label, type, required, placeholder, default } - */ - getConfigFields() { - throw new Error('getConfigFields() must be implemented by provider'); - } - - /** - * Validate configuration - * @param {Object} config - Configuration to validate - * @returns {Object} { valid: boolean, errors: Array } - */ - validateConfig(config) { - const errors = []; - const fields = this.getConfigFields(); - - for (const field of fields) { - if (field.required && !config[field.name]) { - errors.push(`${field.label} is required`); - } - } - - return { - valid: errors.length === 0, - errors - }; - } - - /** - * Send a chat message to the LLM - * @abstract - * @param {string} message - User message - * @param {Object} options - Additional options (systemPrompt, temperature, etc.) - * @returns {Promise} { success: boolean, reply?: string, error?: string } - */ - async chat(message, options = {}) { - throw new Error('chat() must be implemented by provider'); - } - - /** - * Test provider connection - * @returns {Promise} { success: boolean, error?: string } - */ - async testConnection() { - try { - const result = await this.chat('Hello', { temperature: 0.1 }); - return { - success: result.success, - error: result.error - }; - } catch (error) { - return { - success: false, - error: error.message - }; - } - } -} - -module.exports = BaseProvider; diff --git a/src/main/external_llm/DeepseekProvider.js b/src/main/external_llm/DeepseekProvider.js deleted file mode 100644 index 4fe427a..0000000 --- a/src/main/external_llm/DeepseekProvider.js +++ /dev/null @@ -1,134 +0,0 @@ -/** - * @fileoverview Deepseek API Provider - * - * Implements Deepseek's chat completions API. - * - * @author CTrace GUI Team - * @version 1.0.0 - */ - -const https = require('https'); -const BaseProvider = require('./BaseProvider'); - -/** - * Deepseek API Provider - * @extends BaseProvider - */ -class DeepseekProvider extends BaseProvider { - constructor(config) { - super(config); - this.endpoint = config.endpoint || 'https://api.deepseek.com/v1/chat/completions'; - this.model = config.model || 'deepseek-chat'; - this.apiKey = config.apiKey; - } - - getName() { - return 'Deepseek'; - } - - getConfigFields() { - return [ - { - name: 'apiKey', - label: 'API Key', - type: 'password', - required: true, - placeholder: 'sk-...', - help: 'Get your API key from https://platform.deepseek.com/api-keys' - }, - { - name: 'model', - label: 'Model', - type: 'select', - required: true, - default: 'deepseek-chat', - options: [ - { value: 'deepseek-chat', label: 'Deepseek Chat' }, - { value: 'deepseek-coder', label: 'Deepseek Coder' } - ], - help: 'Choose the Deepseek model to use' - }, - { - name: 'endpoint', - label: 'API Endpoint (Advanced)', - type: 'text', - required: false, - default: 'https://api.deepseek.com/v1/chat/completions', - placeholder: 'https://api.deepseek.com/v1/chat/completions', - help: 'Custom endpoint URL' - } - ]; - } - - async chat(message, options = {}) { - if (!this.apiKey) { - return { success: false, error: 'API key is required' }; - } - - const messages = []; - - // Add system prompt - const systemPrompt = options.systemPrompt || 'You are a helpful coding assistant.'; - messages.push({ role: 'system', content: systemPrompt }); - if (options.history && options.history.length > 0) { - messages.push(...options.history); - } - messages.push({ role: 'user', content: message }); - - const body = JSON.stringify({ - model: this.model, - messages: messages, - temperature: options.temperature !== undefined ? options.temperature : 0.7, - max_tokens: options.maxTokens || 2000 - }); - - return new Promise((resolve) => { - const url = new URL(this.endpoint); - const requestOptions = { - hostname: url.hostname, - port: 443, - path: url.pathname + url.search, - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Authorization': `Bearer ${this.apiKey}`, - 'Content-Length': Buffer.byteLength(body) - }, - timeout: 60000 - }; - - const req = https.request(requestOptions, (res) => { - let data = ''; - res.on('data', (chunk) => { data += chunk; }); - res.on('end', () => { - try { - const parsed = JSON.parse(data); - if (parsed.choices && parsed.choices[0] && parsed.choices[0].message) { - resolve({ success: true, reply: parsed.choices[0].message.content }); - } else if (parsed.error) { - resolve({ success: false, error: parsed.error.message || 'API error' }); - } else { - resolve({ success: false, error: 'Invalid API response' }); - } - } catch (err) { - resolve({ success: false, error: 'Failed to parse API response: ' + err.message }); - } - }); - }); - - req.on('error', (err) => { - resolve({ success: false, error: 'API request failed: ' + err.message }); - }); - - req.on('timeout', () => { - req.destroy(); - resolve({ success: false, error: 'API request timed out' }); - }); - - req.write(body); - req.end(); - }); - } -} - -module.exports = DeepseekProvider; diff --git a/src/main/external_llm/GenericOpenAIProvider.js b/src/main/external_llm/GenericOpenAIProvider.js deleted file mode 100644 index 49275d7..0000000 --- a/src/main/external_llm/GenericOpenAIProvider.js +++ /dev/null @@ -1,157 +0,0 @@ -/** - * @fileoverview Generic OpenAI-Compatible Provider - * - * A flexible provider for any LLM service that implements the OpenAI chat completions API. - * This includes services like: - * - Together AI - * - Groq - * - Perplexity - * - Local deployments (LM Studio, Ollama with OpenAI compatibility) - * - Azure OpenAI - * - And many others - * - * @author CTrace GUI Team - * @version 1.0.0 - */ - -const https = require('https'); -const http = require('http'); -const BaseProvider = require('./BaseProvider'); - -/** - * Generic OpenAI-Compatible Provider - * @extends BaseProvider - */ -class GenericOpenAIProvider extends BaseProvider { - constructor(config) { - super(config); - this.endpoint = config.endpoint; - this.model = config.model; - this.apiKey = config.apiKey; - this.name = config.name || 'Custom Provider'; - } - - getName() { - return this.name; - } - - getConfigFields() { - return [ - { - name: 'name', - label: 'Provider Name', - type: 'text', - required: true, - placeholder: 'My Custom LLM', - help: 'A friendly name for this provider' - }, - { - name: 'endpoint', - label: 'API Endpoint', - type: 'text', - required: true, - placeholder: 'https://api.example.com/v1/chat/completions', - help: 'Full URL to the chat completions endpoint' - }, - { - name: 'apiKey', - label: 'API Key', - type: 'password', - required: false, - placeholder: 'Optional API key', - help: 'API key if required by the service (leave blank for local/public endpoints)' - }, - { - name: 'model', - label: 'Model Name', - type: 'text', - required: true, - placeholder: 'gpt-3.5-turbo', - help: 'Model identifier (e.g., "mistralai/Mixtral-8x7B-Instruct-v0.1" for Together AI)' - } - ]; - } - - async chat(message, options = {}) { - if (!this.endpoint) { - return { success: false, error: 'API endpoint is required' }; - } - - if (!this.model) { - return { success: false, error: 'Model name is required' }; - } - - const messages = []; - - // Add system prompt - const systemPrompt = options.systemPrompt || 'You are a helpful coding assistant.'; - messages.push({ role: 'system', content: systemPrompt }); - if (options.history && options.history.length > 0) { - messages.push(...options.history); - } - messages.push({ role: 'user', content: message }); - - const body = JSON.stringify({ - model: this.model, - messages: messages, - temperature: options.temperature !== undefined ? options.temperature : 0.7, - max_tokens: options.maxTokens || 2000 - }); - - return new Promise((resolve) => { - const url = new URL(this.endpoint); - const isHttps = url.protocol === 'https:'; - const protocol = isHttps ? https : http; - - const requestOptions = { - hostname: url.hostname, - port: url.port || (isHttps ? 443 : 80), - path: url.pathname + url.search, - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Content-Length': Buffer.byteLength(body) - }, - timeout: 60000 - }; - - // Add authorization header if API key is provided - if (this.apiKey) { - requestOptions.headers['Authorization'] = `Bearer ${this.apiKey}`; - } - - const req = protocol.request(requestOptions, (res) => { - let data = ''; - res.on('data', (chunk) => { data += chunk; }); - res.on('end', () => { - try { - const parsed = JSON.parse(data); - if (parsed.choices && parsed.choices[0] && parsed.choices[0].message) { - resolve({ success: true, reply: parsed.choices[0].message.content }); - } else if (parsed.error) { - resolve({ success: false, error: parsed.error.message || 'API error' }); - } else { - resolve({ success: false, error: 'Invalid API response' }); - } - } catch (err) { - resolve({ success: false, error: 'Failed to parse API response: ' + err.message }); - } - }); - }); - - req.on('error', (err) => { - resolve({ success: false, error: 'API request failed: ' + err.message }); - }); - - req.on('timeout', () => { - req.destroy(); - resolve({ success: false, error: 'API request timed out' }); - }); - - req.write(body); - req.end(); - }); - } -} - -module.exports = GenericOpenAIProvider; diff --git a/src/main/external_llm/GroqProvider.js b/src/main/external_llm/GroqProvider.js deleted file mode 100644 index 6235f28..0000000 --- a/src/main/external_llm/GroqProvider.js +++ /dev/null @@ -1,126 +0,0 @@ -/** - * @fileoverview Groq API Provider (Example) - * - * This is an example provider showing how easy it is to add support - * for new LLM services. Groq offers extremely fast inference. - * - * @author CTrace GUI Team - * @version 1.0.0 - */ - -const https = require('https'); -const BaseProvider = require('./BaseProvider'); - -/** - * Groq API Provider - Ultra-fast LLM inference - * @extends BaseProvider - */ -class GroqProvider extends BaseProvider { - constructor(config) { - super(config); - this.endpoint = 'https://api.groq.com/openai/v1/chat/completions'; - this.model = config.model || 'mixtral-8x7b-32768'; - this.apiKey = config.apiKey; - } - - getName() { - return 'Groq (Fast Inference)'; - } - - getConfigFields() { - return [ - { - name: 'apiKey', - label: 'API Key', - type: 'password', - required: true, - placeholder: 'gsk_...', - help: 'Get your API key from https://console.groq.com/keys' - }, - { - name: 'model', - label: 'Model', - type: 'select', - required: true, - default: 'mixtral-8x7b-32768', - options: [ - { value: 'mixtral-8x7b-32768', label: 'Mixtral 8x7B (32K context)' }, - { value: 'llama2-70b-4096', label: 'LLaMA2 70B (4K context)' }, - { value: 'gemma-7b-it', label: 'Gemma 7B (8K context)' } - ], - help: 'Choose the Groq model to use' - } - ]; - } - - async chat(message, options = {}) { - if (!this.apiKey) { - return { success: false, error: 'API key is required' }; - } - - const messages = []; - - // Add system prompt - const systemPrompt = options.systemPrompt || 'You are a helpful coding assistant.'; - messages.push({ role: 'system', content: systemPrompt }); - if (options.history && options.history.length > 0) { - messages.push(...options.history); - } - messages.push({ role: 'user', content: message }); - - const body = JSON.stringify({ - model: this.model, - messages: messages, - temperature: options.temperature !== undefined ? options.temperature : 0.7, - max_tokens: options.maxTokens || 2000 - }); - - return new Promise((resolve) => { - const requestOptions = { - hostname: 'api.groq.com', - port: 443, - path: '/openai/v1/chat/completions', - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Authorization': `Bearer ${this.apiKey}`, - 'Content-Length': Buffer.byteLength(body) - }, - timeout: 60000 - }; - - const req = https.request(requestOptions, (res) => { - let data = ''; - res.on('data', (chunk) => { data += chunk; }); - res.on('end', () => { - try { - const parsed = JSON.parse(data); - if (parsed.choices && parsed.choices[0] && parsed.choices[0].message) { - resolve({ success: true, reply: parsed.choices[0].message.content }); - } else if (parsed.error) { - resolve({ success: false, error: parsed.error.message || 'API error' }); - } else { - resolve({ success: false, error: 'Invalid API response' }); - } - } catch (err) { - resolve({ success: false, error: 'Failed to parse API response: ' + err.message }); - } - }); - }); - - req.on('error', (err) => { - resolve({ success: false, error: 'API request failed: ' + err.message }); - }); - - req.on('timeout', () => { - req.destroy(); - resolve({ success: false, error: 'API request timed out' }); - }); - - req.write(body); - req.end(); - }); - } -} - -module.exports = GroqProvider; diff --git a/src/main/external_llm/OpenAIProvider.js b/src/main/external_llm/OpenAIProvider.js deleted file mode 100644 index fcac112..0000000 --- a/src/main/external_llm/OpenAIProvider.js +++ /dev/null @@ -1,137 +0,0 @@ -/** - * @fileoverview OpenAI API Provider (ChatGPT, GPT-4, etc.) - * - * Implements OpenAI's chat completions API for GPT models. - * - * @author CTrace GUI Team - * @version 1.0.0 - */ - -const https = require('https'); -const BaseProvider = require('./BaseProvider'); - -/** - * OpenAI API Provider - * @extends BaseProvider - */ -class OpenAIProvider extends BaseProvider { - constructor(config) { - super(config); - this.endpoint = config.endpoint || 'https://api.openai.com/v1/chat/completions'; - this.model = config.model || 'gpt-4'; - this.apiKey = config.apiKey; - } - - getName() { - return 'OpenAI (ChatGPT)'; - } - - getConfigFields() { - return [ - { - name: 'apiKey', - label: 'API Key', - type: 'password', - required: true, - placeholder: 'sk-...', - help: 'Get your API key from https://platform.openai.com/api-keys' - }, - { - name: 'model', - label: 'Model', - type: 'select', - required: true, - default: 'gpt-4', - options: [ - { value: 'gpt-4', label: 'GPT-4' }, - { value: 'gpt-4-turbo', label: 'GPT-4 Turbo' }, - { value: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo' }, - { value: 'gpt-4o', label: 'GPT-4o' }, - { value: 'gpt-4o-mini', label: 'GPT-4o Mini' } - ], - help: 'Choose the OpenAI model to use' - }, - { - name: 'endpoint', - label: 'API Endpoint (Advanced)', - type: 'text', - required: false, - default: 'https://api.openai.com/v1/chat/completions', - placeholder: 'https://api.openai.com/v1/chat/completions', - help: 'Custom endpoint URL (for proxies or alternative deployments)' - } - ]; - } - - async chat(message, options = {}) { - if (!this.apiKey) { - return { success: false, error: 'API key is required' }; - } - - const messages = []; - - // Add system prompt - const systemPrompt = options.systemPrompt || 'You are a helpful coding assistant.'; - messages.push({ role: 'system', content: systemPrompt }); - if (options.history && options.history.length > 0) { - messages.push(...options.history); - } - messages.push({ role: 'user', content: message }); - - const body = JSON.stringify({ - model: this.model, - messages: messages, - temperature: options.temperature !== undefined ? options.temperature : 0.7, - max_tokens: options.maxTokens || 2000 - }); - - return new Promise((resolve) => { - const url = new URL(this.endpoint); - const requestOptions = { - hostname: url.hostname, - port: 443, - path: url.pathname + url.search, - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Authorization': `Bearer ${this.apiKey}`, - 'Content-Length': Buffer.byteLength(body) - }, - timeout: 60000 - }; - - const req = https.request(requestOptions, (res) => { - let data = ''; - res.on('data', (chunk) => { data += chunk; }); - res.on('end', () => { - try { - const parsed = JSON.parse(data); - if (parsed.choices && parsed.choices[0] && parsed.choices[0].message) { - resolve({ success: true, reply: parsed.choices[0].message.content }); - } else if (parsed.error) { - resolve({ success: false, error: parsed.error.message || 'API error' }); - } else { - resolve({ success: false, error: 'Invalid API response' }); - } - } catch (err) { - resolve({ success: false, error: 'Failed to parse API response: ' + err.message }); - } - }); - }); - - req.on('error', (err) => { - resolve({ success: false, error: 'API request failed: ' + err.message }); - }); - - req.on('timeout', () => { - req.destroy(); - resolve({ success: false, error: 'API request timed out' }); - }); - - req.write(body); - req.end(); - }); - } -} - -module.exports = OpenAIProvider; diff --git a/src/main/external_llm/PerplexityProvider.js b/src/main/external_llm/PerplexityProvider.js deleted file mode 100644 index 4eee211..0000000 --- a/src/main/external_llm/PerplexityProvider.js +++ /dev/null @@ -1,128 +0,0 @@ -/** - * @fileoverview Perplexity API Provider (Example) - * - * Perplexity offers LLMs with real-time internet search capabilities, - * perfect for getting up-to-date information and current best practices. - * - * @author CTrace GUI Team - * @version 1.0.0 - */ - -const https = require('https'); -const BaseProvider = require('./BaseProvider'); - -/** - * Perplexity API Provider - Search-augmented responses - * @extends BaseProvider - */ -class PerplexityProvider extends BaseProvider { - constructor(config) { - super(config); - this.endpoint = 'https://api.perplexity.ai/chat/completions'; - this.model = config.model || 'llama-3.1-sonar-small-128k-online'; - this.apiKey = config.apiKey; - } - - getName() { - return 'Perplexity (Search-Augmented)'; - } - - getConfigFields() { - return [ - { - name: 'apiKey', - label: 'API Key', - type: 'password', - required: true, - placeholder: 'pplx-...', - help: 'Get your API key from https://www.perplexity.ai/settings/api' - }, - { - name: 'model', - label: 'Model', - type: 'select', - required: true, - default: 'llama-3.1-sonar-small-128k-online', - options: [ - { value: 'llama-3.1-sonar-small-128k-online', label: 'Sonar Small (Online, 128K)' }, - { value: 'llama-3.1-sonar-large-128k-online', label: 'Sonar Large (Online, 128K)' }, - { value: 'llama-3.1-sonar-huge-128k-online', label: 'Sonar Huge (Online, 128K)' }, - { value: 'llama-3.1-8b-instruct', label: 'LLaMA 3.1 8B (Offline)' }, - { value: 'llama-3.1-70b-instruct', label: 'LLaMA 3.1 70B (Offline)' } - ], - help: 'Online models have internet search, offline models don\'t' - } - ]; - } - - async chat(message, options = {}) { - if (!this.apiKey) { - return { success: false, error: 'API key is required' }; - } - - const messages = []; - - // Add system prompt - const systemPrompt = options.systemPrompt || 'You are a helpful coding assistant with access to current information.'; - messages.push({ role: 'system', content: systemPrompt }); - if (options.history && options.history.length > 0) { - messages.push(...options.history); - } - messages.push({ role: 'user', content: message }); - - const body = JSON.stringify({ - model: this.model, - messages: messages, - temperature: options.temperature !== undefined ? options.temperature : 0.7, - max_tokens: options.maxTokens || 2000 - }); - - return new Promise((resolve) => { - const requestOptions = { - hostname: 'api.perplexity.ai', - port: 443, - path: '/chat/completions', - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Authorization': `Bearer ${this.apiKey}`, - 'Content-Length': Buffer.byteLength(body) - }, - timeout: 60000 - }; - - const req = https.request(requestOptions, (res) => { - let data = ''; - res.on('data', (chunk) => { data += chunk; }); - res.on('end', () => { - try { - const parsed = JSON.parse(data); - if (parsed.choices && parsed.choices[0] && parsed.choices[0].message) { - resolve({ success: true, reply: parsed.choices[0].message.content }); - } else if (parsed.error) { - resolve({ success: false, error: parsed.error.message || 'API error' }); - } else { - resolve({ success: false, error: 'Invalid API response' }); - } - } catch (err) { - resolve({ success: false, error: 'Failed to parse API response: ' + err.message }); - } - }); - }); - - req.on('error', (err) => { - resolve({ success: false, error: 'API request failed: ' + err.message }); - }); - - req.on('timeout', () => { - req.destroy(); - resolve({ success: false, error: 'API request timed out' }); - }); - - req.write(body); - req.end(); - }); - } -} - -module.exports = PerplexityProvider; diff --git a/src/main/external_llm/ProviderRegistry.js b/src/main/external_llm/ProviderRegistry.js deleted file mode 100644 index 74004d9..0000000 --- a/src/main/external_llm/ProviderRegistry.js +++ /dev/null @@ -1,94 +0,0 @@ -/** - * @fileoverview Provider Registry - * - * Central registry for all available LLM providers. - * Handles provider registration, instantiation, and discovery. - * - * @author CTrace GUI Team - * @version 1.0.0 - */ - -const OpenAIProvider = require('./OpenAIProvider'); -const DeepseekProvider = require('./DeepseekProvider'); -const AnthropicProvider = require('./AnthropicProvider'); -const GenericOpenAIProvider = require('./GenericOpenAIProvider'); -const GroqProvider = require('./GroqProvider'); -const PerplexityProvider = require('./PerplexityProvider'); - -/** - * Registry of available LLM providers - */ -class ProviderRegistry { - constructor() { - this.providers = new Map(); - this.registerDefaultProviders(); - } - - /** - * Register default built-in providers - */ - registerDefaultProviders() { - this.register('openai', OpenAIProvider); - this.register('deepseek', DeepseekProvider); - this.register('anthropic', AnthropicProvider); - this.register('groq', GroqProvider); - this.register('perplexity', PerplexityProvider); - this.register('generic', GenericOpenAIProvider); - } - - /** - * Register a provider class - * @param {string} id - Unique provider identifier - * @param {Function} ProviderClass - Provider class constructor - */ - register(id, ProviderClass) { - this.providers.set(id, ProviderClass); - } - - /** - * Get all available providers - * @returns {Array} Array of provider info { id, name, fields } - */ - getAllProviders() { - const providers = []; - for (const [id, ProviderClass] of this.providers.entries()) { - try { - const instance = new ProviderClass({}); - providers.push({ - id: id, - name: instance.getName(), - fields: instance.getConfigFields() - }); - } catch (err) { - console.error(`Error getting info for provider ${id}:`, err); - } - } - return providers; - } - - /** - * Create a provider instance - * @param {string} id - Provider identifier - * @param {Object} config - Provider configuration - * @returns {BaseProvider} Provider instance - */ - createProvider(id, config) { - const ProviderClass = this.providers.get(id); - if (!ProviderClass) { - throw new Error(`Provider not found: ${id}`); - } - return new ProviderClass(config); - } - - /** - * Check if a provider exists - * @param {string} id - Provider identifier - * @returns {boolean} - */ - hasProvider(id) { - return this.providers.has(id); - } -} - -// Export singleton instance -module.exports = new ProviderRegistry(); diff --git a/src/main/external_llm/endpointPolicy.js b/src/main/external_llm/endpointPolicy.js deleted file mode 100644 index 1e854d0..0000000 --- a/src/main/external_llm/endpointPolicy.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * @fileoverview Endpoint policy for external LLM providers. - * - * A provider endpoint is user-configurable and receives the user's API key in - * an Authorization header. To keep that key from travelling in clear text (or - * being pointed at an internal service), a keyed request may only go to an - * https: URL, or to plain http: on the local machine. - */ - -const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']); - -/** - * @param {string} endpoint - Full URL the provider will call - * @param {boolean} carriesSecret - Whether an API key is attached to the request - * @returns {{ valid: boolean, error?: string }} - */ -function validateEndpoint(endpoint, carriesSecret) { - let url; - try { - url = new URL(String(endpoint || '')); - } catch (_) { - return { valid: false, error: 'Provider endpoint is not a valid URL' }; - } - - if (url.protocol === 'https:') return { valid: true }; - - if (url.protocol === 'http:') { - if (!carriesSecret || LOOPBACK_HOSTS.has(url.hostname)) return { valid: true }; - return { valid: false, error: 'API keys are only sent over https (or http on localhost)' }; - } - - return { valid: false, error: `Unsupported endpoint protocol: ${url.protocol}` }; -} - -module.exports = { validateEndpoint }; diff --git a/src/main/ipc/appInfoHandlers.js b/src/main/ipc/appInfoHandlers.js deleted file mode 100644 index f4b16c8..0000000 --- a/src/main/ipc/appInfoHandlers.js +++ /dev/null @@ -1,56 +0,0 @@ -/** - * @fileoverview IPC handlers for data the sandboxed preload cannot read itself. - * - * With `sandbox: true` the preload script has no filesystem or clipboard - * access, so the few pieces of static app data it used to read directly are - * served from here instead. - */ - -const { ipcMain, clipboard } = require('electron'); -const fs = require('fs').promises; -const path = require('path'); - -const CLIPBOARD_MAX_CHARS = 1024 * 1024; - -let appInfoPromise = null; -let syntaxConfigPromise = null; - -function loadAppInfo() { - if (!appInfoPromise) { - appInfoPromise = fs.readFile(path.join(__dirname, '..', '..', '..', 'package.json'), 'utf-8') - .then((raw) => JSON.parse(raw)) - .then((packageJson) => ({ - name: packageJson.productName || packageJson.name || 'CTraceGUI', - version: packageJson.version || '0.0.0' - })) - .catch((error) => { - console.warn('[AppInfo] Failed to load package.json:', error); - return { name: 'CTraceGUI', version: '0.0.0' }; - }); - } - return appInfoPromise; -} - -function loadSyntaxConfig() { - if (!syntaxConfigPromise) { - syntaxConfigPromise = fs.readFile(path.join(__dirname, '..', '..', 'renderer', 'utils', 'syntax-config.json'), 'utf-8') - .then((raw) => JSON.parse(raw)) - .catch((error) => { - console.warn('[AppInfo] Failed to load syntax-config.json:', error); - return {}; - }); - } - return syntaxConfigPromise; -} - -function setupAppInfoHandlers() { - ipcMain.handle('app-get-info', () => loadAppInfo()); - ipcMain.handle('app-get-syntax-config', () => loadSyntaxConfig()); - - ipcMain.on('clipboard-write-text', (_event, text) => { - if (typeof text !== 'string') return; - clipboard.writeText(text.slice(0, CLIPBOARD_MAX_CHARS)); - }); -} - -module.exports = { setupAppInfoHandlers }; diff --git a/src/main/ipc/assistantHandlers.js b/src/main/ipc/assistantHandlers.js deleted file mode 100644 index 2af892a..0000000 --- a/src/main/ipc/assistantHandlers.js +++ /dev/null @@ -1,479 +0,0 @@ -/** - * @fileoverview IPC handlers for AI assistant (Ollama, External API, Local GGUF) - * - * This module provides IPC handlers for chatting with various LLM providers. - * Now uses a modular provider system for easy extensibility. - * - * @author CTrace GUI Team - * @version 1.0.0 - */ - -const { ipcMain } = require('electron'); -const https = require('https'); -const http = require('http'); -const providerRegistry = require('../external_llm/ProviderRegistry'); -const { loadStoredApiKey } = require('./secureStorageHandlers'); -const { validateEndpoint } = require('../external_llm/endpointPolicy'); -const { isTrustedFile } = require('../utils/workspaceTrust'); - -// Local GGUF state -let localLLM = null; -let loadedModelPath = null; -let loadedGpuLayers = null; -let loadedSystemPrompt = null; - -// Abort controller for in-flight requests -let currentAbortController = null; - -/** - * Setup IPC handlers for assistant chat - * @param {BrowserWindow} mainWindow - Main window reference - */ -function setupAssistantHandlers(mainWindow) { - /** - * Handle assistant chat request - * Input: { provider, message, config } - * config contains: provider-specific configuration - */ - ipcMain.handle('assistant-chat', async (event, { provider, message, history, config: rendererConfig }) => { - // Abort any existing in-flight request - if (currentAbortController) { - currentAbortController.abort(); - } - currentAbortController = new AbortController(); - const { signal } = currentAbortController; - - // The renderer never holds the API key; it is read from encrypted storage here. - const config = { ...(rendererConfig || {}), apiKey: await loadStoredApiKey().catch(() => null) }; - - // Wrap the real request in a race against an abort promise - const abortPromise = new Promise((resolve) => { - signal.addEventListener('abort', () => { - resolve({ success: false, aborted: true, error: 'Request cancelled' }); - }); - }); - - let requestPromise; - try { - if (provider === 'ollama') { - requestPromise = handleOllamaChat(message, history || [], config); - } else if (provider === 'external') { - requestPromise = handleModularProvider(message, history || [], config); - } else if (provider === 'local') { - requestPromise = handleLocalChat(message, history || [], config, signal); - } else { - return { success: false, error: 'Unknown provider or assistant not configured' }; - } - } catch (error) { - console.error('Error starting assistant-chat handler:', error); - return { success: false, error: error.message || 'Unknown error' }; - } - - try { - return await Promise.race([requestPromise, abortPromise]); - } catch (error) { - console.error('Error in assistant-chat handler:', error); - return { success: false, error: error.message || 'Unknown error' }; - } - }); - - /** - * Abort the current in-flight assistant request - */ - ipcMain.handle('assistant-abort', async () => { - if (currentAbortController) { - currentAbortController.abort(); - currentAbortController = null; - } - return { success: true }; - }); - - /** - * Get list of available providers - */ - ipcMain.handle('assistant-get-providers', async () => { - try { - return { - success: true, - providers: providerRegistry.getAllProviders() - }; - } catch (error) { - console.error('Error getting providers:', error); - return { - success: false, - error: error.message - }; - } - }); - - /** - * Test a provider connection - */ - ipcMain.handle('assistant-test-provider', async (event, { providerId, config }) => { - try { - const provider = providerRegistry.createProvider(providerId, config); - return await provider.testConnection(); - } catch (error) { - console.error('Error testing provider:', error); - return { - success: false, - error: error.message - }; - } - }); - - /** - * List models available for a given provider using the provider's own API. - * Input: { providerId: 'openai'|'deepseek', apiKey: string } - * Returns: { success, models: [{ id, owned_by }] } - */ - ipcMain.handle('assistant-list-models', async (_event, { providerId, apiKey: typedKey, useStoredKey }) => { - const apiKey = useStoredKey ? await loadStoredApiKey() : typedKey; - if (!apiKey) return { success: false, error: 'API key is required' }; - - const endpointMap = { - openai: 'https://api.openai.com', - deepseek: 'https://api.deepseek.com', - }; - - const baseUrl = endpointMap[providerId]; - if (!baseUrl) return { success: false, error: `Unknown provider: ${providerId}` }; - - return new Promise((resolve) => { - const url = new URL('/v1/models', baseUrl); - const options = { - hostname: url.hostname, - port: 443, - path: url.pathname, - method: 'GET', - headers: { - 'Authorization': `Bearer ${apiKey}`, - 'Content-Type': 'application/json' - }, - timeout: 15000 - }; - - const req = https.request(options, (res) => { - let data = ''; - res.on('data', (chunk) => { data += chunk; }); - res.on('end', () => { - try { - const parsed = JSON.parse(data); - // Both OpenAI and DeepSeek return { data: [{ id, owned_by, ... }] } - if (parsed.data && Array.isArray(parsed.data)) { - const models = parsed.data - .map((m) => ({ id: m.id, owned_by: m.owned_by || '' })) - .sort((a, b) => a.id.localeCompare(b.id)); - resolve({ success: true, models }); - } else if (parsed.error) { - resolve({ success: false, error: parsed.error.message || 'API error' }); - } else { - resolve({ success: false, error: 'Unexpected response format' }); - } - } catch (err) { - resolve({ success: false, error: 'Failed to parse response: ' + err.message }); - } - }); - }); - - req.on('error', (err) => resolve({ success: false, error: err.message })); - req.on('timeout', () => { req.destroy(); resolve({ success: false, error: 'Request timed out' }); }); - req.end(); - }); - }); - - /** - * Unload local model when requested - */ - ipcMain.handle('assistant-unload-local', async () => { - try { - if (localLLM) { - if (localLLM.context) await localLLM.context.dispose(); - if (localLLM.model) await localLLM.model.dispose(); - localLLM = null; - loadedModelPath = null; - loadedGpuLayers = null; - return { success: true }; - } - return { success: true }; - } catch (error) { - console.error('Error unloading local model:', error); - return { success: false, error: error.message }; - } - }); -} - -/** - * Handle Ollama chat request - * @param {string} message - User message - * @param {Object} config - Config with ollamaHost - * @returns {Promise} - */ -async function handleOllamaChat(message, history, config) { - const host = config.ollamaHost || 'http://localhost:11434'; - const url = new URL('/api/chat', host); - - const messages = []; - - // Add system prompt if provided - if (config.systemPrompt) { - messages.push({ role: 'system', content: config.systemPrompt }); - } - - // Inject conversation history - if (history && history.length > 0) { - messages.push(...history); - } - - messages.push({ role: 'user', content: message }); - - const body = JSON.stringify({ - model: 'llama2', // default model, can be made configurable - messages: messages, - stream: false - }); - - return new Promise((resolve) => { - const protocol = url.protocol === 'https:' ? https : http; - const options = { - hostname: url.hostname, - port: url.port || (url.protocol === 'https:' ? 443 : 80), - path: url.pathname, - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Content-Length': Buffer.byteLength(body) - }, - timeout: 60000 - }; - - const req = protocol.request(options, (res) => { - let data = ''; - res.on('data', (chunk) => { data += chunk; }); - res.on('end', () => { - try { - const parsed = JSON.parse(data); - if (parsed.message && parsed.message.content) { - resolve({ success: true, reply: parsed.message.content }); - } else { - resolve({ success: false, error: 'Invalid response from Ollama' }); - } - } catch (err) { - resolve({ success: false, error: 'Failed to parse Ollama response: ' + err.message }); - } - }); - }); - - req.on('error', (err) => { - resolve({ success: false, error: 'Ollama request failed: ' + err.message }); - }); - - req.on('timeout', () => { - req.destroy(); - resolve({ success: false, error: 'Ollama request timed out' }); - }); - - req.write(body); - req.end(); - }); -} - -/** - * Handle external API chat using modular provider system - * @param {string} message - User message - * @param {Object} config - Config with providerId and provider-specific settings - * @returns {Promise} - */ -async function handleModularProvider(message, history, config) { - const providerId = config.providerId || 'openai'; - - try { - // Create provider instance - const provider = providerRegistry.createProvider(providerId, config); - - // Validate configuration - const validation = provider.validateConfig(config); - if (!validation.valid) { - return { - success: false, - error: 'Configuration error: ' + validation.errors.join(', ') - }; - } - - const endpointCheck = validateEndpoint(provider.endpoint, Boolean(config.apiKey)); - if (!endpointCheck.valid) { - return { success: false, error: endpointCheck.error }; - } - - // Send chat message with conversation history - return await provider.chat(message, { - systemPrompt: config.systemPrompt, - temperature: config.temperature, - maxTokens: config.maxTokens, - history: history || [] - }); - } catch (error) { - console.error('Error with modular provider:', error); - return { - success: false, - error: error.message || 'Provider error' - }; - } -} - -/** - * Handle local GGUF model chat using node-llama-cpp - * @param {string} message - User message - * @param {Object} config - Config with localModelPath and gpuLayers - * @returns {Promise} - */ -async function handleLocalChat(message, history, config, abortSignal) { - const modelPath = config.localModelPath; - - if (!modelPath) { - return { success: false, error: 'Local model path is required' }; - } - if (!isTrustedFile(modelPath)) { - return { success: false, error: 'Choose the model file through the file picker' }; - } - - try { - // Dynamic import of node-llama-cpp (ESM module) - const { getLlama, LlamaChatSession } = await import('node-llama-cpp'); - - // Get GPU layers setting (default to 0 if not specified) - const gpuLayers = config.gpuLayers !== undefined && config.gpuLayers !== null ? config.gpuLayers : 0; - - // Get context size setting (default to 8192 if not specified) - const contextSize = config.contextSize !== undefined && config.contextSize !== null ? config.contextSize : 8192; - - // Load model if not loaded, if path changed, OR if GPU layers setting changed - if (!localLLM || loadedModelPath !== modelPath || loadedGpuLayers !== gpuLayers) { - console.log('Loading local GGUF model from:', modelPath); - - // Dispose old instance if any - if (localLLM) { - console.log('Disposing previous model instance...'); - try { - if (localLLM.context) await localLLM.context.dispose(); - if (localLLM.model) await localLLM.model.dispose(); - } catch (disposeErr) { - console.warn('Error during disposal:', disposeErr); - } - localLLM = null; - } - - // Initialize llama - const llama = await getLlama({ - logLevel: 'warn' - }); - - console.log('=== GPU Detection ==='); - console.log('Attempting to load model with GPU layers:', gpuLayers); - - if (gpuLayers === -1) { - console.log('Mode: Offloading ALL layers to GPU'); - } else if (gpuLayers === 0) { - console.log('Mode: CPU only (no GPU acceleration)'); - } else { - console.log(`Mode: Offloading ${gpuLayers} layers to GPU`); - } - - console.log('Note: Watch for [node-llama-cpp] logs below for GPU/Vulkan device info'); - console.log('====================='); - - // Load the model with GPU configuration - // The underlying llama.cpp will log GPU information like: - // "ggml_vulkan: Using Vulkan1 (NVIDIA GeForce RTX 4070) | vulkan" - const model = await llama.loadModel({ - modelPath: modelPath, - gpuLayers: gpuLayers, // 0 = CPU only, -1 = all layers, or specific number - // Try to enable verbose output - onLoadProgress: (progress) => { - console.log(`Loading model: ${(progress * 100).toFixed(1)}%`); - } - }); - - console.log('✓ Model loaded'); - console.log(' GPU layers used:', gpuLayers === -1 ? 'All layers' : gpuLayers); - console.log(' Model size:', model.size, 'parameters'); - console.log(' Model default context:', model.trainContextSize, 'tokens'); - console.log(' Using context size:', contextSize, 'tokens (saves VRAM)'); - - // Create context with custom size to reduce VRAM usage - const context = await model.createContext({ - contextSize: contextSize // Use configured context size instead of model default (40960) - }); - - // Create chat session with system prompt via constructor (not as raw text) - const systemPromptValue = config.systemPrompt || undefined; - const sequence = context.getSequence(); - const session = new LlamaChatSession({ - contextSequence: sequence, - systemPrompt: systemPromptValue - }); - - localLLM = { model, context, sequence, session }; - loadedModelPath = modelPath; - loadedGpuLayers = gpuLayers; - loadedSystemPrompt = config.systemPrompt || null; - console.log('✓ Model ready for inference'); - console.log('====================='); - } else { - console.log('Using cached model (same path and GPU layers)'); - // Recreate session if system prompt changed (without reloading the model) - const currentSystemPrompt = config.systemPrompt || null; - if (loadedSystemPrompt !== currentSystemPrompt) { - console.log('System prompt changed — recreating chat session'); - // Dispose the old sequence to free it before acquiring a new one. - // A LlamaContext only has one sequence slot; calling getSequence() a - // second time without disposing the first throws "No sequences left". - try { localLLM.sequence.dispose(); } catch { /* ignore */ } - const newSequence = localLLM.context.getSequence(); - localLLM.sequence = newSequence; - localLLM.session = new LlamaChatSession({ - contextSequence: newSequence, - systemPrompt: currentSystemPrompt || undefined - }); - loadedSystemPrompt = currentSystemPrompt; - } - } - - // Generate response - console.log('Generating response for:', message); - - const promptOptions = { maxTokens: config.maxTokens || 2048 }; - if (abortSignal) promptOptions.signal = abortSignal; - - const response = await localLLM.session.prompt(message, promptOptions); - - return { - success: true, - reply: response || '(no response)' - }; - } catch (error) { - console.error('Error with local GGUF model:', error); - console.error('Error stack:', error.stack); - - // Clean up on error - if (localLLM) { - try { - await localLLM.context?.dispose(); - await localLLM.model?.dispose(); - } catch (disposeError) { - console.error('Error disposing model:', disposeError); - } - } - localLLM = null; - loadedModelPath = null; - loadedGpuLayers = null; - loadedSystemPrompt = null; - - return { - success: false, - error: 'Local model error: ' + error.message - }; - } -} - -module.exports = { setupAssistantHandlers }; diff --git a/src/main/ipc/backendSettingsHandlers.js b/src/main/ipc/backendSettingsHandlers.js deleted file mode 100644 index 30a4999..0000000 --- a/src/main/ipc/backendSettingsHandlers.js +++ /dev/null @@ -1,125 +0,0 @@ -const { ipcMain, app, dialog } = require('electron'); -const fs = require('fs').promises; -const path = require('path'); -const { trustFile, isTrustedFile } = require('../utils/workspaceTrust'); - -function getSettingsPath() { - return path.join(app.getPath('userData'), 'backend-settings.json'); -} - -async function loadBackendSettings() { - try { - const raw = await fs.readFile(getSettingsPath(), 'utf8'); - return JSON.parse(raw); - } catch { - return {}; - } -} - -async function saveBackendSettings(settings) { - await fs.writeFile(getSettingsPath(), JSON.stringify(settings, null, 2), 'utf8'); -} - -/** - * The direct binary path is executed by the main process, so it must come from - * the browse dialog (or already be the persisted value); the renderer cannot - * type an arbitrary executable into it. - * @param {Object} settings - Incoming settings from the renderer - * @param {Object} current - Settings currently on disk - * @returns {{ valid: boolean, error?: string, settings?: Object }} - */ -function validateBackendSettings(settings, current) { - if (!settings || typeof settings !== 'object') { - return { valid: false, error: 'Invalid settings payload' }; - } - const cloudCheck = settings.cloud === undefined ? { valid: true, cloud: current && current.cloud } : validateCloudSettings(settings.cloud); - if (!cloudCheck.valid) return cloudCheck; - const cloud = cloudCheck.cloud; - const directBinaryPath = settings.directBinaryPath; - if (directBinaryPath === undefined || directBinaryPath === null || directBinaryPath === '') { - return { valid: true, settings: { directBinaryPath: '', ...(cloud ? { cloud } : {}) } }; - } - if (typeof directBinaryPath !== 'string' || !path.isAbsolute(directBinaryPath)) { - return { valid: false, error: 'Binary path must be an absolute path' }; - } - const unchanged = current && current.directBinaryPath === directBinaryPath; - if (!unchanged && !isTrustedFile(directBinaryPath)) { - return { valid: false, error: 'Choose the binary with the Browse button' }; - } - return { valid: true, settings: { directBinaryPath, ...(cloud ? { cloud } : {}) } }; -} - -/** - * Cloud client settings: platform address (https, or http for a local dev stack), - * optional private CA file, organisation slug and the upgrade link. - */ -function validateCloudSettings(cloud) { - if (cloud === undefined || cloud === null) return { valid: true, cloud: undefined }; - if (typeof cloud !== 'object') return { valid: false, error: 'Invalid cloud settings' }; - const out = {}; - if (cloud.baseUrl) { - if (typeof cloud.baseUrl !== 'string' || !/^https?:\/\/[^\s/?#]+/.test(cloud.baseUrl)) return { valid: false, error: 'Cloud platform address must be an absolute URL' }; - out.baseUrl = cloud.baseUrl.replace(/\/+$/, ''); - } - if (cloud.caFile) { - if (typeof cloud.caFile !== 'string' || !path.isAbsolute(cloud.caFile)) return { valid: false, error: 'CA file must be an absolute path' }; - out.caFile = cloud.caFile; - } - if (cloud.org) { - if (typeof cloud.org !== 'string' || !/^[a-z0-9-]{1,40}$/.test(cloud.org)) return { valid: false, error: 'Organisation must be a slug' }; - out.org = cloud.org; - } - if (cloud.upgradeUrl) { - if (typeof cloud.upgradeUrl !== 'string' || !/^https:\/\//.test(cloud.upgradeUrl)) return { valid: false, error: 'Upgrade link must be https' }; - out.upgradeUrl = cloud.upgradeUrl; - } - return { valid: true, cloud: out }; -} - -function setupBackendSettingsHandlers(mainWindow) { - ipcMain.handle('backend-get-settings', async () => { - try { - const settings = await loadBackendSettings(); - return { success: true, settings }; - } catch (e) { - return { success: false, error: e.message }; - } - }); - - ipcMain.handle('backend-save-settings', async (_event, settings) => { - try { - const validation = validateBackendSettings(settings, await loadBackendSettings()); - if (!validation.valid) return { success: false, error: validation.error }; - await saveBackendSettings(validation.settings); - return { success: true }; - } catch (e) { - return { success: false, error: e.message }; - } - }); - - ipcMain.handle('backend-browse-binary', async () => { - const win = mainWindow && !mainWindow.isDestroyed() ? mainWindow : null; - // macOS and Linux executables carry no extension, so only Windows gets an - // .exe filter — elsewhere it would hide the very file the user is after. - const filters = process.platform === 'win32' - ? [{ name: 'Executable', extensions: ['exe'] }, { name: 'All Files', extensions: ['*'] }] - : [{ name: 'All Files', extensions: ['*'] }]; - - const opts = { - title: process.platform === 'win32' ? 'Locate ctrace.exe' : 'Locate the ctrace binary', - filters, - properties: ['openFile'] - }; - const result = win - ? await dialog.showOpenDialog(win, opts) - : await dialog.showOpenDialog(opts); - - if (result.canceled || result.filePaths.length === 0) { - return { canceled: true }; - } - trustFile(result.filePaths[0]); - return { canceled: false, filePath: result.filePaths[0] }; - }); -} - -module.exports = { setupBackendSettingsHandlers, loadBackendSettings }; diff --git a/src/main/ipc/cloudHandlers.js b/src/main/ipc/cloudHandlers.js deleted file mode 100644 index f929717..0000000 --- a/src/main/ipc/cloudHandlers.js +++ /dev/null @@ -1,79 +0,0 @@ -/** - * IPC surface of the "Run in cloud" integration (contracts/gui-integration.md). - * The main process owns credentials, network and files; the renderer only sees - * the results of these calls and the `cloud-run-event` stream. - */ -const { ipcMain, safeStorage, app, net, shell } = require('electron'); -const path = require('path'); -const { loadBackendSettings } = require('./backendSettingsHandlers'); -const { CloudClient, cloudConfigDir } = require('../cloud/cloudClient'); -const { CloudRun } = require('../cloud/cloudRun'); -const { createSafeStorageStore } = require('../cloud/safeStorageStore'); - -function isOnline() { - try { - return typeof net.isOnline === 'function' ? net.isOnline() : true; - } catch { - return true; - } -} - -function setupCloudHandlers(mainWindow, overrides = {}) { - const userData = app.getPath('userData'); - const cloud = overrides.cloud || new CloudClient({ - loadSettings: loadBackendSettings, - store: createSafeStorageStore({ safeStorage, userDataDir: userData }), - configDir: cloudConfigDir(userData), - log: (line) => console.warn('[cloud]', line), - }); - const emit = (event) => { - if (mainWindow && !mainWindow.isDestroyed()) mainWindow.webContents.send('cloud-run-event', event); - }; - const runs = overrides.runs || new CloudRun({ cloud, emit }); - - const wrap = (fn) => async (_event, ...args) => { - try { - return { success: true, ...(await fn(...args)) }; - } catch (err) { - return { success: false, error: String(err && err.message ? err.message : err), code: typeof err.code === 'number' ? err.code : 4 }; - } - }; - - ipcMain.handle('cloud-status', wrap(async () => ({ status: await cloud.status(isOnline()) }))); - ipcMain.handle('cloud-login-start', wrap(async () => { - const identity = await cloud.loginStart((s) => emit({ type: 'login', state: 'pending', userCode: s.user_code, verificationUri: s.verification_uri, expiresIn: s.expires_in })); - emit({ type: 'login', state: 'approved', identity }); - return { identity }; - })); - ipcMain.handle('cloud-login-cancel', wrap(async () => { - cloud.loginCancel(); - return {}; - })); - ipcMain.handle('cloud-logout', wrap(async () => ({ result: await cloud.logout() }))); - ipcMain.handle('cloud-tools', wrap(async () => { - const { upgradeUrl } = await cloud.settings(); - return { tools: await cloud.tools(), upgradeUrl }; - })); - ipcMain.handle('cloud-limits', wrap(async () => ({ limits: await cloud.limits() }))); - ipcMain.handle('cloud-run-start', wrap(async (opts) => { - if (!opts || typeof opts.rootPath !== 'string' || !path.isAbsolute(opts.rootPath)) throw new Error('rootPath must be an absolute path'); - if (!Array.isArray(opts.tools) || opts.tools.length === 0) throw new Error('select at least one tool'); - return runs.start(opts); - })); - ipcMain.handle('cloud-run-confirm', wrap(async ({ runId, accept }) => runs.confirm(String(runId), Boolean(accept)))); - ipcMain.handle('cloud-run-cancel', wrap(async ({ runId }) => runs.cancel(String(runId)))); - ipcMain.handle('cloud-open-upgrade', wrap(async () => { - const { upgradeUrl } = await cloud.settings(); - if (/^https:\/\//.test(upgradeUrl)) await shell.openExternal(upgradeUrl); - return {}; - })); - ipcMain.handle('cloud-open-url', wrap(async (url) => { - const { baseUrl } = await cloud.settings(); - // Only the platform's own verification address may be opened from here. - if (typeof url === 'string' && url.startsWith(baseUrl)) await shell.openExternal(url); - return {}; - })); - return { cloud, runs }; -} - -module.exports = { setupCloudHandlers }; diff --git a/src/main/ipc/ctraceHandlers.js b/src/main/ipc/ctraceHandlers.js deleted file mode 100644 index 8f1dd13..0000000 --- a/src/main/ipc/ctraceHandlers.js +++ /dev/null @@ -1,802 +0,0 @@ -const { ipcMain } = require('electron'); -const { spawn } = require('child_process'); -const fs = require('fs/promises'); -const os = require('os'); -const path = require('path'); - -const { callApi, ensureServerRunning, shutdownServer, resolveBinaryPath, checkBinaryFormat, getCapturedSince, waitForCapturedJson } = require('../utils/ctraceServeClient'); -const { loadBackendSettings } = require('./backendSettingsHandlers'); - -const DEBUG_BACKEND_REQUESTS = process.env.CTRACE_GUI_DEBUG_BACKEND === '1' || process.env.NODE_ENV === 'development'; - -// TEMPORARY: the packaged coretrace release currently ships without the -// flawfinder/ assets its FlawfinderToolImplementation needs at runtime, so -// invoking it (or falling back to "run every tool" when --invoke is omitted) -// crashes analysis. Drop it from the tool set until upstream fixes the -// release packaging. Remove this once flawfinder is bundled again. -const DISABLED_TOOLS = ['flawfinder']; -const DEFAULT_INVOKE_TOOLS = ['cppcheck', 'ikos', 'tscancode', 'ctrace_stack_analyzer']; - -// Tool names the backend accepts for --invoke (per `ctrace --help` and its -// own CLI-mode "Unknown tool" error). The HTTP /api run_analysis path the -// GUI actually talks to does NOT validate this itself: an unrecognized name -// is silently dropped (empty outputs, status "ok"), unlike CLI mode which -// fails fast with this same message. Validate here so the GUI surfaces the -// same failure CLI mode does instead of reporting a false "no issues found". -const ALLOWED_INVOKE_TOOLS = ['ikos', 'cppcheck', 'tscancode', 'ctrace_stack_analyzer']; - -function parseBoolean(value) { - if (typeof value === 'boolean') return value; - if (typeof value !== 'string') return Boolean(value); - const v = value.trim().toLowerCase(); - if (v === 'true' || v === '1' || v === 'yes') return true; - if (v === 'false' || v === '0' || v === 'no') return false; - return Boolean(value); -} - -function toSnakeCase(key) { - return key.replace(/^-+/, '').replace(/-/g, '_'); -} - -function ensureArray(val) { - if (val == null) return []; - if (Array.isArray(val)) return val; - if (typeof val === 'string') { - // Support comma-separated lists. - if (val.includes(',')) return val.split(',').map(s => s.trim()).filter(Boolean); - return [val]; - } - return [String(val)]; -} - -function isSarif(json) { - return Boolean(json && typeof json === 'object' && Array.isArray(json.runs)); -} - -function sarifResultsCount(sarif) { - if (!isSarif(sarif)) return 0; - const run0 = sarif.runs[0] || {}; - const results = Array.isArray(run0.results) ? run0.results : []; - return results.length; -} - -function looksLikeStackAnalyzerJson(json) { - return Boolean( - json && - typeof json === 'object' && - json.meta && - typeof json.meta === 'object' && - (json.meta.tool === 'ctrace-stack-analyzer' || json.meta.tool === 'ctrace_stack_analyzer') && - Array.isArray(json.diagnostics) - ); -} - -function normalizeToolName(toolName) { - if (typeof toolName !== 'string') return ''; - const trimmed = toolName.trim(); - return trimmed || ''; -} - -function inferToolNameFromMessage(message, fallbackToolName = '') { - const msg = String(message || ''); - const normalizedFallback = normalizeToolName(fallbackToolName); - - // Check for Python traceback (indicates Python-based tool) - if (msg.includes('Traceback (most recent call last)')) { - const scriptMatch = msg.match(/File "([^"]+)"/); - if (scriptMatch) { - const scriptPath = scriptMatch[1]; - const scriptName = scriptPath.split(/[/\\]/).pop(); - if (scriptName && scriptName.endsWith('.py')) { - return scriptName.replace('.py', ''); - } - } - return normalizedFallback || 'PythonTool'; - } - - const toolPatterns = [ - /(?:Running|Executing|Invoking|Error in|Failed to run)\s+([a-zA-Z0-9_\-]+)/i, - /^([a-zA-Z0-9_\-]+):\s*(?:error|ERROR|Error)/i, - /\[([a-zA-Z0-9_\-]+)\]/i, - /ctrace[_-]?([a-zA-Z0-9_\-]+)/i, - ]; - - for (const toolRe of toolPatterns) { - const toolMatch = msg.match(toolRe); - if (toolMatch && toolMatch[1]) { - return toolMatch[1]; - } - } - - return normalizedFallback || 'UnknownTool'; -} - -function isLikelyExecutionFailureLine(line) { - if (typeof line !== 'string') return false; - const trimmed = line.trim(); - if (!trimmed) return false; - - const hardFailurePatterns = [ - /can't open file/i, - /no such file or directory/i, - /unknown tool/i, - /failed to run/i, - /tool execution failed/i, - /unsupported input file type/i, - /failed to analyze/i, - /\bexception\b/i, - /\btraceback\b/i - ]; - - if (hardFailurePatterns.some((re) => re.test(trimmed))) return true; - - // Avoid turning diagnostic payloads or status lines into synthetic tool errors. - if (/^"?severity"?\s*[:=]/i.test(trimmed) || /"severity"\s*:\s*"(?:ERROR|WARNING|INFO)"/i.test(trimmed)) { - return false; - } - if (/^\{.*\}$/.test(trimmed) || /^\[.*\]$/.test(trimmed)) { - try { - JSON.parse(trimmed); - return false; - } catch (_) { - // Fall through for non-JSON lines that merely resemble JSON. - } - } - - // Generic ERROR lines only count if they also include a strong failure keyword. - return /\bERROR\b/i.test(trimmed) && /\b(failed|failure|exception|unknown|invalid|missing|cannot|can't|unable|denied|unsupported)\b/i.test(trimmed); -} - -function buildToolErrorDiagnostics(textEntries, inputFile) { - const diags = []; - const seen = new Set(); - for (const entry of textEntries || []) { - const message = typeof entry === 'string' ? entry : entry && entry.message; - const fallbackToolName = typeof entry === 'string' ? '' : entry && entry.toolName; - const msg = String(message || '').trim(); - if (!msg) continue; - - const matches = []; - const tracebackMatch = msg.match(/Traceback \(most recent call last\):[\s\S]*?(?=\n\s*\n|$)/i); - if (tracebackMatch) { - matches.push(tracebackMatch[0].trim()); - } else { - for (const line of msg.split('\n')) { - if (isLikelyExecutionFailureLine(line)) { - matches.push(line.trim()); - } - } - } - - for (const match of matches) { - if (seen.has(match)) continue; - seen.add(match); - - const toolName = inferToolNameFromMessage(match, fallbackToolName); - const toolError = describeToolExecutionFailure(match, toolName); - diags.push({ - id: `tool-error-${seen.size}`, - severity: 'ERROR', - ruleId: `ToolExecutionError.${toolName}`, - location: { - file: inputFile || '', - function: 'global', - startLine: 1, - startColumn: 1, - endLine: 1, - endColumn: 1 - }, - details: { - message: toolError.summary, - rawMessage: msg, - failureKind: toolError.kind, - toolName, - suggestion: toolError.suggestion - } - }); - } - } - - return diags; -} - -function describeToolExecutionFailure(message, toolName) { - const normalizedTool = normalizeToolName(toolName) || 'requested tool'; - const msg = String(message || '').trim(); - - if (/unknown tool/i.test(msg) || /not available/i.test(msg) || /unsupported tool/i.test(msg)) { - return { - kind: 'tool-unavailable', - summary: `${normalizedTool} was requested but is not available in this backend.`, - suggestion: `Check the requested tool name and confirm that ${normalizedTool} is installed and enabled.` - }; - } - - if (/unsupported input file type/i.test(msg) || /failed to analyze/i.test(msg)) { - return { - kind: 'unsupported-input', - summary: `${normalizedTool} does not support this file's type and could not analyze it.`, - suggestion: `Choose a source file type ${normalizedTool} supports, or remove it from the tools invoked for this file.` - }; - } - - if (/no such file or directory/i.test(msg) || /can't open file/i.test(msg) || /cannot open shared object file/i.test(msg)) { - return { - kind: 'tool-startup-failed', - summary: `${normalizedTool} failed to start because a required file or runtime dependency is missing.`, - suggestion: `Verify that ${normalizedTool} and its required runtime files are installed on this system.` - }; - } - - if (/\btraceback\b/i.test(msg) || /\bexception\b/i.test(msg)) { - return { - kind: 'tool-crashed', - summary: `${normalizedTool} failed while running and reported an internal exception.`, - suggestion: `Inspect the tool output below for the stack trace and verify the tool's own runtime dependencies.` - }; - } - - if (/failed to run/i.test(msg) || /tool execution failed/i.test(msg) || /\bERROR\b/i.test(msg)) { - return { - kind: 'tool-execution-failed', - summary: `${normalizedTool} failed during execution.`, - suggestion: `Inspect the tool output below for the exact failure reported by ${normalizedTool}.` - }; - } - - return { - kind: 'tool-error', - summary: `${normalizedTool} reported an execution error.`, - suggestion: `Inspect the tool output below for more details from ${normalizedTool}.` - }; -} - -function isOutputsEnvelope(result) { - return Boolean(result && typeof result === 'object' && result.outputs && typeof result.outputs === 'object'); -} - -function extractToolMessages(outputs, toolName) { - const entries = outputs && outputs[toolName]; - if (!Array.isArray(entries)) return []; - return entries.map(e => e && e.message).filter(m => m !== undefined); -} - -function extractAllTextMessagesFromOutputs(outputs) { - if (!outputs || typeof outputs !== 'object') return []; - const out = []; - for (const toolName of Object.keys(outputs)) { - const entries = outputs[toolName]; - if (!Array.isArray(entries)) continue; - for (const e of entries) { - if (!e) continue; - if (typeof e.message === 'string' && e.message.trim()) { - out.push({ - toolName, - stream: e.stream || '', - message: e.message - }); - } - } - } - return out; -} - -function extractStackAnalyzerFromOutputs(outputs) { - const candidates = []; - // Common key is snake_case, but be defensive. - candidates.push(...extractToolMessages(outputs, 'ctrace_stack_analyzer')); - candidates.push(...extractToolMessages(outputs, 'ctrace-stack-analyzer')); - // Last message tends to be the final JSON. - for (let i = candidates.length - 1; i >= 0; i--) { - const m = candidates[i]; - if (looksLikeStackAnalyzerJson(m)) return m; - } - return null; -} - -function extractSarifFromOutputs(outputs) { - const sarifs = []; - if (!outputs || typeof outputs !== 'object') return sarifs; - for (const toolName of Object.keys(outputs)) { - const entries = outputs[toolName]; - if (!Array.isArray(entries)) continue; - for (const e of entries) { - const m = e && e.message; - if (isSarif(m)) sarifs.push({ tool: toolName, sarif: m }); - } - } - return sarifs; -} - -function pickBestSarif(sarifs) { - if (!Array.isArray(sarifs) || sarifs.length === 0) return null; - // Prefer SARIF that actually contains results. - const withResults = sarifs.find(s => sarifResultsCount(s.sarif) > 0); - return withResults || sarifs[0]; -} - -function argsToRunAnalysisParams(args = []) { - /** @type {Record} */ - const out = {}; - - // Accept both --key=value and --key value forms. - for (let i = 0; i < args.length; i++) { - const a = args[i]; - if (typeof a !== 'string') continue; - if (!a.startsWith('--')) continue; - - const eqIdx = a.indexOf('='); - let key; - let value; - - if (eqIdx !== -1) { - key = a.slice(2, eqIdx); - value = a.slice(eqIdx + 1); - } else { - key = a.slice(2); - const next = args[i + 1]; - if (typeof next === 'string' && !next.startsWith('--')) { - value = next; - i++; - } else { - value = true; - } - } - - // Normalize keys we know about. - const normalized = toSnakeCase(key); - - // Drop CLI-only flags that shouldn't be forwarded. - if (normalized === 'ipc' || normalized === 'ipc_path') continue; - - // Known list-like keys. - if (normalized === 'input' || normalized === 'entry_points' || normalized === 'entry_point' || normalized === 'invoke') { - const targetKey = normalized === 'entry_point' ? 'entry_points' : normalized; - out[targetKey] = ensureArray(value); - continue; - } - - // Known boolean flags. - if ( - normalized === 'static_analysis' || - normalized === 'dynamic_analysis' || - normalized === 'sarif_format' || - normalized === 'async' || - normalized === 'verbose' - ) { - out[normalized] = parseBoolean(value); - continue; - } - - // Translate historical CLI flag names. - if (normalized === 'sarif_format' || normalized === 'sarif') { - out.sarif_format = true; - continue; - } - - // Default: keep as string or boolean. - out[normalized] = value; - } - - // Ensure required/requested defaults. - out.ipc = 'serve'; - out.ipc_path = out.ipc_path || '/tmp/coretrace_ipc'; - - if (typeof out.static_analysis === 'undefined') out.static_analysis = true; - if (typeof out.dynamic_analysis === 'undefined') out.dynamic_analysis = false; - if (typeof out.async === 'undefined') out.async = false; - - // Default to full analysis profile so all functions (not just entry points) are analyzed. - if (typeof out.analysis_profile === 'undefined') out.analysis_profile = 'full'; - - // `input` is required by the backend. - if (out.input && !Array.isArray(out.input)) out.input = ensureArray(out.input); - - return out; -} - -function deriveCwdFromInputPath(inputPath) { - if (!inputPath || typeof inputPath !== 'string') return ''; - // If the renderer passed a WSL-style path, use posix dirname. - if (inputPath.includes('/')) { - const dir = path.posix.dirname(inputPath); - return dir && dir !== '.' ? dir : ''; - } - const dir = path.dirname(inputPath); - return dir && dir !== '.' ? dir : ''; -} - -// ========================================== -// DIRECT BINARY EXECUTION (no WSL, no HTTP server) -// ========================================== - -/** - * Convert a WSL-style path (/mnt/c/...) back to a Windows path (C:\...). - * Returns the path unchanged if it doesn't match the WSL pattern. - */ -function wslPathToWindows(p) { - if (!p || typeof p !== 'string') return p; - const m = p.match(/^\/mnt\/([a-z])(\/.*)?$/); - if (!m) return p; - const drive = m[1].toUpperCase(); - const rest = (m[2] || '').replace(/\//g, '\\'); - return `${drive}:${rest}`; -} - -/** - * Walk through args array and convert any WSL paths to Windows paths. - * Handles --input=/mnt/... , --input /mnt/... , and bare /mnt/... values. - */ -function convertArgsPathsToWindows(args) { - const out = []; - for (let i = 0; i < args.length; i++) { - const a = String(args[i]); - if (a.startsWith('--input=')) { - const val = a.slice('--input='.length); - const files = val.split(',').map(f => wslPathToWindows(f.trim())).join(','); - out.push(`--input=${files}`); - } else if (a.startsWith('/mnt/')) { - out.push(wslPathToWindows(a)); - } else { - out.push(a); - } - } - return out; -} - -/** - * Strip server-mode-only flags from an args array so they aren't forwarded - * to a standalone ctrace.exe invocation. - */ -function stripServerFlags(args) { - const out = []; - for (let i = 0; i < args.length; i++) { - const a = args[i]; - if (a === '--ipc' || a === '--ipc-path' || a === '--serve-host' || a === '--serve-port' || a === '--shutdown-token') { - const next = args[i + 1]; - if (next && !next.startsWith('--')) i++; // skip value too - continue; - } - if (a.startsWith('--ipc=') || a.startsWith('--ipc-path=') || a.startsWith('--serve-host=') || a.startsWith('--serve-port=') || a.startsWith('--shutdown-token=')) { - continue; - } - out.push(a); - } - return out; -} - -/** Extract all complete JSON objects/arrays from a string. */ -function extractJsonFromText(text) { - const results = []; - let buf = text; - let i = 0; - while (i < buf.length) { - const sObj = buf.indexOf('{', i); - const sArr = buf.indexOf('[', i); - let start, opening; - if (sObj === -1 && sArr === -1) break; - if (sObj === -1) { start = sArr; opening = '['; } - else if (sArr === -1) { start = sObj; opening = '{'; } - else if (sObj < sArr) { start = sObj; opening = '{'; } - else { start = sArr; opening = '['; } - - let depth = 0, inStr = false, esc = false, end = -1; - for (let j = start; j < buf.length; j++) { - const ch = buf[j]; - if (inStr) { - if (esc) { esc = false; continue; } - if (ch === '\\') { esc = true; continue; } - if (ch === '"') inStr = false; - continue; - } - if (ch === '"') { inStr = true; continue; } - if (ch === '{' || ch === '[') { depth++; continue; } - if (ch === '}' || ch === ']') { - depth--; - if (depth === 0) { end = j + 1; break; } - } - } - if (end === -1) break; - try { - results.push(JSON.parse(buf.slice(start, end))); - } catch (_) {} - i = end; - } - return results; -} - -/** - * Spawn ctrace.exe directly (Windows native, no WSL) and return parsed output. - * Returns { success, output } on success or { success: false, error } on failure. - */ -async function runDirectBinary(binaryPath, rawArgs) { - // Validate binary - console.log(`!!!! Running ctrace in direct mode with binary path: ${binaryPath} and args: ${rawArgs.join(' ') } !!!!`); - try { - await fs.access(binaryPath); - } catch (e) { - return { success: false, error: `ctrace binary not found at ${binaryPath}: ${e.message}` }; - } - - const args = stripServerFlags(convertArgsPathsToWindows(rawArgs)); - - console.log(`[ctrace-direct] spawning: ${binaryPath} ${args.join(' ')}`); - - const { code, stdout, stderr } = await new Promise((resolve, reject) => { - let out = '', err = ''; - const proc = spawn(binaryPath, args, { stdio: 'pipe', windowsHide: true }); - proc.stdout.on('data', d => { out += d.toString(); }); - proc.stderr.on('data', d => { err += d.toString(); }); - proc.on('error', reject); - proc.on('close', code => resolve({ code, stdout: out, stderr: err })); - - // 5-minute hard timeout - const timer = setTimeout(() => { - try { proc.kill(); } catch (_) {} - reject(new Error('ctrace direct execution timed out after 5 minutes')); - }, 300000); - proc.on('close', () => clearTimeout(timer)); - }); - - console.log(`[ctrace-direct] exited code=${code}`); - if (stderr.trim()) console.error(`[ctrace-direct stderr]: ${stderr.trimEnd()}`); - - // Try to find useful JSON in stdout - const jsonObjects = extractJsonFromText(stdout); - - // Prefer stack analyzer JSON (has meta + diagnostics) - const stackJson = [...jsonObjects].reverse().find(looksLikeStackAnalyzerJson) || null; - // Prefer SARIF with results - const sarifs = jsonObjects.filter(isSarif); - const bestSarif = sarifs.find(s => sarifResultsCount(s) > 0) || sarifs[0] || null; - - const inputFile = (() => { - const inputArg = args.find(a => a.startsWith('--input=')); - if (inputArg) { - const val = inputArg.slice('--input='.length); - return val.split(',')[0]; - } - return ''; - })(); - - // Build tool error diagnostics from stderr/stdout text - const textEntries = []; - for (const line of (stdout + '\n' + stderr).split('\n')) { - if (line.trim()) textEntries.push(line); - } - const toolErrorDiags = buildToolErrorDiagnostics(textEntries, inputFile); - - if (stackJson) { - const combined = { - ...stackJson, - sarif: bestSarif || null, - diagnostics: Array.isArray(stackJson.diagnostics) - ? [...stackJson.diagnostics, ...toolErrorDiags] - : toolErrorDiags - }; - return { success: true, output: JSON.stringify(combined, null, 2) }; - } - - if (bestSarif) { - return { success: true, output: JSON.stringify(bestSarif, null, 2) }; - } - - if (toolErrorDiags.length > 0) { - const combined = { - meta: { tool: 'coretrace', note: 'Tool execution errors from direct binary run' }, - functions: [], - diagnostics: toolErrorDiags - }; - return { success: true, output: JSON.stringify(combined, null, 2) }; - } - - // If binary failed and no JSON output, surface the error - if (code !== 0 && !stdout.trim()) { - return { success: false, error: stderr.trim() || `ctrace exited with code ${code}` }; - } - - // Return raw stdout if nothing else - return { success: true, output: stdout.trim() }; -} - -// ========================================== -// MAIN HANDLER -// ========================================== - -function setupCtraceHandlers() { - ipcMain.handle('run-ctrace', async (_event, args = []) => { - // Check if user configured a direct binary path - let directBinaryPath = null; - try { - const settings = await loadBackendSettings(); - if (settings && settings.directBinaryPath) { - directBinaryPath = settings.directBinaryPath; - } - } catch (_) {} - - if (directBinaryPath) { - // Direct mode: ensure server is shut down, then run the exe directly - try { await shutdownServer(); } catch (_) {} - return runDirectBinary(directBinaryPath, args); - } - - // Validate binary presence early (for a clear error message). - try { - console.log('[ctrace debug] Binary path:', resolveBinaryPath()); - await fs.access(resolveBinaryPath()); - } catch (e) { - return { success: false, error: `ctrace binary not found: ${e.message}` }; - } - - // On macOS the bundled binary may be a Linux ELF; say so instead of letting - // the spawn fail with "cannot execute binary file". - const format = checkBinaryFormat(resolveBinaryPath()); - if (!format.ok) { - return { success: false, error: format.error }; - } - - // The server is run through WSL on Windows. - if (os.platform() === 'win32') { - // We rely on main.js's WSL readiness checks + UI. - // If WSL is missing, the spawn will fail and we surface the error. - } - - try { - const params = argsToRunAnalysisParams(args); - - if (Array.isArray(params.invoke)) { - const unknownTool = params.invoke.find((tool) => !ALLOWED_INVOKE_TOOLS.includes(tool)); - if (unknownTool) { - return { - success: false, - error: `Unknown tool '${unknownTool}'. Allowed tools: [${ALLOWED_INVOKE_TOOLS.join(',')}]` - }; - } - } - - if (Array.isArray(params.invoke)) { - params.invoke = params.invoke.filter((tool) => !DISABLED_TOOLS.includes(tool)); - } else { - params.invoke = DEFAULT_INVOKE_TOOLS; - } - - // The backend's static_analysis=true mode runs every static tool and - // ignores `invoke` entirely (verified against v0.74.0), so flawfinder - // still crashes even once excluded above. Drop static_analysis and - // rely on the explicit invoke list instead, which the backend does - // honor — this still runs all the other static tools. - if (params.static_analysis) { - delete params.static_analysis; - } - - if (DEBUG_BACKEND_REQUESTS) { - console.log('[ctrace debug] run-ctrace args:', JSON.stringify(args)); - console.log('[ctrace debug] run-ctrace params:', JSON.stringify(params)); - } - - await ensureServerRunning(); - const captureSince = Date.now(); - const apiRes = await callApi('run_analysis', params); - - if (!apiRes.ok) { - const errText = apiRes.json?.error?.message || apiRes.json?.error || apiRes.raw || `HTTP ${apiRes.statusCode}`; - return { success: false, error: errText, statusCode: apiRes.statusCode }; - } - - // Most backends respond with {result: ...}. If not, return the full JSON. - const payload = apiRes.json?.result ?? apiRes.json; - - // Newer backends return a "result" envelope with per-tool outputs. - // If present, flatten the most relevant tool output into the legacy format the GUI expects. - if (isOutputsEnvelope(payload)) { - const outputs = payload.outputs; - let stackJson = extractStackAnalyzerFromOutputs(outputs); - const sarifs = extractSarifFromOutputs(outputs); - const bestSarif = pickBestSarif(sarifs); - - const inputFile = Array.isArray(payload.input) ? payload.input[0] : (Array.isArray(params.input) ? params.input[0] : ''); - const outputTextMessages = extractAllTextMessagesFromOutputs(outputs); - const toolErrorDiags = buildToolErrorDiagnostics(outputTextMessages, inputFile); - - const wantsStackAnalyzer = Array.isArray(params.invoke) && params.invoke.includes('ctrace_stack_analyzer'); - - // Some backends/tools print the stack-analyzer JSON after the HTTP response. - // If we didn't get diagnostics yet, fall back to captured stdout/stderr. - if ( - wantsStackAnalyzer && - typeof waitForCapturedJson === 'function' && - typeof getCapturedSince === 'function' && - (!stackJson || (Array.isArray(stackJson.diagnostics) && stackJson.diagnostics.length === 0)) - ) { - try { - await waitForCapturedJson( - (j) => looksLikeStackAnalyzerJson(j) && Array.isArray(j.diagnostics) && j.diagnostics.length > 0, - { sinceTs: captureSince, timeoutMs: 15000, pollMs: 250 } - ); - } catch { - // Ignore timeouts; we'll still return what we have. - } - - const capturedOut = getCapturedSince(captureSince); - const laterStackJson = [...capturedOut.json].reverse().find( - (j) => looksLikeStackAnalyzerJson(j) && Array.isArray(j.diagnostics) && j.diagnostics.length > 0 - ); - if (laterStackJson) stackJson = laterStackJson; - - // Also surface tool execution errors from stderr/stdout if any. - if (capturedOut.text && capturedOut.text.length > 0) { - toolErrorDiags.push(...buildToolErrorDiagnostics(capturedOut.text, inputFile)); - } - } - - if (stackJson) { - const combined = { - ...stackJson, - sarif: bestSarif ? bestSarif.sarif : null, - diagnostics: Array.isArray(stackJson.diagnostics) - ? [...stackJson.diagnostics, ...toolErrorDiags] - : toolErrorDiags - }; - return { success: true, output: JSON.stringify(combined, null, 2), statusCode: apiRes.statusCode }; - } - - if (bestSarif) { - return { success: true, output: JSON.stringify(bestSarif.sarif, null, 2), statusCode: apiRes.statusCode }; - } - - if (toolErrorDiags.length > 0) { - const combined = { - meta: { tool: 'coretrace', note: 'Tool execution errors captured from /api outputs', sarif: Boolean(payload.sarif_format) }, - functions: [], - diagnostics: toolErrorDiags - }; - return { success: true, output: JSON.stringify(combined, null, 2), statusCode: apiRes.statusCode }; - } - } - - // If we got SARIF with no results, but we invoked the stack analyzer (or any tool that prints - // additional JSON to stdout), wait for the extra JSON and merge so the GUI doesn't show "All clear". - const wantsStackAnalyzer = Array.isArray(params.invoke) && params.invoke.includes('ctrace_stack_analyzer'); - const isSarifPayload = isSarif(payload); - const sarifCount = isSarifPayload ? sarifResultsCount(payload) : null; - - if (wantsStackAnalyzer && isSarifPayload && sarifCount === 0) { - // Wait for stack analyzer JSON to appear on stdout (backend may return SARIF early). - await waitForCapturedJson(looksLikeStackAnalyzerJson, { sinceTs: captureSince, timeoutMs: 45000, pollMs: 250 }); - const capturedOut = getCapturedSince(captureSince); - const stackJson = [...capturedOut.json].reverse().find(looksLikeStackAnalyzerJson) || null; - const toolErrorDiags = buildToolErrorDiagnostics(capturedOut.text, (params.input && params.input[0]) || ''); - - if (stackJson) { - // Preserve SARIF alongside stack analyzer output. - const combined = { - ...stackJson, - sarif: payload, - diagnostics: Array.isArray(stackJson.diagnostics) - ? [...stackJson.diagnostics, ...toolErrorDiags] - : toolErrorDiags - }; - return { success: true, output: JSON.stringify(combined, null, 2), statusCode: apiRes.statusCode }; - } - - // If stack JSON didn't show up, still surface tool execution errors if we saw any. - if (toolErrorDiags.length > 0) { - const combined = { - meta: { tool: 'coretrace', note: 'SARIF contained no results; tool execution errors captured from server logs', sarif: true }, - functions: [], - diagnostics: toolErrorDiags, - sarif: payload - }; - return { success: true, output: JSON.stringify(combined, null, 2), statusCode: apiRes.statusCode }; - } - } - - const output = typeof payload === 'string' ? payload : JSON.stringify(payload, null, 2); - return { success: true, output, statusCode: apiRes.statusCode }; - } catch (e) { - return { success: false, error: e.message }; - } - }); -} - -module.exports = { setupCtraceHandlers, shutdownCtraceServer: shutdownServer }; diff --git a/src/main/ipc/editorHandlers.js b/src/main/ipc/editorHandlers.js deleted file mode 100644 index 27be461..0000000 --- a/src/main/ipc/editorHandlers.js +++ /dev/null @@ -1,36 +0,0 @@ -const { ipcMain } = require('electron'); -const { exec } = require('child_process'); - -/** - * Setup IPC handlers for editor operations - */ -function setupEditorHandlers() { - // Open editor listener - ipcMain.on('open-editor', () => { - console.log("button clicked !"); - let command; - - switch (process.platform) { - case 'win32': // Windows - command = 'notepad'; - break; - case 'darwin': // macOS - command = 'open -a TextEdit'; - break; - case 'linux': // Linux - command = 'x-terminal-emulator -e nano'; // or just 'nano' if terminal already open - break; - default: - console.warn(`[open-editor] Unsupported platform: ${process.platform}`); - return; - } - - exec(command, (err) => { - if (err) { - console.error(`[open-editor] Failed to launch external editor on ${process.platform} (command: "${command}"): [${err.code || 'ERR'}] ${err.message}`); - } - }); - }); -} - -module.exports = { setupEditorHandlers }; \ No newline at end of file diff --git a/src/main/ipc/fileHandlers.js b/src/main/ipc/fileHandlers.js deleted file mode 100644 index 4190dd8..0000000 --- a/src/main/ipc/fileHandlers.js +++ /dev/null @@ -1,884 +0,0 @@ -/** - * @fileoverview IPC handlers for file operations in the main process. - * - * This module provides all IPC handlers for file system operations including - * opening files/folders, saving files, reading file content, and managing - * file system watching for automatic UI updates. - * - * @author CTrace GUI Team - * @version 1.0.0 - */ - -const { ipcMain, dialog } = require('electron'); -const fs = require('fs').promises; -const fsSync = require('fs'); -const path = require('path'); -const { execFile } = require('child_process'); -const { promisify } = require('util'); -const execFileP = promisify(execFile); -const chokidar = require('chokidar'); -const ignore = require('ignore'); -const { detectFileEncoding, buildFileTree, searchInDirectory, FILE_SIZE_LIMIT, LARGE_FILE_THRESHOLD, validatePathInWorkspace } = require('../utils/fileUtils'); -const { formatFileError } = require('../utils/errorUtils'); -const { trustWorkspaceRoot, trustFile, isTrustedWorkspaceRoot, isTrustedFile, isSamePath } = require('../utils/workspaceTrust'); - -const FILE_TREE_MAX_DEPTH = 3; - -// A checked-out repository can point core.fsmonitor at an arbitrary program in -// its own .git/config; running git status would then execute it. Disable it for -// every git invocation on a workspace we did not author. -const GIT_SAFE_CONFIG = ['-c', 'core.fsmonitor=false']; - -/** - * File watcher instance for monitoring workspace changes - * @type {chokidar.FSWatcher|null} - * @private - */ -let fileWatcher = null; - -/** - * Currently watched workspace path - * @type {string|null} - * @private - */ -let currentWatchPath = null; - -let workspaceLoadingSeq = 0; - -/** - * Validates that the renderer may act on targetPath. - * A path is allowed when it was handed out by a native dialog (or restored - * from the saved session) or when it lies inside the current workspace root. - * Returns an error response object when validation fails, or null when the path is safe. - * - * @param {string} targetPath - * @returns {{ success: false, error: string }|null} - */ -function requireInWorkspace(targetPath) { - if (isTrustedFile(targetPath)) return null; - if (!currentWatchPath) { - return { success: false, error: 'Access denied: path was not opened through the application' }; - } - const { valid } = validatePathInWorkspace(targetPath, currentWatchPath); - if (!valid) { - return { success: false, error: 'Access denied: path is outside the current workspace' }; - } - return null; -} - -/** - * Reduce a git porcelain XY status pair to a single decoration code. - * @returns {'U'|'M'|'A'|'D'|'R'|'C'|null} - */ -function gitStatusCode(x, y) { - if (x === '?' || y === '?') return 'U'; // untracked - if (x === 'U' || y === 'U' || (x === 'A' && y === 'A') || (x === 'D' && y === 'D')) return 'C'; // conflict - if (x === 'R' || y === 'R') return 'R'; // renamed - if (x === 'A' || y === 'A') return 'A'; // added - if (x === 'D' || y === 'D') return 'D'; // deleted - if (x === 'M' || y === 'M') return 'M'; // modified - if (x !== ' ' || y !== ' ') return 'M'; // any other change - return null; -} - -/** - * Sets up all IPC handlers for file operations. - * - * This function registers all IPC handlers that the renderer process can invoke - * for file operations. It handles folder dialogs, file dialogs, saving files, - * reading files, and file tree operations. - * - * @function setupFileHandlers - * @param {BrowserWindow} mainWindow - Main window reference for dialogs - * - * @example - * setupFileHandlers(mainWindow); - */ -function setupFileHandlers(mainWindow) { - // Open folder dialog - ipcMain.handle('open-folder-dialog', async () => { - const result = await dialog.showOpenDialog(mainWindow, { - properties: ['openDirectory'] - }); - - if (!result.canceled && result.filePaths.length > 0) { - const folderPath = result.filePaths[0]; - trustWorkspaceRoot(folderPath); - const requestId = ++workspaceLoadingSeq; - try { - try { - mainWindow.webContents.send('workspace-loading', { - status: 'start', - operation: 'open', - folderPath, - requestId - }); - } catch (_) {} - - const fileTree = await buildFileTree(folderPath, FILE_TREE_MAX_DEPTH); - - // Start watching the workspace for changes - startWatchingWorkspace(folderPath, mainWindow, FILE_TREE_MAX_DEPTH); - - try { - mainWindow.webContents.send('workspace-loading', { - status: 'end', - operation: 'open', - folderPath, - requestId, - success: true - }); - } catch (_) {} - - return { - success: true, - folderPath, - fileTree - }; - } catch (error) { - try { - mainWindow.webContents.send('workspace-loading', { - status: 'end', - operation: 'open', - folderPath, - requestId, - success: false, - error: error.message - }); - } catch (_) {} - return { - success: false, - error: formatFileError(error, folderPath, 'open folder') - }; - } - } - - return { success: false, canceled: true }; - }); - - // Check if a file path exists on disk (lightweight, no content read) - ipcMain.handle('check-file-exists', async (_event, filePath) => { - if (!filePath) return { exists: false }; - const violation = requireInWorkspace(filePath); - if (violation) return { exists: false }; - try { - await fs.access(filePath); - return { exists: true }; - } catch { - return { exists: false }; - } - }); - - // Get file tree for refresh (now uses lazy loading) - ipcMain.handle('get-file-tree', async (event, folderPath) => { - const violation = requireInWorkspace(folderPath); - if (violation) return { success: false, error: violation.error }; - const requestId = ++workspaceLoadingSeq; - try { - try { - mainWindow.webContents.send('workspace-loading', { - status: 'start', - operation: 'refresh', - folderPath, - requestId - }); - } catch (_) {} - - const fileTree = await buildFileTree(folderPath, false); // Lazy load - - try { - mainWindow.webContents.send('workspace-loading', { - status: 'end', - operation: 'refresh', - folderPath, - requestId, - success: true - }); - } catch (_) {} - return { - success: true, - fileTree - }; - } catch (error) { - try { - mainWindow.webContents.send('workspace-loading', { - status: 'end', - operation: 'refresh', - folderPath, - requestId, - success: false, - error: formatFileError(error, folderPath, 'refresh file tree for') - }); - } catch (_) {} - return { - success: false, - error: formatFileError(error, folderPath, 'refresh file tree for') - }; - } - }); - - // Get directory contents for lazy loading - ipcMain.handle('get-directory-contents', async (event, dirPath) => { - const violation = requireInWorkspace(dirPath); - if (violation) return { success: false, error: violation.error }; - try { - const contents = await buildFileTree(dirPath, false); - return { - success: true, - contents - }; - } catch (error) { - return { - success: false, - error: formatFileError(error, dirPath, 'read directory contents for') - }; - } - }); - - // Git status for the current workspace. Returns a map of absolute file path - // -> single-letter decoration code. Always resolves (never throws to the UI); - // a missing git binary or a non-repo workspace yields { repo:false, files:{} }. - ipcMain.handle('get-git-status', async () => { - const cwd = currentWatchPath; - if (!cwd) return { success: true, repo: false, files: {} }; - - try { - // Resolve the repo root so porcelain paths (relative to repo root) can be - // turned into absolute paths matching the file-tree item paths. - let repoRoot; - try { - const { stdout } = await execFileP('git', [...GIT_SAFE_CONFIG, '-C', cwd, 'rev-parse', '--show-toplevel'], { timeout: 8000 }); - repoRoot = stdout.trim(); - } catch { - return { success: true, repo: false, files: {} }; - } - if (!repoRoot) return { success: true, repo: false, files: {} }; - - const { stdout } = await execFileP( - 'git', - [...GIT_SAFE_CONFIG, '-c', 'core.quotepath=false', '-C', cwd, 'status', '--porcelain=v1', '--ignored=no', '-z'], - { timeout: 15000, maxBuffer: 16 * 1024 * 1024 } - ); - - const files = {}; - const tokens = stdout.split('\0'); - for (let i = 0; i < tokens.length; i++) { - const entry = tokens[i]; - if (!entry || entry.length < 3) continue; - const x = entry[0]; - const y = entry[1]; - let relPath = entry.slice(3); - - // Renames/copies carry the original path in the next NUL-terminated token. - if (x === 'R' || x === 'C' || y === 'R' || y === 'C') { - i++; // consume original-path token - } - - const code = gitStatusCode(x, y); - if (code) files[path.join(repoRoot, relPath)] = code; - } - - return { success: true, repo: true, files }; - } catch { - return { success: true, repo: false, files: {} }; - } - }); - - // Start watching a workspace (renderer may request this after opening or on - // session restore). Only roots issued by a folder dialog or the saved session - // are accepted, so the renderer cannot re-point the workspace at will. - ipcMain.handle('watch-workspace', async (event, folderPath) => { - try { - if (!folderPath) { - return { success: false, error: 'No folder path provided' }; - } - if (!isTrustedWorkspaceRoot(folderPath)) { - return { success: false, error: 'Access denied: folder was not opened through the application' }; - } - const stats = await fs.stat(folderPath); - if (!stats.isDirectory()) { - return { success: false, error: 'Workspace path is not a directory' }; - } - startWatchingWorkspace(folderPath, mainWindow, FILE_TREE_MAX_DEPTH); - return { success: true }; - } catch (error) { - return { success: false, error: error.message }; - } - }); - - // Open file dialog - ipcMain.handle('open-file-dialog', async () => { - const result = await dialog.showOpenDialog(mainWindow, { - properties: ['openFile'], - filters: [ - { name: 'All Files', extensions: ['*'] }, - { name: 'Text Files', extensions: ['txt', 'md', 'json', 'js', 'ts', 'html', 'css', 'py', 'cpp', 'c', 'h'] } - ] - }); - - if (!result.canceled && result.filePaths.length > 0) { - const filePath = result.filePaths[0]; - trustFile(filePath); - try { - const fileInfo = await detectFileEncoding(filePath); - - // Large-file gate — use size already obtained by detectFileEncoding - if (fileInfo.size > LARGE_FILE_THRESHOLD) { - return { - success: true, - warning: 'large-file', - filePath, - fileName: path.basename(filePath), - totalSize: fileInfo.size - }; - } - - if (!fileInfo.isUTF8) { - // File is not UTF-8, return warning info - return { - success: true, - warning: 'encoding', - filePath, - fileName: path.basename(filePath), - message: 'This file appears to contain non-UTF8 characters. Opening it may cause display issues or data corruption.' - }; - } - - let content; - let isPartial = false; - - if (fileInfo.size > FILE_SIZE_LIMIT) { - // File is large, load only first part - const partialBuffer = fileInfo.buffer.slice(0, FILE_SIZE_LIMIT); - content = partialBuffer.toString('utf8'); - isPartial = true; - } else { - // File is small enough, load entirely - content = fileInfo.buffer.toString('utf8'); - } - - return { - success: true, - filePath, - content, - fileName: path.basename(filePath), - isPartial, - totalSize: fileInfo.size, - loadedSize: isPartial ? FILE_SIZE_LIMIT : fileInfo.size - }; - } catch (error) { - return { - success: false, - error: formatFileError(error, filePath, 'open') - }; - } - } - - return { success: false, canceled: true }; - }); - - // Select local LLM (GGUF) model file - ipcMain.handle('select-llm-file', async () => { - const result = await dialog.showOpenDialog(mainWindow, { - properties: ['openFile'], - filters: [ - { name: 'GGUF / Model Files', extensions: ['gguf', 'bin', 'pt', 'ggml', 'onnx'] }, - { name: 'All Files', extensions: ['*'] } - ] - }); - - if (!result.canceled && result.filePaths.length > 0) { - trustFile(result.filePaths[0]); - return { success: true, filePath: result.filePaths[0] }; - } - - return { success: false, canceled: true }; - }); - - // Save file - ipcMain.handle('save-file', async (event, filePath, content) => { - const violation = requireInWorkspace(filePath); - if (violation) return violation; - try { - await fs.writeFile(filePath, content, 'utf8'); - return { success: true }; - } catch (error) { - return { success: false, error: formatFileError(error, filePath, 'save') }; - } - }); - - // Save file as - ipcMain.handle('save-file-as', async (event, content) => { - const result = await dialog.showSaveDialog(mainWindow, { - filters: [ - { name: 'All Files', extensions: ['*'] }, - { name: 'Text Files', extensions: ['txt'] }, - { name: 'JavaScript', extensions: ['js'] }, - { name: 'TypeScript', extensions: ['ts'] }, - { name: 'HTML', extensions: ['html'] }, - { name: 'CSS', extensions: ['css'] } - ] - }); - - if (!result.canceled) { - trustFile(result.filePath); - try { - await fs.writeFile(result.filePath, content, 'utf8'); - return { - success: true, - filePath: result.filePath, - fileName: path.basename(result.filePath) - }; - } catch (error) { - return { success: false, error: formatFileError(error, result.filePath, 'save') }; - } - } - - return { success: false, canceled: true }; - }); - - // Create a new empty file in a directory - ipcMain.handle('create-file', async (event, directoryPath, fileName) => { - const violation = requireInWorkspace(directoryPath); - if (violation) return violation; - try { - if (!directoryPath) return { success: false, error: 'No directory provided' }; - if (!fileName || typeof fileName !== 'string') return { success: false, error: 'Invalid file name' }; - - const trimmed = fileName.trim(); - if (!trimmed || trimmed === '.' || trimmed === '..') { - return { success: false, error: 'Invalid file name' }; - } - if (trimmed.includes('/') || trimmed.includes('\\')) { - return { success: false, error: 'File name must not contain path separators' }; - } - - const newPath = path.join(directoryPath, trimmed); - - await fs.writeFile(newPath, '', { encoding: 'utf8', flag: 'wx' }); - - return { success: true, path: newPath, name: trimmed }; - } catch (error) { - return { success: false, error: formatFileError(error, newPath, 'create file') }; - } - }); - - // Create a new folder in a directory - ipcMain.handle('create-folder', async (event, directoryPath, folderName) => { - const violation = requireInWorkspace(directoryPath); - if (violation) return violation; - try { - if (!directoryPath) return { success: false, error: 'No directory provided' }; - if (!folderName || typeof folderName !== 'string') return { success: false, error: 'Invalid folder name' }; - - const trimmed = folderName.trim(); - if (!trimmed || trimmed === '.' || trimmed === '..') { - return { success: false, error: 'Invalid folder name' }; - } - if (trimmed.includes('/') || trimmed.includes('\\')) { - return { success: false, error: 'Folder name must not contain path separators' }; - } - - const newPath = path.join(directoryPath, trimmed); - await fs.mkdir(newPath); - - return { success: true, path: newPath, name: trimmed }; - } catch (error) { - return { success: false, error: formatFileError(error, newPath, 'create folder') }; - } - }); - - // Rename a file or folder - ipcMain.handle('rename-path', async (event, targetPath, newName) => { - const violation = requireInWorkspace(targetPath); - if (violation) return violation; - try { - if (!targetPath) return { success: false, error: 'No target path provided' }; - if (!newName || typeof newName !== 'string') return { success: false, error: 'Invalid new name' }; - - const trimmed = newName.trim(); - if (!trimmed || trimmed === '.' || trimmed === '..') { - return { success: false, error: 'Invalid new name' }; - } - if (trimmed.includes('/') || trimmed.includes('\\')) { - return { success: false, error: 'Name must not contain path separators' }; - } - - const stats = await fs.lstat(targetPath); - const newPath = path.join(path.dirname(targetPath), trimmed); - await fs.rename(targetPath, newPath); - - return { success: true, newPath, name: trimmed, isFile: stats.isFile() }; - } catch (error) { - return { success: false, error: formatFileError(error, targetPath, 'rename') }; - } - }); - - // Delete a file or folder (recursive for folders) - ipcMain.handle('delete-path', async (event, targetPath) => { - if (!currentWatchPath) return { success: false, error: 'Access denied: no workspace is currently open' }; - const violation = requireInWorkspace(targetPath); - if (violation) return violation; - if (isSamePath(targetPath, currentWatchPath)) { - return { success: false, error: 'Refusing to delete the workspace root' }; - } - try { - if (!targetPath) return { success: false, error: 'No target path provided' }; - - const stats = await fs.lstat(targetPath); - if (stats.isDirectory()) { - await fs.rm(targetPath, { recursive: true, force: true }); - } else { - await fs.unlink(targetPath); - } - - return { success: true }; - } catch (error) { - return { success: false, error: formatFileError(error, targetPath, 'delete') }; - } - }); - - // Read file content - ipcMain.handle('read-file', async (event, filePath) => { - const violation = requireInWorkspace(filePath); - if (violation) return violation; - try { - const fileInfo = await detectFileEncoding(filePath); - - // Large-file gate — use size already obtained by detectFileEncoding - if (fileInfo.size > LARGE_FILE_THRESHOLD) { - return { - success: true, - warning: 'large-file', - filePath, - fileName: path.basename(filePath), - totalSize: fileInfo.size - }; - } - - if (!fileInfo.isUTF8) { - // File is not UTF-8, return warning info - return { - success: true, - warning: 'encoding', - filePath, - fileName: path.basename(filePath), - message: 'This file appears to contain non-UTF8 characters. Opening it may cause display issues or data corruption.' - }; - } - - let content; - let isPartial = false; - - if (fileInfo.size > FILE_SIZE_LIMIT) { - // File is large, load only first part - const partialBuffer = fileInfo.buffer.slice(0, FILE_SIZE_LIMIT); - content = partialBuffer.toString('utf8'); - isPartial = true; - } else { - // File is small enough, load entirely - content = fileInfo.buffer.toString('utf8'); - } - - return { - success: true, - content, - fileName: path.basename(filePath), - isPartial, - totalSize: fileInfo.size, - loadedSize: isPartial ? FILE_SIZE_LIMIT : fileInfo.size - }; - } catch (error) { - return { success: false, error: formatFileError(error, filePath, 'read') }; - } - }); - - // Load complete file (for large files that were partially loaded) - ipcMain.handle('load-complete-file', async (event, filePath) => { - const violation = requireInWorkspace(filePath); - if (violation) return violation; - try { - const fileInfo = await detectFileEncoding(filePath); - - if (!fileInfo.isUTF8) { - return { - success: false, - error: 'File contains non-UTF8 characters and cannot be safely loaded.' - }; - } - - const content = fileInfo.buffer.toString('utf8'); - - return { - success: true, - content, - fileName: path.basename(filePath), - isPartial: false, - totalSize: fileInfo.size, - loadedSize: fileInfo.size - }; - } catch (error) { - return { success: false, error: formatFileError(error, filePath, 'load') }; - } - }); - - // Read large file (user confirmed — skips the size pre-check) - ipcMain.handle('read-large-file', async (event, filePath) => { - const violation = requireInWorkspace(filePath); - if (violation) return violation; - try { - const fileInfo = await detectFileEncoding(filePath); - - if (!fileInfo.isUTF8) { - return { - success: true, - warning: 'encoding', - filePath, - fileName: path.basename(filePath), - message: 'This file appears to contain non-UTF8 characters. Opening it may cause display issues or data corruption.' - }; - } - - const isPartial = fileInfo.size > FILE_SIZE_LIMIT; - const content = fileInfo.buffer.toString('utf8'); - - return { - success: true, - content, - fileName: path.basename(filePath), - isPartial, - totalSize: fileInfo.size, - loadedSize: fileInfo.buffer.length - }; - } catch (error) { - return { success: false, error: formatFileError(error, filePath, 'read') }; - } - }); - - // Read the next chunk of a file starting at a byte offset - ipcMain.handle('read-file-chunk', async (event, filePath, offset) => { - const violation = requireInWorkspace(filePath); - if (violation) return violation; - try { - const stat = await fs.stat(filePath); - const totalSize = stat.size; - - if (offset >= totalSize) { - return { success: true, content: '', loadedSize: 0, newOffset: offset, isMore: false, totalSize }; - } - - const readSize = Math.min(FILE_SIZE_LIMIT, totalSize - offset); - const fd = await fs.open(filePath, 'r'); - try { - const buffer = Buffer.allocUnsafe(readSize); - const { bytesRead } = await fd.read(buffer, 0, readSize, offset); - const content = buffer.slice(0, bytesRead).toString('utf8'); - const newOffset = offset + bytesRead; - return { - success: true, - content, - loadedSize: bytesRead, - newOffset, - isMore: newOffset < totalSize, - totalSize - }; - } finally { - await fd.close(); - } - } catch (error) { - return { success: false, error: formatFileError(error, filePath, 'read chunk') }; - } - }); - - // Force open file (ignore encoding warnings) - ipcMain.handle('force-open-file', async (event, filePath) => { - const violation = requireInWorkspace(filePath); - if (violation) return violation; - try { - const fileInfo = await detectFileEncoding(filePath); - - let content; - let isPartial = false; - - // Try to read as UTF-8, may have some garbled characters - if (fileInfo.size > FILE_SIZE_LIMIT) { - const partialBuffer = fileInfo.buffer.slice(0, FILE_SIZE_LIMIT); - try { - content = partialBuffer.toString('utf8'); - } catch (error) { - // If UTF-8 fails, try latin1 as fallback - content = partialBuffer.toString('latin1'); - } - isPartial = true; - } else { - try { - content = fileInfo.buffer.toString('utf8'); - } catch (error) { - // If UTF-8 fails, try latin1 as fallback - content = fileInfo.buffer.toString('latin1'); - } - } - - return { - success: true, - content, - fileName: path.basename(filePath), - isPartial, - totalSize: fileInfo.size, - loadedSize: isPartial ? FILE_SIZE_LIMIT : fileInfo.size, - encodingWarning: !fileInfo.isUTF8 - }; - } catch (error) { - return { success: false, error: formatFileError(error, filePath, 'open') }; - } - }); - - // Search in files - ipcMain.handle('search-in-files', async (event, searchTerm, folderPath) => { - const violation = requireInWorkspace(folderPath); - if (violation) return violation; - try { - const results = await searchInDirectory(folderPath, searchTerm); - return { success: true, results }; - } catch (error) { - return { success: false, error: formatFileError(error, folderPath, 'search in') }; - } - }); - - // Handler to force load full file (bypass size limits) - ipcMain.handle('force-load-full-file', async (event, filePath) => { - const violation = requireInWorkspace(filePath); - if (violation) return violation; - try { - const buffer = await fs.readFile(filePath); - const content = buffer.toString('utf8'); - - return { - success: true, - content, - totalSize: buffer.length, - fileName: path.basename(filePath) - }; - } catch (error) { - console.error(`[force-load-full-file] ${formatFileError(error, filePath, 'read')}`); - return { - success: false, - error: formatFileError(error, filePath, 'read') - }; - } - }); -} - -/** - * Load .gitignore rules from the workspace root synchronously. - * Returns an `ignore` instance; if no .gitignore exists the instance is empty. - * @param {string} workspacePath - * @returns {import('ignore').Ignore} - */ -function loadGitignoreRules(workspacePath) { - const ig = ignore(); - try { - const gitignorePath = path.join(workspacePath, '.gitignore'); - const content = fsSync.readFileSync(gitignorePath, 'utf8'); - ig.add(content); - } catch (_) { - // No .gitignore or unreadable — nothing extra ignored - } - return ig; -} - -/** - * Start watching workspace for file changes - * @param {string} workspacePath - Path to watch - * @param {BrowserWindow} mainWindow - Main window reference - */ -function startWatchingWorkspace(workspacePath, mainWindow, watchDepth = FILE_TREE_MAX_DEPTH) { - // Stop existing watcher if any - stopWatchingWorkspace(); - - currentWatchPath = workspacePath; - - // Load .gitignore rules once at watcher start - const ig = loadGitignoreRules(workspacePath); - const isGitignored = (filePath) => { - try { - const rel = path.relative(workspacePath, filePath).replace(/\\/g, '/'); - if (!rel || rel.startsWith('..')) return false; - return ig.ignores(rel); - } catch (_) { - return false; - } - }; - - // Create new watcher - fileWatcher = chokidar.watch(workspacePath, { - ignoreInitial: true, - ignored: [ - /(^|[\/\\])\../, // hidden files/dirs - /node_modules/, - /\.git/, - /dist/, - /build/, - /out/, - /coverage/, - /\.next/, - /\.cache/, - /target/, - /vendor/, - /__pycache__/, - /\.venv/, - /venv/, - /My Music/, - /My Pictures/, - /My Videos/, - /\$RECYCLE\.BIN/, - /System Volume Information/, - isGitignored // .gitignore rules - ], - depth: watchDepth, - ignorePermissionErrors: true - }); - - // Debounce: coalesce rapid FS events before notifying renderer - let updateTimeout; - let lastChangedPath = null; - const debouncedUpdate = (changedPath) => { - clearTimeout(updateTimeout); - lastChangedPath = changedPath || lastChangedPath; - updateTimeout = setTimeout(async () => { - try { - mainWindow.webContents.send('workspace-changed', { - success: true, - folderPath: workspacePath, - changedPath: lastChangedPath - }); - } catch (error) { - console.error('Error updating file tree:', error); - } - }, 300); - }; - - // Listen for file system events - fileWatcher - .on('add', debouncedUpdate) - .on('unlink', debouncedUpdate) - .on('addDir', debouncedUpdate) - .on('unlinkDir', debouncedUpdate) - .on('error', error => console.error('File watcher error:', error)); - - console.log('Started watching workspace:', workspacePath); -} - -/** - * Stop watching current workspace - */ -function stopWatchingWorkspace() { - if (fileWatcher) { - fileWatcher.close(); - fileWatcher = null; - console.log('Stopped watching workspace:', currentWatchPath); - } - currentWatchPath = null; -} - -module.exports = { setupFileHandlers }; \ No newline at end of file diff --git a/src/main/ipc/secureStorageHandlers.js b/src/main/ipc/secureStorageHandlers.js deleted file mode 100644 index 2eca17c..0000000 --- a/src/main/ipc/secureStorageHandlers.js +++ /dev/null @@ -1,238 +0,0 @@ -/** - * @fileoverview IPC handlers for secure assistant configuration storage - * - * Uses Electron's safeStorage API to encrypt/decrypt the API key at rest. - * Non-sensitive fields (provider, model, systemPrompt, …) are stored as - * plain JSON alongside an encrypted blob for the key so that only the OS - * credential store can read it back. - * - * The decrypted key never leaves the main process: the renderer only learns - * whether a key is stored (`hasApiKey`), and provider requests read the key - * through {@link loadStoredApiKey}. - * - * Storage location: /assistant-config.json - * - * @author CTrace GUI Team - * @version 1.0.0 - */ - -const { ipcMain, safeStorage, app } = require('electron'); -const fs = require('fs').promises; -const path = require('path'); -const { trustFile } = require('../utils/workspaceTrust'); - -/** Conversation ids are generated by the renderer, so they are validated here before touching the filesystem. */ -const CONVERSATION_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; - -/** - * Return the path where the assistant config is persisted. - * @returns {string} - */ -function getConfigPath() { - return path.join(app.getPath('userData'), 'assistant-config.json'); -} - -function getConversationsDir() { - return path.join(app.getPath('userData'), 'assistant-conversations'); -} - -/** - * Read the stored config as written on disk (encrypted key blob included). - * @returns {Promise} null when no config exists - */ -async function readStoredConfig() { - try { - return JSON.parse(await fs.readFile(getConfigPath(), 'utf8')); - } catch (error) { - if (error.code === 'ENOENT') return null; - throw error; - } -} - -/** - * Decrypt and return the stored API key, or null when none is stored. - * @returns {Promise} - */ -async function loadStoredApiKey() { - const stored = await readStoredConfig(); - if (!stored || !stored._encryptedApiKey) return null; - if (!safeStorage.isEncryptionAvailable()) return null; - return safeStorage.decryptString(Buffer.from(stored._encryptedApiKey, 'base64')); -} - -/** - * Strip secret material and report whether a key exists. - * @param {Object} stored - * @returns {Object} - */ -function toRendererConfig(stored) { - const { _encryptedApiKey, apiKey, ...rest } = stored; - return { ...rest, hasApiKey: Boolean(_encryptedApiKey) }; -} - -/** - * Resolve the conversation file for an id, rejecting anything that is not a - * plain identifier (path separators, dots, empty strings, …). - * @param {*} id - * @returns {string|null} - */ -function conversationPath(id) { - if (typeof id !== 'string' || !CONVERSATION_ID_RE.test(id)) return null; - return path.join(getConversationsDir(), `${id}.json`); -} - -const INVALID_CONVERSATION_ID = { success: false, error: 'Invalid conversation id' }; - -/** - * Register IPC handlers for secure config operations. - * - * Channels exposed: - * - assistant-config-save (invoke) – persist config, encrypting the apiKey - * - assistant-config-load (invoke) – load config without the apiKey - * - assistant-config-clear (invoke) – delete stored config - */ -function setupSecureStorageHandlers() { - /** - * Persist assistant configuration. - * A non-empty `apiKey` replaces the stored key (encrypted); an empty one - * keeps whatever key is already on disk. The plaintext key is never written. - */ - ipcMain.handle('assistant-config-save', async (_event, config) => { - try { - const { apiKey, hasApiKey, _encryptedApiKey, ...toStore } = config || {}; - const existing = await readStoredConfig(); - - if (apiKey) { - if (!safeStorage.isEncryptionAvailable()) { - return { success: false, error: 'OS credential encryption is unavailable; the API key was not saved' }; - } - toStore._encryptedApiKey = safeStorage.encryptString(apiKey).toString('base64'); - } else if (existing && existing._encryptedApiKey) { - toStore._encryptedApiKey = existing._encryptedApiKey; - } - - if (toStore.localModelPath) trustFile(toStore.localModelPath); - - await fs.writeFile(getConfigPath(), JSON.stringify(toStore, null, 2), 'utf8'); - console.log('[SecureStorage] Assistant config saved'); - return { success: true }; - } catch (error) { - console.error('[SecureStorage] Error saving config:', error); - return { success: false, error: error.message }; - } - }); - - /** - * Load assistant configuration for the renderer (no secret material). - */ - ipcMain.handle('assistant-config-load', async () => { - try { - const stored = await readStoredConfig(); - if (!stored) return { success: false, error: 'No config found' }; - if (stored.localModelPath) trustFile(stored.localModelPath); - return { success: true, config: toRendererConfig(stored) }; - } catch (error) { - console.error('[SecureStorage] Error loading config:', error); - return { success: false, error: error.message }; - } - }); - - /** - * Delete the stored assistant configuration. - */ - ipcMain.handle('assistant-config-clear', async () => { - try { - await fs.unlink(getConfigPath()); - console.log('[SecureStorage] Assistant config cleared'); - return { success: true }; - } catch (error) { - if (error.code === 'ENOENT') return { success: true }; - console.error('[SecureStorage] Error clearing config:', error); - return { success: false, error: error.message }; - } - }); - - // ── Conversation history persistence ────────────────────────────────────── - - /** - * Save (create or overwrite) a conversation. - * Data: { id, title, history, createdAt } - */ - ipcMain.handle('assistant-conversations-save', async (_event, data) => { - const filePath = conversationPath(data && data.id); - if (!filePath) return INVALID_CONVERSATION_ID; - try { - await fs.mkdir(getConversationsDir(), { recursive: true }); - await fs.writeFile(filePath, JSON.stringify({ ...data, updatedAt: new Date().toISOString() }, null, 2), 'utf8'); - return { success: true }; - } catch (error) { - console.error('[SecureStorage] Error saving conversation:', error); - return { success: false, error: error.message }; - } - }); - - /** - * List all saved conversations, sorted newest first. - * Returns: { success, conversations: [{ id, title, createdAt, updatedAt }] } - */ - ipcMain.handle('assistant-conversations-list', async () => { - try { - const dir = getConversationsDir(); - let files; - try { - files = await fs.readdir(dir); - } catch (e) { - if (e.code === 'ENOENT') return { success: true, conversations: [] }; - throw e; - } - const conversations = []; - for (const f of files) { - if (!f.endsWith('.json')) continue; - try { - const raw = await fs.readFile(path.join(dir, f), 'utf8'); - const { id, title, createdAt, updatedAt } = JSON.parse(raw); - conversations.push({ id, title, createdAt, updatedAt }); - } catch (_) { /* skip corrupt files */ } - } - conversations.sort((a, b) => new Date(b.updatedAt || b.createdAt) - new Date(a.updatedAt || a.createdAt)); - return { success: true, conversations }; - } catch (error) { - console.error('[SecureStorage] Error listing conversations:', error); - return { success: false, error: error.message }; - } - }); - - /** - * Load a single saved conversation by id. - * Returns: { success, conversation: { id, title, history, createdAt, updatedAt } } - */ - ipcMain.handle('assistant-conversations-load', async (_event, id) => { - const filePath = conversationPath(id); - if (!filePath) return INVALID_CONVERSATION_ID; - try { - const raw = await fs.readFile(filePath, 'utf8'); - return { success: true, conversation: JSON.parse(raw) }; - } catch (error) { - console.error('[SecureStorage] Error loading conversation:', error); - return { success: false, error: error.message }; - } - }); - - /** - * Delete a saved conversation by id. - */ - ipcMain.handle('assistant-conversations-delete', async (_event, id) => { - const filePath = conversationPath(id); - if (!filePath) return INVALID_CONVERSATION_ID; - try { - await fs.unlink(filePath); - return { success: true }; - } catch (error) { - if (error.code === 'ENOENT') return { success: true }; - console.error('[SecureStorage] Error deleting conversation:', error); - return { success: false, error: error.message }; - } - }); -} - -module.exports = { setupSecureStorageHandlers, loadStoredApiKey }; diff --git a/src/main/ipc/stateHandlers.js b/src/main/ipc/stateHandlers.js deleted file mode 100644 index a22d67c..0000000 --- a/src/main/ipc/stateHandlers.js +++ /dev/null @@ -1,272 +0,0 @@ -/** - * @fileoverview IPC handlers for application state persistence - * - * Provides handlers for saving, loading, and managing application state - * for work loss prevention. State is stored as JSON in the user's data directory. - * - * @author CTrace GUI Team - * @version 1.0.0 - */ - -const { ipcMain, app } = require('electron'); -const fs = require('fs').promises; -const path = require('path'); -const { trustWorkspaceRoot, trustFile, isTrustedWorkspaceRoot, isTrustedFile } = require('../utils/workspaceTrust'); - -/** - * Get the path to the state file in the user's data directory - * @returns {string} Full path to state file - */ -function getStatePath() { - const userDataPath = app.getPath('userData'); - return path.join(userDataPath, 'app-state.json'); -} - -/** - * Get the path to the backup state file - * @returns {string} Full path to backup state file - */ -function getBackupStatePath() { - const userDataPath = app.getPath('userData'); - return path.join(userDataPath, 'app-state.backup.json'); -} - -/** - * Setup IPC handlers for state management operations - * - * Registers the following IPC handlers: - * - save-app-state: Save current application state - * - load-app-state: Load saved application state - * - clear-app-state: Clear saved state - * - get-state-info: Get information about saved state - * - * @function setupStateHandlers - */ -/** - * Strip any workspace or tab path the renderer did not legitimately obtain - * from this process. The renderer only ever sees paths that came from a native - * dialog or lie inside an opened workspace, so anything else is dropped rather - * than persisted and trusted again on the next launch. - * @param {Object} state - * @returns {Object} - */ -function sanitizeStateForSave(state) { - if (!state || typeof state !== 'object') return state; - const clean = { ...state }; - - if (clean.workspacePath && !isTrustedWorkspaceRoot(clean.workspacePath)) { - console.warn('[StateHandlers] Dropping untrusted workspace path from saved state'); - clean.workspacePath = null; - } - - if (Array.isArray(clean.tabs)) { - clean.tabs = clean.tabs.map((tab) => { - if (!tab || !tab.filePath) return tab; - if (isTrustedFile(tab.filePath) || isInsideTrustedWorkspace(tab.filePath, clean.workspacePath)) { - return tab; - } - console.warn('[StateHandlers] Dropping untrusted tab path from saved state'); - return { ...tab, filePath: null }; - }); - } - - return clean; -} - -function isInsideTrustedWorkspace(filePath, workspacePath) { - if (!workspacePath || !isTrustedWorkspaceRoot(workspacePath)) return false; - const relative = path.relative(path.resolve(workspacePath), path.resolve(filePath)); - return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative); -} - -/** - * Paths restored from the saved session were validated when they were saved, - * so they may be used again by the renderer for this launch. - * @param {Object} state - */ -function trustRestoredPaths(state) { - if (state.workspacePath) trustWorkspaceRoot(state.workspacePath); - if (Array.isArray(state.tabs)) { - state.tabs.forEach((tab) => { - if (tab && tab.filePath) trustFile(tab.filePath); - }); - } -} - -function setupStateHandlers() { - /** - * Save application state to disk - * Creates a backup of the previous state before saving - */ - ipcMain.handle('save-app-state', async (event, state) => { - try { - const statePath = getStatePath(); - const backupPath = getBackupStatePath(); - - // Create backup of existing state if it exists - try { - await fs.access(statePath); - await fs.copyFile(statePath, backupPath); - console.log('[StateHandlers] Created backup of existing state'); - } catch (err) { - // No existing state to backup, that's okay - } - - // Save new state - const stateJson = JSON.stringify(sanitizeStateForSave(state), null, 2); - await fs.writeFile(statePath, stateJson, 'utf8'); - - // console.log('[StateHandlers] State saved successfully:', { - // path: statePath, - // size: stateJson.length, - // tabCount: state.tabs?.length || 0 - // }); - - return { success: true }; - } catch (error) { - console.error('[StateHandlers] Error saving state:', error); - return { success: false, error: error.message }; - } - }); - - /** - * Load application state from disk - * Attempts to load from backup if main state file is corrupted - */ - ipcMain.handle('load-app-state', async () => { - const statePath = getStatePath(); - const backupPath = getBackupStatePath(); - - /** - * Try to load and parse a state file - * @param {string} filePath - Path to state file - * @returns {Object|null} Parsed state or null if error - */ - async function tryLoadState(filePath) { - try { - const stateJson = await fs.readFile(filePath, 'utf8'); - const state = JSON.parse(stateJson); - - // Validate state structure - if (!state || typeof state !== 'object') { - console.warn('[StateHandlers] Invalid state structure'); - return null; - } - - console.log('[StateHandlers] State loaded successfully:', { - path: filePath, - version: state.version, - timestamp: state.timestamp, - tabCount: state.tabs?.length || 0 - }); - - return state; - } catch (error) { - if (error.code === 'ENOENT') { - // File not found is normal on first launch — not an error worth logging loudly. - console.log(`[StateHandlers] State file not found (ENOENT): "${path.normalize(filePath)}" — starting fresh`); - } else if (error instanceof SyntaxError) { - console.warn(`[StateHandlers] State file corrupted (invalid JSON) at "${path.normalize(filePath)}" — discarding and falling back to backup`); - } else { - console.warn(`[StateHandlers] Failed to load state from "${path.normalize(filePath)}": [${error.code || 'ERR'}] ${error.message}`); - } - return null; - } - } - - // Try to load main state file - let state = await tryLoadState(statePath); - - // If main state failed, try backup - if (!state) { - console.log('[StateHandlers] Attempting to load backup state...'); - state = await tryLoadState(backupPath); - } - - if (state) { - trustRestoredPaths(state); - return { success: true, state: state }; - } else { - return { success: false, error: 'No valid state found' }; - } - }); - - /** - * Clear saved application state - * Removes both main and backup state files - */ - ipcMain.handle('clear-app-state', async () => { - try { - const statePath = getStatePath(); - const backupPath = getBackupStatePath(); - - // Remove main state file - try { - await fs.unlink(statePath); - console.log('[StateHandlers] Removed main state file'); - } catch (err) { - if (err.code !== 'ENOENT') { - console.warn(`[StateHandlers] Failed to remove state file "${path.normalize(statePath)}": [${err.code || 'ERR'}] ${err.message}`); - } - } - - // Remove backup state file - try { - await fs.unlink(backupPath); - console.log('[StateHandlers] Removed backup state file'); - } catch (err) { - if (err.code !== 'ENOENT') { - console.warn(`[StateHandlers] Failed to remove backup state file "${path.normalize(backupPath)}": [${err.code || 'ERR'}] ${err.message}`); - } - } - - return { success: true }; - } catch (error) { - console.error('[StateHandlers] Error clearing state:', error); - return { success: false, error: error.message }; - } - }); - - /** - * Get information about saved state without loading it - * Useful for checking if state exists and when it was last saved - */ - ipcMain.handle('get-state-info', async () => { - try { - const statePath = getStatePath(); - - try { - const stats = await fs.stat(statePath); - const stateJson = await fs.readFile(statePath, 'utf8'); - const state = JSON.parse(stateJson); - - return { - success: true, - info: { - exists: true, - size: stats.size, - modified: stats.mtime, - version: state.version, - timestamp: state.timestamp, - tabCount: state.tabs?.length || 0, - hasDiagnostics: !!state.diagnostics - } - }; - } catch (error) { - return { - success: true, - info: { - exists: false - } - }; - } - } catch (error) { - console.error('[StateHandlers] Error getting state info:', error); - return { success: false, error: error.message }; - } - }); - - console.log('[StateHandlers] State management IPC handlers registered'); -} - -module.exports = { setupStateHandlers }; diff --git a/src/main/ipc/terminalHandlers.js b/src/main/ipc/terminalHandlers.js deleted file mode 100644 index 9563d2c..0000000 --- a/src/main/ipc/terminalHandlers.js +++ /dev/null @@ -1,302 +0,0 @@ -/** - * Terminal IPC handlers - spawns shell commands with PTY support for interactive commands. - * Uses node-pty to provide pseudo-terminal for sudo, password prompts, etc. - */ - -const { ipcMain } = require('electron'); -const { spawn } = require('child_process'); -const os = require('os'); -const fs = require('fs'); -const path = require('path'); -const pty = require('node-pty'); - -// terminalId -> currently running child process (one at a time per terminal) -const runningProcesses = new Map(); - -function getAvailableShells() { - const platform = os.platform(); - const shells = []; - - if (platform === 'win32') { - shells.push({ id: 'powershell', name: 'PowerShell', icon: 'ps' }); - shells.push({ id: 'cmd', name: 'Command Prompt', icon: 'cmd' }); - - // PowerShell Core (pwsh) - try { - const { execSync } = require('child_process'); - execSync('pwsh --version', { stdio: 'ignore', timeout: 2000, windowsHide: true }); - shells.push({ id: 'pwsh', name: 'PowerShell Core', icon: 'ps' }); - } catch {} - - // Git Bash - const gitBashCandidates = [ - 'C:\\Program Files\\Git\\bin\\bash.exe', - 'C:\\Program Files (x86)\\Git\\bin\\bash.exe', - path.join(os.homedir(), 'AppData', 'Local', 'Programs', 'Git', 'bin', 'bash.exe'), - ]; - for (const p of gitBashCandidates) { - try { - if (fs.existsSync(p)) { - shells.push({ id: 'gitbash', name: 'Git Bash', path: p, icon: 'bash' }); - break; - } - } catch {} - } - - // WSL - try { - const { execSync } = require('child_process'); - execSync('wsl --list --quiet', { stdio: 'ignore', timeout: 3000, windowsHide: true }); - shells.push({ id: 'wsl', name: 'WSL', icon: 'bash' }); - } catch {} - - } else if (platform === 'darwin') { - shells.push({ id: 'zsh', name: 'zsh', icon: 'bash' }); - shells.push({ id: 'bash', name: 'bash', icon: 'bash' }); - } else { - shells.push({ id: 'bash', name: 'bash', icon: 'bash' }); - if (fs.existsSync('/bin/zsh')) shells.push({ id: 'zsh', name: 'zsh', icon: 'bash' }); - if (fs.existsSync('/usr/bin/fish')) shells.push({ id: 'fish', name: 'fish', icon: 'bash' }); - } - - return shells; -} - -function buildSpawnArgs(shellId, command, cwd, shellPath) { - const platform = os.platform(); - - if (platform === 'win32') { - switch (shellId) { - case 'powershell': - return { - cmd: 'powershell.exe', - args: [ - '-NoLogo', '-NonInteractive', - '-Command', - `Set-Location -LiteralPath '${cwd.replace(/'/g, "''")}'; ${command}`, - ], - cwd: os.homedir(), - }; - case 'pwsh': - return { - cmd: 'pwsh.exe', - args: [ - '-NoLogo', '-NonInteractive', - '-Command', - `Set-Location -LiteralPath '${cwd.replace(/'/g, "''")}'; ${command}`, - ], - cwd: os.homedir(), - }; - case 'cmd': - return { cmd: 'cmd.exe', args: ['/C', command], cwd }; - case 'gitbash': - return { - cmd: shellPath || 'C:\\Program Files\\Git\\bin\\bash.exe', - args: ['-c', command], - cwd, - }; - case 'wsl': - return { cmd: 'wsl.exe', args: ['-e', 'bash', '-c', command], cwd: null }; - default: - return { cmd: 'cmd.exe', args: ['/C', command], cwd }; - } - } else { - const bin = - shellId === 'zsh' ? '/bin/zsh' : - shellId === 'fish' ? '/usr/bin/fish' : - '/bin/bash'; - return { cmd: bin, args: ['-c', command], cwd }; - } -} - -function setupTerminalHandlers(mainWindow) { - ipcMain.handle('terminal-get-shells', () => getAvailableShells()); - - ipcMain.handle('terminal-execute', async (event, { terminalId, shellId, shellPath, command, cwd }) => { - // Kill any previously running command in this terminal - const prev = runningProcesses.get(terminalId); - if (prev) { - try { killProcess(prev); } catch {} - runningProcesses.delete(terminalId); - } - - const built = buildSpawnArgs(shellId, command, cwd || os.homedir(), shellPath); - - return new Promise((resolve) => { - let proc; - try { - // Use node-pty for interactive command support (sudo, password prompts, etc.) - proc = pty.spawn(built.cmd, built.args, { - name: 'xterm-color', - cols: 80, - rows: 24, - cwd: built.cwd !== undefined ? built.cwd : (cwd || os.homedir()), - env: { ...process.env, TERM: 'xterm-color' }, - }); - } catch (err) { - if (!mainWindow.isDestroyed()) { - mainWindow.webContents.send('terminal-data', { - terminalId, - data: `\u001b[31mFailed to start: ${err.message}\u001b[0m\r\n`, - }); - mainWindow.webContents.send('terminal-command-done', { terminalId, code: 1 }); - } - resolve({ error: err.message }); - return; - } - - runningProcesses.set(terminalId, proc); - - proc.onData((data) => { - if (!mainWindow.isDestroyed()) { - mainWindow.webContents.send('terminal-data', { terminalId, data: data.toString() }); - } - }); - - proc.onExit(({ exitCode }) => { - runningProcesses.delete(terminalId); - if (!mainWindow.isDestroyed()) { - mainWindow.webContents.send('terminal-command-done', { terminalId, code: exitCode }); - } - resolve({ code: exitCode }); - }); - }); - }); - - ipcMain.handle('terminal-kill-current', (event, terminalId) => { - const proc = runningProcesses.get(terminalId); - if (proc) { - try { - // node-pty process has a kill() method - if (typeof proc.kill === 'function') { - proc.kill(); - } else { - killProcess(proc); - } - } catch {} - runningProcesses.delete(terminalId); - } - }); - - ipcMain.handle('terminal-send-input', (event, { terminalId, input }) => { - const proc = runningProcesses.get(terminalId); - if (proc) { - // node-pty uses write() method directly - proc.write(input + '\n'); - } - }); - - ipcMain.handle('terminal-get-home', () => { - // On Windows, return the home directory - // On Linux/Mac, return home directory - const home = os.homedir(); - return home; - }); - - ipcMain.handle('terminal-get-initial-cwd', () => { - // Return app's current working directory - return process.cwd(); - }); - - ipcMain.handle('terminal-get-completions', async (event, { cwd, partial }) => { - const path = require('path'); - const fs = require('fs'); - - // Parse the partial input to extract what we're completing - const trimmed = partial.trim(); - const lastSpace = trimmed.lastIndexOf(' '); - const word = lastSpace === -1 ? trimmed : trimmed.substring(lastSpace + 1); - - const completions = []; - - // If word is empty, suggest files in cwd - if (!word) { - try { - const files = fs.readdirSync(cwd, { withFileTypes: true }); - for (const f of files.slice(0, 30)) { - completions.push({ - label: f.isDirectory() ? f.name + '/' : f.name, - value: f.name + (f.isDirectory() ? '/' : ''), - isDir: f.isDirectory(), - }); - } - } catch {} - return completions.sort((a, b) => a.label.localeCompare(b.label)); - } - - // If word looks like a path (contains / or \) - if (word.includes('/') || word.includes('\\')) { - const sep = word.includes('\\') ? '\\' : '/'; - const lastSep = word.lastIndexOf(sep); - const dir = lastSep === -1 ? cwd : path.resolve(cwd, word.substring(0, lastSep)); - const prefix = lastSep === -1 ? word : word.substring(lastSep + 1); - - try { - const files = fs.readdirSync(dir, { withFileTypes: true }); - for (const f of files) { - if (f.name.toLowerCase().startsWith(prefix.toLowerCase())) { - const fullPath = word.substring(0, lastSep + 1) + f.name; - completions.push({ - label: f.isDirectory() ? fullPath + '/' : fullPath, - value: fullPath + (f.isDirectory() ? '/' : ''), - isDir: f.isDirectory(), - }); - } - } - } catch {} - return completions.sort((a, b) => a.label.localeCompare(b.label)); - } - - // Otherwise, suggest matching files/executables in cwd - try { - const files = fs.readdirSync(cwd, { withFileTypes: true }); - for (const f of files) { - if (f.name.toLowerCase().startsWith(word.toLowerCase())) { - completions.push({ - label: f.isDirectory() ? f.name + '/' : f.name, - value: f.name + (f.isDirectory() ? '/' : ''), - isDir: f.isDirectory(), - }); - } - } - } catch {} - - // Add some common commands if word starts with a letter and no matches yet - if (completions.length === 0 && /^[a-z]/i.test(word)) { - const commonCmds = [ - 'cd', 'ls', 'pwd', 'echo', 'cat', 'mkdir', 'rm', 'cp', 'mv', 'touch', - 'git', 'npm', 'node', 'python', 'pip', 'docker', 'curl', 'wget', - ]; - for (const cmd of commonCmds) { - if (cmd.startsWith(word.toLowerCase())) { - completions.push({ label: cmd, value: cmd, isDir: false }); - } - } - } - - return completions.sort((a, b) => a.label.localeCompare(b.label)).slice(0, 20); - }); -} - -function killProcess(proc) { - if (process.platform === 'win32') { - spawn('taskkill', ['/pid', String(proc.pid), '/f', '/t'], { windowsHide: true }); - } else { - proc.kill('SIGTERM'); - } -} - -function cleanupTerminals() { - for (const proc of runningProcesses.values()) { - try { - if (typeof proc.kill === 'function') { - proc.kill(); - } else { - killProcess(proc); - } - } catch {} - } - runningProcesses.clear(); -} - -module.exports = { setupTerminalHandlers, cleanupTerminals }; diff --git a/src/main/ipc/updaterHandlers.js b/src/main/ipc/updaterHandlers.js deleted file mode 100644 index 6108e2c..0000000 --- a/src/main/ipc/updaterHandlers.js +++ /dev/null @@ -1,352 +0,0 @@ -/** - * @fileoverview IPC handlers and runtime integration for application updates. - * - * Uses electron-updater and persists update channel selection (main/beta) - * under the userData directory. - */ - -const { ipcMain, app } = require('electron'); -const { autoUpdater } = require('electron-updater'); -const fs = require('fs').promises; -const path = require('path'); - -let updaterInitialized = false; -let mainWindowRef = null; -let lastBackendStatus = null; -const UPDATE_CHECK_INTERVAL_MS = 10 * 60 * 1000; -const UPDATER_LOG_FILE = 'updater.log'; - -function getUpdaterSettingsPath() { - return path.join(app.getPath('userData'), 'updater-settings.json'); -} - -function getUpdaterLogPath() { - return path.join(app.getPath('userData'), UPDATER_LOG_FILE); -} - -function formatLogMeta(meta) { - if (meta == null) return ''; - if (typeof meta === 'string') return meta; - try { - return JSON.stringify(meta); - } catch (_) { - return String(meta); - } -} - -function writeUpdaterLog(level, message, meta) { - const timestamp = new Date().toISOString(); - const details = formatLogMeta(meta); - const line = `[${timestamp}] [${level}] ${message}${details ? ` | ${details}` : ''}\n`; - fs.appendFile(getUpdaterLogPath(), line, 'utf8').catch(() => {}); -} - -function logUpdaterInfo(message, meta) { - console.log('[UpdaterHandlers]', message, ...(meta == null ? [] : [meta])); - writeUpdaterLog('INFO', message, meta); -} - -function logUpdaterWarn(message, meta) { - console.warn('[UpdaterHandlers]', message, ...(meta == null ? [] : [meta])); - writeUpdaterLog('WARN', message, meta); -} - -function logUpdaterError(message, meta) { - console.error('[UpdaterHandlers]', message, ...(meta == null ? [] : [meta])); - writeUpdaterLog('ERROR', message, meta); -} - -function normalizeChannel(channel) { - return channel === 'beta' ? 'beta' : 'main'; -} - -function toUpdaterChannel(channel) { - return channel === 'beta' ? 'beta' : 'latest'; -} - -async function loadUpdaterSettings() { - const settingsPath = getUpdaterSettingsPath(); - try { - const raw = await fs.readFile(settingsPath, 'utf8'); - const parsed = JSON.parse(raw); - return { channel: normalizeChannel(parsed.channel) }; - } catch (_) { - return { channel: 'main' }; - } -} - -async function saveUpdaterSettings(settings) { - const settingsPath = getUpdaterSettingsPath(); - const payload = { - channel: normalizeChannel(settings.channel) - }; - await fs.writeFile(settingsPath, JSON.stringify(payload, null, 2), 'utf8'); - return payload; -} - -function sendUpdaterEvent(payload) { - if (!mainWindowRef || mainWindowRef.isDestroyed()) return; - mainWindowRef.webContents.send('updater-status', payload); -} - -function applyUpdaterChannel(channel) { - const normalized = normalizeChannel(channel); - autoUpdater.allowPrerelease = normalized === 'beta'; - autoUpdater.channel = toUpdaterChannel(normalized); - // electron-updater flips allowDowngrade on whenever a channel is assigned; - // an older build must never be installed over a newer one. - autoUpdater.allowDowngrade = false; - return normalized; -} - -function setupUpdaterHandlers(mainWindow) { - mainWindowRef = mainWindow; - - ipcMain.handle('updater-get-settings', async () => { - try { - const settings = await loadUpdaterSettings(); - const applied = applyUpdaterChannel(settings.channel); - return { - success: true, - settings: { channel: applied }, - isPackaged: app.isPackaged - }; - } catch (error) { - return { success: false, error: error.message }; - } - }); - - ipcMain.handle('updater-set-channel', async (_event, channel) => { - try { - const normalized = normalizeChannel(channel); - const saved = await saveUpdaterSettings({ channel: normalized }); - applyUpdaterChannel(saved.channel); - return { - success: true, - settings: saved - }; - } catch (error) { - return { success: false, error: error.message }; - } - }); - - ipcMain.handle('updater-check-now', async () => { - if (!app.isPackaged) { - logUpdaterWarn('Manual update check rejected in development mode'); - return { - success: false, - error: 'Auto updates are only available in packaged builds.' - }; - } - - try { - logUpdaterInfo('Manual update check requested'); - const result = await autoUpdater.checkForUpdates(); - logUpdaterInfo('Manual update check completed', { - updateInfo: result?.updateInfo || null - }); - return { - success: true, - updateInfo: result?.updateInfo || null - }; - } catch (error) { - logUpdaterError('Manual update check failed', error?.message || String(error)); - return { success: false, error: error.message }; - } - }); - - ipcMain.handle('updater-install-update', async () => { - if (!app.isPackaged) { - logUpdaterWarn('Install update rejected in development mode'); - return { - success: false, - error: 'Install update is only available in packaged builds.' - }; - } - - try { - logUpdaterInfo('Install update requested, app will quit and install'); - setImmediate(() => autoUpdater.quitAndInstall()); - return { success: true }; - } catch (error) { - logUpdaterError('Install update failed', error?.message || String(error)); - return { success: false, error: error.message }; - } - }); - - ipcMain.handle('backend-get-status', async () => { - return { - success: true, - status: lastBackendStatus - }; - }); - - logUpdaterInfo('Updater IPC handlers registered', { logPath: getUpdaterLogPath() }); -} - -async function setupAutoUpdater(mainWindow) { - if (updaterInitialized) return; - updaterInitialized = true; - mainWindowRef = mainWindow; - - const settings = await loadUpdaterSettings(); - const activeChannel = applyUpdaterChannel(settings.channel); - - autoUpdater.autoDownload = true; - // Builds are not code-signed yet, so an update is only installed when the - // user explicitly chooses "restart to apply" (updater-install-update). - autoUpdater.autoInstallOnAppQuit = false; - - logUpdaterInfo('Auto updater initialized', { - activeChannel, - logPath: getUpdaterLogPath(), - isPackaged: app.isPackaged - }); - - autoUpdater.on('checking-for-update', () => { - logUpdaterInfo('Checking for update'); - sendUpdaterEvent({ type: 'checking-for-update' }); - }); - - autoUpdater.on('update-available', (info) => { - logUpdaterInfo('Update available', info); - sendUpdaterEvent({ type: 'update-available', info }); - }); - - autoUpdater.on('update-not-available', (info) => { - logUpdaterInfo('Update not available', info); - sendUpdaterEvent({ type: 'update-not-available', info }); - }); - - autoUpdater.on('download-progress', (progressObj) => { - logUpdaterInfo('Update download progress', { - percent: progressObj?.percent, - transferred: progressObj?.transferred, - total: progressObj?.total, - bytesPerSecond: progressObj?.bytesPerSecond - }); - sendUpdaterEvent({ type: 'download-progress', progress: progressObj }); - }); - - autoUpdater.on('update-downloaded', (info) => { - logUpdaterInfo('Update downloaded', info); - sendUpdaterEvent({ type: 'update-downloaded', info }); - }); - - autoUpdater.on('error', (error) => { - logUpdaterError('Updater error event', error?.message || String(error)); - sendUpdaterEvent({ type: 'error', message: error?.message || String(error) }); - }); - - logUpdaterInfo('Update channel applied', { activeChannel }); - - let backendCheckInFlight = false; - const runBackendCheck = () => { - if (backendCheckInFlight) return; - backendCheckInFlight = true; - - let checkAndUpdateBackendBinary; - try { - ({ checkAndUpdateBackendBinary } = require('../utils/backendUpdater')); - } catch (error) { - logUpdaterWarn('Backend updater module unavailable; skipping backend check', error?.message || String(error)); - backendCheckInFlight = false; - return; - } - - logUpdaterInfo('Running backend binary update check'); - lastBackendStatus = { type: 'backend-checking-for-update', at: Date.now() }; - sendUpdaterEvent({ type: 'backend-checking-for-update' }); - - checkAndUpdateBackendBinary({ - log: (message, meta) => logUpdaterInfo(`[BackendUpdater] ${message}`, meta) - }) - .then((result) => { - if (!result?.success) { - const message = result?.error || 'Unknown backend updater failure'; - logUpdaterWarn('Backend binary update check failed', { message }); - lastBackendStatus = { type: 'backend-error', message, at: Date.now() }; - sendUpdaterEvent({ type: 'backend-error', message }); - return; - } - - if (result.updated) { - logUpdaterInfo('Backend binary updated successfully', result); - lastBackendStatus = { type: 'backend-update-installed', info: result, at: Date.now() }; - sendUpdaterEvent({ type: 'backend-update-installed', info: result }); - - // Restart the ctrace server so the new binary is picked up immediately. - // If the server hasn't started yet this is a no-op (shutdownServer skips if not running). - try { - const { shutdownServer } = require('../utils/ctraceServeClient'); - shutdownServer().catch(() => {}); - } catch (_) {} - return; - } - - logUpdaterInfo('Backend binary already up to date', result); - lastBackendStatus = { type: 'backend-update-not-available', info: result, at: Date.now() }; - sendUpdaterEvent({ type: 'backend-update-not-available', info: result }); - }) - .catch((error) => { - const message = error?.message || String(error); - logUpdaterWarn('Backend binary update check exception', message); - lastBackendStatus = { type: 'backend-error', message, at: Date.now() }; - sendUpdaterEvent({ type: 'backend-error', message }); - }) - .finally(() => { - backendCheckInFlight = false; - }); - }; - - // Backend binary checks should run on startup and periodically in all modes. - runBackendCheck(); - - const backendInterval = setInterval(() => { - runBackendCheck(); - }, UPDATE_CHECK_INTERVAL_MS); - - if (typeof backendInterval.unref === 'function') { - backendInterval.unref(); - } - - if (!app.isPackaged) { - logUpdaterInfo('Skipping app updater check in development mode'); - logUpdaterInfo('Backend updater scheduled', { - startup: 'immediate', - intervalMs: UPDATE_CHECK_INTERVAL_MS - }); - return; - } - - const runUpdateCheck = () => { - logUpdaterInfo('Running update check'); - autoUpdater.checkForUpdates().catch((error) => { - logUpdaterWarn('Update check failed', error?.message || String(error)); - }); - }; - - setTimeout(() => { - runUpdateCheck(); - }, 5000); - - const appInterval = setInterval(() => { - runUpdateCheck(); - }, UPDATE_CHECK_INTERVAL_MS); - - logUpdaterInfo('Updater schedules active', { - backendStartup: 'immediate', - backendIntervalMs: UPDATE_CHECK_INTERVAL_MS, - appStartupDelayMs: 5000, - intervalMs: UPDATE_CHECK_INTERVAL_MS - }); - - if (typeof appInterval.unref === 'function') { - appInterval.unref(); - } -} - -module.exports = { - setupUpdaterHandlers, - setupAutoUpdater -}; diff --git a/src/main/utils/backendUpdater.js b/src/main/utils/backendUpdater.js deleted file mode 100644 index d16072f..0000000 --- a/src/main/utils/backendUpdater.js +++ /dev/null @@ -1,498 +0,0 @@ -const crypto = require('crypto'); -const fs = require('fs/promises'); -const https = require('https'); -const path = require('path'); -const tar = require('tar'); - -const { app } = require('electron'); -const { resolveBinaryPath } = require('./ctraceServeClient'); - -const CORETRACE_REPO_API_LATEST = 'https://api.github.com/repos/CoreTrace/coretrace/releases/latest'; -const REQUEST_TIMEOUT_MS = 30000; - -// Release metadata and assets are only ever fetched from GitHub. Redirects -// (asset downloads bounce to *.githubusercontent.com) are checked against the -// same list so a poisoned Location header cannot send us elsewhere. -const ALLOWED_HOSTS = ['github.com', 'api.github.com']; -const ALLOWED_HOST_SUFFIXES = ['.githubusercontent.com']; -const MAX_JSON_BYTES = 5 * 1024 * 1024; -const MAX_TEXT_BYTES = 64 * 1024; -const MAX_ARCHIVE_BYTES = 512 * 1024 * 1024; - -function assertAllowedUrl(url) { - const parsed = new URL(String(url)); - const host = parsed.hostname.toLowerCase(); - const allowed = parsed.protocol === 'https:' && ( - ALLOWED_HOSTS.includes(host) || ALLOWED_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix)) - ); - if (!allowed) { - throw new Error(`Refusing to fetch backend update from untrusted URL: ${parsed.origin}`); - } - return parsed; -} - -function getUserDataPath() { - if (!app || typeof app.getPath !== 'function') return null; - try { - return app.getPath('userData'); - } catch (_) { - return null; - } -} - -function getManagedBinaryPath() { - const userDataPath = getUserDataPath(); - if (!userDataPath) return null; - return path.join(userDataPath, 'bin', 'ctrace'); -} - -function getManagedLibPath() { - const userDataPath = getUserDataPath(); - if (!userDataPath) return null; - return path.join(userDataPath, 'lib'); -} - -function getBackendStatePath() { - const userDataPath = getUserDataPath(); - if (!userDataPath) return null; - return path.join(userDataPath, 'backend-updater-state.json'); -} - -function getTargetPlatformForBackend() { - if (process.platform === 'win32') return 'linux'; - if (process.platform === 'linux') return 'linux'; - return null; -} - -function getTargetArchTag() { - if (process.arch === 'x64') return 'amd64'; - if (process.arch === 'arm64') return 'arm64'; - return null; -} - -function parseSha256Text(text) { - const match = String(text || '').match(/([a-fA-F0-9]{64})/); - return match ? match[1].toLowerCase() : null; -} - -async function sha256File(filePath) { - const buf = await fs.readFile(filePath); - return crypto.createHash('sha256').update(buf).digest('hex'); -} - -function requestUrl(url, { method = 'GET', headers = {}, timeoutMs = REQUEST_TIMEOUT_MS, maxRedirects = 5, maxBytes = MAX_JSON_BYTES } = {}) { - return new Promise((resolve, reject) => { - try { - assertAllowedUrl(url); - } catch (error) { - reject(error); - return; - } - const appVersion = app && typeof app.getVersion === 'function' ? app.getVersion() : '0.0.0'; - const req = https.request(url, { - method, - headers: { - 'User-Agent': `coretrace-gui/${appVersion}`, - Accept: 'application/vnd.github+json', - ...headers - } - }, (res) => { - const statusCode = res.statusCode || 0; - const location = res.headers.location; - - if (statusCode >= 300 && statusCode < 400 && location && maxRedirects > 0) { - res.resume(); - requestUrl(new URL(location, url).toString(), { method, headers, timeoutMs, maxRedirects: maxRedirects - 1, maxBytes }) - .then(resolve) - .catch(reject); - return; - } - - const chunks = []; - let received = 0; - res.on('data', (c) => { - received += c.length; - if (received > maxBytes) { - req.destroy(new Error(`Response from ${url} exceeded ${maxBytes} bytes`)); - return; - } - chunks.push(c); - }); - res.on('end', () => { - resolve({ - statusCode, - headers: res.headers, - body: Buffer.concat(chunks) - }); - }); - }); - - req.on('error', reject); - req.setTimeout(timeoutMs, () => { - req.destroy(new Error(`Request timeout for ${url}`)); - }); - req.end(); - }); -} - -async function fetchJson(url) { - const res = await requestUrl(url, { headers: { Accept: 'application/vnd.github+json' }, maxBytes: MAX_JSON_BYTES }); - if (res.statusCode < 200 || res.statusCode >= 300) { - const body = res.body ? res.body.toString('utf8') : ''; - throw new Error(`HTTP ${res.statusCode} fetching JSON from ${url}: ${body.slice(0, 200)}`); - } - return JSON.parse(res.body.toString('utf8')); -} - -async function fetchText(url) { - const res = await requestUrl(url, { headers: { Accept: 'text/plain,*/*' }, maxBytes: MAX_TEXT_BYTES }); - if (res.statusCode < 200 || res.statusCode >= 300) { - const body = res.body ? res.body.toString('utf8') : ''; - throw new Error(`HTTP ${res.statusCode} fetching text from ${url}: ${body.slice(0, 200)}`); - } - return res.body.toString('utf8'); -} - -async function downloadToFile(url, targetPath) { - const res = await requestUrl(url, { headers: { Accept: 'application/octet-stream,*/*' }, maxBytes: MAX_ARCHIVE_BYTES }); - if (res.statusCode < 200 || res.statusCode >= 300) { - const body = res.body ? res.body.toString('utf8') : ''; - throw new Error(`HTTP ${res.statusCode} downloading ${url}: ${body.slice(0, 200)}`); - } - await fs.writeFile(targetPath, res.body); -} - -async function readBackendUpdaterState() { - const statePath = getBackendStatePath(); - if (!statePath) return null; - try { - const raw = await fs.readFile(statePath, 'utf8'); - return JSON.parse(raw); - } catch (_) { - return null; - } -} - -async function writeBackendUpdaterState(state) { - const statePath = getBackendStatePath(); - if (!statePath) return; - await fs.mkdir(path.dirname(statePath), { recursive: true }); - await fs.writeFile(statePath, JSON.stringify(state, null, 2), 'utf8'); -} - -async function fileExists(filePath) { - try { - await fs.access(filePath); - return true; - } catch (_) { - return false; - } -} - -async function findFileRecursive(rootDir, name) { - const entries = await fs.readdir(rootDir, { withFileTypes: true }); - for (const entry of entries) { - const fullPath = path.join(rootDir, entry.name); - if (entry.isFile() && entry.name === name) return fullPath; - if (entry.isDirectory()) { - const found = await findFileRecursive(fullPath, name); - if (found) return found; - } - } - return null; -} - -function pickAssets(release, platformTag, archTag) { - const assets = Array.isArray(release?.assets) ? release.assets : []; - // Allow semver prerelease/build metadata in filenames (e.g. v0.74.0-dev.40+gda3218e). - const baseNameRegex = new RegExp(`^coretrace-v[0-9A-Za-z._+-]+-${platformTag}-${archTag}\\.tar\\.gz$`); - const tarAsset = assets.find((a) => baseNameRegex.test(a.name || '')) || null; - const shaAsset = tarAsset - ? assets.find((a) => a.name === `${tarAsset.name}.sha256`) || null - : null; - - return { tarAsset, shaAsset }; -} - -async function installBinary(extractedBinaryPath, targetBinaryPath) { - await fs.mkdir(path.dirname(targetBinaryPath), { recursive: true }); - - const tempTargetPath = `${targetBinaryPath}.tmp`; - await fs.copyFile(extractedBinaryPath, tempTargetPath); - - if (process.platform !== 'win32') { - await fs.chmod(tempTargetPath, 0o755); - } - - try { - await fs.rename(tempTargetPath, targetBinaryPath); - } catch (error) { - if (error && error.code === 'EEXIST') { - await fs.unlink(targetBinaryPath).catch(() => {}); - await fs.rename(tempTargetPath, targetBinaryPath); - return; - } - - if (error && (error.code === 'EPERM' || error.code === 'EBUSY')) { - await fs.unlink(targetBinaryPath).catch(() => {}); - await fs.rename(tempTargetPath, targetBinaryPath); - return; - } - - throw error; - } -} - -async function installDirectory(sourceDir, targetDir) { - await fs.rm(targetDir, { recursive: true, force: true }).catch(() => {}); - await fs.mkdir(path.dirname(targetDir), { recursive: true }); - await fs.cp(sourceDir, targetDir, { - recursive: true, - // Runtime archives use symlinked SONAME entries like libedit.so.2 -> libedit.so.2.0.72. - // Preserve the actual files at install time so the installed tree does not contain - // links back into the temporary extraction directory that is deleted after install. - dereference: true - }); -} - -async function findRuntimeLibDir(rootDir) { - const entries = await fs.readdir(rootDir, { withFileTypes: true }); - - for (const entry of entries) { - const fullPath = path.join(rootDir, entry.name); - if (!entry.isDirectory()) continue; - - if (/^lib(?:64)?$/i.test(entry.name)) { - const nestedEntries = await fs.readdir(fullPath, { withFileTypes: true }); - const hasSharedLibs = nestedEntries.some((nested) => ( - nested.isFile() && - /\.so(?:\.[0-9]+)*$/.test(nested.name) - )); - if (hasSharedLibs) return fullPath; - } - - const nestedFound = await findRuntimeLibDir(fullPath); - if (nestedFound) return nestedFound; - } - - return null; -} - -async function isRuntimeLibDirHealthy(libDir) { - try { - const entries = await fs.readdir(libDir, { withFileTypes: true }); - if (!entries.length) return false; - - for (const entry of entries) { - const fullPath = path.join(libDir, entry.name); - try { - await fs.stat(fullPath); - } catch (_) { - return false; - } - } - - return entries.some((entry) => /^libedit\.so\.2(?:\..*)?$/.test(entry.name)); - } catch (_) { - return false; - } -} - -async function checkAndUpdateBackendBinary({ log = () => {}, force = false } = {}) { - const platformTag = getTargetPlatformForBackend(); - const archTag = getTargetArchTag(); - const userDataPath = getUserDataPath(); - const managedBinaryPath = getManagedBinaryPath(); - const managedLibPath = getManagedLibPath(); - const state = await readBackendUpdaterState(); - - if (!platformTag || !archTag) { - return { - success: true, - skipped: true, - reason: `Unsupported platform/arch for backend updater: ${process.platform}/${process.arch}` - }; - } - - if (!userDataPath || !managedBinaryPath || !managedLibPath) { - return { - success: true, - skipped: true, - reason: 'Electron userData path is unavailable in current runtime' - }; - } - - let release; - let releaseTag = null; - try { - release = await fetchJson(CORETRACE_REPO_API_LATEST); - releaseTag = release?.tag_name || 'unknown'; - } catch (error) { - const cachedReleaseTag = typeof state?.releaseTag === 'string' && state.releaseTag.trim() - ? state.releaseTag.trim() - : null; - - if (cachedReleaseTag) { - log('Using cached backend release tag after fetch failure', { - cachedReleaseTag, - error: error?.message || String(error) - }); - return { - success: true, - updated: false, - releaseTag: cachedReleaseTag, - stale: true, - reason: 'Using cached backend release tag after release metadata fetch failed' - }; - } - - throw error; - } - - const { tarAsset, shaAsset } = pickAssets(release, platformTag, archTag); - if (!tarAsset || !shaAsset) { - return { - success: true, - skipped: true, - reason: `No matching backend assets for ${platformTag}-${archTag} in release ${releaseTag}` - }; - } - - const currentBinaryPath = resolveBinaryPath(); - let currentBinarySha = null; - if (await fileExists(currentBinaryPath)) { - currentBinarySha = await sha256File(currentBinaryPath); - } - const runtimeLibsHealthy = await isRuntimeLibDirHealthy(managedLibPath); - - if ( - !force && - state && - state.releaseTag === releaseTag && - state.arch === archTag && - state.platform === platformTag && - state.binarySha256 && - state.binarySha256 === currentBinarySha && - runtimeLibsHealthy - ) { - return { - success: true, - updated: false, - releaseTag, - reason: 'Backend already up to date (state + checksum match)' - }; - } - - const tmpRoot = path.join(userDataPath, 'backend-updater-tmp'); - const runDir = path.join(tmpRoot, `${Date.now()}-${process.pid}`); - const archivePath = path.join(runDir, tarAsset.name); - const extractDir = path.join(runDir, 'extract'); - - await fs.mkdir(extractDir, { recursive: true }); - - try { - log('Downloading backend checksum file', { name: shaAsset.name, tag: releaseTag }); - const shaText = await fetchText(shaAsset.browser_download_url); - const expectedArchiveSha = parseSha256Text(shaText); - if (!expectedArchiveSha) { - throw new Error(`Could not parse sha256 from asset ${shaAsset.name}`); - } - - log('Downloading backend archive', { name: tarAsset.name, tag: releaseTag }); - await downloadToFile(tarAsset.browser_download_url, archivePath); - - const downloadedArchiveSha = await sha256File(archivePath); - if (downloadedArchiveSha !== expectedArchiveSha) { - throw new Error( - `Checksum mismatch for ${tarAsset.name}: expected ${expectedArchiveSha}, got ${downloadedArchiveSha}` - ); - } - - log('Extracting backend archive', { archivePath }); - await tar.x({ - file: archivePath, - cwd: extractDir, - strict: true, - // On Windows, symlink creation requires admin privileges or Developer Mode. - // The archive contains Linux shared-library symlinks that aren't needed for - // the binary copy, so skip them to avoid EPERM failures. - filter: process.platform === 'win32' - ? (_path, entry) => entry.type !== 'SymbolicLink' - : undefined - }); - - const extractedBinaryPath = await findFileRecursive(extractDir, 'ctrace'); - if (!extractedBinaryPath) { - throw new Error(`Could not locate ctrace binary inside ${tarAsset.name}`); - } - const extractedLibDir = await findRuntimeLibDir(extractDir); - - const downloadedBinarySha = await sha256File(extractedBinaryPath); - - if (currentBinarySha && currentBinarySha === downloadedBinarySha && runtimeLibsHealthy) { - await writeBackendUpdaterState({ - releaseTag, - platform: platformTag, - arch: archTag, - binarySha256: downloadedBinarySha, - assetName: tarAsset.name, - checkedAt: new Date().toISOString() - }); - return { - success: true, - updated: false, - releaseTag, - reason: 'Current binary checksum matches release binary checksum' - }; - } - - log('Installing backend binary', { - from: extractedBinaryPath, - to: managedBinaryPath - }); - await installBinary(extractedBinaryPath, managedBinaryPath); - - if (extractedLibDir) { - log('Installing backend runtime libraries', { - from: extractedLibDir, - to: managedLibPath - }); - await installDirectory(extractedLibDir, managedLibPath); - } else { - log('Backend archive did not include a runtime library directory', { - archive: tarAsset.name - }); - } - - const installedBinarySha = await sha256File(managedBinaryPath); - if (installedBinarySha !== downloadedBinarySha) { - throw new Error('Installed binary checksum verification failed'); - } - - await writeBackendUpdaterState({ - releaseTag, - platform: platformTag, - arch: archTag, - binarySha256: installedBinarySha, - assetName: tarAsset.name, - checkedAt: new Date().toISOString(), - installedAt: new Date().toISOString() - }); - - return { - success: true, - updated: true, - releaseTag, - binaryPath: managedBinaryPath, - binarySha256: installedBinarySha, - assetName: tarAsset.name - }; - } finally { - fs.rm(runDir, { recursive: true, force: true }).catch(() => {}); - } -} - -module.exports = { - checkAndUpdateBackendBinary, - getManagedBinaryPath -}; diff --git a/src/main/utils/ctraceServeClient.js b/src/main/utils/ctraceServeClient.js deleted file mode 100644 index ed28ce8..0000000 --- a/src/main/utils/ctraceServeClient.js +++ /dev/null @@ -1,546 +0,0 @@ -const { spawn } = require('child_process'); -const crypto = require('crypto'); -const fsSync = require('fs'); -const fs = require('fs/promises'); -const http = require('http'); -const net = require('net'); -const os = require('os'); -const path = require('path'); - -const DEFAULT_HOST = '127.0.0.1'; -const DEFAULT_PORT = 8080; -const DEBUG_BACKEND_REQUESTS = process.env.CTRACE_GUI_DEBUG_BACKEND === '1' || process.env.NODE_ENV === 'development'; - -/** - * @typedef {Object} CtraceServerInfo - * @property {string} host - * @property {number} port - * @property {string} token - */ - -let serverProc = null; -/** @type {CtraceServerInfo|null} */ -let serverInfo = null; -let startingPromise = null; - -let requestIdSeq = 0; - -/** - * Captured outputs from the server process. - * We use this to surface diagnostics that the server prints to stdout - * but does not always include in the HTTP response (e.g. some tool outputs). - */ -const captured = { - /** @type {Array<{ ts: number, json: any }>} */ - json: [], - /** @type {Array<{ ts: number, stream: 'stdout'|'stderr', text: string }>} */ - text: [] -}; - -let parseBuffer = ''; - -// Upper bound for buffered, not-yet-parsed backend output. Anything beyond it -// is discarded from the front so a chatty or broken backend cannot grow memory -// without limit. -const PARSE_BUFFER_MAX_CHARS = 4 * 1024 * 1024; - -function trimCaptured(maxAgeMs = 5 * 60 * 1000) { - const cutoff = Date.now() - maxAgeMs; - captured.json = captured.json.filter(m => m.ts >= cutoff); - captured.text = captured.text.filter(m => m.ts >= cutoff); -} - -function tryExtractJsonMessagesFromBuffer() { - // Streaming JSON extraction using brace/bracket balancing with string handling. - // This is intentionally tolerant; malformed chunks are ignored. - const messages = []; - let i = 0; - - while (i < parseBuffer.length) { - // Find start of a JSON value. - const startObj = parseBuffer.indexOf('{', i); - const startArr = parseBuffer.indexOf('[', i); - let start; - let opening; - - if (startObj === -1 && startArr === -1) break; - if (startObj === -1) { - start = startArr; - opening = '['; - } else if (startArr === -1) { - start = startObj; - opening = '{'; - } else if (startObj < startArr) { - start = startObj; - opening = '{'; - } else { - start = startArr; - opening = '['; - } - - let depth = 0; - let inString = false; - let escaped = false; - let end = -1; - - for (let j = start; j < parseBuffer.length; j++) { - const ch = parseBuffer[j]; - - if (inString) { - if (escaped) { - escaped = false; - continue; - } - if (ch === '\\') { - escaped = true; - continue; - } - if (ch === '"') { - inString = false; - } - continue; - } - - if (ch === '"') { - inString = true; - continue; - } - - if (ch === '{' || ch === '[') { - depth++; - continue; - } - if (ch === '}' || ch === ']') { - depth--; - if (depth === 0) { - end = j + 1; - break; - } - } - } - - if (end === -1) { - // Need more data. - break; - } - - const candidate = parseBuffer.slice(start, end); - try { - const parsed = JSON.parse(candidate); - messages.push(parsed); - // Remove everything up to end to avoid quadratic scans. - parseBuffer = parseBuffer.slice(end); - i = 0; - } catch (_) { - // If it looked like JSON but didn't parse, advance one char. - i = start + 1; - } - } - - return messages; -} - -function captureChunk(chunk, stream) { - const ts = Date.now(); - const text = String(chunk || ''); - - // Keep raw text (for tool execution failures, missing files, etc.) - if (text.trim()) { - captured.text.push({ ts, stream, text }); - } - - // Feed JSON extractor. - parseBuffer += text; - if (parseBuffer.length > PARSE_BUFFER_MAX_CHARS) { - parseBuffer = parseBuffer.slice(parseBuffer.length - PARSE_BUFFER_MAX_CHARS); - } - const msgs = tryExtractJsonMessagesFromBuffer(); - for (const m of msgs) { - captured.json.push({ ts: Date.now(), json: m }); - } - - trimCaptured(); -} - -function getCapturedSince(ts) { - trimCaptured(); - return { - json: captured.json.filter(m => m.ts >= ts).map(m => m.json), - text: captured.text.filter(m => m.ts >= ts).map(m => m.text) - }; -} - -async function waitForCapturedJson(predicate, { sinceTs, timeoutMs = 30000, pollMs = 200 } = {}) { - const start = Date.now(); - const since = sinceTs ?? start; - - while (Date.now() - start < timeoutMs) { - const { json } = getCapturedSince(since); - const found = json.find(predicate); - if (found) return found; - await new Promise(r => setTimeout(r, pollMs)); - } - return null; -} - -/** - * Binary file names to look for, most specific first. macOS needs a native - * Mach-O build: the `ctrace` shipped in extraResources is a Linux ELF, so an - * arch-suffixed name is preferred there and the plain name is only a fallback. - * @returns {string[]} - */ -function binaryNameCandidates() { - if (os.platform() === 'darwin') { - return [`ctrace-darwin-${process.arch}`, 'ctrace-darwin', 'ctrace']; - } - return ['ctrace']; -} - -/** - * Directories that may hold the binary, in priority order: the user-managed - * copy first (that is where the backend updater writes), then the packaged - * resources, then the development checkout. - * @returns {string[]} - */ -function binaryDirCandidates() { - const dirs = []; - - try { - const electronModule = require('electron'); - const electronApp = electronModule && electronModule.app; - if (electronApp && typeof electronApp.getPath === 'function') { - dirs.push(path.join(electronApp.getPath('userData'), 'bin')); - } - } catch (_) { - // Ignore; fallback to packaged/development binary path. - } - - if (process.resourcesPath) { - dirs.push(path.join(process.resourcesPath, 'bin')); - } - - dirs.push(path.join(__dirname, '../../../bin')); - - return dirs; -} - -function resolveBinaryPath() { - const dirs = binaryDirCandidates(); - const names = binaryNameCandidates(); - - for (const dir of dirs) { - for (const name of names) { - const candidate = path.join(dir, name); - if (fsSync.existsSync(candidate)) { - return candidate; - } - } - } - - // Nothing exists yet: return the packaged path with the default name so the - // caller's "not found" message points at the location we actually expect. - return path.join(dirs[dirs.length - 1], 'ctrace'); -} - -/** - * Check that a binary matches the executable format of the host OS. Only macOS - * is checked, because that is the platform where a Linux ELF can end up - * bundled: running it there fails with an opaque "cannot execute binary file". - * - * @param {string} binPath - * @returns {{ ok: boolean, error?: string }} - */ -function checkBinaryFormat(binPath) { - if (os.platform() !== 'darwin') return { ok: true }; - - let header; - try { - const fd = fsSync.openSync(binPath, 'r'); - try { - header = Buffer.alloc(4); - fsSync.readSync(fd, header, 0, 4, 0); - } finally { - fsSync.closeSync(fd); - } - } catch (e) { - return { ok: false, error: `Cannot read the ctrace binary at ${binPath}: ${e.message}` }; - } - - // 0x7f 'E' 'L' 'F' — a Linux binary, which macOS cannot load. - if (header[0] === 0x7f && header[1] === 0x45 && header[2] === 0x4c && header[3] === 0x46) { - return { - ok: false, - error: - 'The bundled ctrace binary is a Linux executable and cannot run on macOS. ' + - 'Build or download a macOS (Mach-O) ctrace, then select it from File > Backend Settings, ' + - `or place it next to the bundled one as "ctrace-darwin-${process.arch}".` - }; - } - - return { ok: true }; -} - -function toWslPath(winPath) { - return winPath.replace(/\\/g, '/').replace(/^([A-Z]):/, (m, d) => `/mnt/${d.toLowerCase()}`); -} - -function createShutdownToken() { - return crypto.randomBytes(32).toString('hex'); -} - -function waitForPortOpen({ host, port, timeoutMs = 15000 }) { - const start = Date.now(); - - return new Promise((resolve) => { - const tryOnce = () => { - const socket = net.connect({ host, port }); - - const onDone = (ok) => { - socket.removeAllListeners(); - try { socket.destroy(); } catch (_) {} - resolve(ok); - }; - - socket.once('connect', () => onDone(true)); - socket.once('error', () => { - if (Date.now() - start >= timeoutMs) return onDone(false); - setTimeout(tryOnce, 150); - }); - - socket.setTimeout(1000, () => { - try { socket.destroy(); } catch (_) {} - if (Date.now() - start >= timeoutMs) return resolve(false); - setTimeout(tryOnce, 150); - }); - }; - - tryOnce(); - }); -} - -function findAvailablePort(preferredPort = DEFAULT_PORT) { - // First try preferred port. If it's busy, fallback to an ephemeral port. - const tryPort = (port) => new Promise((resolve) => { - const tester = net.createServer(); - tester.once('error', () => resolve(null)); - tester.once('listening', () => { - const actualPort = tester.address().port; - tester.close(() => resolve(actualPort)); - }); - tester.listen(port, DEFAULT_HOST); - }); - - return (async () => { - const preferred = await tryPort(preferredPort); - if (preferred) return preferred; - const ephemeral = await tryPort(0); - return ephemeral || preferredPort; - })(); -} - -function httpPostJson(url, { headers = {}, body, timeoutMs = 300000 } = {}) { - return new Promise((resolve, reject) => { - const parsed = new URL(url); - - const payload = body == null ? '' : JSON.stringify(body); - - const req = http.request({ - protocol: parsed.protocol, - hostname: parsed.hostname, - port: parsed.port, - path: parsed.pathname + parsed.search, - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Content-Length': Buffer.byteLength(payload), - ...headers - } - }, (res) => { - let data = ''; - res.setEncoding('utf8'); - res.on('data', (chunk) => data += chunk); - res.on('end', () => { - resolve({ statusCode: res.statusCode || 0, headers: res.headers, body: data }); - }); - }); - - req.on('error', reject); - req.setTimeout(timeoutMs, () => { - req.destroy(new Error('Request timeout')); - }); - - req.write(payload); - req.end(); - }); -} - -async function ensureServerRunning(options = {}) { - if (serverProc && serverInfo) return serverInfo; - if (startingPromise) return startingPromise; - - startingPromise = (async () => { - const binPath = resolveBinaryPath(); - console.log(`[ctrace] binary path: ${binPath}`); - try { - await fs.access(binPath); - } catch (e) { - throw new Error(`ctrace binary not found at: ${binPath}`); - } - - const format = checkBinaryFormat(binPath); - if (!format.ok) { - throw new Error(format.error); - } - - const host = DEFAULT_HOST; - const port = await findAvailablePort(DEFAULT_PORT); - const token = createShutdownToken(); - - const args = ['--ipc', 'serve', '--serve-host', host, '--serve-port', String(port), '--shutdown-token', token]; - - let proc; - if (os.platform() === 'win32') { - const wslBinPath = toWslPath(binPath); - - const bashEscape = (s) => { - const str = String(s ?? ''); - // Wrap in single quotes and escape embedded single quotes. - return `'${str.replace(/'/g, `'"'"'`)}'`; - }; - - // Default CWD: parent of the binary's containing directory (i.e. parent of bin/). - // This ensures ctrace always runs from the same relative location in both dev - // (coretrace-gui/) and production (resources/) so tool/model path resolution - // inside the binary is consistent regardless of where Electron was launched from. - const defaultCwd = path.dirname(path.dirname(binPath)); - const cwdOverride = options && typeof options.cwd === 'string' ? options.cwd : ''; - const resolvedCwd = cwdOverride || defaultCwd; - const wslCwd = toWslPath(resolvedCwd); - const cmd = `${wslCwd ? `cd ${bashEscape(wslCwd)} && ` : ''}${bashEscape(wslBinPath)} ${args.map(bashEscape).join(' ')}`; - - // Use bash -lc so the environment is closer to interactive WSL runs - // (and so `cd` works regardless of the default directory). - proc = spawn('wsl', ['bash', '-lc', cmd], { stdio: 'pipe', windowsHide: true }); - } else { - // Linux / WSL-launched process: wrap in bash -lc to get a proper login - // environment (PATH, LLVM, etc.) consistent with interactive WSL sessions. - const bashEscapeLinux = (s) => `'${String(s ?? '').replace(/'/g, `'"'"'`)}'`; - const defaultCwdLinux = path.dirname(path.dirname(binPath)); - const cwdLinux = (options && typeof options.cwd === 'string' && options.cwd) || defaultCwdLinux; - const cmd = `${cwdLinux ? `cd ${bashEscapeLinux(cwdLinux)} && ` : ''}${bashEscapeLinux(binPath)} ${args.map(bashEscapeLinux).join(' ')}`; - proc = spawn('bash', ['-lc', cmd], { stdio: 'pipe' }); - } - - proc.stdout.on('data', (d) => { - // Keep logs useful but not too noisy. - const s = d.toString(); - captureChunk(s, 'stdout'); - if (s.trim()) console.log(`[ctrace serve]: ${s.trimEnd()}`); - }); - - proc.stderr.on('data', (d) => { - const s = d.toString(); - captureChunk(s, 'stderr'); - if (s.trim()) console.error(`[ctrace serve stderr]: ${s.trimEnd()}`); - }); - - proc.on('exit', (code, signal) => { - console.log(`ctrace serve exited: code=${code} signal=${signal}`); - serverProc = null; - serverInfo = null; - startingPromise = null; - }); - - const ready = await waitForPortOpen({ host, port, timeoutMs: 20000 }); - if (!ready) { - try { proc.kill('SIGTERM'); } catch (_) {} - throw new Error(`ctrace serve did not open ${host}:${port} in time`); - } - - serverProc = proc; - serverInfo = { host, port, token }; - return serverInfo; - })(); - - try { - return await startingPromise; - } finally { - startingPromise = null; - } -} - -async function callApi(method, params) { - const info = await ensureServerRunning(); - - const request = { - proto: 'coretrace-1.0', - id: ++requestIdSeq, - type: 'request', - method, - params - }; - - const url = `http://${info.host}:${info.port}/api`; - - if (DEBUG_BACKEND_REQUESTS) { - console.log('[ctrace debug] backend url:', url); - console.log('[ctrace debug] backend request:', JSON.stringify(request)); - } - - const res = await httpPostJson(url, { body: request }); - - let parsed; - try { - parsed = JSON.parse(res.body); - } catch (_) { - // If backend responds with plain text, still surface it. - return { ok: res.statusCode >= 200 && res.statusCode < 300, raw: res.body, statusCode: res.statusCode }; - } - - return { ok: res.statusCode >= 200 && res.statusCode < 300, json: parsed, statusCode: res.statusCode }; -} - -async function shutdownServer() { - if (!serverInfo) return { success: true, skipped: true }; - - const { host, port, token } = serverInfo; - - try { - const res = await httpPostJson(`http://${host}:${port}/shutdown`, { - headers: { - Authorization: `Bearer ${token}` - }, - body: {} - }); - - // Regardless of HTTP status, attempt to stop the process too. - if (serverProc && !serverProc.killed) { - try { serverProc.kill('SIGTERM'); } catch (_) {} - } - - serverProc = null; - serverInfo = null; - - return { success: res.statusCode >= 200 && res.statusCode < 300, statusCode: res.statusCode, body: res.body }; - } catch (e) { - // Fall back to killing the process if HTTP shutdown fails. - if (serverProc && !serverProc.killed) { - try { serverProc.kill('SIGTERM'); } catch (_) {} - } - - serverProc = null; - serverInfo = null; - - return { success: false, error: e.message }; - } -} - -module.exports = { - ensureServerRunning, - callApi, - shutdownServer, - resolveBinaryPath, - checkBinaryFormat, - getCapturedSince, - waitForCapturedJson -}; diff --git a/src/main/utils/errorUtils.js b/src/main/utils/errorUtils.js deleted file mode 100644 index 1480d65..0000000 --- a/src/main/utils/errorUtils.js +++ /dev/null @@ -1,133 +0,0 @@ -'use strict'; - -/** - * @fileoverview Shared error formatting utilities for the main process. - * - * Provides contextual, human-readable error messages for file-system operations - * with platform-aware suggestions (Windows vs macOS/Linux). - */ - -const path = require('path'); - -/** - * Error code → description + platform-aware suggestion. - * `suggestion` may be a string or a zero-argument function that returns a string. - */ -const FILE_ERROR_HINTS = { - ENOENT: { - description: 'file or directory not found', - suggestion: 'Check that the path exists and has not been moved or deleted.', - }, - EACCES: { - description: 'permission denied', - suggestion: () => - process.platform === 'win32' - ? 'Try running the application as Administrator.' - : 'Check file permissions (chmod) or try with elevated privileges.', - }, - EPERM: { - description: 'operation not permitted', - suggestion: () => - process.platform === 'win32' - ? 'Try running the application as Administrator.' - : 'Check that you have the necessary permissions for this path.', - }, - EBUSY: { - description: 'file is busy or locked', - suggestion: 'Close any other program that has this file open, then try again.', - }, - EMFILE: { - description: 'too many open files', - suggestion: 'Close some files or restart the application.', - }, - ENOSPC: { - description: 'no space left on device', - suggestion: 'Free up disk space and try again.', - }, - EEXIST: { - description: 'file or directory already exists', - suggestion: 'Choose a different name or remove the existing entry first.', - }, - EISDIR: { - description: 'path is a directory, not a file', - suggestion: 'Provide a file path, not a directory path.', - }, - ENOTDIR: { - description: 'path is not a directory', - suggestion: 'Provide a directory path.', - }, - EROFS: { - description: 'file system is read-only', - suggestion: 'Save the file to a different location.', - }, - ENOTEMPTY: { - description: 'directory is not empty', - suggestion: 'Remove the contents of the directory first, or use a recursive delete.', - }, -}; - -/** - * Format a file-system error into a contextual, user-facing message. - * - * Examples: - * formatFileError(err, '/tmp/foo.txt', 'save') - * → 'Failed to save "/tmp/foo.txt". File is busy or locked. - * Close any other program that has this file open, then try again. (EBUSY)' - * - * @param {Error} err - The original Node.js error. - * @param {string} filePath - The file or directory path involved. - * @param {string} operation - Short verb describing the operation (e.g. 'save', 'read', 'delete'). - * @returns {string} User-facing error message. - */ -function formatFileError(err, filePath, operation) { - const normalizedPath = filePath ? path.normalize(filePath) : null; - const code = err && err.code ? err.code : ''; - const hint = FILE_ERROR_HINTS[code]; - - let msg = `Failed to ${operation}`; - if (normalizedPath) { - msg += ` "${normalizedPath}"`; - } - msg += '.'; - - if (hint) { - const desc = hint.description; - const suggestion = - typeof hint.suggestion === 'function' ? hint.suggestion() : hint.suggestion; - msg += ` ${capitalize(desc)}.`; - if (suggestion) { - msg += ` ${suggestion}`; - } - if (code) { - msg += ` (${code})`; - } - } else if (err) { - msg += ` ${err.message}`; - } - - return msg; -} - -/** - * Returns both a concise user-facing message and a verbose log string. - * Use the `userMessage` for UI notifications and `logMessage` for console output. - * - * @param {Error} err - * @param {string} filePath - * @param {string} operation - * @returns {{ userMessage: string, logMessage: string }} - */ -function formatFileErrorVerbose(err, filePath, operation) { - const userMessage = formatFileError(err, filePath, operation); - const normalizedPath = filePath ? path.normalize(filePath) : ''; - const code = err && err.code ? err.code : 'ERR'; - const logMessage = `[${operation}] "${normalizedPath}": [${code}] ${err ? err.message : 'unknown error'}`; - return { userMessage, logMessage }; -} - -function capitalize(str) { - if (!str) return str; - return str.charAt(0).toUpperCase() + str.slice(1); -} - -module.exports = { formatFileError, formatFileErrorVerbose, FILE_ERROR_HINTS }; diff --git a/src/main/utils/errorUtils.test.js b/src/main/utils/errorUtils.test.js deleted file mode 100644 index 7c0c7d2..0000000 --- a/src/main/utils/errorUtils.test.js +++ /dev/null @@ -1,77 +0,0 @@ -'use strict'; -/** - * Unit tests for errorUtils.formatFileError. - * Run with: node src/main/utils/errorUtils.test.js - * - * No Electron, no IPC, no real file system — tests the formatter in isolation. - * Each case asserts the *specific hint text* for that error code so the test - * cannot pass if hints are removed or the wrong hint fires. - */ - -const { formatFileError } = require('./errorUtils'); - -const FAKE_PATH = process.platform === 'win32' - ? 'C:\\Users\\nihil\\project\\file.txt' - : '/home/nihil/delivery/eip/coretrace-gui/file.txt'; - -// expectedIncludes: substrings that MUST appear in the formatted message. -// At minimum: a snippet of the hint description and the error code. -// Deliberately avoids checking only the path/operation (those are always present). -const cases = [ - { code: 'ENOENT', op: 'read', expectedIncludes: ['not found', 'ENOENT'] }, - { code: 'EACCES', op: 'save', expectedIncludes: ['Permission denied','EACCES'] }, - { code: 'EPERM', op: 'delete', expectedIncludes: ['not permitted', 'EPERM'] }, - { code: 'EBUSY', op: 'save', expectedIncludes: ['busy or locked', 'EBUSY'] }, - { code: 'EEXIST', op: 'create file', expectedIncludes: ['already exists', 'EEXIST'] }, - { code: 'EISDIR', op: 'read', expectedIncludes: ['directory', 'EISDIR'] }, - { code: 'ENOTDIR', op: 'open folder', expectedIncludes: ['not a directory', 'ENOTDIR'] }, - { code: 'EROFS', op: 'save', expectedIncludes: ['read-only', 'EROFS'] }, - { code: 'ENOSPC', op: 'save', expectedIncludes: ['space left', 'ENOSPC'] }, - { code: 'EMFILE', op: 'open', expectedIncludes: ['open files', 'EMFILE'] }, - { code: 'ENOTEMPTY', op: 'delete', expectedIncludes: ['not empty', 'ENOTEMPTY'] }, - // Unknown code: must fall back to the raw error message, not a hint. - { code: 'UNKNOWN', op: 'read', expectedIncludes: ['mock error message for UNKNOWN'] }, -]; - -console.log('=== formatFileError unit tests ===\n'); - -let passed = 0; -let failed = 0; - -for (const { code, op, expectedIncludes } of cases) { - const err = Object.assign(new Error(`mock error message for ${code}`), { code }); - const msg = formatFileError(err, FAKE_PATH, op); - - const missing = expectedIncludes.filter(s => !msg.includes(s)); - const ok = missing.length === 0; - - if (ok) { - console.log(`[PASS] ${code.padEnd(12)} ${op}`); - console.log(` ${msg}\n`); - passed++; - } else { - console.error(`[FAIL] ${code.padEnd(12)} ${op}`); - console.error(` message : ${msg}`); - console.error(` missing : ${missing.join(', ')}\n`); - failed++; - } -} - -// Negative test: verify the test would NOT pass if hints were removed. -// Simulate a formatter that returns only "Failed to read /path. raw message". -{ - const noHintsFormatter = (err, fp, op) => `Failed to ${op} "${fp}". ${err.message}`; - const err = Object.assign(new Error('raw msg'), { code: 'ENOENT' }); - const badMsg = noHintsFormatter(err, FAKE_PATH, 'read'); - const wouldCatch = !badMsg.includes('not found'); - if (wouldCatch) { - console.log('[PASS] Negative check: hint-text assertions would catch a missing hint\n'); - passed++; - } else { - console.error('[FAIL] Negative check: assertions are too weak — would pass without hints\n'); - failed++; - } -} - -console.log(`Results: ${passed} passed, ${failed} failed`); -if (failed > 0) process.exit(1); diff --git a/src/main/utils/fileErrors.test.js b/src/main/utils/fileErrors.test.js deleted file mode 100644 index a832dc9..0000000 --- a/src/main/utils/fileErrors.test.js +++ /dev/null @@ -1,213 +0,0 @@ -'use strict'; -/** - * Integration tests for file-error paths in fileUtils.js. - * Run with: node src/main/utils/fileErrors.test.js - * - * Triggers real OS errors and asserts the formatted message contains both - * the error code AND the relevant hint text — not just the path. - * A test that only checks the path would pass even with all hints removed. - * - * Note: run as a normal user, NOT as root. - * chmod-based tests have no effect when running as root (root bypasses permissions). - */ - -const fs = require('fs').promises; -const path = require('path'); -const os = require('os'); -const { detectFileEncoding, searchInDirectory } = require('./fileUtils'); -const { formatFileError } = require('./errorUtils'); - -let passed = 0; -let failed = 0; - -function assert(label, condition, detail = '') { - if (condition) { - console.log(`[PASS] ${label}`); - passed++; - } else { - console.error(`[FAIL] ${label}${detail ? '\n ' + detail : ''}`); - failed++; - } -} - -async function withTempDir(fn) { - const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'ctrace-err-test-')); - try { - await fn(tmp); - } finally { - await fs.rm(tmp, { recursive: true, force: true }).catch(() => {}); - } -} - -async function run() { - console.log('=== File error integration tests ===\n'); - - if (process.getuid && process.getuid() === 0) { - console.warn('WARNING: running as root — permission tests will be skipped (root bypasses chmod).\n'); - } - - // ── ENOENT: detectFileEncoding on a missing file ────────────────────────── - // detectFileEncoding re-throws the raw OS error (formatting is the caller's job). - // We check .code and that the path appears — not hint text, which lives in errorUtils.test.js. - await (async () => { - const missing = path.join(os.tmpdir(), `nonexistent-${Date.now()}.txt`); - try { - await detectFileEncoding(missing); - assert('ENOENT detectFileEncoding: throws on missing file', false, 'expected throw, got none'); - } catch (err) { - assert('ENOENT detectFileEncoding: raw error has correct code and path', - err.code === 'ENOENT' && - err.message.includes(path.normalize(missing)), - `code=${err.code} message=${err.message}`); - } - })(); - - // ── ENOENT: writeFile to a path inside a missing directory ─────────────── - // Parent dir does not exist → ENOENT. Verifies both code and path are in the message. - await (async () => { - const ghost = path.join(os.tmpdir(), `no-such-dir-${Date.now()}`, 'file.txt'); - try { - await fs.writeFile(ghost, 'data'); - assert('ENOENT writeFile missing parent dir: throws', false, 'expected throw, got none'); - } catch (err) { - const msg = formatFileError(err, ghost, 'save'); - assert('ENOENT writeFile missing parent dir: message contains code + path + hint', - err.code === 'ENOENT' && - msg.includes('ENOENT') && - msg.includes(path.normalize(ghost)) && - msg.includes('not found'), - msg); - } - })(); - - // ── EEXIST: writeFile with exclusive-create flag (wx) ──────────────────── - // Simulates what create-file does in fileHandlers.js. - await withTempDir(async (tmp) => { - const existing = path.join(tmp, 'already.txt'); - await fs.writeFile(existing, 'hello'); - try { - await fs.writeFile(existing, 'world', { flag: 'wx' }); - assert('EEXIST writeFile wx: throws on existing file', false, 'expected throw, got none'); - } catch (err) { - const msg = formatFileError(err, existing, 'create file'); - assert('EEXIST writeFile wx: message contains code + path + hint', - err.code === 'EEXIST' && - msg.includes('EEXIST') && - msg.includes(path.normalize(existing)) && - msg.includes('already exists'), - msg); - } - }); - - // ── EISDIR: readFile on a directory path ───────────────────────────────── - // On Linux/macOS, reading a directory as a file raises EISDIR. - // The message must reflect "directory" — not a generic "permission denied". - await withTempDir(async (tmp) => { - try { - await fs.readFile(tmp, 'utf8'); - assert('EISDIR readFile on directory: throws', false, 'expected throw, got none'); - } catch (err) { - const msg = formatFileError(err, tmp, 'read'); - // Accept EISDIR (Linux) or EBADF (some edge cases) — but NOT EACCES, - // because that would mean the OS returned a permission error instead of a type error - // and the hint would be wrong ("Permission denied" instead of "directory"). - const validCode = err.code === 'EISDIR' || err.code === 'EBADF'; - assert('EISDIR readFile on directory: correct error code', - validCode, - `got ${err.code} — expected EISDIR or EBADF`); - assert('EISDIR readFile on directory: message mentions "directory"', - msg.includes('directory') && msg.includes(path.normalize(tmp)), - msg); - } - }); - - // ── EACCES: read a file with chmod 000 ─────────────────────────────────── - // Tests formatFileError through detectFileEncoding with a real permission error. - // Skipped on Windows (chmod has no effect) and when running as root. - const isRoot = process.getuid && process.getuid() === 0; - if (process.platform !== 'win32' && !isRoot) { - await withTempDir(async (tmp) => { - const locked = path.join(tmp, 'locked.txt'); - await fs.writeFile(locked, 'content'); - await fs.chmod(locked, 0o000); - try { - await detectFileEncoding(locked); - assert('EACCES detectFileEncoding chmod 000: throws', false, 'expected throw, got none'); - } catch (err) { - // Raw OS error — formatting is the caller's responsibility. - assert('EACCES detectFileEncoding chmod 000: raw error has correct code and path', - err.code === 'EACCES' && - err.message.includes(path.normalize(locked)), - `code=${err.code} message=${err.message}`); - } finally { - await fs.chmod(locked, 0o644).catch(() => {}); - } - }); - } else { - console.log(`[SKIP] EACCES chmod 000 — ${isRoot ? 'running as root' : 'Windows'}`); - } - - // ── EACCES: write to a read-only file (chmod 444) ──────────────────────── - // More realistic than chmod 000: file exists and is readable, but not writable. - // This is what happens when a user tries to save a read-only file. - if (process.platform !== 'win32' && !isRoot) { - await withTempDir(async (tmp) => { - const readonly = path.join(tmp, 'readonly.txt'); - await fs.writeFile(readonly, 'original'); - await fs.chmod(readonly, 0o444); // read-only for everyone - try { - await fs.writeFile(readonly, 'modified'); - assert('EACCES writeFile chmod 444: throws', false, 'expected throw, got none'); - } catch (err) { - const msg = formatFileError(err, readonly, 'save'); - assert('EACCES writeFile chmod 444: message contains code + path + hint', - err.code === 'EACCES' && - msg.includes('EACCES') && - msg.includes(path.normalize(readonly)) && - msg.includes('Permission denied'), - msg); - } finally { - await fs.chmod(readonly, 0o644).catch(() => {}); - } - }); - } else { - console.log(`[SKIP] EACCES chmod 444 write — ${isRoot ? 'running as root' : 'Windows'}`); - } - - // ── searchInDirectory: unreadable file is skipped, not thrown ──────────── - // Verifies the function returns partial results and doesn't crash when - // one file in the directory cannot be read. - if (process.platform !== 'win32' && !isRoot) { - await withTempDir(async (tmp) => { - const readable = path.join(tmp, 'readable.txt'); - const unreadable = path.join(tmp, 'unreadable.txt'); - await fs.writeFile(readable, 'hello world'); - await fs.writeFile(unreadable, 'secret content hello'); // also matches "hello" - await fs.chmod(unreadable, 0o000); - - try { - const results = await searchInDirectory(tmp, 'hello'); - // readable.txt must appear, unreadable.txt must NOT (it was skipped) - const hasReadable = results.some(r => r.fileName === 'readable.txt'); - const hasUnreadable = results.some(r => r.fileName === 'unreadable.txt'); - assert('searchInDirectory: readable file appears in results', hasReadable, JSON.stringify(results)); - assert('searchInDirectory: unreadable file is skipped silently', !hasUnreadable, JSON.stringify(results)); - } catch (err) { - assert('searchInDirectory: does not throw on unreadable file', false, err.message); - assert('searchInDirectory: unreadable file is skipped silently', false, err.message); - } finally { - await fs.chmod(unreadable, 0o644).catch(() => {}); - } - }); - } else { - console.log(`[SKIP] searchInDirectory permission test — ${isRoot ? 'running as root' : 'Windows'}`); - } - - console.log(`\nResults: ${passed} passed, ${failed} failed`); - if (failed > 0) process.exit(1); -} - -run().catch(err => { - console.error('Unexpected test runner error:', err); - process.exit(1); -}); diff --git a/src/main/utils/fileUtils.js b/src/main/utils/fileUtils.js deleted file mode 100644 index 126f180..0000000 --- a/src/main/utils/fileUtils.js +++ /dev/null @@ -1,365 +0,0 @@ -const fs = require('fs').promises; -const path = require('path'); - -// File size limit for initial display (1MB) -const FILE_SIZE_LIMIT = 1024 * 1024; - -// Files larger than this threshold trigger a UI warning before opening (5MB) -const LARGE_FILE_THRESHOLD = 5 * 1024 * 1024; - -/** - * Check if file is UTF-8 encoded - * @param {Buffer} buffer - File buffer to check - * @returns {boolean} - True if file is UTF-8 - */ -function isValidUTF8(buffer) { - // If file is empty, consider it UTF-8 - if (buffer.length === 0) { - return true; - } - - // Check for excessive null bytes (binary indicator) - let nullCount = 0; - const sampleSize = Math.min(buffer.length, 1024); // Check first 1KB - - for (let i = 0; i < sampleSize; i++) { - if (buffer[i] === 0) { - nullCount++; - } - } - - // If more than 1% null bytes, likely binary - if (nullCount / sampleSize > 0.01) { - console.log(`Detected binary file: ${nullCount}/${sampleSize} null bytes`); - return false; - } - - // Try to convert to UTF-8 and check for replacement characters - const text = buffer.toString('utf8'); - const replacementCount = (text.match(/\uFFFD/g) || []).length; - - // If more than 1% replacement characters, likely binary/non-UTF8 - if (replacementCount / text.length > 0.01) { - console.log(`Detected non-UTF8: ${replacementCount}/${text.length} replacement chars`); - return false; - } - - // Check for font file signatures - if (text.includes('FFTM') || text.includes('GDEF') || text.includes('glyf') || - text.includes('cmap') || text.includes('fpgm') || text.includes('gasp') || - text.includes('DSIG') || text.includes('GSUB') || text.includes('GPOS')) { - console.log('Detected font file by signature'); - return false; - } - - // Check for high percentage of non-printable characters - let nonPrintableCount = 0; - const checkLength = Math.min(text.length, 1000); - - for (let i = 0; i < checkLength; i++) { - const code = text.charCodeAt(i); - // Count chars that are not printable ASCII, common whitespace, or extended ASCII - if (code < 32 && code !== 9 && code !== 10 && code !== 13) { - nonPrintableCount++; - } - } - - // If more than 10% non-printable characters, likely binary - if (nonPrintableCount / checkLength > 0.1) { - console.log(`Detected binary: ${nonPrintableCount}/${checkLength} non-printable chars`); - return false; - } - - return true; -} - -/** - * Detect file encoding — reads at most FILE_SIZE_LIMIT bytes so large files - * never fully load into memory. - * @param {string} filePath - Path to the file - * @returns {Object} - File info with encoding and size data - */ -async function detectFileEncoding(filePath) { - const stat = await fs.stat(filePath); - const size = stat.size; - - if (size === 0) { - return { isUTF8: true, size: 0, buffer: Buffer.alloc(0) }; - } - - const readSize = Math.min(size, FILE_SIZE_LIMIT); - const fd = await fs.open(filePath, 'r'); - try { - const buffer = Buffer.allocUnsafe(readSize); - const { bytesRead } = await fd.read(buffer, 0, readSize, 0); - const sliced = buffer.slice(0, bytesRead); - const isUTF8 = isValidUTF8(sliced); - console.log(`File: ${filePath}, Size: ${size}, ReadSize: ${readSize}, IsUTF8: ${isUTF8}`); - console.log(`First 100 bytes:`, sliced.slice(0, 100).toString('hex')); - return { isUTF8, size, buffer: sliced }; - } finally { - await fd.close(); - } -} - -const DEFAULT_IGNORED_DIR_NAMES = new Set([ - 'node_modules', - 'dist', - 'build', - 'out', - 'coverage', - '.git', - '.next', - '.cache', - 'target', - 'vendor', - '__pycache__', - '.venv', - 'venv', - 'My Music', - 'My Pictures', - 'My Videos', - '$RECYCLE.BIN', - 'System Volume Information' -]); - -const MAX_ENTRIES_PER_DIR = 5000; - -function shouldIgnoreTreeEntry(name) { - if (!name) return true; - if (name.startsWith('.')) return true; - return DEFAULT_IGNORED_DIR_NAMES.has(name); -} - -/** - * Build file tree for directory. - * - * `loadChildren` supports two modes: - * - boolean: `true` loads one level of directory children, `false` keeps children lazy (`null`) - * - number: max depth to recursively load (0 = current level only) - * - * @param {string} dirPath - Directory path - * @param {boolean|number} loadChildren - Child loading mode or depth - * @returns {Array} - File tree structure - */ -async function buildFileTree(dirPath, loadChildren = true) { - try { - const dirents = await fs.readdir(dirPath, { withFileTypes: true }); - const tree = []; - - let processedCount = 0; - - for (const dirent of dirents) { - if (processedCount >= MAX_ENTRIES_PER_DIR) break; - const name = dirent.name; - - if (shouldIgnoreTreeEntry(name)) { - continue; - } - - // Avoid potential symlink loops and reduce I/O. - if (dirent.isSymbolicLink && dirent.isSymbolicLink()) { - continue; - } - - processedCount++; - const itemPath = path.join(dirPath, name); - - if (dirent.isDirectory()) { - let children = null; - - // Backward compatibility: callers may pass a numeric depth. - if (typeof loadChildren === 'number') { - if (loadChildren > 0) { - children = await buildFileTree(itemPath, loadChildren - 1); - } - } else if (loadChildren === true) { - // Boolean true loads one level only. - children = await buildFileTree(itemPath, false); - } - - tree.push({ - name, - path: itemPath, - type: 'directory', - hasChildren: true, // Mark that it has potential children - children // `null` means lazily loaded - }); - } else if (dirent.isFile()) { - tree.push({ - name, - path: itemPath, - type: 'file' - }); - } - } - - tree.sort((a, b) => { - // Directories first, then files - if (a.type === 'directory' && b.type === 'file') return -1; - if (a.type === 'file' && b.type === 'directory') return 1; - return a.name.localeCompare(b.name); - }); - - return tree; - } catch (error) { - if (error.code === 'EPERM' || error.code === 'EACCES') { - console.warn(`[buildFileTree] Permission denied (${error.code}) reading directory: "${path.normalize(dirPath)}"`); - return []; - } - console.error(`[buildFileTree] Failed to read directory "${path.normalize(dirPath)}": [${error.code || 'ERR'}] ${error.message}`); - return []; - } -} - -/** - * Escape a string so it matches itself inside a RegExp. - * @param {string} text - * @returns {string} - */ -function escapeRegExp(text) { - return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); -} - -/** - * Search in files within directory - * @param {string} dirPath - Directory path to search - * @param {string} searchTerm - Search term - * @param {number} maxResults - Maximum results to return - * @returns {Array} - Search results - */ -async function searchInDirectory(dirPath, searchTerm, maxResults = 100) { - const results = []; - // The term is matched literally: a crafted pattern must not be able to stall - // the main process (catastrophic backtracking) or throw on bad syntax. - const searchRegex = new RegExp(escapeRegExp(String(searchTerm || '')), 'gi'); - - async function searchRecursively(currentPath, depth = 0) { - if (depth > 5 || results.length >= maxResults) return; - - try { - const items = await fs.readdir(currentPath); - - for (const item of items) { - if (results.length >= maxResults) break; - - // Skip hidden files and common build directories - if (item.startsWith('.') || ['node_modules', 'dist', 'build', '.git'].includes(item)) { - continue; - } - - const itemPath = path.join(currentPath, item); - const stats = await fs.stat(itemPath); - - if (stats.isDirectory()) { - await searchRecursively(itemPath, depth + 1); - } else if (stats.isFile()) { - // Skip known binary extensions immediately (fast path) - const ext = path.extname(item).toLowerCase(); - const binaryExtensions = new Set([ - '.png', '.jpg', '.jpeg', '.gif', '.bmp', '.ico', '.webp', '.svg', - '.pdf', '.zip', '.tar', '.gz', '.bz2', '.xz', '.7z', '.rar', - '.exe', '.dll', '.so', '.dylib', '.bin', '.obj', '.o', '.a', - '.wasm', '.class', '.jar', '.war', '.ear', - '.mp3', '.mp4', '.wav', '.ogg', '.flac', '.mkv', '.avi', '.mov', - '.ttf', '.otf', '.woff', '.woff2', '.eot', - '.db', '.sqlite', '.sqlite3', - '.pyc', '.pyo', - '.node' - ]); - - if (binaryExtensions.has(ext)) continue; - - try { - // Binary detection: sample the first 1 KB before reading the whole file - const fd = await fs.open(itemPath, 'r'); - const sampleBuf = Buffer.alloc(1024); - const { bytesRead } = await fd.read(sampleBuf, 0, 1024, 0); - await fd.close(); - if (bytesRead > 0 && !isValidUTF8(sampleBuf.slice(0, bytesRead))) { - continue; // binary file — skip - } - } catch { - continue; // can't sample — skip - } - - try { - const content = await fs.readFile(itemPath, 'utf8'); - const lines = content.split('\n'); - - lines.forEach((line, lineNumber) => { - const matches = line.match(searchRegex); - if (matches) { - results.push({ - file: itemPath, - fileName: item, - line: lineNumber + 1, - content: line.trim(), - matches: matches.length - }); - } - }); - } catch (error) { - // Skip files that can't be read as text (binary, locked, permission-denied, etc.) - console.warn(`[searchInDirectory] Skipping unreadable file "${path.normalize(itemPath)}": [${error.code || 'ERR'}] ${error.message}`); - } - } - } - } catch (error) { - console.error(`[searchInDirectory] Failed to read directory "${path.normalize(currentPath)}": [${error.code || 'ERR'}] ${error.message}`); - } - } - - await searchRecursively(dirPath); - return results; -} - -/** - * Validates that a path is contained within the given workspace directory. - * - * Both paths are resolved to their absolute, normalized forms before comparison - * to neutralize path traversal sequences (".."), mixed separators, and - * URL-encoded characters that could be used to escape the workspace root. - * - * @param {string} targetPath - The path to validate (may be relative or contain ".."). - * @param {string} workspacePath - The workspace root that targetPath must reside within. - * @returns {{ valid: boolean, resolvedPath: string }} Whether the path is safe and its resolved absolute form. - */ -function validatePathInWorkspace(targetPath, workspacePath) { - if (!targetPath || typeof targetPath !== 'string') { - return { valid: false, resolvedPath: '' }; - } - if (!workspacePath || typeof workspacePath !== 'string') { - return { valid: false, resolvedPath: '' }; - } - - const resolvedTarget = path.resolve(targetPath); - const resolvedWorkspace = path.resolve(workspacePath); - - // Append the platform separator to prevent prefix-collision attacks where a - // directory name is a strict prefix of another (e.g. /workspace vs /workspace-extra). - const workspacePrefix = resolvedWorkspace.endsWith(path.sep) - ? resolvedWorkspace - : resolvedWorkspace + path.sep; - - // NTFS (Windows) paths are case-insensitive; normalise before comparing. - const norm = process.platform === 'win32' - ? (p) => p.toLowerCase() - : (p) => p; - - const valid = - norm(resolvedTarget) === norm(resolvedWorkspace) || - norm(resolvedTarget).startsWith(norm(workspacePrefix)); - - return { valid, resolvedPath: resolvedTarget }; -} - -module.exports = { - detectFileEncoding, - buildFileTree, - searchInDirectory, - isValidUTF8, - validatePathInWorkspace, - FILE_SIZE_LIMIT, - LARGE_FILE_THRESHOLD -}; \ No newline at end of file diff --git a/src/main/utils/workspaceTrust.js b/src/main/utils/workspaceTrust.js deleted file mode 100644 index 7f9edb8..0000000 --- a/src/main/utils/workspaceTrust.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @fileoverview Registry of filesystem locations the renderer may act on. - * - * Paths enter this registry only from main-process sources: native file - * dialogs and the persisted session state. The renderer can ask to read, - * write, watch or delete a path, but it cannot introduce a new one on its own. - */ - -const path = require('path'); - -const trustedRoots = new Set(); -const trustedFiles = new Set(); - -/** - * Canonical comparison key for a path (resolved, case-folded on Windows). - * @param {string} targetPath - * @returns {string} - */ -function pathKey(targetPath) { - const resolved = path.resolve(targetPath); - return process.platform === 'win32' ? resolved.toLowerCase() : resolved; -} - -function isNonEmptyString(value) { - return typeof value === 'string' && value.length > 0; -} - -/** Mark a directory as an allowed workspace root. */ -function trustWorkspaceRoot(folderPath) { - if (isNonEmptyString(folderPath)) trustedRoots.add(pathKey(folderPath)); -} - -/** Mark a single file as allowed even when it lies outside the workspace. */ -function trustFile(filePath) { - if (isNonEmptyString(filePath)) trustedFiles.add(pathKey(filePath)); -} - -function isTrustedWorkspaceRoot(folderPath) { - return isNonEmptyString(folderPath) && trustedRoots.has(pathKey(folderPath)); -} - -function isTrustedFile(filePath) { - return isNonEmptyString(filePath) && trustedFiles.has(pathKey(filePath)); -} - -/** True when both paths refer to the same location. */ -function isSamePath(a, b) { - return isNonEmptyString(a) && isNonEmptyString(b) && pathKey(a) === pathKey(b); -} - -module.exports = { - trustWorkspaceRoot, - trustFile, - isTrustedWorkspaceRoot, - isTrustedFile, - isSamePath -}; diff --git a/src/main/utils/wslTest.js b/src/main/utils/wslTest.js deleted file mode 100644 index 52a08c3..0000000 --- a/src/main/utils/wslTest.js +++ /dev/null @@ -1,129 +0,0 @@ -// WSL and CTrace testing utility (serve-mode) -const { spawn } = require('child_process'); -const os = require('os'); -const fs = require('fs/promises'); - -const { resolveBinaryPath } = require('./ctraceServeClient'); - -function toWslPath(winPath) { - return winPath.replace(/\\/g, '/').replace(/^([A-Z]):/, (m, d) => `/mnt/${d.toLowerCase()}`); -} - -/** - * Test WSL availability and CTrace execution. - * - * Note: SOCAT is no longer required. The GUI now starts CTrace in `--ipc serve` mode. - */ -async function testWSLAndCTrace() { - console.log('🧪 Testing WSL and CTrace Setup'); - console.log('================================'); - - const platform = os.platform(); - console.log(`Platform: ${platform}`); - - if (platform !== 'win32') { - console.log('✅ Not on Windows, WSL test not needed'); - return true; - } - - console.log('\n1. Testing WSL availability...'); - const wslAvailable = await testWSL(); - if (!wslAvailable) { - console.log('❌ WSL is not available'); - return false; - } - console.log('✅ WSL is available'); - - console.log('\n2. Testing CTrace binary via WSL...'); - const ctraceAvailable = await testCTraceViaWSL(); - if (!ctraceAvailable) { - console.log('❌ CTrace binary is not accessible via WSL'); - return false; - } - console.log('✅ CTrace binary is accessible via WSL'); - - console.log('\n🎉 All critical tests passed! WSL and CTrace are properly configured.'); - return true; -} - -function testWSL() { - return new Promise((resolve) => { - const child = spawn('wsl', ['--status'], { stdio: 'pipe' }); - - child.on('error', (err) => { - console.log(`WSL test error: ${err.message}`); - resolve(false); - }); - - child.on('close', (code) => { - console.log(`WSL status exit code: ${code}`); - resolve(code === 0); - }); - - setTimeout(() => { - child.kill(); - resolve(false); - }, 5000); - }); -} - -function testCTraceViaWSL() { - return new Promise((resolve) => { - (async () => { - try { - const binPath = resolveBinaryPath(); - await fs.access(binPath); - - const wslBinPath = toWslPath(binPath); - const child = spawn('wsl', [wslBinPath, '--help'], { stdio: 'pipe' }); - - let stdout = ''; - let stderr = ''; - let resolved = false; - - child.stdout.on('data', (data) => { - stdout += data.toString(); - }); - - child.stderr.on('data', (data) => { - stderr += data.toString(); - }); - - child.on('error', (err) => { - console.log(`CTrace test error: ${err.message}`); - if (!resolved) { - resolved = true; - resolve(false); - } - }); - - child.on('close', (code) => { - console.log(`CTrace --help exit code: ${code}`); - if (stdout) console.log(`Stdout: ${stdout.substring(0, 200)}...`); - if (stderr) console.log(`Stderr: ${stderr.substring(0, 200)}...`); - if (!resolved) { - resolved = true; - resolve(code === 0 || stdout.length > 0 || stderr.length > 0); - } - }); - - setTimeout(() => { - child.kill(); - if (!resolved) { - resolved = true; - resolve(false); - } - }, 5000); - } catch (e) { - console.log(`CTrace binary not accessible: ${e.message}`); - resolve(false); - } - })(); - }); -} - -module.exports = { testWSLAndCTrace }; - -if (require.main === module) { - testWSLAndCTrace().catch(console.error); -} \ No newline at end of file diff --git a/src/preload.js b/src/preload.js deleted file mode 100644 index afb2042..0000000 --- a/src/preload.js +++ /dev/null @@ -1,178 +0,0 @@ -/** - * Preload script: the only bridge between the sandboxed renderer and the - * main process. It runs with `sandbox: true`, so it has no Node.js modules; - * every capability it exposes is a narrow, allow-listed IPC call. - */ -const { contextBridge, ipcRenderer } = require('electron'); - -function getAdditionalArgumentValue(prefix) { - const arg = process.argv.find((entry) => typeof entry === 'string' && entry.startsWith(prefix)); - return arg ? arg.slice(prefix.length) : null; -} - -const monacoBasePath = getAdditionalArgumentValue('--ctrace-monaco-base-path=') || ''; - -let appInfoPromise = null; -let syntaxConfigPromise = null; - -function loadAppInfo() { - if (!appInfoPromise) { - appInfoPromise = ipcRenderer.invoke('app-get-info') - .catch(() => ({ name: 'CTraceGUI', version: '0.0.0' })); - } - return appInfoPromise; -} - -function loadSyntaxConfig() { - if (!syntaxConfigPromise) { - syntaxConfigPromise = ipcRenderer.invoke('app-get-syntax-config').catch(() => ({})); - } - return syntaxConfigPromise; -} - -// Whitelisted IPC channels -const INVOKE_CHANNELS = [ - 'get-file-tree', - 'open-folder-dialog', - 'open-file-dialog', - 'save-file', - 'save-file-as', - 'read-file', - 'read-large-file', - 'read-file-chunk', - 'force-open-file', - 'force-load-full-file', - 'get-directory-contents', - 'get-git-status', - 'search-in-files', - 'create-file', - 'create-folder', - 'rename-path', - 'delete-path', - 'run-ctrace', - 'open-editor', - 'assistant-chat', - 'assistant-abort', - 'assistant-get-providers', - 'assistant-test-provider', - 'assistant-unload-local', - 'assistant-list-models', - 'select-llm-file', - 'save-app-state', - 'load-app-state', - 'clear-app-state', - 'get-state-info', - 'updater-get-settings', - 'updater-check-now', - 'updater-set-channel', - 'updater-install-update', - 'backend-get-status', - 'check-file-exists', - 'backend-get-settings', - 'backend-save-settings', - 'backend-browse-binary', - 'assistant-config-save', - 'assistant-config-load', - 'assistant-config-clear', - 'assistant-conversations-save', - 'assistant-conversations-list', - 'assistant-conversations-load', - 'assistant-conversations-delete', - 'watch-workspace', - 'terminal-get-shells', - 'terminal-execute', - 'terminal-kill-current', - 'terminal-get-home', - 'terminal-get-completions', - 'terminal-get-initial-cwd', - 'terminal-send-input', - 'app-get-info', - 'app-get-syntax-config', - 'cloud-status', - 'cloud-login-start', - 'cloud-login-cancel', - 'cloud-logout', - 'cloud-tools', - 'cloud-limits', - 'cloud-run-start', - 'cloud-run-confirm', - 'cloud-run-cancel', - 'cloud-open-upgrade', - 'cloud-open-url', -]; - -const SEND_CHANNELS = [ - 'window-minimize', - 'window-maximize-toggle', - 'window-close', - 'startup-ready', - 'check-wsl-status', - 'install-wsl', - 'install-wsl-distro', - 'show-wsl-setup', - 'assistant-config-updated', - 'clipboard-write-text', -]; - -const RECEIVE_CHANNELS = [ - 'workspace-changed', - 'workspace-loading', - 'wsl-status', - 'wsl-install-response', - 'updater-status', - 'window-maximized', - 'app-before-quit', - 'terminal-data', - 'terminal-command-done', - 'cloud-run-event', -]; - -contextBridge.exposeInMainWorld('api', { - invoke: (channel, ...args) => { - if (INVOKE_CHANNELS.includes(channel)) { - return ipcRenderer.invoke(channel, ...args); - } - console.error(`IPC invoke channel "${channel}" is not allowed`); - return Promise.reject(new Error(`IPC invoke channel "${channel}" is not allowed`)); - }, - - send: (channel, ...args) => { - if (SEND_CHANNELS.includes(channel)) { - ipcRenderer.send(channel, ...args); - } else { - console.error(`IPC send channel "${channel}" is not allowed`); - } - }, - - on: (channel, callback) => { - if (RECEIVE_CHANNELS.includes(channel)) { - const subscription = (_event, ...args) => callback(...args); - ipcRenderer.on(channel, subscription); - return subscription; - } - console.error(`IPC receive channel "${channel}" is not allowed`); - }, - - removeListener: (channel, subscription) => { - if (RECEIVE_CHANNELS.includes(channel)) { - ipcRenderer.removeListener(channel, subscription); - } - }, - - clipboard: { - writeText: (text) => ipcRenderer.send('clipboard-write-text', String(text)), - }, - - platform: process.platform, - getRuntimeInfo: () => ({ - platform: process.platform, - hardwareAcceleration: getAdditionalArgumentValue('--ctrace-hardware-acceleration=') || 'unknown', - pid: process.pid - }), - - getAppInfo: () => loadAppInfo(), - getSyntaxConfig: () => loadSyntaxConfig(), - getMonacoBasePath: () => monacoBasePath, -}); - - diff --git a/src/renderer/UIController.js b/src/renderer/UIController.js deleted file mode 100644 index ed459eb..0000000 --- a/src/renderer/UIController.js +++ /dev/null @@ -1,1338 +0,0 @@ -;(function() { -// Manager classes and utilities are loaded via - - - - diff --git a/tests/autoSave.test.js b/tests/autoSave.test.js deleted file mode 100644 index bdcf270..0000000 --- a/tests/autoSave.test.js +++ /dev/null @@ -1,74 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); - -const UIController = require('../src/renderer/UIController'); -const EditorPanel = require('../src/renderer/components/EditorPanel'); - -function sleep(ms) { - return new Promise((resolve) => setTimeout(resolve, ms)); -} - -test('triggerAutoSave saves when active tab is modified', async () => { - let saveCalls = 0; - - const fakeController = { - editorPanel: {}, - - autoSaveEnabled: true, - autoSaveTimer: null, - autoSaveDelay: 10, - tabManager: { - getActiveTab() { - return { - filePath: 'C:/tmp/example.txt', - fileName: 'example.txt', - modified: true - }; - } - }, - fileOpsManager: { - async saveFile(options) { - assert.ok(options && options.silent, 'expected autosave to call saveFile({silent:true})'); - saveCalls += 1; - } - } - }; - - const ep = new EditorPanel(fakeController); -ep.triggerAutoSave(); - await sleep(30); - - assert.equal(saveCalls, 1); -}); - -test('triggerAutoSave does not save when active tab is clean', async () => { - let saveCalls = 0; - - const fakeController = { - editorPanel: {}, - - autoSaveEnabled: true, - autoSaveTimer: null, - autoSaveDelay: 10, - tabManager: { - getActiveTab() { - return { - filePath: 'C:/tmp/example.txt', - fileName: 'example.txt', - modified: false - }; - } - }, - fileOpsManager: { - async saveFile() { - saveCalls += 1; - } - } - }; - - const ep = new EditorPanel(fakeController); -ep.triggerAutoSave(); - await sleep(30); - - assert.equal(saveCalls, 0); -}); diff --git a/tests/cloudDiagnostics.test.js b/tests/cloudDiagnostics.test.js deleted file mode 100644 index 5613d18..0000000 --- a/tests/cloudDiagnostics.test.js +++ /dev/null @@ -1,40 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); - -const DiagnosticsManager = require('../src/renderer/managers/DiagnosticsManager'); - -test('cloud findings map to diagnostics attributed to the tool and job; clearSource removes only cloud entries', () => { - const dm = new DiagnosticsManager(null); - dm.currentDiagnostics = [{ id: 'local-1', ruleId: 'X', severity: 'INFO', source: 'local', details: { message: 'local' }, location: { file: 'a.c', startLine: 1, startColumn: 1, endLine: 1, endColumn: 1, function: 'global' } }]; - dm.addCloudFindings( - [ - { ruleId: 'CT-001', level: 'error', message: 'Buffer overflow', path: 'src/a.c', line: 10, column: 3, endLine: 10, endColumn: 20 }, - { ruleId: 'CT-017', level: 'warning', message: 'Unchecked', path: 'src/b.c', line: 4, column: null }, - { ruleId: 'CT-042', level: 'note', message: 'Style', path: 'src/c.c' }, - ], - { tool: 'ctrace', jobId: 'job-1', source: 'cloud:ctrace' }, - ); - assert.equal(dm.currentDiagnostics.length, 4); - const cloud = dm.currentDiagnostics.filter((d) => d.source === 'cloud:ctrace'); - assert.equal(cloud.length, 3); - assert.deepEqual(cloud[0].location, { file: 'src/a.c', startLine: 10, startColumn: 3, endLine: 10, endColumn: 20, function: 'global' }); - assert.equal(cloud[0].severity, 'ERROR'); - assert.equal(cloud[1].severity, 'WARNING'); - assert.equal(cloud[1].location.startColumn, 1); - assert.equal(cloud[2].severity, 'INFO'); - assert.equal(cloud[2].location.startLine, 1); - assert.equal(cloud[0].jobId, 'job-1'); - assert.match(cloud[0].id, /^cloud:ctrace:/); - assert.equal(dm.currentMetadata.tool, 'cloud'); - assert.deepEqual(dm.currentMetadata.tools, ['ctrace']); - assert.equal(dm.currentMetadata.jobId, 'job-1'); - - dm.addCloudFindings([{ ruleId: 'R', level: 'error', message: 'm', path: 'x.c', line: 1 }], { tool: 'runtime', jobId: 'job-1', source: 'cloud:runtime' }); - assert.deepEqual(dm.currentMetadata.tools, ['ctrace', 'runtime']); - assert.equal(dm.currentDiagnostics.length, 5); - - dm.clearSource('cloud'); - assert.equal(dm.currentDiagnostics.length, 1); - assert.equal(dm.currentDiagnostics[0].id, 'local-1'); - assert.equal(dm.currentMetadata, null); -}); diff --git a/tests/cloudRun.test.js b/tests/cloudRun.test.js deleted file mode 100644 index 116afde..0000000 --- a/tests/cloudRun.test.js +++ /dev/null @@ -1,127 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); - -const { CloudRun, serialiseView, serialiseFinding } = require('../src/main/cloud/cloudRun'); - -/** A stand-in for @coretrace/cli-core exposing only what CloudRun touches. */ -function fakeCore(script) { - return { - AuthError: class AuthError extends Error { - constructor(m) { - super(m); - this.code = 3; - } - }, - fetchMe: async () => ({ principal: { kind: 'user', name: 'A' }, orgs: [{ id: '1', slug: 'dev', role: 'owner', access_state: 'active' }] }), - selectOrg: (me) => me.orgs[0], - runsOf: (view) => [...view.runs.values()], - toSarif: () => ({ version: '2.1.0', runs: [] }), - runCloud: async (_api, options, hooks) => script(options, hooks), - }; -} - -function cloudWith(core) { - return { - client: async () => ({ core, api: {}, config: { org: undefined }, credential: { kind: 'session' } }), - tempDir: () => require('os').tmpdir(), - }; -} - -test('a run streams phases, estimate, confirmation, view, findings and done', async () => { - const events = []; - let resolveDone; - const done = new Promise((r) => (resolveDone = r)); - const core = fakeCore(async (options, hooks) => { - assert.equal(options.org, 'dev'); - assert.equal(options.confirm, true); - hooks.onPhase('pack'); - hooks.onPack({ fileCount: 3, expandedSize: 30, compressedSize: 10, excluded: new Map([['gitignore', { count: 2, examples: [] }]]) }); - hooks.onEstimate({ quoteId: 'q', totalReservedCtu: 100, items: [{ tool: 'ctrace', version: '1', reservedCtu: 100 }] }, { remaining_budget_ctu: 500 }, []); - const accepted = await hooks.confirm({ quoteId: 'q', totalReservedCtu: 100, items: [] }, { remaining_budget_ctu: 500 }, '2026-01-01T00:00:00Z'); - assert.equal(accepted, true); - const view = { jobId: 'j1', status: 'running', billedCtu: 0, rejected: [], runs: new Map([['r1', { id: 'r1', tool: 'ctrace', version: '1', status: 'running', progressMessage: 'analysing', inputCtu: 0, outputCtu: 0, billedCtu: 0, reservedCtu: 100 }]]) }; - hooks.onView(view); - hooks.onWaitMode('streaming'); - return { - view: { ...view, status: 'completed', conclusion: 'findings', billedCtu: 100 }, - reports: [{ runId: 'r1', tool: 'ctrace', version: '1', outcome: 'findings', billedCtu: 100, findings: [{ ruleId: 'CT-001', level: 'error', message: 'm', location: { path: 'a.c', line: 1 }, extra: {} }] }], - exitCode: 1, - declined: false, - thresholdCount: 1, - }; - }); - const runs = new CloudRun({ - cloud: cloudWith(core), - emit: (e) => { - events.push(e); - if (e.type === 'awaiting_confirmation') setTimeout(() => runs.confirm(e.runId, true), 5); - if (e.type === 'done') resolveDone(); - }, - }); - const { runId } = await runs.start({ rootPath: '/proj', tools: ['ctrace'] }); - await done; - const types = events.map((e) => e.type); - assert.deepEqual(types, ['phase', 'pack', 'estimate', 'awaiting_confirmation', 'job', 'wait', 'findings', 'done']); - assert.ok(events.every((e) => e.runId === runId)); - assert.equal(events[1].excluded.gitignore, 2); - assert.equal(events[3].confirmDeadline, '2026-01-01T00:00:00Z'); - assert.equal(events[4].runs[0].progress, 'analysing'); - assert.deepEqual(events[6].findings[0], { ruleId: 'CT-001', level: 'error', message: 'm', path: 'a.c', line: 1, column: null, endLine: null, endColumn: null }); - assert.equal(events[7].billedCtu, 100); - assert.equal(typeof events[7].sarif, 'string'); -}); - -test('decline resolves the confirmation with false; errors carry the exit code; cancel aborts', async () => { - const events = []; - let resolveDone; - const done = new Promise((r) => (resolveDone = r)); - const core = fakeCore(async (options, hooks) => { - const accepted = await hooks.confirm({ quoteId: 'q', totalReservedCtu: 5, items: [] }, { remaining_budget_ctu: 1 }, null); - assert.equal(accepted, false); - const err = new Error('Confirmation window expired'); - err.code = 5; - err.detail = { reason: 'expired' }; - throw err; - }); - const runs = new CloudRun({ - cloud: cloudWith(core), - emit: (e) => { - events.push(e); - if (e.type === 'awaiting_confirmation') runs.confirm(e.runId, false); - if (e.type === 'error') resolveDone(); - }, - }); - await runs.start({ rootPath: '/proj', tools: ['ctrace'] }); - await done; - assert.deepEqual(events.at(-1), { runId: events[0].runId, type: 'error', code: 5, message: 'Confirmation window expired', reason: 'expired' }); - assert.deepEqual(runs.confirm('nope', true), { ok: false, error: 'no confirmation pending' }); - assert.deepEqual(runs.cancel('nope'), { ok: false, error: 'unknown run' }); - - // Cancel while the core is waiting on the abort signal. - let aborted = false; - const waiting = fakeCore((options) => new Promise((_, reject) => options.signal.addEventListener('abort', () => { - aborted = true; - const e = new Error('Wait interrupted'); - e.code = 4; - reject(e); - }))); - const events2 = []; - let resolveErr; - const errored = new Promise((r) => (resolveErr = r)); - const runs2 = new CloudRun({ cloud: cloudWith(waiting), emit: (e) => { events2.push(e); if (e.type === 'error') resolveErr(); } }); - const { runId } = await runs2.start({ rootPath: '/proj', tools: ['ctrace'] }); - await new Promise((r) => setTimeout(r, 10)); - assert.deepEqual(runs2.cancel(runId), { ok: true }); - await errored; - assert.equal(aborted, true); - assert.equal(events2.at(-1).code, 4); -}); - -test('serialisers keep only renderer-safe fields', () => { - const core = { runsOf: (v) => [...v.runs.values()] }; - const view = { jobId: 'j', status: 'completed', conclusion: 'clean', billedCtu: 7, rejected: [], runs: new Map([['r', { id: 'r', tool: 't', version: 'v', status: 'completed', outcome: 'clean', inputCtu: 1, outputCtu: 1, billedCtu: 7, reservedCtu: 9 }]]) }; - const s = serialiseView(core, view); - assert.deepEqual(Object.keys(s).sort(), ['billedCtu', 'conclusion', 'confirmDeadline', 'jobId', 'rejected', 'runs', 'status']); - assert.equal(s.runs[0].findingsSoFar, null); - assert.deepEqual(serialiseFinding({ ruleId: 'R', level: 'note', message: 'm', location: { path: 'p' }, extra: { secret: 'x' } }), { ruleId: 'R', level: 'note', message: 'm', path: 'p', line: null, column: null, endLine: null, endColumn: null }); -}); diff --git a/tests/cloudRunManager.test.js b/tests/cloudRunManager.test.js deleted file mode 100644 index 40f64b9..0000000 --- a/tests/cloudRunManager.test.js +++ /dev/null @@ -1,90 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); - -const CloudRunManager = require('../src/renderer/managers/CloudRunManager'); - -function manager() { - const calls = []; - const diagnostics = { - clearSource: (s) => calls.push(['clear', s]), - addCloudFindings: (list, meta) => calls.push(['add', list.length, meta.source, meta.jobId]), - }; - const m = new CloudRunManager({ diagnosticsManager: diagnostics }); - return { m, calls }; -} - -test('status and tools: greying rule is presentation only', () => { - const { m } = manager(); - m.applyStatus({ online: true, signedIn: false, upgradeUrl: 'https://up' }); - assert.equal(m.state.status, 'signed_out'); - m.applyStatus({ online: true, signedIn: true, storeKind: 'safe_storage', identity: { principal: { kind: 'user', name: 'Alice' }, org: 'dev', orgs: [] } }); - assert.equal(m.state.status, 'ready'); - assert.match(m.label(), /Alice \(dev\)/); - m.applyTools([ - { id: 'ctrace', version: '0.74.0', entitled: true, required_entitlement: 'static' }, - { id: 'runtime', version: '1.2.0', entitled: false, required_entitlement: 'runtime' }, - ]); - assert.deepEqual(m.selectableTools(), ['ctrace']); - const runtime = m.state.tools.find((t) => t.id === 'runtime'); - assert.equal(runtime.disabled, true); - assert.equal(runtime.upgradeUrl, 'https://up'); - m.applyStatus({ online: false, signedIn: true }); - assert.equal(m.state.online, false); -}); - -test('full run: pack → estimate → quote → confirm → waiting → findings → finished', () => { - const { m, calls } = manager(); - m.applyStatus({ online: true, signedIn: true, identity: { principal: { kind: 'user', name: 'A' }, org: 'dev' } }); - m.beginRun('r1'); - assert.equal(m.state.status, 'packing'); - assert.deepEqual(calls[0], ['clear', 'cloud']); - m.applyEvent({ type: 'phase', phase: 'upload' }); - assert.equal(m.state.status, 'uploading'); - m.applyEvent({ type: 'pack', fileCount: 12, expandedSize: 1000, compressedSize: 300, excluded: { gitignore: 2 } }); - m.applyEvent({ type: 'phase', phase: 'estimate' }); - m.applyEvent({ type: 'estimate', quote: { quoteId: 'q', totalReservedCtu: 100, items: [{ tool: 'ctrace', version: '0.74.0', reservedCtu: 100 }] }, remainingBudgetCtu: 50000, rejected: [] }); - assert.equal(m.state.status, 'estimating'); - m.applyEvent({ type: 'awaiting_confirmation', confirmDeadline: '2026-09-05T12:00:00Z' }); - assert.equal(m.state.status, 'quote_shown'); - assert.equal(m.state.quote.totalReservedCtu, 100); - m.confirm(true); - assert.equal(m.state.status, 'confirming'); - m.applyEvent({ type: 'job', jobId: 'j1', status: 'queued', runs: [{ id: 'run1', tool: 'ctrace', status: 'pending', billedCtu: 0, reservedCtu: 100 }], rejected: [] }); - assert.equal(m.state.status, 'waiting'); - assert.equal(m.state.jobId, 'j1'); - m.applyEvent({ type: 'wait', mode: 'reconnecting' }); - assert.match(m.label(), /reconnecting/); - m.applyEvent({ type: 'findings', tool: 'ctrace', toolRunId: 'run1', findings: [{ ruleId: 'CT-001', level: 'error', message: 'm', path: 'src/a.c', line: 10, column: 3 }] }); - assert.deepEqual(calls.at(-1), ['add', 1, 'cloud:ctrace', 'j1']); - m.applyEvent({ type: 'done', exitCode: 1, conclusion: 'findings', billedCtu: 100, thresholdCount: 1, jobId: 'j1', sarif: '{}' }); - assert.equal(m.state.status, 'finished'); - assert.match(m.label(), /billed 100 CTU/); -}); - -test('decline, errors and sign-out states', () => { - const { m } = manager(); - m.applyStatus({ online: true, signedIn: true, identity: { principal: { kind: 'user' }, org: 'dev' } }); - m.beginRun('r2'); - m.applyEvent({ type: 'awaiting_confirmation', quote: { quoteId: 'q', totalReservedCtu: 5, items: [] } }); - m.confirm(false); - assert.equal(m.state.status, 'cancelled'); - m.applyEvent({ type: 'phase', phase: 'wait' }); - assert.equal(m.state.status, 'cancelled', 'late phases do not resurrect a cancelled run'); - m.applyEvent({ type: 'done', exitCode: 0, declined: true }); - assert.equal(m.state.summary.declined, true); - assert.match(m.label(), /no CTU reserved/); - - m.beginRun('r3'); - m.applyEvent({ type: 'error', code: 2, message: 'Tree exceeds max_files', reason: 'cap_breach' }); - assert.equal(m.state.status, 'failed'); - assert.equal(m.state.error.reason, 'cap_breach'); - m.applyEvent({ type: 'error', code: 3, message: 'Session revoked' }); - assert.equal(m.state.status, 'signed_out'); - - m.beginLogin(); - m.applyEvent({ type: 'login', state: 'pending', userCode: 'AB12-CD34', verificationUri: 'https://api/device' }); - assert.match(m.label(), /AB12-CD34/); - m.applyEvent({ type: 'login', state: 'approved', identity: { principal: { kind: 'user', name: 'B' }, org: 'dev' } }); - assert.equal(m.state.status, 'ready'); - assert.throws(() => m.set({ status: 'nope' }), /unknown state/); -}); diff --git a/tests/ctraceHandlers.test.js b/tests/ctraceHandlers.test.js deleted file mode 100644 index cb23b72..0000000 --- a/tests/ctraceHandlers.test.js +++ /dev/null @@ -1,356 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); -const path = require('node:path'); -const os = require('node:os'); -const fsPromises = require('node:fs/promises'); -const Module = require('node:module'); -const { EventEmitter } = require('node:events'); - -function withModuleMocks(mocks, callback) { - const originalLoad = Module._load; - Module._load = function (request, parent, isMain) { - if (Object.prototype.hasOwnProperty.call(mocks, request)) { - return mocks[request]; - } - return originalLoad.apply(this, arguments); - }; - try { - return callback(); - } finally { - Module._load = originalLoad; - } -} - -function createChildProcess({ stdout = '', stderr = '', code = 0, error = null }) { - const child = new EventEmitter(); - child.stdout = new EventEmitter(); - child.stderr = new EventEmitter(); - child.kill = () => { child.killed = true; }; - - process.nextTick(() => { - if (error) { - child.emit('error', error instanceof Error ? error : new Error(error)); - return; - } - if (stdout) { - child.stdout.emit('data', Buffer.from(stdout)); - } - if (stderr) { - child.stderr.emit('data', Buffer.from(stderr)); - } - child.emit('close', code); - }); - - return child; -} - -test('run-ctrace handler reports missing binary when access fails', async (t) => { - const handlers = new Map(); - const electronStub = { - ipcMain: { - handle: (channel, handler) => handlers.set(channel, handler) - } - }; - - const serveClientStub = { - ensureServerRunning: t.mock.fn(async () => ({ host: '127.0.0.1', port: 8080, token: 't' })), - callApi: t.mock.fn(async () => ({ ok: true, json: { result: {} }, statusCode: 200 })), - shutdownServer: t.mock.fn(async () => ({ success: true })), - resolveBinaryPath: () => '/fake/bin/ctrace', - checkBinaryFormat: () => ({ ok: true }) - }; - - const { setupCtraceHandlers } = withModuleMocks({ - electron: electronStub, - '../utils/ctraceServeClient': serveClientStub - }, () => { - const modulePath = path.join(__dirname, '../src/main/ipc/ctraceHandlers.js'); - delete require.cache[modulePath]; - return require(modulePath); - }); - - const accessMock = t.mock.method(fsPromises, 'access', async () => { - throw new Error('not found'); - }); - - const platformMock = t.mock.method(os, 'platform', () => 'linux'); - - setupCtraceHandlers(); - const response = await handlers.get('run-ctrace')(null, []); - - assert.strictEqual(response.success, false); - assert.ok(response.error.includes('ctrace binary not found')); - assert.strictEqual(serveClientStub.ensureServerRunning.mock.calls.length, 0); - - accessMock.mock.restore(); - platformMock.mock.restore(); -}); - -test('run-ctrace handler executes binary and returns output', async (t) => { - const handlers = new Map(); - const electronStub = { - ipcMain: { - handle: (channel, handler) => handlers.set(channel, handler) - } - }; - - const serveClientStub = { - ensureServerRunning: t.mock.fn(async () => ({ host: '127.0.0.1', port: 8080, token: 't' })), - callApi: t.mock.fn(async () => ({ ok: true, json: { result: { meta: { tool: 'ctrace' }, diagnostics: [] } }, statusCode: 200 })), - shutdownServer: t.mock.fn(async () => ({ success: true })), - resolveBinaryPath: () => '/fake/bin/ctrace', - checkBinaryFormat: () => ({ ok: true }) - }; - - const { setupCtraceHandlers } = withModuleMocks({ - electron: electronStub, - '../utils/ctraceServeClient': serveClientStub - }, () => { - const modulePath = path.join(__dirname, '../src/main/ipc/ctraceHandlers.js'); - delete require.cache[modulePath]; - return require(modulePath); - }); - - const accessMock = t.mock.method(fsPromises, 'access', async () => {}); - const platformMock = t.mock.method(os, 'platform', () => 'linux'); - - setupCtraceHandlers(); - const response = await handlers.get('run-ctrace')(null, ['--version']); - - assert.strictEqual(response.success, true); - assert.ok(typeof response.output === 'string'); - assert.ok(response.output.includes('"diagnostics"')); - assert.strictEqual(serveClientStub.ensureServerRunning.mock.calls.length, 1); - assert.strictEqual(serveClientStub.callApi.mock.calls.length, 1); - - accessMock.mock.restore(); - platformMock.mock.restore(); -}); - -test('run-ctrace handler flattens result.outputs stack analyzer JSON', async (t) => { - const handlers = new Map(); - const electronStub = { - ipcMain: { - handle: (channel, handler) => handlers.set(channel, handler) - } - }; - - const serveClientStub = { - ensureServerRunning: t.mock.fn(async () => ({ host: '127.0.0.1', port: 8080, token: 't' })), - callApi: t.mock.fn(async () => ({ - ok: true, - statusCode: 200, - json: { - result: { - sarif_format: true, - invoked_tools: ['ctrace_stack_analyzer'], - outputs: { - ctrace_stack_analyzer: [ - { - stream: 'stdout', - message: { - meta: { tool: 'ctrace-stack-analyzer', inputFile: 'x.c', mode: 'IR', stackLimit: 123, analysisTimeMs: -1 }, - functions: [], - diagnostics: [ - { - id: '1', - ruleId: 'StackPointerEscape', - severity: 'WARNING', - location: { file: 'x.c', function: 'main', startLine: 10, startColumn: 1, endLine: 10, endColumn: 1 }, - details: { message: 'escape' } - } - ] - } - } - ] - } - } - } - })), - shutdownServer: t.mock.fn(async () => ({ success: true })), - resolveBinaryPath: () => '/fake/bin/ctrace', - checkBinaryFormat: () => ({ ok: true }) - }; - - const { setupCtraceHandlers } = withModuleMocks({ - electron: electronStub, - '../utils/ctraceServeClient': serveClientStub - }, () => { - const modulePath = path.join(__dirname, '../src/main/ipc/ctraceHandlers.js'); - delete require.cache[modulePath]; - return require(modulePath); - }); - - const accessMock = t.mock.method(fsPromises, 'access', async () => {}); - const platformMock = t.mock.method(os, 'platform', () => 'linux'); - - setupCtraceHandlers(); - const response = await handlers.get('run-ctrace')(null, ['--invoke', 'ctrace_stack_analyzer', '--sarif-format']); - - assert.strictEqual(response.success, true); - const parsed = JSON.parse(response.output); - assert.strictEqual(parsed.meta.tool, 'ctrace-stack-analyzer'); - assert.ok(Array.isArray(parsed.diagnostics)); - assert.strictEqual(parsed.diagnostics.length, 1); - assert.strictEqual(parsed.diagnostics[0].ruleId, 'StackPointerEscape'); - - accessMock.mock.restore(); - platformMock.mock.restore(); -}); - -test('run-ctrace handler ignores generic ERROR text from normal tool output', async (t) => { - const handlers = new Map(); - const electronStub = { - ipcMain: { - handle: (channel, handler) => handlers.set(channel, handler) - } - }; - - const serveClientStub = { - ensureServerRunning: t.mock.fn(async () => ({ host: '127.0.0.1', port: 8080, token: 't' })), - callApi: t.mock.fn(async () => ({ - ok: true, - statusCode: 200, - json: { - result: { - outputs: { - ctrace_stack_analyzer: [ - { - stream: 'stdout', - message: '{"severity":"ERROR","ruleId":"StackPointerEscape","message":"normal diagnostic payload"}' - } - ] - } - } - } - })), - shutdownServer: t.mock.fn(async () => ({ success: true })), - resolveBinaryPath: () => '/fake/bin/ctrace', - checkBinaryFormat: () => ({ ok: true }) - }; - - const { setupCtraceHandlers } = withModuleMocks({ - electron: electronStub, - '../utils/ctraceServeClient': serveClientStub - }, () => { - const modulePath = path.join(__dirname, '../src/main/ipc/ctraceHandlers.js'); - delete require.cache[modulePath]; - return require(modulePath); - }); - - const accessMock = t.mock.method(fsPromises, 'access', async () => {}); - const platformMock = t.mock.method(os, 'platform', () => 'linux'); - - setupCtraceHandlers(); - const response = await handlers.get('run-ctrace')(null, []); - - assert.strictEqual(response.success, true); - assert.strictEqual(response.output.includes('ToolExecutionError.UnknownTool'), false); - - accessMock.mock.restore(); - platformMock.mock.restore(); -}); - -test('run-ctrace handler preserves tool name for real unknown tool failures', async (t) => { - const handlers = new Map(); - const electronStub = { - ipcMain: { - handle: (channel, handler) => handlers.set(channel, handler) - } - }; - - const serveClientStub = { - ensureServerRunning: t.mock.fn(async () => ({ host: '127.0.0.1', port: 8080, token: 't' })), - callApi: t.mock.fn(async () => ({ - ok: true, - statusCode: 200, - json: { - result: { - outputs: { - ctrace_stack_analyzer: [ - { - stream: 'stderr', - message: 'ERROR: unknown tool requested by backend' - } - ] - } - } - } - })), - shutdownServer: t.mock.fn(async () => ({ success: true })), - resolveBinaryPath: () => '/fake/bin/ctrace', - checkBinaryFormat: () => ({ ok: true }) - }; - - const { setupCtraceHandlers } = withModuleMocks({ - electron: electronStub, - '../utils/ctraceServeClient': serveClientStub - }, () => { - const modulePath = path.join(__dirname, '../src/main/ipc/ctraceHandlers.js'); - delete require.cache[modulePath]; - return require(modulePath); - }); - - const accessMock = t.mock.method(fsPromises, 'access', async () => {}); - const platformMock = t.mock.method(os, 'platform', () => 'linux'); - - setupCtraceHandlers(); - const response = await handlers.get('run-ctrace')(null, []); - - assert.strictEqual(response.success, true); - const parsed = JSON.parse(response.output); - assert.ok(Array.isArray(parsed.diagnostics)); - assert.strictEqual(parsed.diagnostics.length, 1); - assert.strictEqual(parsed.diagnostics[0].ruleId, 'ToolExecutionError.ctrace_stack_analyzer'); - - accessMock.mock.restore(); - platformMock.mock.restore(); -}); - -test('run-ctrace handler fails fast on an unknown --invoke tool name instead of reporting a clean run', async (t) => { - const handlers = new Map(); - const electronStub = { - ipcMain: { - handle: (channel, handler) => handlers.set(channel, handler) - } - }; - - const serveClientStub = { - ensureServerRunning: t.mock.fn(async () => ({ host: '127.0.0.1', port: 8080, token: 't' })), - // The real /api run_analysis endpoint silently drops unknown invoke - // entries (empty outputs, status "ok") instead of erroring, so this - // stub should never even be reached once the fix validates client-side. - callApi: t.mock.fn(async () => ({ - ok: true, - statusCode: 200, - json: { result: { outputs: {}, invoked_tools: ['notatool'] } } - })), - shutdownServer: t.mock.fn(async () => ({ success: true })), - resolveBinaryPath: () => '/fake/bin/ctrace', - checkBinaryFormat: () => ({ ok: true }) - }; - - const { setupCtraceHandlers } = withModuleMocks({ - electron: electronStub, - '../utils/ctraceServeClient': serveClientStub - }, () => { - const modulePath = path.join(__dirname, '../src/main/ipc/ctraceHandlers.js'); - delete require.cache[modulePath]; - return require(modulePath); - }); - - const accessMock = t.mock.method(fsPromises, 'access', async () => {}); - const platformMock = t.mock.method(os, 'platform', () => 'linux'); - - setupCtraceHandlers(); - const response = await handlers.get('run-ctrace')(null, ['--invoke', 'notatool']); - - assert.strictEqual(response.success, false); - assert.match(response.error, /Unknown tool 'notatool'/); - assert.match(response.error, /ikos,cppcheck,tscancode,ctrace_stack_analyzer/); - assert.strictEqual(serveClientStub.callApi.mock.calls.length, 0, 'should fail before ever calling the backend API'); - - accessMock.mock.restore(); - platformMock.mock.restore(); -}); - diff --git a/tests/ctraceServeClient.test.js b/tests/ctraceServeClient.test.js deleted file mode 100644 index 330149f..0000000 --- a/tests/ctraceServeClient.test.js +++ /dev/null @@ -1,76 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); -const fs = require('node:fs'); -const os = require('node:os'); -const path = require('node:path'); -const Module = require('node:module'); - -const MODULE_PATH = path.join(__dirname, '../src/main/utils/ctraceServeClient.js'); - -// Load ctraceServeClient with `os.platform()` forced to a given value, so the -// macOS-only checks can be exercised from any host. -function loadWithPlatform(platform) { - const osStub = Object.create(os); - osStub.platform = () => platform; - - const originalLoad = Module._load; - Module._load = function (request, ...rest) { - if (request === 'os') return osStub; - return originalLoad.call(this, request, ...rest); - }; - - try { - delete require.cache[require.resolve(MODULE_PATH)]; - return require(MODULE_PATH); - } finally { - Module._load = originalLoad; - delete require.cache[require.resolve(MODULE_PATH)]; - } -} - -function writeBinary(name, header) { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ctrace-test-')); - const file = path.join(dir, name); - fs.writeFileSync(file, Buffer.from(header)); - return file; -} - -// 0x7f 'E' 'L' 'F' — Linux; 0xcffaedfe — 64-bit Mach-O, little endian. -const ELF_HEADER = [0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00]; -const MACHO_HEADER = [0xcf, 0xfa, 0xed, 0xfe, 0x0c, 0x00, 0x00, 0x01]; - -test('checkBinaryFormat rejects a Linux binary on macOS', () => { - const { checkBinaryFormat } = loadWithPlatform('darwin'); - const file = writeBinary('ctrace', ELF_HEADER); - - const result = checkBinaryFormat(file); - - assert.equal(result.ok, false); - assert.match(result.error, /Linux executable and cannot run on macOS/); - assert.match(result.error, /Backend Settings/); -}); - -test('checkBinaryFormat accepts a Mach-O binary on macOS', () => { - const { checkBinaryFormat } = loadWithPlatform('darwin'); - const file = writeBinary('ctrace-darwin-arm64', MACHO_HEADER); - - assert.deepEqual(checkBinaryFormat(file), { ok: true }); -}); - -test('checkBinaryFormat reports an unreadable binary on macOS', () => { - const { checkBinaryFormat } = loadWithPlatform('darwin'); - - const result = checkBinaryFormat(path.join(os.tmpdir(), 'does-not-exist-ctrace')); - - assert.equal(result.ok, false); - assert.match(result.error, /Cannot read the ctrace binary/); -}); - -test('checkBinaryFormat leaves other platforms alone', () => { - const { checkBinaryFormat } = loadWithPlatform('linux'); - const file = writeBinary('ctrace', ELF_HEADER); - - assert.deepEqual(checkBinaryFormat(file), { ok: true }); - // Not even read: a missing file is fine off macOS. - assert.deepEqual(checkBinaryFormat('/nope'), { ok: true }); -}); diff --git a/tests/editorHandlers.test.js b/tests/editorHandlers.test.js deleted file mode 100644 index 833a3be..0000000 --- a/tests/editorHandlers.test.js +++ /dev/null @@ -1,61 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); -const path = require('node:path'); -const Module = require('node:module'); - -function withModuleMocks(mocks, callback) { - const originalLoad = Module._load; - Module._load = function (request, parent, isMain) { - if (Object.prototype.hasOwnProperty.call(mocks, request)) { - return mocks[request]; - } - return originalLoad.apply(this, arguments); - }; - try { - return callback(); - } finally { - Module._load = originalLoad; - } -} - -test('open-editor uses platform specific commands', async (t) => { - const handlers = new Map(); - const electronStub = { - ipcMain: { - on: (channel, listener) => handlers.set(channel, listener) - } - }; - - const execStub = t.mock.fn((command, cb) => cb && cb(null)); - - const modulePath = path.join(__dirname, '../src/main/ipc/editorHandlers.js'); - const { setupEditorHandlers } = withModuleMocks({ - electron: electronStub, - 'child_process': { exec: (...args) => execStub(...args) } - }, () => { - delete require.cache[modulePath]; - return require(modulePath); - }); - - const originalPlatform = process.platform; - - setupEditorHandlers(); - assert.ok(handlers.has('open-editor')); - - const listener = handlers.get('open-editor'); - - Object.defineProperty(process, 'platform', { value: 'linux' }); - listener(); - assert.strictEqual(execStub.mock.calls.at(-1).arguments[0], 'x-terminal-emulator -e nano'); - - Object.defineProperty(process, 'platform', { value: 'darwin' }); - listener(); - assert.strictEqual(execStub.mock.calls.at(-1).arguments[0], 'open -a TextEdit'); - - Object.defineProperty(process, 'platform', { value: 'win32' }); - listener(); - assert.strictEqual(execStub.mock.calls.at(-1).arguments[0], 'notepad'); - - Object.defineProperty(process, 'platform', { value: originalPlatform }); -}); - diff --git a/tests/emojiTest.test.js b/tests/emojiTest.test.js deleted file mode 100644 index 56a6426..0000000 --- a/tests/emojiTest.test.js +++ /dev/null @@ -1,42 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); -const path = require('node:path'); -const os = require('node:os'); - -const modulePath = path.join(__dirname, '../src/renderer/utils/emojiTest.js'); - -test('testEmojiSupport inspects DOM and returns metadata', () => { - const originalPlatform = os.platform(); - const platformMock = test.mock.method(os, 'platform', () => 'testos'); - - const createdElements = []; - const bodyChildren = []; - - global.document = { - createElement: () => { - const element = { style: {}, textContent: '' }; - createdElements.push(element); - return element; - }, - body: { - appendChild: (el) => bodyChildren.push({ type: 'append', el }), - removeChild: (el) => bodyChildren.push({ type: 'remove', el }) - } - }; - global.window = { - getComputedStyle: () => ({ fontFamily: 'Mock Font' }) - }; - - delete require.cache[modulePath]; - const { testEmojiSupport } = require(modulePath); - - const result = testEmojiSupport(); - assert.strictEqual(result.platform, 'testos'); - assert.ok(result.supportedEmojis.includes('📁')); - assert.strictEqual(result.fontFamily, 'Mock Font'); - assert.strictEqual(createdElements.length, 1); - assert.deepStrictEqual(bodyChildren.map((entry) => entry.type), ['append', 'remove']); - - platformMock.mock.restore(); -}); - diff --git a/tests/fileHandlers.test.js b/tests/fileHandlers.test.js deleted file mode 100644 index 8ba3bf0..0000000 --- a/tests/fileHandlers.test.js +++ /dev/null @@ -1,136 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); -const path = require('node:path'); -const fsPromises = require('node:fs/promises'); -const Module = require('node:module'); -const { EventEmitter } = require('node:events'); - -function withModuleMocks(mocks, callback) { - const originalLoad = Module._load; - Module._load = function (request, parent, isMain) { - if (Object.prototype.hasOwnProperty.call(mocks, request)) { - return mocks[request]; - } - return originalLoad.apply(this, arguments); - }; - try { - return callback(); - } finally { - Module._load = originalLoad; - } -} - -test('open-folder-dialog handler returns tree and starts watcher', async (t) => { - const handlers = new Map(); - const recorded = { watchCalls: 0 }; - const mainWindow = { - webContents: { - send: t.mock.fn() - } - }; - - const electronStub = { - ipcMain: { - handle: (channel, handler) => handlers.set(channel, handler), - on: () => {} - }, - dialog: { - showOpenDialog: () => Promise.resolve({ canceled: false, filePaths: ['/workspace/project'] }), - showSaveDialog: () => Promise.resolve({ canceled: false, filePath: '/workspace/save.txt' }) - } - }; - - const fileUtilsStub = { - buildFileTree: async (folderPath) => [{ name: 'file.txt', path: `${folderPath}/file.txt`, type: 'file' }], - detectFileEncoding: async () => ({ isUTF8: true, size: 10, buffer: Buffer.from('hello world') }), - searchInDirectory: async () => [{ file: '/workspace/project/file.txt', content: 'match' }], - FILE_SIZE_LIMIT: 5, - LARGE_FILE_THRESHOLD: 5 * 1024 * 1024, - validatePathInWorkspace: (targetPath) => ({ valid: true, resolvedPath: targetPath }) - }; - - const chokidarStub = { - watch: () => { - recorded.watchCalls++; - const emitter = new EventEmitter(); - emitter.on = function (event, listener) { - EventEmitter.prototype.on.call(this, event, listener); - return this; - }; - emitter.close = () => { emitter.closed = true; }; - return emitter; - } - }; - - const modulePath = path.join(__dirname, '../src/main/ipc/fileHandlers.js'); - const mocks = { - electron: electronStub, - chokidar: chokidarStub, - '../utils/fileUtils': fileUtilsStub - }; - - const writeFileMock = t.mock.method(fsPromises, 'writeFile', async () => {}); - - const { setupFileHandlers } = withModuleMocks(mocks, () => { - delete require.cache[modulePath]; - return require(modulePath); - }); - - setupFileHandlers(mainWindow); - assert.ok(handlers.has('open-folder-dialog')); - - const response = await handlers.get('open-folder-dialog')(); - assert.deepStrictEqual(response, { - success: true, - folderPath: '/workspace/project', - fileTree: [{ name: 'file.txt', path: '/workspace/project/file.txt', type: 'file' }] - }); - assert.strictEqual(recorded.watchCalls, 1); - - const saveResponse = await handlers.get('save-file')(null, '/workspace/project/file.txt', 'updated'); - assert.deepStrictEqual(saveResponse, { success: true }); - assert.strictEqual(writeFileMock.mock.calls.length > 0, true); - - const searchResponse = await handlers.get('search-in-files')(null, 'match', '/workspace/project'); - assert.deepStrictEqual(searchResponse, { success: true, results: [{ file: '/workspace/project/file.txt', content: 'match' }] }); -}); - -test('open-file-dialog returns encoding warning when detectFileEncoding rejects UTF-8', async (t) => { - const handlers = new Map(); - const electronStub = { - ipcMain: { - handle: (channel, handler) => handlers.set(channel, handler), - on: () => {} - }, - dialog: { - showOpenDialog: () => Promise.resolve({ canceled: false, filePaths: ['/workspace/warn.bin'] }), - showSaveDialog: () => Promise.resolve({ canceled: true }) - } - }; - - const fileUtilsStub = { - buildFileTree: async () => [], - detectFileEncoding: async () => ({ isUTF8: false, size: 20, buffer: Buffer.alloc(0) }), - searchInDirectory: async () => [], - FILE_SIZE_LIMIT: 5, - LARGE_FILE_THRESHOLD: 5 * 1024 * 1024, - validatePathInWorkspace: (targetPath) => ({ valid: true, resolvedPath: targetPath }) - }; - - const modulePath = path.join(__dirname, '../src/main/ipc/fileHandlers.js'); - - const { setupFileHandlers } = withModuleMocks({ - electron: electronStub, - chokidar: { watch: () => new EventEmitter() }, - '../utils/fileUtils': fileUtilsStub - }, () => { - delete require.cache[modulePath]; - return require(modulePath); - }); - - setupFileHandlers({ webContents: { send: () => {} } }); - const response = await handlers.get('open-file-dialog')(); - assert.strictEqual(response.warning, 'encoding'); - assert.strictEqual(response.success, true); -}); - diff --git a/tests/fileTypeUtils.test.js b/tests/fileTypeUtils.test.js deleted file mode 100644 index 9980f03..0000000 --- a/tests/fileTypeUtils.test.js +++ /dev/null @@ -1,38 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); -const path = require('node:path'); - -const modulePath = path.join(__dirname, '../src/renderer/utils/fileTypeUtils.js'); -delete require.cache[modulePath]; -const fileTypeUtils = require(modulePath); - -const { detectFileType, updateFileTypeStatus, getFileIcon, formatFileSize } = fileTypeUtils; - -test('detectFileType categorizes extensions', () => { - assert.strictEqual(detectFileType('main.c'), 'C'); - assert.strictEqual(detectFileType('main.cpp'), 'C++'); - assert.strictEqual(detectFileType('script.py'), 'Python'); - assert.strictEqual(detectFileType('README.md'), 'Markdown'); - assert.strictEqual(detectFileType(''), 'Plain Text'); -}); - -test('updateFileTypeStatus writes to DOM element when present', () => { - const element = { textContent: '' }; - global.document = { getElementById: () => element }; - updateFileTypeStatus('example.js'); - assert.strictEqual(element.textContent, 'JavaScript'); -}); - -test('getFileIcon returns emoji and formatFileSize formats numbers', () => { - // Known extensions return an tag pointing at a bundled SVG, with no - // inline event handler (the page runs under a strict CSP) - const jsIcon = getFileIcon('file.js'); - assert.ok(jsIcon.includes('../assets/icons/devicon/javascript-original.svg'), 'js icon should reference the bundled SVG'); - assert.ok(!/\son[a-z]+=/.test(jsIcon), 'js icon must not carry inline event handlers'); - // Unknown extensions return the emoji directly - assert.strictEqual(getFileIcon('unknown.xyz'), '📄'); - assert.strictEqual(formatFileSize(0), '0 Bytes'); - assert.strictEqual(formatFileSize(1024), '1 KB'); - assert.strictEqual(formatFileSize(1024 * 1024), '1 MB'); -}); - diff --git a/tests/fileUtils.test.js b/tests/fileUtils.test.js deleted file mode 100644 index 1174858..0000000 --- a/tests/fileUtils.test.js +++ /dev/null @@ -1,87 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); -const fs = require('node:fs/promises'); -const path = require('node:path'); -const os = require('node:os'); - -const { - isValidUTF8, - buildFileTree, - searchInDirectory, - detectFileEncoding -} = require('../src/main/utils/fileUtils'); - -async function withTempDir(callback) { - const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'file-utils-test-')); - try { - return await callback(tempDir); - } finally { - await fs.rm(tempDir, { recursive: true, force: true }); - } -} - -test('isValidUTF8 returns true for ASCII text', () => { - const buffer = Buffer.from('Hello, world!', 'utf8'); - assert.strictEqual(isValidUTF8(buffer), true); -}); - -test('isValidUTF8 returns true for empty buffer', () => { - const buffer = Buffer.alloc(0); - assert.strictEqual(isValidUTF8(buffer), true); -}); - -test('isValidUTF8 returns false when null byte ratio exceeds threshold', () => { - const buffer = Buffer.alloc(200, 1); - for (let i = 0; i < 50; i++) { - buffer[i] = 0; - } - assert.strictEqual(isValidUTF8(buffer), false); -}); - -test('buildFileTree lists directories before files and skips ignored entries', async () => { - await withTempDir(async (tempDir) => { - await fs.mkdir(path.join(tempDir, 'visibleDir')); - await fs.writeFile(path.join(tempDir, 'visibleDir', 'inner.txt'), 'content'); - await fs.writeFile(path.join(tempDir, 'visibleFile.txt'), 'content'); - await fs.writeFile(path.join(tempDir, '.hiddenFile'), 'secret'); - await fs.mkdir(path.join(tempDir, 'node_modules')); - - const tree = await buildFileTree(tempDir); - assert.strictEqual(tree.length, 2); - assert.deepStrictEqual(tree.map((entry) => entry.name), ['visibleDir', 'visibleFile.txt']); - - const dirEntry = tree.find((entry) => entry.type === 'directory'); - assert.ok(dirEntry, 'expected directory entry to be present'); - assert.deepStrictEqual(dirEntry.children.map((child) => child.name), ['inner.txt']); - }); -}); - -test('searchInDirectory finds matches and respects maximum results', async () => { - await withTempDir(async (tempDir) => { - await fs.writeFile(path.join(tempDir, 'first.txt'), 'TODO: write tests\nNothing here'); - await fs.mkdir(path.join(tempDir, 'subdir')); - await fs.writeFile(path.join(tempDir, 'subdir', 'second.txt'), 'Line 1\nSecond TODO item'); - await fs.writeFile(path.join(tempDir, 'subdir', 'third.txt'), 'TODO once more'); - - const results = await searchInDirectory(tempDir, 'TODO', 2); - assert.strictEqual(results.length, 2); - results.forEach((result) => { - assert.ok(result.content.includes('TODO')); - assert.ok(result.file.endsWith('.txt')); - }); - }); -}); - -test('detectFileEncoding reads UTF-8 files', async () => { - await withTempDir(async (tempDir) => { - const filePath = path.join(tempDir, 'hello.txt'); - const content = 'Hello, world!'; - await fs.writeFile(filePath, content, 'utf8'); - - const info = await detectFileEncoding(filePath); - assert.strictEqual(info.isUTF8, true); - assert.strictEqual(info.size, Buffer.byteLength(content)); - assert.ok(Buffer.isBuffer(info.buffer)); - assert.strictEqual(info.buffer.toString('utf8'), content); - }); -}); diff --git a/tests/safeStorageStore.test.js b/tests/safeStorageStore.test.js deleted file mode 100644 index 6264c3f..0000000 --- a/tests/safeStorageStore.test.js +++ /dev/null @@ -1,33 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); -const fs = require('node:fs'); -const os = require('node:os'); -const path = require('node:path'); - -const { createSafeStorageStore } = require('../src/main/cloud/safeStorageStore'); - -function fakeSafeStorage(available = true) { - return { - isEncryptionAvailable: () => available, - encryptString: (s) => Buffer.from(`enc:${Buffer.from(s).toString('base64')}`), - decryptString: (b) => Buffer.from(b.toString().replace(/^enc:/, ''), 'base64').toString(), - }; -} - -test('safeStorage store round trip, removal and unavailability', async () => { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ct-ss-')); - const store = createSafeStorageStore({ safeStorage: fakeSafeStorage(), userDataDir: dir }); - assert.equal(store.kind, 'safe_storage'); - assert.equal(await store.available(), true); - assert.equal(await store.load('p'), undefined); - const session = { baseUrl: 'https://api', profile: 'p', refreshToken: 'rt_secret_1234567890', savedAt: 'now' }; - await store.save('p', session); - const raw = fs.readFileSync(path.join(dir, 'cloud-credentials.json'), 'utf8'); - assert.ok(!raw.includes('rt_secret')); - assert.deepEqual(await store.load('p'), session); - assert.equal(await store.remove('p'), true); - assert.equal(await store.remove('p'), false); - assert.equal(fs.existsSync(path.join(dir, 'cloud-credentials.json')), false); - const off = createSafeStorageStore({ safeStorage: fakeSafeStorage(false), userDataDir: dir }); - assert.equal(await off.available(), false); -}); diff --git a/tests/stateManager.test.js b/tests/stateManager.test.js deleted file mode 100644 index d49ed95..0000000 --- a/tests/stateManager.test.js +++ /dev/null @@ -1,89 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); - -test('restoreState syncs restored workspace into SearchManager', async () => { - const searchManager = { - setWorkspacePathCalls: [], - setWorkspacePath(workspacePath) { - this.setWorkspacePathCalls.push(workspacePath); - } - }; - - const watchWorkspaceCalls = []; - - const fileOpsManager = { - currentWorkspacePath: null, - updateWorkspaceUICalls: [], - updateWorkspaceUI(folderName, fileTree) { - this.updateWorkspaceUICalls.push({ folderName, fileTree }); - } - }; - - global.window = { - api: { - async invoke(channel, ...args) { - if (channel === 'load-app-state') { - return { - success: true, - state: { - version: '1.0.0', - timestamp: new Date().toISOString(), - tabs: [], - workspacePath: '/tmp/demo-workspace' - } - }; - } - - if (channel === 'watch-workspace') { - assert.deepStrictEqual(args, ['/tmp/demo-workspace']); - watchWorkspaceCalls.push(args[0]); - return { success: true }; - } - - if (channel === 'get-file-tree') { - assert.deepStrictEqual(args, ['/tmp/demo-workspace']); - return { - success: true, - fileTree: [{ name: 'README.md', path: '/tmp/demo-workspace/README.md', type: 'file' }] - }; - } - - throw new Error(`Unexpected invoke channel: ${channel}`); - } - }, - uiController: { - fileOpsManager, - searchManager - } - }; - - const StateManager = require('../src/renderer/managers/StateManager'); - - const stateManager = new StateManager( - { - openTabs: new Map(), - tabsContainer: { appendChild() {} }, - showEditor() {}, - switchToTab: async () => {}, - tabIdCounter: 0 - }, - { editor: null }, - {} - ); - - const restored = await stateManager.restoreState(); - - assert.equal(restored, true); - assert.equal(fileOpsManager.currentWorkspacePath, '/tmp/demo-workspace'); - assert.deepStrictEqual(fileOpsManager.updateWorkspaceUICalls, [ - { - folderName: 'demo-workspace', - fileTree: [{ name: 'README.md', path: '/tmp/demo-workspace/README.md', type: 'file' }] - } - ]); - assert.deepStrictEqual(searchManager.setWorkspacePathCalls, ['/tmp/demo-workspace']); - assert.deepStrictEqual(watchWorkspaceCalls, ['/tmp/demo-workspace']); - - delete require.cache[require.resolve('../src/renderer/managers/StateManager')]; - delete global.window; -}); diff --git a/tests/uiControllerSearch.test.js b/tests/uiControllerSearch.test.js deleted file mode 100644 index e8ddc9d..0000000 --- a/tests/uiControllerSearch.test.js +++ /dev/null @@ -1,65 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); - -const UIController = require('../src/renderer/UIController'); - -function sleep(ms) { - return new Promise((resolve) => setTimeout(resolve, ms)); -} - -test('openSearchResult keeps the search sidebar active', async () => { - let showExplorerCalls = 0; - let jumpedToLine = null; - - global.window = { - api: { - async invoke(channel, ...args) { - if (channel === 'read-file') { - assert.deepStrictEqual(args, ['/tmp/demo.txt']); - return { - success: true, - fileName: 'demo.txt', - content: 'line 1\nline 2\nline 3' - }; - } - - throw new Error(`Unexpected invoke channel: ${channel}`); - } - } - }; - - const fakeController = { - notificationManager: { - showSuccess() {}, - showError() {}, - showWarning() {}, - async showEncodingWarningDialog() { - return 'yes'; - } - }, - fileOpsManager: { - openFileInTab(filePath, content, fileName) { - assert.equal(filePath, '/tmp/demo.txt'); - assert.equal(fileName, 'demo.txt'); - assert.equal(content, 'line 1\nline 2\nline 3'); - return 'tab_1'; - } - }, - editorManager: { - jumpToLine(lineNumber) { - jumpedToLine = lineNumber; - } - }, - showExplorer() { - showExplorerCalls += 1; - } - }; - - await UIController.prototype.openSearchResult.call(fakeController, '/tmp/demo.txt', 2); - await sleep(250); - - assert.equal(showExplorerCalls, 0); - assert.equal(jumpedToLine, 2); - - delete global.window; -}); diff --git a/tests/updaterHandlers.test.js b/tests/updaterHandlers.test.js deleted file mode 100644 index ebea155..0000000 --- a/tests/updaterHandlers.test.js +++ /dev/null @@ -1,202 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); -const path = require('node:path'); -const Module = require('node:module'); - -function withModuleMocks(mocks, callback) { - const originalLoad = Module._load; - Module._load = function (request, parent, isMain) { - if (Object.prototype.hasOwnProperty.call(mocks, request)) { - return mocks[request]; - } - return originalLoad.apply(this, arguments); - }; - try { - return callback(); - } finally { - Module._load = originalLoad; - } -} - -test('updater handlers load/save channel and gate checks in dev mode', async (t) => { - const handlers = new Map(); - const readFileMock = t.mock.fn(async () => JSON.stringify({ channel: 'beta' })); - const writeFileMock = t.mock.fn(async () => {}); - const appendFileMock = t.mock.fn(async () => {}); - - const autoUpdaterStub = { - allowPrerelease: false, - channel: 'latest', - autoDownload: false, - autoInstallOnAppQuit: false, - on: t.mock.fn(), - checkForUpdates: t.mock.fn(async () => ({ updateInfo: null })), - quitAndInstall: t.mock.fn() - }; - - const electronStub = { - ipcMain: { - handle: (channel, handler) => handlers.set(channel, handler) - }, - app: { - isPackaged: false, - getPath: () => '/tmp/test-user-data' - } - }; - - const modulePath = path.join(__dirname, '../src/main/ipc/updaterHandlers.js'); - const { setupUpdaterHandlers } = withModuleMocks({ - electron: electronStub, - 'electron-updater': { autoUpdater: autoUpdaterStub }, - fs: { - promises: { - readFile: (...args) => readFileMock(...args), - writeFile: (...args) => writeFileMock(...args), - appendFile: (...args) => appendFileMock(...args) - } - } - }, () => { - delete require.cache[modulePath]; - return require(modulePath); - }); - - setupUpdaterHandlers({ isDestroyed: () => false, webContents: { send: () => {} } }); - - const getSettings = await handlers.get('updater-get-settings')(); - assert.equal(getSettings.success, true); - assert.equal(getSettings.settings.channel, 'beta'); - assert.equal(autoUpdaterStub.allowPrerelease, true); - assert.equal(autoUpdaterStub.channel, 'beta'); - - const setChannel = await handlers.get('updater-set-channel')(null, 'main'); - assert.equal(setChannel.success, true); - assert.equal(setChannel.settings.channel, 'main'); - assert.equal(autoUpdaterStub.allowPrerelease, false); - assert.equal(autoUpdaterStub.channel, 'latest'); - assert.equal(writeFileMock.mock.calls.length > 0, true); - - const checkNow = await handlers.get('updater-check-now')(); - assert.equal(checkNow.success, false); - assert.match(checkNow.error, /packaged builds/i); -}); - -test('setupAutoUpdater runs initial check when packaged', async (t) => { - const autoUpdaterStub = { - allowPrerelease: false, - channel: 'latest', - autoDownload: false, - autoInstallOnAppQuit: false, - on: t.mock.fn(), - checkForUpdates: t.mock.fn(async () => ({ updateInfo: { version: '1.0.1' } })), - quitAndInstall: t.mock.fn() - }; - - const electronStub = { - ipcMain: { - handle: () => {} - }, - app: { - isPackaged: true, - getPath: () => '/tmp/test-user-data' - } - }; - - const timeoutMock = t.mock.method(global, 'setTimeout', (fn) => { - fn(); - return 0; - }); - - const modulePath = path.join(__dirname, '../src/main/ipc/updaterHandlers.js'); - const { setupAutoUpdater } = withModuleMocks({ - electron: electronStub, - 'electron-updater': { autoUpdater: autoUpdaterStub }, - fs: { - promises: { - readFile: async () => JSON.stringify({ channel: 'main' }), - writeFile: async () => {}, - appendFile: async () => {} - } - } - }, () => { - delete require.cache[modulePath]; - return require(modulePath); - }); - - await setupAutoUpdater({ isDestroyed: () => false, webContents: { send: () => {} } }); - assert.equal(autoUpdaterStub.checkForUpdates.mock.calls.length, 1); - - timeoutMock.mock.restore(); -}); - -test('setupAutoUpdater emits backend release tag when backend check uses cached data', async () => { - const sentEvents = []; - const backendUpdaterPath = path.join(__dirname, '../src/main/utils/backendUpdater.js'); - - const autoUpdaterStub = { - allowPrerelease: false, - channel: 'latest', - autoDownload: false, - autoInstallOnAppQuit: false, - on: () => {}, - checkForUpdates: async () => ({ updateInfo: null }), - quitAndInstall: () => {} - }; - - const electronStub = { - ipcMain: { - handle: () => {} - }, - app: { - isPackaged: false, - getPath: () => '/tmp/test-user-data' - } - }; - - require.cache[backendUpdaterPath] = { - id: backendUpdaterPath, - filename: backendUpdaterPath, - loaded: true, - exports: { - checkAndUpdateBackendBinary: async () => ({ - success: true, - updated: false, - releaseTag: 'v1.2.3', - stale: true, - reason: 'cached' - }) - } - }; - - const modulePath = path.join(__dirname, '../src/main/ipc/updaterHandlers.js'); - const { setupAutoUpdater } = withModuleMocks({ - electron: electronStub, - 'electron-updater': { autoUpdater: autoUpdaterStub }, - fs: { - promises: { - readFile: async () => JSON.stringify({ channel: 'main' }), - writeFile: async () => {}, - appendFile: async () => {} - } - }, - }, () => { - delete require.cache[modulePath]; - return require(modulePath); - }); - - await setupAutoUpdater({ - isDestroyed: () => false, - webContents: { - send: (_channel, payload) => { - sentEvents.push(payload); - } - } - }); - - await new Promise((resolve) => setImmediate(resolve)); - - const backendResultEvent = sentEvents.find((event) => event && event.type === 'backend-update-not-available'); - assert.ok(backendResultEvent); - assert.equal(backendResultEvent.info.releaseTag, 'v1.2.3'); - - delete require.cache[backendUpdaterPath]; -}); diff --git a/tests/version.test.js b/tests/version.test.js deleted file mode 100644 index 989e4ef..0000000 --- a/tests/version.test.js +++ /dev/null @@ -1,54 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); - -const pkg = require('../package.json'); - -// The release scheme these tests pin down: -// - stable releases are X.Y.Z -// - prereleases are X.Y.Z-beta.N and nothing else, because electron-builder -// names the update manifest after the prerelease identifier and `beta` is -// the only one the in-app channel selector reads -// - the git tag is v, checked again by the release workflow -// -// A past release shipped as 5.0.1-a, which produced an `a.yml` manifest no -// channel ever looked at. These assertions exist so that cannot recur. - -const SEMVER = /^(\d+)\.(\d+)\.(\d+)(?:-(beta)\.(\d+))?$/; - -test('package version follows the release scheme', () => { - const match = SEMVER.exec(pkg.version); - - assert.ok( - match, - `package.json version "${pkg.version}" must be X.Y.Z or X.Y.Z-beta.N` - ); -}); - -test('a prerelease version uses the beta identifier', () => { - if (!pkg.version.includes('-')) return; - - assert.match( - pkg.version, - /-beta\.\d+$/, - `prerelease "${pkg.version}" would publish a manifest no update channel reads` - ); -}); - -test('the GitHub publisher targets the coretrace-gui repo and publishes directly', () => { - const publish = Array.isArray(pkg.build.publish) ? pkg.build.publish[0] : pkg.build.publish; - - assert.equal(publish.provider, 'github'); - assert.equal(publish.owner, 'CoreTrace'); - assert.equal(publish.repo, 'coretrace-gui'); - // Left unset, electron-builder creates a draft that someone has to publish by - // hand — which is how v5.0.1 sat unreleased for months. - assert.equal(publish.releaseType, 'release'); -}); - -test('macOS builds ship the zip electron-updater needs alongside the dmg', () => { - const targets = pkg.build.mac.target; - - assert.ok(Array.isArray(targets), 'mac.target must list every artifact'); - assert.ok(targets.includes('dmg'), 'mac.target must include dmg'); - assert.ok(targets.includes('zip'), 'electron-updater cannot update from a dmg alone'); -});