{"record":{"id":"7753c8114d47ea20","repo":"clash-verge-rev/clash-verge-rev","slug":"failed-to-create-task","errorCode":null,"errorMessage":"failed to create {} task: {}","messagePattern":"failed to create (.+?) task: (.+?)","errorType":"exception","errorClass":"anyhow::Error","httpStatus":null,"severity":"error","filePath":"src-tauri/src/utils/schtasks.rs","lineNumber":285,"sourceCode":"        cmd.args([\"/Query\", \"/TN\", mode.name()]);\n        cmd\n    })?;\n\n    Ok(output.status.success())\n}\n\npub fn create_task(mode: TaskMode) -> Result<()> {\n    let task_xml_path = write_task_xml(mode)?;\n    let output = schtasks_output({\n        let mut cmd = Command::new(\"schtasks\");\n        cmd.args([\"/Create\", \"/TN\", mode.name(), \"/XML\"]);\n        cmd.arg(&task_xml_path);\n        cmd.arg(\"/F\");\n        cmd\n    })?;\n\n    if !output.status.success() {\n        return Err(anyhow!(\n            \"failed to create {} task: {}\",\n            mode.label(),\n            output_message(&output)\n        ));\n    }\n\n    logging!(info, Type::Setup, \"Created {} auto-launch task\", mode.label());\n    Ok(())\n}\n\npub fn remove_task(mode: TaskMode) -> Result<()> {\n    let output = schtasks_output({\n        let mut cmd = Command::new(\"schtasks\");\n        cmd.args([\"/Delete\", \"/TN\", mode.name(), \"/F\"]);\n        cmd\n    })?;\n\n    if output.status.success() {","sourceCodeStart":267,"sourceCodeEnd":303,"githubUrl":"https://github.com/clash-verge-rev/clash-verge-rev/blob/5cad0f2799e74b1105e133bcfc2a45f5c1370ef1/src-tauri/src/utils/schtasks.rs#L267-L303","documentation":"create_task() writes the XML and invokes `schtasks /Create /TN <name> /XML <path> /F`. /F forces overwrite of an existing task, so a non-zero exit means schtasks rejected the task definition or refused the operation. The error carries output_message() (decoded stdout/stderr) so the OS reason is visible.","triggerScenarios":"Creating the Admin task while running unelevated (RunLevel HighestAvailable denied); USERNAME/USERDOMAIN producing a UserId the scheduler will not accept (e.g., MicrosoftAccount\\foo); XML schema violation across Windows versions; task name conflicts with a task owned by another principal; Task Scheduler service stopped or corrupt.","commonSituations":"User toggled 'auto-launch as admin' without UAC elevation; account renamed after the task was first created; domain account where the NetBIOS domain differs from USERDOMAIN; localized Windows where the principal format differs.","solutions":["If is_admin was true, re-launch the app with 'Run as administrator' before toggling auto-launch.","Open Task Scheduler GUI, look for residual 'Clash Verge' / 'Clash Verge (Admin)' tasks, delete them, then retry.","Verify get_task_user_id() resolves to DOMAIN\\\\user that matches the account that will log in.","Run `schtasks /Create /TN \"Clash Verge\" /XML <path> /F` manually in cmd to capture the exact reason from schtasks."],"exampleFix":"// before - unelevated process tries admin task\ncreate_task(TaskMode::Admin)?;\n// after - refuse admin task creation without elevation\nif is_admin && !is_elevated() {\n    return Err(anyhow!(\"re-launch as administrator to create the admin auto-launch task\"));\n}\ncreate_task(TaskMode::Admin)?;","handlingStrategy":"validation","validationCode":"#[cfg(windows)]\nfn is_elevated() -> bool {\n    use windows::Win32::Security::{GetTokenInformation, TokenElevation, TOKEN_ELEVATION, TOKEN_QUERY};\n    use windows::Win32::System::Threading::OpenProcessToken;\n    use windows::Win32::Foundation::{CloseHandle, HANDLE};\n    // open current process token, query TokenElevation, return elevation.Level != 0\n    true // (body abbreviated)\n}\nif is_admin && !is_elevated() { return Err(anyhow!(\"elevation required\")); }","typeGuard":null,"tryCatchPattern":"if let Err(e) = create_task(target) {\n    let msg = e.to_string().to_lowercase();\n    if msg.contains(\"access\") || msg.contains(\"admin\") {\n        // surface an elevation prompt to the user\n    }\n    return Err(e);\n}","preventionTips":["Gate Admin task creation behind an is_elevated() check.","Surface schtasks' output_message verbatim in the UI so the user sees the OS reason.","Resolve UserId from USERNAME/USERDOMAIN at install time and persist it, so a later account rename does not break the task."],"tags":["windows","schtasks","permissions","uac"],"analyzedSha":"5cad0f2799e74b1105e133bcfc2a45f5c1370ef1","analyzedAt":"2026-08-12T03:25:57.699Z","schemaVersion":2},"datasetVersion":"2026-08-12T08:17:17.861Z"}