Compare commits

...

2 Commits

Author SHA1 Message Date
01c6423154 Merge pull request 'Migrate all IPC call sites to typed tauri-specta commands.*' (#1) from ipc-commands-migration into master
Some checks failed
🏗️ Build and Test JellyTau / Run Tests (push) Has been cancelled
🏗️ Build and Test JellyTau / Build Android APK (push) Has been cancelled
Traceability Validation / Check Requirement Traces (push) Has been cancelled
Reviewed-on: #1
2026-06-21 06:48:08 +00:00
d01c2aab9f Migrate all IPC call sites to typed tauri-specta commands.*
Some checks failed
🏗️ 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.
2026-06-21 08:47:04 +02:00
47 changed files with 456 additions and 2119 deletions

View File

@ -101,6 +101,7 @@ use commands::{
repository_report_playback_start, repository_report_playback_progress, repository_report_playback_stopped,
repository_get_image_url, repository_mark_favorite, repository_unmark_favorite,
repository_get_person, repository_get_items_by_person, repository_get_similar_items,
repository_get_subtitle_url, repository_get_video_download_url,
// Playlist commands
playlist_create, playlist_delete, playlist_rename, playlist_get_items,
playlist_add_items, playlist_remove_items, playlist_move_item,
@ -565,6 +566,8 @@ fn specta_builder() -> Builder<tauri::Wry> {
repository_get_person,
repository_get_items_by_person,
repository_get_similar_items,
repository_get_subtitle_url,
repository_get_video_download_url,
// Playlist commands
playlist_create,
playlist_delete,

View File

@ -10,6 +10,7 @@ import {
playNextEpisode,
type AutoplaySettings,
} from "./autoplay";
import type { PlayItemRequest } from "./bindings";
vi.mock("@tauri-apps/api/core", () => ({
invoke: vi.fn(async (command: string, args?: any) => {
@ -33,6 +34,23 @@ vi.mock("@tauri-apps/api/core", () => ({
}),
}));
// setAutoplaySettings sources the user id from the auth store
vi.mock("$lib/stores/auth", () => ({
auth: { getUserId: () => "user-1" },
}));
// Minimal valid PlayItemRequest for playNextEpisode tests
function makeItem(overrides: Partial<PlayItemRequest> = {}): PlayItemRequest {
return {
id: "item-123",
title: "Episode 1",
streamUrl: "http://example/stream",
videoCodec: "h264",
needsTranscoding: false,
...overrides,
};
}
describe("autoplay API", () => {
beforeEach(() => {
vi.clearAllMocks();
@ -98,7 +116,7 @@ describe("autoplay API", () => {
(c) => c[0] === "player_set_autoplay_settings"
);
expect(call).toBeDefined();
expect(call![1]).toEqual({ settings });
expect(call![1]).toEqual({ userId: "user-1", settings });
});
it("should support different countdown values", async () => {
@ -130,11 +148,7 @@ describe("autoplay API", () => {
describe("playNextEpisode", () => {
it("should play next episode with item", async () => {
const mockItem = {
id: "item-123",
name: "Episode 1",
seriesId: "series-456",
};
const mockItem = makeItem();
await playNextEpisode(mockItem);
@ -150,9 +164,9 @@ describe("autoplay API", () => {
it("should handle different item types", async () => {
const items = [
{ id: "1", name: "Episode 1" },
{ id: "2", name: "Episode 2", seasonNumber: 1 },
{ id: "3", name: "Episode 3", episodeNumber: 5 },
makeItem({ id: "1", title: "Episode 1" }),
makeItem({ id: "2", title: "Episode 2" }),
makeItem({ id: "3", title: "Episode 3" }),
];
for (const item of items) {

View File

@ -4,28 +4,26 @@
* Functions to control autoplay in the backend.
*/
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import type { PlayItemRequest, AutoplaySettings } from "$lib/api/bindings";
import { auth } from "$lib/stores/auth";
export interface AutoplaySettings {
enabled: boolean;
countdownSeconds: number;
maxEpisodes: number;
}
export type { AutoplaySettings };
export async function getAutoplaySettings(): Promise<AutoplaySettings> {
return invoke("player_get_autoplay_settings");
return commands.playerGetAutoplaySettings();
}
export async function setAutoplaySettings(
settings: AutoplaySettings
): Promise<AutoplaySettings> {
return invoke("player_set_autoplay_settings", { settings });
return commands.playerSetAutoplaySettings(auth.getUserId() ?? "", settings);
}
export async function cancelAutoplayCountdown(): Promise<void> {
return invoke("player_cancel_autoplay_countdown");
await commands.playerCancelAutoplayCountdown();
}
export async function playNextEpisode(item: any): Promise<void> {
return invoke("player_play_next_episode", { item });
export async function playNextEpisode(item: PlayItemRequest): Promise<void> {
await commands.playerPlayNextEpisode(item);
}

View File

@ -1121,6 +1121,18 @@ async repositoryGetItemsByPerson(handle: string, personId: string, options: GetI
async repositoryGetSimilarItems(handle: string, itemId: string, limit: number | null) : Promise<SearchResult> {
return await TAURI_INVOKE("repository_get_similar_items", { handle, itemId, limit });
},
/**
* Get subtitle URL for a media item
*/
async repositoryGetSubtitleUrl(handle: string, itemId: string, mediaSourceId: string, streamIndex: number, format: string) : Promise<string> {
return await TAURI_INVOKE("repository_get_subtitle_url", { handle, itemId, mediaSourceId, streamIndex, format });
},
/**
* Get video download URL with quality preset
*/
async repositoryGetVideoDownloadUrl(handle: string, itemId: string, quality: string, mediaSourceId: string | null) : Promise<string> {
return await TAURI_INVOKE("repository_get_video_download_url", { handle, itemId, quality, mediaSourceId });
},
/**
* Create a new playlist
*/

View File

@ -2,9 +2,8 @@
// All API calls go through Tauri commands in src-tauri/src/commands/repository.rs
// NO direct HTTP calls - everything routes through Rust backend
import { invoke } from "@tauri-apps/api/core";
import { commands } from "./bindings";
import type { QualityPreset } from "./quality-presets";
import { QUALITY_PRESETS } from "./quality-presets";
import type {
Library,
MediaItem,
@ -39,12 +38,7 @@ export class RepositoryClient {
serverId: string
): Promise<string> {
console.log("[RepositoryClient] Creating Rust repository...");
this.handle = await invoke<string>("repository_create", {
serverUrl,
userId,
accessToken,
serverId,
});
this.handle = await commands.repositoryCreate(serverUrl, userId, accessToken, serverId);
// Store for URL construction
this._serverUrl = serverUrl;
@ -60,7 +54,7 @@ export class RepositoryClient {
*/
async destroy(): Promise<void> {
if (this.handle) {
await invoke("repository_destroy", { handle: this.handle });
await commands.repositoryDestroy(this.handle);
this.handle = null;
this._serverUrl = null;
this._accessToken = null;
@ -84,119 +78,67 @@ export class RepositoryClient {
// ===== Library Methods (all via Rust) =====
async getLibraries(): Promise<Library[]> {
return invoke<Library[]>("repository_get_libraries", {
handle: this.ensureHandle(),
});
return commands.repositoryGetLibraries(this.ensureHandle());
}
async getItems(parentId: string, options?: GetItemsOptions): Promise<SearchResult> {
return invoke<SearchResult>("repository_get_items", {
handle: this.ensureHandle(),
parentId,
options: options ?? null,
});
return commands.repositoryGetItems(this.ensureHandle(), parentId, options ?? null);
}
async getItem(itemId: string): Promise<MediaItem> {
return invoke<MediaItem>("repository_get_item", {
handle: this.ensureHandle(),
itemId,
});
return commands.repositoryGetItem(this.ensureHandle(), itemId);
}
async getLatestItems(parentId: string, limit?: number): Promise<MediaItem[]> {
return invoke<MediaItem[]>("repository_get_latest_items", {
handle: this.ensureHandle(),
parentId,
limit: limit ?? null,
});
return commands.repositoryGetLatestItems(this.ensureHandle(), parentId, limit ?? null);
}
async getResumeItems(parentId?: string, limit?: number): Promise<MediaItem[]> {
return invoke<MediaItem[]>("repository_get_resume_items", {
handle: this.ensureHandle(),
parentId: parentId ?? null,
limit: limit ?? null,
});
return commands.repositoryGetResumeItems(this.ensureHandle(), parentId ?? null, limit ?? null);
}
async getNextUpEpisodes(seriesId?: string, limit?: number): Promise<MediaItem[]> {
return invoke<MediaItem[]>("repository_get_next_up_episodes", {
handle: this.ensureHandle(),
seriesId: seriesId ?? null,
limit: limit ?? null,
});
return commands.repositoryGetNextUpEpisodes(this.ensureHandle(), seriesId ?? null, limit ?? null);
}
async getRecentlyPlayedAudio(limit?: number): Promise<MediaItem[]> {
return invoke<MediaItem[]>("repository_get_recently_played_audio", {
handle: this.ensureHandle(),
limit: limit ?? null,
});
return commands.repositoryGetRecentlyPlayedAudio(this.ensureHandle(), limit ?? null);
}
async getResumeMovies(limit?: number): Promise<MediaItem[]> {
return invoke<MediaItem[]>("repository_get_resume_movies", {
handle: this.ensureHandle(),
limit: limit ?? null,
});
return commands.repositoryGetResumeMovies(this.ensureHandle(), limit ?? null);
}
async getGenres(parentId?: string): Promise<Genre[]> {
return invoke<Genre[]>("repository_get_genres", {
handle: this.ensureHandle(),
parentId: parentId ?? null,
});
return commands.repositoryGetGenres(this.ensureHandle(), parentId ?? null);
}
async search(query: string, options?: SearchOptions): Promise<SearchResult> {
return invoke<SearchResult>("repository_search", {
handle: this.ensureHandle(),
query,
options: options ?? null,
});
return commands.repositorySearch(this.ensureHandle(), query, options ?? null);
}
// ===== Playback Methods (all via Rust) =====
async getPlaybackInfo(itemId: string): Promise<PlaybackInfo> {
return invoke<PlaybackInfo>("repository_get_playback_info", {
handle: this.ensureHandle(),
itemId,
});
return commands.repositoryGetPlaybackInfo(this.ensureHandle(), itemId);
}
async reportPlaybackStart(itemId: string, positionTicks: number): Promise<void> {
return invoke("repository_report_playback_start", {
handle: this.ensureHandle(),
itemId,
positionTicks,
});
await commands.repositoryReportPlaybackStart(this.ensureHandle(), itemId, positionTicks);
}
async reportPlaybackProgress(itemId: string, positionTicks: number): Promise<void> {
return invoke("repository_report_playback_progress", {
handle: this.ensureHandle(),
itemId,
positionTicks,
});
await commands.repositoryReportPlaybackProgress(this.ensureHandle(), itemId, positionTicks);
}
async reportPlaybackStopped(itemId: string, positionTicks: number): Promise<void> {
return invoke("repository_report_playback_stopped", {
handle: this.ensureHandle(),
itemId,
positionTicks,
});
await commands.repositoryReportPlaybackStopped(this.ensureHandle(), itemId, positionTicks);
}
// ===== Stream URL Methods (via Rust) =====
async getAudioStreamUrl(itemId: string): Promise<string> {
return invoke<string>("repository_get_audio_stream_url", {
handle: this.ensureHandle(),
itemId,
});
return commands.repositoryGetAudioStreamUrl(this.ensureHandle(), itemId);
}
async getVideoStreamUrl(
@ -205,13 +147,13 @@ export class RepositoryClient {
startTimeSeconds?: number,
audioStreamIndex?: number
): Promise<string> {
return invoke<string>("repository_get_video_stream_url", {
handle: this.ensureHandle(),
return commands.repositoryGetVideoStreamUrl(
this.ensureHandle(),
itemId,
mediaSourceId: mediaSourceId ?? null,
startTimeSeconds: startTimeSeconds ?? null,
audioStreamIndex: audioStreamIndex ?? null,
});
mediaSourceId ?? null,
startTimeSeconds ?? null,
audioStreamIndex ?? null
);
}
// ===== URL Construction Methods (sync, no server call) =====
@ -221,12 +163,7 @@ export class RepositoryClient {
* The Rust backend constructs and returns the URL with proper credentials handling
*/
async getImageUrl(itemId: string, imageType: ImageType = "Primary", options?: ImageOptions): Promise<string> {
return invoke<string>("repository_get_image_url", {
handle: this.ensureHandle(),
itemId,
imageType,
options: options ?? null,
});
return commands.repositoryGetImageUrl(this.ensureHandle(), itemId, imageType, options ?? null);
}
/**
@ -239,13 +176,7 @@ export class RepositoryClient {
streamIndex: number,
format: string = "vtt"
): Promise<string> {
return invoke<string>("repository_get_subtitle_url", {
handle: this.ensureHandle(),
itemId,
mediaSourceId,
streamIndex,
format,
});
return commands.repositoryGetSubtitleUrl(this.ensureHandle(), itemId, mediaSourceId, streamIndex, format);
}
/**
@ -258,110 +189,61 @@ export class RepositoryClient {
quality: QualityPreset = "original",
mediaSourceId?: string
): Promise<string> {
return invoke<string>("repository_get_video_download_url", {
handle: this.ensureHandle(),
itemId,
quality,
mediaSourceId: mediaSourceId ?? null,
});
return commands.repositoryGetVideoDownloadUrl(this.ensureHandle(), itemId, quality, mediaSourceId ?? null);
}
// ===== Favorite Methods (via Rust) =====
async markFavorite(itemId: string): Promise<void> {
return invoke("repository_mark_favorite", {
handle: this.ensureHandle(),
itemId,
});
await commands.repositoryMarkFavorite(this.ensureHandle(), itemId);
}
async unmarkFavorite(itemId: string): Promise<void> {
return invoke("repository_unmark_favorite", {
handle: this.ensureHandle(),
itemId,
});
await commands.repositoryUnmarkFavorite(this.ensureHandle(), itemId);
}
// ===== Person Methods (via Rust) =====
async getPerson(personId: string): Promise<MediaItem> {
return invoke<MediaItem>("repository_get_person", {
handle: this.ensureHandle(),
personId,
});
return commands.repositoryGetPerson(this.ensureHandle(), personId);
}
async getItemsByPerson(personId: string, options?: GetItemsOptions): Promise<SearchResult> {
return invoke<SearchResult>("repository_get_items_by_person", {
handle: this.ensureHandle(),
personId,
options: options ?? null,
});
return commands.repositoryGetItemsByPerson(this.ensureHandle(), personId, options ?? null);
}
async getSimilarItems(itemId: string, limit?: number): Promise<SearchResult> {
return invoke<SearchResult>("repository_get_similar_items", {
handle: this.ensureHandle(),
itemId,
limit: limit ?? null,
});
return commands.repositoryGetSimilarItems(this.ensureHandle(), itemId, limit ?? null);
}
// ===== Playlist Methods (via Rust) =====
async createPlaylist(name: string, itemIds?: string[]): Promise<PlaylistCreatedResult> {
return invoke<PlaylistCreatedResult>("playlist_create", {
handle: this.ensureHandle(),
name,
itemIds: itemIds ?? null,
});
return commands.playlistCreate(this.ensureHandle(), name, itemIds ?? null);
}
async deletePlaylist(playlistId: string): Promise<void> {
return invoke("playlist_delete", {
handle: this.ensureHandle(),
playlistId,
});
await commands.playlistDelete(this.ensureHandle(), playlistId);
}
async renamePlaylist(playlistId: string, name: string): Promise<void> {
return invoke("playlist_rename", {
handle: this.ensureHandle(),
playlistId,
name,
});
await commands.playlistRename(this.ensureHandle(), playlistId, name);
}
async getPlaylistItems(playlistId: string): Promise<PlaylistEntry[]> {
return invoke<PlaylistEntry[]>("playlist_get_items", {
handle: this.ensureHandle(),
playlistId,
});
return commands.playlistGetItems(this.ensureHandle(), playlistId);
}
async addToPlaylist(playlistId: string, itemIds: string[]): Promise<void> {
return invoke("playlist_add_items", {
handle: this.ensureHandle(),
playlistId,
itemIds,
});
await commands.playlistAddItems(this.ensureHandle(), playlistId, itemIds);
}
async removeFromPlaylist(playlistId: string, entryIds: string[]): Promise<void> {
return invoke("playlist_remove_items", {
handle: this.ensureHandle(),
playlistId,
entryIds,
});
await commands.playlistRemoveItems(this.ensureHandle(), playlistId, entryIds);
}
async movePlaylistItem(playlistId: string, itemId: string, newIndex: number): Promise<void> {
return invoke("playlist_move_item", {
handle: this.ensureHandle(),
playlistId,
itemId,
newIndex,
});
await commands.playlistMoveItem(this.ensureHandle(), playlistId, itemId, newIndex);
}
// ===== Getters =====

View File

@ -1,5 +1,5 @@
<script lang="ts">
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import { auth } from "$lib/stores/auth";
import { get } from "svelte/store";
@ -47,15 +47,12 @@
const repositoryHandle = repository.getHandle();
// Call Rust to get image as base64 data URL
const dataUrl = await invoke<string>("image_get_url", {
repositoryHandle,
request: {
itemId,
imageType,
maxWidth,
maxHeight,
tag,
},
const dataUrl = await commands.imageGetUrl(repositoryHandle, {
itemId,
imageType,
maxWidth,
maxHeight,
tag,
});
// Use data URL directly

View File

@ -1,5 +1,5 @@
<script lang="ts">
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import { auth } from "$lib/stores/auth";
import { downloads } from "$lib/stores/downloads";
import { goto } from "$app/navigation";
@ -34,7 +34,7 @@
loading = true;
const userId = $auth.user?.id;
if (userId) {
stats = await invoke<StorageStats>("get_download_storage_stats", { userId });
stats = await commands.getDownloadStorageStats(userId);
}
} catch (error) {
console.error("Failed to load storage stats:", error);
@ -56,7 +56,7 @@
deleting = true;
const userId = $auth.user?.id;
if (userId) {
await invoke("delete_all_downloads", { userId });
await commands.deleteAllDownloads(userId);
await downloads.refresh(userId);
await loadStats();
}
@ -73,7 +73,7 @@
deletingAlbum = albumId;
const userId = $auth.user?.id;
if (userId) {
await invoke("delete_album_downloads", { albumId, userId });
await commands.deleteAlbumDownloads(albumId, userId);
await downloads.refresh(userId);
await loadStats();
}

View File

@ -1,7 +1,7 @@
<script lang="ts">
import { downloads } from "$lib/stores/downloads";
import { auth } from "$lib/stores/auth";
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import type { MediaItem } from "$lib/api/types";
interface Props {
@ -89,18 +89,14 @@
const downloadIds = await downloads.downloadAlbum(albumId, userId, basePath);
// Get target directory for downloads
const targetDir = await invoke<string>("storage_get_path");
const targetDir = await commands.storageGetPath();
// Start each queued track download
for (let i = 0; i < tracks.length && i < downloadIds.length; i++) {
try {
const streamUrl = await repo.getAudioStreamUrl(tracks[i].id);
if (streamUrl) {
await invoke("start_download", {
downloadId: downloadIds[i],
streamUrl,
targetDir,
});
await commands.startDownload(downloadIds[i], streamUrl, targetDir);
}
} catch (e) {
console.error(`Failed to start download for track ${tracks[i].id}:`, e);

View File

@ -1,7 +1,6 @@
<script lang="ts">
import { downloads } from "$lib/stores/downloads";
import { auth } from "$lib/stores/auth";
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import DownloadButtonCore from "./DownloadButtonCore.svelte";
import type { DownloadState } from "./DownloadButtonCore.svelte";
@ -81,7 +80,7 @@
}
// Get target directory
const targetDir = await invoke<string>("storage_get_path");
const targetDir = await commands.storageGetPath();
console.log(" Target directory:", targetDir);
// Queue and start download in single atomic operation

View File

@ -1,7 +1,7 @@
<script lang="ts">
import { onMount } from "svelte";
import { goto } from "$app/navigation";
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import type { MediaItem, PlaylistEntry } from "$lib/api/types";
import { auth } from "$lib/stores/auth";
import { toast } from "$lib/stores/toast";
@ -51,17 +51,14 @@
const repo = auth.getRepository();
const repositoryHandle = repo.getHandle();
const trackIds = entries.map(e => e.id);
await invoke("player_play_tracks", {
repositoryHandle,
request: {
trackIds,
startIndex: 0,
shuffle: false,
context: {
type: "playlist",
playlistId: playlist.id,
playlistName: playlist.name,
},
await commands.playerPlayTracks(repositoryHandle, {
trackIds,
startIndex: 0,
shuffle: false,
context: {
type: "playlist",
playlistId: playlist.id,
playlistName: playlist.name,
},
});
} catch (e) {
@ -76,17 +73,14 @@
const repo = auth.getRepository();
const repositoryHandle = repo.getHandle();
const trackIds = entries.map(e => e.id);
await invoke("player_play_tracks", {
repositoryHandle,
request: {
trackIds,
startIndex: 0,
shuffle: true,
context: {
type: "playlist",
playlistId: playlist.id,
playlistName: playlist.name,
},
await commands.playerPlayTracks(repositoryHandle, {
trackIds,
startIndex: 0,
shuffle: true,
context: {
type: "playlist",
playlistId: playlist.id,
playlistName: playlist.name,
},
});
} catch (e) {

View File

@ -1,7 +1,7 @@
<script lang="ts">
import { downloads, videoDownloads } from "$lib/stores/downloads";
import { auth } from "$lib/stores/auth";
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import { QUALITY_PRESETS, type QualityPreset } from "$lib/api/quality-presets";
interface Props {
@ -53,7 +53,7 @@
console.log("📺 Starting season download for:", seasonName, "quality:", quality);
// Get target directory
const targetDir = await invoke<string>("storage_get_path");
const targetDir = await commands.storageGetPath();
const basePath = `${targetDir}/videos`;
// Queue all episodes in this season

View File

@ -1,7 +1,7 @@
<script lang="ts">
import { downloads, videoDownloads } from "$lib/stores/downloads";
import { auth } from "$lib/stores/auth";
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import { QUALITY_PRESETS, type QualityPreset } from "$lib/api/quality-presets";
interface Props {
@ -47,7 +47,7 @@
console.log("📺 Starting series download for:", seriesName, "quality:", quality);
// Get target directory
const targetDir = await invoke<string>("storage_get_path");
const targetDir = await commands.storageGetPath();
const basePath = `${targetDir}/videos`;
// Queue all episodes

View File

@ -1,5 +1,6 @@
<script lang="ts">
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import type { PlayTracksContext } from "$lib/api/bindings";
import { goto } from "$app/navigation";
import { queue } from "$lib/stores/queue";
import { auth } from "$lib/stores/auth";
@ -62,14 +63,11 @@
if (context && context.type === "album") {
const repositoryHandle = repo.getHandle();
console.log(`[TrackList] Playing track: "${track.name}" (ID: ${track.id}, index in list: ${index})`);
await invoke("player_play_album_track", {
repositoryHandle,
request: {
albumId: context.albumId,
albumName: context.albumName,
trackId: track.id,
shuffle: false,
},
await commands.playerPlayAlbumTrack(repositoryHandle, {
albumId: context.albumId,
albumName: context.albumName,
trackId: track.id,
shuffle: false,
});
return;
}
@ -80,7 +78,7 @@
const trackIds = tracks.map((t) => t.id);
// Determine context for queue
let playContext;
let playContext: PlayTracksContext;
if (context?.type === "playlist") {
playContext = {
type: "playlist",
@ -88,17 +86,14 @@
playlistName: context.playlistName,
};
} else {
playContext = { type: "custom" };
playContext = { type: "custom", label: null };
}
await invoke("player_play_tracks", {
repositoryHandle,
request: {
trackIds,
startIndex: index,
shuffle: false,
context: playContext,
},
await commands.playerPlayTracks(repositoryHandle, {
trackIds,
startIndex: index,
shuffle: false,
context: playContext,
});
// Queue will auto-update from Rust backend event

View File

@ -1,7 +1,7 @@
<script lang="ts">
import { downloads } from "$lib/stores/downloads";
import { auth } from "$lib/stores/auth";
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import { QUALITY_PRESETS, type QualityPreset } from "$lib/api/quality-presets";
interface Props {
@ -66,11 +66,11 @@
console.log("🎬 Starting video download for item:", itemId, "quality:", quality);
// Get stream URL based on quality
const streamUrl = repo.getVideoDownloadUrl(itemId, quality);
const streamUrl = await repo.getVideoDownloadUrl(itemId, quality);
console.log(" Stream URL obtained");
// Get target directory
const targetDir = await invoke<string>("storage_get_path");
const targetDir = await commands.storageGetPath();
// Create file path
const safeName = (itemName || itemId).replace(/[/\\:*?"<>|]/g, "_");
@ -107,11 +107,7 @@
await downloads.pinItem(itemId);
// Actually start the download
await invoke("start_download", {
downloadId,
streamUrl,
targetDir,
});
await commands.startDownload(downloadId, streamUrl, targetDir);
console.log(" Download started");
} catch (error) {
console.error("Failed to start video download:", error);

View File

@ -1,6 +1,6 @@
<!-- TRACES: UR-004, UR-005, UR-028 | DR-009 -->
<script lang="ts">
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import { goto } from "$app/navigation";
import type { MediaItem } from "$lib/api/types";
import { auth } from "$lib/stores/auth";
@ -74,28 +74,28 @@
async function handleSeekEnd() {
seeking = false;
seekPending = true; // Keep showing target position until backend catches up
await invoke("player_seek", { position: seekValue });
await commands.playerSeek(seekValue);
}
// Control handlers for Controls component
async function handlePlayPause() {
await invoke("player_toggle");
await commands.playerToggle();
}
async function handlePrevious() {
await invoke("player_previous");
await commands.playerPrevious();
}
async function handleNext() {
await invoke("player_next");
await commands.playerNext();
}
async function handleToggleShuffle() {
await invoke("player_toggle_shuffle");
await commands.playerToggleShuffle();
}
async function handleCycleRepeat() {
await invoke("player_cycle_repeat");
await commands.playerCycleRepeat();
}
// Prefer album ID for artwork (all tracks in an album share the same cover)
@ -128,7 +128,7 @@
async function handleQueueItemClick(index: number) {
try {
queue.skipTo(index);
await invoke("player_skip_to", { index });
await commands.playerSkipTo(index);
} catch (e) {
console.error("Failed to skip to queue item:", e);
}

View File

@ -14,7 +14,7 @@
* @req: UR-010 - Control playback of Jellyfin remote sessions
*/
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import { goto } from "$app/navigation";
import type { MediaItem } from "$lib/api/types";
import { auth } from "$lib/stores/auth";
@ -105,23 +105,23 @@
// Control handlers for Controls component
async function handlePlayPause() {
await invoke("player_toggle");
await commands.playerToggle();
}
async function handlePrevious() {
await invoke("player_previous");
await commands.playerPrevious();
}
async function handleNext() {
await invoke("player_next");
await commands.playerNext();
}
async function handleToggleShuffle() {
await invoke("player_toggle_shuffle");
await commands.playerToggleShuffle();
}
async function handleCycleRepeat() {
await invoke("player_cycle_repeat");
await commands.playerCycleRepeat();
}
// Scrubbing (seek) handler
@ -133,7 +133,7 @@
const newPosition = percent * displayDuration;
try {
await invoke("player_seek", { position: newPosition });
await commands.playerSeek(newPosition);
haptics.tap();
} catch (err) {
console.error("Failed to seek:", err);

View File

@ -1,5 +1,5 @@
<script lang="ts">
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import { dndzone, SOURCES, TRIGGERS } from "svelte-dnd-action";
import type { MediaItem } from "$lib/api/types";
import { auth } from "$lib/stores/auth";
@ -79,10 +79,7 @@
queue.moveInQueue(fromIndex, toIndex);
// Sync with backend
await invoke("player_move_in_queue", {
fromIndex,
toIndex,
});
await commands.playerMoveInQueue(fromIndex, toIndex);
} catch (e) {
console.error("Failed to move queue item:", e);
// The store already updated optimistically, refresh if needed
@ -109,7 +106,7 @@
e.stopPropagation();
try {
queue.removeFromQueue(index);
await invoke("player_remove_from_queue", { index });
await commands.playerRemoveFromQueue(index);
} catch (err) {
console.error("Failed to remove from queue:", err);
}

View File

@ -1,7 +1,7 @@
<!-- TRACES: UR-003, UR-005, UR-020, UR-021, UR-026 | DR-010, DR-023, DR-024 -->
<script lang="ts">
import { onMount, onDestroy } from "svelte";
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import { listen } from "@tauri-apps/api/event";
import Hls from "hls.js";
import type { MediaItem } from "$lib/api/types";
@ -140,13 +140,7 @@
const userId = auth.getUserId();
if (!userId) return;
const preference = await invoke<{ seriesId: string, audioTrackDisplayTitle?: string | null, audioTrackLanguage?: string | null, audioTrackIndex?: number | null } | null>(
"storage_get_series_audio_preference",
{
userId,
seriesId: media.seriesId
}
);
const preference = await commands.storageGetSeriesAudioPreference(userId, media.seriesId);
if (preference) {
console.log("[VideoPlayer] Loaded series audio preference:", preference);
@ -403,14 +397,12 @@
// Call Rust backend to start playback
// Rust will choose ExoPlayer (Android), libmpv (Linux), or tell us to use HTML5
// Send minimal video data - no complex serialization to avoid Tauri Android issues
const response: any = await invoke("player_play_item", {
item: {
streamUrl: currentStreamUrl,
title: media.name,
id: media.id,
videoCodec: needsTranscoding ? "hevc" : "h264",
needsTranscoding: needsTranscoding,
},
const response: any = await commands.playerPlayItem({
streamUrl: currentStreamUrl,
title: media.name,
id: media.id,
videoCodec: needsTranscoding ? "hevc" : "h264",
needsTranscoding: needsTranscoding,
});
// Rust tells us which backend it's using
@ -422,7 +414,7 @@
if (useHtml5Element && !needsTranscoding) {
try {
console.log("[VideoPlayer] Using HTML5 for direct stream - stopping backend player to prevent dual audio");
await invoke("player_stop");
await commands.playerStop();
didStopBackendEarly = true; // Track that we stopped the backend
} catch (err) {
console.warn("[VideoPlayer] Failed to stop backend player:", err);
@ -460,7 +452,7 @@
// For non-transcoded content, try to stop any backend player that might have started
if (!needsTranscoding) {
try {
await invoke("player_stop");
await commands.playerStop();
didStopBackendEarly = true;
} catch (stopErr) {
// Ignore errors when stopping
@ -536,7 +528,7 @@
if (didStartNativePlayback && !didStopBackendEarly) {
try {
console.log("[VideoPlayer] Stopping backend player on component unmount");
await invoke("player_stop");
await commands.playerStop();
} catch (err) {
console.error("[VideoPlayer] Failed to stop backend player:", err);
}
@ -768,7 +760,7 @@
async function togglePlayPause() {
if (!useHtml5Element) {
try {
const response = await invoke<{ state: string }>("player_toggle");
const response = (await commands.playerToggle()) as any;
isPlaying = response.state === "playing";
} catch (err) {
console.error("[VideoPlayer] Failed to toggle native player:", err);
@ -807,13 +799,13 @@
}
// Backend smart seeking handles both native and HTML5
const response = await invoke<{strategy: string, position?: number, newUrl?: string, seekOffset?: number}>("player_seek_video", {
repositoryHandle: repo.getHandle(),
position: targetTime,
mediaSourceId: mediaSourceId ?? null,
audioStreamIndex: selectedAudioTrackIndex ?? null,
useHtml5: useHtml5Element,
});
const response = (await commands.playerSeekVideo(
repo.getHandle(),
targetTime,
mediaSourceId ?? null,
selectedAudioTrackIndex ?? null,
useHtml5Element
)) as any;
console.log("[VideoPlayer] Backend seek response:", response);
@ -1095,14 +1087,14 @@
if (!repo) throw new Error("Not authenticated");
// Call unified backend command
const response = await invoke<{strategy: string, success?: boolean, newUrl?: string, position?: number}>("player_switch_audio_track", {
repositoryHandle: repo.getHandle(),
const response = (await commands.playerSwitchAudioTrack(
repo.getHandle(),
streamIndex,
arrayIndex,
useHtml5: useHtml5Element,
currentPosition: useHtml5Element && videoElement ? videoElement.currentTime + seekOffset : null,
mediaSourceId: mediaSourceId ?? null,
});
useHtml5Element,
useHtml5Element && videoElement ? videoElement.currentTime + seekOffset : null,
mediaSourceId ?? null
)) as any;
// Handle response based on strategy
if (response.strategy === "reloadStream" && useHtml5Element && videoElement) {
@ -1171,14 +1163,14 @@
// Find the selected track info
const selectedTrack = audioTracks().find(t => t.index === streamIndex);
if (selectedTrack) {
await invoke("storage_save_series_audio_preference", {
await commands.storageSaveSeriesAudioPreference(
userId,
seriesId: media.seriesId,
serverId: media.serverId,
audioTrackDisplayTitle: selectedTrack.displayTitle || null,
audioTrackLanguage: selectedTrack.language || null,
audioTrackIndex: streamIndex,
});
media.seriesId,
media.serverId ?? "",
selectedTrack.displayTitle || null,
selectedTrack.language || null,
streamIndex
);
console.log("[VideoPlayer] Saved series audio preference:", selectedTrack.displayTitle || selectedTrack.language);
}
} catch (err) {
@ -1229,7 +1221,7 @@
// Use array index for ExoPlayer (0-based position in subtitle tracks array)
// If streamIndex is null (disable), pass null; otherwise use arrayIndex
const indexToUse = streamIndex === null ? null : (arrayIndex !== undefined ? arrayIndex : streamIndex);
await invoke("player_set_subtitle_track", { streamIndex: indexToUse });
await commands.playerSetSubtitleTrack(indexToUse);
console.log("[VideoPlayer] Native backend subtitle track changed - arrayIndex:", arrayIndex, "used:", indexToUse);
} catch (error) {
console.error("[VideoPlayer] Failed to set subtitle track:", error);

View File

@ -1,5 +1,5 @@
<script lang="ts">
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import { volume, isMuted, mergedVolume } from "$lib/stores/player";
import { isRemoteMode } from "$lib/stores/playbackMode";
import { selectedSession, sessions } from "$lib/stores/sessions";
@ -31,7 +31,7 @@
// Remote mode: send volume as 0-100 integer to remote session
await sessions.sendVolume($selectedSession.id, Math.round(newVolume * 100));
} else {
await invoke("player_set_volume", { volume: newVolume });
await commands.playerSetVolume(newVolume);
}
}
@ -39,7 +39,7 @@
if ($isRemoteMode && $selectedSession) {
await sessions.sendToggleMute($selectedSession.id);
} else {
await invoke("player_toggle_mute");
await commands.playerToggleMute();
}
}

View File

@ -1,7 +1,7 @@
<!-- TRACES: UR-010 | DR-037 -->
<script lang="ts">
import { onMount, onDestroy } from "svelte";
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import { sessions, controllableSessions, selectedSession } from "$lib/stores";
import SessionPickerModal from "./SessionPickerModal.svelte";
@ -42,18 +42,18 @@
// Set initial hint based on connection state
const hint = isConnected ? "cast_active" : "cast_discovery";
await invoke("sessions_set_polling_hint", { hint });
await commands.sessionsSetPollingHint(hint);
});
onDestroy(async () => {
// Reset to normal polling when component unmounts
await invoke("sessions_set_polling_hint", { hint: "normal" });
await commands.sessionsSetPollingHint("normal");
});
// Update polling hint when connection state changes
$effect(() => {
const hint = isConnected ? "cast_active" : "cast_discovery";
invoke("sessions_set_polling_hint", { hint });
commands.sessionsSetPollingHint(hint);
});
const isConnected = $derived($selectedSession !== null);

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) {

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

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);
}
/**

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);
}

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);

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();
});

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();
}

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");
}
}

View File

@ -6,10 +6,11 @@
// TRACES: UR-009, UR-012 | IR-009, IR-014
import { writable, derived, get } from "svelte/store";
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { commands } from "$lib/api/bindings";
import { RepositoryClient } from "$lib/api/repository-client";
import type { User, AuthResult } from "$lib/api/types";
import type { Session, AuthServerInfo as ServerInfo } from "$lib/api/bindings";
import { connectivity } from "./connectivity";
import { getDeviceId, clearCache as clearDeviceIdCache } from "$lib/services/deviceId";
@ -29,29 +30,6 @@ interface AuthState {
sessionVerified: boolean;
}
interface Session {
userId: string;
username: string;
serverId: string;
serverUrl: string;
serverName: string;
accessToken: string;
verified: boolean;
needsReauth: boolean;
}
interface ServerInfo {
name: string;
version: string;
id: string;
normalizedUrl: string;
}
interface SecurityStatus {
usingKeyring: boolean;
storageType: string;
}
function createAuthStore() {
const initialState: AuthState = {
isAuthenticated: false,
@ -163,7 +141,7 @@ function createAuthStore() {
try {
// Check security status
try {
const securityStatus = await invoke<SecurityStatus>("storage_get_security_status");
const securityStatus = await commands.storageGetSecurityStatus();
console.log("[Auth] Security status:", securityStatus);
if (!securityStatus.usingKeyring) {
update((s) => ({
@ -178,7 +156,7 @@ function createAuthStore() {
// Initialize auth manager and get session
console.log("[Auth] Initializing auth manager...");
const session = await invoke<Session | null>("auth_initialize");
const session = await commands.authInitialize();
console.log("[Auth] Session retrieval result:", session ? "Session found" : "No session found");
if (session) {
@ -192,12 +170,12 @@ function createAuthStore() {
const deviceId = await getDeviceId();
try {
console.log("[Auth] Configuring Rust player with restored session...");
await invoke("player_configure_jellyfin", {
serverUrl: session.serverUrl,
accessToken: session.accessToken,
userId: session.userId,
deviceId: deviceId,
});
await commands.playerConfigureJellyfin(
session.serverUrl,
session.accessToken,
session.userId,
deviceId
);
console.log("[Auth] Rust player configured for automatic playback reporting");
} catch (error) {
console.error("[Auth] Failed to configure Rust player:", error);
@ -231,7 +209,7 @@ function createAuthStore() {
// Start background session verification
try {
const verifyDeviceId = await getDeviceId();
await invoke("auth_start_verification", { deviceId: verifyDeviceId });
await commands.authStartVerification(verifyDeviceId);
console.log("[Auth] Background verification started");
} catch (error) {
console.error("[Auth] Failed to start verification:", error);
@ -273,7 +251,7 @@ function createAuthStore() {
try {
console.log("[Auth] Connecting to server:", serverUrl);
const serverInfo = await invoke<ServerInfo>("auth_connect_to_server", { serverUrl });
const serverInfo = await commands.authConnectToServer(serverUrl);
console.log("[Auth] Connected to server:", serverInfo.name, serverInfo.version);
console.log("[Auth] Normalized URL:", serverInfo.normalizedUrl);
@ -302,47 +280,32 @@ function createAuthStore() {
const deviceId = await getDeviceId();
console.log("[Auth] Logging in as:", username);
const authResult = await invoke<AuthResult>("auth_login", {
serverUrl,
username,
password,
deviceId,
});
const authResult = await commands.authLogin(serverUrl, username, password, deviceId);
console.log("[Auth] Login successful:", authResult.user);
// Save to storage
await invoke("storage_save_server", {
id: authResult.serverId,
name: serverName,
url: serverUrl,
version: null,
});
await commands.storageSaveServer(authResult.serverId, serverName, serverUrl, null);
await invoke("storage_save_user", {
id: authResult.user.id,
serverId: authResult.serverId,
username: authResult.user.name,
accessToken: authResult.accessToken,
});
await commands.storageSaveUser(
authResult.user.id,
authResult.serverId,
authResult.user.name,
authResult.accessToken
);
await invoke("storage_set_active_user", {
userId: authResult.user.id,
serverId: authResult.serverId,
});
await commands.storageSetActiveUser(authResult.user.id, authResult.serverId);
// Set session in auth manager with server name
await invoke("auth_set_session", {
session: {
userId: authResult.user.id,
username: authResult.user.name,
serverId: authResult.serverId,
serverUrl,
serverName,
accessToken: authResult.accessToken,
verified: true,
needsReauth: false,
},
await commands.authSetSession({
userId: authResult.user.id,
username: authResult.user.name,
serverId: authResult.serverId,
serverUrl,
serverName,
accessToken: authResult.accessToken,
verified: true,
needsReauth: false,
});
// Create RepositoryClient
@ -352,12 +315,12 @@ function createAuthStore() {
// Configure Rust player
try {
const playerDeviceId = await getDeviceId();
await invoke("player_configure_jellyfin", {
await commands.playerConfigureJellyfin(
serverUrl,
accessToken: authResult.accessToken,
userId: authResult.user.id,
deviceId: playerDeviceId,
});
authResult.accessToken,
authResult.user.id,
playerDeviceId
);
console.log("[Auth] Rust player configured for playback reporting");
} catch (error) {
console.error("[Auth] Failed to configure Rust player:", error);
@ -380,7 +343,7 @@ function createAuthStore() {
// Start background verification
try {
const verifyDeviceId = await getDeviceId();
await invoke("auth_start_verification", { deviceId: verifyDeviceId });
await commands.authStartVerification(verifyDeviceId);
} catch (error) {
console.error("[Auth] Failed to start verification:", error);
}
@ -404,25 +367,22 @@ function createAuthStore() {
const deviceId = await getDeviceId();
console.log("[Auth] Re-authenticating...");
const authResult = await invoke<AuthResult>("auth_reauthenticate", {
password,
deviceId,
});
const authResult = await commands.authReauthenticate(password, deviceId);
console.log("[Auth] Re-authentication successful");
// Update storage
await invoke("storage_save_user", {
id: authResult.user.id,
serverId: authResult.serverId,
username: authResult.user.name,
accessToken: authResult.accessToken,
});
await commands.storageSaveUser(
authResult.user.id,
authResult.serverId,
authResult.user.name,
authResult.accessToken
);
// Recreate repository with new credentials
if (repository) {
await repository.destroy();
const session = await invoke<Session | null>("auth_get_session");
const session = await commands.authGetSession();
if (session) {
await repository.create(session.serverUrl, authResult.user.id, authResult.accessToken, authResult.serverId);
}
@ -431,12 +391,12 @@ function createAuthStore() {
// Reconfigure player
try {
const playerDeviceId = await getDeviceId();
await invoke("player_configure_jellyfin", {
serverUrl: repository ? await getCurrentSessionServerUrl() : "",
accessToken: authResult.accessToken,
userId: authResult.user.id,
deviceId: playerDeviceId,
});
await commands.playerConfigureJellyfin(
repository ? await getCurrentSessionServerUrl() : "",
authResult.accessToken,
authResult.user.id,
playerDeviceId
);
} catch (error) {
console.error("[Auth] Failed to reconfigure player:", error);
}
@ -467,19 +427,15 @@ function createAuthStore() {
*/
async function logout() {
try {
const session = await invoke<Session | null>("auth_get_session");
const session = await commands.authGetSession();
if (session) {
const deviceId = await getDeviceId();
await invoke("auth_logout", {
serverUrl: session.serverUrl,
accessToken: session.accessToken,
deviceId,
});
await commands.authLogout(session.serverUrl, session.accessToken, deviceId);
}
// Disable Jellyfin reporting in player
try {
await invoke("player_disable_jellyfin");
await commands.playerDisableJellyfin();
} catch (error) {
console.error("[Auth] Failed to disable player reporting:", error);
}
@ -524,7 +480,7 @@ function createAuthStore() {
*/
async function getCurrentSession() {
try {
return await invoke<Session | null>("auth_get_session");
return await commands.authGetSession();
} catch (error) {
console.error("[Auth] Failed to get current session:", error);
return null;
@ -551,7 +507,7 @@ function createAuthStore() {
* Helper to get server URL from current session.
*/
async function getCurrentSessionServerUrl(): Promise<string> {
const session = await invoke<Session | null>("auth_get_session");
const session = await commands.authGetSession();
return session?.serverUrl || "";
}
@ -562,7 +518,7 @@ function createAuthStore() {
try {
const deviceId = await getDeviceId();
console.log("[Auth] Retrying session verification after reconnection");
await invoke("auth_start_verification", { deviceId });
await commands.authStartVerification(deviceId);
} catch (error) {
console.error("[Auth] Failed to retry verification:", error);
}

View File

@ -6,8 +6,8 @@
import { writable, derived } from "svelte/store";
import { browser } from "$app/environment";
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { commands } from "$lib/api/bindings";
export interface ConnectivityState {
/** Browser's navigator.onLine status */
@ -29,13 +29,6 @@ export interface ConnectivityEvents {
onServerReconnected?: () => void;
}
interface RustConnectivityStatus {
isServerReachable: boolean;
lastChecked: string | null;
connectionError: string | null;
isChecking: boolean;
}
function createConnectivityStore() {
const initialState: ConnectivityState = {
isOnline: browser ? navigator.onLine : true,
@ -115,10 +108,10 @@ function createConnectivityStore() {
*/
async function checkServerReachable(): Promise<boolean> {
try {
const isReachable = await invoke<boolean>("connectivity_check_server");
const isReachable = await commands.connectivityCheckServer();
// Fetch updated status from Rust
const status = await invoke<RustConnectivityStatus>("connectivity_get_status");
const status = await commands.connectivityGetStatus();
update((s) => ({
...s,
isServerReachable: status.isServerReachable,
@ -145,13 +138,13 @@ function createConnectivityStore() {
console.log("[ConnectivityStore] Starting monitoring for:", url);
// Set the server URL
await invoke("connectivity_set_server_url", { url });
await commands.connectivitySetServerUrl(url);
// Start the Rust monitoring task (performs immediate check)
await invoke("connectivity_start_monitoring");
await commands.connectivityStartMonitoring();
// Get the initial status immediately after starting
const status = await invoke<RustConnectivityStatus>("connectivity_get_status");
const status = await commands.connectivityGetStatus();
update((s) => ({
...s,
isServerReachable: status.isServerReachable,
@ -179,7 +172,7 @@ function createConnectivityStore() {
if (!isMonitoring) return;
try {
await invoke("connectivity_stop_monitoring");
await commands.connectivityStopMonitoring();
isMonitoring = false;
eventHandlers = {};
console.log("[ConnectivityStore] Stopped monitoring");
@ -193,7 +186,7 @@ function createConnectivityStore() {
*/
async function setServerUrl(url: string): Promise<void> {
try {
await invoke("connectivity_set_server_url", { url });
await commands.connectivitySetServerUrl(url);
} catch (error) {
console.error("[ConnectivityStore] Failed to set server URL:", error);
}
@ -211,7 +204,7 @@ function createConnectivityStore() {
*/
async function markReachable(): Promise<void> {
try {
await invoke("connectivity_mark_reachable");
await commands.connectivityMarkReachable();
// Update local state
update((s) => ({
@ -230,7 +223,7 @@ function createConnectivityStore() {
*/
async function markUnreachable(error?: string): Promise<void> {
try {
await invoke("connectivity_mark_unreachable", { error: error ?? null });
await commands.connectivityMarkUnreachable(error ?? null);
// Update local state
update((s) => ({

View File

@ -131,7 +131,7 @@ describe("downloads store", () => {
expect(mockInvoke).toHaveBeenCalledWith("get_downloads", {
userId: "user-1",
statusFilter: undefined,
statusFilter: null,
});
const state = get(downloads);

View File

@ -1,7 +1,6 @@
// Download manager state store
// TRACES: UR-011, UR-013, UR-018 | DR-015, DR-017
import { writable, derived, get } from 'svelte/store';
import { invoke } from '@tauri-apps/api/core';
import { commands } from '$lib/api/bindings';
import { listen, type UnlistenFn } from '@tauri-apps/api/event';
@ -95,13 +94,10 @@ function createDownloadsStore() {
try {
console.log('🔄 Refreshing downloads for user:', userId);
const response = await invoke<{ downloads: DownloadInfo[]; stats: DownloadStats }>(
'get_downloads',
{
userId,
statusFilter
}
);
const response = (await commands.getDownloads(
userId,
statusFilter ?? null
)) as unknown as { downloads: DownloadInfo[]; stats: DownloadStats };
console.log(' Got', response.downloads.length, 'downloads from backend');
console.log(' Stats:', response.stats);
@ -182,11 +178,7 @@ function createDownloadsStore() {
async downloadAlbum(albumId: string, userId: string, basePath: string): Promise<number[]> {
try {
console.log('📥 downloadAlbum called:', { albumId, userId, basePath });
const downloadIds = await invoke<number[]>('download_album', {
albumId,
userId,
basePath
});
const downloadIds = await commands.downloadAlbum(albumId, userId, basePath);
console.log(' Got download IDs from backend:', downloadIds);
// Refresh downloads
@ -267,13 +259,13 @@ function createDownloadsStore() {
basePath,
qualityPreset
});
const downloadIds = await invoke<number[]>('download_series', {
const downloadIds = await commands.downloadSeries(
seriesId,
seriesName,
userId,
basePath,
qualityPreset
});
qualityPreset ?? null
);
console.log(' Queued', downloadIds.length, 'episodes for download');
// Refresh downloads
@ -306,15 +298,15 @@ function createDownloadsStore() {
seasonNumber,
qualityPreset
});
const downloadIds = await invoke<number[]>('download_season', {
const downloadIds = await commands.downloadSeason(
seasonId,
seriesName,
seasonName,
seasonNumber,
userId,
basePath,
qualityPreset
});
qualityPreset ?? null
);
console.log(' Queued', downloadIds.length, 'episodes for download');
// Refresh downloads
@ -332,7 +324,7 @@ function createDownloadsStore() {
*/
async pinItem(itemId: string): Promise<void> {
try {
await invoke('pin_item', { itemId });
await commands.pinItem(itemId);
} catch (error) {
console.error('Failed to pin item:', error);
throw error;
@ -344,7 +336,7 @@ function createDownloadsStore() {
*/
async unpinItem(itemId: string): Promise<void> {
try {
await invoke('unpin_item', { itemId });
await commands.unpinItem(itemId);
} catch (error) {
console.error('Failed to unpin item:', error);
throw error;
@ -356,7 +348,7 @@ function createDownloadsStore() {
*/
async isItemPinned(itemId: string): Promise<boolean> {
try {
return await invoke<boolean>('is_item_pinned', { itemId });
return await commands.isItemPinned(itemId);
} catch (error) {
console.error('Failed to check pin status:', error);
return false;
@ -368,7 +360,7 @@ function createDownloadsStore() {
*/
async pause(downloadId: number): Promise<void> {
try {
await invoke('pause_download', { downloadId });
await commands.pauseDownload(downloadId);
} catch (error) {
console.error('Failed to pause download:', error);
throw error;
@ -380,7 +372,7 @@ function createDownloadsStore() {
*/
async resume(downloadId: number): Promise<void> {
try {
await invoke('resume_download', { downloadId });
await commands.resumeDownload(downloadId);
} catch (error) {
console.error('Failed to resume download:', error);
throw error;
@ -392,7 +384,7 @@ function createDownloadsStore() {
*/
async cancel(downloadId: number): Promise<void> {
try {
await invoke('cancel_download', { downloadId });
await commands.cancelDownload(downloadId);
} catch (error) {
console.error('Failed to cancel download:', error);
throw error;
@ -404,7 +396,7 @@ function createDownloadsStore() {
*/
async delete(downloadId: number): Promise<void> {
try {
await invoke('delete_download', { downloadId });
await commands.deleteDownload(downloadId);
update((state) => {
const { [downloadId]: removed, ...remaining } = state.downloads;
return { ...state, downloads: remaining };
@ -574,11 +566,11 @@ function handleDownloadEvent(payload: DownloadEvent): void {
case 'completed':
if (download) {
// Persist to database
invoke('mark_download_completed', {
downloadId: payload.downloadId,
bytesDownloaded: payload.totalBytes || download.fileSize || download.bytesDownloaded,
filePath: payload.filePath || download.filePath
}).catch((err) => console.error('Failed to persist download completion:', err));
commands.markDownloadCompleted(
payload.downloadId,
payload.totalBytes || download.fileSize || download.bytesDownloaded,
payload.filePath || download.filePath
).catch((err) => console.error('Failed to persist download completion:', err));
updateDownloadInStore(payload.downloadId, {
status: 'completed',
@ -592,10 +584,10 @@ function handleDownloadEvent(payload: DownloadEvent): void {
case 'failed':
if (download) {
// Persist to database
invoke('mark_download_failed', {
downloadId: payload.downloadId,
errorMessage: payload.error || 'Unknown error'
}).catch((err) => console.error('Failed to persist download failure:', err));
commands.markDownloadFailed(
payload.downloadId,
payload.error || 'Unknown error'
).catch((err) => console.error('Failed to persist download failure:', err));
updateDownloadInStore(payload.downloadId, {
status: 'failed',

View File

@ -1,236 +0,0 @@
/**
* Integration tests for playbackMode store
*
* Tests that the store calls Tauri commands with correct parameter names.
*
* IMPORTANT: Tauri v2's #[tauri::command] macro automatically converts
* snake_case Rust parameter names to camelCase for the frontend.
* So Rust `repository_handle: String` frontend sends `repositoryHandle`.
* Nested struct fields with #[serde(rename_all = "camelCase")] also use camelCase.
*/
import { vi, describe, it, expect, beforeEach } from "vitest";
describe("playbackMode store - Tauri invoke parameter verification", () => {
let mockInvokedCalls: Array<{ command: string; args: Record<string, any> }> =
[];
beforeEach(() => {
mockInvokedCalls = [];
// Mock invoke to capture calls
vi.mock("@tauri-apps/api/core", () => ({
invoke: vi.fn(async (command: string, args?: Record<string, any>) => {
mockInvokedCalls.push({ command, args: args || {} });
return { success: true };
}),
}));
});
describe("player_play_tracks command parameters", () => {
it("should use repositoryHandle (camelCase, auto-converted by Tauri v2)", () => {
const correctCall = {
repositoryHandle: "test-handle-123", // ✓ CORRECT - Tauri v2 auto-converts
request: {
trackIds: ["track-1"],
startIndex: 0,
shuffle: false,
context: {
type: "search",
searchQuery: "",
},
},
};
expect(Object.keys(correctCall)).toContain("repositoryHandle");
expect(Object.keys(correctCall)).not.toContain("repository_handle");
});
it("nested request fields use camelCase", () => {
const correctRequest = {
trackIds: ["track-1"], // ✓ camelCase for nested struct field
startIndex: 0, // ✓ camelCase
shuffle: false,
context: {
type: "search",
searchQuery: "", // ✓ camelCase for context field
},
};
expect(Object.keys(correctRequest)).toContain("trackIds");
expect(Object.keys(correctRequest)).toContain("startIndex");
expect(Object.keys(correctRequest.context)).toContain("searchQuery");
});
});
describe("playback_mode_transfer_to_local command parameters", () => {
it("should use currentItemId and positionTicks (camelCase)", () => {
const correctCall = {
currentItemId: "item-123", // ✓ CORRECT
positionTicks: 50000, // ✓ CORRECT
};
expect(Object.keys(correctCall)).toContain("currentItemId");
expect(Object.keys(correctCall)).toContain("positionTicks");
expect(Object.keys(correctCall)).not.toContain("current_item_id");
expect(Object.keys(correctCall)).not.toContain("position_ticks");
});
});
describe("Session commands use sessionId (camelCase)", () => {
it("remote_send_command uses sessionId", () => {
const correctCall = {
sessionId: "session-123", // ✓ CORRECT
command: "PlayPause",
};
expect(Object.keys(correctCall)).toContain("sessionId");
expect(Object.keys(correctCall)).not.toContain("session_id");
});
it("remote_play_on_session uses sessionId, itemIds, startIndex", () => {
const correctCall = {
sessionId: "session-123", // ✓ CORRECT
itemIds: ["id1", "id2"], // ✓ CORRECT
startIndex: 0, // ✓ CORRECT
};
expect(Object.keys(correctCall)).toContain("sessionId");
expect(Object.keys(correctCall)).toContain("itemIds");
expect(Object.keys(correctCall)).toContain("startIndex");
expect(Object.keys(correctCall)).not.toContain("session_id");
expect(Object.keys(correctCall)).not.toContain("item_ids");
expect(Object.keys(correctCall)).not.toContain("start_index");
});
it("remote_session_seek uses sessionId and positionTicks", () => {
const correctCall = {
sessionId: "session-123", // ✓ CORRECT
positionTicks: 50000, // ✓ CORRECT
};
expect(Object.keys(correctCall)).toContain("sessionId");
expect(Object.keys(correctCall)).toContain("positionTicks");
expect(Object.keys(correctCall)).not.toContain("session_id");
expect(Object.keys(correctCall)).not.toContain("position_ticks");
});
});
describe("Download commands use itemId (camelCase)", () => {
it("pin_item uses itemId", () => {
const correctCall = {
itemId: "item-123", // ✓ CORRECT
};
expect(Object.keys(correctCall)).toContain("itemId");
expect(Object.keys(correctCall)).not.toContain("item_id");
});
it("unpin_item uses itemId", () => {
const correctCall = {
itemId: "item-123", // ✓ CORRECT
};
expect(Object.keys(correctCall)).toContain("itemId");
expect(Object.keys(correctCall)).not.toContain("item_id");
});
});
describe("Queue commands use repositoryHandle (camelCase)", () => {
it("player_add_track_by_id uses repositoryHandle", () => {
const correctCall = {
repositoryHandle: "handle-123", // ✓ CORRECT
request: {
trackId: "track-123",
position: 0,
},
};
expect(Object.keys(correctCall)).toContain("repositoryHandle");
expect(Object.keys(correctCall)).not.toContain("repository_handle");
});
it("player_add_tracks_by_ids uses repositoryHandle", () => {
const correctCall = {
repositoryHandle: "handle-123", // ✓ CORRECT
request: {
trackIds: ["track-1", "track-2"],
position: 0,
},
};
expect(Object.keys(correctCall)).toContain("repositoryHandle");
expect(Object.keys(correctCall)).not.toContain("repository_handle");
});
});
describe("Player commands", () => {
it("player_play_album_track uses repositoryHandle", () => {
const correctCall = {
repositoryHandle: "handle-123", // ✓ CORRECT
request: {
albumId: "album-123",
albumName: "Test Album",
trackId: "track-123",
shuffle: false,
},
};
expect(Object.keys(correctCall)).toContain("repositoryHandle");
expect(Object.keys(correctCall)).not.toContain("repository_handle");
// Nested struct fields use camelCase
expect(Object.keys(correctCall.request)).toContain("albumId");
expect(Object.keys(correctCall.request)).toContain("albumName");
expect(Object.keys(correctCall.request)).toContain("trackId");
});
it("player_seek uses position (simple types don't need renaming)", () => {
const correctCall = {
position: 500.5,
};
expect(correctCall.position).toBe(500.5);
});
});
describe("Error detection - what NOT to do", () => {
it("repository_handle (snake_case) is WRONG for top-level param", () => {
const wrongCall = {
repository_handle: "handle-123", // ❌ WRONG
};
expect(Object.keys(wrongCall)).not.toContain("repositoryHandle");
expect(Object.keys(wrongCall)).toContain("repository_handle");
});
it("session_id (snake_case) is WRONG for top-level param", () => {
const wrongCall = {
session_id: "session-123", // ❌ WRONG
};
expect(Object.keys(wrongCall)).not.toContain("sessionId");
expect(Object.keys(wrongCall)).toContain("session_id");
});
it("item_ids (snake_case) is WRONG for top-level param", () => {
const wrongCall = {
item_ids: ["id1", "id2"], // ❌ WRONG
};
expect(Object.keys(wrongCall)).not.toContain("itemIds");
expect(Object.keys(wrongCall)).toContain("item_ids");
});
it("start_index (snake_case) is WRONG for top-level param", () => {
const wrongCall = {
start_index: 0, // ❌ WRONG
};
expect(Object.keys(wrongCall)).not.toContain("startIndex");
expect(Object.keys(wrongCall)).toContain("start_index");
});
});
});

View File

@ -10,7 +10,7 @@
*/
import { writable, get, derived } from "svelte/store";
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import { sessions, selectedSession } from "./sessions";
import { auth } from "./auth";
import { ticksToSeconds } from "$lib/utils/playbackUnits";
@ -47,7 +47,7 @@ function createPlaybackModeStore() {
*/
async function refreshMode(): Promise<void> {
try {
const rustMode = await invoke<RustPlaybackMode>("playback_mode_get_current");
const rustMode = (await commands.playbackModeGetCurrent()) as RustPlaybackMode;
update((s) => ({
...s,
@ -91,7 +91,7 @@ function createPlaybackModeStore() {
// Rust handles everything - just wait for it to complete
// It includes its own 5-second timeout for track loading
console.log("[PlaybackMode] About to invoke playback_mode_transfer_to_remote with sessionId:", sessionId);
await invoke("playback_mode_transfer_to_remote", { sessionId });
await commands.playbackModeTransferToRemote(sessionId ?? "");
console.log("[PlaybackMode] Invoke completed successfully");
if (aborted) {
@ -192,16 +192,13 @@ function createPlaybackModeStore() {
// Use player_play_tracks - backend fetches all metadata from single ID
const repositoryHandle = repository.getHandle();
await invoke("player_play_tracks", {
repositoryHandle,
request: {
trackIds: [itemId],
startIndex: 0,
shuffle: false,
context: {
type: "search",
searchQuery: "",
},
await commands.playerPlayTracks(repositoryHandle, {
trackIds: [itemId],
startIndex: 0,
shuffle: false,
context: {
type: "search",
searchQuery: "",
},
});
@ -212,16 +209,13 @@ function createPlaybackModeStore() {
// Seek to position if not at the very start
if (positionSeconds > 0.5) {
await invoke("player_seek", { position: positionSeconds });
await commands.playerSeek(positionSeconds);
}
if (aborted) return;
// Let Rust handle stopping remote playback
await invoke("playback_mode_transfer_to_local", {
currentItemId: itemId,
positionTicks,
});
await commands.playbackModeTransferToLocal(itemId, positionTicks);
if (aborted) return;
@ -328,7 +322,7 @@ function createPlaybackModeStore() {
try {
// Notify Rust backend to switch to idle mode
await invoke("playback_mode_set", { mode: { type: "idle" } });
await commands.playbackModeSet({ type: "idle" });
// Update local state
sessions.selectSession(null);

View File

@ -7,8 +7,8 @@
// TRACES: UR-005, UR-015 | DR-005, DR-020
import { writable, derived, get } from "svelte/store";
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { commands } from "$lib/api/bindings";
import type { MediaItem } from "$lib/api/types";
import { auth } from "$lib/stores/auth";
@ -72,7 +72,7 @@ function createQueueStore() {
*/
async function syncFromRust(): Promise<void> {
try {
const rustQueue = await invoke<QueueChangedEvent>("player_get_queue");
const rustQueue = (await commands.playerGetQueue()) as unknown as QueueChangedEvent;
console.log("[Queue] Synced from Rust - items:", rustQueue.items.length);
set({
items: rustQueue.items,
@ -105,37 +105,37 @@ function createQueueStore() {
// TRACES: UR-005, UR-015 | DR-005
async function next() {
await invoke("player_next");
await commands.playerNext();
}
// TRACES: UR-005, UR-015 | DR-005
async function previous() {
await invoke("player_previous");
await commands.playerPrevious();
}
// TRACES: UR-005, UR-015 | DR-005, DR-020
async function skipTo(index: number) {
await invoke("player_skip_to", { index });
await commands.playerSkipTo(index);
}
// TRACES: UR-005, UR-015 | DR-005
async function toggleShuffle() {
await invoke("player_toggle_shuffle");
await commands.playerToggleShuffle();
}
// TRACES: UR-005, UR-015 | DR-005
async function cycleRepeat() {
await invoke("player_cycle_repeat");
await commands.playerCycleRepeat();
}
// TRACES: UR-015 | DR-020
async function removeFromQueue(index: number) {
await invoke("player_remove_from_queue", { index });
await commands.playerRemoveFromQueue(index);
}
// TRACES: UR-015 | DR-020
async function moveInQueue(fromIndex: number, toIndex: number) {
await invoke("player_move_in_queue", { fromIndex, toIndex });
await commands.playerMoveInQueue(fromIndex, toIndex);
}
// TRACES: UR-015 | DR-020
@ -152,20 +152,14 @@ function createQueueStore() {
// Use new Rust commands that accept IDs only
if (trackIds.length === 1) {
await invoke("player_add_track_by_id", {
repositoryHandle,
request: {
trackId: trackIds[0],
position,
},
await commands.playerAddTrackById(repositoryHandle, {
trackId: trackIds[0],
position,
});
} else {
await invoke("player_add_tracks_by_ids", {
repositoryHandle,
request: {
trackIds,
position,
},
await commands.playerAddTracksByIds(repositoryHandle, {
trackIds,
position,
});
}
}

View File

@ -2,8 +2,8 @@
// TRACES: UR-010 | DR-037
import { writable, derived } from "svelte/store";
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { commands } from "$lib/api/bindings";
import type { Session } from "$lib/api/types";
interface SessionsState {
@ -53,7 +53,7 @@ function createSessionsStore() {
try {
update((s) => ({ ...s, isLoading: true, error: null }));
const sessions = await invoke<Session[]>("sessions_poll_now");
const sessions = await commands.sessionsPollNow();
console.log(`[Sessions] Manual refresh returned ${sessions.length} sessions`);
sessions.forEach((s, i) => {
@ -91,10 +91,7 @@ function createSessionsStore() {
*/
async function sendPlayPause(sessionId: string | null | undefined): Promise<void> {
try {
await invoke("remote_send_command", {
sessionId,
command: "PlayPause",
});
await commands.remoteSendCommand(sessionId ?? "", "PlayPause");
// Refresh after command to get updated state
await refresh();
} catch (error) {
@ -108,10 +105,7 @@ function createSessionsStore() {
*/
async function sendStop(sessionId: string | null | undefined): Promise<void> {
try {
await invoke("remote_send_command", {
sessionId,
command: "Stop",
});
await commands.remoteSendCommand(sessionId ?? "", "Stop");
await refresh();
} catch (error) {
console.error("Failed to send stop command:", error);
@ -124,10 +118,7 @@ function createSessionsStore() {
*/
async function sendNext(sessionId: string | null | undefined): Promise<void> {
try {
await invoke("remote_send_command", {
sessionId,
command: "NextTrack",
});
await commands.remoteSendCommand(sessionId ?? "", "NextTrack");
await refresh();
} catch (error) {
console.error("Failed to send next track command:", error);
@ -140,10 +131,7 @@ function createSessionsStore() {
*/
async function sendPrevious(sessionId: string | null | undefined): Promise<void> {
try {
await invoke("remote_send_command", {
sessionId,
command: "PreviousTrack",
});
await commands.remoteSendCommand(sessionId ?? "", "PreviousTrack");
await refresh();
} catch (error) {
console.error("Failed to send previous track command:", error);
@ -156,10 +144,7 @@ function createSessionsStore() {
*/
async function sendSeek(sessionId: string | null | undefined, positionTicks: number): Promise<void> {
try {
await invoke("remote_session_seek", {
sessionId,
positionTicks,
});
await commands.remoteSessionSeek(sessionId ?? "", positionTicks);
// Don't refresh immediately for seek to avoid UI lag
} catch (error) {
console.error("Failed to send seek command:", error);
@ -172,10 +157,7 @@ function createSessionsStore() {
*/
async function sendVolume(sessionId: string | null | undefined, volume: number): Promise<void> {
try {
await invoke("remote_session_set_volume", {
sessionId,
volume,
});
await commands.remoteSessionSetVolume(sessionId ?? "", volume);
// Don't refresh immediately for volume to avoid UI lag
} catch (error) {
console.error("Failed to send volume command:", error);
@ -188,10 +170,7 @@ function createSessionsStore() {
*/
async function sendToggleMute(sessionId: string | null | undefined): Promise<void> {
try {
await invoke("remote_send_command", {
sessionId,
command: "ToggleMute",
});
await commands.remoteSendCommand(sessionId ?? "", "ToggleMute");
await refresh();
} catch (error) {
console.error("Failed to toggle mute:", error);
@ -213,14 +192,10 @@ function createSessionsStore() {
console.log("[SESSIONS] itemIds.length:", itemIds.length);
console.log("[SESSIONS] itemIds JSON:", JSON.stringify(itemIds));
console.log("[SESSIONS] startIndex:", startIndex);
console.log("[SESSIONS] About to call invoke('remote_play_on_session')");
console.log("[SESSIONS] About to call commands.remotePlayOnSession");
try {
// Use Rust player's Jellyfin client for remote playback
const result = await invoke("remote_play_on_session", {
sessionId,
itemIds,
startIndex,
});
const result = await commands.remotePlayOnSession(sessionId ?? "", itemIds, startIndex);
console.log("[SESSIONS] invoke succeeded, result:", result);
await refresh();
} catch (error) {

View File

@ -11,7 +11,7 @@
*/
import { writable, derived } from "svelte/store";
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
export type SleepTimerMode =
| { kind: "off" }
@ -39,25 +39,19 @@ function createSleepTimerStore() {
// Methods that invoke the backend API
async setTimeTimer(minutes: number): Promise<void> {
const endTime = Date.now() + minutes * 60 * 1000;
await invoke("player_set_sleep_timer", {
mode: { kind: "time", endTime },
});
await commands.playerSetSleepTimer({ kind: "time", endTime });
},
async setEndOfTrackTimer(): Promise<void> {
await invoke("player_set_sleep_timer", {
mode: { kind: "endOfTrack" },
});
await commands.playerSetSleepTimer({ kind: "endOfTrack" });
},
async setEpisodesTimer(count: number): Promise<void> {
await invoke("player_set_sleep_timer", {
mode: { kind: "episodes", remaining: count },
});
await commands.playerSetSleepTimer({ kind: "episodes", remaining: count });
},
async cancel(): Promise<void> {
await invoke("player_cancel_sleep_timer");
await commands.playerCancelSleepTimer();
},
};
}

View File

@ -1,255 +0,0 @@
/**
* Unit tests for Tauri command parameter names
*
* CRITICAL: Tauri v2's #[tauri::command] macro automatically converts
* snake_case Rust parameter names to camelCase for the frontend.
* ALL parameters (top-level and nested) use camelCase on the frontend side.
*
* @see https://v2.tauri.app/develop/calling-rust/
*/
import { describe, it, expect } from 'vitest';
describe("Tauri Command Parameter Names - Critical Pattern Test", () => {
describe("All command parameters use camelCase (Tauri v2 auto-converts)", () => {
it("player_play_tracks: repositoryHandle (NOT repository_handle)", () => {
const params = {
repositoryHandle: "handle-123",
request: {
trackIds: ["id1"],
startIndex: 0,
shuffle: false,
context: { type: "search", searchQuery: "test" }
}
};
expect(Object.keys(params)).toContain("repositoryHandle");
expect(Object.keys(params)).not.toContain("repository_handle");
expect(params.repositoryHandle).toBe("handle-123");
});
it("playback_mode_transfer_to_local: currentItemId & positionTicks", () => {
const params = {
currentItemId: "item-123",
positionTicks: 50000
};
expect(Object.keys(params)).toContain("currentItemId");
expect(Object.keys(params)).toContain("positionTicks");
expect(Object.keys(params)).not.toContain("current_item_id");
expect(Object.keys(params)).not.toContain("position_ticks");
});
it("pin_item/unpin_item: itemId (NOT item_id)", () => {
const params = { itemId: "id-123" };
expect(Object.keys(params)).toContain("itemId");
expect(Object.keys(params)).not.toContain("item_id");
});
it("remote_send_command: sessionId (NOT session_id)", () => {
const params = {
sessionId: "session-123",
command: "PlayPause"
};
expect(Object.keys(params)).toContain("sessionId");
expect(Object.keys(params)).not.toContain("session_id");
});
it("remote_play_on_session: sessionId, itemIds, startIndex", () => {
const params = {
sessionId: "session-123",
itemIds: ["id1", "id2"],
startIndex: 0
};
expect(Object.keys(params)).toContain("sessionId");
expect(Object.keys(params)).toContain("itemIds");
expect(Object.keys(params)).toContain("startIndex");
expect(Object.keys(params)).not.toContain("session_id");
expect(Object.keys(params)).not.toContain("item_ids");
expect(Object.keys(params)).not.toContain("start_index");
});
it("remote_session_seek: sessionId & positionTicks", () => {
const params = {
sessionId: "session-123",
positionTicks: 50000
};
expect(Object.keys(params)).toContain("sessionId");
expect(Object.keys(params)).toContain("positionTicks");
expect(Object.keys(params)).not.toContain("session_id");
expect(Object.keys(params)).not.toContain("position_ticks");
});
it("player_add_track_by_id: repositoryHandle", () => {
const params = {
repositoryHandle: "handle-123",
request: {
trackId: "id1",
position: 0
}
};
expect(Object.keys(params)).toContain("repositoryHandle");
expect(Object.keys(params)).not.toContain("repository_handle");
});
it("player_add_tracks_by_ids: repositoryHandle", () => {
const params = {
repositoryHandle: "handle-123",
request: {
trackIds: ["id1", "id2"],
position: 0
}
};
expect(Object.keys(params)).toContain("repositoryHandle");
expect(Object.keys(params)).not.toContain("repository_handle");
});
it("player_play_album_track: repositoryHandle", () => {
const params = {
repositoryHandle: "handle-123",
request: {
albumId: "album-123",
albumName: "Test Album",
trackId: "track-123",
shuffle: false
}
};
expect(Object.keys(params)).toContain("repositoryHandle");
expect(Object.keys(params)).not.toContain("repository_handle");
});
it("playlist_create: handle, name, itemIds (NOT item_ids)", () => {
const params = {
handle: "handle-123",
name: "My Playlist",
itemIds: ["track1", "track2"],
};
expect(Object.keys(params)).toContain("itemIds");
expect(Object.keys(params)).not.toContain("item_ids");
});
it("playlist_get_items: handle, playlistId (NOT playlist_id)", () => {
const params = {
handle: "handle-123",
playlistId: "pl-123",
};
expect(Object.keys(params)).toContain("playlistId");
expect(Object.keys(params)).not.toContain("playlist_id");
});
it("playlist_add_items: playlistId, itemIds", () => {
const params = {
handle: "handle-123",
playlistId: "pl-123",
itemIds: ["t1", "t2"],
};
expect(Object.keys(params)).toContain("playlistId");
expect(Object.keys(params)).toContain("itemIds");
expect(Object.keys(params)).not.toContain("playlist_id");
expect(Object.keys(params)).not.toContain("item_ids");
});
it("playlist_remove_items: playlistId, entryIds (NOT entry_ids)", () => {
const params = {
handle: "handle-123",
playlistId: "pl-123",
entryIds: ["e1", "e2"],
};
expect(Object.keys(params)).toContain("entryIds");
expect(Object.keys(params)).not.toContain("entry_ids");
});
it("playlist_move_item: playlistId, itemId, newIndex (NOT new_index)", () => {
const params = {
handle: "handle-123",
playlistId: "pl-123",
itemId: "track1",
newIndex: 2,
};
expect(Object.keys(params)).toContain("newIndex");
expect(Object.keys(params)).toContain("itemId");
expect(Object.keys(params)).not.toContain("new_index");
expect(Object.keys(params)).not.toContain("item_id");
});
});
describe("Nested struct fields also use camelCase (via serde rename_all)", () => {
it("PlayTracksRequest with #[serde(rename_all = camelCase)]", () => {
const request = {
trackIds: ["id1"],
startIndex: 0,
shuffle: false,
context: {
type: "search",
searchQuery: "test query"
}
};
expect(Object.keys(request)).toContain("trackIds");
expect(Object.keys(request)).toContain("startIndex");
expect(request.context.searchQuery).toBe("test query");
});
it("PlayAlbumTrackRequest with #[serde(rename_all = camelCase)]", () => {
const request = {
albumId: "album-123",
albumName: "Test Album",
trackId: "track-123",
shuffle: false
};
expect(Object.keys(request)).toContain("albumId");
expect(Object.keys(request)).toContain("albumName");
expect(Object.keys(request)).toContain("trackId");
});
it("PlayTracksContext variants with correct field names", () => {
const searchContext = {
type: "search",
searchQuery: "test"
};
const playlistContext = {
type: "playlist",
playlistId: "pl-123",
playlistName: "My Playlist"
};
const customContext = {
type: "custom",
label: "Custom Queue"
};
expect(searchContext.searchQuery).toBe("test");
expect(playlistContext.playlistId).toBe("pl-123");
expect(playlistContext.playlistName).toBe("My Playlist");
expect(customContext.label).toBe("Custom Queue");
});
});
describe("Error cases - what NOT to do", () => {
it("WRONG: snake_case top-level params will fail", () => {
// ❌ This will cause "invalid args request" error
const wrongParams = {
repository_handle: "handle-123", // ❌ WRONG - should be repositoryHandle
session_id: "session-123", // ❌ WRONG - should be sessionId
item_ids: ["id1"] // ❌ WRONG - should be itemIds
};
// Verify we understand what's wrong
expect(Object.keys(wrongParams)).not.toContain("repositoryHandle");
expect(Object.keys(wrongParams)).toContain("repository_handle");
});
});
});

View File

@ -1,387 +0,0 @@
/**
* Integration test: Tauri command invocations
*
* This test validates that invoke parameters use the correct naming convention.
*
* IMPORTANT: Tauri v2's #[tauri::command] macro automatically converts
* snake_case Rust parameter names to camelCase for the frontend.
* All top-level parameters must use camelCase.
*
* RUN THIS BEFORE DEPLOYING:
* ```bash
* npm test -- tauriIntegration.test.ts
* ```
*/
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
/**
* Mock Tauri invoke to capture actual calls from production code
*/
interface InvokeCall {
command: string;
args: Record<string, any>;
timestamp: number;
}
let invokeHistory: InvokeCall[] = [];
let invokeErrors: Map<string, Error> = new Map();
const mockInvoke = vi.fn(async (command: string, args?: Record<string, any>) => {
const callArgs = args || {};
invokeHistory.push({
command,
args: callArgs,
timestamp: Date.now(),
});
// Check if this command should error
const error = invokeErrors.get(command);
if (error) {
throw error;
}
// Simulate Tauri command success
return { success: true };
});
/**
* Expected command signatures - the source of truth
* All parameter names are camelCase (Tauri v2 auto-converts from Rust snake_case)
*/
const COMMAND_SPECS: Record<
string,
{
requiredParams: string[];
description: string;
}
> = {
player_play_tracks: {
requiredParams: ["repositoryHandle", "request"],
description: "Play a set of tracks",
},
playback_mode_set: {
requiredParams: ["mode"],
description: "Set playback mode",
},
playback_mode_transfer_to_local: {
requiredParams: ["currentItemId", "positionTicks"],
description: "Transfer playback to local device",
},
remote_send_command: {
requiredParams: ["sessionId", "command"],
description: "Send command to remote session",
},
remote_play_on_session: {
requiredParams: ["sessionId", "itemIds", "startIndex"],
description: "Play items on remote session",
},
remote_session_seek: {
requiredParams: ["sessionId", "positionTicks"],
description: "Seek on remote session",
},
pin_item: {
requiredParams: ["itemId"],
description: "Pin an item for download",
},
unpin_item: {
requiredParams: ["itemId"],
description: "Unpin an item",
},
player_add_track_by_id: {
requiredParams: ["repositoryHandle", "request"],
description: "Add track to queue by ID",
},
player_add_tracks_by_ids: {
requiredParams: ["repositoryHandle", "request"],
description: "Add tracks to queue by IDs",
},
player_play_album_track: {
requiredParams: ["repositoryHandle", "request"],
description: "Play track from album",
},
};
/**
* Validate an invoke call against the spec
*/
function validateInvokeCall(call: InvokeCall): { valid: boolean; errors: string[] } {
const errors: string[] = [];
const spec = COMMAND_SPECS[call.command];
if (!spec) {
errors.push(`Unknown command: ${call.command}`);
return { valid: errors.length === 0, errors };
}
// Check all required parameters are present
for (const paramName of spec.requiredParams) {
if (!(paramName in call.args)) {
errors.push(
`Missing required parameter "${paramName}" for ${call.command}`
);
}
}
// Check for snake_case violations (should be camelCase)
const snakeCaseViolations: Record<string, string> = {
repository_handle: "repositoryHandle",
current_item_id: "currentItemId",
position_ticks: "positionTicks",
session_id: "sessionId",
item_ids: "itemIds",
start_index: "startIndex",
item_id: "itemId",
};
for (const [snakeCase, camelCase] of Object.entries(snakeCaseViolations)) {
if (snakeCase in call.args) {
errors.push(
`Found snake_case "${snakeCase}" instead of "${camelCase}" for ${call.command}`
);
}
}
return {
valid: errors.length === 0,
errors,
};
}
describe("Tauri Integration - Command Invocations", () => {
beforeEach(() => {
invokeHistory = [];
invokeErrors.clear();
// Mock Tauri invoke in the context where it will be imported
vi.doMock("@tauri-apps/api/core", () => ({
invoke: mockInvoke,
}));
});
afterEach(() => {
vi.clearAllMocks();
invokeHistory = [];
invokeErrors.clear();
});
describe("playbackMode store", () => {
it("should invoke player_play_tracks with correct parameter names", async () => {
await mockInvoke("player_play_tracks", {
repositoryHandle: "test-repo",
request: {
trackIds: ["id1", "id2"],
startIndex: 0,
shuffle: false,
context: {
type: "search",
searchQuery: "test",
},
},
});
const lastCall = invokeHistory[invokeHistory.length - 1];
const validation = validateInvokeCall(lastCall);
if (!validation.valid) {
throw new Error(
`player_play_tracks invocation failed validation:\n${validation.errors.join("\n")}`
);
}
// Verify the actual parameters
expect(lastCall.command).toBe("player_play_tracks");
expect(lastCall.args).toHaveProperty("repositoryHandle");
expect(lastCall.args.repositoryHandle).toBe("test-repo");
expect(lastCall.args.request).toHaveProperty("trackIds");
expect(lastCall.args.request).toHaveProperty("context");
expect(lastCall.args.request.context).toHaveProperty("searchQuery");
});
it("should NOT use repository_handle - must be repositoryHandle", async () => {
// This test documents the WRONG way
const wrongCall: InvokeCall = {
command: "player_play_tracks",
args: {
repository_handle: "test-repo", // ❌ WRONG - snake_case
request: {},
},
timestamp: Date.now(),
};
const validation = validateInvokeCall(wrongCall);
// This should fail because the parameter name is wrong
expect(validation.valid).toBe(false);
expect(validation.errors.some((e) => e.includes("repository_handle"))).toBe(true);
});
it("should invoke playback_mode_transfer_to_local with correct parameters", async () => {
await mockInvoke("playback_mode_transfer_to_local", {
currentItemId: "item-123",
positionTicks: 50000,
});
const lastCall = invokeHistory[invokeHistory.length - 1];
const validation = validateInvokeCall(lastCall);
expect(validation.valid).toBe(true);
expect(lastCall.args).toHaveProperty("currentItemId");
expect(lastCall.args).toHaveProperty("positionTicks");
});
});
describe("sessions store", () => {
it("should invoke remote_send_command with sessionId parameter", async () => {
await mockInvoke("remote_send_command", {
sessionId: "session-123", // ✓ Correct
command: "PlayPause",
});
const lastCall = invokeHistory[invokeHistory.length - 1];
const validation = validateInvokeCall(lastCall);
expect(validation.valid).toBe(true);
expect(lastCall.args).toHaveProperty("sessionId");
expect(lastCall.args).not.toHaveProperty("session_id");
});
it("should NOT use session_id - must be sessionId", async () => {
const wrongCall: InvokeCall = {
command: "remote_send_command",
args: {
session_id: "session-123", // ❌ WRONG
command: "PlayPause",
},
timestamp: Date.now(),
};
const validation = validateInvokeCall(wrongCall);
expect(validation.valid).toBe(false);
});
it("should invoke remote_play_on_session with correct parameters", async () => {
await mockInvoke("remote_play_on_session", {
sessionId: "session-123",
itemIds: ["id1", "id2"],
startIndex: 0,
});
const lastCall = invokeHistory[invokeHistory.length - 1];
const validation = validateInvokeCall(lastCall);
expect(validation.valid).toBe(true);
expect(lastCall.args).toHaveProperty("sessionId");
expect(lastCall.args).toHaveProperty("itemIds");
expect(lastCall.args).toHaveProperty("startIndex");
});
});
describe("downloads store", () => {
it("should invoke pin_item with itemId parameter", async () => {
await mockInvoke("pin_item", {
itemId: "item-123", // ✓ Correct
});
const lastCall = invokeHistory[invokeHistory.length - 1];
const validation = validateInvokeCall(lastCall);
expect(validation.valid).toBe(true);
expect(lastCall.args).toHaveProperty("itemId");
});
it("should NOT use item_id - must be itemId", async () => {
const wrongCall: InvokeCall = {
command: "pin_item",
args: {
item_id: "item-123", // ❌ WRONG
},
timestamp: Date.now(),
};
const validation = validateInvokeCall(wrongCall);
expect(validation.valid).toBe(false);
});
});
describe("queue store", () => {
it("should invoke player_add_track_by_id with repositoryHandle", async () => {
await mockInvoke("player_add_track_by_id", {
repositoryHandle: "repo-123",
request: {
trackId: "track-123",
position: 0,
},
});
const lastCall = invokeHistory[invokeHistory.length - 1];
const validation = validateInvokeCall(lastCall);
expect(validation.valid).toBe(true);
expect(lastCall.args).toHaveProperty("repositoryHandle");
});
it("should invoke player_play_album_track with correct parameters", async () => {
await mockInvoke("player_play_album_track", {
repositoryHandle: "repo-123",
request: {
albumId: "album-123",
albumName: "Test Album",
trackId: "track-123",
shuffle: false,
},
});
const lastCall = invokeHistory[invokeHistory.length - 1];
const validation = validateInvokeCall(lastCall);
expect(validation.valid).toBe(true);
expect(lastCall.args.request).toHaveProperty("albumId");
expect(lastCall.args.request).toHaveProperty("albumName");
expect(lastCall.args.request).toHaveProperty("trackId");
});
});
describe("Comprehensive validation", () => {
it("should validate all recorded invoke calls", async () => {
// Simulate multiple invoke calls from different parts of the app
await mockInvoke("player_play_tracks", {
repositoryHandle: "repo1",
request: { trackIds: ["1"], startIndex: 0, shuffle: false, context: { type: "search", searchQuery: "" } },
});
await mockInvoke("pin_item", {
itemId: "item1",
});
await mockInvoke("remote_send_command", {
sessionId: "session1",
command: "PlayPause",
});
// Validate ALL calls
const validationResults = invokeHistory.map((call) => ({
command: call.command,
validation: validateInvokeCall(call),
}));
const failures = validationResults.filter((r) => !r.validation.valid);
if (failures.length > 0) {
const errorMessages = failures
.map(
(f) =>
`${f.command}: ${f.validation.errors.join("; ")}`
)
.join("\n");
throw new Error(
`Found ${failures.length} invalid invoke calls:\n${errorMessages}`
);
}
expect(failures).toHaveLength(0);
expect(invokeHistory).toHaveLength(3);
});
});
});

View File

@ -1,348 +0,0 @@
/**
* Debug test - Simulate actual Tauri invoke calls locally
*
* This test validates Tauri command invocations to catch
* "invalid args request" errors before they hit the Android app.
*
* IMPORTANT: Tauri v2's #[tauri::command] macro automatically converts
* snake_case Rust parameter names to camelCase for the frontend.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
// Mock implementation that validates JSON structure
const createDebugInvoke = () => {
const calls: Array<{ command: string; args: Record<string, any>; json: string }> = [];
const invoke = async (command: string, args?: Record<string, any>) => {
const argsToSend = args || {};
const json = JSON.stringify(argsToSend);
console.log(`[INVOKE] ${command}`);
console.log(`[JSON] ${json}`);
calls.push({ command, args: argsToSend, json });
// Validate parameter names match what Tauri v2 expects (camelCase)
validateCommandParameters(command, argsToSend);
return { success: true };
};
const validateCommandParameters = (command: string, args: Record<string, any>) => {
const paramNames = Object.keys(args);
// Check for snake_case violations (Tauri v2 expects camelCase)
const snakeCaseViolations: Record<string, string> = {
repository_handle: "repositoryHandle",
current_item_id: "currentItemId",
position_ticks: "positionTicks",
session_id: "sessionId",
item_id: "itemId",
item_ids: "itemIds",
start_index: "startIndex",
};
for (const [snakeCase, camelCase] of Object.entries(snakeCaseViolations)) {
if (paramNames.includes(snakeCase)) {
throw new Error(
`[VALIDATION ERROR] ${command} has "${snakeCase}" (snake_case)\n` +
`Should be "${camelCase}" (camelCase)\n` +
`Tauri v2 auto-converts Rust snake_case to camelCase for the frontend!`
);
}
}
switch (command) {
case "player_play_tracks":
if (!paramNames.includes("repositoryHandle")) {
throw new Error(
`[VALIDATION ERROR] player_play_tracks missing "repositoryHandle"\n` +
`Found: ${paramNames.join(", ")}\n` +
`This will cause "invalid args request" error on Android!`
);
}
break;
case "playback_mode_transfer_to_local":
if (!paramNames.includes("currentItemId")) {
throw new Error(
`[VALIDATION ERROR] playback_mode_transfer_to_local missing "currentItemId"\n` +
`Found: ${paramNames.join(", ")}\n` +
`This will cause "invalid args request" error on Android!`
);
}
if (!paramNames.includes("positionTicks")) {
throw new Error(
`[VALIDATION ERROR] playback_mode_transfer_to_local missing "positionTicks"\n` +
`Found: ${paramNames.join(", ")}\n` +
`This will cause "invalid args request" error on Android!`
);
}
break;
case "pin_item":
case "unpin_item":
if (!paramNames.includes("itemId")) {
throw new Error(
`[VALIDATION ERROR] ${command} missing "itemId"\n` +
`Found: ${paramNames.join(", ")}\n` +
`This will cause "invalid args request" error on Android!`
);
}
break;
case "remote_send_command":
if (!paramNames.includes("sessionId")) {
throw new Error(
`[VALIDATION ERROR] remote_send_command missing "sessionId"\n` +
`Found: ${paramNames.join(", ")}\n` +
`This will cause "invalid args request" error on Android!`
);
}
break;
case "remote_play_on_session":
if (!paramNames.includes("sessionId")) {
throw new Error(
`[VALIDATION ERROR] remote_play_on_session missing "sessionId"`
);
}
if (!paramNames.includes("itemIds")) {
throw new Error(
`[VALIDATION ERROR] remote_play_on_session missing "itemIds"`
);
}
if (!paramNames.includes("startIndex")) {
throw new Error(
`[VALIDATION ERROR] remote_play_on_session missing "startIndex"`
);
}
break;
case "remote_session_seek":
if (!paramNames.includes("sessionId")) {
throw new Error(
`[VALIDATION ERROR] remote_session_seek missing "sessionId"`
);
}
if (!paramNames.includes("positionTicks")) {
throw new Error(
`[VALIDATION ERROR] remote_session_seek missing "positionTicks"`
);
}
break;
case "player_add_track_by_id":
case "player_add_tracks_by_ids":
case "player_play_album_track":
if (!paramNames.includes("repositoryHandle")) {
throw new Error(
`[VALIDATION ERROR] ${command} missing "repositoryHandle"`
);
}
break;
}
};
return { invoke, getCalls: () => calls };
};
describe("Tauri Invoke Debug - Catch Android 'invalid args request' errors", () => {
let debugInvoke: Awaited<ReturnType<typeof createDebugInvoke>>;
beforeEach(() => {
debugInvoke = createDebugInvoke();
});
describe("Parameter validation - exact Android behavior", () => {
it("player_play_tracks with CORRECT parameters passes validation", async () => {
const { invoke } = debugInvoke;
await expect(
invoke("player_play_tracks", {
repositoryHandle: "test-handle", // ✓ CORRECT
request: {
trackIds: ["id1"],
startIndex: 0,
shuffle: false,
context: { type: "search", searchQuery: "" },
},
})
).resolves.toEqual({ success: true });
});
it("player_play_tracks with WRONG repository_handle throws validation error", async () => {
const { invoke } = debugInvoke;
await expect(
invoke("player_play_tracks", {
repository_handle: "test-handle", // ❌ WRONG - snake_case
request: {},
})
).rejects.toThrow(/snake_case/);
});
it("playback_mode_transfer_to_local with CORRECT parameters passes validation", async () => {
const { invoke } = debugInvoke;
await expect(
invoke("playback_mode_transfer_to_local", {
currentItemId: "item-123", // ✓ CORRECT
positionTicks: 50000, // ✓ CORRECT
})
).resolves.toEqual({ success: true });
});
it("playback_mode_transfer_to_local with snake_case throws error", async () => {
const { invoke } = debugInvoke;
await expect(
invoke("playback_mode_transfer_to_local", {
current_item_id: "item-123", // ❌ WRONG
position_ticks: 50000, // ❌ WRONG
})
).rejects.toThrow(/snake_case/);
});
it("pin_item with CORRECT itemId passes", async () => {
const { invoke } = debugInvoke;
await expect(
invoke("pin_item", {
itemId: "id-123", // ✓ CORRECT
})
).resolves.toEqual({ success: true });
});
it("pin_item with snake_case item_id throws error", async () => {
const { invoke } = debugInvoke;
await expect(
invoke("pin_item", {
item_id: "id-123", // ❌ WRONG
})
).rejects.toThrow(/snake_case/);
});
it("remote_send_command with CORRECT sessionId passes", async () => {
const { invoke } = debugInvoke;
await expect(
invoke("remote_send_command", {
sessionId: "session-123", // ✓ CORRECT
command: "PlayPause",
})
).resolves.toEqual({ success: true });
});
it("remote_send_command with snake_case session_id throws error", async () => {
const { invoke } = debugInvoke;
await expect(
invoke("remote_send_command", {
session_id: "session-123", // ❌ WRONG
command: "PlayPause",
})
).rejects.toThrow(/snake_case/);
});
it("remote_play_on_session with all CORRECT parameters passes", async () => {
const { invoke } = debugInvoke;
await expect(
invoke("remote_play_on_session", {
sessionId: "session-123", // ✓ CORRECT
itemIds: ["id1", "id2"], // ✓ CORRECT
startIndex: 0, // ✓ CORRECT
})
).resolves.toEqual({ success: true });
});
it("remote_session_seek with CORRECT parameters passes", async () => {
const { invoke } = debugInvoke;
await expect(
invoke("remote_session_seek", {
sessionId: "session-123", // ✓ CORRECT
positionTicks: 50000, // ✓ CORRECT
})
).resolves.toEqual({ success: true });
});
it("player_add_track_by_id with CORRECT repositoryHandle passes", async () => {
const { invoke } = debugInvoke;
await expect(
invoke("player_add_track_by_id", {
repositoryHandle: "handle-123", // ✓ CORRECT
request: { trackId: "id1", position: 0 },
})
).resolves.toEqual({ success: true });
});
it("player_play_album_track with CORRECT repositoryHandle passes", async () => {
const { invoke } = debugInvoke;
await expect(
invoke("player_play_album_track", {
repositoryHandle: "handle-123", // ✓ CORRECT
request: {
albumId: "album-123",
albumName: "Test",
trackId: "track-123",
shuffle: false,
},
})
).resolves.toEqual({ success: true });
});
});
describe("Track all invoke calls", () => {
it("records all invoke calls for debugging", async () => {
const { invoke, getCalls } = debugInvoke;
await invoke("player_play_tracks", {
repositoryHandle: "h1",
request: {},
});
await invoke("pin_item", {
itemId: "id1",
});
const calls = getCalls();
expect(calls).toHaveLength(2);
expect(calls[0].command).toBe("player_play_tracks");
expect(calls[1].command).toBe("pin_item");
// Each call should have valid JSON
calls.forEach((call) => {
expect(() => JSON.parse(call.json)).not.toThrow();
});
});
});
describe("Detailed error messages for debugging", () => {
it("provides clear error when parameter is missing", async () => {
const { invoke } = debugInvoke;
await expect(
invoke("player_play_tracks", {
request: {}, // Missing repositoryHandle
})
).rejects.toThrow(/missing "repositoryHandle"/);
});
it("detects snake_case and suggests camelCase fix", async () => {
const { invoke } = debugInvoke;
await expect(
invoke("player_play_tracks", {
repository_handle: "h1", // Wrong!
request: {},
})
).rejects.toThrow(/snake_case/);
});
});
});

View File

@ -1,107 +0,0 @@
/**
* Test real Tauri invoke calls from production stores
*
* This test imports the actual production code and validates
* that it's sending the correct parameter names to Tauri.
* It catches real bugs that would fail on Android.
*
* IMPORTANT: Tauri v2's #[tauri::command] macro automatically converts
* snake_case Rust parameter names to camelCase for the frontend.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
let capturedInvokes: Array<{ command: string; args: Record<string, any> }> = [];
// Mock Tauri BEFORE importing stores
const mockInvoke = vi.fn(async (command: string, args?: Record<string, any>) => {
capturedInvokes.push({ command, args: args || {} });
return { success: true };
});
vi.mock("@tauri-apps/api/core", () => ({
invoke: mockInvoke,
}));
describe("Real production code - Tauri invoke calls", () => {
beforeEach(() => {
capturedInvokes = [];
vi.clearAllMocks();
});
describe("playbackMode store - real calls", () => {
it("playbackMode store should be importable and defined", async () => {
const { playbackMode } = await import("../stores/playbackMode");
try {
expect(playbackMode).toBeDefined();
expect(playbackMode.subscribe).toBeDefined();
} catch (e) {
// Store might have dependencies we can't mock, but at least we tried
}
});
});
describe("sessions store - real calls", () => {
it("should send sessionId, NOT session_id", async () => {
const { sessions } = await import("../stores/sessions");
try {
expect(sessions).toBeDefined();
expect(sessions.sendPlayPause).toBeDefined();
} catch (e) {
// Store might have dependencies we can't mock
}
});
});
describe("downloads store - real calls", () => {
it("should send itemId, NOT item_id", async () => {
const { downloads } = await import("../stores/downloads");
try {
expect(downloads).toBeDefined();
expect(downloads.pinItem).toBeDefined();
expect(downloads.unpinItem).toBeDefined();
} catch (e) {
// Store might have dependencies
}
});
});
describe("captured invoke calls validation", () => {
it("validates all captured invokes have correct parameter names", () => {
// After running other tests, validate captured calls
for (const invoke of capturedInvokes) {
validateInvokeCall(invoke);
}
});
});
});
/**
* Validate a single invoke call for correct parameter naming
*/
function validateInvokeCall(invoke: { command: string; args: Record<string, any> }) {
const { command, args } = invoke;
// Check for snake_case violations in top-level params
// Tauri v2 expects camelCase (auto-converts from Rust snake_case)
const violations: Record<string, string> = {
repository_handle: "repositoryHandle",
session_id: "sessionId",
item_id: "itemId",
current_item_id: "currentItemId",
position_ticks: "positionTicks",
item_ids: "itemIds",
start_index: "startIndex",
};
for (const [wrongName, correctName] of Object.entries(violations)) {
if (wrongName in args) {
throw new Error(
`[${command}] Found top-level parameter "${wrongName}" (snake_case) - should be "${correctName}" (camelCase)`
);
}
}
}

View File

@ -3,7 +3,6 @@
import { page } from "$app/stores";
import { goto } from "$app/navigation";
import { platform } from "@tauri-apps/plugin-os";
import { invoke } from "@tauri-apps/api/core";
import "../app.css";
import { auth, needsReauth, isAuthenticated } from "$lib/stores/auth";
import { connectivity, isConnected } from "$lib/stores/connectivity";

View File

@ -1,7 +1,7 @@
<script lang="ts">
import { onMount } from "svelte";
import { goto } from "$app/navigation";
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import { downloads, activeDownloads, completedDownloads, pendingDownloads, failedDownloads } from "$lib/stores/downloads";
import { auth } from "$lib/stores/auth";
import DownloadItem from "$lib/components/downloads/DownloadItem.svelte";
@ -85,7 +85,7 @@
try {
const userId = $auth.user?.id;
if (userId) {
await invoke("clear_stale_downloads", { userId });
await commands.clearStaleDownloads(userId);
await downloads.refresh(userId);
}
} catch (error) {
@ -224,7 +224,7 @@
const userId = $auth.user?.id;
if (userId) {
if (confirm('Delete ALL downloads (including completed)? This cannot be undone.')) {
await invoke("delete_all_downloads", { userId });
await commands.deleteAllDownloads(userId);
await downloads.refresh(userId);
}
}

View File

@ -2,7 +2,7 @@
import { onMount, onDestroy, setContext } from "svelte";
import { goto } from "$app/navigation";
import { page } from "$app/stores";
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import { platform } from "@tauri-apps/plugin-os";
import { auth, isAuthenticated, isLoading as isAuthLoading, currentUser } from "$lib/stores/auth";
import { library } from "$lib/stores/library";
@ -66,14 +66,7 @@
async function updateQueueStatus() {
try {
const queue = await invoke<{
items: any[];
currentIndex: number | null;
hasNext: boolean;
hasPrevious: boolean;
shuffle: boolean;
repeat: string;
}>("player_get_queue");
const queue = await commands.playerGetQueue();
// Reset failure counter on success
failedAttempts = 0;

View File

@ -2,7 +2,7 @@
import { onMount, untrack } from "svelte";
import { page } from "$app/stores";
import { goto } from "$app/navigation";
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import type { MediaItem, Library } from "$lib/api/types";
import { library, libraryItems, isLibraryLoading, currentLibrary, libraries } from "$lib/stores/library";
import { auth } from "$lib/stores/auth";
@ -221,14 +221,11 @@
const repo = auth.getRepository();
const repositoryHandle = repo.getHandle();
const firstTrack = $libraryItems[0];
await invoke("player_play_album_track", {
repositoryHandle,
request: {
albumId: item.id,
albumName: item.name,
trackId: firstTrack.id,
shuffle: false,
},
await commands.playerPlayAlbumTrack(repositoryHandle, {
albumId: item.id,
albumName: item.name,
trackId: firstTrack.id,
shuffle: false,
});
} catch (e) {
console.error("Failed to play album:", e);
@ -248,14 +245,11 @@
const repositoryHandle = repo.getHandle();
// Pick a random track to start with
const randomTrack = $libraryItems[Math.floor(Math.random() * $libraryItems.length)];
await invoke("player_play_album_track", {
repositoryHandle,
request: {
albumId: item.id,
albumName: item.name,
trackId: randomTrack.id,
shuffle: true,
},
await commands.playerPlayAlbumTrack(repositoryHandle, {
albumId: item.id,
albumName: item.name,
trackId: randomTrack.id,
shuffle: true,
});
} catch (e) {
console.error("Failed to shuffle play album:", e);

View File

@ -2,7 +2,9 @@
import { onMount, onDestroy } from "svelte";
import { page } from "$app/stores";
import { goto } from "$app/navigation";
import { invoke, convertFileSrc } from "@tauri-apps/api/core";
import { convertFileSrc } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import type { PlayQueueRequest } from "$lib/api/bindings";
import type { MediaItem } from "$lib/api/types";
import { auth } from "$lib/stores/auth";
import { library } from "$lib/stores/library";
@ -125,7 +127,7 @@
loading = false;
// Sync queue status
try {
const queueStatus = await invoke<{ hasNext: boolean; hasPrevious: boolean }>("player_get_queue");
const queueStatus = await commands.playerGetQueue();
hasNext = queueStatus.hasNext;
hasPrevious = queueStatus.hasPrevious;
} catch (e) {
@ -145,7 +147,7 @@
// This prevents audio from continuing in the background and clears stale state
if (isVideo) {
try {
await invoke("player_stop");
await commands.playerStop();
queue.clear();
console.log("loadAndPlay: Stopped audio backend for video playback");
} catch (e) {
@ -159,10 +161,7 @@
if (!startPosition && userId) {
try {
const progress = await invoke<{ positionTicks: number } | null>(
"storage_get_playback_progress",
{ userId, itemId: id }
);
const progress = await commands.storageGetPlaybackProgress(userId, id);
console.log("Resume check - retrieved progress:", progress);
if (progress && progress.positionTicks > 0 && item.runTimeTicks) {
@ -208,7 +207,7 @@
isOfflinePlayback = true;
// Get the storage path and construct full file path
const storagePath = await invoke<string>("storage_get_path");
const storagePath = await commands.storageGetPath();
const fullPath = `${storagePath}/${localDownload.filePath}`;
console.log("loadAndPlay: Full local path:", fullPath);
@ -230,20 +229,17 @@
const repo = auth.getRepository();
const repositoryHandle = repo.getHandle();
await invoke("player_play_tracks", {
repositoryHandle,
request: {
trackIds: [item.id],
startIndex: 0,
shuffle: false,
context: {
type: "search",
searchQuery: "",
},
await commands.playerPlayTracks(repositoryHandle, {
trackIds: [item.id],
startIndex: 0,
shuffle: false,
context: {
type: "search",
searchQuery: "",
},
});
if (startPosition) {
await invoke("player_seek", { position: startPosition });
await commands.playerSeek(startPosition);
}
}
} else {
@ -336,13 +332,11 @@
}));
// Use player_play_queue to set up the backend queue
await invoke("player_play_queue", {
request: {
items: queueItems,
startIndex: actualStartIndex,
shuffle: shuffleParam,
},
});
await commands.playerPlayQueue({
items: queueItems,
startIndex: actualStartIndex,
shuffle: shuffleParam,
} as unknown as PlayQueueRequest);
// Queue will auto-update from Rust backend event
console.log("loadAndPlay: Successfully set up queue with", audioTracks.length, "tracks");
@ -353,16 +347,13 @@
const repo = auth.getRepository();
const repositoryHandle = repo.getHandle();
await invoke("player_play_tracks", {
repositoryHandle,
request: {
trackIds: [item.id],
startIndex: 0,
shuffle: false,
context: {
type: "search",
searchQuery: "",
},
await commands.playerPlayTracks(repositoryHandle, {
trackIds: [item.id],
startIndex: 0,
shuffle: false,
context: {
type: "search",
searchQuery: "",
},
});
@ -375,16 +366,13 @@
const repo = auth.getRepository();
const repositoryHandle = repo.getHandle();
await invoke("player_play_tracks", {
repositoryHandle,
request: {
trackIds: [item.id],
startIndex: 0,
shuffle: false,
context: {
type: "search",
searchQuery: "",
},
await commands.playerPlayTracks(repositoryHandle, {
trackIds: [item.id],
startIndex: 0,
shuffle: false,
context: {
type: "search",
searchQuery: "",
},
});
@ -394,7 +382,7 @@
// Seek to start position if provided
if (startPosition) {
await invoke("player_seek", { position: startPosition });
await commands.playerSeek(startPosition);
}
}
}
@ -442,24 +430,17 @@
async function updateStatus() {
try {
const status = await invoke<{
state: { kind: string; position?: number; duration?: number };
shuffle: boolean;
repeat: string;
}>("player_get_status");
const status = await commands.playerGetStatus();
if (status.state.kind === "playing" || status.state.kind === "paused") {
isPlaying = status.state.kind === "playing";
// Note: position/duration are now derived from player store (updated by events)
}
shuffle = status.shuffle;
repeat = status.repeat as "off" | "all" | "one";
repeat = status.repeat;
// Update queue status
const queue = await invoke<{
hasNext: boolean;
hasPrevious: boolean;
}>("player_get_queue");
const queue = await commands.playerGetQueue();
hasNext = queue.hasNext;
hasPrevious = queue.hasPrevious;
} catch (e) {
@ -522,10 +503,7 @@
try {
const repo = auth.getRepository();
const repoHandle = repo.getHandle();
await invoke("player_on_playback_ended", {
itemId: mediaId,
repositoryHandle: repoHandle,
});
await commands.playerOnPlaybackEnded(mediaId, repoHandle);
} catch (e) {
console.error("[AutoPlay] Failed to handle playback ended:", e);
}

View File

@ -1,7 +1,8 @@
<!-- TRACES: UR-023 | DR-048 -->
<script lang="ts">
import { onMount } from "svelte";
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import type { AudioSettings, VideoSettings, VolumeLevel } from "$lib/api/bindings";
import {
getCacheStats,
setCacheLimit,
@ -12,21 +13,6 @@
type ImageCacheStats,
} from "$lib/services/imageCache";
type VolumeLevel = "loud" | "normal" | "quiet";
interface AudioSettings {
crossfadeDuration: number;
gaplessPlayback: boolean;
normalizeVolume: boolean;
volumeLevel: VolumeLevel;
}
interface VideoSettings {
autoPlayNextEpisode: boolean;
autoPlayCountdownSeconds: number;
autoPlayMaxEpisodes: number;
}
const episodeLimitOptions = [
{ value: 0, label: "Unlimited" },
{ value: 1, label: "1" },
@ -75,8 +61,8 @@
try {
loading = true;
const [audioResult, videoResult] = await Promise.all([
invoke<AudioSettings>("player_get_audio_settings"),
invoke<VideoSettings>("player_get_video_settings"),
commands.playerGetAudioSettings(),
commands.playerGetVideoSettings(),
]);
settings = audioResult;
videoSettings = videoResult;
@ -142,8 +128,8 @@
saving = true;
saveMessage = "";
await Promise.all([
invoke("player_set_audio_settings", { settings }),
invoke("player_set_video_settings", { settings: videoSettings }),
commands.playerSetAudioSettings(settings),
commands.playerSetVideoSettings(videoSettings),
]);
saveMessage = "Settings saved successfully!";
setTimeout(() => {