fix: add Windows/WSL compatibility fixes from issue #177

- Add WSL and Windows detection to environment detector
- Implement safe interactive wrapper for handling non-TTY environments
- Add non-interactive fallback for hive-mind wizard
- Improve error messages for raw mode failures
- Auto-detect and recommend --no-interactive flag for WSL/Windows
- Add graceful degradation when raw mode is not supported
This commit is contained in:
rUv committed 2025-07-09 15:55:10 +00:00
1 parent ac01d4e108
commit 52ecafb1c1
7 files changed
+258 -44

No files matched your search

Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -1,7 +1,7 @@
const chalk = require('chalk');
const path = require('path');
const fs = require('fs');
const sqlite3 = require('sqlite3').verbose();
const Database = require('better-sqlite3');
// Interactive Wizard Implementation
async function runInteractiveWizard() {
+81 -43
View File
@@ -13,6 +13,7 @@ import chalk from 'chalk';
import ora from 'ora';
import { args, cwd, exit, writeTextFile, readTextFile, mkdirAsync } from '../node-compat.js';
import { isInteractive, isRawModeSupported, warnNonInteractive, checkNonInteractiveAuth } from '../utils/interactive-detector.js';
import { safeInteractive, nonInteractiveProgress, nonInteractiveSelect } from '../utils/safe-interactive.js';
// Import SQLite for persistence
import Database from 'better-sqlite3';
@@ -222,50 +223,87 @@ async function initHiveMind(flags) {
/**
* Interactive wizard for hive mind operations
*/
async function hiveMindWizard() {
console.log(chalk.yellow('\n🧙 Hive Mind Interactive Wizard\n'));
const { action } = await inquirer.prompt([
{
type: 'list',
name: 'action',
message: 'What would you like to do?',
choices: [
{ name: '🐝 Create new swarm', value: 'spawn' },
{ name: '📊 View swarm status', value: 'status' },
{ name: '🧠 Manage collective memory', value: 'memory' },
{ name: '🤝 View consensus decisions', value: 'consensus' },
{ name: '📈 Performance metrics', value: 'metrics' },
{ name: '🔧 Configure hive mind', value: 'config' },
{ name: '❌ Exit', value: 'exit' }
]
// Wrapped wizard function that handles non-interactive environments
const hiveMindWizard = safeInteractive(
// Interactive version
async function(flags = {}) {
console.log(chalk.yellow('\n🧙 Hive Mind Interactive Wizard\n'));
const { action } = await inquirer.prompt([
{
type: 'list',
name: 'action',
message: 'What would you like to do?',
choices: [
{ name: '🐝 Create new swarm', value: 'spawn' },
{ name: '📊 View swarm status', value: 'status' },
{ name: '🧠 Manage collective memory', value: 'memory' },
{ name: '🤝 View consensus decisions', value: 'consensus' },
{ name: '📈 Performance metrics', value: 'metrics' },
{ name: '🔧 Configure hive mind', value: 'config' },
{ name: '❌ Exit', value: 'exit' }
]
}
]);
switch (action) {
case 'spawn':
await spawnSwarmWizard();
break;
case 'status':
await showStatus({});
break;
case 'memory':
await manageMemoryWizard();
break;
case 'consensus':
await showConsensus({});
break;
case 'metrics':
await showMetrics({});
break;
case 'config':
await configureWizard();
break;
case 'exit':
console.log(chalk.gray('Exiting wizard...'));
break;
}
]);
switch (action) {
case 'spawn':
await spawnSwarmWizard();
break;
case 'status':
await showStatus({});
break;
case 'memory':
await manageMemoryWizard();
break;
case 'consensus':
await showConsensus({});
break;
case 'metrics':
await showMetrics({});
break;
case 'config':
await configureWizard();
break;
case 'exit':
console.log(chalk.gray('Exiting wizard...'));
break;
},
// Non-interactive fallback
async function(flags = {}) {
console.log(chalk.yellow('\n🧙 Hive Mind - Non-Interactive Mode\n'));
// Default to creating a swarm with sensible defaults
console.log(chalk.cyan('Creating new swarm with default settings...'));
console.log(chalk.gray('Use command-line flags to customize:'));
console.log(chalk.gray(' --objective "Your task" Set swarm objective'));
console.log(chalk.gray(' --queen-type strategic Set queen type'));
console.log(chalk.gray(' --max-workers 8 Set worker count'));
console.log();
const objective = flags.objective || 'General task coordination';
const config = {
name: flags.name || `swarm-${Date.now()}`,
queenType: flags.queenType || flags['queen-type'] || 'strategic',
maxWorkers: parseInt(flags.maxWorkers || flags['max-workers'] || '8'),
consensusAlgorithm: flags.consensus || 'majority',
autoScale: flags.autoScale || flags['auto-scale'] || false,
encryption: flags.encryption || false
};
await spawnSwarm([objective], {
...flags,
name: config.name,
queenType: config.queenType,
maxWorkers: config.maxWorkers,
consensusAlgorithm: config.consensusAlgorithm,
autoScale: config.autoScale,
encryption: config.encryption,
nonInteractive: true
});
}
}
);
/**
* Spawn swarm wizard
@@ -1179,7 +1217,7 @@ export async function hiveMindCommand(args, flags) {
break;
case 'wizard':
await hiveMindWizard();
await hiveMindWizard(flags);
break;
case 'help':
+2
View File
@@ -36,6 +36,8 @@ export async function handleRawModeError(
console.log();
console.log(chalk.cyan('Common causes:'));
console.log(chalk.gray('• VS Code integrated terminal'));
console.log(chalk.gray('• WSL (Windows Subsystem for Linux)'));
console.log(chalk.gray('• Native Windows terminals'));
console.log(chalk.gray('• CI/CD environments'));
console.log(chalk.gray('• Docker containers'));
console.log(chalk.gray('• SSH sessions without TTY'));
+33
View File
@@ -14,6 +14,8 @@ export interface ExecutionEnvironment {
isSSH: boolean;
isGitBash: boolean;
isWindowsTerminal: boolean;
isWSL: boolean;
isWindows: boolean;
supportsRawMode: boolean;
supportsColor: boolean;
terminalType: string;
@@ -40,6 +42,8 @@ export function detectExecutionEnvironment(options: EnvironmentOptions = {}): Ex
isSSH: false,
isGitBash: false,
isWindowsTerminal: false,
isWSL: false,
isWindows: false,
supportsRawMode: false,
supportsColor: true,
terminalType: 'unknown',
@@ -85,6 +89,16 @@ export function detectExecutionEnvironment(options: EnvironmentOptions = {}): Ex
// Windows Terminal detection
env.isWindowsTerminal = Boolean(process.env.WT_SESSION);
// Windows detection
env.isWindows = process.platform === 'win32';
// WSL detection
env.isWSL = Boolean(
process.env.WSL_DISTRO_NAME ||
process.env.WSL_INTEROP ||
(existsSync('/proc/version') && readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft'))
);
// Raw mode support check
env.supportsRawMode = checkRawModeSupport();
@@ -160,6 +174,21 @@ function generateRecommendations(env: ExecutionEnvironment): void {
env.warnings.push('Git Bash detected - some interactive features may not work correctly');
}
// WSL specific recommendations
if (env.isWSL) {
env.recommendedFlags.push('--no-interactive');
env.warnings.push('WSL detected - raw mode may cause hangs, using non-interactive mode');
if (!env.supportsRawMode) {
env.warnings.push('WSL subprocess context detected - interactive features disabled');
}
}
// Windows specific recommendations
if (env.isWindows && !env.isWSL) {
env.recommendedFlags.push('--compatible-ui');
env.warnings.push('Native Windows detected - using compatible UI mode');
}
// Raw mode not supported
if (!env.supportsRawMode && env.isInteractive) {
env.recommendedFlags.push('--compatible-ui');
@@ -242,6 +271,8 @@ export function getEnvironmentDescription(env?: ExecutionEnvironment): string {
if (environment.isSSH) parts.push('SSH');
if (environment.isGitBash) parts.push('Git Bash');
if (environment.isWindowsTerminal) parts.push('Windows Terminal');
if (environment.isWSL) parts.push('WSL');
if (environment.isWindows && !environment.isWSL) parts.push('Windows');
if (parts.length === 0) {
parts.push(environment.terminalType);
@@ -265,6 +296,8 @@ export function shouldUseNonInteractiveMode(options?: { force?: boolean }): bool
return !env.isInteractive ||
env.isCI ||
env.isVSCode ||
env.isWSL ||
env.isWindows ||
!env.supportsRawMode;
}
+141
View File
@@ -0,0 +1,141 @@
/**
* Safe Interactive Wrapper - Handles interactive commands in non-interactive environments
*/
import chalk from 'chalk';
import { shouldUseNonInteractiveMode, detectExecutionEnvironment } from './environment-detector.js';
/**
* Wraps an interactive function with safety checks
* @param {Function} interactiveFn - The interactive function to wrap
* @param {Function} fallbackFn - The non-interactive fallback function
* @param {Object} options - Options for the wrapper
* @returns {Function} The wrapped function
*/
export function safeInteractive(interactiveFn, fallbackFn, options = {}) {
return async function(...args) {
const flags = args[args.length - 1] || {};
// Check if user explicitly requested non-interactive mode
if (flags.nonInteractive || flags['no-interactive']) {
if (fallbackFn) {
return fallbackFn(...args);
} else {
console.log(chalk.yellow('⚠️ Non-interactive mode requested but no fallback available'));
console.log(chalk.gray('This command requires interactive mode to function properly'));
process.exit(1);
}
}
// Auto-detect if we should use non-interactive mode
if (shouldUseNonInteractiveMode()) {
const env = detectExecutionEnvironment({ skipWarnings: true });
if (!options.silent) {
console.log(chalk.yellow('\n⚠️ Interactive mode not available'));
// Provide specific message based on environment
if (env.isWSL) {
console.log(chalk.gray('WSL detected - raw mode may cause process hangs'));
console.log(chalk.cyan('💡 Tip: Use --no-interactive flag or run in native Linux'));
} else if (env.isWindows) {
console.log(chalk.gray('Windows detected - terminal compatibility issues'));
console.log(chalk.cyan('💡 Tip: Use Windows Terminal or WSL2 for better experience'));
} else if (env.isVSCode) {
console.log(chalk.gray('VS Code terminal detected - limited interactive support'));
console.log(chalk.cyan('💡 Tip: Use external terminal for full functionality'));
} else if (!env.supportsRawMode) {
console.log(chalk.gray('Terminal does not support raw mode'));
}
console.log();
}
if (fallbackFn) {
return fallbackFn(...args);
} else {
console.log(chalk.red('❌ This command requires interactive mode'));
console.log(chalk.gray('Please run in a compatible terminal environment'));
process.exit(1);
}
}
// Try to run the interactive function
try {
return await interactiveFn(...args);
} catch (error) {
// Check if it's a raw mode error
if (error.message && (
error.message.includes('setRawMode') ||
error.message.includes('raw mode') ||
error.message.includes('stdin') ||
error.message.includes('TTY')
)) {
console.log(chalk.yellow('\n⚠️ Interactive mode failed'));
console.log(chalk.gray(error.message));
if (fallbackFn) {
console.log(chalk.cyan('Falling back to non-interactive mode...'));
return fallbackFn(...args);
} else {
console.log(chalk.red('❌ No non-interactive fallback available'));
process.exit(1);
}
}
// Re-throw other errors
throw error;
}
};
}
/**
* Create a non-interactive version of a prompt
* @param {string} message - The prompt message
* @param {*} defaultValue - The default value to use
* @returns {*} The default value
*/
export function nonInteractivePrompt(message, defaultValue) {
console.log(chalk.gray(`📝 ${message}`));
console.log(chalk.cyan(` Using default: ${defaultValue}`));
return defaultValue;
}
/**
* Create a non-interactive version of a selection
* @param {string} message - The selection message
* @param {Array} choices - The available choices
* @param {*} defaultChoice - The default choice
* @returns {*} The default choice
*/
export function nonInteractiveSelect(message, choices, defaultChoice) {
console.log(chalk.gray(`📋 ${message}`));
console.log(chalk.gray(' Available choices:'));
choices.forEach(choice => {
const isDefault = choice === defaultChoice || choice.value === defaultChoice;
console.log(chalk.gray(` ${isDefault ? '▶' : ' '} ${choice.name || choice}`));
});
console.log(chalk.cyan(` Using default: ${defaultChoice}`));
return defaultChoice;
}
/**
* Show a non-interactive progress indicator
* @param {string} message - The progress message
* @returns {Object} Progress control object
*/
export function nonInteractiveProgress(message) {
console.log(chalk.gray(`⏳ ${message}...`));
return {
update: (newMessage) => {
console.log(chalk.gray(` ${newMessage}`));
},
succeed: (finalMessage) => {
console.log(chalk.green(`✅ ${finalMessage || message}`));
},
fail: (errorMessage) => {
console.log(chalk.red(`❌ ${errorMessage || 'Failed'}`));
}
};
}