# msger TODO List

> **📋 Feature Comparison:** See `Y:\dev\utils\msgview\TODO.md` for complete feature comparison table between msger and msgview

## Recent Session (2025-11-12) - Warning Cleanup

**Status:** ✅ COMPLETED - Version 0.1.95

### What Was Fixed:

1. **Rust Compiler Warnings**
   - Fixed "unused variable: webview" warning on Linux
   - Fixed "variable does not need to be mutable" warning
   - Fixed "unused Result that must be used" warning
   - Added `#[cfg_attr(not(windows), allow(unused_variables))]` for webview (only used on Windows for About menu)
   - Changed `let mut webview` to `let webview`
   - Changed `SetWindowSubclass(...).ok();` to `let _ = SetWindowSubclass(...).ok();`

### Testing:
- ✅ Windows build: Zero warnings
- ✅ Linux build: Zero warnings
- ✅ Windows runtime: Working perfectly
- ✅ WSL runtime: Working perfectly

---

## Session (2025-11-12) - WSL Linux Support Fixed

**Status:** ✅ COMPLETED - Version 0.1.94

### What Was Implemented:

1. **Fixed WSL/Linux Support**
   - Root cause: `wry` webview library requires platform-specific builders on Linux
   - Windows uses `.build(window.as_ref())` with native window handles
   - Linux requires `.build_gtk(vbox)` with GTK container
   - Added imports:
     - `tao::platform::unix::WindowExtUnix` for Linux
     - `wry::WebViewBuilderExtUnix` for Linux
   - Added conditional compilation to use correct builder per platform
   - Location: msger-native/src/main.rs

2. **Fixed Build Script Binary Placement**
   - Linux binary was placed in wrong location (`../msgernative-linux-x64`)
   - shower.ts expected it in `msger-native/bin/msgernative`
   - Updated build.ts to copy to correct location
   - Also maintains old location for compatibility

3. **Platform-Specific Imports**
   - Made Windows-specific imports conditional with `#[cfg(target_os = "windows")]`
   - Added Linux-specific imports with `#[cfg(target_os = "linux")]`
   - Prevents compilation errors when building for different platforms

### Files Changed:
- `msger-native/src/main.rs` - Added GTK support for Linux webview creation
- `msger-native/build.ts` - Fixed binary placement for Linux builds
- `package.json` - Version bump to 0.1.94

### Testing:
- ✅ Windows build and runtime (v0.1.94)
- ✅ Linux build via WSL (v0.1.94)
- ✅ WSL runtime - window displays correctly with GTK/webkit2gtk
- ✅ Timeout functionality works in WSL
- ✅ Button responses work in WSL

### Previous WSL Issue - RESOLVED:
- Previous error: `Failed to create webview: UnsupportedWindowHandle`
- Cause: Using `.build(window.as_ref())` on Linux instead of `.build_gtk(vbox)`
- Fix: Implemented platform-specific webview building
- WSL now works perfectly with WSLg GUI support

---

## Session (2025-11-12) - Hash Option, F11 Fix, Button Response, Debug Mode

**Status:** ✅ COMPLETED - Version 0.1.91 (published to npm)

### Installation Status:
- ✅ Windows build successful (0.1.91)
- ✅ Published to npm as @bobfrankston/msger@0.1.91
- ✅ Installed globally (required `taskkill /im msger*` to unlock files)
- ❌ WSL fails with `UnsupportedWindowHandle` error (tested with v0.1.91)

### Known Issues:
1. **WSL Build Error (E0432)**
   - WSL Linux build fails during Rust compilation in installer script
   - Error: Could not compile msgernative (bin "msgernative")
   - Needs investigation of import/dependency issue
   - Impact: Can't build Linux binary from Windows, but published npm package includes prebuilt binary

2. **WSL Runtime Error - CONFIRMED in v0.1.91**
   - Error: `Failed to create webview: UnsupportedWindowHandle`
   - Location: main.rs:314 (`.build(window.as_ref())`)
   - Root cause: WSL doesn't have native GUI/display server for Windows apps
   - The `wry` crate requires a native window handle (HWND on Windows, X11 on Linux)
   - **WSL environment:**
     - Running from `wsl msger` tries to use Windows binary with WSL context
     - No valid window handle available in this hybrid environment
   - **Resolution options:**
     1. Use WSLg (Windows 11) - may need DISPLAY env var configuration
     2. Run from Windows PowerShell instead: `msger "hello"` (works perfectly)
     3. Future: Investigate if WSL2 GUI apps can create windows
   - **Workaround:** Always run msger from Windows, not through `wsl` command

