{"record":{"id":"e4d7b71ffc06481b","repo":"farion1231/cc-switch","slug":"error-while-running-tauri-application","errorCode":null,"errorMessage":"error while running tauri application","messagePattern":"error while running tauri application","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"critical","filePath":"src-tauri/src/lib.rs","lineNumber":1719,"sourceCode":"            // Workspace files (OpenClaw)\n            commands::read_workspace_file,\n            commands::write_workspace_file,\n            // Daily memory files (OpenClaw workspace)\n            commands::list_daily_memory_files,\n            commands::read_daily_memory_file,\n            commands::write_daily_memory_file,\n            commands::delete_daily_memory_file,\n            commands::search_daily_memory_files,\n            commands::open_workspace_directory,\n            // lightweight mode (for testing or low-resource environments)\n            commands::enter_lightweight_mode,\n            commands::exit_lightweight_mode,\n            commands::is_lightweight_mode,\n        ]);\n\n    let app = builder\n        .build(tauri::generate_context!())\n        .expect(\"error while running tauri application\");\n\n    app.run(|app_handle, event| {\n        // 处理退出请求（所有平台）\n        if let RunEvent::ExitRequested { api, code, .. } = &event {\n            match classify_exit_request(*code) {\n                // code 为 None 表示运行时自动触发（如隐藏窗口的 WebView 被回收导致无存活窗口），\n                // 此时应仅阻止退出、保持托盘后台运行。\n                ExitRequestAction::StayInTray => {\n                    log::info!(\"运行时触发退出请求（无存活窗口），阻止退出以保持托盘后台运行\");\n                    api.prevent_exit();\n                    return;\n                }\n                // code 为 RESTART_EXIT_CODE：app.restart() / 自更新 relaunch 发起的重启。\n                // 这条路径上 prevent_exit() 会被 Tauri 忽略，事件循环必定退出，随后由\n                // Tauri 在 RunEvent::Exit 后用新二进制 re-exec（macOS 会按更新后的\n                // Info.plist 解析可执行名）。\n                //\n                // 绝不能复用下面的异步清理任务：该任务在 tokio 线程调 save_window_state，","sourceCodeStart":1701,"sourceCodeEnd":1737,"githubUrl":"https://github.com/farion1231/cc-switch/blob/3217f72596f2d1c0f879f0a05f83803825d9809f/src-tauri/src/lib.rs#L1701-L1737","documentation":"This is a Rust panic from `.expect(\"error while running tauri application\")` after `tauri::Builder::build(tauri::generate_context!())` (src-tauri/src/lib.rs:1709). `build()` returns `Result<App, tauri::Error>`, and it errs when Tauri cannot assemble the app at startup: a plugin's `initialize()` failed (this app chains single_instance, deep_link, process, dialog, opener, store, window_state, log, updater), the main window/WebView from tauri.conf.json could not be created, or the `setup` hook aborted. Tauri surfaces it this way because application assembly is treated as unrecoverable: without plugins and a webview the app cannot function. The real cause is appended to the panic message as the `Debug` of `tauri::Error` (e.g. `PluginInitialization(\"...\")` or a WebView creation error) — always read the text after the colon.","triggerScenarios":"Calling `builder.build(tauri::generate_context!())` when: (1) the system cannot create a WebView — Linux without `libwebkit2gtk-4.1-0`/GTK3, Windows without the WebView2 runtime (and the default downloadBootstrapper cannot reach the network), or a headless session with no `DISPLAY`/`WAYLAND_DISPLAY` (SSH, CI, Docker); (2) a plugin fails init — tauri-plugin-store or tauri-plugin-window-state hitting an unwritable/corrupt app-data dir (`~/.local/share/<identifier>`), or an older single-instance plugin version erroring because another instance holds the lock; (3) the `setup` closure (which runs inside `build()` in Tauri v2) panics or a plugin like deep-link/updater fails its initialization with the bundled config.","commonSituations":"Running `cargo tauri dev` over SSH or in CI without a display server; deploying a raw binary or AppImage to a minimal Linux distro that lacks webkit2gtk 4.1 (Tauri v2 moved from 4.0 to 4.1, so images built for v1 break); Windows Server or stripped Windows without WebView2, or air-gapped machines where the bootstrapper download fails; stale single-instance socket / corrupted window-state or store JSON after a crash or force-kill; Tauri v1→v2 migrations where plugin init order or capabilities changed.","solutions":["Read the full panic output first: the text after 'error while running tauri application:' is the Debug of tauri::Error and names the failing subsystem (PluginInitialization(\"store\"), webview creation, etc.) — fix that subsystem, not the expect() line.","If in a headless/SSH/CI session, give the app a display: `xvfb-run -a cargo tauri dev` or set DISPLAY/WAYLAND_DISPLAY; for tests, prefer this app's lightweight mode instead of launching the full windowed build.","On Linux, install the WebView runtime deps the binary links against: `sudo apt install libwebkit2gtk-4.1-0 libgtk-3-0` and verify with `ldd target/release/<binary> | grep -i webkit`; on distros with only webkit2gtk-4.0, upgrade or build against 4.0.","On Windows, install the WebView2 Evergreen Runtime, or set `bundle.webviewInstallMode` to `offlineInstaller`/`embedBootstrapper` in tauri.conf.json so air-gapped machines get a runtime.","If state corruption or a stale single-instance lock is the cause (app-data dir `~/.local/share/<identifier>`), delete the window-state/store files or call the existing `destroy_single_instance_lock`, then relaunch.","Replace `.expect` with real Result handling that logs the error before exiting, so production failures carry a clean diagnostic instead of a bare panic (see exampleFix)."],"exampleFix":"// before (src-tauri/src/lib.rs:1707)\nlet app = builder\n    .build(tauri::generate_context!())\n    .expect(\"error while running tauri application\");\n\n// after\nlet app = match builder.build(tauri::generate_context!()) {\n    Ok(app) => app,\n    Err(e) => {\n        eprintln!(\"failed to start application: {e:#}\");\n        log::error!(\"tauri build failed: {e:#}\");\n        std::process::exit(1);\n    }\n};","handlingStrategy":"try-catch","validationCode":"// Pre-flight checks before builder.build() (Linux/Unix)\nfn environment_ready() -> bool {\n    #[cfg(target_os = \"linux\")]\n    {\n        if std::env::var_os(\"DISPLAY\").is_none() && std::env::var_os(\"WAYLAND_DISPLAY\").is_none() {\n            eprintln!(\"no display server found; set DISPLAY/WAYLAND_DISPLAY or run under xvfb\");\n            return false;\n        }\n    }\n    true\n}\n\nif !environment_ready() {\n    std::process::exit(1);\n}\nlet app = builder.build(tauri::generate_context!());","typeGuard":"// Narrow the tauri::Error variant to decide recovery vs exit\nfn is_plugin_init_error(e: &tauri::Error) -> bool {\n    matches!(e, tauri::Error::PluginInitialization(_))\n}","tryCatchPattern":"// Rust: never .expect() on build(); match the Result and log {:#} (anyhow-style chain)\nlet app = match builder.build(tauri::generate_context!()) {\n    Ok(app) => app,\n    Err(err) if is_plugin_init_error(&err) => {\n        log::error!(\"plugin failed to initialize: {err:#}\");\n        std::process::exit(1);\n    }\n    Err(err) => {\n        log::error!(\"tauri app build failed: {err:#}\");\n        eprintln!(\"tauri app build failed: {err:#}\");\n        std::process::exit(1);\n    }\n};","preventionTips":["Treat app startup as fallible: handle the Result from build() with logging instead of .expect() so field failures are diagnosable.","In CI or tests that touch the full app, run under `xvfb-run` or skip window creation; this repo already ships lightweight-mode commands for low-resource environments — use them.","Ship runtime deps with the bundle: declare webkit2gtk-4.1 deb/rpm dependencies and set Windows `webviewInstallMode` explicitly rather than relying on the online bootstrapper.","Document the required WebView (WebKit2GTK 4.1 / WebView2) in install instructions and add a smoke test that launches the binary on a clean image.","Avoid force-killing the app; use its exit path so single-instance locks and window-state/store files are released cleanly (see destroy_single_instance_lock in this codebase)."],"tags":["tauri","rust","panic","startup","webview","desktop-app","plugin-init"],"backgroundTag":"tauri-app-failed-to-start","analyzedSha":"3217f72596f2d1c0f879f0a05f83803825d9809f","analyzedAt":"2026-08-20T14:29:00.113Z","contentChangedAt":"2026-08-20T14:29:00.113Z","schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}