diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..f30fe032e --- /dev/null +++ b/.dockerignore @@ -0,0 +1,13 @@ +.git +.indexion +.env +.env.* +!.env.example +**/node_modules +**/target +**/.output +**/.nitro +**/dist +db-data +backup +*.log diff --git a/Dockerfile b/Dockerfile index 8166ed173..bbe8a01ba 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,10 +1,44 @@ FROM oven/bun:debian -# Install python3, ffmpeg, and ca-certificates for yt-dlp and media processing +# Install the native build toolchain, Python for the CPU ONNX Runtime package, +# ffmpeg, and certificates for media processing. RUN apt-get update && apt-get install -y --no-install-recommends \ - python3 \ - ffmpeg \ + build-essential \ ca-certificates \ + curl \ + ffmpeg \ + libssl-dev \ + pkg-config \ + python3 \ + python3-pip \ && rm -rf /var/lib/apt/lists/* +# dghs-imgutils-rs is a Rust N-API addon and requires a current Rust toolchain +# during bun install. The addon loads the runtime dynamically at application +# startup, so keep the compatible CPU runtime beside its provider library. +RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | \ + sh -s -- -y --profile minimal --default-toolchain stable +ENV PATH="/root/.cargo/bin:${PATH}" + +RUN python3 -m pip install --no-cache-dir --target /tmp/onnxruntime \ + onnxruntime==1.24.2 \ + && mkdir -p /usr/local/lib/onnxruntime \ + && find /tmp/onnxruntime/onnxruntime/capi -maxdepth 1 -type f \ + -name 'libonnxruntime*.so*' \ + -exec cp {} /usr/local/lib/onnxruntime/ \; \ + && test -f /usr/local/lib/onnxruntime/libonnxruntime.so.1.24.2 \ + && test -f /usr/local/lib/onnxruntime/libonnxruntime_providers_shared.so \ + && rm -rf /tmp/onnxruntime + +ENV ORT_DYLIB_PATH="/usr/local/lib/onnxruntime/libonnxruntime.so.1.24.2" +ENV LD_LIBRARY_PATH="/usr/local/lib/onnxruntime" +ENV DGHS_BACKEND="cpu" +ENV DGHS_PRECISION="fp32" + WORKDIR /app + +COPY . . + +RUN bun install --frozen-lockfile +RUN bun run --cwd apps/server validate:native +RUN bun run --cwd apps/server build diff --git a/REPORT.md b/REPORT.md index 97c33187a..4ab625761 100644 --- a/REPORT.md +++ b/REPORT.md @@ -14,6 +14,6 @@ | AI接続状態・latency | 実装済み | `ai.health` contract/router と V2 Config画面 | | リロード後の前後メディア移動 | 実装済み | `apps/server/src/routes/v2/media-context.ts` と sessionStorage | | Collectionのgrid / list表示 | 実装済み | `packages/ui/src/source-media-grid.tsx` と V2 Search / Source画面 | -| Tauriの `/v2/*` route adapter | 対応済み(Jobsを除く) | `apps/tauri/src/routes/v2/`。既存Tauri画面へ検索、Manager、Config、About、Sourcesを接続 | +| Tauriの `/v2/*` route adapter | 実装済み | `apps/tauri/src/routes/v2/` と `apps/tauri/src/routes/jobs.tsx`。既存Tauri画面へ検索、Manager、Jobs、Config、About、Sourcesを接続 | 未対応の画面やAPIを追加する場合は、loading / error / offline / retryとリアルタイム更新まで同じ画面内で接続します。 diff --git a/apps/server/drizzle/0026_nebulous_metal_master.sql b/apps/server/drizzle/0026_nebulous_metal_master.sql new file mode 100644 index 000000000..6a1dafb74 --- /dev/null +++ b/apps/server/drizzle/0026_nebulous_metal_master.sql @@ -0,0 +1,10 @@ +CREATE TABLE "search_snapshots" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "version" integer DEFAULT 1 NOT NULL, + "fingerprint" text NOT NULL, + "state" jsonb NOT NULL, + "created_at" timestamp DEFAULT now() NOT NULL, + CONSTRAINT "search_snapshots_fingerprint_unique" UNIQUE("fingerprint") +); +--> statement-breakpoint +CREATE INDEX "idx_search_snapshots_created_at" ON "search_snapshots" USING btree ("created_at"); \ No newline at end of file diff --git a/apps/server/drizzle/meta/0026_snapshot.json b/apps/server/drizzle/meta/0026_snapshot.json new file mode 100644 index 000000000..ad1355b15 --- /dev/null +++ b/apps/server/drizzle/meta/0026_snapshot.json @@ -0,0 +1,3391 @@ +{ + "id": "ed86b785-ed10-4de8-94e6-a389bee87ea7", + "prevId": "65fa6c9c-2e70-45bb-ab6d-04644838f7d0", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.author_accounts": { + "name": "author_accounts", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "author_id": { + "name": "author_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "platform": { + "name": "platform", + "type": "author_platform", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "profile_url": { + "name": "profile_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_author_accounts_author_id": { + "name": "idx_author_accounts_author_id", + "columns": [ + { + "expression": "author_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_author_accounts_platform_account_unique": { + "name": "idx_author_accounts_platform_account_unique", + "columns": [ + { + "expression": "platform", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "author_accounts_author_id_authors_id_fk": { + "name": "author_accounts_author_id_authors_id_fk", + "tableFrom": "author_accounts", + "tableTo": "authors", + "columnsFrom": [ + "author_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.authors": { + "name": "authors", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_authors_account_id": { + "name": "idx_authors_account_id", + "columns": [ + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_authors_name": { + "name": "idx_authors_name", + "columns": [ + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.categories": { + "name": "categories", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "''" + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'#808080'" + }, + "parent_id": { + "name": "parent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "categories_parent_id_categories_id_fk": { + "name": "categories_parent_id_categories_id_fk", + "tableFrom": "categories", + "tableTo": "categories", + "columnsFrom": [ + "parent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "categories_name_unique": { + "name": "categories_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.ccip_embeddings": { + "name": "ccip_embeddings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "region_id": { + "name": "region_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "embedding": { + "name": "embedding", + "type": "vector(768)", + "primaryKey": false, + "notNull": true + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "embedding_version": { + "name": "embedding_version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "media_modified_at": { + "name": "media_modified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "extracted_at": { + "name": "extracted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_ccip_embeddings_region_id": { + "name": "idx_ccip_embeddings_region_id", + "columns": [ + { + "expression": "region_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_ccip_embeddings_embedding_cosine": { + "name": "idx_ccip_embeddings_embedding_cosine", + "columns": [ + { + "expression": "embedding", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "vector_cosine_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "hnsw", + "with": { + "m": 16, + "ef_construction": 64 + } + } + }, + "foreignKeys": { + "ccip_embeddings_region_id_media_regions_id_fk": { + "name": "ccip_embeddings_region_id_media_regions_id_fk", + "tableFrom": "ccip_embeddings", + "tableTo": "media_regions", + "columnsFrom": [ + "region_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "uq_ccip_embeddings_region_model_version": { + "name": "uq_ccip_embeddings_region_model_version", + "nullsNotDistinct": false, + "columns": [ + "region_id", + "model", + "embedding_version" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.character_ips": { + "name": "character_ips", + "schema": "", + "columns": { + "character_id": { + "name": "character_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "ip_id": { + "name": "ip_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + } + }, + "indexes": { + "idx_character_ips_ip_id_character_id": { + "name": "idx_character_ips_ip_id_character_id", + "columns": [ + { + "expression": "ip_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "character_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "character_ips_character_id_characters_id_fk": { + "name": "character_ips_character_id_characters_id_fk", + "tableFrom": "character_ips", + "tableTo": "characters", + "columnsFrom": [ + "character_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "character_ips_ip_id_ips_id_fk": { + "name": "character_ips_ip_id_ips_id_fk", + "tableFrom": "character_ips", + "tableTo": "ips", + "columnsFrom": [ + "ip_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "character_ips_character_id_ip_id_pk": { + "name": "character_ips_character_id_ip_id_pk", + "columns": [ + "character_id", + "ip_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.characters": { + "name": "characters", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "''" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "aliases": { + "name": "aliases", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "characters_name_unique": { + "name": "characters_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.collections": { + "name": "collections", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "''" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "collections_user_id_users_id_fk": { + "name": "collections_user_id_users_id_fk", + "tableFrom": "collections", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.ips": { + "name": "ips", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "''" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "ips_name_unique": { + "name": "ips_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.jobs": { + "name": "jobs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_id": { + "name": "source_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "job_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "result": { + "name": "result", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "parent_id": { + "name": "parent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "cancel_requested_at": { + "name": "cancel_requested_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "cancelled_at": { + "name": "cancelled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "attempt_count": { + "name": "attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "artifact_path": { + "name": "artifact_path", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "artifact_file_name": { + "name": "artifact_file_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "artifact_content_type": { + "name": "artifact_content_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "artifact_size": { + "name": "artifact_size", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "artifact_expires_at": { + "name": "artifact_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_jobs_pending_import_request": { + "name": "idx_jobs_pending_import_request", + "columns": [ + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"jobs\".\"status\" = 'pending' AND \"jobs\".\"type\" = 'import_request'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_jobs_pending_created": { + "name": "idx_jobs_pending_created", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"jobs\".\"status\" = 'pending' AND \"jobs\".\"type\" <> 'import_request'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_jobs_pending_type_created": { + "name": "idx_jobs_pending_type_created", + "columns": [ + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"jobs\".\"status\" = 'pending' AND \"jobs\".\"type\" <> 'import_request'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "uq_jobs_active_thumbnail": { + "name": "uq_jobs_active_thumbnail", + "columns": [ + { + "expression": "source_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "(\"payload\"->>'mediaId')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "(\"payload\"->>'size')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"jobs\".\"type\" = 'generate_thumbnail'\n\t\t\t\t\tAND \"jobs\".\"status\" IN ('pending', 'in_progress')\n\t\t\t\t\tAND \"jobs\".\"source_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_jobs_cancelable": { + "name": "idx_jobs_cancelable", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"jobs\".\"status\" IN ('pending', 'in_progress')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_jobs_artifact_expiry": { + "name": "idx_jobs_artifact_expiry", + "columns": [ + { + "expression": "artifact_expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"jobs\".\"artifact_path\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "jobs_source_id_media_sources_id_fk": { + "name": "jobs_source_id_media_sources_id_fk", + "tableFrom": "jobs", + "tableTo": "media_sources", + "columnsFrom": [ + "source_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "jobs_parent_id_jobs_id_fk": { + "name": "jobs_parent_id_jobs_id_fk", + "tableFrom": "jobs", + "tableTo": "jobs", + "columnsFrom": [ + "parent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.media_authors": { + "name": "media_authors", + "schema": "", + "columns": { + "media_id": { + "name": "media_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "author_id": { + "name": "author_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "idx_media_authors_author_id_media_id": { + "name": "idx_media_authors_author_id_media_id", + "columns": [ + { + "expression": "author_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "media_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "media_authors_media_id_media_id_fk": { + "name": "media_authors_media_id_media_id_fk", + "tableFrom": "media_authors", + "tableTo": "media", + "columnsFrom": [ + "media_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "media_authors_author_id_authors_id_fk": { + "name": "media_authors_author_id_authors_id_fk", + "tableFrom": "media_authors", + "tableTo": "authors", + "columnsFrom": [ + "author_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "media_authors_media_id_author_id_pk": { + "name": "media_authors_media_id_author_id_pk", + "columns": [ + "media_id", + "author_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.media_categories": { + "name": "media_categories", + "schema": "", + "columns": { + "media_id": { + "name": "media_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "category_id": { + "name": "category_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "idx_media_categories_category_id_media_id": { + "name": "idx_media_categories_category_id_media_id", + "columns": [ + { + "expression": "category_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "media_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "media_categories_media_id_media_id_fk": { + "name": "media_categories_media_id_media_id_fk", + "tableFrom": "media_categories", + "tableTo": "media", + "columnsFrom": [ + "media_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "media_categories_category_id_categories_id_fk": { + "name": "media_categories_category_id_categories_id_fk", + "tableFrom": "media_categories", + "tableTo": "categories", + "columnsFrom": [ + "category_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "media_categories_media_id_category_id_pk": { + "name": "media_categories_media_id_category_id_pk", + "columns": [ + "media_id", + "category_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.media_characters": { + "name": "media_characters", + "schema": "", + "columns": { + "media_id": { + "name": "media_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "character_id": { + "name": "character_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "confidence": { + "name": "confidence", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + } + }, + "indexes": { + "idx_media_characters_character_id_media_id": { + "name": "idx_media_characters_character_id_media_id", + "columns": [ + { + "expression": "character_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "media_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "media_characters_media_id_media_id_fk": { + "name": "media_characters_media_id_media_id_fk", + "tableFrom": "media_characters", + "tableTo": "media", + "columnsFrom": [ + "media_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "media_characters_character_id_characters_id_fk": { + "name": "media_characters_character_id_characters_id_fk", + "tableFrom": "media_characters", + "tableTo": "characters", + "columnsFrom": [ + "character_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "media_characters_media_id_character_id_pk": { + "name": "media_characters_media_id_character_id_pk", + "columns": [ + "media_id", + "character_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.media_collections": { + "name": "media_collections", + "schema": "", + "columns": { + "collection_id": { + "name": "collection_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "media_id": { + "name": "media_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "display_order": { + "name": "display_order", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_media_collections_media_id": { + "name": "idx_media_collections_media_id", + "columns": [ + { + "expression": "media_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "media_collections_collection_id_collections_id_fk": { + "name": "media_collections_collection_id_collections_id_fk", + "tableFrom": "media_collections", + "tableTo": "collections", + "columnsFrom": [ + "collection_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "media_collections_media_id_media_id_fk": { + "name": "media_collections_media_id_media_id_fk", + "tableFrom": "media_collections", + "tableTo": "media", + "columnsFrom": [ + "media_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "media_collections_collection_id_media_id_pk": { + "name": "media_collections_collection_id_media_id_pk", + "columns": [ + "collection_id", + "media_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.media_details": { + "name": "media_details", + "schema": "", + "columns": { + "media_id": { + "name": "media_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "rating": { + "name": "rating", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "favorite": { + "name": "favorite", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "view_count": { + "name": "view_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "last_viewed_at": { + "name": "last_viewed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "'1970-01-01 00:00:00'" + } + }, + "indexes": { + "idx_media_details_rating": { + "name": "idx_media_details_rating", + "columns": [ + { + "expression": "rating", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_media_details_favorite": { + "name": "idx_media_details_favorite", + "columns": [ + { + "expression": "favorite", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_media_details_view_count": { + "name": "idx_media_details_view_count", + "columns": [ + { + "expression": "view_count", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "media_details_media_id_media_id_fk": { + "name": "media_details_media_id_media_id_fk", + "tableFrom": "media_details", + "tableTo": "media", + "columnsFrom": [ + "media_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.media_generation_info": { + "name": "media_generation_info", + "schema": "", + "columns": { + "media_id": { + "name": "media_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "prompt": { + "name": "prompt", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "negative_prompt": { + "name": "negative_prompt", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workflow": { + "name": "workflow", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "loras": { + "name": "loras", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "vae": { + "name": "vae", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "hypernetworks": { + "name": "hypernetworks", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "embeddings": { + "name": "embeddings", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "ai_generated": { + "name": "ai_generated", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "model_name": { + "name": "model_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "''" + }, + "seed": { + "name": "seed", + "type": "bigint", + "primaryKey": false, + "notNull": false, + "default": -1 + }, + "cfg_scale": { + "name": "cfg_scale", + "type": "real", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "steps": { + "name": "steps", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + } + }, + "indexes": { + "idx_media_generation_info_metadata": { + "name": "idx_media_generation_info_metadata", + "columns": [ + { + "expression": "metadata", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_media_generation_info_ai_generated": { + "name": "idx_media_generation_info_ai_generated", + "columns": [ + { + "expression": "ai_generated", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_media_generation_info_model_name": { + "name": "idx_media_generation_info_model_name", + "columns": [ + { + "expression": "model_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "media_generation_info_media_id_media_id_fk": { + "name": "media_generation_info_media_id_media_id_fk", + "tableFrom": "media_generation_info", + "tableTo": "media", + "columnsFrom": [ + "media_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.media_ips": { + "name": "media_ips", + "schema": "", + "columns": { + "media_id": { + "name": "media_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "ip_id": { + "name": "ip_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "confidence": { + "name": "confidence", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + } + }, + "indexes": { + "idx_media_ips_ip_id_media_id": { + "name": "idx_media_ips_ip_id_media_id", + "columns": [ + { + "expression": "ip_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "media_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "media_ips_media_id_media_id_fk": { + "name": "media_ips_media_id_media_id_fk", + "tableFrom": "media_ips", + "tableTo": "media", + "columnsFrom": [ + "media_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "media_ips_ip_id_ips_id_fk": { + "name": "media_ips_ip_id_ips_id_fk", + "tableFrom": "media_ips", + "tableTo": "ips", + "columnsFrom": [ + "ip_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "media_ips_media_id_ip_id_pk": { + "name": "media_ips_media_id_ip_id_pk", + "columns": [ + "media_id", + "ip_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.media_projects": { + "name": "media_projects", + "schema": "", + "columns": { + "media_id": { + "name": "media_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "idx_media_projects_project_id_media_id": { + "name": "idx_media_projects_project_id_media_id", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "media_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "media_projects_media_id_media_id_fk": { + "name": "media_projects_media_id_media_id_fk", + "tableFrom": "media_projects", + "tableTo": "media", + "columnsFrom": [ + "media_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "media_projects_project_id_projects_id_fk": { + "name": "media_projects_project_id_projects_id_fk", + "tableFrom": "media_projects", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "media_projects_media_id_project_id_pk": { + "name": "media_projects_media_id_project_id_pk", + "columns": [ + "media_id", + "project_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.media_regions": { + "name": "media_regions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "media_id": { + "name": "media_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "media_region_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "x": { + "name": "x", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "y": { + "name": "y", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "width": { + "name": "width", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "height": { + "name": "height", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "source_modified_at": { + "name": "source_modified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "detector": { + "name": "detector", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "detector_version": { + "name": "detector_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "score": { + "name": "score", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_media_regions_media_id": { + "name": "idx_media_regions_media_id", + "columns": [ + { + "expression": "media_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "uq_media_regions_full_media_id": { + "name": "uq_media_regions_full_media_id", + "columns": [ + { + "expression": "media_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"media_regions\".\"kind\" = 'full'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "media_regions_media_id_media_id_fk": { + "name": "media_regions_media_id_media_id_fk", + "tableFrom": "media_regions", + "tableTo": "media", + "columnsFrom": [ + "media_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "media_regions_bbox_by_kind": { + "name": "media_regions_bbox_by_kind", + "value": "(\n\t\t\t\t(\"media_regions\".\"kind\" = 'full' AND \"media_regions\".\"x\" IS NULL AND \"media_regions\".\"y\" IS NULL AND \"media_regions\".\"width\" IS NULL AND \"media_regions\".\"height\" IS NULL)\n\t\t\t\tOR\n\t\t\t\t(\"media_regions\".\"kind\" <> 'full' AND \"media_regions\".\"x\" IS NOT NULL AND \"media_regions\".\"y\" IS NOT NULL AND \"media_regions\".\"width\" IS NOT NULL AND \"media_regions\".\"height\" IS NOT NULL\n\t\t\t\t\tAND \"media_regions\".\"x\" >= 0 AND \"media_regions\".\"y\" >= 0 AND \"media_regions\".\"width\" > 0 AND \"media_regions\".\"height\" > 0\n\t\t\t\t\tAND \"media_regions\".\"x\" + \"media_regions\".\"width\" <= 1 AND \"media_regions\".\"y\" + \"media_regions\".\"height\" <= 1)\n\t\t\t)" + }, + "media_regions_score_range": { + "name": "media_regions_score_range", + "value": "\"media_regions\".\"score\" IS NULL OR (\"media_regions\".\"score\" >= 0 AND \"media_regions\".\"score\" <= 1)" + } + }, + "isRLSEnabled": false + }, + "public.media_relations": { + "name": "media_relations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "parent_media_id": { + "name": "parent_media_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "child_media_id": { + "name": "child_media_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "relation_type": { + "name": "relation_type", + "type": "media_relation_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "order_index": { + "name": "order_index", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_media_relations_child": { + "name": "idx_media_relations_child", + "columns": [ + { + "expression": "child_media_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_media_relations_type": { + "name": "idx_media_relations_type", + "columns": [ + { + "expression": "relation_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "media_relations_parent_media_id_media_id_fk": { + "name": "media_relations_parent_media_id_media_id_fk", + "tableFrom": "media_relations", + "tableTo": "media", + "columnsFrom": [ + "parent_media_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "media_relations_child_media_id_media_id_fk": { + "name": "media_relations_child_media_id_media_id_fk", + "tableFrom": "media_relations", + "tableTo": "media", + "columnsFrom": [ + "child_media_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "parent_child_type_unique": { + "name": "parent_child_type_unique", + "nullsNotDistinct": false, + "columns": [ + "parent_media_id", + "child_media_id", + "relation_type" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.media_sources": { + "name": "media_sources", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "media_source_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "connection_info": { + "name": "connection_info", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "sync_status": { + "name": "sync_status", + "type": "media_source_sync_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'idle'" + }, + "last_sync_started_at": { + "name": "last_sync_started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_sync_completed_at": { + "name": "last_sync_completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_sync_error": { + "name": "last_sync_error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.media_sync": { + "name": "media_sync", + "schema": "", + "columns": { + "media_id": { + "name": "media_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "sync_status": { + "name": "sync_status", + "type": "media_sync_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": false, + "default": "'synced'" + }, + "backup_urls": { + "name": "backup_urls", + "type": "text[]", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "last_synced_at": { + "name": "last_synced_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "sync_attempts": { + "name": "sync_attempts", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "media_sync_media_id_media_id_fk": { + "name": "media_sync_media_id_media_id_fk", + "tableFrom": "media_sync", + "tableTo": "media", + "columnsFrom": [ + "media_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.media_tags": { + "name": "media_tags", + "schema": "", + "columns": { + "media_id": { + "name": "media_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "tag_id": { + "name": "tag_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "tag_type": { + "name": "tag_type", + "type": "tag_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'positive'" + }, + "confidence": { + "name": "confidence", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + } + }, + "indexes": { + "idx_media_tags_tag_id_tag_type_media_id": { + "name": "idx_media_tags_tag_id_tag_type_media_id", + "columns": [ + { + "expression": "tag_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tag_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "media_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "media_tags_media_id_media_id_fk": { + "name": "media_tags_media_id_media_id_fk", + "tableFrom": "media_tags", + "tableTo": "media", + "columnsFrom": [ + "media_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "media_tags_tag_id_tags_id_fk": { + "name": "media_tags_tag_id_tags_id_fk", + "tableFrom": "media_tags", + "tableTo": "tags", + "columnsFrom": [ + "tag_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "media_tags_media_id_tag_id_tag_type_pk": { + "name": "media_tags_media_id_tag_id_tag_type_pk", + "columns": [ + "media_id", + "tag_id", + "tag_type" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.media_technical_info": { + "name": "media_technical_info", + "schema": "", + "columns": { + "media_id": { + "name": "media_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "color_profile": { + "name": "color_profile", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "''" + }, + "exif_data": { + "name": "exif_data", + "type": "jsonb", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "hash_md5": { + "name": "hash_md5", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "''" + }, + "hash_perceptual": { + "name": "hash_perceptual", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "''" + }, + "duration_seconds": { + "name": "duration_seconds", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "frame_rate": { + "name": "frame_rate", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "bitrate_kbps": { + "name": "bitrate_kbps", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "video_codec": { + "name": "video_codec", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "audio_codec": { + "name": "audio_codec", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_media_technical_info_hash_md5": { + "name": "idx_media_technical_info_hash_md5", + "columns": [ + { + "expression": "hash_md5", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "media_technical_info_media_id_media_id_fk": { + "name": "media_technical_info_media_id_media_id_fk", + "tableFrom": "media_technical_info", + "tableTo": "media", + "columnsFrom": [ + "media_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.media_urls": { + "name": "media_urls", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "media_id": { + "name": "media_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_media_urls_media_id": { + "name": "idx_media_urls_media_id", + "columns": [ + { + "expression": "media_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_media_urls_url": { + "name": "idx_media_urls_url", + "columns": [ + { + "expression": "url", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_media_urls_media_id_url_unique": { + "name": "idx_media_urls_media_id_url_unique", + "columns": [ + { + "expression": "media_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "url", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "media_urls_media_id_media_id_fk": { + "name": "media_urls_media_id_media_id_fk", + "tableFrom": "media_urls", + "tableTo": "media", + "columnsFrom": [ + "media_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.media": { + "name": "media", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "source_id": { + "name": "source_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "file_path": { + "name": "file_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file_name": { + "name": "file_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "media_type": { + "name": "media_type", + "type": "media_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "width": { + "name": "width", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "height": { + "name": "height", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "file_size": { + "name": "file_size", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "modified_at": { + "name": "modified_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "indexed_at": { + "name": "indexed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "status": { + "name": "status", + "type": "media_organization_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + } + }, + "indexes": { + "idx_media_source_id": { + "name": "idx_media_source_id", + "columns": [ + { + "expression": "source_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_media_file_size": { + "name": "idx_media_file_size", + "columns": [ + { + "expression": "file_size", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_media_file_name": { + "name": "idx_media_file_name", + "columns": [ + { + "expression": "file_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_media_created_at": { + "name": "idx_media_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_media_description": { + "name": "idx_media_description", + "columns": [ + { + "expression": "description", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "media_source_id_media_sources_id_fk": { + "name": "media_source_id_media_sources_id_fk", + "tableFrom": "media", + "tableTo": "media_sources", + "columnsFrom": [ + "source_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "source_id_file_path_unique": { + "name": "source_id_file_path_unique", + "nullsNotDistinct": false, + "columns": [ + "source_id", + "file_path" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.presets": { + "name": "presets", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "sort": { + "name": "sort", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "order": { + "name": "order", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "presets_name_unique": { + "name": "presets_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.projects": { + "name": "projects", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "''" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_projects_name": { + "name": "idx_projects_name", + "columns": [ + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "projects_name_unique": { + "name": "projects_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.search_snapshots": { + "name": "search_snapshots", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "fingerprint": { + "name": "fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state": { + "name": "state", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_search_snapshots_created_at": { + "name": "idx_search_snapshots_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "search_snapshots_fingerprint_unique": { + "name": "search_snapshots_fingerprint_unique", + "nullsNotDistinct": false, + "columns": [ + "fingerprint" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.similar_media": { + "name": "similar_media", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "media1_id": { + "name": "media1_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "media2_id": { + "name": "media2_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "similarity_score": { + "name": "similarity_score", + "type": "real", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "algorithm": { + "name": "algorithm", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'perceptual'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": { + "idx_similar_media_score": { + "name": "idx_similar_media_score", + "columns": [ + { + "expression": "similarity_score", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "similar_media_media1_id_media_id_fk": { + "name": "similar_media_media1_id_media_id_fk", + "tableFrom": "similar_media", + "tableTo": "media", + "columnsFrom": [ + "media1_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "similar_media_media2_id_media_id_fk": { + "name": "similar_media_media2_id_media_id_fk", + "tableFrom": "similar_media", + "tableTo": "media", + "columnsFrom": [ + "media2_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "media1Id_media2Id_algorithm_unique": { + "name": "media1Id_media2Id_algorithm_unique", + "nullsNotDistinct": false, + "columns": [ + "media1_id", + "media2_id", + "algorithm" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tags": { + "name": "tags", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "attribute": { + "name": "attribute", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "author_id": { + "name": "author_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_tags_author_id": { + "name": "idx_tags_author_id", + "columns": [ + { + "expression": "author_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "tags_author_id_authors_id_fk": { + "name": "tags_author_id_authors_id_fk", + "tableFrom": "tags", + "tableTo": "authors", + "columnsFrom": [ + "author_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "tags_name_unique": { + "name": "tags_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_email_unique": { + "name": "users_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.view_history": { + "name": "view_history", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "media_id": { + "name": "media_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "viewed_at": { + "name": "viewed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "''" + } + }, + "indexes": {}, + "foreignKeys": { + "view_history_media_id_media_id_fk": { + "name": "view_history_media_id_media_id_fk", + "tableFrom": "view_history", + "tableTo": "media", + "columnsFrom": [ + "media_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.author_platform": { + "name": "author_platform", + "schema": "public", + "values": [ + "twitter", + "pixiv-fanbox", + "danbooru" + ] + }, + "public.job_status": { + "name": "job_status", + "schema": "public", + "values": [ + "pending", + "in_progress", + "completed", + "failed", + "cancelled" + ] + }, + "public.media_organization_status": { + "name": "media_organization_status", + "schema": "public", + "values": [ + "active", + "archived", + "deleted" + ] + }, + "public.media_region_kind": { + "name": "media_region_kind", + "schema": "public", + "values": [ + "full", + "person", + "manual" + ] + }, + "public.media_relation_type": { + "name": "media_relation_type", + "schema": "public", + "values": [ + "variant", + "version", + "page", + "derivative", + "edit", + "source" + ] + }, + "public.media_source_sync_status": { + "name": "media_source_sync_status", + "schema": "public", + "values": [ + "idle", + "syncing", + "error" + ] + }, + "public.media_source_type": { + "name": "media_source_type", + "schema": "public", + "values": [ + "local", + "sftp", + "s3" + ] + }, + "public.media_sync_status": { + "name": "media_sync_status", + "schema": "public", + "values": [ + "synced", + "pending", + "failed" + ] + }, + "public.media_type": { + "name": "media_type", + "schema": "public", + "values": [ + "image", + "video", + "audio" + ] + }, + "public.tag_type": { + "name": "tag_type", + "schema": "public", + "values": [ + "positive", + "negative" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/apps/server/drizzle/meta/_journal.json b/apps/server/drizzle/meta/_journal.json index 029ca5819..8e9db3b5e 100644 --- a/apps/server/drizzle/meta/_journal.json +++ b/apps/server/drizzle/meta/_journal.json @@ -183,6 +183,13 @@ "when": 1786574384357, "tag": "0025_left_doctor_octopus", "breakpoints": true + }, + { + "idx": 26, + "version": "7", + "when": 1787235852419, + "tag": "0026_nebulous_metal_master", + "breakpoints": true } ] } \ No newline at end of file diff --git a/apps/server/package.json b/apps/server/package.json index 2819a6ee8..a3d86a502 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -15,6 +15,7 @@ "db:push": "drizzle-kit push", "db:drop": "drizzle-kit drop", "db:studio": "drizzle-kit studio", + "validate:native": "bun scripts/validate-native-runtime.ts", "lint": "biome lint ./src", "format": "biome format --fix ./src", "check": "biome check --fix --unsafe ./src", @@ -55,7 +56,7 @@ "@tanstack/solid-start": "^1.168.19", "archiver": "^8.0.0", "chokidar": "^5.0.0", - "dghs-imgutils-rs": "github:hmjn023/dghs-imgutils-rs#v0.2.0", + "dghs-imgutils-rs": "github:hmjn023/dghs-imgutils-rs#457553648518c8df370391391443b6302e19b05a", "drizzle-orm": "^0.45.2", "ffmpeg-static": "^5.3.0", "fluent-ffmpeg": "^2.1.3", diff --git a/apps/server/public/openapi.json b/apps/server/public/openapi.json index df56d89eb..f9e3f5003 100644 --- a/apps/server/public/openapi.json +++ b/apps/server/public/openapi.json @@ -19,6 +19,10 @@ "name": "Media", "description": "Operations for managing media files and their metadata" }, + { + "name": "Search Snapshots", + "description": "Operations for storing and restoring immutable search states used by browser history" + }, { "name": "Tags", "description": "Operations for managing tags and tag associations" @@ -8591,11 +8595,32 @@ "type": "number", "minimum": 1000, "default": 120000 + }, + "provider": { + "enum": [ + "auto", + "cpu", + "cuda", + "tensorrt", + "directml", + "intel_gpu", + "intel_npu", + "amd_gpu", + "amd_npu", + "openvino" + ], + "type": "string", + "default": "auto" + }, + "device": { + "type": "string", + "maxLength": 64 } }, "default": { "baseUrl": "", - "timeoutMs": 120000 + "timeoutMs": 120000, + "provider": "auto" } }, "downloads": { @@ -8889,11 +8914,32 @@ "type": "number", "minimum": 1000, "default": 120000 + }, + "provider": { + "enum": [ + "auto", + "cpu", + "cuda", + "tensorrt", + "directml", + "intel_gpu", + "intel_npu", + "amd_gpu", + "amd_npu", + "openvino" + ], + "type": "string", + "default": "auto" + }, + "device": { + "type": "string", + "maxLength": 64 } }, "default": { "baseUrl": "", - "timeoutMs": 120000 + "timeoutMs": 120000, + "provider": "auto" } }, "downloads": { @@ -10197,6 +10243,254 @@ } } } + }, + "/searchSnapshots/capture": { + "post": { + "operationId": "searchSnapshots.capture", + "summary": "検索状態を履歴スナップショットとして保存", + "description": "ブラウザ履歴から復元できる検索条件を保存し、スナップショットIDを返します。", + "tags": [ + "Search Snapshots" + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "state": { + "$ref": "#/components/schemas/SearchSnapshotState" + } + }, + "required": [ + "state" + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + } + }, + "required": [ + "id" + ] + } + } + } + } + } + } + }, + "/searchSnapshots/get": { + "post": { + "operationId": "searchSnapshots.get", + "summary": "検索履歴スナップショット取得", + "description": "スナップショットIDから保存済みの検索条件を取得します。", + "tags": [ + "Search Snapshots" + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + } + }, + "required": [ + "id" + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SafeSearchSnapshot" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "SearchSnapshotState": { + "type": "object", + "description": "検索結果を再現するための条件。ページング、スクロール位置、ユーザープリセットIDは含みません。", + "properties": { + "mode": { + "enum": [ + "simple", + "pro", + "vector" + ], + "type": "string" + }, + "searchQuery": { + "type": "string" + }, + "selectedTags": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludeTags": { + "type": "array", + "items": { + "type": "string" + } + }, + "tagMode": { + "enum": [ + "and", + "or" + ], + "type": "string" + }, + "selectedSource": { + "type": "string" + }, + "selectedProjects": { + "type": "array", + "items": { + "type": "string" + } + }, + "selectedIps": { + "type": "array", + "items": { + "type": "string" + } + }, + "selectedCharacters": { + "type": "array", + "items": { + "type": "string" + } + }, + "selectedAuthors": { + "type": "array", + "items": { + "type": "string" + } + }, + "advancedCondition": { + "anyOf": [ + { + "type": "object" + }, + { + "type": "null" + } + ] + }, + "similarityAnchorMediaId": { + "anyOf": [ + { + "type": "string", + "format": "uuid" + }, + { + "type": "null" + } + ] + }, + "similarityTopK": { + "enum": [ + 20, + 50, + 100 + ], + "type": "integer" + }, + "limit": { + "type": "number" + }, + "sortBy": { + "enum": [ + "date", + "name", + "size", + "rating", + "viewCount" + ], + "type": "string" + }, + "sortOrder": { + "enum": [ + "asc", + "desc" + ], + "type": "string" + } + }, + "required": [ + "mode", + "searchQuery", + "selectedTags", + "excludeTags", + "tagMode", + "selectedSource", + "selectedProjects", + "selectedIps", + "selectedCharacters", + "selectedAuthors", + "advancedCondition", + "similarityAnchorMediaId", + "similarityTopK", + "limit", + "sortBy", + "sortOrder" + ] + }, + "SafeSearchSnapshotState": { + "$ref": "#/components/schemas/SearchSnapshotState" + }, + "SafeSearchSnapshot": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "version": { + "const": 1, + "type": "integer" + }, + "state": { + "$ref": "#/components/schemas/SafeSearchSnapshotState" + } + }, + "required": [ + "id", + "version", + "state" + ] + } } } -} \ No newline at end of file +} diff --git a/apps/server/scripts/validate-native-runtime.ts b/apps/server/scripts/validate-native-runtime.ts new file mode 100644 index 000000000..39ca33c5f --- /dev/null +++ b/apps/server/scripts/validate-native-runtime.ts @@ -0,0 +1,11 @@ +import { probeInferenceBackends } from "dghs-imgutils-rs"; + +const cpuBackend = probeInferenceBackends({ + backend: "cpu", + precision: "fp32", +}).find((backend) => backend.backend === "cpu"); + +if (!cpuBackend?.available) { + const reason = cpuBackend?.reason ? `: ${cpuBackend.reason}` : ""; + throw new Error(`CPU ONNX Runtime provider is unavailable${reason}`); +} diff --git a/apps/server/src/infrastructure/ai/inference-options.ts b/apps/server/src/infrastructure/ai/inference-options.ts new file mode 100644 index 000000000..b64afa4ce --- /dev/null +++ b/apps/server/src/infrastructure/ai/inference-options.ts @@ -0,0 +1,33 @@ +import type { AiConfig } from "@solid-imager/core/domain/config/config-schema"; +import type { NapiInferenceOptions } from "dghs-imgutils-rs"; + +type InferenceConfig = Pick; + +const NATIVE_PROVIDER_BY_CONFIG: Record = { + amd_gpu: "amd_gpu", + amd_npu: "amd_npu", + auto: "auto", + cpu: "cpu", + cuda: "cuda", + directml: "directml", + intel_gpu: "intel_gpu", + intel_npu: "intel_npu", + openvino: "openvino", + tensorrt: "tensorrt", +}; + +/** Converts the persisted AI configuration to the native provider selector. */ +export function createNativeInferenceOptions( + config: InferenceConfig, +): NapiInferenceOptions { + const device = config.device?.trim(); + return { + // dghs exports this as an ambient const enum, which cannot be referenced + // at runtime with the server's isolatedModules setting. The explicit map + // above keeps the values synchronized at this external package boundary. + provider: NATIVE_PROVIDER_BY_CONFIG[ + config.provider + ] as NapiInferenceOptions["provider"], + ...(device ? { device } : {}), + }; +} diff --git a/apps/server/src/infrastructure/ai/rust-ai-client.ts b/apps/server/src/infrastructure/ai/rust-ai-client.ts index 976bb2cfe..5b606ecb7 100644 --- a/apps/server/src/infrastructure/ai/rust-ai-client.ts +++ b/apps/server/src/infrastructure/ai/rust-ai-client.ts @@ -1,6 +1,7 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { createClient } from "@solid-imager/client"; +import type { AiConfig } from "@solid-imager/core/domain/config/config-schema"; import type { AppContract } from "@solid-imager/core/domain/contract"; import type { IAiClient } from "@solid-imager/core/domain/interfaces/ai-client"; import { @@ -14,6 +15,13 @@ import { taggingResponseSchema, } from "@solid-imager/core/domain/tagging/schemas"; import { asyncPool } from "@solid-imager/core/utils/async-pool"; +import type { NapiInferenceOptions } from "dghs-imgutils-rs"; +import { createNativeInferenceOptions } from "~/infrastructure/ai/inference-options"; + +type RustAiClientConfig = Pick< + AiConfig, + "baseUrl" | "timeoutMs" | "provider" | "device" +>; function createRemoteOrpcClient(remoteUrl: string, timeoutMs: number) { return createClient({ @@ -46,17 +54,23 @@ function hasCcipDistances(value: unknown): value is { export class RustAiClient implements IAiClient { private baseUrl: string; private timeoutMs: number; + private inferenceOptions: NapiInferenceOptions; private client: ReturnType | null = null; - constructor(baseUrl = "", timeoutMs = 30_000) { - this.baseUrl = baseUrl; - this.timeoutMs = timeoutMs; + constructor(config: Partial = {}) { + this.baseUrl = config.baseUrl ?? ""; + this.timeoutMs = config.timeoutMs ?? 30_000; + this.inferenceOptions = createNativeInferenceOptions({ + provider: config.provider ?? "auto", + device: config.device, + }); this.refreshClient(); } - updateConfig(config: { baseUrl: string; timeoutMs: number }) { + updateConfig(config: RustAiClientConfig) { this.baseUrl = config.baseUrl; this.timeoutMs = config.timeoutMs; + this.inferenceOptions = createNativeInferenceOptions(config); this.refreshClient(); } @@ -193,7 +207,12 @@ export class RustAiClient implements IAiClient { } const { getPixaiTags } = await import("dghs-imgutils-rs"); - const result = await getPixaiTags(filePath); + const result = await getPixaiTags( + filePath, + undefined, + undefined, + this.inferenceOptions, + ); return taggingResponseSchema.parse({ general: result.general, character: result.character, @@ -216,7 +235,13 @@ export class RustAiClient implements IAiClient { } const { getOppaioracleTags } = await import("dghs-imgutils-rs"); - const result = await getOppaioracleTags(filePath); + const result = await getOppaioracleTags( + filePath, + undefined, + undefined, + undefined, + this.inferenceOptions, + ); return oppaiOracleResponseSchema.parse({ general: result.general, rating: result.rating, @@ -254,7 +279,11 @@ export class RustAiClient implements IAiClient { } const { ccipGetEmbedding } = await import("dghs-imgutils-rs"); - const embedding = await ccipGetEmbedding(filePath); + const embedding = await ccipGetEmbedding( + filePath, + undefined, + this.inferenceOptions, + ); return ccipFeatureResponseSchema.parse({ feature: embedding, }); diff --git a/apps/server/src/infrastructure/api-clients/queries/index.ts b/apps/server/src/infrastructure/api-clients/queries/index.ts index d92c674bb..4511d8fcd 100644 --- a/apps/server/src/infrastructure/api-clients/queries/index.ts +++ b/apps/server/src/infrastructure/api-clients/queries/index.ts @@ -1,4 +1,5 @@ import { createORPCSolidQueryUtils } from "@orpc/solid-query"; +import type { JobListRequest } from "@solid-imager/core/domain/jobs/schemas"; import { authorsQueryKeys, charactersQueryKeys, @@ -8,6 +9,7 @@ import { defaultConfigQueryConfig, defaultIpsQueryConfig, defaultJobsQueryConfig, + defaultJobsQueryInput, defaultMediaDetailsQueryConfig, defaultProjectsQueryConfig, defaultSourcesQueryConfig, @@ -48,7 +50,9 @@ export const allIpsQueryOptions = () => ({ queryKey: ipsQueryKeys.all(), ...defaultIpsQueryConfig, }); -export const jobsQueryOptions = (input = { limit: 200, offset: 0 }) => ({ +export const jobsQueryOptions = ( + input: JobListRequest = defaultJobsQueryInput, +) => ({ ...utils.jobs.list.queryOptions({ input }), queryKey: jobsQueryKeys.list(input), ...defaultJobsQueryConfig, diff --git a/apps/server/src/infrastructure/api/app-router.ts b/apps/server/src/infrastructure/api/app-router.ts index af6c032cc..d0ea8ecda 100644 --- a/apps/server/src/infrastructure/api/app-router.ts +++ b/apps/server/src/infrastructure/api/app-router.ts @@ -13,6 +13,7 @@ import { jobsRouter } from "~/infrastructure/api/routers/jobs-router"; import { mediaRouter } from "~/infrastructure/api/routers/media-router"; import { presetsRouter } from "~/infrastructure/api/routers/presets-router"; import { projectsRouter } from "~/infrastructure/api/routers/projects-router"; +import { searchSnapshotsRouter } from "~/infrastructure/api/routers/search-snapshots-router"; import { sourcesRouter } from "~/infrastructure/api/routers/sources-router"; import { tagsRouter } from "~/infrastructure/api/routers/tags-router"; import { thumbnailsRouter } from "~/infrastructure/api/routers/thumbnails-router"; @@ -44,6 +45,7 @@ export const appRouter = appRouterImplementer.router({ utils: utilsRouter, config: configRouter, presets: presetsRouter, + searchSnapshots: searchSnapshotsRouter, }); export type AppRouter = typeof appRouter; diff --git a/apps/server/src/infrastructure/api/clients/search-history-client.ts b/apps/server/src/infrastructure/api/clients/search-history-client.ts new file mode 100644 index 000000000..751fd6541 --- /dev/null +++ b/apps/server/src/infrastructure/api/clients/search-history-client.ts @@ -0,0 +1,6 @@ +import type { SearchSnapshotsOrpcLike } from "@solid-imager/core/domain/contract/search-snapshots-client"; +import { orpc } from "~/infrastructure/api-clients/orpc-client"; + +export const SearchHistoryClient: SearchSnapshotsOrpcLike = { + searchSnapshots: orpc.searchSnapshots, +}; diff --git a/apps/server/src/infrastructure/api/openapi-tags.ts b/apps/server/src/infrastructure/api/openapi-tags.ts index bd8cd9f02..753a1a6cb 100644 --- a/apps/server/src/infrastructure/api/openapi-tags.ts +++ b/apps/server/src/infrastructure/api/openapi-tags.ts @@ -12,6 +12,11 @@ export const openApiTags = [ name: "Media", description: "Operations for managing media files and their metadata", }, + { + name: "Search Snapshots", + description: + "Operations for storing and restoring immutable search states used by browser history", + }, { name: "Tags", description: "Operations for managing tags and tag associations", diff --git a/apps/server/src/infrastructure/api/routers/ai-router.ts b/apps/server/src/infrastructure/api/routers/ai-router.ts index 3ebe14cf2..3734e84ec 100644 --- a/apps/server/src/infrastructure/api/routers/ai-router.ts +++ b/apps/server/src/infrastructure/api/routers/ai-router.ts @@ -13,8 +13,10 @@ import { type NapiBBox, taggingResponseSchema, } from "@solid-imager/core/domain/tagging/schemas"; +import type { NapiInferenceOptions } from "dghs-imgutils-rs"; import { and, asc, desc, eq, isNull, sql } from "drizzle-orm"; import sharp from "sharp"; +import { createNativeInferenceOptions } from "~/infrastructure/ai/inference-options"; import { db } from "~/infrastructure/db"; import { jobs, @@ -100,6 +102,7 @@ async function cropDetection( det: { bbox: NapiBBox; label: string; score: number }, idx: number, transparent: boolean, + inferenceOptions: NapiInferenceOptions, ) { const { x1, y1, x2, y2 } = det.bbox; const w = Math.round(x2 - x1); @@ -124,7 +127,9 @@ async function cropDetection( .toFile(cropPath); try { const { segmentRgbaWithIsnetis } = await import("dghs-imgutils-rs"); - cropBuffer = Buffer.from(await segmentRgbaWithIsnetis(cropPath)); + cropBuffer = Buffer.from( + await segmentRgbaWithIsnetis(cropPath, undefined, inferenceOptions), + ); _format = "png"; } finally { await Bun.file(cropPath) @@ -641,6 +646,9 @@ export const aiRouter = os.router({ if ("file" in input) { const buffer = Buffer.from(await input.file.arrayBuffer()); + const inferenceOptions = createNativeInferenceOptions( + services.getConfigService().getConfig().ai, + ); const tmpPath = path.join( tmpdir(), `crop-${Date.now()}-${Math.random().toString(36).slice(2)}`, @@ -648,11 +656,18 @@ export const aiRouter = os.router({ await Bun.write(tmpPath, buffer); try { const { detectPerson } = await import("dghs-imgutils-rs"); - const detections = await detectPerson(tmpPath); + const detections = await detectPerson( + tmpPath, + undefined, + undefined, + undefined, + undefined, + inferenceOptions, + ); const resultDetections = await Promise.all( detections.map(async (det, idx) => - cropDetection(tmpPath, det, idx, transparent), + cropDetection(tmpPath, det, idx, transparent, inferenceOptions), ), ); @@ -723,11 +738,19 @@ export const aiRouter = os.router({ } const { detectPerson } = await import("dghs-imgutils-rs"); - const detections = await detectPerson(fullPath); + const inferenceOptions = createNativeInferenceOptions(config.ai); + const detections = await detectPerson( + fullPath, + undefined, + undefined, + undefined, + undefined, + inferenceOptions, + ); const resultDetections = await Promise.all( detections.map(async (det, idx) => - cropDetection(fullPath, det, idx, transparent), + cropDetection(fullPath, det, idx, transparent, inferenceOptions), ), ); diff --git a/apps/server/src/infrastructure/api/routers/search-snapshots-router.ts b/apps/server/src/infrastructure/api/routers/search-snapshots-router.ts new file mode 100644 index 000000000..482e43dc4 --- /dev/null +++ b/apps/server/src/infrastructure/api/routers/search-snapshots-router.ts @@ -0,0 +1,43 @@ +import { implement } from "@orpc/server"; +import { searchSnapshotsContract } from "@solid-imager/core/domain/contract/search-snapshots.contract"; +import type { SearchSnapshot } from "@solid-imager/core/domain/search/history"; +import { safeSearchSnapshotSchema } from "@solid-imager/core/domain/search/history"; +import { SearchSnapshotService } from "~/infrastructure/services/search-snapshot-service"; + +const os = implement(searchSnapshotsContract); + +function toSafeSearchSnapshot(snapshot: SearchSnapshot) { + const { state } = snapshot; + return safeSearchSnapshotSchema.parse({ + id: snapshot.id, + version: snapshot.version, + state: { + mode: state.mode, + searchQuery: state.searchQuery, + selectedTags: state.selectedTags, + excludeTags: state.excludeTags, + tagMode: state.tagMode, + selectedSource: state.selectedSource, + selectedProjects: state.selectedProjects, + selectedIps: state.selectedIps, + selectedCharacters: state.selectedCharacters, + selectedAuthors: state.selectedAuthors, + advancedCondition: state.advancedCondition, + similarityAnchorMediaId: state.similarityAnchorMediaId, + similarityTopK: state.similarityTopK, + limit: state.limit, + sortBy: state.sortBy, + sortOrder: state.sortOrder, + }, + }); +} + +export const searchSnapshotsRouter = os.router({ + capture: os.capture.handler(async ({ input }) => { + const snapshot = await SearchSnapshotService.capture(input.state); + return { id: snapshot.id }; + }), + get: os.get.handler(async ({ input }) => + toSafeSearchSnapshot(await SearchSnapshotService.get(input.id)), + ), +}); diff --git a/apps/server/src/infrastructure/bootstrap.ts b/apps/server/src/infrastructure/bootstrap.ts index 66e56b731..8fe6cde6f 100644 --- a/apps/server/src/infrastructure/bootstrap.ts +++ b/apps/server/src/infrastructure/bootstrap.ts @@ -83,7 +83,7 @@ export function initServices() { services.registerImageProcessor(ImageProcessor); // Initialize RustAiClient with config values - const rustAiClient = new RustAiClient(config.ai.baseUrl, config.ai.timeoutMs); + const rustAiClient = new RustAiClient(config.ai); services.registerAiClient(rustAiClient); configService.onChange((newConfig) => rustAiClient.updateConfig(newConfig.ai), diff --git a/apps/server/src/infrastructure/repositories/search-snapshot-repository.ts b/apps/server/src/infrastructure/repositories/search-snapshot-repository.ts new file mode 100644 index 000000000..bba0bb8d5 --- /dev/null +++ b/apps/server/src/infrastructure/repositories/search-snapshot-repository.ts @@ -0,0 +1,6 @@ +import type { SearchSnapshotRepository as SearchSnapshotRepositoryPort } from "@solid-imager/core/domain/repositories/search-snapshot-repository"; +import { createSearchSnapshotRepository } from "@solid-imager/db/repositories/search-snapshot-repository"; +import { getExecutor } from "~/infrastructure/db/executor"; + +export const SearchSnapshotRepository: SearchSnapshotRepositoryPort = + createSearchSnapshotRepository(getExecutor); diff --git a/apps/server/src/infrastructure/services/search-snapshot-service.ts b/apps/server/src/infrastructure/services/search-snapshot-service.ts new file mode 100644 index 000000000..93fabda75 --- /dev/null +++ b/apps/server/src/infrastructure/services/search-snapshot-service.ts @@ -0,0 +1,21 @@ +import type { ISearchSnapshotService } from "@solid-imager/application"; +import { createSearchSnapshotService } from "@solid-imager/application/services/search-snapshot-service"; +import type { SearchSnapshotRepository as SearchSnapshotRepositoryPort } from "@solid-imager/core/domain/repositories/search-snapshot-repository"; +import { SearchSnapshotRepository } from "~/infrastructure/repositories/search-snapshot-repository"; + +let service: ISearchSnapshotService = createSearchSnapshotService( + SearchSnapshotRepository, +); + +export const setSearchSnapshotRepository = ( + repository: SearchSnapshotRepositoryPort, +) => { + service = createSearchSnapshotService(repository); +}; + +export const SearchSnapshotService = new Proxy({} as ISearchSnapshotService, { + get(_, property) { + const value = service[property as keyof ISearchSnapshotService]; + return typeof value === "function" ? value.bind(service) : value; + }, +}); diff --git a/apps/server/src/routes/search.tsx b/apps/server/src/routes/search.tsx index 99f01a148..29773ee19 100644 --- a/apps/server/src/routes/search.tsx +++ b/apps/server/src/routes/search.tsx @@ -1,17 +1,18 @@ import { Button } from "@solid-imager/ui/button"; -import { - persistSearchScrollPosition, - useCurrentSearchPersistence, -} from "@solid-imager/ui/hooks/use-current-search-persistence"; +import { persistSearchScrollPosition } from "@solid-imager/ui/hooks/use-current-search-persistence"; +import { useSearchHistoryPersistence } from "@solid-imager/ui/hooks/use-search-history-persistence"; import { useSearchPage } from "@solid-imager/ui/hooks/use-search-page"; import { createPresetClient } from "@solid-imager/ui/preset-client"; import { RouteDataPendingScreen } from "@solid-imager/ui/router-status"; import { SearchScreen } from "@solid-imager/ui/screens/search-screen"; +import { createSearchHistoryClient } from "@solid-imager/ui/search-history-client"; +import { searchHistoryQuerySchema } from "@solid-imager/ui/search-history-route"; import { createFileRoute } from "@tanstack/solid-router"; import { createSignal, onMount, Show } from "solid-js"; import { LegacyMediaGridItem } from "~/components/media/legacy-media-grid-item"; import { useMediaSourceEvents } from "~/hooks/use-media-source-events"; import { PresetClient as rawPresetClient } from "~/infrastructure/api/clients/preset-client"; +import { SearchHistoryClient as rawSearchHistoryClient } from "~/infrastructure/api/clients/search-history-client"; import { allAuthorsQueryOptions, allCharactersQueryOptions, @@ -32,6 +33,7 @@ import { } from "~/presentation/store/search-store"; export const Route = createFileRoute("/search")({ + validateSearch: searchHistoryQuerySchema, ssr: true, loader: async ({ context, preload }: RouteLoaderContext) => { if (preload && typeof window !== "undefined") { @@ -65,6 +67,7 @@ export const Route = createFileRoute("/search")({ const SEARCH_RESULTS_REFRESH_DEBOUNCE_MS = 300; const PresetClient = createPresetClient(rawPresetClient); +const SearchHistoryClient = createSearchHistoryClient(rawSearchHistoryClient); function SearchRouteBoundary() { const [isMounted, setIsMounted] = createSignal(false); @@ -92,7 +95,9 @@ function SearchRouteFallback() { } function SearchRoute() { - const isSearchStateRestored = useCurrentSearchPersistence("all"); + const searchHistory = useSearchHistoryPersistence("all", { + client: SearchHistoryClient, + }); const page = useSearchPage({ searchMedia, @@ -113,14 +118,18 @@ function SearchRoute() { scrollY: () => searchState.scrollY, setScrollY: (y) => { setSearchState("scrollY", y); - persistSearchScrollPosition("all", y); + persistSearchScrollPosition("all", y, { + historyEntryKey: searchHistory.historyEntryKey, + }); }, setOffset: (o) => setSearchState("offset", o), mode: () => searchState.mode, similarityAnchorMediaId: () => searchState.similarityAnchorMediaId, similarityTopK: () => searchState.similarityTopK, refreshDebounceMs: SEARCH_RESULTS_REFRESH_DEBOUNCE_MS, - isSearchStateRestored, + isSearchStateRestored: searchHistory.isRestored, + commitSearchHistory: searchHistory.commitNow, + historyEntryKey: searchHistory.historyEntryKey, enableVirtualization: true, }); diff --git a/apps/server/src/routes/sources/$mediaSourceId/components/legacy-source-media-page.tsx b/apps/server/src/routes/sources/$mediaSourceId/components/legacy-source-media-page.tsx index 0e3c0622e..a3121f815 100644 --- a/apps/server/src/routes/sources/$mediaSourceId/components/legacy-source-media-page.tsx +++ b/apps/server/src/routes/sources/$mediaSourceId/components/legacy-source-media-page.tsx @@ -1,9 +1,13 @@ import { SourceMediaScreen } from "@solid-imager/ui/screens/source-media-screen"; +import { createSearchHistoryClient } from "@solid-imager/ui/search-history-client"; import type { Accessor } from "solid-js"; import { LegacyMediaGridItem } from "~/components/media/legacy-media-grid-item"; import { UploadMediaModal } from "~/components/upload-media-modal"; +import { SearchHistoryClient as rawSearchHistoryClient } from "~/infrastructure/api/clients/search-history-client"; import { SourceMediaPageController } from "./source-media-page"; +const SearchHistoryClient = createSearchHistoryClient(rawSearchHistoryClient); + export function SourceMediaPage( props: { mediaSourceId?: Accessor } = {}, ) { @@ -11,6 +15,7 @@ export function SourceMediaPage( ( ; screenComponent: Component; uploadModalComponent: SourceMediaScreenProps["uploadModalComponent"]; persistenceSurface: SearchPersistenceSurface; + searchHistoryClient: SearchHistoryClient; renderItem: SourceMediaGridRenderer; bulkActionsClass: string; ssrGuard?: boolean; @@ -137,6 +138,7 @@ export function SourceMediaPageController( mediaSourceId={mediaSourceId} mediaSourceName={mediaSourceName} persistenceSurface={props.persistenceSurface} + searchHistoryClient={props.searchHistoryClient} transport={transport} presetClient={PresetClient} actions={{ diff --git a/apps/server/src/routes/sources/$mediaSourceId/components/v2-source-media-page.tsx b/apps/server/src/routes/sources/$mediaSourceId/components/v2-source-media-page.tsx index 6d47677b6..4d39c9cd6 100644 --- a/apps/server/src/routes/sources/$mediaSourceId/components/v2-source-media-page.tsx +++ b/apps/server/src/routes/sources/$mediaSourceId/components/v2-source-media-page.tsx @@ -1,15 +1,19 @@ import { V2SourceMediaScreen } from "@solid-imager/ui/screens/v2-source-media-screen"; +import { createSearchHistoryClient } from "@solid-imager/ui/search-history-client"; import { useLocation, useNavigate } from "@tanstack/solid-router"; import type { Accessor } from "solid-js"; import { ThumbnailImage } from "~/components/media/thumbnail-image"; import { V2MediaGridItem } from "~/components/media/v2-media-grid-item"; import { V2UploadMediaModal } from "~/components/v2-upload-media-modal"; +import { SearchHistoryClient as rawSearchHistoryClient } from "~/infrastructure/api/clients/search-history-client"; import { saveV2MediaContext } from "~/routes/v2/media-context"; import { SourceMediaPageController, type SourceMediaPageControllerProps, } from "./source-media-page"; +const SearchHistoryClient = createSearchHistoryClient(rawSearchHistoryClient); + export function V2SourceMediaPage(props: { mediaSourceId?: Accessor }) { const location = useLocation(); const navigate = useNavigate(); @@ -38,6 +42,7 @@ export function V2SourceMediaPage(props: { mediaSourceId?: Accessor }) { onOpenMediaDetail={onOpenMediaDetail} onPrepareMediaDetail={onPrepareMediaDetail} persistenceSurface="v2" + searchHistoryClient={SearchHistoryClient} bulkActionsClass="fixed bottom-[calc(1rem+env(safe-area-inset-bottom))] left-1/2 z-50 flex w-[calc(100%-2rem)] max-w-md -translate-x-1/2 flex-wrap items-center justify-center gap-2 rounded-md border border-[var(--v2-border)] bg-[var(--v2-surface)] px-3 py-3 sm:bottom-[calc(1.5rem+env(safe-area-inset-bottom))] sm:w-auto sm:max-w-none sm:flex-nowrap sm:gap-3 sm:px-4" renderItem={(media, options, onToggleSelect) => ( [ params.mediaSourceId, diff --git a/apps/server/src/routes/v2/components/v2-search-content.tsx b/apps/server/src/routes/v2/components/v2-search-content.tsx index 18f26fbf6..dc44f92e5 100644 --- a/apps/server/src/routes/v2/components/v2-search-content.tsx +++ b/apps/server/src/routes/v2/components/v2-search-content.tsx @@ -1,15 +1,15 @@ -import { - persistSearchScrollPosition, - useCurrentSearchPersistence, -} from "@solid-imager/ui/hooks/use-current-search-persistence"; +import { persistSearchScrollPosition } from "@solid-imager/ui/hooks/use-current-search-persistence"; +import { useSearchHistoryPersistence } from "@solid-imager/ui/hooks/use-search-history-persistence"; import { useSearchPage } from "@solid-imager/ui/hooks/use-search-page"; import { createPresetClient } from "@solid-imager/ui/preset-client"; import { V2SearchScreen } from "@solid-imager/ui/screens/v2-search-screen"; +import { createSearchHistoryClient } from "@solid-imager/ui/search-history-client"; import { useLocation, useNavigate } from "@tanstack/solid-router"; import { ThumbnailImage } from "~/components/media/thumbnail-image"; import { V2MediaGridItem } from "~/components/media/v2-media-grid-item"; import { useMediaSourceEvents } from "~/hooks/use-media-source-events"; import { PresetClient as rawPresetClient } from "~/infrastructure/api/clients/preset-client"; +import { SearchHistoryClient as rawSearchHistoryClient } from "~/infrastructure/api/clients/search-history-client"; import { allAuthorsQueryOptions, allCharactersQueryOptions, @@ -32,6 +32,7 @@ import { saveV2MediaContext } from "../media-context"; const SEARCH_RESULTS_REFRESH_DEBOUNCE_MS = 300; const V2_SEARCH_RESULTS_PER_PAGE = 200; const PresetClient = createPresetClient(rawPresetClient); +const SearchHistoryClient = createSearchHistoryClient(rawSearchHistoryClient); function rememberReturnPath(href: string): void { try { @@ -44,7 +45,8 @@ function rememberReturnPath(href: string): void { export default function V2SearchContent() { const location = useLocation(); const navigate = useNavigate(); - const isSearchStateRestored = useCurrentSearchPersistence("all", { + const searchHistory = useSearchHistoryPersistence("all", { + client: SearchHistoryClient, surface: "v2", }); const page = useSearchPage({ @@ -68,14 +70,19 @@ export default function V2SearchContent() { scrollY: () => searchState.scrollY, setScrollY: (value) => { setSearchState("scrollY", value); - persistSearchScrollPosition("all", value, { surface: "v2" }); + persistSearchScrollPosition("all", value, { + surface: "v2", + historyEntryKey: searchHistory.historyEntryKey, + }); }, setOffset: (value) => setSearchState("offset", value), mode: () => searchState.mode, similarityAnchorMediaId: () => searchState.similarityAnchorMediaId, similarityTopK: () => searchState.similarityTopK, refreshDebounceMs: SEARCH_RESULTS_REFRESH_DEBOUNCE_MS, - isSearchStateRestored, + isSearchStateRestored: searchHistory.isRestored, + commitSearchHistory: searchHistory.commitNow, + historyEntryKey: searchHistory.historyEntryKey, enableVirtualization: true, scrollContainerSelector: '[data-media-scroll="v2-search"]', }); diff --git a/apps/server/src/routes/v2/jobs.tsx b/apps/server/src/routes/v2/jobs.tsx index 0c9290615..5f62cdf38 100644 --- a/apps/server/src/routes/v2/jobs.tsx +++ b/apps/server/src/routes/v2/jobs.tsx @@ -1,11 +1,16 @@ import type { JobListResponse } from "@solid-imager/core/domain/jobs/schemas"; import { useJobEvents } from "@solid-imager/ui/hooks/use-job-events"; -import { jobsQueryKeys } from "@solid-imager/ui/query-options"; +import { + DEFAULT_JOBS_PAGE_SIZE, + jobsQueryKeys, + updateJobProgress, +} from "@solid-imager/ui/query-options"; import { toQueryUiState } from "@solid-imager/ui/query-state"; import { V2JobsScreen } from "@solid-imager/ui/screens/v2-jobs-screen"; import { toast } from "@solid-imager/ui/toast"; import { createQuery, useQueryClient } from "@tanstack/solid-query"; import { createFileRoute } from "@tanstack/solid-router"; +import { createSignal } from "solid-js"; import { orpc } from "~/infrastructure/api-clients/orpc-client"; import { jobsQueryOptions } from "~/infrastructure/api-clients/queries"; @@ -14,13 +19,34 @@ export const Route = createFileRoute("/v2/jobs")({ }); function V2JobsRoute() { - const jobsQuery = createQuery(() => jobsQueryOptions()); + const [pageIndex, setPageIndex] = createSignal(0); + const jobsQuery = createQuery(() => + jobsQueryOptions({ + limit: DEFAULT_JOBS_PAGE_SIZE, + offset: pageIndex() * DEFAULT_JOBS_PAGE_SIZE, + }), + ); const queryClient = useQueryClient(); + const pagination = () => { + const total = jobsQuery.data?.total ?? 0; + return { + canNext: (pageIndex() + 1) * DEFAULT_JOBS_PAGE_SIZE < total, + canPrevious: pageIndex() > 0, + current: pageIndex() + 1, + onNext: () => setPageIndex((current) => current + 1), + onPrevious: () => setPageIndex((current) => Math.max(0, current - 1)), + total: Math.max(1, Math.ceil(total / DEFAULT_JOBS_PAGE_SIZE)), + }; + }; useJobEvents( (signal) => orpc.jobs.events(undefined, { signal }), (event) => { if (event.event === "job-progress") { + queryClient.setQueriesData( + { queryKey: jobsQueryKeys.listPrefix() }, + (data) => updateJobProgress(data, event.data), + ); return; } void queryClient.invalidateQueries({ queryKey: jobsQueryKeys.all() }); @@ -72,6 +98,7 @@ function V2JobsRoute() { anchor.click(); anchor.remove(); }} + page={pagination} state={() => toQueryUiState(jobsQuery)} /> ); diff --git a/apps/server/src/routes/v2/search.tsx b/apps/server/src/routes/v2/search.tsx index 2a1ea7152..c8865334b 100644 --- a/apps/server/src/routes/v2/search.tsx +++ b/apps/server/src/routes/v2/search.tsx @@ -1,3 +1,4 @@ +import { searchHistoryQuerySchema } from "@solid-imager/ui/search-history-route"; import { createFileRoute, lazyRouteComponent } from "@tanstack/solid-router"; const V2SearchRoute = lazyRouteComponent( @@ -5,6 +6,7 @@ const V2SearchRoute = lazyRouteComponent( ); export const Route = createFileRoute("/v2/search")({ + validateSearch: searchHistoryQuerySchema, ssr: false, pendingComponent: () => null, component: V2SearchRoute, diff --git a/apps/server/src/routes/v2/sources/$mediaSourceId/index.tsx b/apps/server/src/routes/v2/sources/$mediaSourceId/index.tsx index efa90631b..a23840030 100644 --- a/apps/server/src/routes/v2/sources/$mediaSourceId/index.tsx +++ b/apps/server/src/routes/v2/sources/$mediaSourceId/index.tsx @@ -1,7 +1,9 @@ +import { searchHistoryQuerySchema } from "@solid-imager/ui/search-history-route"; import { createFileRoute } from "@tanstack/solid-router"; import { V2SourceMediaPage } from "~/routes/sources/$mediaSourceId/components/v2-source-media-page"; export const Route = createFileRoute("/v2/sources/$mediaSourceId/")({ + validateSearch: searchHistoryQuerySchema, ssr: false, pendingComponent: () => null, remountDeps: ({ params }: { params: { mediaSourceId: string } }) => [ diff --git a/apps/server/src/tests/e2e/search-history.spec.ts b/apps/server/src/tests/e2e/search-history.spec.ts new file mode 100644 index 000000000..70406442d --- /dev/null +++ b/apps/server/src/tests/e2e/search-history.spec.ts @@ -0,0 +1,110 @@ +import { + E2E_PRIMARY_FILE_NAME, + E2E_SIMILAR_FILE_NAME, + E2E_SIMILAR_MEDIA_ID, + mediaPath, +} from "./support/fixture"; +import { expect, test, waitForAppHydration } from "./support/test"; + +const snapshotUrl = /\/search\?search=[0-9a-f-]{36}$/; + +test("search results remain traversable across detail navigation", async ({ + page, +}) => { + await page.goto("/search"); + await expect( + page.getByRole("heading", { name: "メディア検索", exact: true }), + ).toBeVisible(); + await waitForAppHydration(page); + + const fileNameInput = page.getByPlaceholder("ファイル名を入力..."); + const searchButton = page.getByRole("button", { name: "検索", exact: true }); + + await fileNameInput.fill(E2E_PRIMARY_FILE_NAME); + await searchButton.click(); + await expect(page).toHaveURL(snapshotUrl); + await expect(fileNameInput).toHaveValue(E2E_PRIMARY_FILE_NAME); + await expect( + page.getByRole("link", { name: new RegExp(E2E_PRIMARY_FILE_NAME) }), + ).toBeVisible(); + const firstSearchUrl = page.url(); + + await fileNameInput.fill(E2E_SIMILAR_FILE_NAME); + await searchButton.click(); + await expect(page).toHaveURL(snapshotUrl); + await expect(page).not.toHaveURL(firstSearchUrl); + await expect(fileNameInput).toHaveValue(E2E_SIMILAR_FILE_NAME); + await expect( + page.getByRole("link", { name: new RegExp(E2E_SIMILAR_FILE_NAME) }), + ).toBeVisible(); + const secondSearchUrl = page.url(); + + await page + .getByRole("link", { name: new RegExp(E2E_SIMILAR_FILE_NAME) }) + .click(); + await expect(page).toHaveURL( + new RegExp(`${mediaPath(E2E_SIMILAR_MEDIA_ID)}/?$`), + ); + await expect( + page.getByRole("heading", { name: E2E_SIMILAR_FILE_NAME, exact: true }), + ).toBeVisible(); + + await page.goBack(); + await expect(page).toHaveURL(secondSearchUrl); + await expect(page.getByPlaceholder("ファイル名を入力...")).toHaveValue( + E2E_SIMILAR_FILE_NAME, + ); + + await page.goBack(); + await expect(page).toHaveURL(firstSearchUrl); + await expect(page.getByPlaceholder("ファイル名を入力...")).toHaveValue( + E2E_PRIMARY_FILE_NAME, + ); + await expect( + page.getByRole("link", { name: new RegExp(E2E_PRIMARY_FILE_NAME) }), + ).toBeVisible(); + + // A copied/bookmarked URL has no in-memory history state, so it must restore + // the same snapshot through the server-side lookup endpoint. + await page.goto(secondSearchUrl); + await waitForAppHydration(page); + await expect(page.getByPlaceholder("ファイル名を入力...")).toHaveValue( + E2E_SIMILAR_FILE_NAME, + ); + await expect( + page.getByRole("link", { name: new RegExp(E2E_SIMILAR_FILE_NAME) }), + ).toBeVisible(); +}); + +test("flushes pending search state before immediate navigation", async ({ + page, +}) => { + await page.goto("/search"); + await expect( + page.getByRole("heading", { name: "メディア検索", exact: true }), + ).toBeVisible(); + await waitForAppHydration(page); + + const fileNameInput = page.getByPlaceholder("ファイル名を入力..."); + const searchButton = page.getByRole("button", { name: "検索", exact: true }); + await fileNameInput.fill(E2E_PRIMARY_FILE_NAME); + await searchButton.click(); + await expect(page).toHaveURL(snapshotUrl); + + const primaryResult = page.getByRole("link", { + name: new RegExp(E2E_PRIMARY_FILE_NAME), + }); + await expect(primaryResult).toBeVisible(); + + // Leave the current search before the debounce timer can commit the edit. + await fileNameInput.fill(E2E_SIMILAR_FILE_NAME); + await page.getByRole("link", { name: "Home", exact: true }).click(); + await expect(page).toHaveURL(/\/$/); + + await page.goBack(); + await waitForAppHydration(page); + await expect(page).toHaveURL(/\/search(?:\?search=[0-9a-f-]{36})?$/); + await expect(page.getByPlaceholder("ファイル名を入力...")).toHaveValue( + E2E_SIMILAR_FILE_NAME, + ); +}); diff --git a/apps/server/src/tests/unit/application/services/search-snapshot-service.test.ts b/apps/server/src/tests/unit/application/services/search-snapshot-service.test.ts new file mode 100644 index 000000000..81e2c2e6b --- /dev/null +++ b/apps/server/src/tests/unit/application/services/search-snapshot-service.test.ts @@ -0,0 +1,99 @@ +import { fingerprintState } from "@solid-imager/application/services/search-snapshot-service"; +import { ResourceNotFoundError } from "@solid-imager/core/domain/errors"; +import type { SearchSnapshotRepository } from "@solid-imager/core/domain/repositories/search-snapshot-repository"; +import { + type SearchSnapshot, + searchSnapshotStateSchema, +} from "@solid-imager/core/domain/search/history"; +import { defaultState } from "@solid-imager/core/domain/search/schema"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { + SearchSnapshotService, + setSearchSnapshotRepository, +} from "~/infrastructure/services/search-snapshot-service"; + +const snapshotState = searchSnapshotStateSchema.parse({ + ...defaultState, + activePresetId: undefined, + offset: undefined, + scrollY: undefined, +}); + +const snapshot: SearchSnapshot = { + id: "11111111-1111-4111-8111-111111111111", + version: 1, + fingerprint: "fingerprint", + state: snapshotState, + createdAt: new Date("2026-08-20T00:00:00.000Z"), +}; + +describe("SearchSnapshotService", () => { + let repository: SearchSnapshotRepository; + + beforeEach(() => { + repository = { + get: vi.fn().mockResolvedValue(snapshot), + getByFingerprint: vi.fn(), + create: vi.fn().mockResolvedValue(snapshot), + }; + setSearchSnapshotRepository(repository); + }); + + it("captures a validated state and delegates deduplication to the repository", async () => { + const result = await SearchSnapshotService.capture(snapshotState); + + expect(result).toEqual(snapshot); + expect(repository.create).toHaveBeenCalledWith({ + fingerprint: expect.any(String), + state: snapshotState, + }); + }); + + it("generates the same fingerprint for equivalent object key order", async () => { + await SearchSnapshotService.capture(snapshotState); + const firstFingerprint = vi.mocked(repository.create).mock.calls[0]?.[0] + .fingerprint; + await SearchSnapshotService.capture({ + ...snapshotState, + selectedTags: [...snapshotState.selectedTags], + }); + const secondFingerprint = vi.mocked(repository.create).mock.calls[1]?.[0] + .fingerprint; + + expect(secondFingerprint).toBe(firstFingerprint); + }); + + it("generates the same fingerprint when state keys are inserted in a different order", () => { + const reorderedState = { + sortOrder: snapshotState.sortOrder, + sortBy: snapshotState.sortBy, + limit: snapshotState.limit, + similarityTopK: snapshotState.similarityTopK, + similarityAnchorMediaId: snapshotState.similarityAnchorMediaId, + advancedCondition: snapshotState.advancedCondition, + selectedAuthors: snapshotState.selectedAuthors, + selectedCharacters: snapshotState.selectedCharacters, + selectedIps: snapshotState.selectedIps, + selectedProjects: snapshotState.selectedProjects, + selectedSource: snapshotState.selectedSource, + tagMode: snapshotState.tagMode, + excludeTags: snapshotState.excludeTags, + selectedTags: snapshotState.selectedTags, + searchQuery: snapshotState.searchQuery, + mode: snapshotState.mode, + } satisfies typeof snapshotState; + + expect(Object.keys(reorderedState)).not.toEqual(Object.keys(snapshotState)); + expect(fingerprintState(reorderedState)).toBe( + fingerprintState(snapshotState), + ); + }); + + it("throws a typed not-found error", async () => { + vi.mocked(repository.get).mockResolvedValue(null); + + await expect( + SearchSnapshotService.get("22222222-2222-4222-8222-222222222222"), + ).rejects.toThrow(ResourceNotFoundError); + }); +}); diff --git a/apps/server/src/tests/unit/infrastructure/ai/inference-options.test.ts b/apps/server/src/tests/unit/infrastructure/ai/inference-options.test.ts new file mode 100644 index 000000000..4a3fa37d0 --- /dev/null +++ b/apps/server/src/tests/unit/infrastructure/ai/inference-options.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from "vitest"; +import { createNativeInferenceOptions } from "~/infrastructure/ai/inference-options"; + +describe("createNativeInferenceOptions", () => { + it.each([ + ["auto", "auto"], + ["cpu", "cpu"], + ["cuda", "cuda"], + ["tensorrt", "tensorrt"], + ["directml", "directml"], + ["intel_gpu", "intel_gpu"], + ["intel_npu", "intel_npu"], + ["amd_gpu", "amd_gpu"], + ["amd_npu", "amd_npu"], + ["openvino", "openvino"], + ] as const)("maps %s to the native provider value", (provider, expected) => { + expect(createNativeInferenceOptions({ provider })).toEqual({ + provider: expected, + }); + }); + + it("trims a configured device and omits blank values", () => { + expect( + createNativeInferenceOptions({ + provider: "intel_gpu", + device: " GPU.0 ", + }), + ).toEqual({ + provider: "intel_gpu", + device: "GPU.0", + }); + expect( + createNativeInferenceOptions({ provider: "auto", device: " " }), + ).toEqual({ + provider: "auto", + }); + }); +}); diff --git a/apps/tauri/src/infrastructure/api/clients/search-history-client.ts b/apps/tauri/src/infrastructure/api/clients/search-history-client.ts new file mode 100644 index 000000000..e2094a4f8 --- /dev/null +++ b/apps/tauri/src/infrastructure/api/clients/search-history-client.ts @@ -0,0 +1,6 @@ +import type { SearchSnapshotsOrpcLike } from "@solid-imager/core/domain/contract/search-snapshots-client"; +import { client } from "~/orpc-client"; + +export const SearchHistoryClient: SearchSnapshotsOrpcLike = { + searchSnapshots: client.searchSnapshots, +}; diff --git a/apps/tauri/src/queries/index.ts b/apps/tauri/src/queries/index.ts index 81edc05c3..ac85ae9c6 100644 --- a/apps/tauri/src/queries/index.ts +++ b/apps/tauri/src/queries/index.ts @@ -1,4 +1,5 @@ import { createORPCSolidQueryUtils } from "@orpc/solid-query"; +import type { JobListRequest } from "@solid-imager/core/domain/jobs/schemas"; import { authorsQueryKeys, charactersQueryKeys, @@ -7,11 +8,14 @@ import { defaultCharactersQueryConfig, defaultConfigQueryConfig, defaultIpsQueryConfig, + defaultJobsQueryConfig, + defaultJobsQueryInput, defaultMediaDetailsQueryConfig, defaultProjectsQueryConfig, defaultSourcesQueryConfig, defaultTagsQueryConfig, ipsQueryKeys, + jobsQueryKeys, mediaDetailsQueryKeys, projectsQueryKeys, sourcesQueryKeys, @@ -46,6 +50,13 @@ export const allIpsQueryOptions = () => ({ queryKey: ipsQueryKeys.all(), ...defaultIpsQueryConfig, }); +export const jobsQueryOptions = ( + input: JobListRequest = defaultJobsQueryInput, +) => ({ + ...utils.jobs.list.queryOptions({ input }), + queryKey: jobsQueryKeys.list(input), + ...defaultJobsQueryConfig, +}); export const allAuthorsQueryOptions = () => ({ ...utils.authors.list.queryOptions(), queryKey: authorsQueryKeys.all(), diff --git a/apps/tauri/src/routes/jobs.tsx b/apps/tauri/src/routes/jobs.tsx new file mode 100644 index 000000000..0cd418630 --- /dev/null +++ b/apps/tauri/src/routes/jobs.tsx @@ -0,0 +1,127 @@ +import { downloadCompletedJobArtifact } from "@solid-imager/client"; +import type { + JobDto, + JobListResponse, +} from "@solid-imager/core/domain/jobs/schemas"; +import { useJobEvents } from "@solid-imager/ui/hooks/use-job-events"; +import { + DEFAULT_JOBS_PAGE_SIZE, + jobsQueryKeys, + updateJobProgress, +} from "@solid-imager/ui/query-options"; +import { toQueryUiState } from "@solid-imager/ui/query-state"; +import { V2JobsScreen } from "@solid-imager/ui/screens/v2-jobs-screen"; +import { toast } from "@solid-imager/ui/toast"; +import { createQuery, useQueryClient } from "@tanstack/solid-query"; +import { createFileRoute } from "@tanstack/solid-router"; +import { createSignal } from "solid-js"; +import { orpc } from "~/infrastructure/api-clients/orpc-client"; +import { jobsQueryOptions } from "~/queries"; + +export const Route = createFileRoute("/jobs")({ + loader: ({ context }) => { + void context.queryClient.prefetchQuery(jobsQueryOptions()); + }, + component: JobsRoute, +}); + +async function downloadJobArtifact(job: JobDto): Promise { + if (!job.artifact) return; + + try { + const blob = await downloadCompletedJobArtifact(orpc.jobs, job.id); + const url = URL.createObjectURL(blob); + const anchor = document.createElement("a"); + anchor.href = url; + anchor.download = job.artifact.fileName; + document.body.appendChild(anchor); + anchor.click(); + anchor.remove(); + URL.revokeObjectURL(url); + toast.success(`Downloaded ${job.artifact.fileName}`); + } catch (error) { + toast.error( + error instanceof Error ? error.message : "Failed to download artifact", + ); + throw error; + } +} + +function JobsRoute() { + const [pageIndex, setPageIndex] = createSignal(0); + const jobsQuery = createQuery(() => + jobsQueryOptions({ + limit: DEFAULT_JOBS_PAGE_SIZE, + offset: pageIndex() * DEFAULT_JOBS_PAGE_SIZE, + }), + ); + const queryClient = useQueryClient(); + const pagination = () => { + const total = jobsQuery.data?.total ?? 0; + return { + canNext: (pageIndex() + 1) * DEFAULT_JOBS_PAGE_SIZE < total, + canPrevious: pageIndex() > 0, + current: pageIndex() + 1, + onNext: () => setPageIndex((current) => current + 1), + onPrevious: () => setPageIndex((current) => Math.max(0, current - 1)), + total: Math.max(1, Math.ceil(total / DEFAULT_JOBS_PAGE_SIZE)), + }; + }; + + useJobEvents( + (signal) => orpc.jobs.events(undefined, { signal }), + (event) => { + if (event.event === "job-progress") { + queryClient.setQueriesData( + { queryKey: jobsQueryKeys.listPrefix() }, + (data) => updateJobProgress(data, event.data), + ); + return; + } + void queryClient.invalidateQueries({ queryKey: jobsQueryKeys.all() }); + }, + ); + + return ( +
+ jobsQuery.isFetching} + jobs={() => jobsQuery.data?.items ?? []} + onRefresh={async () => { + await jobsQuery.refetch(); + }} + onRetry={async (jobId) => { + try { + await orpc.jobs.retry({ id: jobId }); + await queryClient.invalidateQueries({ + queryKey: jobsQueryKeys.all(), + }); + toast.success("Job queued for retry"); + } catch (error) { + toast.error( + error instanceof Error ? error.message : "Failed to retry job", + ); + throw error; + } + }} + onCancel={async (jobId) => { + try { + await orpc.jobs.cancel({ id: jobId }); + await queryClient.invalidateQueries({ + queryKey: jobsQueryKeys.all(), + }); + toast.success("Job cancellation requested"); + } catch (error) { + toast.error( + error instanceof Error ? error.message : "Failed to cancel job", + ); + throw error; + } + }} + onDownload={downloadJobArtifact} + page={pagination} + state={() => toQueryUiState(jobsQuery)} + /> +
+ ); +} diff --git a/apps/tauri/src/routes/search.tsx b/apps/tauri/src/routes/search.tsx index 244a1ef88..1961ea3d1 100644 --- a/apps/tauri/src/routes/search.tsx +++ b/apps/tauri/src/routes/search.tsx @@ -1,13 +1,16 @@ import { Button } from "@solid-imager/ui/button"; import { persistSearchScrollPosition } from "@solid-imager/ui/hooks/use-current-search-persistence"; +import { useSearchHistoryPersistence } from "@solid-imager/ui/hooks/use-search-history-persistence"; import { useSearchPage } from "@solid-imager/ui/hooks/use-search-page"; import { createPresetClient } from "@solid-imager/ui/preset-client"; import { SearchScreen } from "@solid-imager/ui/screens/search-screen"; +import { createSearchHistoryClient } from "@solid-imager/ui/search-history-client"; +import { searchHistoryQuerySchema } from "@solid-imager/ui/search-history-route"; import { createFileRoute } from "@tanstack/solid-router"; import { MediaGridItem } from "~/components/media/media-grid-item"; -import { useCurrentSearchPersistence } from "~/hooks/use-current-search-persistence"; import { useMediaSourceEvents } from "~/hooks/use-media-source-events"; import { PresetClient as rawPresetClient } from "~/infrastructure/api/clients/preset-client"; +import { SearchHistoryClient as rawSearchHistoryClient } from "~/infrastructure/api/clients/search-history-client"; import { searchMedia, searchSimilar, @@ -27,6 +30,7 @@ import { } from "~/queries"; export const Route = createFileRoute("/search")({ + validateSearch: searchHistoryQuerySchema, loader: ({ context }) => { void context.queryClient.prefetchQuery(tagsQueryOptions()); void context.queryClient.prefetchQuery(mediaSourcesQueryOptions()); @@ -41,9 +45,12 @@ export const Route = createFileRoute("/search")({ const SEARCH_RESULTS_REFRESH_DEBOUNCE_MS = 300; const PresetClient = createPresetClient(rawPresetClient); +const SearchHistoryClient = createSearchHistoryClient(rawSearchHistoryClient); function SearchRoute() { - const isSearchStateRestored = useCurrentSearchPersistence("all"); + const searchHistory = useSearchHistoryPersistence("all", { + client: SearchHistoryClient, + }); const page = useSearchPage({ searchMedia, @@ -64,14 +71,18 @@ function SearchRoute() { scrollY: () => searchState.scrollY, setScrollY: (y) => { setSearchState("scrollY", y); - persistSearchScrollPosition("all", y); + persistSearchScrollPosition("all", y, { + historyEntryKey: searchHistory.historyEntryKey, + }); }, setOffset: (o) => setSearchState("offset", o), mode: () => searchState.mode, similarityAnchorMediaId: () => searchState.similarityAnchorMediaId, similarityTopK: () => searchState.similarityTopK, refreshDebounceMs: SEARCH_RESULTS_REFRESH_DEBOUNCE_MS, - isSearchStateRestored, + isSearchStateRestored: searchHistory.isRestored, + commitSearchHistory: searchHistory.commitNow, + historyEntryKey: searchHistory.historyEntryKey, enableVirtualization: true, }); diff --git a/apps/tauri/src/routes/sources/$mediaSourceId/components/source-media-page.tsx b/apps/tauri/src/routes/sources/$mediaSourceId/components/source-media-page.tsx index d618e61b5..77ed03a33 100644 --- a/apps/tauri/src/routes/sources/$mediaSourceId/components/source-media-page.tsx +++ b/apps/tauri/src/routes/sources/$mediaSourceId/components/source-media-page.tsx @@ -1,6 +1,7 @@ import { useSourceRootPath } from "@solid-imager/ui/hooks/use-source-root-path"; import { createPresetClient } from "@solid-imager/ui/preset-client"; import { SourceMediaScreen } from "@solid-imager/ui/screens/source-media-screen"; +import { createSearchHistoryClient } from "@solid-imager/ui/search-history-client"; import { SourceMediaPage as SourceMediaPageComponent } from "@solid-imager/ui/source-media-page"; import { useParams } from "@tanstack/solid-router"; import { MediaGridItem } from "~/components/media/media-grid-item"; @@ -8,6 +9,7 @@ import { MoveCopyMediaDialog } from "~/components/media/move-copy-media-dialog"; import { UploadMediaModal } from "~/components/upload-media-modal"; import { createTauriTransport } from "~/hooks/use-media-source-events"; import { PresetClient as rawPresetClient } from "~/infrastructure/api/clients/preset-client"; +import { SearchHistoryClient as rawSearchHistoryClient } from "~/infrastructure/api/clients/search-history-client"; import { copyMedia, deleteMedia, @@ -39,6 +41,7 @@ import { } from "~/queries"; const presetClient = createPresetClient(rawPresetClient); +const searchHistoryClient = createSearchHistoryClient(rawSearchHistoryClient); export function SourceMediaPage() { const params = useParams({ from: "/sources/$mediaSourceId/" }); @@ -54,6 +57,7 @@ export function SourceMediaPage() { screenComponent={SourceMediaScreen} transport={transport} presetClient={presetClient} + searchHistoryClient={searchHistoryClient} actions={{ searchMedia, uploadMedia: (sourceId, file, opts) => diff --git a/apps/tauri/src/routes/sources/$mediaSourceId/index.tsx b/apps/tauri/src/routes/sources/$mediaSourceId/index.tsx index f9d638dc2..d84f0c71d 100644 --- a/apps/tauri/src/routes/sources/$mediaSourceId/index.tsx +++ b/apps/tauri/src/routes/sources/$mediaSourceId/index.tsx @@ -1,3 +1,4 @@ +import { searchHistoryQuerySchema } from "@solid-imager/ui/search-history-route"; import { createFileRoute } from "@tanstack/solid-router"; import { allAuthorsQueryOptions, @@ -10,6 +11,7 @@ import { import { SourceMediaPage } from "./components/source-media-page"; export const Route = createFileRoute("/sources/$mediaSourceId/")({ + validateSearch: searchHistoryQuerySchema, loader: ({ context }) => { void context.queryClient.prefetchQuery(tagsQueryOptions()); void context.queryClient.prefetchQuery(allProjectsQueryOptions()); diff --git a/apps/tauri/src/routes/v2/$.tsx b/apps/tauri/src/routes/v2/$.tsx index 6d444f567..822b91b89 100644 --- a/apps/tauri/src/routes/v2/$.tsx +++ b/apps/tauri/src/routes/v2/$.tsx @@ -32,6 +32,9 @@ function V2RouteAdapter() { + + + diff --git a/apps/xtracter/package.json b/apps/xtracter/package.json index 549615935..5acf2a98f 100644 --- a/apps/xtracter/package.json +++ b/apps/xtracter/package.json @@ -8,6 +8,7 @@ "build": "vite build", "preview": "vite preview", "typecheck": "bun x tsc --noEmit", + "test": "vitest run", "lint": "biome lint ./src", "format": "biome format --fix ./src", "check": "biome check --fix --unsafe ./src" diff --git a/apps/xtracter/src/background/index.ts b/apps/xtracter/src/background/index.ts index 341076aa0..b1b75b138 100644 --- a/apps/xtracter/src/background/index.ts +++ b/apps/xtracter/src/background/index.ts @@ -9,6 +9,7 @@ import type { PostDownloadMessage, TweetMetadata, } from "@ext/schema"; +import { resolveEffectiveSourceId } from "@ext/utils/source-selection"; const DATE_STRING_LENGTH = 19; // "YYYY-MM-DDTHH-mm-ss" @@ -77,29 +78,33 @@ async function getMediaSources(): Promise { } } -// Determine which source ID to use async function getTargetSourceId(): Promise { - // 1. Check local storage for user selection const result: { selectedSourceId?: string } = await chrome.storage.local.get([ "selectedSourceId", ]); - if (result.selectedSourceId) { - return result.selectedSourceId; - } - // 2. Fallback const sources = await getMediaSources(); - const twitterSource = sources.find((s) => s.name === "twitter"); - if (twitterSource?.id) { - await chrome.storage.local.set({ selectedSourceId: twitterSource.id }); - return twitterSource.id; + if (sources.length === 0) { + return result.selectedSourceId ?? null; } - if (sources.length > 0 && sources[0].id) { - await chrome.storage.local.set({ selectedSourceId: sources[0].id }); - return sources[0].id; + + const selectableSources = sources.filter( + (source): source is SafeMediaSource & { id: string } => + typeof source.id === "string", + ); + const resolved = resolveEffectiveSourceId( + selectableSources, + result.selectedSourceId, + "twitter", + ); + if (!resolved?.id) { + return result.selectedSourceId ?? null; } - return null; + if (resolved.id !== result.selectedSourceId) { + await chrome.storage.local.set({ selectedSourceId: resolved.id }); + } + return resolved.id; } async function postDownloads(items: TweetMetadata[]) { diff --git a/apps/xtracter/src/popup/index.tsx b/apps/xtracter/src/popup/index.tsx index c90316526..90ef56843 100644 --- a/apps/xtracter/src/popup/index.tsx +++ b/apps/xtracter/src/popup/index.tsx @@ -1,5 +1,6 @@ import { getClient } from "@ext/api"; import type { MediaSource, TweetMetadata } from "@ext/schema"; +import { resolveEffectiveSourceId } from "@ext/utils/source-selection"; import { createSignal, For, onMount, Show } from "solid-js"; import { render } from "solid-js/web"; @@ -17,17 +18,19 @@ function Popup() { const [exportStatus, setExportStatus] = createSignal(""); const [uploadStatus, setUploadStatus] = createSignal(""); + let selectRef: HTMLSelectElement | undefined; + let fetchSeq = 0; + const loadSettings = async () => { const settings: { apiUrl?: string; selectedSourceId?: string } = await chrome.storage.local.get(["selectedSourceId", "apiUrl"]); if (settings.apiUrl) setApiUrl(settings.apiUrl); - if (settings.selectedSourceId) - setSelectedSourceId(settings.selectedSourceId); - await fetchSources(); + await fetchSources(settings.selectedSourceId); }; - const fetchSources = async () => { + const fetchSources = async (preferredId?: string) => { + const seq = ++fetchSeq; setIsLoading(true); setStatus("Loading sources..."); setStatusType("info"); @@ -36,24 +39,25 @@ function Popup() { const resp: MediaSource[] = await chrome.runtime.sendMessage({ type: "GET_SOURCES", }); + if (seq !== fetchSeq) return; setSources(resp || []); - const hasSelectedSource = resp?.some((s) => s.id === selectedSourceId()); - if ( - resp && - resp.length > 0 && - (!selectedSourceId() || !hasSelectedSource) - ) { - const firstId = resp[0].id; - setSelectedSourceId(firstId); - await chrome.storage.local.set({ selectedSourceId: firstId }); + const previousId = preferredId ?? selectedSourceId(); + const resolved = resolveEffectiveSourceId(resp ?? [], previousId); + if (resolved) { + setSelectedSourceId(resolved.id); + if (selectRef) selectRef.value = resolved.id; + if (resolved.id !== previousId) { + await chrome.storage.local.set({ selectedSourceId: resolved.id }); + } } setStatus(""); } catch (_err) { + if (seq !== fetchSeq) return; setStatus("Failed to load sources. Check API URL."); setStatusType("error"); } finally { - setIsLoading(false); + if (seq === fetchSeq) setIsLoading(false); } }; @@ -160,6 +164,7 @@ function Popup() { ( + + {itemProps.item.rawValue.label} + + )} + onChange={(value) => { + if (value) { + const provider = AiProviderSchema.parse(value.value); + props.onProviderChange(provider); + if (provider !== props.provider && props.device) { + props.onDeviceChange(""); + } + } + }} + options={PROVIDER_OPTIONS} + optionTextValue="label" + optionValue="value" + value={selectedOption()} + > + + > + {(state) => state.selectedOption()?.label ?? "自動選択 (Auto)"} + + + + + +

+ ローカル推論に使用するproviderを選択します。リモートAIサーバー指定時はリモート側の設定が適用されます。 +

+ + +
+ + props.onDeviceChange(event.currentTarget.value)} + placeholder={getDevicePlaceholder(props.provider)} + value={props.device ?? ""} + /> + +

+ {getDeviceDescription(props.provider)} +

+ +

+ 現在のproviderではdevice指定は使用されません。 +

+
+
+ + ); +} diff --git a/packages/ui/src/query-options/index.ts b/packages/ui/src/query-options/index.ts index 81fd29f6d..34dc91864 100644 --- a/packages/ui/src/query-options/index.ts +++ b/packages/ui/src/query-options/index.ts @@ -20,8 +20,11 @@ export { } from "./ips-query"; export { buildJobsQueryOptions, + DEFAULT_JOBS_PAGE_SIZE, defaultJobsQueryConfig, + defaultJobsQueryInput, jobsQueryKeys, + updateJobProgress, } from "./jobs-query"; export { buildMediaDetailsQueryOptions, diff --git a/packages/ui/src/query-options/jobs-query.test.ts b/packages/ui/src/query-options/jobs-query.test.ts new file mode 100644 index 000000000..6dd001d1b --- /dev/null +++ b/packages/ui/src/query-options/jobs-query.test.ts @@ -0,0 +1,53 @@ +import type { JobListResponse } from "@solid-imager/core/domain/jobs/schemas"; +import { describe, expect, it } from "vitest"; +import { updateJobProgress } from "./jobs-query"; + +const jobList: JobListResponse = { + items: [ + { + artifact: null, + attemptCount: 1, + cancelRequestedAt: null, + cancelledAt: null, + createdAt: new Date("2026-01-01T00:00:00.000Z"), + error: null, + finishedAt: null, + id: "00000000-0000-4000-8000-000000000001", + mediaSourceId: null, + parentId: null, + progress: { failed: 2, processed: 1, total: 10 }, + startedAt: new Date("2026-01-01T00:00:01.000Z"), + status: "in_progress", + targetMediaId: null, + type: "batch_tagging_parent", + updatedAt: new Date("2026-01-01T00:00:02.000Z"), + }, + ], + total: 1, +}; + +describe("updateJobProgress", () => { + it("updates a matching cached job while preserving failure counts", () => { + const updated = updateJobProgress(jobList, { + jobId: "00000000-0000-4000-8000-000000000001", + processed: 7, + total: 12, + }); + + expect(updated?.items[0]?.progress).toEqual({ + failed: 2, + processed: 7, + total: 12, + }); + }); + + it("does not replace a list that does not contain the event job", () => { + const updated = updateJobProgress(jobList, { + jobId: "00000000-0000-4000-8000-000000000002", + processed: 7, + total: 12, + }); + + expect(updated).toBe(jobList); + }); +}); diff --git a/packages/ui/src/query-options/jobs-query.ts b/packages/ui/src/query-options/jobs-query.ts index b84cf3bae..b8259dd63 100644 --- a/packages/ui/src/query-options/jobs-query.ts +++ b/packages/ui/src/query-options/jobs-query.ts @@ -2,10 +2,18 @@ import type { JobListRequest, JobListResponse, } from "@solid-imager/core/domain/jobs/schemas"; +import type { JobProgressEvent } from "@solid-imager/core/domain/sources/events"; import { queryOptions } from "@tanstack/solid-query"; +export const DEFAULT_JOBS_PAGE_SIZE = 200; +export const defaultJobsQueryInput = { + limit: DEFAULT_JOBS_PAGE_SIZE, + offset: 0, +} satisfies JobListRequest; + export const jobsQueryKeys = { all: () => ["jobs"] as const, + listPrefix: () => ["jobs", "list"] as const, list: (input: JobListRequest) => ["jobs", "list", input] as const, detail: (jobId: string) => ["jobs", "detail", jobId] as const, }; @@ -24,3 +32,26 @@ export function buildJobsQueryOptions( ...defaultJobsQueryConfig, }); } + +export function updateJobProgress( + data: JobListResponse | undefined, + event: JobProgressEvent, +): JobListResponse | undefined { + if (!data || !event.jobId) return data; + + let updated = false; + const items = data.items.map((job) => { + if (job.id !== event.jobId) return job; + updated = true; + return { + ...job, + progress: { + ...(job.progress ?? { failed: 0 }), + processed: event.processed, + total: event.total, + }, + }; + }); + + return updated ? { ...data, items } : data; +} diff --git a/packages/ui/src/screens/config-screen.tsx b/packages/ui/src/screens/config-screen.tsx index 7535e5e74..8a027ab30 100644 --- a/packages/ui/src/screens/config-screen.tsx +++ b/packages/ui/src/screens/config-screen.tsx @@ -9,6 +9,7 @@ import { FormFieldMessage, getFormErrorMessage, } from "../form-message"; +import { InferenceDeviceFields } from "../inference-device-fields"; import { Input } from "../input"; import { Label } from "../label"; import { Switch, SwitchControl, SwitchLabel, SwitchThumb } from "../switch"; @@ -286,6 +287,31 @@ export function ConfigScreen(props: ConfigScreenProps) { )} + + {(providerField) => ( + + {(deviceField) => ( + + deviceField().handleChange(device || undefined) + } + onProviderChange={(provider) => + providerField().handleChange(provider) + } + provider={providerField().state.value ?? "auto"} + providerError={getFormErrorMessage( + providerField().state.meta.errors[0], + )} + idPrefix="legacy-ai-inference" + /> + )} + + )} + diff --git a/packages/ui/src/screens/v2-config-screen.tsx b/packages/ui/src/screens/v2-config-screen.tsx index 2e425e8d8..b338d091b 100644 --- a/packages/ui/src/screens/v2-config-screen.tsx +++ b/packages/ui/src/screens/v2-config-screen.tsx @@ -28,6 +28,7 @@ import { FormFieldMessage, getFormErrorMessage, } from "../form-message"; +import { InferenceDeviceFields } from "../inference-device-fields"; import { Input } from "../input"; import { Label } from "../label"; import { Switch, SwitchControl, SwitchLabel, SwitchThumb } from "../switch"; @@ -384,6 +385,31 @@ export function V2ConfigScreen(props: V2ConfigScreenProps) { )} + + {(providerField) => ( + + {(deviceField) => ( + + deviceField().handleChange(device || undefined) + } + onProviderChange={(provider) => + providerField().handleChange(provider) + } + provider={providerField().state.value ?? "auto"} + providerError={getFormErrorMessage( + providerField().state.meta.errors[0], + )} + idPrefix="v2-ai-inference" + /> + )} + + )} + diff --git a/packages/ui/src/screens/v2-jobs-screen.tsx b/packages/ui/src/screens/v2-jobs-screen.tsx index 23ed4c3cd..3c05a95a2 100644 --- a/packages/ui/src/screens/v2-jobs-screen.tsx +++ b/packages/ui/src/screens/v2-jobs-screen.tsx @@ -4,6 +4,8 @@ import { type JobListResponse, } from "@solid-imager/core/domain/jobs/schemas"; import Ban from "lucide-solid/icons/ban"; +import ChevronLeft from "lucide-solid/icons/chevron-left"; +import ChevronRight from "lucide-solid/icons/chevron-right"; import CircleAlert from "lucide-solid/icons/circle-alert"; import CircleCheck from "lucide-solid/icons/circle-check"; import Clock3 from "lucide-solid/icons/clock-3"; @@ -55,6 +57,15 @@ const JOB_FILTERS = [ type JobFilter = (typeof JOB_FILTERS)[number]["value"]; +export type V2JobsPagination = { + canNext: boolean; + canPrevious: boolean; + current: number; + onNext: () => void; + onPrevious: () => void; + total: number; +}; + export type V2JobsScreenProps = { isRefreshing: Accessor; jobs: Accessor; @@ -62,6 +73,7 @@ export type V2JobsScreenProps = { onRetry: (jobId: string) => void | Promise; onCancel: (jobId: string) => void | Promise; onDownload: (job: JobDto) => void | Promise; + page: Accessor; state: Accessor>; }; @@ -609,6 +621,53 @@ export function V2JobsScreen(props: V2JobsScreenProps) { )} + 1}> + + diff --git a/packages/ui/src/search-history-client.ts b/packages/ui/src/search-history-client.ts new file mode 100644 index 000000000..3d8fc652e --- /dev/null +++ b/packages/ui/src/search-history-client.ts @@ -0,0 +1,19 @@ +import type { SearchSnapshotsOrpcLike } from "@solid-imager/core/domain/contract/search-snapshots-client"; +import type { + SafeSearchSnapshot, + SearchSnapshotState, +} from "@solid-imager/core/domain/search/history"; + +export type SearchHistoryClient = { + capture: (state: SearchSnapshotState) => Promise<{ id: string }>; + get: (id: string) => Promise; +}; + +export function createSearchHistoryClient( + orpc: SearchSnapshotsOrpcLike, +): SearchHistoryClient { + return { + capture: async (state) => await orpc.searchSnapshots.capture({ state }), + get: async (id) => await orpc.searchSnapshots.get({ id }), + }; +} diff --git a/packages/ui/src/search-history-route.ts b/packages/ui/src/search-history-route.ts new file mode 100644 index 000000000..d3672d4d9 --- /dev/null +++ b/packages/ui/src/search-history-route.ts @@ -0,0 +1,5 @@ +import { z } from "zod"; + +export const searchHistoryQuerySchema = z.object({ + search: z.uuid({ version: "v4" }).optional(), +}); diff --git a/packages/ui/src/source-media-page.tsx b/packages/ui/src/source-media-page.tsx index d0432e143..26b9c265d 100644 --- a/packages/ui/src/source-media-page.tsx +++ b/packages/ui/src/source-media-page.tsx @@ -9,11 +9,9 @@ import type { TagResponse } from "@solid-imager/core/domain/tags/schemas"; import { createQuery, useQueryClient } from "@tanstack/solid-query"; import type { Accessor, Component, JSX } from "solid-js"; import { isServer } from "solid-js/web"; -import { - type SearchPersistenceSurface, - useCurrentSearchPersistence, -} from "./hooks/use-current-search-persistence"; +import type { SearchPersistenceSurface } from "./hooks/use-current-search-persistence"; import type { MediaSourceEventTransport } from "./hooks/use-media-source-events"; +import { useSearchHistoryPersistence } from "./hooks/use-search-history-persistence"; import { type SourceMediaPageActions, type SourceMediaPagePresetClient, @@ -22,6 +20,7 @@ import { import { MediaListActions } from "./media-list-actions"; import { toQueryUiState } from "./query-state"; import type { SourceMediaScreenProps } from "./screens/source-media-screen.types"; +import type { SearchHistoryClient } from "./search-history-client"; // biome-ignore lint/suspicious/noExplicitAny: oRPC query option factories do not satisfy Solid Query's overloaded public type type QueryOptionFactory<_TData> = () => any; @@ -64,6 +63,7 @@ export type SourceMediaPageProps = { selectedCount?: () => number; onEnterBulkSelectMode?: () => void; persistenceSurface?: SearchPersistenceSurface; + searchHistoryClient: SearchHistoryClient; /** The route owns the presentation surface (legacy, v2, or another host). */ screenComponent: Component; scrollContainerSelector?: string; @@ -71,10 +71,11 @@ export type SourceMediaPageProps = { export function SourceMediaPage(props: SourceMediaPageProps): JSX.Element { const queryClient = useQueryClient(); - const isSearchStateRestored = useCurrentSearchPersistence( - props.mediaSourceId, - { surface: props.persistenceSurface }, - ); + const searchHistory = useSearchHistoryPersistence(props.mediaSourceId, { + client: props.searchHistoryClient, + surface: props.persistenceSurface, + }); + const isSearchStateRestored = searchHistory.isRestored; const tags = createQuery( clientOnlyQueryOptions(props.tagsQueryOptions), @@ -127,8 +128,10 @@ export function SourceMediaPage(props: SourceMediaPageProps): JSX.Element { sortOrder: props.sortOrder, onThumbnailReady: props.onThumbnailReady, isSearchStateRestored, + commitSearchHistory: searchHistory.commitNow, enableVirtualization: props.enableVirtualization, scrollContainerSelector: props.scrollContainerSelector, + historyEntryKey: searchHistory.historyEntryKey, }); const renderActions: SourceMediaScreenProps["renderActions"] = (actions) => ( diff --git a/vitest.config.ts b/vitest.config.ts index 8f97cff11..04b2dd10a 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -6,6 +6,7 @@ export default defineConfig({ "apps/cli/vitest.config.ts", "apps/server/vitest.unit.config.ts", "apps/server/vitest.integration.config.ts", + "apps/xtracter/vitest.config.ts", "packages/core/vitest.config.ts", "packages/ui/vitest.config.ts", ],