3. **Installation Tip**
   - Running msger processes can block file updates
   - Before installing: `taskkill /im msger* /F` or close all msger windows
   - This frees up binary files for replacement

### Next Steps:
1. Wait ~5-10 minutes for npm to propagate version 0.1.91
2. Run `npm install -g @bobfrankston/msger` to install globally on Windows
3. Investigate WSL build error (likely missing import or dependency issue)
4. Optional: Manually install in WSL with `wsl npm install -g @bobfrankston/msger`

### What Was Implemented:

1. **Hash Fragment Option (`-hash`)**
   - Appends hash fragment to URL (e.g., `-url "https://example.com" -hash section1`)
   - Automatically strips leading # to avoid ##
   - Requires `-url` to be set (throws error if hash without url)
   - Supported in JSON config files
   - Implementation: shower.ts:204-212
   - **Status:** ✅ Working

2. **F11 Fullscreen Fix**
   - **Issue:** JavaScript was intercepting F11 key and using HTML5 fullscreen instead of native
   - **Fix:** Changed JavaScript F11 handler to use IPC `toggleFullscreen` action
   - Now uses Rust's native window fullscreen (same as Rust's F11 handler)
   - Implementation: template.html:329-348
   - **Status:** ✅ Working

3. **Button Response Optimization**
   - **Issue:** OK button sometimes took long time to exit window
   - **Fix:** Optimized event loop to check for button result first in MainEventsCleared
   - Window now exits immediately when button clicked
   - Implementation: main.rs:704-715
   - **Status:** ✅ Working - instant response

4. **Debug Mode (MSGER_DEBUG)**
   - Added optional debug logging controlled by environment variable
   - Usage: `$env:MSGER_DEBUG=1` then run msger
   - Shows: startup, keyboard events, IPC messages, button clicks, exit flow
   - Zero performance impact when disabled (compile-time checks)
   - Implementation: main.rs:257-277, 612-635, 444-534
   - **Status:** ✅ Working

5. **Build Process Improvements**
   - Commented out Raspberry Pi build warning (build.ts:178-185)
   - Added automatic PATH cleaning for Windows builds to fix Git link.exe vs VS linker conflict
   - PATH fix function removes Git's /usr/bin from PATH (build.ts:34-43)
   - **Status:** ✅ Working

6. **Context Menu (Right-Click)**
   - Attempted to add right-click context menu with Fullscreen toggle
   - Code implemented in template.html and msger-api.js
   - **Issue:** Menu conflicts with Windows system menu, simulated F12 doesn't work
   - **Decision:** Commented out for now, F11/F12 keyboard shortcuts work fine
   - **Status:** ⏸️ Code exists but commented out in template.html and msger-api.js
   - **TODO:** Revisit context menu implementation - possibly add more useful items or improve UX

7. **Project Cleanup**
   - Moved all test HTML files to `tests/` directory
   - Files: test-msger-api.html, test-msger-functions.html, test-data-persistence.html, test-ipc-reach.html, msger-storage-demo.html, test-htmlfrom.html

### Files Modified:
- `package.json` - Version bumped to 0.1.90
- `shower.ts` - Added hash field to MessageBoxOptions, hash append logic
- `clihandler.ts` - Added -hash CLI parsing, save/load support
- `README.md` - Documented -hash option, removed context menu mentions
- `msger-native/build.ts` - Pi warning removed, PATH fix added
- `msger-native/src/main.rs` - Debug mode, F11 handling, button response optimization
- `msger-native/src/template.html` - F11 IPC fix, context menu code (commented out)
- `msger-native/src/msger-api.js` - Context menu code (commented out)
- Test files moved to `tests/` directory

### Testing:
```bash
# Hash option
node . -url "https://example.com" -hash section1

# Debug mode
$env:MSGER_DEBUG=1
node . "Test message"

# F11 fullscreen toggle - works instantly
# F12 DevTools - works
# OK button - instant response
```

### Future Work:
- Consider more useful context menu items (Copy, Paste, etc.)
- Investigate better UX to distinguish from Windows system menu
- Possibly use Ctrl+Right-click or custom activation method

---

## Recent Session (2025-11-11) - Configuration Management

**Status:** ✅ COMPLETED

### What Was Implemented:

1. **Architecture Simplification**
   - Rust binary now ONLY reads JSON from stdin (removed clap, CLI parsing, file I/O)
   - TypeScript wrapper handles ALL complexity (CLI, file I/O, JSONC parsing, merging)
   - Cleaner separation: Rust = display engine, TypeScript = orchestration

