tauri-plugin-debug-tools 0.1.4

Debug utilities for Tauri WebView apps.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# tauri-plugin-debug-tools

Comprehensive debug utilities for Tauri WebView applications with AI-powered automated debugging workflows.

## Features

- **WebView State Capture** - Capture URL, title, viewport, and User-Agent
- **Console Log Collection** - Ring-buffer based log collection with batched flushing
- **Screenshot Integration** - System screenshot command integration
- **AI Agent Skill** - Automated debugging workflow for AI agents
- **Debug Snapshots** - Save comprehensive debug state to disk
- **Event-based Communication** - Send debug commands to frontend via Tauri events

## Quick Start

### Installation

Add to your Tauri project's `Cargo.toml`:

```toml
[dependencies]
tauri-plugin-debug-tools = "0.1.1"
```

Install the frontend package:

```bash
npm install tauri-plugin-debug-tools
# or
bun add tauri-plugin-debug-tools
```

### Setup

**1. Register the plugin** in your Tauri app:

```rust
// src-tauri/src/main.rs or lib.rs
fn main() {
    tauri::Builder::default()
        .plugin(tauri_plugin_debug_tools::init())
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
```

**2. Configure the plugin (optional)** in your `tauri.conf.json` if you want to override defaults:

```json
{
    "plugins": {
        "debug-tools": {
            "timeout": 30
        }
    }
}
```

If you don't need custom configuration, you can omit this section.

**3. Enable permissions** in `src-tauri/capabilities/default.json`:

```json
{
  "permissions": [
    "debug-tools:default"
  ]
}
```

    **4. Initialize frontend logger** in your app entry point:

```typescript
// src/main.ts or src/App.tsx
import { debugTools } from "tauri-plugin-debug-tools/consoleLogger";

// Use instead of console.*
debugTools.log("Application started");
debugTools.error("Something went wrong");

// Or import individual functions
import { log, error, warn } from "tauri-plugin-debug-tools/consoleLogger";
```

## Usage

### Frontend API

#### Console Logging

```typescript
import { debugTools, consoleLogger } from "tauri-plugin-debug-tools/consoleLogger";

// Log messages (automatically collected)
debugTools.log("Info message");
debugTools.warn("Warning message");
debugTools.error("Error message", { context: "data" });

// Retrieve logs
const allLogs = consoleLogger.getLogs();
const errors = consoleLogger.getErrors();
const recent = consoleLogger.getRecentLogs(50);

// Get statistics
const stats = consoleLogger.getStats();
// { total: 150, byLevel: { log: 100, warn: 30, error: 20, info: 0, debug: 0 } }
```

#### WebView State Inspection

```typescript
import { captureWebViewState } from "tauri-plugin-debug-tools/debugBridge";

const state = await captureWebViewState();
console.log(state);
// {
//   url: "http://localhost:5173",
//   title: "My App",
//   user_agent: "TauriWebView/2.0",
//   viewport: { width: 1200, height: 800 }
// }
```

#### Debug Commands

```typescript
import { sendDebugCommand } from "tauri-plugin-debug-tools/debugBridge";

// Send event-based commands to frontend
await sendDebugCommand("refresh_state", { force: true });
```

### Backend Commands

All commands are available through the Tauri IPC system:

| Command | Description | Output |
| ------- | ----------- | ------ |
| `capture_webview_state` | Capture WebView state | `WebViewState` JSON |
| `get_console_logs` | Legacy console logs | Empty array (use frontend logger) |
| `send_debug_command` | Send event to frontend | Success message |
| `append_debug_logs` | Append logs to file | Returns actual file path string |
| `reset_debug_logs` | Clear log file | Returns actual file path string |
| `clear_debug_log_files_command` | Delete/truncate debug log files | `ClearDebugLogsResult` JSON |
| `copy_screenshot_to_debug_dir` | Copy screenshot to debug-tools/screenshots | `CopyScreenshotResult` JSON |
| `write_debug_snapshot` | Save debug snapshot (legacy, uses temp dir) | Returns actual file path string |

#### Finding Log File Locations

Both `reset_debug_logs` and `append_debug_logs` commands return the actual file path where logs are stored:

```typescript
import { invoke } from '@tauri-apps/api/core';

// Get log file path
const logPath = await invoke('plugin:debug-tools|reset_debug_logs');
console.log('Logs are stored at:', logPath);
// Example output: "/Users/you/Library/Logs/com.example.app/debug-tools/frontend_console_my_app_12345.jsonl"
```

**Typical locations:**

- **macOS**: `~/Library/Logs/<bundle-id>/debug-tools/frontend_console_[app_name]_[pid].jsonl`
- **Linux/Windows**: Application log directory resolved by Tauri path APIs

Where `[app_name]` is the application name from `package_info` and `[pid]` is the process ID.

The exact path can vary by host app configuration. Always use the path returned by `reset_debug_logs` / `append_debug_logs` as the source of truth.

#### Clear Debug Log Files

```typescript
import { invoke } from '@tauri-apps/api/core';

const result = await invoke('plugin:debug-tools|clear_debug_log_files_command');
console.log(result);
// {
//   deleted_paths: [...],
//   truncated_paths: [...],
//   failed_paths: [...]
// }
```

`clear_debug_log_files_command` cleans up files under the plugin log root (`.../debug-tools`) and these subdirectories when they exist:

- `dom_snapshots/`
- `screenshots/`

Typical startup workflow in host apps:

1. Call `clear_debug_log_files_command` once during app boot.
2. Re-capture runtime artifacts (for example `capture_dom_snapshot`) after initialization.

#### Live Monitoring (Recommended)

```bash
LOG_DIR="$HOME/Library/Logs/<bundle-id>/debug-tools"
LATEST=$(ls -1t "$LOG_DIR"/frontend_console_*.jsonl | head -n 1)
tail -f "$LATEST"
```

If you don't know the exact location, fetch it via IPC first:

```bash
# in your host app code, call once:
# invoke('plugin:debug-tools|reset_debug_logs')
# then monitor the returned absolute path
```

Filter error logs only:

```bash
grep -in '"level":"error"' "$LATEST"
```

#### Copy Screenshot to Debug Directory

`tauri-plugin-screenshots` saves screenshots to `app_data_dir/tauri-plugin-screenshots/`. Use `copy_screenshot_to_debug_dir` to copy them into the unified debug-tools directory:

```typescript
import { captureMainWindowToDebugDir } from "tauri-plugin-debug-tools/screenshotHelper";

// Capture and copy in one step
const path = await captureMainWindowToDebugDir();
console.log(path);
// ~/Library/Logs/<bundle-id>/debug-tools/screenshots/1740145200_window-1.png
```

Or manually:

```typescript
import { invoke } from '@tauri-apps/api/core';

const result = await invoke('plugin:debug-tools|copy_screenshot_to_debug_dir', {
  sourcePath: '/path/to/screenshot.png'
});
console.log(result.destination_path);
```

## AI Agent Skill

### Skill Installation

Copy the bundled skill to your agent's skills directory:

(example: Codex)

```bash
cp -R skills/debug-tauri ~/.codex/skills/debug-tauri
```

Or for custom skill directories:

```bash
cp -R skills/debug-tauri /path/to/your/skills/debug-tauri
```

### Skill Usage

Invoke the skill to start automated debugging:

```bash
/debug-tauri
```

The skill will:

1. ✅ Verify the app process is running
2. 📸 Capture a screenshot
3. 📝 Collect console logs (via IPC)
4. 🔍 Analyze visual and runtime state
5. 📄 Generate a comprehensive debug report
6. 💡 Propose fixes based on findings

### Example Report

```markdown
# Tauri Debug Report - 2025-12-31T22:00:00Z

## Screenshot
/tmp/tauri_debug_1735689600.png

## Process Status
- Status: Running
- PID: 12345

## Console Logs
### Recent Errors
- [ERROR] WebGL context lost (timestamp: 1735689550)
- [ERROR] Failed to load texture.png (timestamp: 1735689555)

### Log Statistics
- Total: 1,234 logs
- Errors: 2
- Warnings: 15

## Visual Analysis
### UI State
Main window visible with rendering artifacts in canvas area.

### Recommendations
1. Investigate WebGL context loss - check GPU driver
2. Verify texture.png exists in public/ directory
```

