Migrate all IPC call sites to typed tauri-specta commands.*
🏗️ Build and Test JellyTau / Run Tests (pull_request) Successful in 4m39s
Traceability Validation / Check Requirement Traces (pull_request) Failing after 36s
🏗️ Build and Test JellyTau / Build Android APK (pull_request) Failing after 1m57s

Replace the remaining ~155 untyped invoke() calls across stores, services,
components, and routes with the generated commands.* wrappers from
$lib/api/bindings, so every IPC call is compile-time-checked against the
command signatures.

- Register repository_get_subtitle_url and repository_get_video_download_url
  in specta_builder() and the invoke_handler; regenerate bindings.ts.
- Source duplicated wire types (AutoplaySettings, CacheConfig, Session,
  ConnectivityStatus, audio/video settings, etc.) from bindings.
- Fix two bugs surfaced by the typed wrappers:
  - VideoDownloadButton passed an un-awaited Promise as the stream URL.
  - setAutoplaySettings omitted the required userId argument.
- Update unit tests asserting the old invoke(name, args) shape.
- Remove the five param-naming guard tests; the compiler and codegen now
  enforce what they checked.

svelte-check: 0 errors. vitest: green. cargo test --lib: green.
This commit is contained in:
2026-06-21 08:47:04 +02:00
parent 14e9d7e03a
commit d01c2aab9f
47 changed files with 456 additions and 2119 deletions
+2 -2
View File
@@ -8,7 +8,7 @@
* TRACES: UR-009 | DR-011
*/
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
let cachedDeviceId: string | null = null;
@@ -30,7 +30,7 @@ export async function getDeviceId(): Promise<string> {
try {
// Rust backend handles generation and storage atomically
const deviceId = await invoke<string>("device_get_id");
const deviceId = await commands.deviceGetId();
cachedDeviceId = deviceId;
return deviceId;
} catch (e) {
+3 -7
View File
@@ -1,7 +1,7 @@
// Favorites service - Handles toggling favorite status with optimistic updates
// TRACES: UR-017 | DR-021
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import { auth } from "$lib/stores/auth";
/**
@@ -29,11 +29,7 @@ export async function toggleFavorite(
const newIsFavorite = !currentIsFavorite;
// 1. Update local database first (optimistic update)
await invoke("storage_toggle_favorite", {
userId,
itemId,
isFavorite: newIsFavorite,
});
await commands.storageToggleFavorite(userId, itemId, newIsFavorite);
// 2. Sync to Jellyfin server
try {
@@ -45,7 +41,7 @@ export async function toggleFavorite(
}
// 3. Mark as synced
await invoke("storage_mark_synced", { userId, itemId });
await commands.storageMarkSynced(userId, itemId);
} catch (error) {
console.error("Failed to sync favorite to server:", error);
// Favorite is stored locally and will be synced later
+7 -16
View File
@@ -1,8 +1,8 @@
// Image cache service - Handles lazy caching of thumbnails with LRU eviction
// TRACES: UR-007 | DR-016
import { invoke } from "@tauri-apps/api/core";
import { convertFileSrc } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
/**
* Statistics about the thumbnail cache
@@ -38,11 +38,7 @@ export async function getCachedImageUrl(
// Try to get cached version
try {
const cachedPath = await invoke<string | null>("thumbnail_get_cached", {
itemId,
imageType,
tag,
});
const cachedPath = await commands.thumbnailGetCached(itemId, imageType, tag);
if (cachedPath) {
// Convert file path to asset URL for Tauri
@@ -62,12 +58,7 @@ export async function getCachedImageUrl(
const serverImageUrl = `${serverUrl}/Items/${itemId}/Images/${imageType}?${params.toString()}`;
// Trigger background caching (fire and forget)
invoke("thumbnail_save", {
itemId,
imageType,
tag,
url: serverImageUrl,
}).catch((e) => {
commands.thumbnailSave(itemId, imageType, tag, serverImageUrl).catch((e) => {
// Silently fail - caching is best-effort
console.debug("Background thumbnail cache failed:", e);
});
@@ -80,7 +71,7 @@ export async function getCachedImageUrl(
* Get thumbnail cache statistics
*/
export async function getCacheStats(): Promise<ImageCacheStats> {
return invoke("thumbnail_get_stats");
return commands.thumbnailGetStats();
}
/**
@@ -89,14 +80,14 @@ export async function getCacheStats(): Promise<ImageCacheStats> {
* @param limitBytes - The maximum cache size in bytes (0 = unlimited)
*/
export async function setCacheLimit(limitBytes: number): Promise<void> {
return invoke("thumbnail_set_limit", { limitBytes });
await commands.thumbnailSetLimit(limitBytes);
}
/**
* Clear all cached thumbnails
*/
export async function clearCache(): Promise<void> {
return invoke("thumbnail_clear_cache");
await commands.thumbnailClearCache();
}
/**
@@ -105,7 +96,7 @@ export async function clearCache(): Promise<void> {
* @param itemId - The Jellyfin item ID
*/
export async function deleteItemCache(itemId: string): Promise<void> {
return invoke("thumbnail_delete_item", { itemId });
await commands.thumbnailDeleteItem(itemId);
}
/**
+5 -19
View File
@@ -9,7 +9,7 @@
//
// TRACES: UR-005, UR-019, UR-025 | DR-028, DR-047
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import { auth } from "$lib/stores/auth";
/**
@@ -42,13 +42,7 @@ export async function reportPlaybackStart(
// Update local DB with context (always works, even offline)
if (userId) {
try {
await invoke("storage_update_playback_context", {
userId,
itemId,
positionTicks,
contextType,
contextId,
});
await commands.storageUpdatePlaybackContext(userId, itemId, positionTicks, contextType, contextId);
} catch (e) {
console.error("[PlaybackReporting] Failed to update playback context:", e);
}
@@ -79,11 +73,7 @@ export async function reportPlaybackProgress(
// Update local DB only (progress updates are frequent, don't report to server)
if (userId) {
try {
await invoke("storage_update_playback_progress", {
userId,
itemId,
positionTicks,
});
await commands.storageUpdatePlaybackProgress(userId, itemId, positionTicks);
} catch (e) {
console.error("[PlaybackReporting] Failed to update local progress:", e);
}
@@ -107,11 +97,7 @@ export async function reportPlaybackStopped(itemId: string, positionSeconds: num
// Update local DB first (always works, even offline)
if (userId) {
try {
await invoke("storage_update_playback_progress", {
userId,
itemId,
positionTicks,
});
await commands.storageUpdatePlaybackProgress(userId, itemId, positionTicks);
} catch (e) {
console.error("[PlaybackReporting] Failed to update local progress:", e);
}
@@ -143,7 +129,7 @@ export async function markAsPlayed(itemId: string): Promise<void> {
// Update local DB first
if (userId) {
try {
await invoke("storage_mark_played", { userId, itemId });
await commands.storageMarkPlayed(userId, itemId);
} catch (e) {
console.error("[PlaybackReporting] Failed to mark as played in local DB:", e);
}
+4 -9
View File
@@ -9,7 +9,7 @@
*/
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import { player, playbackPosition } from "$lib/stores/player";
import { queue, currentQueueItem } from "$lib/stores/queue";
import { playbackMode } from "$lib/stores/playbackMode";
@@ -230,12 +230,7 @@ async function handleStateChanged(state: string, _mediaId: string | null): Promi
*/
async function updateQueueStatus(): Promise<void> {
try {
const queueStatus = await invoke<{
hasNext: boolean;
hasPrevious: boolean;
shuffle: boolean;
repeat: string;
}>("player_get_queue");
const queueStatus = await commands.playerGetQueue();
// Import appState stores dynamically to avoid circular imports
const { hasNext, hasPrevious, shuffle, repeat } = await import("$lib/stores/appState");
@@ -266,7 +261,7 @@ function handleMediaLoaded(duration: number): void {
async function handlePlaybackEnded(): Promise<void> {
// Call backend to handle autoplay decision (queue advance, sleep timer, episode popup, etc.)
try {
await invoke("player_on_playback_ended");
await commands.playerOnPlaybackEnded(null, null);
} catch (e) {
console.error("[playerEvents] Failed to handle playback ended:", e);
// Fallback: set idle state on error
@@ -284,7 +279,7 @@ async function handleError(message: string, recoverable: boolean): Promise<void>
// Stop backend player to prevent orphaned playback
// This also reports playback stopped to Jellyfin server
try {
await invoke("player_stop");
await commands.playerStop();
console.log("Backend player stopped after error");
} catch (e) {
console.error("Failed to stop player after error:", e);
+19 -5
View File
@@ -6,6 +6,20 @@
import { describe, it, expect, beforeEach, vi } from "vitest";
import { preloadUpcomingTracks, updateCacheConfig, getCacheConfig } from "./preload";
import type { CacheConfig } from "$lib/api/bindings";
// updateCacheConfig now takes a full CacheConfig (matches the backend command)
function makeConfig(overrides: Partial<CacheConfig> = {}): CacheConfig {
return {
queuePrecacheEnabled: true,
queuePrecacheCount: 5,
albumAffinityEnabled: false,
albumAffinityThreshold: 0.75,
storageLimit: 2 * 1024 * 1024 * 1024,
wifiOnly: false,
...overrides,
};
}
vi.mock("@tauri-apps/api/core", () => ({
invoke: vi.fn(async (command: string, args?: any) => {
@@ -135,10 +149,10 @@ describe("preload service", () => {
describe("updateCacheConfig", () => {
it("should update cache config", async () => {
const config = {
const config = makeConfig({
queuePrecacheEnabled: false,
queuePrecacheCount: 10,
};
});
await expect(updateCacheConfig(config)).resolves.toBeUndefined();
});
@@ -147,7 +161,7 @@ describe("preload service", () => {
const { invoke } = await import("@tauri-apps/api/core");
const invokeSpy = vi.mocked(invoke);
const config = { queuePrecacheEnabled: true };
const config = makeConfig({ queuePrecacheEnabled: true });
await updateCacheConfig(config);
const call = invokeSpy.mock.calls.find(
@@ -157,8 +171,8 @@ describe("preload service", () => {
expect(call![1]).toHaveProperty("config", config);
});
it("should support partial config updates", async () => {
const config = { wifiOnly: true };
it("should support overriding individual config options", async () => {
const config = makeConfig({ wifiOnly: true });
await expect(updateCacheConfig(config)).resolves.toBeUndefined();
});
+8 -29
View File
@@ -5,15 +5,10 @@
* TRACES: UR-004, UR-011 | DR-006, DR-015
*/
import { invoke } from '@tauri-apps/api/core';
import { commands } from '$lib/api/bindings';
import type { CacheConfig } from '$lib/api/bindings';
import { auth } from '$lib/stores/auth';
interface PreloadResult {
queuedCount: number;
alreadyDownloaded: number;
skipped: number;
}
interface PreloadOptions {
/** Enable debug logging */
debug?: boolean;
@@ -39,10 +34,8 @@ export async function preloadUpcomingTracks(options: PreloadOptions = {}): Promi
if (debug) console.log('[Preload] Triggering preload for user:', userId);
const result = await invoke<PreloadResult>('player_preload_upcoming', {
userId,
downloadBasePath: '/downloads' // This parameter is currently unused in the backend
});
// downloadBasePath is currently unused in the backend
const result = await commands.playerPreloadUpcoming(userId, '/downloads');
if (debug) {
console.log('[Preload] Result:', {
@@ -66,27 +59,13 @@ export async function preloadUpcomingTracks(options: PreloadOptions = {}): Promi
/**
* Update smart cache configuration
*/
export async function updateCacheConfig(config: {
queuePrecacheEnabled?: boolean;
queuePrecacheCount?: number;
albumAffinityEnabled?: boolean;
albumAffinityThreshold?: number;
storageLimit?: number;
wifiOnly?: boolean;
}): Promise<void> {
await invoke('player_set_cache_config', { config });
export async function updateCacheConfig(config: CacheConfig): Promise<void> {
await commands.playerSetCacheConfig(config);
}
/**
* Get current cache configuration
*/
export async function getCacheConfig(): Promise<{
queuePrecacheEnabled: boolean;
queuePrecacheCount: number;
albumAffinityEnabled: boolean;
albumAffinityThreshold: number;
storageLimit: number;
wifiOnly: boolean;
}> {
return await invoke('player_get_cache_config');
export async function getCacheConfig(): Promise<CacheConfig> {
return await commands.playerGetCacheConfig();
}
+11 -25
View File
@@ -6,7 +6,7 @@
//
// TRACES: UR-002, UR-017, UR-025 | DR-014
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import { auth } from "$lib/stores/auth";
// Types matching Rust structs
@@ -73,12 +73,12 @@ class SyncService {
throw new Error("Not authenticated");
}
const id = await invoke<number>("sync_queue_mutation", {
const id = await commands.syncQueueMutation(
userId,
operation,
itemId,
payload: payload ? JSON.stringify(payload) : null,
});
payload ? JSON.stringify(payload) : null
);
console.log(`[SyncService] Queued ${operation} for item ${itemId}, id: ${id}`);
return id;
@@ -90,11 +90,7 @@ class SyncService {
*/
async queueFavorite(itemId: string, isFavorite: boolean): Promise<number> {
// Update local state first
await invoke("storage_toggle_favorite", {
userId: auth.getUserId(),
itemId,
isFavorite,
});
await commands.storageToggleFavorite(auth.getUserId() ?? "", itemId, isFavorite);
return this.queueMutation(
isFavorite ? "mark_favorite" : "unmark_favorite",
@@ -111,11 +107,7 @@ class SyncService {
positionTicks: number
): Promise<number> {
// Update local state first
await invoke("storage_update_playback_progress", {
userId: auth.getUserId(),
itemId,
positionTicks,
});
await commands.storageUpdatePlaybackProgress(auth.getUserId() ?? "", itemId, positionTicks);
return this.queueMutation("update_progress", itemId, { positionTicks });
}
@@ -126,10 +118,7 @@ class SyncService {
*/
async queueMarkPlayed(itemId: string): Promise<number> {
// Update local state first
await invoke("storage_mark_played", {
userId: auth.getUserId(),
itemId,
});
await commands.storageMarkPlayed(auth.getUserId() ?? "", itemId);
return this.queueMutation("mark_played", itemId);
}
@@ -143,7 +132,7 @@ class SyncService {
return 0;
}
return invoke<number>("sync_get_pending_count", { userId });
return commands.syncGetPendingCount(userId);
}
/**
@@ -155,17 +144,14 @@ class SyncService {
return [];
}
return invoke<SyncQueueItem[]>("sync_get_pending", {
userId,
limit,
});
return commands.syncGetPending(userId, limit ?? null);
}
/**
* Clean up completed operations older than specified days
*/
async cleanup(daysOld: number = 7): Promise<number> {
const deleted = await invoke<number>("sync_cleanup_completed", { daysOld });
const deleted = await commands.syncCleanupCompleted(daysOld);
console.log(`[SyncService] Cleaned up ${deleted} old completed operations`);
return deleted;
}
@@ -204,7 +190,7 @@ class SyncService {
async clearUser(): Promise<void> {
const userId = auth.getUserId();
if (userId) {
await invoke("sync_clear_user", { userId });
await commands.syncClearUser(userId);
console.log("[SyncService] Cleared sync queue for user");
}
}