Add a backend command
This guide adds a Rust command that the control window can call. As an example, it adds library_touch, which updates a resource's updated_at.
Every command has to be declared and granted by name. Missing any step gives a permission error at runtime, not a compile error.
1. Write the command
Put it in the module it belongs to, here src-tauri/src/library.rs:
#[tauri::command]
pub fn library_touch(state: State<AppState>, id: String) -> AppResult<()> {
let ws = state.workspace()?;
ws.with(|c| {
let changed = c.execute(
"UPDATE resources SET updated_at = ?2 WHERE id = ?1",
params![id, now_ms()],
)?;
if changed == 0 {
return Err(AppError::NotFound(id.clone()));
}
Ok(())
})
}library.rs already imports params, State, AppState, now_ms, AppError and AppResult. library_restore in the same file is a good model.
Follow the existing conventions:
- Return
AppResult<T>. Errors reach the interface as a plain string. - Use
AppError::invalid("…")for messages the operator will read, and write them as complete sentences. - Make the command
asyncif it creates windows, touches the coordinator, or does slow work. Move blocking file work ontotauri::async_runtime::spawn_blocking. - Never hold the coordinator lock and the database lock at the same time.
2. Register it
Add it to the generate_handler! list in src-tauri/src/lib.rs:
library::library_touch,3. Declare it
Add the name to COMMANDS in src-tauri/build.rs. This generates permissions/autogenerated/library_touch.toml, with allow-library-touch and deny-library-touch. Commit the generated file.
4. Grant it
Add the permission to src-tauri/capabilities/default.json (the control window):
"allow-library-touch",Only add it to capabilities/output.json if the audience or confidence window really needs it. Output windows are meant to render and acknowledge only. See Security and permissions.
5. Add a typed wrapper
In src/lib/api.ts:
libraryTouch: (id: string) => invoke<void>("library_touch", { id }),Arguments are camelCase in TypeScript and snake_case in Rust. Tauri converts between them.
6. Mock it for the browser
So npm run dev keeps working, add a case to the switch in handle() in src/lib/mock-backend.ts, next to library_restore:
case "library_touch":
if (!db.resources[a.id]) throw `Not found: ${a.id}`;
db.resources[a.id].updatedAt = now();
persist();
return null;If the command can't work in a browser, throw "This action needs the desktop app" as the package commands do.
7. Check it
npm run tauri devCall it from the interface, or from the devtools console of the control window. If you see … not allowed errors, recheck steps 3 and 4.
Then add the command to the Backend commands reference.