## Architecture

```mermaid
flowchart TB
    subgraph DevEnv["Development Environment"]
        subgraph AIAgent["AI Agent (Codex/Claude Code)"]
            Skill["debug-tauri skill<br/>- Process verification<br/>- Screenshot capture<br/>- Log collection<br/>- Analysis & reporting"]
        end

        subgraph Tauri["Tauri Application"]
            subgraph Frontend["Frontend (TypeScript)"]
                CL["consoleLogger<br/>- Ring buffer (1000 entries)<br/>- Auto flush (1s/200 logs)<br/>- Error handling"]
                DB["debugBridge<br/>- State capture<br/>- Log retrieval<br/>- Debug commands"]
                CL -->|"Logs"| DB
            end

            subgraph Backend["Backend (Rust)"]
                Plugin["tauri-plugin-debug-tools<br/>- capture_webview_state<br/>- append_debug_logs<br/>- reset_debug_logs<br/>- write_debug_snapshot<br/>- send_debug_command"]
            end

            DB -->|"Tauri IPC"| Plugin
            CL -->|"Batch flush"| Plugin
        end

        FS["File System<br/>App log directory (logs & snapshots)<br/>e.g., ~/Library/Logs/<bundle-id>/debug-tools/frontend_console_app_12345.jsonl"]

        Plugin -->|"Write logs & snapshots"| FS
    end

    Skill -->|"1. Verify process"| Tauri
    Skill -->|"2. Invoke IPC commands"| DB
    Skill -->|"3. Read logs & snapshots"| FS
    Skill -->|"4. Capture screenshot"| FS
    FS -->|"5. Analyze & report"| Skill

    style Frontend fill:#e1f5ff
    style Backend fill:#ffe1e1
    style FS fill:#fff4e1
    style AIAgent fill:#f0e1ff
    style Skill fill:#e8d4ff
```

## Log Collection System

The plugin uses a sophisticated ring-buffer based logging system:

- **Buffer Size**: Max 1,000 log entries (automatically drops oldest)
- **Batch Flushing**: Every 1 second or 200 pending logs
- **Auto-initialization**: Starts on module load
- **Error Handling**: Catches global `error` and `unhandledrejection` events
- **Stack Traces**: Automatically captures and normalizes stack traces
- **Zero Config**: No Safari DevTools required

## Troubleshooting

| Symptom | Check command | Action |
| --- | --- | --- |
| Logs are not being written | `invoke('plugin:debug-tools\|reset_debug_logs')` and verify returned path exists | Monitor the returned absolute path directly with `tail -f` |
| `EADDRINUSE` when starting dev app | `lsof -tiTCP:5173 -sTCP:LISTEN \| xargs kill` | Kill the listed PID, then restart the host app |
| IPC permission error (`denied` / `forbidden`) | Inspect `src-tauri/capabilities/*.json` | Add `"debug-tools:default"` and restart app |
| Continuous `NetworkError` in logs | `grep -in '"level":"error"' "$LATEST"` and inspect API/auth logs | Fix host app API/auth state first (usually not plugin failure) |
| Playback state error (`play() without pause()/stop()`) | `grep -in 'play()' "$LATEST"` | Fix host app playback state transition ordering |

## Development

```bash
# Install dependencies
bun install

# Build TypeScript
npm run build

# Lint
npm run lint

# Format
npm run format
```

## Platform Support

- ✅ macOS (tested)
- ⚠️ Windows (log directory resolved by Tauri path APIs)
- ⚠️ Linux (log directory resolved by Tauri path APIs)

## License

This project is licensed under either of:

- Apache License, Version 2.0 ([LICENSE-APACHE]LICENSE-APACHE or <http://www.apache.org/licenses/LICENSE-2.0>)
- MIT license ([LICENSE-MIT]LICENSE-MIT or <http://opensource.org/licenses/MIT>)

at your option.

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## Related Projects

- [Tauri]https://tauri.app - Build smaller, faster, and more secure desktop applications
- [Codex]https://github.com/anthropics/anthropic-sdk-typescript - AI-powered code assistant