Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -170,4 +170,5 @@ OPUS_ANALYSIS_AND_IDEAS.md
# Auto Claude generated files
.security-key
/shared_docs
Agents.md
Agents.md
logs/security/
88 changes: 88 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,91 @@
## Unreleased - WSL2/WSLg Compatibility
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Use an H1 for the first heading.

Line 1: markdownlint MD041 expects the first heading to be H1.

📝 Proposed fix
-## Unreleased - WSL2/WSLg Compatibility
+# Unreleased - WSL2/WSLg Compatibility
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
## Unreleased - WSL2/WSLg Compatibility
# Unreleased - WSL2/WSLg Compatibility
🧰 Tools
🪛 markdownlint-cli2 (0.18.1)

1-1: First line in a file should be a top-level heading

(MD041, first-line-heading, first-line-h1)

🤖 Prompt for AI Agents
In `@CHANGELOG.md` at line 1, Change the first heading in CHANGELOG.md from a
level-2 heading "## Unreleased - WSL2/WSLg Compatibility" to a level-1 heading
by replacing "##" with "#" so the file starts with a top-level H1 (e.g., "#
Unreleased - WSL2/WSLg Compatibility") to satisfy markdownlint MD041.


### ✨ New Platform Support

- **Full WSL2/WSLg compatibility** - Auto Claude Electron desktop app now runs natively on Windows 11 WSL2 with WSLg (Windows Subsystem for Linux Graphics)

- Added comprehensive WSL2 setup guide and troubleshooting documentation ([guides/WSL2_SETUP.md](guides/WSL2_SETUP.md))

### 🛠️ Technical Improvements

**Lazy Initialization Pattern:**
- Implemented lazy initialization for all Electron app access to handle delayed initialization on WSL2
- Replaced direct `@electron-toolkit/utils` usage with safe platform detection
- Added Proxy-based lazy initialization for singleton services (ProjectStore, ChangelogService, TitleGenerator)

**Sentry Integration:**
- Fixed Sentry initialization timing with safe version detection and package.json fallback
- Sentry now initializes before app.whenReady() while remaining WSL2-compatible
- Temporarily disabled Sentry environment propagation to subprocesses for WSL2 compatibility

**electron-log:**
- Disabled preload script to avoid WSL2 path resolution issues
- Main logging functionality preserved and working correctly

**electron-updater:**
- Implemented lazy loading pattern with module-level variable
- Added null checks to all autoUpdater access functions
- Changed `getCurrentVersion()` to use `app.getVersion()` instead of autoUpdater for better reliability

**Settings Management:**
- Fixed settings path resolution by using `getSettingsPath()` function calls instead of module-level constants

**Build Configuration:**
- Ensured CJS format with `.js` extensions for main and preload bundles
- Fixed preload script path from `.mjs` to `.js` to match build output
- Externalized Sentry packages to avoid bundling issues

**Backend Path Detection:**
- Added safe `app.getAppPath()` access with try-catch for WSL2 compatibility
- Multiple fallback paths for backend detection

### 🐛 Bug Fixes

- Fixed "app.getVersion() is not a function" errors on WSL2 startup
- Fixed "autoUpdater is not defined" errors when accessing update functions
- Fixed "settingsPath is not defined" error in setup wizard
- Fixed preload script "index.mjs" not found error
- Fixed Sentry initialization timing error: "SDK should be initialized before app ready event"
- Fixed electron-log preload script path resolution failures
- Fixed module-level constant initialization issues on WSL2
- Fixed singleton service initialization timing on WSL2

### 📚 Documentation

- Added [WSL2_SETUP.md](guides/WSL2_SETUP.md) with:
- Prerequisites and installation steps
- Step-by-step WSLg verification guide
- Comprehensive troubleshooting section
- Technical explanations of all fixes
- Architecture patterns for WSL2 compatibility
- Testing checklist for WSL2 development

### 🔧 Files Changed

**Main Process:**
- `apps/frontend/src/main/index.ts` - Lazy platform detection, safe app initialization
- `apps/frontend/src/main/sentry.ts` - Safe version detection with fallbacks
- `apps/frontend/src/main/app-logger.ts` - Disabled preload for WSL2
- `apps/frontend/src/main/app-updater.ts` - Lazy loading with null checks
- `apps/frontend/src/main/project-store.ts` - Proxy-based lazy initialization
- `apps/frontend/src/main/changelog/changelog-service.ts` - Proxy-based lazy initialization, safe path detection
- `apps/frontend/src/main/title-generator.ts` - Proxy-based lazy initialization, safe path detection
- `apps/frontend/src/main/env-utils.ts` - Disabled Sentry subprocess env for WSL2

**IPC Handlers:**
- `apps/frontend/src/main/ipc-handlers/settings-handlers.ts` - Function-based path resolution
- `apps/frontend/src/main/ipc-handlers/context/utils.ts` - WSL2-safe path handling
- `apps/frontend/src/main/ipc-handlers/project-handlers.ts` - WSL2-safe initialization

**Build Configuration:**
- `apps/frontend/electron.vite.config.ts` - CJS format, external dependencies
- `apps/frontend/package.json` - Updated for WSL2 compatibility

**Other:**
- `.gitignore` - Added logs/security/ exclusion

---

## 2.7.4 - Terminal & Workflow Enhancements

### ✨ New Features
Expand Down
4 changes: 3 additions & 1 deletion apps/backend/agents/tools_pkg/tools/qa.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
from typing import Any

from core.file_utils import write_json_atomic
from spec.validate_pkg.auto_fix import auto_fix_plan

try:
from claude_agent_sdk import tool
Expand Down Expand Up @@ -159,6 +158,9 @@ async def update_qa_status(args: dict[str, Any]) -> dict[str, Any]:

except json.JSONDecodeError as e:
# Attempt to auto-fix the plan and retry
# Lazy import to avoid circular dependency
from spec.validate_pkg.auto_fix import auto_fix_plan

if auto_fix_plan(spec_dir):
# Retry after fix
try:
Expand Down
4 changes: 3 additions & 1 deletion apps/backend/agents/tools_pkg/tools/subtask.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
from typing import Any

from core.file_utils import write_json_atomic
from spec.validate_pkg.auto_fix import auto_fix_plan

try:
from claude_agent_sdk import tool
Expand Down Expand Up @@ -142,6 +141,9 @@ async def update_subtask_status(args: dict[str, Any]) -> dict[str, Any]:

except json.JSONDecodeError as e:
# Attempt to auto-fix the plan and retry
# Lazy import to avoid circular dependency
from spec.validate_pkg.auto_fix import auto_fix_plan

if auto_fix_plan(spec_dir):
# Retry after fix
try:
Expand Down
37 changes: 17 additions & 20 deletions apps/frontend/electron.vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,31 +20,24 @@ const sentryDefines = {
export default defineConfig({
main: {
define: sentryDefines,
plugins: [externalizeDepsPlugin({
// Bundle these packages into the main process (they won't be in node_modules in packaged app)
exclude: [
'uuid',
'chokidar',
'kuzu',
'electron-updater',
'@electron-toolkit/utils',
// Sentry and its transitive dependencies (opentelemetry -> debug -> ms)
'@sentry/electron',
'@sentry/core',
'@sentry/node',
'@sentry/utils',
'@opentelemetry/instrumentation',
'debug',
'ms'
]
})],
plugins: [externalizeDepsPlugin()],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🌐 Web query:

electron-vite v5 externalizeDepsPlugin default behavior exclude option documentation

💡 Result:

Short answer:

  • In electron-vite v5 the externalizeDepsPlugin is deprecated; dependency externalization is enabled by default and configured via build.externalizeDeps. [1][2]
  • Default behavior: electron and Node built-ins are always externalized; for main & preload processes package.json "dependencies" are externalized (not bundled) while renderer dependencies are bundled. [1]
  • The exclude option (build.externalizeDeps.exclude) is an array of package names you want to bundle (i.e., remove from automatic externalization). Example: build.externalizeDeps.exclude: ['foo'] will cause 'foo' to be bundled. [1][3]

Sources:
[1] electron-vite — Dependency Handling / Config (externalizeDeps docs).
[2] electron-vite — Migration from v4 (externalizeDepsPlugin deprecated).
[3] electron-vite — Troubleshooting example showing externalizeDepsPlugin({ exclude: ['foo'] }).


🏁 Script executed:

# First, let's examine the electron.vite.config.ts file to understand the context
find . -name "electron.vite.config.ts" -type f | head -5

Repository: AndyMik90/Auto-Claude

Length of output: 104


🏁 Script executed:

# Check the actual file content to understand the changes
if [ -f "apps/frontend/electron.vite.config.ts" ]; then
  cat -n "apps/frontend/electron.vite.config.ts"
fi

Repository: AndyMik90/Auto-Claude

Length of output: 3678


Migrate away from deprecated externalizeDepsPlugin in electron-vite v5.

The externalizeDepsPlugin is deprecated in electron-vite v5; dependency externalization is now configured via build.externalizeDeps instead. While the plugin may still work for compatibility, lines 23 and 45 should migrate to the modern configuration approach. Additionally, the preload build (line 45) lacks an explicit external list—consider adding one to match the main build's approach, or explicitly configure which packages should be externalized via build.externalizeDeps.exclude to ensure preload dependencies are handled consistently.

🤖 Prompt for AI Agents
In `@apps/frontend/electron.vite.config.ts` at line 23, Replace the deprecated
externalizeDepsPlugin usage by moving dependency externalization into the Vite
build config: remove externalizeDepsPlugin() from the plugins array and add a
build.externalizeDeps object for the main build (the same scope where plugins
currently include externalizeDepsPlugin), specifying exclude/include as needed;
for the preload build (the secondary build configuration referenced in the file)
add a matching build.externalizeDeps or an explicit build.rollupOptions.external
list so preload dependencies are handled consistently with the main build.
Target symbols: externalizeDepsPlugin, build.externalizeDeps, and the preload
build configuration block.

build: {
rollupOptions: {
input: {
index: resolve(__dirname, 'src/main/index.ts')
},
// Only node-pty needs to be external (native module rebuilt by electron-builder)
external: ['@lydell/node-pty']
output: {
format: 'cjs',
entryFileNames: '[name].js'
},
// External modules that should not be bundled
external: [
'@lydell/node-pty', // Native module
'@sentry/electron', // Sentry main (causes WSL2 issues when bundled)
'@sentry/core',
'@sentry/node',
'@electron-toolkit/utils' // Electron utilities (access app before ready)
]
Comment on lines +29 to +40
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
fd -a -t f 'package.json' -x python3 - <<'PY'
import json, sys
path = sys.argv[1]
try:
    with open(path, "r", encoding="utf-8") as f:
        data = json.load(f)
    module_type = data.get('type', '(unset)')
    print(f"{path}: type={module_type}")
except Exception as e:
    print(f"{path}: ERROR - {e}")
PY

Repository: AndyMik90/Auto-Claude

Length of output: 151


🏁 Script executed:

cat apps/frontend/electron.vite.config.ts

Repository: AndyMik90/Auto-Claude

Length of output: 3006


🏁 Script executed:

fd 'package.json' -t f | head -20

Repository: AndyMik90/Auto-Claude

Length of output: 104


🏁 Script executed:

cat package.json 2>/dev/null | grep -E '"type"|"name"' || echo "No root package.json or type field"

Repository: AndyMik90/Auto-Claude

Length of output: 108


🏁 Script executed:

cat apps/frontend/package.json 2>/dev/null | grep -E '"type"|"name"' || echo "No frontend package.json or type field"

Repository: AndyMik90/Auto-Claude

Length of output: 163


Fix CJS output naming for "type": "module" environment.

The apps/frontend/package.json has "type": "module" set, which means Node.js and Electron will interpret .js files as ESM. With format: 'cjs' and entryFileNames: '[name].js', the CommonJS output will be misinterpreted as ES modules, causing runtime failures.

Change both main and preload output configuration to use .cjs extension:

Required fix

For main build (lines 29-31):

         output: {
           format: 'cjs',
-          entryFileNames: '[name].js'
+          entryFileNames: '[name].cjs'
         },

For preload build (apply same change):

         output: {
           format: 'cjs',
-          entryFileNames: '[name].js'
+          entryFileNames: '[name].cjs'
         }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
output: {
format: 'cjs',
entryFileNames: '[name].js'
},
// External modules that should not be bundled
external: [
'@lydell/node-pty', // Native module
'@sentry/electron', // Sentry main (causes WSL2 issues when bundled)
'@sentry/core',
'@sentry/node',
'@electron-toolkit/utils' // Electron utilities (access app before ready)
]
output: {
format: 'cjs',
entryFileNames: '[name].cjs'
},
// External modules that should not be bundled
external: [
'@lydell/node-pty', // Native module
'@sentry/electron', // Sentry main (causes WSL2 issues when bundled)
'@sentry/core',
'@sentry/node',
'@electron-toolkit/utils' // Electron utilities (access app before ready)
]
🤖 Prompt for AI Agents
In `@apps/frontend/electron.vite.config.ts` around lines 29 - 40, The build
outputs use format: 'cjs' with entryFileNames: '[name].js' which conflicts with
apps/frontend/package.json "type": "module" (causing .js to be treated as ESM);
update the Vite/Electron build config where output.format === 'cjs' (both the
main build and the preload build) to use entryFileNames: '[name].cjs' (and any
related asset naming if present) so CommonJS bundles get a .cjs extension and
are correctly loaded by Electron/Node.

}
}
},
Expand All @@ -54,6 +47,10 @@ export default defineConfig({
rollupOptions: {
input: {
index: resolve(__dirname, 'src/preload/index.ts')
},
output: {
format: 'cjs',
entryFileNames: '[name].js'
}
}
}
Expand Down
3 changes: 3 additions & 0 deletions apps/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,13 @@
"node": ">=24.0.0",
"npm": ">=10.0.0"
},
"//": "NOTE: Use 'dev:wsl2' scripts for WSL2 environments. The --no-sandbox flag disables Chromium's sandbox security feature and should ONLY be used in WSL2. Regular 'dev' scripts are safe for macOS/Windows/Linux. Production builds never use --no-sandbox.",
"scripts": {
"postinstall": "node scripts/postinstall.cjs",
"dev": "electron-vite dev",
"dev:debug": "cross-env DEBUG=true electron-vite dev",
"dev:wsl2": "node scripts/check-wsl2.cjs && electron-vite dev -- --no-sandbox",
"dev:debug:wsl2": "node scripts/check-wsl2.cjs && cross-env DEBUG=true electron-vite dev -- --no-sandbox",
Comment on lines +21 to +27
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Good approach: Separate WSL2 scripts isolate the security-sensitive flag.

The dedicated dev:wsl2 and dev:debug:wsl2 scripts with the check-wsl2.cjs guard ensure --no-sandbox is only used in appropriate environments, keeping the regular dev scripts safe for macOS/Windows/Linux.

Consider adding WSL2 variants for MCP scripts as well for consistency:

     "dev:mcp": "electron-vite dev -- --remote-debugging-port=9222",
+    "dev:mcp:wsl2": "node scripts/check-wsl2.cjs && electron-vite dev -- --no-sandbox --remote-debugging-port=9222",
🤖 Prompt for AI Agents
In `@apps/frontend/package.json` around lines 20 - 26, Add WSL2-specific variants
for the MCP dev scripts analogous to the existing electron dev scripts:
duplicate the existing MCP script names (e.g., "mcp:dev" and "mcp:dev:debug")
into new scripts like "mcp:dev:wsl2" and "mcp:dev:debug:wsl2" that run the same
commands but prefixed with node scripts/check-wsl2.cjs && and appended with --
--no-sandbox; ensure the new script names exactly mirror the pattern used by
"dev:wsl2" and "dev:debug:wsl2" so the guard and flag are applied only in WSL2
environments.

"dev:mcp": "electron-vite dev -- --remote-debugging-port=9222",
"build": "electron-vite build",
"start": "electron .",
Expand Down
78 changes: 78 additions & 0 deletions apps/frontend/scripts/check-wsl2.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/**
* WSL2 Detection Script
*
* Validates that the development environment is running in WSL2 before allowing
* --no-sandbox flag usage. This prevents accidental use of disabled Chromium
* sandbox outside of WSL2 environments where it's required.
*
* Usage: node scripts/check-wsl2.cjs
* Exit codes:
* 0 - Running in WSL2 (safe to use --no-sandbox)
* 1 - Not running in WSL2 (should not use --no-sandbox)
*/

const fs = require('fs');

/**
* Check if running in WSL2 environment
* @returns {boolean} true if in WSL2, false otherwise
*/
function isWSL2() {
// Method 1: Check WSL_DISTRO_NAME environment variable
if (process.env.WSL_DISTRO_NAME) {
return true;
}

// Method 2: Check /proc/version for WSL2 signature (Linux only)
if (process.platform === 'linux') {
try {
const versionInfo = fs.readFileSync('/proc/version', 'utf8').toLowerCase();
// WSL2 typically contains 'microsoft' and 'wsl2' in kernel version
if (versionInfo.includes('microsoft') && versionInfo.includes('wsl2')) {
return true;
}
// Older WSL2 versions might only have 'microsoft'
if (versionInfo.includes('microsoft')) {
return true;
}
} catch {
// /proc/version doesn't exist or can't be read
return false;
}
Comment on lines +26 to +41
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Avoid early return so later detection methods still run.

If /proc/version is unreadable, the function returns false and skips method 3 (wsl.exe interop), which can cause false negatives. Let the function fall through instead.

🛠️ Proposed fix
-    } catch {
-      // /proc/version doesn't exist or can't be read
-      return false;
-    }
+    } catch {
+      // /proc/version doesn't exist or can't be read
+      // fall through to other detection methods
+    }
🤖 Prompt for AI Agents
In `@apps/frontend/scripts/check-wsl2.cjs` around lines 26 - 41, The try/catch
around fs.readFileSync('/proc/version', 'utf8') inside the Linux branch
currently returns false in the catch, which causes the function to short-circuit
and skip the later wsl.exe interop check (method 3); remove the early return in
the catch so the function falls through to the subsequent detection logic (leave
the positive returns when versionInfo indicates WSL2 intact), e.g., replace the
catch body that returns false with an empty catch or a comment so method 3
(wsl.exe interop) still runs.

}

// Method 3: Check for WSL interop (wsl.exe in PATH)
if (process.platform === 'linux') {
try {
const { execSync } = require('child_process');
execSync('which wsl.exe', { stdio: 'ignore' });
return true;
} catch {
// wsl.exe not found
}
}

return false;
Comment on lines +20 to +55
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# First, find the platform module
find . -type f -name "*platform*" | grep -E "\.(ts|tsx|js)$" | head -20

Repository: AndyMik90/Auto-Claude

Length of output: 164


🏁 Script executed:

# Check directory structure of apps/frontend
ls -la apps/frontend/ 2>/dev/null || echo "Directory not found"

Repository: AndyMik90/Auto-Claude

Length of output: 1266


🏁 Script executed:

# Look for the script file
find . -type f -name "check-wsl2.cjs" 2>/dev/null

Repository: AndyMik90/Auto-Claude

Length of output: 103


🏁 Script executed:

# Read the platform module files to see what's exported
echo "=== apps/frontend/src/shared/platform.ts ===" && wc -l apps/frontend/src/shared/platform.ts

Repository: AndyMik90/Auto-Claude

Length of output: 149


🏁 Script executed:

# Check if there's a platform module in main/
ls -la apps/frontend/src/main/platform/ 2>/dev/null || echo "Not found"

Repository: AndyMik90/Auto-Claude

Length of output: 421


🏁 Script executed:

# Read the actual check-wsl2.cjs script
cat -n apps/frontend/scripts/check-wsl2.cjs

Repository: AndyMik90/Auto-Claude

Length of output: 3138


🏁 Script executed:

# Read the main platform module
head -60 apps/frontend/src/main/platform/index.ts

Repository: AndyMik90/Auto-Claude

Length of output: 1614


🏁 Script executed:

# Read shared platform module
cat -n apps/frontend/src/shared/platform.ts

Repository: AndyMik90/Auto-Claude

Length of output: 2080


🏁 Script executed:

# Read the rest of the main platform module
cat -n apps/frontend/src/main/platform/index.ts

Repository: AndyMik90/Auto-Claude

Length of output: 14717


🏁 Script executed:

# Search for isWSL2 in the codebase
rg "isWSL2" --type ts --type js --type cjs

Repository: AndyMik90/Auto-Claude

Length of output: 92


🏁 Script executed:

# Search for isWSL2 without file type filter
rg "isWSL2" -A 3

Repository: AndyMik90/Auto-Claude

Length of output: 1709


🏁 Script executed:

# Check if there's a built version or dist directory
find . -type d -name "dist" -o -name "build" | head -10

Repository: AndyMik90/Auto-Claude

Length of output: 47


🏁 Script executed:

# Check how other scripts import from platform module
ls -la apps/frontend/scripts/

Repository: AndyMik90/Auto-Claude

Length of output: 529


🏁 Script executed:

# Check package.json to see how scripts/cjs files use the platform module
head -100 apps/frontend/package.json | grep -A 20 "scripts"

Repository: AndyMik90/Auto-Claude

Length of output: 2332


🏁 Script executed:

# Check if there's a built/bundled version of platform module
find . -path "*/dist/*" -o -path "*/build/*" | grep platform | head -10

Repository: AndyMik90/Auto-Claude

Length of output: 47


🏁 Script executed:

# Check how postinstall.cjs or other scripts import from TypeScript modules
head -50 apps/frontend/scripts/postinstall.cjs

Repository: AndyMik90/Auto-Claude

Length of output: 1612


🏁 Script executed:

# Verify the exact differences in /proc/version checks between platform module and script
echo "=== Platform module check ===" && sed -n '95,108p' apps/frontend/src/main/platform/index.ts
echo "=== Script check ===" && sed -n '26,42p' apps/frontend/scripts/check-wsl2.cjs

Repository: AndyMik90/Auto-Claude

Length of output: 1182


🏁 Script executed:

# Check if platform module has build output or if it's directly imported
cat apps/frontend/tsconfig.json | head -50

Repository: AndyMik90/Auto-Claude

Length of output: 880


🏁 Script executed:

# Verify how env-utils.ts imports isWSL2 from platform module (TypeScript to TypeScript)
grep -A 5 "import.*isWSL2" apps/frontend/src/main/env-utils.ts

Repository: AndyMik90/Auto-Claude

Length of output: 243


Consolidate WSL2 detection into platform module; the refactor suggestion needs adjustment for CJS compatibility.

This script uses process.platform directly and duplicates detection logic that exists in the platform module. However, the platform module's isWSL2() function is incomplete—it only checks the environment variable and /proc/version for 'microsoft', but lacks the wsl.exe interop check (Method 3) present in this script.

To properly refactor:

  1. First, enhance apps/frontend/src/main/platform/index.ts to include all three detection methods (especially the wsl.exe check).
  2. Then, import and reuse that function in the script. Note that a direct TypeScript import won't work in CommonJS—you'll need either a CJS wrapper export or build the platform module for CommonJS consumption.

Also note the /proc/version check differs between implementations: the platform module checks for 'microsoft' only, while this script checks for both 'microsoft' and 'wsl2' with a fallback. Align these implementations when consolidating.

🤖 Prompt for AI Agents
In `@apps/frontend/scripts/check-wsl2.cjs` around lines 20 - 55, The isWSL2
detection must be consolidated: update the platform module's isWSL2() to include
all three checks (env var WSL_DISTRO_NAME, /proc/version matching 'microsoft'
and/or 'wsl2' with the same fallback logic as the script, and the wsl.exe
interop check using execSync('which wsl.exe')), then make that enhanced isWSL2
available to CommonJS consumers by exporting a CJS-compatible wrapper or
building a CJS build of the platform module; finally replace the duplicated
logic in the script with a require() of the CJS-compatible isWSL2 export so the
frontend script (CommonJS) reuses the single implementation.

}

// Main execution
const isWsl2 = isWSL2();

if (isWsl2) {
console.log('✓ WSL2 environment detected - --no-sandbox flag is safe to use');
process.exit(0);
} else {
console.error('✗ Not running in WSL2!');
console.error('');
console.error('The dev:wsl2 script is designed for WSL2 environments only.');
console.error('It disables Chromium sandbox (--no-sandbox) which is a security risk outside WSL2.');
console.error('');
console.error('Please use one of these alternatives:');
console.error(' • npm run dev - Development mode with Chromium sandbox enabled');
console.error(' • npm run dev:debug - Debug mode with Chromium sandbox enabled');
console.error('');
console.error('If you are in WSL2 but seeing this error, check:');
console.error(' 1. WSL_DISTRO_NAME environment variable is set');
console.error(' 2. Running WSL2 (not WSL1): wsl.exe --list --verbose');
process.exit(1);
}
10 changes: 7 additions & 3 deletions apps/frontend/src/main/app-logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import os from 'os';

// Configure electron-log (wrapped in try-catch for re-import scenarios in tests)
try {
log.initialize();
log.initialize({ preload: false }); // Disable preload to avoid WSL2 path issues
} catch {
// Already initialized, ignore
}
Expand All @@ -42,15 +42,19 @@ log.transports.console.format = '[{h}:{i}:{s}] [{level}] {text}';
// Determine if this is a beta version
function isBetaVersion(): boolean {
try {
// WSL2 compatibility: app may not be ready yet at module load time
if (!app || typeof app.getVersion !== 'function') {
return false;
}
const version = app.getVersion();
return version.includes('-beta') || version.includes('-alpha') || version.includes('-rc');
} catch (error) {
log.warn('Failed to detect beta version:', error);
// Silently fail if app is not ready yet - this is called at module load time
return false;
Comment on lines +45 to 53
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Beta logging may never enable if app isn’t ready at module load.

Line 45-63: If app isn’t ready, isBetaVersion() returns false and the debug level is never re-applied. Consider re-checking once app.whenReady() resolves to keep beta diagnostics on WSL2/test setups.

♻️ Proposed refactor
-// Enhanced logging for beta versions (lazy check - safe for WSL2)
-if (isBetaVersion()) {
-  log.transports.file.level = 'debug';
-  log.info('Beta version detected - enhanced logging enabled');
-} else {
-  log.transports.file.level = 'info';
-}
+const enableBetaLogging = () => {
+  if (isBetaVersion()) {
+    log.transports.file.level = 'debug';
+    log.info('Beta version detected - enhanced logging enabled');
+  } else {
+    log.transports.file.level = 'info';
+  }
+};
+
+enableBetaLogging();
+if (app && typeof app.whenReady === 'function') {
+  app.whenReady().then(enableBetaLogging).catch(() => {
+    // ignore: fallback to default log level
+  });
+}

Also applies to: 57-63

🤖 Prompt for AI Agents
In `@apps/frontend/src/main/app-logger.ts` around lines 45 - 53, isBetaVersion()
currently returns false if Electron's app isn't ready at module load, which
prevents beta debug level from being reapplied later; update the logic so when
app is not ready you attach a single app.whenReady().then(...) callback that
re-evaluates isBetaVersion() and re-applies the debug/log level (the same code
path used when isBetaVersion() returns true initially). Use the isBetaVersion()
function name and app.whenReady() to locate spots to add the retry/rehydration
and ensure you don't add duplicate listeners (e.g., only schedule once or remove
the listener after running).

}
}

// Enhanced logging for beta versions
// Enhanced logging for beta versions (lazy check - safe for WSL2)
if (isBetaVersion()) {
log.transports.file.level = 'debug';
log.info('Beta version detected - enhanced logging enabled');
Expand Down
Loading
Loading