2. **-load/-save Configuration Management**
   - `-load <file>` - Load config from JSON file (supports comments via JSON5)
   - `-save <file>` - Save only explicitly specified CLI arguments (not defaults)
   - Auto `.json` extension: `myconfig` → `myconfig.json` (uses `path.extname()`)
   - Merge logic: CLI args override loaded config values

3. **-noshow Flag**
   - Save config without displaying message box
   - NOT saved in JSON (runtime flag only)
   - Usage: `msger -title "Test" -message "Hello" -save myconfig -noshow`

4. **Screen Numbering Fix**
   - Monitors sorted by physical layout (matching winpos)
   - Bottom row first (higher Y), then left to right (lower X)
   - Implementation in `main.rs:285-297`

5. **Documentation Updated**
   - README.md: Added -load/-save examples, -noshow flag, auto-extension notes
   - Help text: Updated with new options
   - All examples tested and working

### Files Modified:
- `msger-native/Cargo.toml` - Removed clap dependency
- `msger-native/src/main.rs` - Removed CLI parsing, added screen sorting
- `package.json` - Added json5 dependency
- `cli.ts` - Added load/save/noshow handling, auto-extension logic
- `clihandler.ts` - Added CLI options, loadConfigFile(), saveConfigFile()
- `README.md` - Documented new features

### Usage Examples:
```bash
# Load and override
msger -load myconfig -title "Override"

# Save minimal config (only specified args)
msger -title "Test" -message "Hello" -save myconfig -noshow

# Auto-extension
msger -save myconfig        # Creates myconfig.json
msger -load myconfig        # Loads myconfig.json
```

### Known Issues / Next Steps:
- None - all features working and tested
- Version bumped to 0.1.84 (already in package.json)

---

## High Priority - Platform App Support

### 1. File System API (Week of 2025-11-11+)
**Goal:** Make msger feasible for writing platform apps with file access

**Status:** Not started - requires debugging time

**Implementation:**

#### A) File Dialogs (Always Safe - No Flag Required)
```javascript
await msger.selectFile(options)      // Pick single file → {path, content}
await msger.selectFiles(options)     // Pick multiple files → [{path, content}...]
await msger.saveFileAs(content, name, options)  // Save dialog → path
await msger.selectFolder(options)    // Folder picker → path
```

#### B) Direct File Access (Requires --allowFs Flag)
```javascript
// Direct file operations by path - requires: msger -htmlfrom app.html --allowFs
await msger.fs.read(path)            // Read file content
await msger.fs.write(path, content)  // Write file
await msger.fs.list(path)            // List directory
await msger.fs.exists(path)          // Check if exists
await msger.fs.delete(path)          // Delete file
await msger.fs.mkdir(path)           // Create directory
```

**Why it's possible:**
- IPC works perfectly in template mode (proven by button clicks)
- Just need bidirectional IPC pattern (JavaScript → Rust → JavaScript)
- Use `rfd` crate for native file dialogs

**Steps:**
- [ ] Add `rfd = "0.14"` to Cargo.toml
- [ ] Add `allowFs` flag to MessageBoxOptions struct
- [ ] Extend IPC handler to recognize file actions
- [ ] Implement file dialog operations (always allowed)
- [ ] Implement direct path operations (check allowFs flag first)
- [ ] Send results back via `webview.evaluate_script()`
- [ ] Add JavaScript functions that poll for result in `window.__msger_file_result`
- [ ] Test file dialogs
- [ ] Test direct file operations with --allowFs flag
- [ ] Test security (direct operations should fail without --allowFs)
- [ ] Update documentation (README, MSGER-API-SUMMARY, msgerdefs)
- [ ] Create sample apps demonstrating file API

---

### 2. Window Manipulation APIs via IPC
**Goal:** Runtime window control in template mode

**Status:** Not started - requires debugging time

**Implementation:**
```javascript
await msger.setSize(width, height)
await msger.setPosition(x, y)
await msger.setTitle(title)
await msger.setAlwaysOnTop(enabled)
await msger.minimize()
await msger.maximize()
```

**Why it's possible:**
- IPC works in template mode
- These were disabled prematurely thinking ALL IPC was broken
- Can be re-enabled with bidirectional IPC pattern (same as file API)

**Steps:**
- [ ] Extend IPC handler to recognize window actions
- [ ] Implement window manipulation functions in Rust
- [ ] Send results/confirmations back via `webview.evaluate_script()`
- [ ] Add JavaScript async functions
- [ ] Test in template mode
- [ ] Verify still crashes in URL mode (expected)
- [ ] Update documentation

