From 158cd881dc344b8cf66b949be786420d54bed4fc Mon Sep 17 00:00:00 2001 From: Jeffrey Alan Scudder Date: Fri, 26 Dec 2025 22:59:23 -0800 Subject: [PATCH] ac-electron: fix opacity slider, emacs startup, copy/paste, remove verbose logs - Fix emacs.el syntax error (extra paren) - Opacity slider now controls entire terminal overlay opacity - Add Cmd+C/V for terminal copy/paste - Remove verbose console logging - Ensure emacs daemon ready before connecting - xterm transparency CSS fixes --- .copilot/.gitignore | 2 + .copilot/README.md | 18 + .devcontainer/config.fish | 35 +- .devcontainer/devcontainer.json | 1 + .devcontainer/entry.fish | 64 ++- .electron-bridge/command.json | 6 + .electron-bridge/result.json | 11 + .vscode/settings.json | 5 +- ac-electron/.gitignore | 18 + ac-electron/build/entitlements.mac.plist | 20 + ac-electron/main.js | 193 +++++++-- ac-electron/package-lock.json | 1 - ac-electron/package.json | 31 +- ac-electron/reinstall.sh | 24 ++ ac-electron/renderer/development.html | 368 +++++++++++++++--- ac-electron/renderer/shell.html | 21 +- artery/artery-auto.mjs | 95 +++++ artery/artery-electron.mjs | 275 +++++++++++++ artery/test-configs.json | 5 + artery/test-notepat-quick.mjs | 148 +++++++ dotfiles/dot_config/emacs.el | 142 +++++-- .../fish/functions/electric-snake-bite.fish | 28 ++ 22 files changed, 1337 insertions(+), 174 deletions(-) create mode 100644 .copilot/.gitignore create mode 100644 .copilot/README.md create mode 100644 .electron-bridge/command.json create mode 100644 .electron-bridge/result.json create mode 100644 ac-electron/.gitignore create mode 100644 ac-electron/build/entitlements.mac.plist create mode 100755 ac-electron/reinstall.sh create mode 100644 artery/artery-auto.mjs create mode 100644 artery/artery-electron.mjs create mode 100644 artery/test-notepat-quick.mjs create mode 100644 dotfiles/fish/functions/electric-snake-bite.fish diff --git a/.copilot/.gitignore b/.copilot/.gitignore new file mode 100644 index 0000000000..d96b146edb --- /dev/null +++ b/.copilot/.gitignore @@ -0,0 +1,2 @@ +config.json +init-copilot.fish diff --git a/.copilot/README.md b/.copilot/README.md new file mode 100644 index 0000000000..f11ca65d67 --- /dev/null +++ b/.copilot/README.md @@ -0,0 +1,18 @@ +# GitHub Copilot Configuration + +This directory contains persistent Copilot settings for the aesthetic-computer devcontainer. + +## Features +- **Default model**: Claude Opus 4.5 +- **Auto-authentication**: Uses GH_TOKEN from `aesthetic-computer-vault/.env` +- **Session persistence**: Maintains login across container restarts + +## Setup +Run `./aesthetic-computer-vault/devault.fish` on container start to initialize: +1. Exports GH_TOKEN from vault +2. Authenticates gh CLI +3. Configures VS Code Copilot settings + +## Files +- `config.json` โ€” Copilot preferences +- `init-copilot.fish` โ€” Initialization script (run by devault.fish) diff --git a/.devcontainer/config.fish b/.devcontainer/config.fish index 4ed4955b49..86f1c2bbb8 100644 --- a/.devcontainer/config.fish +++ b/.devcontainer/config.fish @@ -32,15 +32,13 @@ if test -d /workspaces/aesthetic-computer end # Persist Copilot CLI sessions across container restarts -# Store session state in vault so conversations survive reboots -if test -d /workspaces/aesthetic-computer/aesthetic-computer-vault/home/.copilot - if test ! -L ~/.copilot - # Remove any existing directory (not symlink) - if test -d ~/.copilot - rm -rf ~/.copilot - end - ln -s /workspaces/aesthetic-computer/aesthetic-computer-vault/home/.copilot ~/.copilot - echo "โœ“ Copilot sessions will persist across reboots" +# Now handled by Docker volume mount (aesthetic-copilot-data) +# The volume is mounted at /home/me/.copilot in devcontainer.json +# No symlink needed - just ensure proper permissions +if test -d ~/.copilot + # Fix permissions if needed (volume may have wrong owner after restart) + if not test -O ~/.copilot + sudo chown -R me:me ~/.copilot 2>/dev/null end end @@ -1236,13 +1234,13 @@ function ac-pix echo "" # Add space after sixel in eat end -# Full aesthetic platform restart (emacs + reconnect artery) +# Full aesthetic platform restart (emacs + reconnect llm) function ac-restart echo "๐Ÿ”„ Full aesthetic platform restart..." ac-emacs-restart if test $status -eq 0 - echo "๐Ÿฉธ Reconnecting to artery..." - emacsclient -nw -c --eval '(aesthetic-backend (quote "artery"))' + echo "๐Ÿค– Reconnecting to llm..." + emacsclient -nw -c --eval '(aesthetic-backend (quote "llm"))' end end @@ -1362,7 +1360,7 @@ end # For fast config reloading - simple approach function platform - emacsclient -nw -c --eval '(aesthetic-backend (quote "artery"))' + emacsclient -nw -c --eval '(aesthetic-backend (quote "llm"))' end function ensure-emacs-daemon-ready @@ -1564,7 +1562,7 @@ function aesthetic # Connect to emacs and run aesthetic-backend to create all tabs echo "๐Ÿš€ Connecting to aesthetic platform..." - emacsclient -nw -c --eval '(aesthetic-backend (quote "artery"))' + emacsclient -nw -c --eval '(aesthetic-backend (quote "llm"))' end # Convenience alias for skipping the wait @@ -1582,7 +1580,7 @@ function aesthetic-direct end # Connect to emacs with aesthetic-backend - emacsclient -nw -c --eval '(aesthetic-backend (quote "artery"))' + emacsclient -nw -c --eval '(aesthetic-backend (quote "llm"))' end # TODO: Automatically kill online mode and go to offline mode if necessary. @@ -2154,10 +2152,11 @@ alias acw 'cd ~/aesthetic-computer/system; npm run watch' # GitHub Copilot CLI (LLM agent in terminal) # Uses GH_TOKEN from vault for auth, runs interactively +# Default to Claude Opus 4.5 for best quality # Use --continue to resume last session after reboot -alias ac-llm 'clear; ac; copilot' -alias ac-llm-continue 'clear; ac; copilot --continue' -alias ac-llm-resume 'clear; ac; copilot --resume' +alias ac-llm 'clear; ac; copilot --model claude-opus-4.5' +alias ac-llm-continue 'clear; ac; copilot --model claude-opus-4.5 --continue' +alias ac-llm-resume 'clear; ac; copilot --model claude-opus-4.5 --resume' # Process viewer (htop for monitoring system resources) alias ac-top 'clear; htop' diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index ca3417bb71..c31d4bbd4d 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -22,6 +22,7 @@ "source=${localWorkspaceFolder}/.devcontainer/.emacs.d,target=/home/me/.emacs.d,type=bind,consistency=cached", "source=${localWorkspaceFolder}/.devcontainer/envs,target=/home/me/envs,type=bind,consistency=cached", "source=aesthetic-fish-data,target=/home/me/.local/share/fish,type=volume", + "source=aesthetic-copilot-data,target=/home/me/.copilot,type=volume", "source=codespaces-linux-var-lib-docker,target=/var/lib/docker,type=volume", "source=/var/run/docker.sock,target=/var/run/docker-host.sock,type=bind", "type=bind,source=/var/run/docker.sock,target=/var/run/docker.sock" diff --git a/.devcontainer/entry.fish b/.devcontainer/entry.fish index 9f894eb3d4..dc8601dce4 100644 --- a/.devcontainer/entry.fish +++ b/.devcontainer/entry.fish @@ -523,14 +523,37 @@ if test -d /home/me/aesthetic-computer log_ok "Environment variables reloaded after vault mount" end - # Setup SSH keys from vault - if test -d /home/me/aesthetic-computer/aesthetic-computer-vault/home/.ssh - mkdir -p /home/me/.ssh - cp -f /home/me/aesthetic-computer/aesthetic-computer-vault/home/.ssh/* /home/me/.ssh/ - chmod 700 /home/me/.ssh - chmod 600 /home/me/.ssh/id_rsa 2>/dev/null - chmod 644 /home/me/.ssh/id_rsa.pub 2>/dev/null - log_ok "SSH keys restored from vault" + # Setup SSH keys from vault (only if not already set up) + set -l vault_ssh /home/me/aesthetic-computer/aesthetic-computer-vault/home/.ssh + if test -d $vault_ssh + # Only copy if id_rsa doesn't exist yet (first time setup) + if not test -f /home/me/.ssh/id_rsa + mkdir -p /home/me/.ssh + cp -f $vault_ssh/* /home/me/.ssh/ 2>/dev/null + chown -R me:me /home/me/.ssh 2>/dev/null + chmod 700 /home/me/.ssh 2>/dev/null + chmod 600 /home/me/.ssh/id_rsa 2>/dev/null + chmod 644 /home/me/.ssh/id_rsa.pub 2>/dev/null + chmod 600 /home/me/.ssh/config 2>/dev/null + chmod 600 /home/me/.ssh/aesthetic_pds 2>/dev/null + chmod 644 /home/me/.ssh/aesthetic_pds.pub 2>/dev/null + log_ok "SSH keys restored from vault" + else + log_info "SSH keys already exist, skipping vault copy" + end + end + + # Setup Copilot CLI config from vault (if volume is empty but vault has backup) + set -l vault_copilot /home/me/aesthetic-computer/aesthetic-computer-vault/home/.copilot + if test -d $vault_copilot + # Only restore if volume mount is empty (no config.json) + if not test -f /home/me/.copilot/config.json + mkdir -p /home/me/.copilot + cp -f $vault_copilot/config.json /home/me/.copilot/ 2>/dev/null + log_ok "Copilot CLI config restored from vault" + else + log_info "Copilot CLI config already exists (using volume data)" + end end else log_error "Vault unmounted! /home/me/aesthetic-computer not found" @@ -552,12 +575,27 @@ log_ok "Ensured /home/me/.emacs-logs exists" log_info "Fixing fish config permissions..." ensure_fish_config_permissions -# Fix SSH directory permissions +# Fix SSH directory permissions (only if we own it - don't use sudo which can fail) if test -d /home/me/.ssh - sudo chown -R me:me /home/me/.ssh 2>/dev/null - sudo chmod 700 /home/me/.ssh 2>/dev/null - sudo chmod 600 /home/me/.ssh/* 2>/dev/null - echo "โœ… Fixed permissions for /home/me/.ssh (after vault setup)" + if test -O /home/me/.ssh + chmod 700 /home/me/.ssh 2>/dev/null + chmod 600 /home/me/.ssh/* 2>/dev/null + chmod 644 /home/me/.ssh/*.pub 2>/dev/null + echo "โœ… Fixed permissions for /home/me/.ssh" + else + log_info "SSH dir not owned by me, skipping permission fix" + end +end + +# Fix Copilot CLI directory permissions (volume mount may have root ownership) +if test -d /home/me/.copilot + sudo chown -R me:me /home/me/.copilot 2>/dev/null + sudo chmod 700 /home/me/.copilot 2>/dev/null + # Ensure pkg directory exists and is writable for package extraction + mkdir -p /home/me/.copilot/pkg 2>/dev/null + chmod 755 /home/me/.copilot/pkg 2>/dev/null + sudo chmod 600 /home/me/.copilot/config.json 2>/dev/null + echo "โœ… Fixed permissions for /home/me/.copilot (Copilot CLI config)" end if not test -d /home/me/aesthetic-computer/aesthetic-computer-code diff --git a/.electron-bridge/command.json b/.electron-bridge/command.json new file mode 100644 index 0000000000..8ac6ed22f7 --- /dev/null +++ b/.electron-bridge/command.json @@ -0,0 +1,6 @@ +{ + "id": 12345, + "cmd": "get-state", + "params": {}, + "timestamp": "2025-12-27T05:30:00.000Z" +} diff --git a/.electron-bridge/result.json b/.electron-bridge/result.json new file mode 100644 index 0000000000..77b11bd95e --- /dev/null +++ b/.electron-bridge/result.json @@ -0,0 +1,11 @@ +{ + "id": 12345, + "data": { + "env": "prod", + "piece": "starfield", + "url": "about:blank", + "mode": "shell", + "connected": false + }, + "error": null +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index 647ae6d7fa..13ec0bf511 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -67,5 +67,8 @@ "deno.unstable": true, "deno.importMap": ".netlify/edge-functions-import-map.json", "task.quickOpen.showAll": true, - "task.allowAutomaticTasks": "on" + "task.allowAutomaticTasks": "on", + "github.copilot.advanced": { + "defaultModel": "claude-opus-4.5" + } } \ No newline at end of file diff --git a/ac-electron/.gitignore b/ac-electron/.gitignore new file mode 100644 index 0000000000..393b629aee --- /dev/null +++ b/ac-electron/.gitignore @@ -0,0 +1,18 @@ +# Build outputs +dist/ + +# Dependencies +node_modules/ + +# Logs +*.log +npm-debug.log* + +# OS files +.DS_Store +Thumbs.db + +# Editor +.idea/ +*.swp +*.swo diff --git a/ac-electron/build/entitlements.mac.plist b/ac-electron/build/entitlements.mac.plist new file mode 100644 index 0000000000..fb3c830f37 --- /dev/null +++ b/ac-electron/build/entitlements.mac.plist @@ -0,0 +1,20 @@ + + + + + com.apple.security.cs.allow-jit + + com.apple.security.cs.allow-unsigned-executable-memory + + com.apple.security.cs.disable-library-validation + + com.apple.security.cs.allow-dyld-environment-variables + + com.apple.security.network.client + + com.apple.security.network.server + + com.apple.security.inherit + + + diff --git a/ac-electron/main.js b/ac-electron/main.js index 70c74aee3b..c76b72e5ae 100644 --- a/ac-electron/main.js +++ b/ac-electron/main.js @@ -56,10 +56,28 @@ let windowIdCounter = 0; let focusedWindowId = null; let shellWindowId = null; // Singleton tracking for shell window +// Find docker binary path (needed for packaged app which may not have PATH set) +function getDockerPath() { + if (process.platform === 'darwin') { + const dockerLocations = [ + '/opt/homebrew/bin/docker', // Apple Silicon Homebrew + '/usr/local/bin/docker', // Intel Homebrew / Docker Desktop + '/Applications/Docker.app/Contents/Resources/bin/docker' + ]; + for (const loc of dockerLocations) { + if (fs.existsSync(loc)) { + return loc; + } + } + } + return 'docker'; +} + // Check if Docker is available async function checkDocker() { + const dockerPath = getDockerPath(); return new Promise((resolve) => { - const docker = spawn('docker', ['info'], { stdio: 'pipe' }); + const docker = spawn(dockerPath, ['info'], { stdio: 'pipe' }); docker.on('close', (code) => resolve(code === 0)); docker.on('error', () => resolve(false)); }); @@ -67,8 +85,21 @@ async function checkDocker() { // Check if devcontainer is running async function checkDevcontainer() { + const dockerPath = getDockerPath(); + return new Promise((resolve) => { + const docker = spawn(dockerPath, ['ps', '--filter', 'name=aesthetic', '--format', '{{.Names}}'], { stdio: 'pipe' }); + let output = ''; + docker.stdout.on('data', (data) => output += data.toString()); + docker.on('close', () => resolve(output.includes('aesthetic'))); + docker.on('error', () => resolve(false)); + }); +} + +// Check if container exists (running or stopped) +async function checkContainerExists() { + const dockerPath = getDockerPath(); return new Promise((resolve) => { - const docker = spawn('docker', ['ps', '--filter', 'name=aesthetic', '--format', '{{.Names}}'], { stdio: 'pipe' }); + const docker = spawn(dockerPath, ['ps', '-a', '--filter', 'name=aesthetic', '--format', '{{.Names}}'], { stdio: 'pipe' }); let output = ''; docker.stdout.on('data', (data) => output += data.toString()); docker.on('close', () => resolve(output.includes('aesthetic'))); @@ -76,14 +107,63 @@ async function checkDevcontainer() { }); } +// Start an existing stopped container +async function startExistingContainer() { + const dockerPath = getDockerPath(); + return new Promise((resolve, reject) => { + console.log('Starting existing container...'); + const docker = spawn(dockerPath, ['start', 'aesthetic'], { stdio: 'pipe' }); + docker.on('close', (code) => { + if (code === 0) { + console.log('Container started successfully'); + resolve(true); + } else { + reject(new Error(`docker start exited with code ${code}`)); + } + }); + docker.on('error', (err) => reject(err)); + }); +} + // Start the devcontainer async function startDevcontainer() { return new Promise((resolve, reject) => { - const workspaceFolder = path.resolve(__dirname, '..'); + // For packaged app, the workspace is one level up from the app bundle's Resources folder + // When running in dev: __dirname is ac-electron, workspace is .. + // When packaged: __dirname is inside app.asar, need to find actual workspace + let workspaceFolder; + if (__dirname.includes('app.asar')) { + // Packaged app - assume workspace is at a known location or use env var + workspaceFolder = process.env.AC_WORKSPACE || path.join(process.env.HOME, 'Desktop/code/aesthetic-computer'); + } else { + workspaceFolder = path.resolve(__dirname, '..'); + } console.log('Starting devcontainer in:', workspaceFolder); - const devcontainer = spawn('devcontainer', ['up', '--workspace-folder', workspaceFolder], { - stdio: 'pipe' + // Find devcontainer CLI + let devcontainerPath = 'devcontainer'; + if (process.platform === 'darwin') { + const locations = [ + '/opt/homebrew/bin/devcontainer', + '/usr/local/bin/devcontainer', + path.join(process.env.HOME, '.npm-global/bin/devcontainer'), + path.join(process.env.HOME, 'node_modules/.bin/devcontainer') + ]; + for (const loc of locations) { + if (fs.existsSync(loc)) { + devcontainerPath = loc; + break; + } + } + } + console.log('Using devcontainer CLI:', devcontainerPath); + + const devcontainer = spawn(devcontainerPath, ['up', '--workspace-folder', workspaceFolder], { + stdio: 'pipe', + env: { + ...process.env, + PATH: `${process.env.PATH}:/usr/local/bin:/opt/homebrew/bin` + } }); let output = ''; @@ -288,21 +368,21 @@ function createWindow(mode = 'production') { let winWidth, winHeight, winX, winY; if (isDev) { - // Dev window: nearly full screen (has integrated terminal overlay) - winWidth = screenWidth - 100; - winHeight = screenHeight - 50; - winX = 50; - winY = 0; + // Dev window: compact, cute size - positioned center-right + winWidth = 900; + winHeight = 700; + winX = Math.floor((screenWidth - winWidth) / 2) + 100; + winY = Math.floor((screenHeight - winHeight) / 2); } else if (isShell) { - // Standalone shell: right side of screen - winWidth = Math.floor(screenWidth * 0.45); - winHeight = screenHeight - 50; - winX = Math.floor(screenWidth * 0.55); - winY = 0; + // Standalone shell: compact, right side of screen + winWidth = 800; + winHeight = 600; + winX = screenWidth - winWidth - 50; + winY = Math.floor((screenHeight - winHeight) / 2); } else { - // Production: centered - winWidth = 1280; - winHeight = 800; + // Production: centered, compact + winWidth = 1024; + winHeight = 768; winX = Math.floor((screenWidth - winWidth) / 2); winY = Math.floor((screenHeight - winHeight) / 2); } @@ -334,6 +414,10 @@ function createWindow(mode = 'production') { // Show when ready win.once('ready-to-show', () => { win.show(); + // Auto-open devtools in dev mode + if (isDev) { + win.webContents.openDevTools({ mode: 'detach' }); + } }); // Load appropriate HTML @@ -418,6 +502,25 @@ ipcMain.handle('check-container', async () => { return result; }); +ipcMain.handle('check-container-exists', async () => { + console.log('[main] check-container-exists called'); + const result = await checkContainerExists(); + console.log('[main] check-container-exists result:', result); + return result; +}); + +ipcMain.handle('start-existing-container', async () => { + console.log('[main] start-existing-container called'); + try { + await startExistingContainer(); + console.log('[main] start-existing-container success'); + return { success: true }; + } catch (err) { + console.error('[main] start-existing-container error:', err); + return { success: false, error: err.message }; + } +}); + ipcMain.handle('start-container', async () => { console.log('[main] start-container called'); try { @@ -463,13 +566,14 @@ ipcMain.handle('connect-pty', async (event) => { try { // Spawn docker exec to get into the container with fish shell - // Use full path to docker in case PATH isn't set correctly in Electron - const dockerPath = process.platform === 'darwin' - ? '/usr/local/bin/docker' // Common Docker Desktop location - : 'docker'; + const dockerPath = getDockerPath(); console.log('[main] Spawning PTY with docker at:', dockerPath); + // Ensure PATH includes common locations for packaged app + const extraPaths = '/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin'; + const fullPath = process.env.PATH ? `${process.env.PATH}:${extraPaths}` : extraPaths; + const shellProcess = pty.spawn(dockerPath, ['exec', '-it', 'aesthetic', 'fish'], { name: 'xterm-256color', cols: 120, @@ -478,7 +582,7 @@ ipcMain.handle('connect-pty', async (event) => { env: { ...process.env, TERM: 'xterm-256color', - PATH: process.env.PATH + ':/usr/local/bin:/opt/homebrew/bin' + PATH: fullPath }, }); @@ -486,8 +590,12 @@ ipcMain.handle('connect-pty', async (event) => { // Forward PTY output to renderer shellProcess.onData((data) => { + console.log('[main] PTY data received, length:', data.length, 'preview:', data.substring(0, 50).replace(/\n/g, '\\n')); if (!win.isDestroyed()) { win.webContents.send('pty-data', data); + console.log('[main] PTY data sent to renderer'); + } else { + console.log('[main] Window destroyed, cannot send PTY data'); } }); @@ -521,7 +629,12 @@ ipcMain.on('pty-resize', (event, cols, rows) => { const win = BrowserWindow.fromWebContents(event.sender); for (const [id, winData] of windows) { if (winData.window === win && winData.ptyProcess) { - winData.ptyProcess.resize(cols, rows); + try { + winData.ptyProcess.resize(cols, rows); + } catch (err) { + // PTY may not be ready yet or already exited + console.warn('[main] PTY resize failed:', err.message); + } break; } } @@ -656,19 +769,21 @@ ipcMain.on('ac-reload', (event) => { app.whenReady().then(async () => { createMenu(); - // Watch for reboot request file from devcontainer + // Watch for reboot request file from devcontainer (electric-snake-bite) const REBOOT_MARKER = path.join(__dirname, '.reboot-requested'); const checkRebootMarker = () => { if (fs.existsSync(REBOOT_MARKER)) { - console.log('[main] Reboot marker detected, exiting with code 42...'); + console.log('[main] โšก๐Ÿ Electric Snake Bite detected! Relaunching...'); fs.unlinkSync(REBOOT_MARKER); // Clean up marker - // Exit with code 42 - wrapper script should restart us - app.exit(42); + // Relaunch the app then quit current instance + app.relaunch(); + app.quit(); } }; // Check every 2 seconds for reboot marker setInterval(checkRebootMarker, 2000); + setInterval(checkRebootMarker, 2000); // Create initial window(s) based on CLI args // Default to dev window with integrated terminal overlay (press Cmd+` to toggle) @@ -710,15 +825,12 @@ app.on('will-quit', () => { } } - // Stop the devcontainer when quitting + // Stop the devcontainer when the app quits try { - execSync('docker stop aesthetic 2>/dev/null || true', { - timeout: 5000, - stdio: 'ignore' - }); - console.log('[main] Stopped devcontainer on quit'); + require('child_process').execSync('docker stop aesthetic', { timeout: 5000 }); + console.log('[main] Stopped devcontainer'); } catch (e) { - // Ignore errors - container might not be running + console.log('[main] Could not stop devcontainer:', e.message); } }); @@ -743,15 +855,12 @@ function cleanup() { } } - // Stop the devcontainer + // Stop the devcontainer on cleanup try { - execSync('docker stop aesthetic 2>/dev/null || true', { - timeout: 5000, - stdio: 'ignore' - }); - console.log('[main] Stopped devcontainer on cleanup'); + require('child_process').execSync('docker stop aesthetic', { timeout: 5000 }); + console.log('[main] Stopped devcontainer'); } catch (e) { - // Ignore + console.log('[main] Could not stop devcontainer:', e.message); } process.exit(0); diff --git a/ac-electron/package-lock.json b/ac-electron/package-lock.json index d1fe145f61..ed4ae4f619 100644 --- a/ac-electron/package-lock.json +++ b/ac-electron/package-lock.json @@ -2941,7 +2941,6 @@ "integrity": "sha512-NoXo6Liy2heSklTI5OIZbCgXC1RzrDQsZkeEwXhdOro3FT1VBOvbubvscdPnjVuQ4AMwwv61oaH96AbiYg9EnQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "app-builder-lib": "25.1.8", "builder-util": "25.1.7", diff --git a/ac-electron/package.json b/ac-electron/package.json index 866a6f428c..f2d165da80 100644 --- a/ac-electron/package.json +++ b/ac-electron/package.json @@ -22,15 +22,9 @@ "output": "dist", "buildResources": "build" }, - "files": [ - "main.js", - "preload.js", - "renderer/**/*", - "!node_modules/**/*", - "node_modules/xterm/**/*", - "node_modules/xterm-addon-fit/**/*", - "node_modules/xterm-addon-webgl/**/*" - ], + "extraMetadata": { + "name": "aesthetic-computer" + }, "mac": { "category": "public.app-category.graphics-design", "target": [ @@ -41,9 +35,24 @@ ] } ], - "hardenedRuntime": true, - "gatekeeperAssess": false + "hardenedRuntime": false, + "gatekeeperAssess": false, + "entitlements": "build/entitlements.mac.plist", + "entitlementsInherit": "build/entitlements.mac.plist", + "extendInfo": { + "NSDesktopFolderUsageDescription": "Aesthetic Computer needs access to your Desktop to manage the workspace.", + "NSDocumentsFolderUsageDescription": "Aesthetic Computer needs access to Documents for file operations.", + "NSDownloadsFolderUsageDescription": "Aesthetic Computer needs access to Downloads for file operations." + } }, + "files": [ + "main.js", + "preload.js", + "renderer/**/*", + "!node_modules/**/*", + "node_modules/@xterm/**/*", + "node_modules/node-pty/**/*" + ], "win": { "target": [ { diff --git a/ac-electron/reinstall.sh b/ac-electron/reinstall.sh new file mode 100755 index 0000000000..5a8425cfa5 --- /dev/null +++ b/ac-electron/reinstall.sh @@ -0,0 +1,24 @@ +#!/bin/bash +# Quick rebuild and reinstall of Aesthetic Computer app + +set -e + +cd "$(dirname "$0")" + +echo "๐Ÿ”„ Closing running instances..." +pkill -f "Aesthetic Computer" 2>/dev/null || true +sleep 0.5 + +echo "๐Ÿ“ฆ Building macOS app..." +npm run build:mac + +echo "๐Ÿ—‘๏ธ Removing old installation..." +rm -rf "/Applications/Aesthetic Computer.app" + +echo "๐Ÿ“ฒ Installing to Applications..." +cp -R "dist/mac-universal/Aesthetic Computer.app" /Applications/ + +echo "๐Ÿš€ Launching app..." +open "/Applications/Aesthetic Computer.app" + +echo "โœ… Done!" diff --git a/ac-electron/renderer/development.html b/ac-electron/renderer/development.html index 72af853d08..d74b7372b8 100644 --- a/ac-electron/renderer/development.html +++ b/ac-electron/renderer/development.html @@ -15,27 +15,16 @@ background: #0a0a12; } - /* Main AC webview - full screen */ - #ac-webview { - position: absolute; - top: 0; left: 0; - width: 100%; - height: 100%; - border: none; - opacity: 0; - transition: opacity 0.3s ease; - } - #ac-webview.connected { opacity: 1; } - - /* Control bar - always on top and fully visible */ + /* Control bar - fixed at top, pushes content down */ #control-bar { - position: absolute; + position: fixed; top: 0; left: 0; right: 0; + height: 36px; display: flex; align-items: center; gap: 12px; padding: 8px 15px; - background: rgba(0, 0, 0, 0.9); + background: rgba(0, 0, 0, 0.95); border-bottom: 1px solid rgba(255, 0, 255, 0.3); font-family: 'SF Mono', monospace; font-size: 12px; @@ -55,6 +44,18 @@ -webkit-app-region: no-drag; } + /* Main AC webview - below control bar */ + #ac-webview { + position: absolute; + top: 36px; left: 0; + width: 100%; + height: calc(100% - 36px); + border: none; + opacity: 0; + transition: opacity 0.3s ease; + } + #ac-webview.connected { opacity: 1; } + .title { color: #f0f; cursor: default; @@ -173,19 +174,27 @@ /* Terminal overlay - below control bar */ #terminal-overlay { position: absolute; - top: 38px; left: 0; right: 0; bottom: 0; + top: 36px; left: 0; right: 0; bottom: 0; z-index: 100; display: flex; flex-direction: column; - transition: opacity 0.2s ease; + transition: opacity 0.2s ease, top 0.2s ease; + background: rgb(10, 10, 18); + opacity: 0.7; } - /* Terminal background - this gets opacity */ + /* When control bar is hidden, expand to full height */ + body.bar-hidden #ac-webview { + top: 0; + height: 100%; + } + body.bar-hidden #terminal-overlay { + top: 0; + } + + /* Terminal background div no longer needed but kept for compatibility */ #terminal-bg { - position: absolute; - top: 0; left: 0; right: 0; bottom: 0; - background: rgba(10, 10, 18, 1); - pointer-events: none; + display: none; } /* Passthrough mode - terminal doesn't capture clicks */ @@ -196,6 +205,17 @@ pointer-events: none; } + /* Shell mode - terminal captures all clicks */ + #terminal-overlay:not(.passthrough) { + pointer-events: auto; + } + #terminal-overlay:not(.passthrough) #terminal-container { + pointer-events: auto; + } + #terminal-overlay:not(.passthrough) .xterm { + pointer-events: auto; + } + /* Terminal container */ #terminal-container { position: relative; @@ -204,7 +224,10 @@ overflow: hidden; z-index: 1; } - .xterm { height: 100%; } + .xterm { height: 100%; background: transparent !important; } + .xterm-viewport { background: transparent !important; } + .xterm-screen { background: transparent !important; } + .xterm canvas { background: transparent !important; } /* Mode indicator overlay */ #mode-indicator { @@ -289,8 +312,8 @@
- - + +
@@ -301,8 +324,8 @@
Opacity - - 85% + + 70%
โŒ˜` toggle ยท โŒ˜H hide bar @@ -345,13 +368,19 @@ prod: 'https://aesthetic.computer' }; - let currentEnv = 'local'; // 'local' or 'prod' - let currentPiece = 'prompt'; + let currentEnv = 'prod'; // 'local' or 'prod' - start with prod + let currentPiece = 'starfield'; // default piece let attempts = 0; let serverConnected = false; let checkInterval = null; let currentMode = 'shell'; // 'shell' or 'app' let controlBarVisible = true; + + // Helper to build AC URL with electron-specific params + function acUrl(piece) { + const baseUrl = URLS[currentEnv]; + return `${baseUrl}/${piece}?nogap`; + } // ========== Terminal Setup ========== const term = new Terminal({ @@ -419,7 +448,7 @@ connectionOverlay.classList.remove('hidden'); checkServer(); } else { - webview.src = `${baseUrl}/${currentPiece}`; + webview.src = acUrl(currentPiece); } } else { envLocalBtn.classList.remove('active'); @@ -427,7 +456,7 @@ // Production is always available connectionOverlay.classList.add('hidden'); webview.classList.add('connected'); - webview.src = `${baseUrl}/${currentPiece}`; + webview.src = acUrl(currentPiece); if (checkInterval) { clearInterval(checkInterval); checkInterval = null; @@ -445,11 +474,13 @@ controlBarVisible = !controlBarVisible; if (controlBarVisible) { controlBar.classList.remove('hidden'); - terminalOverlay.style.top = '38px'; + document.body.classList.remove('bar-hidden'); } else { controlBar.classList.add('hidden'); - terminalOverlay.style.top = '0'; + document.body.classList.add('bar-hidden'); } + // Refit terminal after layout change + setTimeout(() => fitAddon.fit(), 50); } // ========== Mode Switching ========== @@ -488,7 +519,28 @@ modeAppBtn.addEventListener('click', () => setMode('app')); // Keyboard shortcuts - document.addEventListener('keydown', (e) => { + document.addEventListener('keydown', async (e) => { + // Cmd+C to copy selected text from terminal (when in shell mode) + if ((e.metaKey || e.ctrlKey) && e.key === 'c' && currentMode === 'shell') { + if (term.hasSelection()) { + e.preventDefault(); + const selection = term.getSelection(); + await navigator.clipboard.writeText(selection); + } + // If no selection, let Ctrl+C pass through to terminal (interrupt) + } + // Cmd+V to paste into terminal + if ((e.metaKey || e.ctrlKey) && e.key === 'v' && currentMode === 'shell') { + e.preventDefault(); + try { + const text = await navigator.clipboard.readText(); + if (text) { + ipcRenderer.send('pty-input', text); + } + } catch (err) { + // Clipboard access denied + } + } // Cmd+` to toggle shell/app mode if ((e.metaKey || e.ctrlKey) && e.key === '`') { e.preventDefault(); @@ -508,12 +560,20 @@ e.preventDefault(); setEnv('prod'); } + // Cmd+Shift+R to trigger full app reboot (electric-snake-bite) + if ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key === 'R') { + e.preventDefault(); + console.log('[dev] โšก๐Ÿ Electric Snake Bite - Rebooting app...'); + term.writeln('\r\n\x1b[95mโšก๐Ÿ Electric Snake Bite - Rebooting Electron...\x1b[0m\r\n'); + await ipcRenderer.invoke('app-reboot'); + } }); // ========== Opacity Slider ========== function updateOpacity(value) { - // Apply opacity to the entire terminal overlay (control bar is separate) - terminalOverlay.style.opacity = value / 100; + // Apply opacity to the entire terminal overlay (text + background) + const opacity = value / 100; + terminalOverlay.style.opacity = opacity; opacityValue.textContent = value + '%'; } @@ -543,7 +603,7 @@ statusMessage.textContent = 'Server found!'; serverConnected = true; - webview.src = `${baseUrl}/${currentPiece}`; + webview.src = acUrl(currentPiece); return true; } catch (e) { return false; @@ -613,10 +673,17 @@ return; } - const containerOk = await ipcRenderer.invoke('check-container'); - if (!containerOk) { - term.writeln('\x1b[33mStarting devcontainer...\x1b[0m'); - await ipcRenderer.invoke('start-container'); + const containerRunning = await ipcRenderer.invoke('check-container'); + if (!containerRunning) { + // Check if container exists but is stopped + const containerExists = await ipcRenderer.invoke('check-container-exists'); + if (containerExists) { + term.writeln('\x1b[33mStarting existing container...\x1b[0m'); + await ipcRenderer.invoke('start-existing-container'); + } else { + term.writeln('\x1b[33mCreating devcontainer...\x1b[0m'); + await ipcRenderer.invoke('start-container'); + } } const connected = await ipcRenderer.invoke('connect-pty'); @@ -625,18 +692,64 @@ return; } - ipcRenderer.on('pty-data', (event, data) => term.write(data)); - term.onData((data) => ipcRenderer.send('pty-input', data)); + // โšก๐Ÿ Electric Snake Bite - Special escape sequence detection + // When the devcontainer outputs this magic string, reload the window + const ELECTRIC_SNAKE_BITE = '\x1b]9999;electric-snake-bite\x07'; + let escapeBuffer = ''; + let dataCount = 0; + + ipcRenderer.on('pty-data', (event, data) => { + dataCount++; + + // Check for electric-snake-bite escape sequence + escapeBuffer += data; + if (escapeBuffer.length > 100) { + escapeBuffer = escapeBuffer.slice(-50); // Keep buffer small + } + + if (escapeBuffer.includes('electric-snake-bite')) { + escapeBuffer = ''; + // Don't write the escape sequence to terminal + const cleanData = data.replace(/\x1b\]9999;electric-snake-bite\x07/g, ''); + if (cleanData) term.write(cleanData); + // Reload after a brief delay + setTimeout(() => location.reload(), 100); + return; + } + + term.write(data); + }); + // Filter out terminal query responses before sending to PTY + // These are responses to OSC queries like ]11;rgb:... (background color) + term.onData((data) => { + // Filter out OSC responses (]10;..., ]11;..., etc) and DA responses + if (data.match(/^\x1b\]1[0-9];/) || data.match(/^\x1b\[\?/)) { + return; + } + ipcRenderer.send('pty-input', data); + }); ipcRenderer.on('pty-exit', (event, code) => { term.writeln(`\r\n\x1b[33mShell exited with code ${code}\x1b[0m`); }); ipcRenderer.send('pty-resize', term.cols, term.rows); - // Auto-start emacs + // Auto-start emacs with proper daemon wait + // The container may need time for emacs daemon to fully initialize setTimeout(() => { - ipcRenderer.send('pty-input', 'ac-aesthetic\n'); - }, 500); + // First ensure emacs daemon is ready, then connect + // Use a retry-aware startup command + ipcRenderer.send('pty-input', 'ensure-emacs-daemon-ready --timeout=60 && ac-aesthetic\n'); + // After emacs loads, send resize and refresh to sync terminal + setTimeout(() => { + // Fit terminal first + fitAddon.fit(); + // Send resize to PTY + ipcRenderer.send('pty-resize', term.cols, term.rows); + // Redraw emacs + ipcRenderer.send('pty-input', '\x0c'); // Ctrl+L to redraw emacs + }, 3000); // Wait longer for daemon init + }, 500); // Give fish a moment to fully init } catch (err) { term.writeln(`\x1b[31mError: ${err.message}\x1b[0m`); @@ -650,7 +763,7 @@ ipcRenderer.on('ac-navigate', (event, piece) => { const baseUrl = URLS[currentEnv]; currentPiece = piece; - webview.src = `${baseUrl}/${piece}`; + webview.src = acUrl(piece); updateTitle(webview.src); }); @@ -705,10 +818,167 @@ webview.reload(); }); + // ========== File-Based Bridge for Devcontainer Tests ========== + // Watches for command files from artery-electron.mjs in the devcontainer + const { existsSync, readFileSync, writeFileSync, mkdirSync, unlinkSync } = require('fs'); + const pathModule = require('path'); + // @electron/remote is optional - don't crash if not available + let remote = null; + try { remote = require('@electron/remote'); } catch (e) { } + + // Get workspace root - the parent of ac-electron + // In dev mode, process.cwd() is usually the workspace root + // Or we can use the app path + let WORKSPACE_ROOT = process.cwd(); + + // Verify we found the right place + if (!existsSync(pathModule.join(WORKSPACE_ROOT, '.electron-bridge')) && + !existsSync(pathModule.join(WORKSPACE_ROOT, 'ac-electron'))) { + // Try going up from current directory + let testPath = WORKSPACE_ROOT; + for (let i = 0; i < 5; i++) { + if (existsSync(pathModule.join(testPath, 'ac-electron'))) { + WORKSPACE_ROOT = testPath; + break; + } + testPath = pathModule.dirname(testPath); + } + } + + const BRIDGE_DIR = pathModule.join(WORKSPACE_ROOT, '.electron-bridge'); + const CMD_FILE = pathModule.join(BRIDGE_DIR, 'command.json'); + const RESULT_FILE = pathModule.join(BRIDGE_DIR, 'result.json'); + + let lastProcessedId = null; + let bridgeWatcher = null; + + async function processCommand(request) { + const { id, cmd, params } = request; + + // Skip if already processed + if (id === lastProcessedId) return; + lastProcessedId = id; + + let result = { id, data: null, error: null }; + + try { + switch (cmd) { + case 'get-state': + result.data = { + env: currentEnv, + piece: currentPiece, + url: webview.src, + mode: currentMode, + connected: serverConnected + }; + break; + + case 'navigate': + const baseUrl = URLS[currentEnv]; + currentPiece = params.piece; + webview.src = acUrl(params.piece); + updateTitle(webview.src); + result.data = { success: true, piece: params.piece }; + break; + + case 'eval': + try { + const evalResult = await webview.executeJavaScript(params.code); + result.data = { success: true, result: evalResult }; + } catch (e) { + result.data = { success: false, error: e.message }; + } + break; + + case 'reload': + webview.reload(); + result.data = { success: true }; + break; + + case 'screenshot': + try { + const nativeImage = await webview.capturePage(); + result.data = { success: true, dataUrl: nativeImage.toDataURL() }; + } catch (e) { + result.data = { success: false, error: e.message }; + } + break; + + case 'set-env': + if (params.env === 'local' || params.env === 'prod') { + setEnv(params.env); + result.data = { success: true, env: params.env }; + } else { + result.error = 'Invalid env'; + } + break; + + case 'set-mode': + if (params.mode === 'shell' || params.mode === 'app') { + setMode(params.mode); + result.data = { success: true, mode: params.mode }; + } else { + result.error = 'Invalid mode'; + } + break; + + case 'enable-console': + // Console capture - could forward to a log file + result.data = { success: true }; + break; + + default: + result.error = `Unknown command: ${cmd}`; + } + } catch (e) { + result.error = e.message; + } + + // Write result + writeFileSync(RESULT_FILE, JSON.stringify(result, null, 2)); + } + + function checkBridgeCommand() { + try { + if (existsSync(CMD_FILE)) { + const content = readFileSync(CMD_FILE, 'utf8'); + const request = JSON.parse(content); + if (request.id !== lastProcessedId) { + processCommand(request); + } + } + } catch (e) { + // Ignore read errors + } + } + + function initBridge() { + try { + // Ensure bridge directory exists + if (!existsSync(BRIDGE_DIR)) { + mkdirSync(BRIDGE_DIR, { recursive: true }); + } + + // Poll for commands (file watching can be unreliable across Docker) + setInterval(checkBridgeCommand, 100); + + console.log('[dev] File bridge initialized at', BRIDGE_DIR); + } catch (e) { + console.warn('[dev] Could not init file bridge:', e.message); + } + } + // ========== Init ========== - checkServer(); - checkInterval = setInterval(checkServer, 2000); + setEnv('prod'); // Start with production - loads /starfield initShell(); + initBridge(); + + // Ensure webview loads immediately + setTimeout(() => { + if (webview.src === 'about:blank') { + webview.src = acUrl('starfield'); + } + }, 100); \ No newline at end of file diff --git a/ac-electron/renderer/shell.html b/ac-electron/renderer/shell.html index 5c9547dd15..56a180bc73 100644 --- a/ac-electron/renderer/shell.html +++ b/ac-electron/renderer/shell.html @@ -15,10 +15,12 @@ } #terminal-container { width: 100%; - height: 100%; + height: calc(100% - 64px); /* Leave space at top */ + margin-top: 64px; /* Push terminal down */ padding: 8px; } .xterm { height: 100%; } + .xterm-viewport { padding-top: 0 !important; } @@ -96,11 +98,18 @@ return; } - // Check container - const containerOk = await ipcRenderer.invoke('check-container'); - if (!containerOk) { - term.writeln('\x1b[33mStarting devcontainer...\x1b[0m'); - await ipcRenderer.invoke('start-container'); + // Check if container is running + const containerRunning = await ipcRenderer.invoke('check-container'); + if (!containerRunning) { + // Check if container exists but is stopped + const containerExists = await ipcRenderer.invoke('check-container-exists'); + if (containerExists) { + term.writeln('\x1b[33mStarting existing container...\x1b[0m'); + await ipcRenderer.invoke('start-existing-container'); + } else { + term.writeln('\x1b[33mCreating devcontainer...\x1b[0m'); + await ipcRenderer.invoke('start-container'); + } } // Connect PTY diff --git a/artery/artery-auto.mjs b/artery/artery-auto.mjs new file mode 100644 index 0000000000..2906088358 --- /dev/null +++ b/artery/artery-auto.mjs @@ -0,0 +1,95 @@ +#!/usr/bin/env node +/** + * ๐Ÿฉธ Artery Auto - Automatically selects CDP or Electron adapter + * + * Import this instead of artery.mjs to get the right adapter for your environment: + * - In VS Code with CDP: uses artery.mjs (CDP-based) + * - In Electron app: uses artery-electron.mjs (file-based IPC) + */ + +import fs from 'fs'; +import http from 'http'; + +const BRIDGE_DIR = '/workspaces/aesthetic-computer/.electron-bridge'; + +/** + * Test if CDP is available at localhost:9333 or other common ports + */ +async function testCDP() { + const candidates = [ + { host: 'localhost', port: 9333 }, + { host: 'localhost', port: 9222 }, + { host: 'host.docker.internal', port: 9333 }, + { host: 'host.docker.internal', port: 9222 }, + ]; + + for (const { host, port } of candidates) { + try { + const works = await new Promise((resolve) => { + const req = http.get({ + hostname: host, + port, + path: '/json', + timeout: 1000, + headers: { 'Host': 'localhost' } + }, (res) => { + let data = ''; + res.on('data', (chunk) => data += chunk); + res.on('end', () => resolve(data.length > 10)); + }); + req.on('error', () => resolve(false)); + req.on('timeout', () => { req.destroy(); resolve(false); }); + }); + if (works) return true; + } catch (e) { + // Continue + } + } + return false; +} + +/** + * Check if Electron bridge is available + */ +function isElectronBridge() { + return fs.existsSync(BRIDGE_DIR) || process.env.AC_ELECTRON === 'true'; +} + +/** + * Get the appropriate Artery class + */ +export async function getArtery() { + // First check if CDP is available + const cdpAvailable = await testCDP(); + + if (cdpAvailable) { + console.log('๐Ÿฉธ Using CDP adapter (VS Code)'); + const { default: Artery } = await import('./artery.mjs'); + return Artery; + } + + // Check if Electron bridge exists + if (isElectronBridge()) { + console.log('๐Ÿฉธ Using Electron adapter'); + const { default: ArteryElectron } = await import('./artery-electron.mjs'); + return ArteryElectron; + } + + // No adapter available - create bridge directory to enable Electron mode + console.log('๐Ÿฉธ Creating Electron bridge directory...'); + fs.mkdirSync(BRIDGE_DIR, { recursive: true }); + const { default: ArteryElectron } = await import('./artery-electron.mjs'); + return ArteryElectron; +} + +/** + * Create and connect an Artery instance + */ +export async function createArtery() { + const ArteryClass = await getArtery(); + const artery = new ArteryClass(); + return artery; +} + +// Default export for drop-in replacement +export default { getArtery, createArtery }; diff --git a/artery/artery-electron.mjs b/artery/artery-electron.mjs new file mode 100644 index 0000000000..160f84aa33 --- /dev/null +++ b/artery/artery-electron.mjs @@ -0,0 +1,275 @@ +#!/usr/bin/env node +/** + * ๐Ÿฉธ Artery Electron Adapter + * + * Provides CDP-compatible interface for running Artery tests in the Electron app. + * Uses Electron's IPC bridge instead of Chrome DevTools Protocol. + * + * Communication happens via file-based IPC since we're in a devcontainer + * that's connected to Electron via PTY (not direct IPC). + */ + +import fs from 'fs'; +import path from 'path'; +import { fileURLToPath } from 'url'; +import { execSync } from 'child_process'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +// Colors +const RESET = '\x1b[0m'; +const BOLD = '\x1b[1m'; +const RED_BG = '\x1b[41m'; +const PINK = '\x1b[95m'; +const PURPLE_BG = '\x1b[45m'; +const WHITE = '\x1b[97m'; +const CYAN = '\x1b[96m'; +const GREEN = '\x1b[92m'; +const YELLOW = '\x1b[93m'; + +const redLog = (msg) => console.log(`${RED_BG}${PINK}${msg}${RESET}`); +const brightLog = (msg) => console.log(`${RED_BG}${PINK}${BOLD}${msg}${RESET}`); +const darkLog = (msg) => console.log(`${PURPLE_BG}${WHITE}${msg}${RESET}`); + +// Bridge directory - shared between container and Electron via mounted workspace +const BRIDGE_DIR = '/workspaces/aesthetic-computer/.electron-bridge'; +const CMD_FILE = `${BRIDGE_DIR}/command.json`; +const RESULT_FILE = `${BRIDGE_DIR}/result.json`; + +function ensureBridgeDir() { + if (!fs.existsSync(BRIDGE_DIR)) { + fs.mkdirSync(BRIDGE_DIR, { recursive: true }); + } +} + +// File-based IPC for container <-> Electron communication +async function sendCommand(cmd, params = {}, timeout = 10000) { + ensureBridgeDir(); + + const request = { + id: Date.now() + Math.random(), + cmd, + params, + timestamp: new Date().toISOString() + }; + + // Clear any old result + if (fs.existsSync(RESULT_FILE)) { + fs.unlinkSync(RESULT_FILE); + } + + // Write command + fs.writeFileSync(CMD_FILE, JSON.stringify(request, null, 2)); + + // Wait for result + const startTime = Date.now(); + while (Date.now() - startTime < timeout) { + if (fs.existsSync(RESULT_FILE)) { + try { + const content = fs.readFileSync(RESULT_FILE, 'utf8'); + const result = JSON.parse(content); + if (result.id === request.id) { + fs.unlinkSync(RESULT_FILE); + if (result.error) { + throw new Error(result.error); + } + return result.data; + } + } catch (e) { + if (e.code !== 'ENOENT') { + // Parse error or other issue - keep waiting briefly + await new Promise(r => setTimeout(r, 20)); + } + } + } + await new Promise(r => setTimeout(r, 50)); + } + + throw new Error(`Timeout waiting for ${cmd} response`); +} + +/** + * ArteryElectron - CDP-compatible interface for Electron app + */ +class ArteryElectron { + constructor() { + this.connected = false; + this.consoleCallback = null; + this.messageId = 0; + } + + async connect() { + redLog('๐Ÿฉธ Connecting to Electron webview...'); + + try { + const state = await this.getState(); + if (state) { + this.connected = true; + brightLog('๐Ÿฉธ Connected to Electron!'); + return true; + } + throw new Error('No state returned'); + } catch (e) { + throw new Error(`Failed to connect: ${e.message}`); + } + } + + async getState() { + return sendCommand('get-state'); + } + + async jump(piece) { + brightLog(`๐Ÿฉธ Jump: ${piece}`); + return sendCommand('navigate', { piece }); + } + + async getCurrentPiece() { + const state = await this.getState(); + return state?.piece || null; + } + + // CDP-compatible send method + async send(method, params = {}) { + if (method === 'Runtime.evaluate') { + const result = await this.eval(params.expression); + return { result: { value: result } }; + } + + if (method === 'Runtime.enable') { + return {}; + } + + if (method === 'Input.dispatchKeyEvent') { + return this.dispatchKeyEvent(params); + } + + console.warn(`[ArteryElectron] Unhandled method: ${method}`); + return {}; + } + + async eval(expression) { + const result = await sendCommand('eval', { code: expression }); + return result?.result; + } + + async dispatchKeyEvent(params) { + const { type, key, code, keyCode, windowsVirtualKeyCode, shiftKey, ctrlKey, altKey, metaKey } = params; + + const eventInit = JSON.stringify({ + key: key || '', + code: code || '', + keyCode: keyCode || windowsVirtualKeyCode || 0, + which: keyCode || windowsVirtualKeyCode || 0, + shiftKey: shiftKey || false, + ctrlKey: ctrlKey || false, + altKey: altKey || false, + metaKey: metaKey || false, + bubbles: true, + cancelable: true + }); + + const eventType = type === 'keyDown' ? 'keydown' : type === 'keyUp' ? 'keyup' : type; + + await this.eval(` + (function() { + const event = new KeyboardEvent('${eventType}', ${eventInit}); + window.dispatchEvent(event); + })() + `); + + return {}; + } + + async enableConsole(callback) { + this.consoleCallback = callback; + return {}; + } + + async activateAudio() { + brightLog('๐Ÿฉธ Activating audio...'); + return this.eval(` + (async function() { + const canvas = document.querySelector('canvas'); + if (canvas) { + canvas.click(); + return 'Audio activated'; + } + document.body.click(); + return 'Audio activated via body'; + })() + `); + } + + async reload() { + return sendCommand('reload'); + } + + async screenshot() { + return sendCommand('screenshot'); + } + + close() { + this.connected = false; + darkLog('๐Ÿฉธ Closed'); + } + + on(event, handler) { + if (event === 'Runtime.consoleAPICalled') { + this.consoleCallback = handler; + } + } + + off(event) { + if (event === 'Runtime.consoleAPICalled') { + this.consoleCallback = null; + } + } + + // Static methods - panel control not needed in Electron + static async openPanelStandalone() { + brightLog('๐Ÿฉธ Electron webview ready'); + return true; + } + + static async closePanelStandalone() { + darkLog('๐Ÿฉธ Electron webview stays open'); + return true; + } +} + +/** + * Check if Electron bridge is available + */ +export function isElectronBridgeAvailable() { + return fs.existsSync(BRIDGE_DIR) || process.env.AC_ELECTRON === 'true'; +} + +export default ArteryElectron; + +// CLI test +if (import.meta.url === `file://${process.argv[1]}`) { + const cmd = process.argv[2]; + + console.log(`${CYAN}๐Ÿฉธ Artery Electron Bridge${RESET}\n`); + + if (cmd === 'test') { + (async () => { + try { + const artery = new ArteryElectron(); + await artery.connect(); + + const state = await artery.getState(); + console.log(`${GREEN}State:${RESET}`, state); + + artery.close(); + console.log(`\n${GREEN}โœ“ Test complete${RESET}`); + } catch (e) { + console.error(`${YELLOW}Error:${RESET}`, e.message); + process.exit(1); + } + })(); + } else { + console.log('Usage: node artery-electron.mjs test'); + } +} diff --git a/artery/test-configs.json b/artery/test-configs.json index 931ce173af..6927d3da55 100644 --- a/artery/test-configs.json +++ b/artery/test-configs.json @@ -13,6 +13,11 @@ ] }, "tests": { + "test-notepat-quick.mjs": { + "name": "notepat-quick", + "icon": "โšก", + "desc": "Quick notepat test (Electron compatible)" + }, "test-notepat-stability.mjs": { "name": "stability", "icon": "๐Ÿ”ฌ", diff --git a/artery/test-notepat-quick.mjs b/artery/test-notepat-quick.mjs new file mode 100644 index 0000000000..9889156282 --- /dev/null +++ b/artery/test-notepat-quick.mjs @@ -0,0 +1,148 @@ +#!/usr/bin/env node +/** + * ๐ŸŽน Notepat Quick Test (Electron Compatible) + * + * A simpler version of test-notepat.mjs that works with both CDP and Electron. + * Plays a short melody on notepat to verify the connection is working. + */ + +import { getArtery } from './artery-auto.mjs'; + +// Colors +const PURPLE_BG = '\x1b[45m'; +const WHITE = '\x1b[97m'; +const RESET = '\x1b[0m'; +const GREEN = '\x1b[92m'; +const CYAN = '\x1b[96m'; +const YELLOW = '\x1b[93m'; + +const testLog = (msg) => console.log(`${PURPLE_BG}${WHITE}๐Ÿงช${RESET} ${msg}`); +const successLog = (msg) => console.log(`${GREEN}โœ… ${msg}${RESET}`); + +// Note to key mapping (simplified) +const NOTE_KEYS = { + 'c': 'a', 'd': 's', 'e': 'd', 'f': 'f', 'g': 'g', 'a': 'h', 'b': 'j', + 'C': 'q', 'D': 'w', 'E': 'e', 'F': 'r', 'G': 't', 'A': 'y', 'B': 'u', +}; + +// Simple melody - Twinkle Twinkle first phrase +const MELODY = [ + { note: 'c', duration: 400 }, + { note: 'c', duration: 400 }, + { note: 'g', duration: 400 }, + { note: 'g', duration: 400 }, + { note: 'a', duration: 400 }, + { note: 'a', duration: 400 }, + { note: 'g', duration: 800 }, +]; + +async function pressKey(client, key) { + const code = `Key${key.toUpperCase()}`; + const keyCode = key.toUpperCase().charCodeAt(0); + + await client.send('Runtime.evaluate', { + expression: ` + (function() { + const event = new KeyboardEvent('keydown', { + key: '${key}', + code: '${code}', + keyCode: ${keyCode}, + which: ${keyCode}, + bubbles: true, + cancelable: true + }); + window.dispatchEvent(event); + })() + ` + }); +} + +async function releaseKey(client, key) { + const code = `Key${key.toUpperCase()}`; + const keyCode = key.toUpperCase().charCodeAt(0); + + await client.send('Runtime.evaluate', { + expression: ` + (function() { + const event = new KeyboardEvent('keyup', { + key: '${key}', + code: '${code}', + keyCode: ${keyCode}, + which: ${keyCode}, + bubbles: true, + cancelable: true + }); + window.dispatchEvent(event); + })() + ` + }); +} + +async function playNote(client, note, duration) { + const key = NOTE_KEYS[note]; + if (!key) return; + + await pressKey(client, key); + await new Promise(r => setTimeout(r, Math.min(duration, 200))); + await releaseKey(client, key); + await new Promise(r => setTimeout(r, duration - 200)); +} + +async function main() { + testLog('Notepat Quick Test (Electron Compatible)\n'); + + try { + // Get the appropriate Artery class + const Artery = await getArtery(); + + // Open panel (no-op in Electron) + await Artery.openPanelStandalone(); + await new Promise(r => setTimeout(r, 500)); + + // Connect + const client = new Artery(); + await client.connect(); + testLog('Connected'); + + // Navigate to notepat + await client.jump('notepat'); + testLog('Navigated to notepat'); + + // Wait for piece to load + await new Promise(r => setTimeout(r, 2000)); + + // Activate audio + await client.activateAudio(); + testLog('Audio activated'); + + await new Promise(r => setTimeout(r, 500)); + + // Play melody + console.log(`\n${CYAN}๐ŸŽต Playing Twinkle Twinkle...${RESET}\n`); + + for (const { note, duration } of MELODY) { + process.stdout.write(`${YELLOW}โ™ช${RESET}`); + await playNote(client, note, duration); + } + + console.log('\n'); + successLog('Melody complete!'); + + // Return to prompt + await new Promise(r => setTimeout(r, 1000)); + await client.jump('prompt'); + testLog('Returned to prompt'); + + client.close(); + await Artery.closePanelStandalone(); + + successLog('Test passed!\n'); + process.exit(0); + + } catch (err) { + console.error(`\n${YELLOW}Error:${RESET}`, err.message); + process.exit(1); + } +} + +main(); diff --git a/dotfiles/dot_config/emacs.el b/dotfiles/dot_config/emacs.el index 6e757358c5..c8375d99e5 100644 --- a/dotfiles/dot_config/emacs.el +++ b/dotfiles/dot_config/emacs.el @@ -220,20 +220,58 @@ Returns: 'ready, 'restarted, 'dead, or 'not-found" 'not-found)) ;;; --- Copilot Completion Notification --- -;; Flash artery-tui when Copilot response is done (called via MCP) +;; Flash current terminal when Copilot response is done (called via MCP) + +(defvar ac-notify-flash-active nil "Whether notification flash is currently active.") +(defvar ac-notify-flash-timer nil "Timer for notification flashing.") +(defvar ac-notify-flash-count 0 "Number of flash cycles completed.") +(defvar ac-notify-original-bg nil "Original background color before flash.") + +(defun ac-notify-stop-flash () + "Stop the notification flash and restore original background." + (interactive) + (when ac-notify-flash-timer + (cancel-timer ac-notify-flash-timer) + (setq ac-notify-flash-timer nil)) + (setq ac-notify-flash-active nil) + (setq ac-notify-flash-count 0) + ;; Restore original background + (when ac-notify-original-bg + (set-face-background 'default ac-notify-original-bg) + (setq ac-notify-original-bg nil)) + ;; Force redisplay + (redisplay t)) + +(defun ac-notify-do-flash () + "Perform one flash cycle." + (when ac-notify-flash-active + (setq ac-notify-flash-count (1+ ac-notify-flash-count)) + ;; Alternate between flash color and original + (if (= (mod ac-notify-flash-count 2) 1) + (set-face-background 'default "#1a3a1a") ; Dark green flash + (set-face-background 'default ac-notify-original-bg)) + (redisplay t) + ;; Continue flashing + (setq ac-notify-flash-timer + (run-at-time 0.25 nil #'ac-notify-do-flash)))) (defun ac-notify-done (&optional message) - "Notify completion by signaling artery-tui to flash and switching to artery tab. + "Notify completion by flashing the current buffer background. +Flash continues until user clicks or presses a key. Called by MCP tools at the end of each response." (interactive) (let ((msg (or message "Done"))) - ;; Create signal file that artery-tui watches + ;; Also signal artery-tui (for when viewing that tab) (with-temp-file "/tmp/ac-copilot-done" (insert "done")) - ;; Switch to artery tab so user sees the flash - (condition-case nil - (tab-bar-switch-to-tab "artery") - (error nil)) + ;; Start flashing in current buffer + (unless ac-notify-flash-active + (setq ac-notify-original-bg (face-background 'default nil t)) + (setq ac-notify-flash-active t) + (setq ac-notify-flash-count 0) + (ac-notify-do-flash) + ;; Stop flash on any input (mouse or keyboard) + (add-hook 'pre-command-hook #'ac-notify-stop-flash)) (message "๐Ÿ”” %s" msg))) (ac-perf-session-start) @@ -316,8 +354,26 @@ Called by MCP tools at the end of each response." (derived-mode-p 'eat-mode)) (display-line-numbers-mode -1))) +(defun ac-optimize-eat-terminal () + "Disable heavy modes in eat terminal buffers for better performance." + ;; Disable line numbers + (display-line-numbers-mode -1) + ;; Disable evil-mode (use emacs keybindings in terminals) + (when (and (boundp 'evil-local-mode) (fboundp 'evil-local-mode)) + (evil-local-mode -1)) + ;; Disable origami (code folding not needed in terminal) + (when (and (boundp 'origami-mode) (fboundp 'origami-mode)) + (origami-mode -1)) + ;; Disable yascroll (scrollbar causes rendering overhead) + (when (and (boundp 'yascroll-bar-mode) (fboundp 'yascroll-bar-mode)) + (yascroll-bar-mode -1)) + ;; Disable fill column indicator + (when (fboundp 'display-fill-column-indicator-mode) + (display-fill-column-indicator-mode -1))) + (add-hook 'eshell-mode-hook 'disable-line-numbers-in-modes) (add-hook 'eat-mode-hook 'disable-line-numbers-in-modes) +(add-hook 'eat-mode-hook 'ac-optimize-eat-terminal) (add-hook 'image-mode-hook 'disable-line-numbers-in-modes) ;; Electric pairs @@ -973,15 +1029,23 @@ Skips creation if tab already exists." (kill-buffer buf))) (error nil)) + ;; Helper to check if a tab with a given name exists + (defun ac--tab-exists-p (name) + "Return t if a tab named NAME exists." + (seq-find (lambda (tab) (string= name (alist-get 'name tab))) + (tab-bar-tabs))) + ;; Initialize the first tab as "artery" with artery CLI (dev mode with hot-reload) - ;; Only create if it doesn't already exist - (unless (get-buffer "๐Ÿฉธ-artery") + ;; Only create if the tab doesn't already exist + (unless (ac--tab-exists-p "artery") (tab-rename "artery") (let ((default-directory ac--directory-path) - (buf (generate-new-buffer "๐Ÿฉธ-artery"))) + (buf (or (get-buffer "๐Ÿฉธ-artery") + (generate-new-buffer "๐Ÿฉธ-artery")))) (with-current-buffer buf - (eat-mode) - (eat-exec buf "๐Ÿฉธ-artery" "/usr/bin/fish" nil '("-c" "ac-artery-dev")) + (unless (eq major-mode 'eat-mode) + (eat-mode) + (eat-exec buf "๐Ÿฉธ-artery" "/usr/bin/fish" nil '("-c" "ac-artery-dev"))) ;; Enable semi-char mode so TUI gets individual keypresses (eat-semi-char-mode) ;; Disable evil mode for artery - use emacs state @@ -991,40 +1055,52 @@ Skips creation if tab already exists." (redisplay t))) ; Yield to prevent freeze ;; Create fishy tab (plain fish shell for quick terminal access via LLM) - ;; Only create if it doesn't already exist - (unless (get-buffer "๐ŸŸ-fishy") + ;; Only create if the tab doesn't already exist + (unless (ac--tab-exists-p "fishy") (tab-new) (tab-rename "fishy") (let ((default-directory ac--directory-path) - (buf (generate-new-buffer "๐ŸŸ-fishy"))) + (buf (or (get-buffer "๐ŸŸ-fishy") + (generate-new-buffer "๐ŸŸ-fishy")))) (with-current-buffer buf - (eat-mode) - (eat-exec buf "๐ŸŸ-fishy" "/usr/bin/fish" nil nil) + (unless (eq major-mode 'eat-mode) + (eat-mode) + (eat-exec buf "๐ŸŸ-fishy" "/usr/bin/fish" nil nil)) (eat-semi-char-mode) (when (and (boundp 'evil-mode) evil-mode) (evil-emacs-state))) (switch-to-buffer buf) (redisplay t))) - ;; Create all the split tabs immediately (no delays) - (dolist (tab-spec '(("status" ("url" "tunnel")) - ("stripe" ("stripe-print" "stripe-ticket")) - ("chat" ("chat-system" "chat-sotce" "chat-clock")) - ("web 1/2" ("site" "session")) - ("web 2/2" ("redis" "bookmarks" "oven" "media")) - ("tests" ("kidlisp")) - ("llm" ("llm")) - ("top" ("top")))) ; Process viewer tab - (let ((tab-name (car tab-spec)) - (commands (cadr tab-spec))) - (ac--create-split-tab tab-name commands))) - - ;; Switch to the requested tab - (run-with-timer 0.5 nil + ;; Create all the split tabs with staggered delays to prevent terminal garbling + (let ((delay 0.3) + (tab-specs '(("status" ("url" "tunnel")) + ("stripe" ("stripe-print" "stripe-ticket")) + ("chat" ("chat-system" "chat-sotce" "chat-clock")) + ("web 1/2" ("site" "session")) + ("web 2/2" ("redis" "bookmarks" "oven" "media")) + ("tests" ("kidlisp")) + ("llm" ("llm")) + ("top" ("top"))))) ; Process viewer tab + (dolist (tab-spec tab-specs) + (let ((tab-name (car tab-spec)) + (commands (cadr tab-spec)) + (current-delay delay)) + (run-with-timer current-delay nil + (lambda (name cmds) + (ac--create-split-tab name cmds) + (redisplay t)) + tab-name commands) + (setq delay (+ delay 0.3))))) ; 300ms between each tab + + ;; Switch to the requested tab (after all tabs created - 8 tabs * 0.3s = 2.4s + buffer) + (run-with-timer 3.0 nil (lambda (target) (condition-case nil (if (member target '("artery" "fishy" "status" "stripe" "chat" "web 1/2" "web 2/2" "tests" "llm" "top")) - (tab-bar-switch-to-tab target) + (progn + (tab-bar-switch-to-tab target) + (redisplay t)) (message "No such tab: %s" target)) (error nil))) target-tab)) diff --git a/dotfiles/fish/functions/electric-snake-bite.fish b/dotfiles/fish/functions/electric-snake-bite.fish new file mode 100644 index 0000000000..087ed9c73f --- /dev/null +++ b/dotfiles/fish/functions/electric-snake-bite.fish @@ -0,0 +1,28 @@ +#!/usr/bin/env fish +# โšก๐Ÿ Electric Snake Bite +# +# Triggers a reload of the Electron development window from inside the devcontainer. +# Works by outputting a special escape sequence that the Electron terminal watches for. +# +# Usage: electric-snake-bite +# esb (alias) + +function electric-snake-bite --description "โšก๐Ÿ Reload Electron dev window" + # Output the magic escape sequence + # OSC 9999 is a custom/unused OSC code we're hijacking + printf '\e]9999;electric-snake-bite\a' + echo "โšก๐Ÿ Electric Snake Bite sent! Window should reload..." +end + +# Short alias +function esb --description "โšก๐Ÿ Alias for electric-snake-bite" + electric-snake-bite +end + +# If called directly, run it +if status is-interactive + # Just define the functions +else + # Called as script - execute + electric-snake-bite +end -- knotmirror 0.0.1