---

### 3. System Menu (Windows Title Bar Menu)
**Goal:** Add custom entries to Windows system menu as alternative to keyboard shortcuts

**Status:** Not started - Windows-specific feature

**Problem:**
- Keystrokes don't reliably reach the window (WebView2 captures them first)
- F11 doesn't trigger native fullscreen
- No easy way to toggle features at runtime

**Solution:** Add custom entries to Windows system menu (Alt+Space or right-click title bar)

**Menu Items to Add:**
- Toggle Always On Top (with checkmark showing current state)
- Zoom submenu → 50%, 75%, 100%, 125%, 150%, 200%
- Toggle Fullscreen (native window fullscreen)
- Open DevTools (F12 alternative)
- Reload Content (refresh)
- Separator
- Copy Window Info (position, size, monitor - for debugging)

**Steps:**
- [ ] Get window HWND from tao window using `raw_window_handle()`
- [ ] Call Windows API: `GetSystemMenu(hwnd, FALSE)`
- [ ] Add separator: `AppendMenuW(menu, MF_SEPARATOR, 0, NULL)`
- [ ] Add custom menu items with unique IDs (>= 0x1000)
- [ ] Store window state (always on top, zoom level, fullscreen)
- [ ] Handle `WM_SYSCOMMAND` in window event loop
- [ ] Check if wParam matches custom menu IDs
- [ ] Execute appropriate action
- [ ] Update menu checkmarks when state changes
- [ ] Test all menu items
- [ ] Document in README (mention Alt+Space to access)

**Libraries needed:**
- `winapi` crate (already in dependencies)
- `use winapi::um::winuser::{GetSystemMenu, AppendMenuW, MF_STRING, MF_SEPARATOR, MF_CHECKED};`

**Why this works:**
- Bypasses WebView2 keyboard capture
- Native Windows UI, familiar to users
- Can show current state (checkmarks)
- Works in both template and URL mode

---

## Medium Priority - Maintenance

### 4. Periodic wry Update Check
**Goal:** Check if newer wry versions fix URL mode IPC crash

**Status:** Recurring task - check every few months

**Current:** wry 0.47.2 has IPC crash bug in URL mode

**Steps:**
- [ ] Check wry releases: https://github.com/tauri-apps/wry/releases
- [ ] Read changelog for IPC/WebView2 fixes
- [ ] Test with newer version if promising
- [ ] If fixed: update Cargo.toml, test thoroughly, document
- [ ] If fixed: re-enable file/window APIs in URL mode

**Next check:** January 2025

---

## Low Priority - Enhancements

### 5. Auto-Update Window Title from Document (URL Mode)
**Goal:** When using -url, automatically set window title from document's <title> tag

**Status:** Not started - enhancement

**Current behavior:**
- Window title comes from -title flag or defaults to "Message"
- -url mode ignores document's <title> tag
- User must manually specify title or get generic "Message" title

**Desired behavior:**
- If -title flag provided: use it (explicit override)
- If -title NOT provided and using -url: extract title from document's <title> tag
- Works like a browser - shows page title in window title bar

**Implementation approaches:**

**Option A: Listen for title changes (recommended)**
```rust
// In webview builder
.with_navigation_handler(|uri| {
    // Allow navigation
    true
})
// After page loads, get title via JavaScript
webview.evaluate_script("document.title").then(|title| {
    window.set_title(&title);
});
```

**Option B: Use WebView2 DocumentTitleChanged event**
```rust
// Windows-specific: Listen for DocumentTitleChanged event
// Update window.set_title() when document title changes
```

**Steps:**
- [ ] Check if -title flag was explicitly provided (distinguish from default)
- [ ] If -url mode AND no explicit -title: enable auto-title
- [ ] After page loads, extract document.title via JavaScript
- [ ] Call `window.set_title()` with extracted title
- [ ] Listen for dynamic title changes (SPA navigation)
- [ ] Test with static HTML files
- [ ] Test with dynamic web pages
- [ ] Test with pages that change title dynamically
- [ ] Document in README: "Window title automatically uses document <title> when using -url without -title flag"

**Edge cases:**
- Page with no <title> tag: fallback to URL or "Message"
- Page that changes title dynamically: update window title
- SPA navigation: keep listening for title changes

---

### 6. Cross-Compile Support for Raspberry Pi on Windows
**Goal:** Build ARM64 binary on Windows without SSH to Pi

**Status:** Not started - nice to have

**Current approach:** SSH to Pi, build there, copy back

**Research:**
- Rust cross-compilation to ARM64 Linux
- Install ARM64 toolchain on Windows
- Configure Cargo for cross-compilation
- Test binary on actual Pi

**Links:**
- https://www.perplexity.ai/search/can-the-rust-tool-chain-compil-kTNtAElGREq2YIU8qCpx_Q#1

---

### 6. Linux System Menu Support
**Goal:** Add custom menu entries on Linux (if possible)

**Status:** Not started - research needed

**Question:** Does GTK/Linux have equivalent to Windows system menu?

**Research:**
- GTK menu bar integration
- Custom right-click menu on title bar
- Alternative: Add menu bar inside webview content

---

### 7. Improve CSP for -htmlfrom
**Goal:** Allow external resources when using -htmlfrom

**Status:** Not started - may be wry limitation

**Current:** CSP blocks external CSS/JS/images when embedding HTML

**Workaround:** Use -url for pages with external resources

**Research:**
- Can we configure WebView2 CSP?
- Can we inject meta CSP tag?
- Can we proxy external resources?

---

## Open Bugs

None currently known!

---

## Completed ✅

- ✅ JSON configuration file support (2025-11-11)
  - Load from file: `msgernative config.json` or `-json config.json`
  - CLI arguments override JSON values
  - Pure CLI mode works without JSON
  - Added `clap` crate for argument parsing
- ✅ Windows system menu integration (2025-11-11)
  - "About (Window Info)" entry in system menu
  - Shows window position, size, DPI scaling details
  - Uses Windows API (GetSystemMenu, AppendMenuW)
  - Window subclassing for WM_SYSCOMMAND handling
- ✅ Code refactoring (2025-11-11)
  - Extracted JavaScript API to msger-api.js
  - Uses include_str! for compile-time embedding
  - Cleaner separation of concerns
- ✅ Multi-monitor positioning fix - Rust side (2025-11-06)
- ✅ Multi-monitor positioning fix - CLI parsing bug (2025-11-06)
  - Fixed: `-pos 10,10,1` now correctly parses third parameter as screen number
  - Previously: Only `-pos 10,10 -screen 1` worked
- ✅ Remove redundant localStorage API wrappers (2025-11-06)
- ✅ Add repository field to package.json files (2025-11-06)
- ✅ Fix `nul` file git error (2025-11-06)
- ✅ Isolated storage with custom WebContext
- ✅ F11 HTML5 fullscreen implementation
- ✅ -htmlfrom option (load HTML from file/URL with buttons)
- ✅ -fullscreen CLI flag for native window fullscreen
- ✅ -dev flag parsing (partial - can't auto-open DevTools)
- ✅ Icon support with -icon option
- ✅ Fix zoomLevel declaration order bug
- ✅ Template mode IPC for button results

---

## Notes

**Development Priority:**
1. File System API - Most important for platform apps
2. System Menu - Best UX alternative to keyboard shortcuts
3. Window Manipulation APIs - Nice to have, lower priority
4. Everything else - As time permits

**Testing Strategy:**
- Always test in both template mode and URL mode
- Verify file API security (--allowFs flag enforcement)
- Test on multi-monitor setups
- Create sample apps demonstrating new features

**Documentation Updates Required for Each Feature:**
- README.md - User-facing documentation
- SESSION-NOTES.md - Development notes
- MSGER-API-SUMMARY.md - API reference
- msgerdefs/README.md - TypeScript package docs
- Update msgerdefs TypeScript definitions

### GTK/Linux Rendering Issue (Pi, WSL)
**Status:** 🔍 INVESTIGATING - See [PI-RENDERING-NOTES.md](PI-RENDERING-NOTES.md) for details

**Problem:**
- GTK window shows garbled rendering on Linux (Pi ARM64, WSL x64)
- Brief valid header appears, then screen corrupts
- Affects all webkit2gtk-based platforms

**Investigation:**
- Attempted `vbox.show_all()` / `vbox.show()` before `build_gtk()` - failed (requires gtk::prelude import)
- WebView framework alternatives documented in PI-RENDERING-NOTES.md
- Consider trying Tauri framework (built on wry with better GTK handling)

**Current Workaround:**
- Windows build works perfectly
- Linux builds compile but rendering broken

**Next Steps:**
- Research Tauri framework as wry replacement
- Check wry GitHub issues for similar GTK rendering bugs
- Consider webkit2gtk direct integration for more control
