Compare commits
151 Commits
584a92b7cd
...
v0.2.0
| Author | SHA1 | Date | |
|---|---|---|---|
| cad3b9c57d | |||
| e551b15aca | |||
| 0b4459365d | |||
| 4aa74d535b | |||
| 48df4f2965 | |||
| 2bc4a98164 | |||
| 6923777345 | |||
| 96e62cb7c1 | |||
| 42564a93e0 | |||
| b8d009c973 | |||
| dcc1612802 | |||
| 2c699a5aac | |||
| ca5c500e18 | |||
| 782cf0ea08 | |||
| 5004a2d01a | |||
| 9a282dda86 | |||
| b23212ea1c | |||
| a791f112f5 | |||
| 7020a6b6cf | |||
| bf38fac30d | |||
| 79e2e28979 | |||
| aa3fe2062d | |||
| af1a443a64 | |||
| 302a3151ef | |||
| d7c3cbd683 | |||
| 2d567c0810 | |||
| 5ff3ff53a6 | |||
| 827e1a8ecf | |||
| 32c6ae09d6 | |||
| 44179c83a7 | |||
| 4fcc42f356 | |||
| aa3d843a4b | |||
| 01faec9155 | |||
| 3242897a3b | |||
| 8f424773d2 | |||
| 2149b4cad5 | |||
| 2901425f42 | |||
| 1074c875a3 | |||
| 58ecb03070 | |||
| 2c0b928bf5 | |||
| fe312e7678 | |||
| 52ac2543ec | |||
| fbf8a7878c | |||
| 4d41f3744f | |||
| c27662dd74 | |||
| ee2a1b204e | |||
| 6806703363 | |||
| 90fd6f4fed | |||
| 053a2bd846 | |||
| 54016df830 | |||
| 5d46ee5b94 | |||
| 83081928f6 | |||
| e374ff6b02 | |||
| 3ab9357d6f | |||
| fe65bc6f38 | |||
| 68932b55c5 | |||
| f1116c6c26 | |||
| b92b850d02 | |||
| bf04df7484 | |||
| d29a779c13 | |||
| b7e82dbf91 | |||
| 749b23723a | |||
| 68d19d219e | |||
| 31b46327fd | |||
| 29d9106039 | |||
| a78111c8d4 | |||
| 4cdbc54d18 | |||
| d5b93b2e21 | |||
| 257b2b54e7 | |||
| d619b01f2e | |||
| 1a971899d1 | |||
| 8fe5daf25d | |||
| 619bd0c9d2 | |||
| 996bb71375 | |||
| 0d9229635b | |||
| cdb8aa20b9 | |||
| d2af84d9e8 | |||
| 68a9df5ab3 | |||
| 79ce458fd5 | |||
| a9a8f8422e | |||
| ab7022e118 | |||
| 23e9850c7a | |||
| c111032d99 | |||
| c13f78c68b | |||
| f2939d70ab | |||
| 8dbabc2d9e | |||
| 5bc397af01 | |||
| af3c8418ee | |||
| 9144be2518 | |||
| d81624573d | |||
| 949382f28c | |||
| e4a63c8bb0 | |||
| 1685134116 | |||
| 705f8c2e56 | |||
| 52d54d2404 | |||
| 3a2b134103 | |||
| 71ad7bf762 | |||
| 992417710f | |||
| 4c6da99507 | |||
| 24d4e82950 | |||
| 7a18011b0f | |||
| cebd709391 | |||
| d55e4c7502 | |||
| a40a2e8d12 | |||
| 2ce1547844 | |||
| 623aabbb51 | |||
| f65fd350cc | |||
| 86a1a53289 | |||
| ebf16e8cb9 | |||
| e7d9c39fd1 | |||
| 136d74a81b | |||
| bb0038e0a1 | |||
| 90dec3b212 | |||
| e3fde46e91 | |||
| a12e81d8bd | |||
| 6bef90b7fb | |||
| 55cd3b5aa7 | |||
| c878970180 | |||
| 1a95e31f78 | |||
| e1e89b0f87 | |||
| 0909b58110 | |||
| 4f9ab0b821 | |||
| a06e76c7a7 | |||
| 1e008244ae | |||
| ebed194f17 | |||
| 3684b98d55 | |||
| 74a4134f2f | |||
| f66fbe7931 | |||
| 5870205047 | |||
| 3db95a4489 | |||
| c1ab651131 | |||
| 166ffdb189 | |||
| 58750b169a | |||
| 1e148bdf18 | |||
| 7367845f8b | |||
| 50e8bc8e4d | |||
| 779a18f56e | |||
| d027de675b | |||
| b7cfc9177e | |||
| 479de76ebb | |||
| 21f6c30d25 | |||
| 1df75fd490 | |||
| a4c928345c | |||
| ca58c2ddd4 | |||
| c97fec2eb3 | |||
| 9047c8053a | |||
| f049f8c997 | |||
| 3e0f59300e | |||
| 00bf7da344 | |||
| e14dbda41d | |||
| 072c3887cf |
@@ -0,0 +1,22 @@
|
||||
# Keep LF in the working copy for all text files (prettier enforces LF)
|
||||
* text=auto eol=lf
|
||||
|
||||
# Windows scripts that genuinely need CRLF
|
||||
*.bat text eol=crlf
|
||||
*.cmd text eol=crlf
|
||||
*.ps1 text eol=crlf
|
||||
|
||||
# Binary assets — never touch line endings
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
*.webp binary
|
||||
*.gif binary
|
||||
*.ico binary
|
||||
*.icns binary
|
||||
*.woff binary
|
||||
*.woff2 binary
|
||||
*.ttf binary
|
||||
*.otf binary
|
||||
*.mp4 binary
|
||||
*.onnx binary
|
||||
@@ -3,11 +3,40 @@ name: CI
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- '.github/workflows/ci.yml'
|
||||
# CHANGELOG.md is a build input: src/changelog.ts imports it ?raw for
|
||||
# the What's New modal, and changelog.test.ts asserts on its content.
|
||||
- 'CHANGELOG.md'
|
||||
- 'index.html'
|
||||
- 'package.json'
|
||||
- 'pnpm-lock.yaml'
|
||||
- 'pnpm-workspace.yaml'
|
||||
- 'src/**'
|
||||
- 'src-tauri/**'
|
||||
- 'tsconfig*.json'
|
||||
- 'vite.config.ts'
|
||||
pull_request:
|
||||
paths:
|
||||
- '.github/workflows/ci.yml'
|
||||
# CHANGELOG.md is a build input: src/changelog.ts imports it ?raw for
|
||||
# the What's New modal, and changelog.test.ts asserts on its content.
|
||||
- 'CHANGELOG.md'
|
||||
- 'index.html'
|
||||
- 'package.json'
|
||||
- 'pnpm-lock.yaml'
|
||||
- 'pnpm-workspace.yaml'
|
||||
- 'src/**'
|
||||
- 'src-tauri/**'
|
||||
- 'tsconfig*.json'
|
||||
- 'vite.config.ts'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
@@ -15,7 +44,9 @@ jobs:
|
||||
# windows-latest to match the release target — the ML crates (ort, candle)
|
||||
# and the NSIS bundle only ever ship from Windows.
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
CARGO_INCREMENTAL: 0
|
||||
GITEA_STATUS_TOKEN: ${{ secrets.GITEA_STATUS_TOKEN }}
|
||||
steps:
|
||||
- name: Report pending status to Gitea
|
||||
@@ -52,10 +83,14 @@ jobs:
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
|
||||
- name: Install frontend dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Unit tests
|
||||
run: pnpm test:unit
|
||||
|
||||
# tsc + vite build; also produces dist/ which tauri's build script expects
|
||||
- name: Type-check and build frontend
|
||||
run: pnpm build:vite
|
||||
@@ -79,6 +114,10 @@ jobs:
|
||||
working-directory: src-tauri
|
||||
run: cargo clippy --all-targets --locked --no-default-features -- -D warnings
|
||||
|
||||
- name: Rust tests
|
||||
working-directory: src-tauri
|
||||
run: cargo test --locked --no-default-features
|
||||
|
||||
- name: Report final status to Gitea
|
||||
if: always() && github.event_name != 'pull_request' && env.GITEA_STATUS_TOKEN != ''
|
||||
continue-on-error: true
|
||||
|
||||
@@ -8,15 +8,59 @@ on:
|
||||
tags:
|
||||
- 'v*'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Existing release tag to build, for example v0.1.1'
|
||||
required: true
|
||||
type: string
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.ref_name }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release:
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
CARGO_INCREMENTAL: 0
|
||||
GITEA_STATUS_TOKEN: ${{ secrets.GITEA_STATUS_TOKEN }}
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.ref_name }}
|
||||
steps:
|
||||
# refs/tags/ qualification: a branch with a tag-like name must never win
|
||||
# ref resolution. Works for tag pushes too — RELEASE_TAG is the tag name.
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: refs/tags/${{ env.RELEASE_TAG }}
|
||||
|
||||
# On workflow_dispatch GITHUB_SHA is the dispatched branch head, not the
|
||||
# tag's commit — resolve the real one for Gitea commit statuses.
|
||||
- name: Resolve release commit
|
||||
shell: pwsh
|
||||
run: |
|
||||
$sha = git rev-parse HEAD
|
||||
"RELEASE_SHA=$sha" | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
|
||||
- name: Verify release version
|
||||
shell: pwsh
|
||||
run: |
|
||||
if ($env:RELEASE_TAG -notmatch '^v\d+\.\d+\.\d+(-.+)?$') {
|
||||
throw "Release tag '$env:RELEASE_TAG' must look like v0.1.1"
|
||||
}
|
||||
|
||||
$packageVersion = (Get-Content package.json -Raw | ConvertFrom-Json).version
|
||||
$cargoVersion = (Select-String -Path src-tauri/Cargo.toml -Pattern '^version\s*=\s*"(.+)"').Matches[0].Groups[1].Value
|
||||
|
||||
if ($packageVersion -ne $cargoVersion) {
|
||||
throw "package.json version ($packageVersion) does not match Cargo.toml version ($cargoVersion)"
|
||||
}
|
||||
|
||||
if ($env:RELEASE_TAG -ne "v$packageVersion") {
|
||||
throw "Release tag '$env:RELEASE_TAG' does not match project version v$packageVersion"
|
||||
}
|
||||
|
||||
- name: Report pending status to Gitea
|
||||
if: env.GITEA_STATUS_TOKEN != ''
|
||||
continue-on-error: true
|
||||
@@ -36,13 +80,11 @@ jobs:
|
||||
} | ConvertTo-Json
|
||||
Invoke-RestMethod `
|
||||
-Method Post `
|
||||
-Uri "https://git.jezz.wtf/api/v1/repos/JezzWTF/phokus/statuses/$env:GITHUB_SHA" `
|
||||
-Uri "https://git.jezz.wtf/api/v1/repos/JezzWTF/phokus/statuses/$env:RELEASE_SHA" `
|
||||
-Headers $headers `
|
||||
-ContentType "application/json" `
|
||||
-Body $body
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 11
|
||||
@@ -51,6 +93,7 @@ jobs:
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
|
||||
- name: Install Rust stable
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
@@ -71,7 +114,7 @@ jobs:
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
||||
with:
|
||||
tagName: ${{ github.ref_name }}
|
||||
tagName: ${{ env.RELEASE_TAG }}
|
||||
releaseName: 'Phokus v__VERSION__'
|
||||
releaseBody: 'See the assets below to download and install this version.'
|
||||
releaseDraft: true
|
||||
@@ -105,9 +148,11 @@ jobs:
|
||||
description = "GitHub Actions release finished: $env:JOB_STATUS"
|
||||
target_url = $env:GITHUB_RUN_URL
|
||||
} | ConvertTo-Json
|
||||
# RELEASE_SHA is unset if the job died before checkout; fall back.
|
||||
$sha = if ($env:RELEASE_SHA) { $env:RELEASE_SHA } else { $env:GITHUB_SHA }
|
||||
Invoke-RestMethod `
|
||||
-Method Post `
|
||||
-Uri "https://git.jezz.wtf/api/v1/repos/JezzWTF/phokus/statuses/$env:GITHUB_SHA" `
|
||||
-Uri "https://git.jezz.wtf/api/v1/repos/JezzWTF/phokus/statuses/$sha" `
|
||||
-Headers $headers `
|
||||
-ContentType "application/json" `
|
||||
-Body $body
|
||||
|
||||
@@ -35,5 +35,12 @@ dist-ssr
|
||||
*.pyc
|
||||
|
||||
# Bundled CUDA runtime DLLs for the CUDA build (copied from the toolkit
|
||||
# locally; ~600 MB, never committed). See RELEASE_PLAN.md "CUDA release variant".
|
||||
# locally; ~600 MB, never committed).
|
||||
src-tauri/cuda-redist/
|
||||
|
||||
# Playwright
|
||||
/test-results/
|
||||
/playwright-report/
|
||||
/blob-report/
|
||||
/playwright/.cache/
|
||||
/playwright/.auth/
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# Build outputs
|
||||
dist/
|
||||
build/
|
||||
|
||||
# Tauri / Rust (handled by cargo fmt)
|
||||
src-tauri/
|
||||
|
||||
# Lock files & generated
|
||||
pnpm-lock.yaml
|
||||
*.lock
|
||||
|
||||
# Generated
|
||||
src/vite-env.d.ts
|
||||
|
||||
# Public assets
|
||||
public/
|
||||
|
||||
# Website subpackage (has its own config if needed)
|
||||
website/
|
||||
|
||||
# Markdown & docs (hand-written or tool-generated, keep diffs quiet)
|
||||
*.md
|
||||
docs/
|
||||
|
||||
# CI workflows
|
||||
.github/
|
||||
.gitea/
|
||||
|
||||
# Tool-managed config
|
||||
.claude/
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"semi": false,
|
||||
"singleQuote": true,
|
||||
"jsxSingleQuote": false,
|
||||
"trailingComma": "es5",
|
||||
"printWidth": 100,
|
||||
"tabWidth": 2,
|
||||
"useTabs": false,
|
||||
"bracketSpacing": true,
|
||||
"bracketSameLine": false,
|
||||
"arrowParens": "always",
|
||||
"endOfLine": "lf",
|
||||
"plugins": ["prettier-plugin-tailwindcss"]
|
||||
}
|
||||
@@ -5,6 +5,223 @@ All notable changes to Phokus are documented here. The format is based on
|
||||
aims to follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html)
|
||||
(0.x: anything may change between minor versions).
|
||||
|
||||
## [0.2.0] — 2026-07-11
|
||||
|
||||
### Added
|
||||
|
||||
- **What's New** — after updating, Phokus now greets you with a "What's new"
|
||||
toast that opens a tidy in-app tour of the new version. Added, Changed, and
|
||||
Fixed notes are grouped into collapsible sections, so you can skim the good
|
||||
bits without playing "spot the difference".
|
||||
- **Quick theme switch** — right-click the settings cog in the title bar to
|
||||
swap between Phokus, Subtle Light, and Conventional Dark instantly. No Settings
|
||||
detour required.
|
||||
- **Albums** — make your own cross-folder collections without moving a single
|
||||
file. Albums live in their own sidebar section with cover thumbnails, can be
|
||||
created, renamed, reordered, opened, and cleaned up in Manage mode, and deleting
|
||||
one only removes the grouping.
|
||||
- **Gallery multi-select** — hover a thumbnail's top-left corner to start
|
||||
selecting, then use the floating action bar to tag, rate, favorite, add to an
|
||||
album, or delete a whole batch at once. It also works in similar-image, region,
|
||||
and album views, because bulk work should not disappear the moment you need it.
|
||||
- **Colour search** — narrow the Gallery, Timeline, or tag results by dominant
|
||||
colour using toolbar swatches or a custom picker. Great for those "I know it
|
||||
was mostly blue" moments.
|
||||
- **Album-aware similar search** — similar-image and region searches started from
|
||||
an album can now stay inside that album, jump back to the source folder, or
|
||||
search everything.
|
||||
- **Tag manager** — Explore's Tag Cloud now has a Manage mode for renaming,
|
||||
merging, and deleting tags across the whole library.
|
||||
- **Camera info in the lightbox** — the info panel now shows EXIF details like
|
||||
camera, lens, aperture, shutter speed, ISO, and focal length. Geotagged photos
|
||||
also get a browser link for their GPS coordinates, and already-indexed images
|
||||
do not need a re-index.
|
||||
- **Build badge in Settings** — Settings -> Updates now shows whether you are
|
||||
running the CPU build or the CUDA build.
|
||||
- **Choose your tagging model** — Settings -> AI Workspace now lets you pick
|
||||
between the anime-focused WD tagger and JoyTag, which is better suited to photo
|
||||
libraries and stronger on NSFW concepts (if that's your thing, we don't judge).
|
||||
New users get the same choice during the welcome tour, and each model keeps its
|
||||
own confidence threshold instead of sharing one.
|
||||
- **Reset AI tags** — a new reset action in Settings -> AI Workspace and the Tag
|
||||
manager wipes AI-generated tags for a folder or the whole library, cancelling
|
||||
any tagging still in flight. Tag manager rows now show which tags came from the
|
||||
AI, so you know what you are about to lose before you lose it. Manually-added
|
||||
tags are never touched.
|
||||
- **Related tags in Explore** — Hover over a tag in the Tag Cloud to see the tags
|
||||
that most often appear with it, complete with connection lines and image counts.
|
||||
Handy for finding little clusters you did not know were there.
|
||||
- **Pause workers for longer** — Settings -> General can now remember per-folder
|
||||
worker pauses across app restarts, useful for folders you want to keep in the
|
||||
library but leave out of background processing for now.
|
||||
- **Editable folder path** — the folder picker now has an address bar, so you can
|
||||
paste a path directly while still using breadcrumbs for quick jumps.
|
||||
- **Slideshow mode** — turn the lightbox into a fullscreen, image-only slideshow
|
||||
from whatever collection you are already browsing.
|
||||
- **Add to album from the right-click menu** — right-click any image in the
|
||||
Gallery or Timeline and file it straight into an album from the new "Add to
|
||||
Album" submenu. One image, one click, zero ceremony.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Settings got a spring clean** — preferences are now organised into General,
|
||||
Media, Updates & Setup, Storage, and AI Workspace pages, so update and
|
||||
maintenance controls no longer hide at the bottom of unrelated sections.
|
||||
- **Menus got their act together** — right-click menus (images, folders,
|
||||
albums, the theme switcher) and every dropdown (sort, folder scope, settings,
|
||||
sidebar) now share one style with one set of manners: they stay on screen
|
||||
instead of wandering off the edge, all close on Escape, and right-click menus
|
||||
can do proper submenus now. Subtle Light dresses them all the same way too,
|
||||
instead of saving the nice outfit for one dropdown.
|
||||
- **Neater lightbox details** — image and video metadata now sits in two columns,
|
||||
so the info panel shows more at a glance with less scrolling.
|
||||
- **Faster Explore revisits** — returning to a folder's visual clusters should
|
||||
feel much faster now, even in big libraries.
|
||||
- **Calmer Tag Cloud during AI tagging** — Explore no longer keeps hammering the
|
||||
tag list while a folder is actively being tagged, so tagging stays smoother and
|
||||
the cloud catches up once the work settles.
|
||||
- **Faster first-time clustering** — large libraries build their first visual
|
||||
clusters much more quickly, while still keeping the groups nicely balanced.
|
||||
- **Better tag browsing** — the Tag manager now has live search, sorting
|
||||
(most-used, least-used, A-Z, and Z-A), smooth scrolling for huge tag lists, and
|
||||
it keeps your filter/sort in place while you edit.
|
||||
- **Safer deletion** — deleting media now asks for confirmation and clearly says
|
||||
the file is being removed from disk. This covers gallery bulk delete and the
|
||||
Duplicate Finder.
|
||||
- **Clearer update progress** — Settings -> Updates now shows a real download
|
||||
progress bar with a percentage instead of the old lonely "Downloading" label.
|
||||
- **Better narrow-window layout** — the toolbar, filters, search box, colour
|
||||
picker, sidebar, and lightbox info panel now adapt more gracefully when the
|
||||
window is short on space.
|
||||
- **Tidier Explore clusters** — busier clusters get more room, dense groups
|
||||
overlap less, and everything should stay easier to read and click.
|
||||
- **Faster CPU tagging** — CPU-only AI tagging can now use multiple cores while
|
||||
leaving some breathing room for the rest of the app. GPU tagging is unchanged.
|
||||
- **Smoother tooltips** — Phokus now uses its custom tooltip style across more of
|
||||
the app instead of falling back to the native browser tooltip.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Explore no longer flashes the last folder** — switching folders now clears
|
||||
the old clusters/tags and shows a loading state while the new folder catches
|
||||
up.
|
||||
- **Ratings keep your search order** — if you ever rated an image mid-search and
|
||||
watched your results reshuffle themselves, that's over. Similar-image, region,
|
||||
semantic, tag, and album results now stay put.
|
||||
- **Update progress comes back when you need it** — if you dismiss the update
|
||||
prompt and later start the update from the title bar or Settings, the progress
|
||||
toast now reappears instead of hiding away in Settings.
|
||||
- **Subtle Light cleanup** — fixed dark or hard-to-read surfaces, hover states,
|
||||
dialogs, updater buttons, onboarding controls, and green action buttons in the
|
||||
light theme.
|
||||
- **No more self-indexing loops** — adding a broad folder like your whole user
|
||||
profile used to send Phokus off indexing its own thumbnail cache, generating
|
||||
thumbnails of thumbnails until the end of time. It now skips its own app-data
|
||||
directory.
|
||||
- **Background tasks show the active work first** — when one folder is paused and
|
||||
another is processing, the active folder gets the main spot in the background
|
||||
tasks bar.
|
||||
- **First launch fits smaller screens** — on 1366x768-style displays, fresh
|
||||
installs used to open with part of the app tucked below the taskbar. The window
|
||||
now clamps itself to the usable monitor area.
|
||||
- **Explore is clearer in Subtle Light** — cluster captions, buttons, cloud
|
||||
words, hover glows, and the new connection lines now use stronger light-theme
|
||||
colours.
|
||||
- **Explore got a few sharp edges sanded down** — Cluster Cloud uses the in-app
|
||||
tooltip, singular counts now say "1 image", and the folder-scope dropdown no
|
||||
longer hides behind cluster cards.
|
||||
- **AI tagging stays responsive** — starting a big tagging job used to turn the
|
||||
rest of the app into a slideshow. GPU tagging now works in smaller bursts with
|
||||
brief pauses between them, so the UI keeps moving and the first results land
|
||||
sooner.
|
||||
- **Lightbox AI tags wake up on time** — the lightbox's AI tags action no longer
|
||||
stays disabled until you happen to open Settings, and it switches on as soon as
|
||||
a model download finishes.
|
||||
- **Noisy AI tags get cleaned up** — generic low-signal tags from WD and JoyTag
|
||||
are filtered before they are saved, and matching older generated tags are
|
||||
cleaned up on startup. Your manually-added tags are left alone.
|
||||
- **Selected Folders starts empty** — choosing "Selected Folders" for AI tagging
|
||||
no longer pre-selects the first folder. You decide exactly what gets queued.
|
||||
- **A handful of tiny UI papercuts are gone** — the zoom buttons now show the
|
||||
right tile size when you hover them, the folder picker no longer adds an odd
|
||||
trailing slash to Windows drive breadcrumbs, the search field's clear button
|
||||
no longer sits a few pixels too high, and menu labels no longer highlight like
|
||||
text when you drag across them.
|
||||
|
||||
## [0.1.1] — 2026-06-23
|
||||
|
||||
### Added
|
||||
|
||||
- **Custom multi-folder picker** — replaces the native OS dialog with an
|
||||
in-app folder browser that lets you navigate, stage folders from multiple
|
||||
locations, and add them all in one go. Duplicate roots are skipped
|
||||
automatically; partially-failed batches remove successfully-added entries
|
||||
from the staging panel so only failed folders remain to retry.
|
||||
- **Rebuild semantic index** maintenance action in Settings — drops and
|
||||
recreates the vector tables at the current model dimension, then re-queues
|
||||
every image for embedding. Fixes "dimension mismatch" search errors that
|
||||
occur after switching between CLIP models with different output sizes.
|
||||
- **Video playback settings** — new Video Playback group in Settings with two
|
||||
persisted toggles: "Autoplay in lightbox" (default on) and "Start muted"
|
||||
(default off). Settings apply to the next opened video rather than the
|
||||
current one.
|
||||
- **Timeline scrubber** — a year/month rail on the Timeline view that jumps to
|
||||
any period in the library. Timeline now loads the full filtered set so the
|
||||
scrubber spans the whole library instead of just the first page.
|
||||
- **Folder reordering** in the sidebar — drag-and-drop (with edge auto-scroll)
|
||||
or keyboard (↑/↓ on the drag handle), with the custom order persisted across
|
||||
sessions; the Libraries list also gains A–Z / Z–A / Custom sort.
|
||||
- Failed AI-tagging jobs can now be located from the background worker prompt,
|
||||
including a gallery filter for images with failed tags and an expanded list
|
||||
of failed filenames/errors.
|
||||
- A new theme system adds Phokus, Subtle Light, and Conventional Dark chrome
|
||||
options across the app.
|
||||
- First-run onboarding now includes an inline theme picker so new users can
|
||||
choose their preferred app chrome before continuing the tour.
|
||||
|
||||
### Changed
|
||||
|
||||
- Settings sections are reordered — General is now the first and default
|
||||
section instead of AI Workspace.
|
||||
- The Duplicate Finder group list is now virtualised — only on-screen cards
|
||||
mount, so large result sets (e.g. 5,000+ pairs) scroll without lag rather
|
||||
than mounting every thumbnail at once.
|
||||
- The gallery grid is now row-virtualised, so very large libraries scroll
|
||||
smoothly and only on-screen thumbnails are rendered.
|
||||
- Polished the new theme surfaces before release, including readable
|
||||
subtle-light secondary buttons, failed-worker action buttons, and onboarding
|
||||
controls.
|
||||
- Onboarding preview media keeps the dark gallery/media surface regardless of
|
||||
the active chrome theme.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **AVIF thumbnails** — AVIF files are now processed correctly by routing
|
||||
thumbnail generation through the bundled FFmpeg path instead of the Rust
|
||||
image decoder (which has no dav1d dependency). Previously-failed AVIF jobs
|
||||
are requeued on startup; JPEG derivatives are fed to the embedding and
|
||||
tagging pipeline while the lightbox continues to display the original file.
|
||||
- Accent text is now readable in the Subtle Light theme.
|
||||
- Folder picker chevron tooltip now correctly shows "No subfolders" for leaf
|
||||
entries instead of "Open folder" in both branches.
|
||||
- Folder picker Unix breadcrumb root now shows "/" instead of always "Home"
|
||||
for non-home paths such as `/mnt/data`.
|
||||
- Video embedding jobs are no longer claimed before their thumbnail exists, and
|
||||
any that previously failed for that reason are requeued on startup — videos no
|
||||
longer churn through failed embeddings.
|
||||
- Subtle Light theme consistency — the lightbox metadata panel now follows the
|
||||
light chrome while the image canvas stays dark (matching Conventional Dark),
|
||||
and gallery/timeline media badges, duplicate-finder thumbnails, and the window
|
||||
restore icon now theme correctly instead of staying Phokus-dark.
|
||||
- Timeline scrolling is now smooth on large libraries — it virtualizes per row
|
||||
of tiles instead of per month, so a month with thousands of photos no longer
|
||||
mounts every tile at once (thumbnails now load in incrementally as you scroll,
|
||||
matching the All Media grid).
|
||||
- Background worker updates (thumbnails, metadata, embeddings, tags) no longer
|
||||
re-sort the entire loaded image set on every batch. In Timeline, which loads
|
||||
the whole library, this re-sort caused severe lag and could crash the app
|
||||
during background indexing.
|
||||
|
||||
## [0.1.0] — 2026-06-14
|
||||
|
||||
First public release. Windows desktop, distributed as an unsigned NSIS
|
||||
@@ -47,4 +264,6 @@ installer with a built-in updater.
|
||||
Settings, with live size/reclaimable stats.
|
||||
- **Window state** persistence and single-instance handling.
|
||||
|
||||
[0.2.0]: https://github.com/JezzWTF/phokus/releases/tag/v0.2.0
|
||||
[0.1.1]: https://github.com/JezzWTF/phokus/releases/tag/v0.1.1
|
||||
[0.1.0]: https://github.com/JezzWTF/phokus/releases/tag/v0.1.0
|
||||
|
||||
@@ -15,32 +15,67 @@ pnpm dev:app
|
||||
# Frontend only (no Tauri window)
|
||||
pnpm dev:vite
|
||||
|
||||
# Production build
|
||||
pnpm build:app
|
||||
# UI Lab — browser-only frontend with mocked Tauri backend (http://127.0.0.1:1422)
|
||||
pnpm dev:ui
|
||||
|
||||
# Production build (CPU)
|
||||
pnpm build:app:cpu
|
||||
|
||||
# Production build (CUDA / GPU-accelerated)
|
||||
pnpm build:app:cuda
|
||||
|
||||
# Type-check frontend
|
||||
pnpm build:vite
|
||||
|
||||
# Frontend unit tests (Vitest; only picks up src/**/*.test.ts)
|
||||
pnpm test:unit
|
||||
pnpm test:unit:watch
|
||||
|
||||
# Rust unit tests (in-memory SQLite; --no-default-features skips CUDA)
|
||||
pnpm test:rust
|
||||
|
||||
# E2E tests (Playwright against the UI Lab; auto-starts the server)
|
||||
pnpm test:e2e
|
||||
pnpm exec playwright test tests/ui-lab.spec.ts # single file
|
||||
pnpm exec playwright test -g "filename search" # single test by name
|
||||
|
||||
# Formatting (Prettier + prettier-plugin-tailwindcss; cargo fmt for Rust)
|
||||
pnpm format:all
|
||||
```
|
||||
|
||||
Use **pnpm** — never npm.
|
||||
|
||||
There are no test suites configured.
|
||||
Three test layers, none of which exercise the real Tauri window:
|
||||
- **Vitest unit tests** — co-located `*.test.ts` next to the pure logic they cover (`src/store/helpers.ts`, formatters, path utils); fixture factories in `src/test/factories.ts`.
|
||||
- **Rust unit tests** — inline `#[cfg(test)]` modules; DB tests run against in-memory SQLite via the shared `db::test_support` fixture (`test_conn()` + `test_image()`), which registers sqlite-vec and applies both migrations. Reuse it for any new DB-touching tests.
|
||||
- **Playwright e2e smoke tests** in `tests/` — run against the UI Lab (browser mocks).
|
||||
|
||||
## Architecture
|
||||
|
||||
### Frontend (`src/`)
|
||||
|
||||
- **`store.ts`** — single Zustand store (`useGalleryStore`) that owns all app state and all `invoke()` calls to the Tauri backend. Every feature (folders, images, search, similar images, tags, captions, tagger, duplicates) is implemented as store actions here. React components are thin consumers.
|
||||
- **`src/store/`** — single Zustand store (`useGalleryStore`) that owns all app state and all `invoke()` calls to the Tauri backend, split into per-feature slices combined in `index.ts` (which exports `useGalleryStore` and the `GalleryStore` type). `types.ts` holds all interfaces/type unions (including `ImageRecord`); `helpers.ts` holds pure functions and cross-slice module state (search parsing, image sort/merge, request-token guards). Slices: `librarySlice` (folders), `gallerySlice` (image paging/filters/bulk actions), `searchSlice` (search + similar-images), `exploreSlice` (visual clusters, tag cloud, tags), `albumSlice`, `duplicateSlice`, `taggerSlice`, `captionSlice`, `settingsSlice`, `appSlice` (updates, onboarding, ffmpeg, worker pauses); `events.ts` wires the Tauri event listeners (`subscribeToProgress`). Components still call `useGalleryStore(s => s.field)` against one flat state object — the slice split is internal. React components are thin consumers.
|
||||
- **`App.tsx`** — sets up Tauri event listeners (`subscribeToProgress`) and renders the top-level layout (sidebar + active view).
|
||||
- **`src/components/`** — UI components: `Gallery`, `Lightbox`, `Sidebar`, `Toolbar`, `TagCloud`, `DuplicateFinder`, `BackgroundTasks`, `SettingsModal`, `MenuBar`, `TitleBar`.
|
||||
- **`src/components/`** — UI components: `Gallery`, `Lightbox`, `Sidebar`, `Toolbar`, `Timeline`, `ExploreView`, `DuplicateFinder`, `BackgroundTasks`, `SettingsModal`, `TitleBar`.
|
||||
- **`src/components/menu/`** — shared floating-UI primitives: `useDismissable`, `MenuPanel`/`MenuItem`/`SubMenu`, the portal-based `ContextMenu`, and the app-wide `Dropdown`. Build menus, dropdowns, and popovers on these instead of hand-rolling.
|
||||
- State management: Zustand v5, no selectors library — components call `useGalleryStore(s => s.field)` directly.
|
||||
- Styling: Tailwind CSS v4 (Vite plugin, no config file).
|
||||
- Virtualized gallery grid: `@tanstack/react-virtual`.
|
||||
- Animation: `framer-motion`.
|
||||
|
||||
### UI Lab (`src/dev/`)
|
||||
|
||||
`pnpm dev:ui` runs the real frontend (same `App.tsx`, store, components, CSS) in a plain browser with Tauri fully mocked — no Rust backend or Tauri window. `src/main.tsx` imports `src/dev/setupMockTauri.ts` before `App` in `ui` mode; `mockBackend.ts` implements an in-memory command backend, with fixtures in `mockFixtures.ts`/`mockScenarios.ts`. Pick a seeded state via `?scenario=` (`rich` default; also `empty`, `new-user`, `just-updated`, `busy`, `duplicates`, `album`, `errors`, `huge`) and a What's New entry via `?changelog=`. `Ctrl+Shift+D` opens the demo panel. Full guide: `docs/ui-lab.md`.
|
||||
|
||||
Rules that keep UI Lab working:
|
||||
- Components that render thumbnails/covers/posters must use `mediaSrc(...)` from `src/lib/mediaSrc.ts`, never `convertFileSrc(...)` directly.
|
||||
- New Tauri commands invoked from the frontend need a mock in `src/dev/mockBackend.ts` (unmocked commands log console errors, which fail the e2e tests).
|
||||
|
||||
UI Lab is for visual/layout work and agent browser inspection. Native behavior (file pickers, real thumbnails, window controls, updater) must still be validated in `pnpm dev:app`.
|
||||
|
||||
### Search modes
|
||||
|
||||
The search bar supports prefix syntax parsed by `parseSearchValue` in `store.ts`:
|
||||
The search bar supports prefix syntax parsed by `parseSearchValue` in `src/store/helpers.ts`:
|
||||
- No prefix / `f:` — filename search (paginated, DB-backed)
|
||||
- `/s <query>` or `s: <query>` — semantic (embedding) search
|
||||
- `/t <tag>` or `t: <tag>` — tag search
|
||||
@@ -64,6 +99,8 @@ Key modules:
|
||||
| `hnsw_index.rs` | In-memory HNSW index wrapper (hnsw_rs) |
|
||||
| `tagger.rs` | WD tagger: ONNX model download, inference, CSV tag loading |
|
||||
| `captioner.rs` | AI captioning (ONNX, disabled in workers but code intact) |
|
||||
| `download.rs` | Resilient file downloads via the system `curl` (resume, stall detection) |
|
||||
| `onnx_runtime.rs` | Shared ONNX Runtime DLL provisioning + `ort` init (used by tagger and captioner; DLLs live in the caption model dir for legacy reasons) |
|
||||
| `thumbnail.rs` | Thumbnail generation (image crate + fast_image_resize, FFmpeg for video) |
|
||||
| `media.rs` | FFmpeg sidecar provisioning and probing |
|
||||
| `storage.rs` | `StorageProfile` for tuning worker counts |
|
||||
@@ -84,7 +121,7 @@ Database: SQLite with WAL mode, stored in the Tauri app data directory as `galle
|
||||
|
||||
### Key types
|
||||
|
||||
`ImageRecord` (mirrored in `store.ts` and `db.rs`) is the central data type. It carries embedding status, tagging status, caption data, and media metadata. The frontend type must stay in sync with the Rust struct serialization.
|
||||
`ImageRecord` (mirrored in `src/store/types.ts` and `db.rs`) is the central data type. It carries embedding status, tagging status, caption data, and media metadata. The frontend type must stay in sync with the Rust struct serialization.
|
||||
|
||||
## Development notes
|
||||
|
||||
@@ -92,3 +129,5 @@ Database: SQLite with WAL mode, stored in the Tauri app data directory as `galle
|
||||
- ML inference crates (`candle-*`, `ort`, `image`, `rayon`, `tokenizers`, `xxhash-rust`, `rusqlite`) use `opt-level = 3` in dev profile to keep inference performance acceptable.
|
||||
- The caption worker is intentionally disabled (`lib.rs:73`) — the backend code is intact for future re-enabling.
|
||||
- **Never use `any` type** in TypeScript — look up correct types.
|
||||
- `website/` is a separate Vite project for the marketing site (phokus.jezz.wtf): `pnpm dev:web` / `pnpm build:web`. It is not part of the app build.
|
||||
- `pnpm changelog:add -- --type fixed --message "..."` appends an entry to the `[Unreleased]` section of `CHANGELOG.md`, which also feeds the in-app What's New modal (types: added, changed, deprecated, removed, fixed, security).
|
||||
|
||||
@@ -34,7 +34,7 @@ A local-first desktop media library for browsing, filtering, and curating image
|
||||
| Images | Videos |
|
||||
|--------|--------|
|
||||
| jpg, jpeg, png, gif, bmp | mp4, mov, m4v |
|
||||
| tiff, tif, webp, avif, heic, heif | webm |
|
||||
| tiff, tif, webp, avif | webm |
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -109,13 +109,22 @@ pnpm dev:app
|
||||
# Frontend only
|
||||
pnpm dev:vite
|
||||
|
||||
# Production build
|
||||
pnpm build:app
|
||||
# Browser-only UI Lab with mocked Tauri APIs
|
||||
pnpm dev:ui
|
||||
|
||||
# Production build (CPU)
|
||||
pnpm build:app:cpu
|
||||
|
||||
# Production build (CUDA / GPU-accelerated)
|
||||
pnpm build:app:cuda
|
||||
|
||||
# Type-check the frontend
|
||||
pnpm build:vite
|
||||
```
|
||||
|
||||
For visual frontend work without launching Tauri or the Rust backend, see
|
||||
[Phokus UI Lab](docs/ui-lab.md).
|
||||
|
||||
## How it works
|
||||
|
||||
1. Add a folder from the sidebar — the Rust indexer walks it recursively.
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
# Phokus v0.1.1
|
||||
|
||||
> Draft for the GitHub Release body. Fill in the checksums and trim as needed.
|
||||
|
||||
**Phokus is a local-first desktop media library for Windows** — point it at
|
||||
your image and video folders and it builds a fast, searchable gallery with
|
||||
thumbnails, semantic search, visual discovery, AI tagging, and duplicate
|
||||
cleanup. Everything is processed on your machine; nothing is uploaded.
|
||||
|
||||
This is a quality-of-life release on top of 0.1.0: a new in-app folder
|
||||
picker, themes, smoother scrolling on large libraries, and a batch of fixes.
|
||||
If you're updating from 0.1.0, the built-in updater will fetch this for you.
|
||||
|
||||
## Install / update
|
||||
|
||||
- **Updating from 0.1.0:** the in-app updater will offer 0.1.1 on launch — one
|
||||
click downloads, installs, and relaunches.
|
||||
- **Fresh install:** download `Phokus_0.1.1_x64-setup.exe` below and run it.
|
||||
**Windows SmartScreen will warn** that the publisher is unrecognized — this
|
||||
build is **not code-signed**. Click **More info → Run anyway**.
|
||||
- Requires **Windows 10/11**. WebView2 is fetched automatically if missing.
|
||||
|
||||
NVIDIA users wanting GPU embedding speed can use the
|
||||
`Phokus_0.1.1_x64-cuda-setup.exe` variant instead (larger download; bundles the
|
||||
CUDA runtime DLLs).
|
||||
|
||||
## Highlights
|
||||
|
||||
### Added
|
||||
- **Custom multi-folder picker** — navigate and stage folders from multiple
|
||||
locations and add them in one go, replacing the native OS dialog.
|
||||
- **Themes** — Phokus, Subtle Light, and Conventional Dark chrome, with an
|
||||
inline theme picker in first-run onboarding.
|
||||
- **Timeline scrubber** — a year/month rail to jump anywhere in the library.
|
||||
- **Folder reordering** in the sidebar (drag-and-drop or keyboard), persisted,
|
||||
plus A–Z / Z–A / Custom sort for the Libraries list.
|
||||
- **Video playback settings** — autoplay-in-lightbox and start-muted toggles.
|
||||
- **Rebuild semantic index** maintenance action — fixes "dimension mismatch"
|
||||
search errors after switching CLIP models.
|
||||
- Locate and filter images with failed AI-tagging jobs.
|
||||
|
||||
### Changed
|
||||
- Gallery grid and Duplicate Finder list are now row-virtualised — large
|
||||
libraries and large result sets (5,000+ pairs) scroll without lag.
|
||||
- Settings now open on General by default.
|
||||
|
||||
### Fixed
|
||||
- **AVIF thumbnails** now generate correctly (routed through bundled FFmpeg);
|
||||
previously-failed AVIF jobs are requeued on startup.
|
||||
- Video embedding jobs no longer churn through failed states before their
|
||||
thumbnail exists; previously-failed ones are requeued.
|
||||
- Timeline scrolling is smooth on large libraries (per-row virtualisation);
|
||||
background batches no longer re-sort the whole loaded set.
|
||||
- Numerous Subtle Light theme readability/parity fixes.
|
||||
|
||||
See the [changelog](https://github.com/JezzWTF/phokus/blob/main/CHANGELOG.md)
|
||||
for the full list.
|
||||
|
||||
## Checksums
|
||||
|
||||
```
|
||||
SHA-256 (Phokus_0.1.1_x64-setup.exe) = 1c19cbeb77f38a44149380c42c76b633add65777d317e1f3ff7e45d96d12d287
|
||||
SHA-256 (Phokus_0.1.1_x64-cuda-setup.exe) = a7337ef5ee0478a785b48acc8012e8fc5c957341161d6103409213ad78eb845f
|
||||
```
|
||||
@@ -0,0 +1,85 @@
|
||||
# Phokus v0.2.0
|
||||
|
||||
> Draft for the GitHub Release body. Fill in the checksums and trim as needed.
|
||||
|
||||
**Phokus is a local-first desktop media library for Windows** — point it at
|
||||
your image and video folders and it builds a fast, searchable gallery with
|
||||
thumbnails, semantic search, visual discovery, AI tagging, and duplicate
|
||||
cleanup. Everything is processed on your machine; nothing is uploaded.
|
||||
|
||||
0.2.0 is the biggest update since launch: albums, gallery multi-select with
|
||||
bulk actions, colour search, a second AI tagging model (JoyTag), a full tag
|
||||
manager, camera EXIF details in the lightbox, a slideshow mode, and a large
|
||||
batch of performance and theme fixes. Updating from 0.1.x? The built-in
|
||||
updater will fetch this for you — and afterwards, a new in-app "What's New"
|
||||
tour shows you around.
|
||||
|
||||
## Install / update
|
||||
|
||||
- **Updating from 0.1.x:** the in-app updater will offer 0.2.0 on launch — one
|
||||
click downloads, installs, and relaunches.
|
||||
- **Fresh install:** download `Phokus_0.2.0_x64-setup.exe` below and run it.
|
||||
**Windows SmartScreen will warn** that the publisher is unrecognized — this
|
||||
build is **not code-signed**. Click **More info → Run anyway**.
|
||||
- Requires **Windows 10/11**. WebView2 is fetched automatically if missing.
|
||||
|
||||
NVIDIA users wanting GPU embedding/tagging speed can use the
|
||||
`Phokus_0.2.0_x64-cuda-setup.exe` variant instead (larger download; bundles the
|
||||
CUDA runtime DLLs). Settings → Updates now shows which build you are running.
|
||||
|
||||
## Highlights
|
||||
|
||||
### Added
|
||||
- **Albums** — cross-folder collections without moving files: their own
|
||||
sidebar section with cover thumbnails, create/rename/reorder/manage, and
|
||||
album-aware similar-image search.
|
||||
- **Gallery multi-select** — hover a thumbnail's corner to start selecting,
|
||||
then bulk tag, rate, favorite, add to an album, or delete from a floating
|
||||
action bar. Works in similar-image, region, and album views too.
|
||||
- **Colour search** — filter the Gallery, Timeline, or tag results by dominant
|
||||
colour via toolbar swatches or a custom picker.
|
||||
- **Choose your tagging model** — pick between the anime-focused WD tagger and
|
||||
**JoyTag** (better for photo libraries), each with its own confidence
|
||||
threshold, plus a **Reset AI tags** action that never touches manual tags.
|
||||
- **Tag manager** — rename, merge, and delete tags across the library, with
|
||||
live search and sorting; Explore's Tag Cloud also shows **related tags** on
|
||||
hover.
|
||||
- **Camera info in the lightbox** — EXIF camera, lens, aperture, shutter
|
||||
speed, ISO, focal length, and a map link for geotagged photos.
|
||||
- **Slideshow mode**, **What's New tour after updates**, **quick theme switch**
|
||||
from the title bar, an editable path bar in the folder picker, persistent
|
||||
per-folder worker pauses, and add-to-album from the right-click menu.
|
||||
|
||||
### Changed
|
||||
- **Settings reorganised** into General, Media, Updates & Setup, Storage, and
|
||||
AI Workspace pages.
|
||||
- **Menus unified** — all context menus and dropdowns share one style, stay on
|
||||
screen, close on Escape, and support submenus.
|
||||
- **Faster Explore** — quicker cluster revisits, much faster first-time
|
||||
clustering on large libraries, and a calmer Tag Cloud during active tagging.
|
||||
- **Faster CPU tagging** (multi-core with headroom) and smoother GPU tagging.
|
||||
- **Safer deletion** — deleting media now asks for confirmation and says
|
||||
clearly that files are removed from disk.
|
||||
- Better narrow-window layouts, a real update download progress bar, and a
|
||||
two-column lightbox info panel.
|
||||
|
||||
### Fixed
|
||||
- **No more self-indexing loops** — Phokus now skips its own thumbnail cache
|
||||
when you add a broad folder like your user profile.
|
||||
- **Ratings keep your search order** — rating an image mid-search no longer
|
||||
reshuffles similar-image, region, semantic, tag, or album results.
|
||||
- **AI tagging stays responsive** — big GPU tagging jobs no longer freeze the
|
||||
UI, and noisy low-signal tags are filtered (older ones cleaned up on
|
||||
startup).
|
||||
- First launch now fits smaller screens, Explore no longer flashes the
|
||||
previous folder, and a long list of Subtle Light readability fixes.
|
||||
|
||||
See the [changelog](https://github.com/JezzWTF/phokus/blob/main/CHANGELOG.md)
|
||||
for the full list.
|
||||
|
||||
## Checksums
|
||||
|
||||
```
|
||||
SHA-256 (Phokus_0.2.0_x64-setup.exe) = TBD
|
||||
SHA-256 (Phokus_0.2.0_x64-cuda-setup.exe) = TBD
|
||||
```
|
||||
@@ -0,0 +1,201 @@
|
||||
# Phokus UI Lab
|
||||
|
||||
Phokus UI Lab is a browser-only development mode for visual work on the real
|
||||
Phokus frontend. It runs the same `App.tsx`, Zustand store, components, and CSS
|
||||
as the Tauri app, but installs Tauri JavaScript mocks before the app imports.
|
||||
|
||||
This gives UI agents and contributors a stable browser target without launching
|
||||
the Rust backend or a Tauri window.
|
||||
|
||||
## Run It
|
||||
|
||||
```bash
|
||||
pnpm dev:ui
|
||||
```
|
||||
|
||||
Then open:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:1422
|
||||
```
|
||||
|
||||
The script runs Vite in the custom `ui` mode:
|
||||
|
||||
```bash
|
||||
vite --mode ui --host 127.0.0.1 --port 1422 --strictPort
|
||||
```
|
||||
|
||||
The normal app development commands are unchanged:
|
||||
|
||||
```bash
|
||||
pnpm dev:app # Tauri app + Rust backend
|
||||
pnpm dev:vite # frontend dev server for Tauri dev
|
||||
```
|
||||
|
||||
## Scenarios
|
||||
|
||||
UI Lab reads `?scenario=` from the URL. If no scenario is provided, it uses
|
||||
`rich`.
|
||||
|
||||
| URL | Purpose |
|
||||
| --- | --- |
|
||||
| `/?scenario=rich` | Default realistic library with folders, albums, ratings, favorites, tags, images, and videos |
|
||||
| `/?scenario=empty` | Empty library with no folders or media (onboarding already completed) |
|
||||
| `/?scenario=new-user` | True first run: onboarding tour open, empty library, no tagger model downloaded |
|
||||
| `/?scenario=just-updated` | Rich library that has just been updated — the "What's new" toast fires on launch |
|
||||
| `/?scenario=busy` | Background workers with pending thumbnail, metadata, embedding, caption, and tagging jobs |
|
||||
| `/?scenario=duplicates` | Duplicate Finder opened with duplicate groups already available |
|
||||
| `/?scenario=album` | Gallery opened directly into an album |
|
||||
| `/?scenario=errors` | Broken thumbnails, folder scan errors, failed embeddings, failed tagging, and metadata issues |
|
||||
| `/?scenario=huge` | Large mock library for virtualization and layout checks |
|
||||
|
||||
Examples:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:1422/?scenario=duplicates
|
||||
http://127.0.0.1:1422/?scenario=errors
|
||||
http://127.0.0.1:1422/?scenario=huge
|
||||
```
|
||||
|
||||
## Changelog Previews
|
||||
|
||||
The What's New modal adapts its layout to release size (compact single column
|
||||
for small releases, a two-pane section rail for large ones). UI Lab reads
|
||||
`?changelog=` to override which entry the modal shows:
|
||||
|
||||
| URL | Purpose |
|
||||
| --- | --- |
|
||||
| `/?changelog=unreleased` | The in-progress `[Unreleased]` notes — large release, rail layout |
|
||||
| `/?changelog=small` | Synthetic hotfix-sized entry — compact single-column layout |
|
||||
| `/?changelog=0.1.1` | Any specific released version |
|
||||
|
||||
Open the modal via the demo panel: `Ctrl+Shift+D` → Open "What's new" modal.
|
||||
|
||||
Combine with the scenario above to walk the whole post-update greeting for the
|
||||
next release: `/?scenario=just-updated&changelog=unreleased`.
|
||||
|
||||
## How It Works
|
||||
|
||||
`src/main.tsx` bootstraps the app asynchronously. In `ui` mode it imports
|
||||
`src/dev/setupMockTauri.ts` first, then imports the real `App`.
|
||||
|
||||
That order matters because static imports are hoisted. The Tauri mocks must be
|
||||
installed before `App`, the store, the title bar, or visual components import
|
||||
Tauri APIs.
|
||||
|
||||
The mock setup installs:
|
||||
|
||||
- `mockWindows("main")` for window APIs used by the title bar
|
||||
- `mockConvertFileSrc("windows")` as a baseline Tauri file URL mock
|
||||
- `mockIPC(..., { shouldMockEvents: true })` for `invoke`, `listen`, and `emit`
|
||||
|
||||
The in-memory backend lives in:
|
||||
|
||||
```text
|
||||
src/dev/mockBackend.ts
|
||||
src/dev/mockFixtures.ts
|
||||
src/dev/mockScenarios.ts
|
||||
src/dev/applyMockScenario.ts
|
||||
```
|
||||
|
||||
Happy-path fixture media is generated from existing onboarding images and
|
||||
website screenshots into:
|
||||
|
||||
```text
|
||||
public/dev-media/fixture-*.webp
|
||||
```
|
||||
|
||||
The pack is deliberately small and deterministic, but varied enough for browser
|
||||
screenshots: square, portrait, landscape, monochrome, tinted, framed, and
|
||||
interface-like crops. Synthetic or deliberately broken fixture paths can still
|
||||
use the `mock://` scheme described below.
|
||||
|
||||
## Mock Media
|
||||
|
||||
Visual components should use `mediaSrc(...)` instead of calling
|
||||
`convertFileSrc(...)` directly:
|
||||
|
||||
```ts
|
||||
import { mediaSrc } from "../lib/mediaSrc";
|
||||
|
||||
const src = mediaSrc(image.thumbnail_path);
|
||||
```
|
||||
|
||||
In normal Tauri modes, `mediaSrc` delegates to `convertFileSrc`. In UI Lab,
|
||||
root-relative asset URLs such as `/dev-media/fixture-01.webp` are returned
|
||||
as-is. Paths beginning with `mock://` are also served from `public/dev-media`:
|
||||
|
||||
```text
|
||||
mock://thumb-1.svg -> /dev-media/thumb-1.svg
|
||||
```
|
||||
|
||||
Use `mediaSrc` when adding components that render thumbnails, album covers,
|
||||
preview images, or video posters.
|
||||
|
||||
## Adding A Mock Command
|
||||
|
||||
If the browser console logs an unmocked command, add it to
|
||||
`src/dev/mockBackend.ts`.
|
||||
|
||||
Prefer returning realistic data for commands that affect visible UI. For actions
|
||||
that would touch the machine, return a safe no-op:
|
||||
|
||||
```ts
|
||||
case "open_app_data_folder":
|
||||
return null;
|
||||
```
|
||||
|
||||
When adding fixture data, keep it shaped like the real store/Rust contracts.
|
||||
Most frontend-facing types are exported from `src/store.ts`, so the mocks can
|
||||
stay type-checked against the real UI.
|
||||
|
||||
## Adding A Scenario
|
||||
|
||||
1. Add the scenario name to `MockScenario` and `SCENARIOS` in
|
||||
`src/dev/mockScenarios.ts`.
|
||||
2. Adjust fixture creation in `src/dev/mockFixtures.ts`.
|
||||
3. If the scenario should open a specific view, add that behavior in
|
||||
`src/dev/applyMockScenario.ts`.
|
||||
4. Visit `http://127.0.0.1:1422/?scenario=your-scenario` and check for console
|
||||
errors.
|
||||
|
||||
## What UI Lab Is For
|
||||
|
||||
UI Lab is intended for:
|
||||
|
||||
- visual iteration on the real app shell
|
||||
- layout and responsive checks
|
||||
- state-heavy views like Explore, Timeline, Duplicates, albums, and Settings
|
||||
- AI-agent screenshot/browser inspection
|
||||
- safe UI work without filesystem or Rust-side effects
|
||||
|
||||
It is not a replacement for Tauri app testing. Validate native behavior with
|
||||
`pnpm dev:app` when touching:
|
||||
|
||||
- file or folder pickers
|
||||
- filesystem permissions
|
||||
- real thumbnail/video loading
|
||||
- window drag, minimize, maximize, or close behavior
|
||||
- Rust backend performance
|
||||
- updater installation
|
||||
- WebView2-specific behavior
|
||||
|
||||
## Verification
|
||||
|
||||
Useful checks after changing UI Lab:
|
||||
|
||||
```bash
|
||||
pnpm exec tsc --noEmit
|
||||
pnpm build:vite
|
||||
pnpm dev:ui
|
||||
```
|
||||
|
||||
Then smoke-test at least:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:1422/?scenario=rich
|
||||
http://127.0.0.1:1422/?scenario=empty
|
||||
http://127.0.0.1:1422/?scenario=duplicates
|
||||
http://127.0.0.1:1422/?scenario=errors
|
||||
http://127.0.0.1:1422/?scenario=huge
|
||||
```
|
||||
@@ -1,20 +1,32 @@
|
||||
{
|
||||
"name": "phokus",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.0",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build:app": "tauri build",
|
||||
"build:app:cpu": "tauri build -- --no-default-features",
|
||||
"build:app:cuda": "tauri build --config src-tauri/tauri.cuda.conf.json",
|
||||
"build:vite": "tsc && vite build",
|
||||
"build:web": "cd website && tsc && vite build",
|
||||
"changelog:add": "node tools/changelog-add.mjs",
|
||||
"clean:app": "cd src-tauri && cargo clean",
|
||||
"dev:app": "tauri dev",
|
||||
"dev:app:cpu": "tauri dev -- --no-default-features",
|
||||
"build:app:cpu": "tauri build -- --no-default-features",
|
||||
"build:app:cuda": "tauri build --config src-tauri/tauri.cuda.conf.json",
|
||||
"dev:ui": "vite --mode ui --host 127.0.0.1 --port 1422 --strictPort",
|
||||
"dev:vite": "vite",
|
||||
"dev:web": "cd website && pnpm dev",
|
||||
"format": "prettier --write .",
|
||||
"format:all": "pnpm format && pnpm format:rust",
|
||||
"format:check": "prettier --check .",
|
||||
"format:rust": "cd src-tauri && cargo fmt",
|
||||
"format:rust:check": "cd src-tauri && cargo fmt --check",
|
||||
"preview": "vite preview",
|
||||
"tauri": "tauri"
|
||||
"tauri": "tauri",
|
||||
"test:e2e": "playwright test",
|
||||
"test:rust": "cd src-tauri && cargo test --no-default-features",
|
||||
"test:unit": "vitest run",
|
||||
"test:unit:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-virtual": "^3.13.23",
|
||||
@@ -32,14 +44,19 @@
|
||||
"zustand": "^5.0.12"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.61.1",
|
||||
"@tailwindcss/vite": "^4.2.2",
|
||||
"@tauri-apps/cli": "^2",
|
||||
"@types/d3-force": "^3.0.10",
|
||||
"@types/node": "^26.0.1",
|
||||
"@types/react": "^19.1.8",
|
||||
"@types/react-dom": "^19.1.6",
|
||||
"@vitejs/plugin-react": "^4.6.0",
|
||||
"prettier": "^3.9.4",
|
||||
"prettier-plugin-tailwindcss": "^0.8.0",
|
||||
"tailwindcss": "^4.2.2",
|
||||
"typescript": "~5.8.3",
|
||||
"vite": "^7.0.4"
|
||||
"vite": "^7.0.4",
|
||||
"vitest": "^4.1.9"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { defineConfig, devices } from '@playwright/test'
|
||||
|
||||
/**
|
||||
* Read environment variables from file.
|
||||
* https://github.com/motdotla/dotenv
|
||||
*/
|
||||
// import dotenv from 'dotenv';
|
||||
// import path from 'path';
|
||||
// dotenv.config({ path: path.resolve(__dirname, '.env') });
|
||||
|
||||
/**
|
||||
* See https://playwright.dev/docs/test-configuration.
|
||||
*/
|
||||
export default defineConfig({
|
||||
testDir: './tests',
|
||||
/* Run tests in files in parallel */
|
||||
fullyParallel: true,
|
||||
/* Fail the build on CI if you accidentally left test.only in the source code. */
|
||||
forbidOnly: !!process.env.CI,
|
||||
/* Retry on CI only */
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
/* Opt out of parallel tests on CI. */
|
||||
workers: process.env.CI ? 1 : 4,
|
||||
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
|
||||
reporter: 'html',
|
||||
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
|
||||
use: {
|
||||
/* Base URL to use in actions like `await page.goto('')`. */
|
||||
baseURL: 'http://127.0.0.1:1422',
|
||||
|
||||
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
|
||||
trace: 'on-first-retry',
|
||||
},
|
||||
|
||||
/* Configure projects for major browsers */
|
||||
projects: [
|
||||
{
|
||||
name: 'chromium',
|
||||
use: { ...devices['Desktop Chrome'] },
|
||||
},
|
||||
|
||||
{
|
||||
name: 'webkit',
|
||||
use: { ...devices['Desktop Safari'] },
|
||||
},
|
||||
|
||||
/* Test against mobile viewports. */
|
||||
// {
|
||||
// name: 'Mobile Chrome',
|
||||
// use: { ...devices['Pixel 5'] },
|
||||
// },
|
||||
// {
|
||||
// name: 'Mobile Safari',
|
||||
// use: { ...devices['iPhone 12'] },
|
||||
// },
|
||||
|
||||
/* Test against branded browsers. */
|
||||
// {
|
||||
// name: 'Microsoft Edge',
|
||||
// use: { ...devices['Desktop Edge'], channel: 'msedge' },
|
||||
// },
|
||||
// {
|
||||
// name: 'Google Chrome',
|
||||
// use: { ...devices['Desktop Chrome'], channel: 'chrome' },
|
||||
// },
|
||||
],
|
||||
|
||||
/* Run the Phokus UI Lab (browser-only dev mode, see docs/ui-lab.md) before starting the tests */
|
||||
webServer: {
|
||||
command: 'pnpm exec vite --mode ui --host 127.0.0.1 --port 1422 --strictPort',
|
||||
url: 'http://127.0.0.1:1422',
|
||||
reuseExistingServer: !process.env.CI,
|
||||
timeout: 120_000,
|
||||
},
|
||||
})
|
||||
@@ -1,2 +1,6 @@
|
||||
packages:
|
||||
- website
|
||||
|
||||
allowBuilds:
|
||||
esbuild: true
|
||||
sharp: true
|
||||
|
||||
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 70 KiB |
|
After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 78 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 81 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 81 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 105 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 43 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 55 KiB |
|
After Width: | Height: | Size: 7.1 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 106 KiB |
|
After Width: | Height: | Size: 48 KiB |
|
After Width: | Height: | Size: 37 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 21 KiB |
@@ -0,0 +1,43 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256" role="img" aria-label="Phokus">
|
||||
<title>Phokus</title>
|
||||
|
||||
<!--
|
||||
Phokus app mark — a camera iris.
|
||||
The hexagon in the middle is the lens OPENING; each blade edge sweeps from a
|
||||
corner of the opening out to the rim, all leaning the same way (the pinwheel).
|
||||
|
||||
Tuning knobs (edit and re-open in any browser/Figma):
|
||||
* opening roundness -> the "52" radius in the opening <path> arcs.
|
||||
smaller (toward 30) = rounder/softer hole; larger (toward 90) = flatter, sharper.
|
||||
* blade curve -> the "110" radius in each blade <path>.
|
||||
smaller = more pronounced curve; larger = straighter blade.
|
||||
* blade sweep amount -> the +40deg baked into the blade endpoint (70.71,-84.27).
|
||||
* curve DIRECTION -> the final flag in each "A r r 0 0 X" command (0<->1 flips the bow).
|
||||
* weight -> stroke-width on the <g>.
|
||||
* color -> stroke on the <g>; swap "#e9e9ec" for currentColor to inherit.
|
||||
A brand-accent focal dot is provided at the bottom (commented out).
|
||||
-->
|
||||
|
||||
<rect x="8" y="8" width="240" height="240" rx="52" fill="#0e0f14"/>
|
||||
|
||||
<g transform="translate(128 128)" fill="none" stroke="#e9e9ec" stroke-width="9"
|
||||
stroke-linecap="round" stroke-linejoin="round">
|
||||
|
||||
<!-- outer rim -->
|
||||
<circle r="110"/>
|
||||
|
||||
<!-- lens opening: soft, arc-rounded hexagon -->
|
||||
<path d="M0,-46 A52,52 0 0 0 39.84,-23 A52,52 0 0 0 39.84,23 A52,52 0 0 0 0,46 A52,52 0 0 0 -39.84,23 A52,52 0 0 0 -39.84,-23 A52,52 0 0 0 0,-46 Z"/>
|
||||
|
||||
<!-- blades: one curved edge, swept six times -->
|
||||
<g transform="rotate(0)"><path d="M0,-46 A110,110 0 0 1 70.71,-84.27"/></g>
|
||||
<g transform="rotate(60)"><path d="M0,-46 A110,110 0 0 1 70.71,-84.27"/></g>
|
||||
<g transform="rotate(120)"><path d="M0,-46 A110,110 0 0 1 70.71,-84.27"/></g>
|
||||
<g transform="rotate(180)"><path d="M0,-46 A110,110 0 0 1 70.71,-84.27"/></g>
|
||||
<g transform="rotate(240)"><path d="M0,-46 A110,110 0 0 1 70.71,-84.27"/></g>
|
||||
<g transform="rotate(300)"><path d="M0,-46 A110,110 0 0 1 70.71,-84.27"/></g>
|
||||
</g>
|
||||
|
||||
<!-- optional brand focal point -->
|
||||
<!-- <circle cx="128" cy="128" r="9" fill="#e6a23c"/> -->
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.2 KiB |
@@ -0,0 +1,189 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
# Codex Cloud setup for Phokus.
|
||||
# Paste this script into the Codex Cloud environment setup field, or run it from
|
||||
# the repo root with: bash scripts/codex-cloud-setup.sh
|
||||
#
|
||||
# Goals:
|
||||
# - install Linux packages needed by Tauri/WebKit and native Rust crates
|
||||
# - install JS dependencies with pnpm using the lockfile
|
||||
# - pre-fetch Rust dependencies while setup still has internet access
|
||||
# - keep the environment CPU-safe by avoiding Phokus' default CUDA feature set
|
||||
# - leave Codex with clear verification commands for UI and Rust work
|
||||
|
||||
log() {
|
||||
printf '\n\033[1;36m[phokus-codex]\033[0m %s\n' "$*"
|
||||
}
|
||||
|
||||
warn() {
|
||||
printf '\n\033[1;33m[phokus-codex warning]\033[0m %s\n' "$*" >&2
|
||||
}
|
||||
|
||||
repo_root="$(pwd)"
|
||||
|
||||
if [[ ! -f "package.json" || ! -d "src-tauri" ]]; then
|
||||
warn "This script should be run from the Phokus repository root. Current directory: ${repo_root}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
export CI=1
|
||||
export PNPM_HOME="${PNPM_HOME:-$HOME/.local/share/pnpm}"
|
||||
export PATH="$PNPM_HOME:$HOME/.cargo/bin:$PATH"
|
||||
|
||||
# Persist useful shell defaults for the later Codex agent phase. Codex setup runs
|
||||
# in a separate Bash session, so exports here alone would not survive.
|
||||
if ! grep -q "# Phokus Codex Cloud" "$HOME/.bashrc" 2>/dev/null; then
|
||||
cat >> "$HOME/.bashrc" <<'BASHRC'
|
||||
|
||||
# Phokus Codex Cloud
|
||||
export PNPM_HOME="${PNPM_HOME:-$HOME/.local/share/pnpm}"
|
||||
export PATH="$PNPM_HOME:$HOME/.cargo/bin:$PATH"
|
||||
export CI=1
|
||||
BASHRC
|
||||
fi
|
||||
|
||||
install_apt_packages() {
|
||||
if ! command -v apt-get >/dev/null 2>&1; then
|
||||
warn "apt-get not found; skipping system package installation."
|
||||
return 0
|
||||
fi
|
||||
|
||||
log "Installing Linux system dependencies for Tauri, WebKit, SQLite/native crates, and browser tooling"
|
||||
|
||||
sudo apt-get update
|
||||
|
||||
# Tauri v2 Linux builds need the WebKitGTK/AppIndicator/Rsvg stack. Some base
|
||||
# images expose either the 4.1 or 4.0 WebKit development package, so try the
|
||||
# modern package first and gracefully fall back.
|
||||
local common_packages=(
|
||||
build-essential
|
||||
curl
|
||||
wget
|
||||
file
|
||||
pkg-config
|
||||
libssl-dev
|
||||
libgtk-3-dev
|
||||
libayatana-appindicator3-dev
|
||||
librsvg2-dev
|
||||
patchelf
|
||||
ca-certificates
|
||||
)
|
||||
|
||||
if apt-cache show libwebkit2gtk-4.1-dev >/dev/null 2>&1; then
|
||||
sudo apt-get install -y --no-install-recommends "${common_packages[@]}" libwebkit2gtk-4.1-dev
|
||||
else
|
||||
sudo apt-get install -y --no-install-recommends "${common_packages[@]}" libwebkit2gtk-4.0-dev
|
||||
fi
|
||||
}
|
||||
|
||||
ensure_node_and_pnpm() {
|
||||
log "Preparing Node/pnpm"
|
||||
|
||||
if ! command -v node >/dev/null 2>&1; then
|
||||
warn "Node.js is not available in this image. Pin Node.js 20+ in the Codex environment settings or use a Codex universal image with Node installed."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
node_major="$(node -p "process.versions.node.split('.')[0]")"
|
||||
if [[ "$node_major" -lt 20 ]]; then
|
||||
warn "Phokus expects Node.js 20+. Current version: $(node --version). Pin Node.js 20+ in Codex environment settings."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p "$PNPM_HOME"
|
||||
|
||||
if command -v corepack >/dev/null 2>&1; then
|
||||
corepack enable
|
||||
corepack prepare pnpm@latest --activate
|
||||
fi
|
||||
|
||||
if ! command -v pnpm >/dev/null 2>&1; then
|
||||
npm install -g pnpm
|
||||
fi
|
||||
|
||||
log "Node: $(node --version)"
|
||||
log "pnpm: $(pnpm --version)"
|
||||
}
|
||||
|
||||
ensure_rust() {
|
||||
log "Preparing Rust toolchain"
|
||||
|
||||
if ! command -v rustup >/dev/null 2>&1; then
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal
|
||||
# shellcheck source=/dev/null
|
||||
source "$HOME/.cargo/env"
|
||||
fi
|
||||
|
||||
rustup toolchain install stable --profile minimal
|
||||
rustup default stable
|
||||
rustup component add rustfmt clippy
|
||||
|
||||
log "rustc: $(rustc --version)"
|
||||
log "cargo: $(cargo --version)"
|
||||
}
|
||||
|
||||
install_js_dependencies() {
|
||||
log "Installing frontend dependencies"
|
||||
pnpm install --frozen-lockfile
|
||||
}
|
||||
|
||||
prefetch_rust_dependencies() {
|
||||
log "Pre-fetching Rust dependencies for CPU-safe Tauri checks"
|
||||
|
||||
# Phokus enables candle-cuda by default in Cargo.toml. Codex Cloud usually runs
|
||||
# in a CPU Linux container, so use --no-default-features for checks/builds
|
||||
# unless you intentionally configure a CUDA-capable environment.
|
||||
cargo fetch --manifest-path src-tauri/Cargo.toml --locked
|
||||
|
||||
# This is intentionally a check, not a full release build. It warms the Cargo
|
||||
# cache and catches missing native packages without making setup painfully slow.
|
||||
cargo check --manifest-path src-tauri/Cargo.toml --locked --no-default-features
|
||||
}
|
||||
|
||||
install_playwright_browsers() {
|
||||
log "Installing Playwright Chromium dependencies for UI Lab/browser screenshots"
|
||||
|
||||
# Safe even if no Playwright tests are present yet. Useful for Codex browser
|
||||
# inspection against `pnpm dev:ui`.
|
||||
pnpm exec playwright install --with-deps chromium || warn "Playwright browser install failed; UI work may still run, but browser automation/screenshots may need manual setup."
|
||||
}
|
||||
|
||||
print_next_steps() {
|
||||
cat <<'EOF'
|
||||
|
||||
[phokus-codex] Setup complete.
|
||||
|
||||
Recommended Codex verification commands:
|
||||
pnpm exec tsc --noEmit
|
||||
pnpm build:vite
|
||||
cargo check --manifest-path src-tauri/Cargo.toml --locked --no-default-features
|
||||
|
||||
For visual UI work in Codex/browser environments:
|
||||
pnpm dev:ui
|
||||
open http://127.0.0.1:1422/?scenario=rich
|
||||
|
||||
Other useful UI Lab scenarios:
|
||||
http://127.0.0.1:1422/?scenario=empty
|
||||
http://127.0.0.1:1422/?scenario=duplicates
|
||||
http://127.0.0.1:1422/?scenario=errors
|
||||
http://127.0.0.1:1422/?scenario=huge
|
||||
|
||||
Avoid the below in standard CPU-only Codex Cloud unless you have configured CUDA:
|
||||
pnpm dev:app
|
||||
pnpm build:app:cuda
|
||||
cargo check --manifest-path src-tauri/Cargo.toml
|
||||
EOF
|
||||
}
|
||||
|
||||
main() {
|
||||
install_apt_packages
|
||||
ensure_node_and_pnpm
|
||||
ensure_rust
|
||||
install_js_dependencies
|
||||
prefetch_rust_dependencies
|
||||
install_playwright_browsers
|
||||
print_next_steps
|
||||
}
|
||||
|
||||
main "$@"
|
||||
@@ -4595,7 +4595,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "phokus"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"candle-core",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "phokus"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
description = "Local-first desktop media library"
|
||||
authors = ["JezzWTF"]
|
||||
license = "MIT"
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Capability for the main window",
|
||||
"windows": ["main"],
|
||||
"windows": [
|
||||
"main"
|
||||
],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"opener:default",
|
||||
@@ -19,6 +21,8 @@
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-toggle-maximize",
|
||||
"core:window:allow-is-maximized"
|
||||
"core:window:allow-is-maximized",
|
||||
"core:window:allow-start-dragging",
|
||||
"core:window:allow-start-resize-dragging"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/// AI-generated tags that are too broad/noisy to be useful in this gallery.
|
||||
/// Edit this list to change what the tagger removes. Manual user tags are not
|
||||
/// affected.
|
||||
pub const AI_TAG_REMOVAL_LIST: &[&str] = &["1girl", "1boy", "no humans", "2girls", "2boys"];
|
||||
|
||||
fn normalize_tag_for_removal(tag: &str) -> String {
|
||||
tag.trim()
|
||||
.chars()
|
||||
.filter(|c| !matches!(c, ' ' | '_' | '-'))
|
||||
.flat_map(char::to_lowercase)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn is_removed_ai_tag(tag: &str) -> bool {
|
||||
let normalized = normalize_tag_for_removal(tag);
|
||||
AI_TAG_REMOVAL_LIST
|
||||
.iter()
|
||||
.any(|blocked| normalize_tag_for_removal(blocked) == normalized)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn removed_ai_tags_match_common_spellings() {
|
||||
for tag in [
|
||||
"1girl",
|
||||
"1 girl",
|
||||
"1_girl",
|
||||
"1-girl",
|
||||
"NO_HUMANS",
|
||||
"no humans",
|
||||
] {
|
||||
assert!(is_removed_ai_tag(tag), "{tag} should be removed");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removed_ai_tags_do_not_match_unrelated_tags() {
|
||||
for tag in ["girl", "boy", "humans", "solo", "landscape"] {
|
||||
assert!(!is_removed_ai_tag(tag), "{tag} should be kept");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removed_ai_tags_tolerate_padding_and_mixed_separators() {
|
||||
assert!(is_removed_ai_tag(" 1girl "));
|
||||
assert!(is_removed_ai_tag("1_-_girl"));
|
||||
assert!(is_removed_ai_tag("No Humans"));
|
||||
assert!(!is_removed_ai_tag(""));
|
||||
assert!(!is_removed_ai_tag(" "));
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,6 @@
|
||||
use crate::onnx_runtime::{
|
||||
self, DIRECTML_DLL_FILE, ONNX_RUNTIME_DLL_FILE, ONNX_RUNTIME_PROVIDERS_DLL_FILE,
|
||||
};
|
||||
use anyhow::Result;
|
||||
use hf_hub::{api::sync::Api, Repo, RepoType};
|
||||
use image::{imageops::FilterType, ImageReader};
|
||||
@@ -8,50 +11,16 @@ use ort::session::{builder::GraphOptimizationLevel, Session};
|
||||
use ort::value::{Shape, Tensor};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::borrow::Cow;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Mutex;
|
||||
use std::time::Instant;
|
||||
use tokenizers::Tokenizer;
|
||||
|
||||
// Suppress the console window when spawning curl.exe from the GUI app.
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::os::windows::process::CommandExt;
|
||||
#[cfg(target_os = "windows")]
|
||||
const CREATE_NO_WINDOW: u32 = 0x08000000;
|
||||
|
||||
pub const FLORENCE_MODEL_ID: &str = "onnx-community/Florence-2-base-ft";
|
||||
pub const FLORENCE_CAPTION_MODEL_NAME: &str = "florence-2-base-ft-onnx-q4";
|
||||
const ONNX_RUNTIME_NUGET_URL: &str =
|
||||
"https://www.nuget.org/api/v2/package/Microsoft.ML.OnnxRuntime.DirectML/1.24.2";
|
||||
const DIRECTML_NUGET_URL: &str =
|
||||
"https://www.nuget.org/api/v2/package/Microsoft.AI.DirectML/1.15.4";
|
||||
const ONNX_RUNTIME_DLL_FILE: &str = "onnxruntime/onnxruntime.dll";
|
||||
const ONNX_RUNTIME_PROVIDERS_DLL_FILE: &str = "onnxruntime/onnxruntime_providers_shared.dll";
|
||||
const DIRECTML_DLL_FILE: &str = "onnxruntime/DirectML.dll";
|
||||
const CAPTION_ACCELERATION_FILE: &str = "settings/caption_acceleration.txt";
|
||||
const CAPTION_DETAIL_FILE: &str = "settings/caption_detail.txt";
|
||||
|
||||
const ONNX_RUNTIME_FILES: &[(&str, &str, &str)] = &[
|
||||
(
|
||||
ONNX_RUNTIME_DLL_FILE,
|
||||
ONNX_RUNTIME_NUGET_URL,
|
||||
"runtimes/win-x64/native/onnxruntime.dll",
|
||||
),
|
||||
(
|
||||
ONNX_RUNTIME_PROVIDERS_DLL_FILE,
|
||||
ONNX_RUNTIME_NUGET_URL,
|
||||
"runtimes/win-x64/native/onnxruntime_providers_shared.dll",
|
||||
),
|
||||
(
|
||||
DIRECTML_DLL_FILE,
|
||||
DIRECTML_NUGET_URL,
|
||||
"bin/x64-win/DirectML.dll",
|
||||
),
|
||||
];
|
||||
|
||||
const REQUIRED_FILES: &[&str] = &[
|
||||
ONNX_RUNTIME_DLL_FILE,
|
||||
ONNX_RUNTIME_PROVIDERS_DLL_FILE,
|
||||
@@ -69,18 +38,14 @@ const REQUIRED_FILES: &[&str] = &[
|
||||
"onnx/embed_tokens_fp16.onnx",
|
||||
];
|
||||
|
||||
// Mutex<bool> rather than OnceLock<Result>: a failed attempt (DLL not yet
|
||||
// downloaded) must NOT be cached, or a later successful download could never
|
||||
// recover within the same app session.
|
||||
static ORT_RUNTIME_INIT: Mutex<bool> = Mutex::new(false);
|
||||
|
||||
/// Set to `true` by `set_caption_acceleration` so the caption worker loop
|
||||
/// knows to drop its cached `FlorenceCaptioner` and reload with the new EP.
|
||||
pub static CAPTION_SESSION_DIRTY: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum CaptionAcceleration {
|
||||
#[default]
|
||||
Auto,
|
||||
Cpu,
|
||||
Directml,
|
||||
@@ -96,17 +61,12 @@ impl CaptionAcceleration {
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for CaptionAcceleration {
|
||||
fn default() -> Self {
|
||||
Self::Auto
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum CaptionDetail {
|
||||
Short,
|
||||
Detailed,
|
||||
#[default]
|
||||
Paragraph,
|
||||
}
|
||||
|
||||
@@ -136,12 +96,6 @@ impl CaptionDetail {
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for CaptionDetail {
|
||||
fn default() -> Self {
|
||||
Self::Paragraph
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct CaptionModelStatus {
|
||||
pub model_id: &'static str,
|
||||
@@ -304,11 +258,11 @@ pub fn prepare_caption_model_with_progress(
|
||||
if let Some(parent) = destination.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
if ONNX_RUNTIME_FILES
|
||||
if onnx_runtime::ONNX_RUNTIME_FILES
|
||||
.iter()
|
||||
.any(|(runtime_file, _, _)| runtime_file == file)
|
||||
{
|
||||
download_onnx_runtime_files(&local_dir)?;
|
||||
onnx_runtime::download_onnx_runtime_files(&local_dir)?;
|
||||
completed_files = REQUIRED_FILES
|
||||
.iter()
|
||||
.filter(|file| local_dir.join(file).exists())
|
||||
@@ -354,7 +308,7 @@ pub fn probe_caption_runtime(app_data_dir: &Path) -> Result<CaptionRuntimeProbe>
|
||||
}
|
||||
|
||||
let local_dir = model_dir(app_data_dir);
|
||||
ensure_onnx_runtime(&local_dir)?;
|
||||
onnx_runtime::ensure_onnx_runtime(&local_dir)?;
|
||||
let tokenizer =
|
||||
Tokenizer::from_file(local_dir.join("tokenizer.json")).map_err(anyhow::Error::msg)?;
|
||||
|
||||
@@ -403,7 +357,7 @@ pub fn probe_caption_vision(app_data_dir: &Path, image_path: &Path) -> Result<Ca
|
||||
}
|
||||
|
||||
let local_dir = model_dir(app_data_dir);
|
||||
ensure_onnx_runtime(&local_dir)?;
|
||||
onnx_runtime::ensure_onnx_runtime(&local_dir)?;
|
||||
let pixels = preprocess_image(image_path)?;
|
||||
let input_shape = vec![1, 3, 768, 768];
|
||||
let input = Tensor::from_array(([1usize, 3, 768, 768], pixels.into_boxed_slice()))
|
||||
@@ -448,7 +402,7 @@ impl FlorenceCaptioner {
|
||||
}
|
||||
|
||||
let local_dir = model_dir(app_data_dir);
|
||||
ensure_onnx_runtime(&local_dir)?;
|
||||
onnx_runtime::ensure_onnx_runtime(&local_dir)?;
|
||||
let tokenizer =
|
||||
Tokenizer::from_file(local_dir.join("tokenizer.json")).map_err(anyhow::Error::msg)?;
|
||||
let caption_detail = caption_detail(app_data_dir);
|
||||
@@ -657,288 +611,6 @@ fn probe_vision_session(
|
||||
})
|
||||
}
|
||||
|
||||
pub fn ensure_onnx_runtime(local_dir: &Path) -> Result<()> {
|
||||
let mut initialized = ORT_RUNTIME_INIT
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("ONNX runtime init lock poisoned"))?;
|
||||
if *initialized {
|
||||
return Ok(());
|
||||
}
|
||||
let dll_path = local_dir.join(ONNX_RUNTIME_DLL_FILE);
|
||||
if !dll_path.exists() {
|
||||
anyhow::bail!("ONNX Runtime DLL is missing: {}", dll_path.display());
|
||||
}
|
||||
ort::environment::init_from(&dll_path)
|
||||
.map_err(|error| anyhow::anyhow!(error.to_string()))?
|
||||
.with_name("phokus-florence")
|
||||
.commit();
|
||||
*initialized = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Download any ONNX Runtime DLLs missing from `local_dir`, reporting per-file
|
||||
/// byte progress as `(short_label, downloaded_bytes, total_bytes)`.
|
||||
/// `total_bytes` is `None` when the server omits Content-Length. Unlike
|
||||
/// `ensure_onnx_runtime` (init only), this actually provisions the files —
|
||||
/// callers that can run on a clean install must call this first. The callback
|
||||
/// fires per chunk; callers should throttle.
|
||||
pub fn provision_onnx_runtime_with_progress(
|
||||
local_dir: &Path,
|
||||
mut on_progress: impl FnMut(&str, u64, Option<u64>),
|
||||
) -> Result<()> {
|
||||
for (destination_file, source_url, archive_path) in ONNX_RUNTIME_FILES {
|
||||
let destination = local_dir.join(destination_file);
|
||||
if destination.exists() {
|
||||
continue;
|
||||
}
|
||||
// Strip the "onnxruntime/" prefix for a clean label.
|
||||
let label = destination_file
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.unwrap_or(destination_file);
|
||||
download_nuget_file(
|
||||
source_url,
|
||||
archive_path,
|
||||
&destination,
|
||||
|downloaded, total| on_progress(label, downloaded, total),
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Number of ONNX Runtime DLLs still missing from `local_dir` (for progress
|
||||
/// step counts before downloading).
|
||||
pub fn missing_onnx_runtime_count(local_dir: &Path) -> usize {
|
||||
ONNX_RUNTIME_FILES
|
||||
.iter()
|
||||
.filter(|(destination_file, _, _)| !local_dir.join(destination_file).exists())
|
||||
.count()
|
||||
}
|
||||
|
||||
fn download_onnx_runtime_files(local_dir: &Path) -> Result<()> {
|
||||
if !cfg!(target_os = "windows") {
|
||||
anyhow::bail!(
|
||||
"Florence-2 ONNX Runtime download is currently configured for Windows builds"
|
||||
);
|
||||
}
|
||||
|
||||
for (destination_file, source_url, archive_path) in ONNX_RUNTIME_FILES {
|
||||
let destination = local_dir.join(destination_file);
|
||||
download_nuget_file(source_url, archive_path, &destination, |_, _| {})?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Give up only after this many *consecutive* curl runs that download nothing;
|
||||
// a run that makes any progress resets the counter, so a large file completes
|
||||
// across however many resumes it takes. Kept low so a hard stall (e.g. a
|
||||
// broken VM NIC) fails in a couple of minutes — surfacing a retryable error —
|
||||
// rather than locking the UI on "preparing" for many minutes.
|
||||
const MAX_STALL_RETRIES: usize = 3;
|
||||
|
||||
/// Resiliently download `url` to `destination` using the system `curl.exe`.
|
||||
///
|
||||
/// ureq's read timeout does not fire on a stalled large transfer on Windows
|
||||
/// (schannel doesn't honor the socket read timeout), so a stall there hangs
|
||||
/// forever. curl detects an inactivity stall (`--speed-time`), resumes from
|
||||
/// the partial file (`-C -`), and retries internally — the same behavior a
|
||||
/// browser gets. We monitor the `.part` file's size for the progress bar and
|
||||
/// wrap curl in an outer progress-aware retry as a backstop. The partial file
|
||||
/// survives an app restart, so a later retry continues from disk.
|
||||
pub fn download_file_resilient(
|
||||
url: &str,
|
||||
destination: &Path,
|
||||
mut on_progress: impl FnMut(u64, Option<u64>),
|
||||
) -> Result<()> {
|
||||
if let Some(parent) = destination.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let part = match destination.extension() {
|
||||
Some(ext) => destination.with_extension(format!("{}.part", ext.to_string_lossy())),
|
||||
None => destination.with_extension("part"),
|
||||
};
|
||||
let name = destination
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| url.to_string());
|
||||
|
||||
log::info!("{name}: resolving download size");
|
||||
let total = remote_content_length(url);
|
||||
|
||||
// Reconcile any existing `.part` against the real size: exactly complete →
|
||||
// finish; oversized (stale/corrupt) → discard so curl restarts cleanly
|
||||
// (otherwise `curl -C -` would 416 forever).
|
||||
if let Some(total) = total {
|
||||
let size = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
|
||||
if size == total {
|
||||
std::fs::rename(&part, destination)?;
|
||||
return Ok(());
|
||||
}
|
||||
if size > total {
|
||||
let _ = std::fs::remove_file(&part);
|
||||
}
|
||||
}
|
||||
log::info!(
|
||||
"{name}: downloading via curl ({} bytes)",
|
||||
total
|
||||
.map(|t| t.to_string())
|
||||
.unwrap_or_else(|| "unknown size".into())
|
||||
);
|
||||
|
||||
let mut stalls = 0usize;
|
||||
loop {
|
||||
let before = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
|
||||
match run_curl_download(url, &part, total, &mut on_progress) {
|
||||
Ok(()) => break,
|
||||
Err(error) => {
|
||||
let after = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
|
||||
if after > before {
|
||||
log::warn!("{name}: curl interrupted at {after} bytes, resuming: {error}");
|
||||
stalls = 0;
|
||||
} else {
|
||||
stalls += 1;
|
||||
log::warn!(
|
||||
"{name}: curl made no progress ({stalls}/{MAX_STALL_RETRIES}): {error}"
|
||||
);
|
||||
if stalls >= MAX_STALL_RETRIES {
|
||||
// Discard the partial so a future attempt restarts clean
|
||||
// rather than getting stuck re-resuming a bad file.
|
||||
let _ = std::fs::remove_file(&part);
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_secs(2));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(total) = total {
|
||||
let got = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
|
||||
if got < total {
|
||||
anyhow::bail!("{name}: incomplete after curl ({got}/{total} bytes)");
|
||||
}
|
||||
}
|
||||
std::fs::rename(&part, destination)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Size probe via `curl -r 0-0` (a 1-byte Range request), parsing the total
|
||||
/// from the `Content-Range: bytes 0-0/<total>` header. Uses curl rather than
|
||||
/// ureq so no part of the download path depends on ureq (which hangs on this
|
||||
/// VM's TLS stack). Returns None if the server doesn't report a size.
|
||||
fn remote_content_length(url: &str) -> Option<u64> {
|
||||
let mut command = Command::new("curl.exe");
|
||||
command.args([
|
||||
"-sL",
|
||||
"-r",
|
||||
"0-0",
|
||||
"-D",
|
||||
"-",
|
||||
"-o",
|
||||
"NUL",
|
||||
"--connect-timeout",
|
||||
"30",
|
||||
"--max-time",
|
||||
"30",
|
||||
url,
|
||||
]);
|
||||
#[cfg(target_os = "windows")]
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
let output = command.output().ok()?;
|
||||
let headers = String::from_utf8_lossy(&output.stdout);
|
||||
for line in headers.lines() {
|
||||
if let Some(rest) = line.to_ascii_lowercase().strip_prefix("content-range:") {
|
||||
if let Some(total) = rest.rsplit('/').next().map(str::trim) {
|
||||
if let Ok(n) = total.parse::<u64>() {
|
||||
return Some(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Run one `curl.exe` download to `dest`, resuming from any partial file, while
|
||||
/// reporting progress from the growing file size. Returns an error (leaving the
|
||||
/// partial in place) if curl exits non-zero.
|
||||
fn run_curl_download(
|
||||
url: &str,
|
||||
dest: &Path,
|
||||
total: Option<u64>,
|
||||
on_progress: &mut impl FnMut(u64, Option<u64>),
|
||||
) -> Result<()> {
|
||||
let mut command = Command::new("curl.exe");
|
||||
command
|
||||
.arg("-fSL") // fail on HTTP errors, follow redirects, show errors
|
||||
.args(["-C", "-"]) // resume from the existing output file
|
||||
.args(["--retry", "3", "--retry-delay", "1", "--retry-connrefused"])
|
||||
.args(["--connect-timeout", "30"])
|
||||
// Abort (then --retry resumes) if under 1 KB/s for 30s — a real
|
||||
// inactivity timeout, which is what ureq couldn't deliver here.
|
||||
.args(["--speed-limit", "1024", "--speed-time", "30"])
|
||||
.arg("-s") // no progress meter (we watch the file instead)
|
||||
.arg("-o")
|
||||
.arg(dest)
|
||||
.arg(url)
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::piped());
|
||||
#[cfg(target_os = "windows")]
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.map_err(|e| anyhow::anyhow!("failed to launch curl.exe (required for downloads): {e}"))?;
|
||||
|
||||
loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
if status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut stderr = String::new();
|
||||
if let Some(mut pipe) = child.stderr.take() {
|
||||
let _ = pipe.read_to_string(&mut stderr);
|
||||
}
|
||||
anyhow::bail!(
|
||||
"curl exited with {}: {}",
|
||||
status
|
||||
.code()
|
||||
.map(|c| c.to_string())
|
||||
.unwrap_or_else(|| "signal".into()),
|
||||
stderr.trim()
|
||||
);
|
||||
}
|
||||
let downloaded = std::fs::metadata(dest).map(|m| m.len()).unwrap_or(0);
|
||||
on_progress(downloaded, total);
|
||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||
}
|
||||
}
|
||||
|
||||
fn download_nuget_file(
|
||||
source_url: &str,
|
||||
archive_path: &str,
|
||||
destination: &Path,
|
||||
on_progress: impl FnMut(u64, Option<u64>),
|
||||
) -> Result<()> {
|
||||
// Download the .nupkg (a zip) resiliently, then extract the one DLL.
|
||||
let package = destination.with_extension("nupkg");
|
||||
download_file_resilient(source_url, &package, on_progress)?;
|
||||
|
||||
log::info!("extracting {archive_path} from package");
|
||||
let file = std::fs::File::open(&package)?;
|
||||
let mut archive = zip::ZipArchive::new(file)?;
|
||||
let mut dll = archive.by_name(archive_path)?;
|
||||
let temp_destination = destination.with_extension("tmp");
|
||||
{
|
||||
let mut out = std::fs::File::create(&temp_destination)?;
|
||||
std::io::copy(&mut dll, &mut out)?;
|
||||
}
|
||||
std::fs::rename(&temp_destination, destination)?;
|
||||
let _ = std::fs::remove_file(&package);
|
||||
log::info!("extracted {archive_path}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_vision_encoder(session: &mut Session, image_path: &Path) -> Result<TensorData> {
|
||||
let pixels = preprocess_image(image_path)?;
|
||||
let input = Tensor::from_array(([1usize, 3, 768, 768], pixels.into_boxed_slice()))
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Dominant-color palette extraction for color search.
|
||||
//!
|
||||
//! Colors are sampled from the already-generated thumbnail (small, fast) rather
|
||||
//! than the full image. We coarse-quantize pixels into an RGB histogram, then
|
||||
//! return the most populated bins as representative colors with their weight
|
||||
//! (fraction of sampled pixels). Search then filters images whose palette has a
|
||||
//! color within a distance threshold of the query color.
|
||||
|
||||
use image::RgbImage;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct PaletteColor {
|
||||
pub r: u8,
|
||||
pub g: u8,
|
||||
pub b: u8,
|
||||
/// Fraction of sampled pixels (0.0–1.0) that fell in this color's bin.
|
||||
pub weight: f32,
|
||||
}
|
||||
|
||||
/// Bits kept per channel when binning. 4 bits → 16 levels/channel → 4096 bins:
|
||||
/// coarse enough to group near-identical shades, fine enough to separate hues.
|
||||
const QUANT_BITS: u32 = 4;
|
||||
/// Cap on sampled pixels so very large frames stay cheap; thumbnails are tiny so
|
||||
/// this rarely bites, but the backfill may read arbitrary thumbnail sizes.
|
||||
const MAX_SAMPLES: usize = 50_000;
|
||||
|
||||
/// Extract up to `k` dominant colors from an RGB image, most-common first.
|
||||
pub fn extract_palette(img: &RgbImage, k: usize) -> Vec<PaletteColor> {
|
||||
let pixels = img.as_raw();
|
||||
let pixel_count = pixels.len() / 3;
|
||||
if pixel_count == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let step = (pixel_count / MAX_SAMPLES).max(1);
|
||||
let shift = 8 - QUANT_BITS;
|
||||
|
||||
// bin key → (sum_r, sum_g, sum_b, count); summing lets us return the bin's
|
||||
// average color rather than the quantized corner.
|
||||
let mut bins: HashMap<u16, (u64, u64, u64, u64)> = HashMap::new();
|
||||
let mut total: u64 = 0;
|
||||
for pixel in pixels.chunks_exact(3).step_by(step) {
|
||||
let (r, g, b) = (pixel[0], pixel[1], pixel[2]);
|
||||
let key = (((r as u16) >> shift) << (QUANT_BITS * 2))
|
||||
| (((g as u16) >> shift) << QUANT_BITS)
|
||||
| ((b as u16) >> shift);
|
||||
let entry = bins.entry(key).or_insert((0, 0, 0, 0));
|
||||
entry.0 += r as u64;
|
||||
entry.1 += g as u64;
|
||||
entry.2 += b as u64;
|
||||
entry.3 += 1;
|
||||
total += 1;
|
||||
}
|
||||
if total == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let mut entries: Vec<(u64, u64, u64, u64)> = bins.into_values().collect();
|
||||
entries.sort_unstable_by_key(|entry| std::cmp::Reverse(entry.3));
|
||||
entries
|
||||
.into_iter()
|
||||
.take(k)
|
||||
.map(|(sum_r, sum_g, sum_b, count)| PaletteColor {
|
||||
r: (sum_r / count) as u8,
|
||||
g: (sum_g / count) as u8,
|
||||
b: (sum_b / count) as u8,
|
||||
weight: count as f32 / total as f32,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Decode a thumbnail file and extract its palette. Used by the backfill pass.
|
||||
pub fn extract_palette_from_file(thumbnail_path: &Path, k: usize) -> Option<Vec<PaletteColor>> {
|
||||
let img = image::ImageReader::open(thumbnail_path)
|
||||
.ok()?
|
||||
.decode()
|
||||
.ok()?;
|
||||
Some(extract_palette(&img.into_rgb8(), k))
|
||||
}
|
||||
|
||||
/// Number of palette colors stored per image.
|
||||
pub const PALETTE_SIZE: usize = 5;
|
||||
|
||||
/// Max squared RGB distance for a palette color to count as matching a query
|
||||
/// color (~70 units in RGB space). Tunable feel/precision of color search.
|
||||
pub const MATCH_DISTANCE_SQ: i64 = 4900;
|
||||
|
||||
/// Minimum weight (fraction of pixels) a palette color must have to match, so
|
||||
/// trivial specks of a color don't trigger a match.
|
||||
pub const MATCH_MIN_WEIGHT: f64 = 0.05;
|
||||
@@ -0,0 +1,240 @@
|
||||
//! Resilient file downloads via the system `curl` binary.
|
||||
//!
|
||||
//! Used for all large model/runtime downloads (tagger models, ONNX Runtime
|
||||
//! DLLs, caption model). ureq's read timeout does not fire on a stalled large
|
||||
//! transfer on Windows (schannel doesn't honor the socket read timeout), so a
|
||||
//! stall there hangs forever. curl detects an inactivity stall
|
||||
//! (`--speed-time`), resumes from the partial file (`-C -`), and retries
|
||||
//! internally — the same behavior a browser gets.
|
||||
|
||||
use anyhow::Result;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
// Suppress the console window when spawning curl from the GUI app.
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::os::windows::process::CommandExt;
|
||||
#[cfg(target_os = "windows")]
|
||||
const CREATE_NO_WINDOW: u32 = 0x08000000;
|
||||
|
||||
/// Discard target for curl output we only need the headers of.
|
||||
#[cfg(target_os = "windows")]
|
||||
const NULL_DEVICE: &str = "NUL";
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
const NULL_DEVICE: &str = "/dev/null";
|
||||
|
||||
/// Build a `curl` command with platform quirks applied. Windows resolves the
|
||||
/// bare name to `curl.exe` (bundled since Windows 10 1803) and needs the
|
||||
/// no-window flag; macOS ships curl; Linux is expected to have it installed.
|
||||
fn curl_command() -> Command {
|
||||
#[allow(unused_mut)]
|
||||
let mut command = Command::new("curl");
|
||||
#[cfg(target_os = "windows")]
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
command
|
||||
}
|
||||
|
||||
// Give up only after this many *consecutive* curl runs that download nothing;
|
||||
// a run that makes any progress resets the counter, so a large file completes
|
||||
// across however many resumes it takes. Kept low so a hard stall (e.g. a
|
||||
// broken VM NIC) fails in a couple of minutes — surfacing a retryable error —
|
||||
// rather than locking the UI on "preparing" for many minutes.
|
||||
const MAX_STALL_RETRIES: usize = 3;
|
||||
|
||||
/// Resiliently download `url` to `destination` using the system `curl`.
|
||||
///
|
||||
/// We monitor the `.part` file's size for the progress bar and wrap curl in an
|
||||
/// outer progress-aware retry as a backstop. The partial file survives an app
|
||||
/// restart, so a later retry continues from disk.
|
||||
pub fn download_file_resilient(
|
||||
url: &str,
|
||||
destination: &Path,
|
||||
mut on_progress: impl FnMut(u64, Option<u64>),
|
||||
) -> Result<()> {
|
||||
if let Some(parent) = destination.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let part = match destination.extension() {
|
||||
Some(ext) => destination.with_extension(format!("{}.part", ext.to_string_lossy())),
|
||||
None => destination.with_extension("part"),
|
||||
};
|
||||
let name = destination
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| url.to_string());
|
||||
|
||||
log::info!("{name}: resolving download size");
|
||||
let total = remote_content_length(url);
|
||||
|
||||
// Reconcile any existing `.part` against the real size: exactly complete →
|
||||
// finish; oversized (stale/corrupt) → discard so curl restarts cleanly
|
||||
// (otherwise `curl -C -` would 416 forever).
|
||||
if let Some(total) = total {
|
||||
let size = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
|
||||
if size == total {
|
||||
std::fs::rename(&part, destination)?;
|
||||
return Ok(());
|
||||
}
|
||||
if size > total {
|
||||
let _ = std::fs::remove_file(&part);
|
||||
}
|
||||
}
|
||||
log::info!(
|
||||
"{name}: downloading via curl ({} bytes)",
|
||||
total
|
||||
.map(|t| t.to_string())
|
||||
.unwrap_or_else(|| "unknown size".into())
|
||||
);
|
||||
|
||||
let mut stalls = 0usize;
|
||||
loop {
|
||||
let before = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
|
||||
match run_curl_download(url, &part, total, &mut on_progress) {
|
||||
Ok(()) => break,
|
||||
Err(error) => {
|
||||
let after = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
|
||||
if after > before {
|
||||
log::warn!("{name}: curl interrupted at {after} bytes, resuming: {error}");
|
||||
stalls = 0;
|
||||
} else {
|
||||
stalls += 1;
|
||||
log::warn!(
|
||||
"{name}: curl made no progress ({stalls}/{MAX_STALL_RETRIES}): {error}"
|
||||
);
|
||||
if stalls >= MAX_STALL_RETRIES {
|
||||
// Discard the partial so a future attempt restarts clean
|
||||
// rather than getting stuck re-resuming a bad file.
|
||||
let _ = std::fs::remove_file(&part);
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_secs(2));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(total) = total {
|
||||
let got = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
|
||||
if got < total {
|
||||
anyhow::bail!("{name}: incomplete after curl ({got}/{total} bytes)");
|
||||
}
|
||||
}
|
||||
std::fs::rename(&part, destination)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Size probe via `curl -r 0-0` (a 1-byte Range request), parsing the total
|
||||
/// from the `Content-Range: bytes 0-0/<total>` header. Uses curl rather than
|
||||
/// ureq so no part of the download path depends on ureq (which hangs on this
|
||||
/// VM's TLS stack). Returns None if the server doesn't report a size.
|
||||
fn remote_content_length(url: &str) -> Option<u64> {
|
||||
let mut command = curl_command();
|
||||
command.args([
|
||||
"-sL",
|
||||
"-r",
|
||||
"0-0",
|
||||
"-D",
|
||||
"-",
|
||||
"-o",
|
||||
NULL_DEVICE,
|
||||
"--connect-timeout",
|
||||
"30",
|
||||
"--max-time",
|
||||
"30",
|
||||
"--",
|
||||
url,
|
||||
]);
|
||||
let output = command.output().ok()?;
|
||||
let headers = String::from_utf8_lossy(&output.stdout);
|
||||
for line in headers.lines() {
|
||||
if let Some(rest) = line.to_ascii_lowercase().strip_prefix("content-range:") {
|
||||
if let Some(total) = rest.rsplit('/').next().map(str::trim) {
|
||||
if let Ok(n) = total.parse::<u64>() {
|
||||
return Some(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Run one `curl` download to `dest`, resuming from any partial file, while
|
||||
/// reporting progress from the growing file size. Returns an error (leaving the
|
||||
/// partial in place) if curl exits non-zero.
|
||||
fn run_curl_download(
|
||||
url: &str,
|
||||
dest: &Path,
|
||||
total: Option<u64>,
|
||||
on_progress: &mut impl FnMut(u64, Option<u64>),
|
||||
) -> Result<()> {
|
||||
let mut command = curl_command();
|
||||
command
|
||||
.arg("-fSL") // fail on HTTP errors, follow redirects, show errors
|
||||
.args(["-C", "-"]) // resume from the existing output file
|
||||
.args(["--retry", "3", "--retry-delay", "1", "--retry-connrefused"])
|
||||
.args(["--connect-timeout", "30"])
|
||||
// Abort (then --retry resumes) if under 1 KB/s for 30s — a real
|
||||
// inactivity timeout, which is what ureq couldn't deliver here.
|
||||
.args(["--speed-limit", "1024", "--speed-time", "30"])
|
||||
.arg("-s") // no progress meter (we watch the file instead)
|
||||
.arg("-o")
|
||||
.arg(dest)
|
||||
.arg("--")
|
||||
.arg(url)
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::piped());
|
||||
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.map_err(|e| anyhow::anyhow!("failed to launch curl (required for downloads): {e}"))?;
|
||||
|
||||
loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
if status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut stderr = String::new();
|
||||
if let Some(mut pipe) = child.stderr.take() {
|
||||
let _ = pipe.read_to_string(&mut stderr);
|
||||
}
|
||||
anyhow::bail!(
|
||||
"curl exited with {}: {}",
|
||||
status
|
||||
.code()
|
||||
.map(|c| c.to_string())
|
||||
.unwrap_or_else(|| "signal".into()),
|
||||
stderr.trim()
|
||||
);
|
||||
}
|
||||
let downloaded = std::fs::metadata(dest).map(|m| m.len()).unwrap_or(0);
|
||||
on_progress(downloaded, total);
|
||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||
}
|
||||
}
|
||||
|
||||
/// Download a NuGet package (a zip) resiliently, then extract the single file
|
||||
/// at `archive_path` into `destination`.
|
||||
pub fn download_nuget_file(
|
||||
source_url: &str,
|
||||
archive_path: &str,
|
||||
destination: &Path,
|
||||
on_progress: impl FnMut(u64, Option<u64>),
|
||||
) -> Result<()> {
|
||||
let package = destination.with_extension("nupkg");
|
||||
download_file_resilient(source_url, &package, on_progress)?;
|
||||
|
||||
log::info!("extracting {archive_path} from package");
|
||||
let file = std::fs::File::open(&package)?;
|
||||
let mut archive = zip::ZipArchive::new(file)?;
|
||||
let mut dll = archive.by_name(archive_path)?;
|
||||
let temp_destination = destination.with_extension("tmp");
|
||||
{
|
||||
let mut out = std::fs::File::create(&temp_destination)?;
|
||||
std::io::copy(&mut dll, &mut out)?;
|
||||
}
|
||||
std::fs::rename(&temp_destination, destination)?;
|
||||
let _ = std::fs::remove_file(&package);
|
||||
log::info!("extracted {archive_path}");
|
||||
Ok(())
|
||||
}
|
||||
@@ -220,19 +220,19 @@ fn load_images(paths: &[PathBuf], image_size: usize) -> Result<Tensor> {
|
||||
|
||||
/// Returns the path that should be fed to the CLIP image embedder for a given media file.
|
||||
///
|
||||
/// For videos the thumbnail image is used (because CLIP only understands still images).
|
||||
/// If a video has no thumbnail yet, an error is returned — the caller should mark the
|
||||
/// embedding job as failed rather than trying to decode the raw video file.
|
||||
/// For videos and AVIFs the thumbnail image is used because CLIP preprocessing
|
||||
/// only uses decoders from the `image` crate, while AVIF is decoded through
|
||||
/// FFmpeg into a JPEG thumbnail.
|
||||
pub fn embedding_source_path(
|
||||
path: &str,
|
||||
thumbnail_path: Option<&str>,
|
||||
media_kind: &str,
|
||||
) -> Result<PathBuf> {
|
||||
if media_kind == "video" {
|
||||
if media_kind == "video" || is_avif_path(path) {
|
||||
match thumbnail_path {
|
||||
Some(thumb) => Ok(PathBuf::from(thumb)),
|
||||
None => Err(anyhow::anyhow!(
|
||||
"No thumbnail available yet for video '{}' — embedding deferred until thumbnail is generated",
|
||||
"No thumbnail available yet for '{}' — embedding deferred until thumbnail is generated",
|
||||
std::path::Path::new(path)
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy())
|
||||
@@ -243,3 +243,10 @@ pub fn embedding_source_path(
|
||||
Ok(PathBuf::from(path))
|
||||
}
|
||||
}
|
||||
|
||||
fn is_avif_path(path: &str) -> bool {
|
||||
std::path::Path::new(path)
|
||||
.extension()
|
||||
.and_then(|ext| ext.to_str())
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("avif"))
|
||||
}
|
||||
|
||||
@@ -92,6 +92,7 @@ pub fn find_similar_image_matches(
|
||||
conn: &Connection,
|
||||
image_id: i64,
|
||||
folder_id: Option<i64>,
|
||||
album_id: Option<i64>,
|
||||
threshold: f32,
|
||||
offset: usize,
|
||||
limit: usize,
|
||||
@@ -103,10 +104,17 @@ pub fn find_similar_image_matches(
|
||||
None => return Ok(Vec::new()),
|
||||
};
|
||||
|
||||
// Fetch folder image IDs *before* acquiring the read lock so we don't hold
|
||||
// Build the allowed-id set *before* acquiring the read lock so we don't hold
|
||||
// the lock across a potentially slow SQLite query, which would delay any
|
||||
// concurrent ensure_index call waiting for a write lock.
|
||||
let folder_image_ids: Option<Vec<i64>> = if let Some(folder_id) = folder_id {
|
||||
// concurrent ensure_index call waiting for a write lock. Album scope takes
|
||||
// precedence over folder scope; both reuse the HNSW filtered search.
|
||||
let allowed_image_ids: Option<Vec<i64>> = if let Some(album_id) = album_id {
|
||||
let mut stmt = conn.prepare("SELECT image_id FROM album_images WHERE album_id = ?1")?;
|
||||
let ids = stmt
|
||||
.query_map([album_id], |row| row.get::<_, i64>(0))?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Some(ids)
|
||||
} else if let Some(folder_id) = folder_id {
|
||||
let ids = vector::get_all_image_embeddings_with_ids(conn, Some(folder_id))?
|
||||
.into_iter()
|
||||
.map(|(id, _)| id)
|
||||
@@ -122,7 +130,7 @@ pub fn find_similar_image_matches(
|
||||
};
|
||||
|
||||
let knbn = (offset + limit).max(limit).saturating_add(32);
|
||||
let neighbours: Vec<Neighbour> = if let Some(image_ids) = folder_image_ids {
|
||||
let neighbours: Vec<Neighbour> = if let Some(image_ids) = allowed_image_ids {
|
||||
let mut allowed_ids = image_ids
|
||||
.into_iter()
|
||||
.filter_map(|allowed_image_id| {
|
||||
|
||||
@@ -3,22 +3,22 @@ use crate::db::{self, DbPool, EmbeddingJob, FolderJobProgress, ImageRecord, Inde
|
||||
use crate::embedder::{embedding_source_path, ClipImageEmbedder};
|
||||
use crate::media::{probe_video_metadata, MediaTools};
|
||||
use crate::storage::{detect_storage_profile, RuntimeAdaptiveProfile, StorageProfile};
|
||||
use crate::tagger::{self, WdTagger};
|
||||
use crate::tagger::{self, Tagger};
|
||||
use crate::thumbnail;
|
||||
use crate::vector;
|
||||
use anyhow::Result;
|
||||
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
|
||||
use rayon::prelude::*;
|
||||
use serde::Serialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
use tauri::{AppHandle, Emitter};
|
||||
use tauri::{AppHandle, Emitter, Manager};
|
||||
use walkdir::WalkDir;
|
||||
|
||||
const IMAGE_EXTENSIONS: &[&str] = &[
|
||||
"jpg", "jpeg", "png", "gif", "bmp", "tiff", "tif", "webp", "avif", "heic", "heif",
|
||||
"jpg", "jpeg", "png", "gif", "bmp", "tiff", "tif", "webp", "avif",
|
||||
];
|
||||
|
||||
const VIDEO_EXTENSIONS: &[&str] = &["mp4", "mov", "m4v", "webm"];
|
||||
@@ -41,6 +41,14 @@ struct PausedWorkerFolders {
|
||||
tagging: HashSet<i64>,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize, Serialize)]
|
||||
pub struct PersistedPausedWorkerFolders {
|
||||
pub thumbnail: Vec<i64>,
|
||||
pub metadata: Vec<i64>,
|
||||
pub embedding: Vec<i64>,
|
||||
pub tagging: Vec<i64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct FolderWorkerPausedState {
|
||||
pub thumbnail: bool,
|
||||
@@ -50,6 +58,41 @@ pub struct FolderWorkerPausedState {
|
||||
pub tagging: bool,
|
||||
}
|
||||
|
||||
pub fn replace_worker_paused_states(states: PersistedPausedWorkerFolders) {
|
||||
if let Ok(mut paused_folders) = PAUSED_WORKER_FOLDERS
|
||||
.get_or_init(|| Mutex::new(PausedWorkerFolders::default()))
|
||||
.lock()
|
||||
{
|
||||
paused_folders.thumbnail = states.thumbnail.into_iter().collect();
|
||||
paused_folders.metadata = states.metadata.into_iter().collect();
|
||||
paused_folders.embedding = states.embedding.into_iter().collect();
|
||||
paused_folders.caption = HashSet::new();
|
||||
paused_folders.tagging = states.tagging.into_iter().collect();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn snapshot_worker_paused_states() -> PersistedPausedWorkerFolders {
|
||||
let Ok(paused_folders) = PAUSED_WORKER_FOLDERS
|
||||
.get_or_init(|| Mutex::new(PausedWorkerFolders::default()))
|
||||
.lock()
|
||||
else {
|
||||
return PersistedPausedWorkerFolders::default();
|
||||
};
|
||||
|
||||
let sorted = |set: &HashSet<i64>| {
|
||||
let mut ids = set.iter().copied().collect::<Vec<_>>();
|
||||
ids.sort_unstable();
|
||||
ids
|
||||
};
|
||||
|
||||
PersistedPausedWorkerFolders {
|
||||
thumbnail: sorted(&paused_folders.thumbnail),
|
||||
metadata: sorted(&paused_folders.metadata),
|
||||
embedding: sorted(&paused_folders.embedding),
|
||||
tagging: sorted(&paused_folders.tagging),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_worker_paused(worker: &str, folder_id: i64, paused: bool) {
|
||||
if let Ok(mut paused_folders) = PAUSED_WORKER_FOLDERS
|
||||
.get_or_init(|| Mutex::new(PausedWorkerFolders::default()))
|
||||
@@ -190,6 +233,13 @@ pub struct MediaUpdateBatch {
|
||||
pub images: Vec<ImageRecord>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize)]
|
||||
pub struct ColorBackfillProgress {
|
||||
pub processed: i64,
|
||||
pub total: i64,
|
||||
pub done: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize)]
|
||||
pub struct MediaJobProgressEvent {
|
||||
pub progress: Vec<FolderJobProgress>,
|
||||
@@ -323,7 +373,7 @@ pub fn start_caption_worker(app: AppHandle, pool: DbPool, app_data_dir: PathBuf)
|
||||
|
||||
pub fn start_tagging_worker(app: AppHandle, pool: DbPool, app_data_dir: PathBuf) {
|
||||
std::thread::spawn(move || {
|
||||
let mut tagger_instance: Option<WdTagger> = None;
|
||||
let mut tagger_instance: Option<Box<dyn Tagger>> = None;
|
||||
log::info!("Tagging worker started.");
|
||||
loop {
|
||||
// If the acceleration setting changed, drop the cached session so
|
||||
@@ -347,7 +397,51 @@ pub fn start_tagging_worker(app: AppHandle, pool: DbPool, app_data_dir: PathBuf)
|
||||
});
|
||||
}
|
||||
|
||||
/// True when `path` lives inside Phokus's own app-data directory (thumbnail
|
||||
/// cache, database, downloaded models). If a user indexes an ancestor of this
|
||||
/// directory — e.g. their whole `Users` folder — the app would otherwise index
|
||||
/// its own thumbnails, generate thumbnails of those thumbnails, and loop
|
||||
/// forever. The whole subtree is pruned from folder scans and ignored by the
|
||||
/// watcher to break that cycle.
|
||||
///
|
||||
/// Comparison is component-aware (so a sibling like `…/phokus-backup` never
|
||||
/// matches) and case-insensitive on Windows — the indexed root may report a
|
||||
/// different casing than `app_data_dir` (e.g. `c:\users\…` vs `C:\Users\…`),
|
||||
/// and a case-sensitive prefix check there would silently let the loop back in.
|
||||
fn is_within_app_data(path: &Path, app_data_dir: Option<&Path>) -> bool {
|
||||
let Some(dir) = app_data_dir else {
|
||||
return false;
|
||||
};
|
||||
let mut base = dir.components();
|
||||
let mut target = path.components();
|
||||
loop {
|
||||
let Some(base_component) = base.next() else {
|
||||
// Consumed every component of the app-data dir while still matching →
|
||||
// `path` is the app-data dir itself or a descendant.
|
||||
return true;
|
||||
};
|
||||
let Some(target_component) = target.next() else {
|
||||
// `path` is shorter than the app-data dir, so it cannot be inside it.
|
||||
return false;
|
||||
};
|
||||
let matches = if cfg!(windows) {
|
||||
base_component
|
||||
.as_os_str()
|
||||
.eq_ignore_ascii_case(target_component.as_os_str())
|
||||
} else {
|
||||
base_component == target_component
|
||||
};
|
||||
if !matches {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn do_index(app: AppHandle, pool: &DbPool, folder_id: i64, folder_path: PathBuf) -> Result<()> {
|
||||
// Resolve our own app-data directory so the walk can skip it (see
|
||||
// `is_within_app_data`). Resolution failure is non-fatal — we just lose the
|
||||
// guard, which only matters when indexing an ancestor of the app data dir.
|
||||
let app_data_dir = app.path().app_data_dir().ok();
|
||||
let existing_entries = {
|
||||
let conn = pool.get()?;
|
||||
db::get_folder_media_index(&conn, folder_id)?
|
||||
@@ -364,6 +458,9 @@ fn do_index(app: AppHandle, pool: &DbPool, folder_id: i64, folder_path: PathBuf)
|
||||
let media_paths: Vec<PathBuf> = WalkDir::new(&folder_path)
|
||||
.follow_links(true)
|
||||
.into_iter()
|
||||
// Prune our own app-data subtree before descending into it, so we never
|
||||
// scan (and re-thumbnail) the thumbnail cache.
|
||||
.filter_entry(|entry| !is_within_app_data(entry.path(), app_data_dir.as_deref()))
|
||||
.filter_map(|entry| match entry {
|
||||
Ok(e) if e.file_type().is_file() && is_supported_media(e.path()) => {
|
||||
Some(e.path().to_path_buf())
|
||||
@@ -550,6 +647,9 @@ fn build_record(
|
||||
let filename = path.file_name()?.to_string_lossy().to_string();
|
||||
let metadata = std::fs::metadata(path).ok()?;
|
||||
let file_size = metadata.len() as i64;
|
||||
if file_size == 0 {
|
||||
return None;
|
||||
}
|
||||
let modified_at = metadata.modified().ok().map(|time| {
|
||||
let date_time: chrono::DateTime<chrono::Utc> = time.into();
|
||||
date_time.to_rfc3339()
|
||||
@@ -660,10 +760,13 @@ fn process_thumbnail_batch(
|
||||
|
||||
let (image_jobs, video_jobs): (Vec<_>, Vec<_>) =
|
||||
jobs.into_iter().partition(|job| job.media_kind == "image");
|
||||
let (avif_jobs, raster_jobs): (Vec<_>, Vec<_>) = image_jobs
|
||||
.into_iter()
|
||||
.partition(|job| is_avif_path(Path::new(&job.path)));
|
||||
|
||||
// Images: parallel decode, committed as one batch.
|
||||
if !image_jobs.is_empty() {
|
||||
let results = image_jobs
|
||||
if !raster_jobs.is_empty() {
|
||||
let results = raster_jobs
|
||||
.par_iter()
|
||||
.map(|job| {
|
||||
(
|
||||
@@ -675,6 +778,15 @@ fn process_thumbnail_batch(
|
||||
persist_thumbnail_results(app, pool, results)?;
|
||||
}
|
||||
|
||||
// AVIF: FFmpeg-backed decode, like videos. Keep this off the shared rayon
|
||||
// pool because each subprocess blocks its worker thread.
|
||||
for job in &avif_jobs {
|
||||
let result =
|
||||
thumbnail::generate_avif_thumbnail(media_tools, Path::new(&job.path), cache_dir)
|
||||
.map(Some);
|
||||
persist_thumbnail_results(app, pool, vec![(job.image_id, result)])?;
|
||||
}
|
||||
|
||||
// Videos: sequential, off the rayon pool — each ffmpeg call blocks its
|
||||
// thread, and a video-heavy batch on the shared pool would starve image
|
||||
// decoding across all workers. Committed per item so progress keeps
|
||||
@@ -722,6 +834,13 @@ fn persist_thumbnail_results(
|
||||
width,
|
||||
height,
|
||||
)?);
|
||||
|
||||
// Store the dominant-color palette sampled during resizing.
|
||||
if let Some(thumb) = &generated {
|
||||
if !thumb.palette.is_empty() {
|
||||
db::replace_image_colors(&tx, image_id, &thumb.palette)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tx.commit()?;
|
||||
@@ -746,6 +865,82 @@ fn persist_thumbnail_results(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_avif_path(path: &Path) -> bool {
|
||||
path.extension()
|
||||
.and_then(|ext| ext.to_str())
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("avif"))
|
||||
}
|
||||
|
||||
/// One-shot background pass that samples a color palette from the (already
|
||||
/// generated) thumbnails of images indexed before color search existed. New
|
||||
/// images get their palette during thumbnail generation, so this only fills the
|
||||
/// historical gap. Emits `color-backfill-progress` so the UI can show a count.
|
||||
pub fn start_color_backfill(app: AppHandle, pool: DbPool) {
|
||||
std::thread::spawn(move || {
|
||||
let total = match pool.get() {
|
||||
Ok(conn) => db::count_images_missing_colors(&conn).unwrap_or(0),
|
||||
Err(_) => return,
|
||||
};
|
||||
if total == 0 {
|
||||
return;
|
||||
}
|
||||
log::info!("Color backfill: sampling palettes for {total} images.");
|
||||
|
||||
let mut processed: i64 = 0;
|
||||
loop {
|
||||
let batch = match pool.get() {
|
||||
Ok(conn) => db::get_images_missing_colors(&conn, 64).unwrap_or_default(),
|
||||
Err(_) => break,
|
||||
};
|
||||
if batch.is_empty() {
|
||||
break;
|
||||
}
|
||||
|
||||
for (image_id, thumbnail_path) in batch {
|
||||
let palette = crate::color::extract_palette_from_file(
|
||||
Path::new(&thumbnail_path),
|
||||
crate::color::PALETTE_SIZE,
|
||||
);
|
||||
let colors: Vec<(u8, u8, u8, f32)> = match palette {
|
||||
Some(colors) if !colors.is_empty() => colors
|
||||
.into_iter()
|
||||
.map(|c| (c.r, c.g, c.b, c.weight))
|
||||
.collect(),
|
||||
// Unreadable thumbnail: store a zero-weight sentinel so the
|
||||
// image isn't reprocessed forever (it just won't match).
|
||||
_ => vec![(0, 0, 0, 0.0)],
|
||||
};
|
||||
let _ = with_db_write_lock(|| {
|
||||
let conn = pool.get()?;
|
||||
db::replace_image_colors(&conn, image_id, &colors)
|
||||
});
|
||||
processed += 1;
|
||||
}
|
||||
|
||||
let _ = app.emit(
|
||||
"color-backfill-progress",
|
||||
ColorBackfillProgress {
|
||||
processed,
|
||||
total,
|
||||
done: false,
|
||||
},
|
||||
);
|
||||
// Yield so the backfill stays in the background under active use.
|
||||
std::thread::sleep(Duration::from_millis(15));
|
||||
}
|
||||
|
||||
log::info!("Color backfill complete: {processed} images sampled.");
|
||||
let _ = app.emit(
|
||||
"color-backfill-progress",
|
||||
ColorBackfillProgress {
|
||||
processed,
|
||||
total,
|
||||
done: true,
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// Returns `Ok(true)` if a batch was claimed and processed, `Ok(false)` if
|
||||
/// the queue was empty.
|
||||
fn process_metadata_batch(
|
||||
@@ -869,20 +1064,20 @@ fn process_embedding_batch(
|
||||
let embedder = embedder.as_ref().expect("embedder should be initialized");
|
||||
|
||||
let infer_started_at = Instant::now();
|
||||
// Resolve the source path for each job. Videos without a thumbnail produce an Err
|
||||
// here — those jobs are marked failed immediately without going to the embedder.
|
||||
// Resolve each source path. Video jobs without thumbnails are not claimable, so an
|
||||
// error here represents a real race or missing thumbnail rather than normal deferral.
|
||||
let source_results: Vec<Result<PathBuf>> = jobs
|
||||
.iter()
|
||||
.map(|job| embedding_source_path(&job.path, job.thumbnail_path.as_deref(), &job.media_kind))
|
||||
.collect();
|
||||
|
||||
// Separate jobs with a valid source from those that fail early (e.g. video with no thumbnail).
|
||||
// Separate jobs with a valid source from genuine early failures.
|
||||
let mut embeddable_indices: Vec<usize> = Vec::new();
|
||||
let mut embeddable_paths: Vec<PathBuf> = Vec::new();
|
||||
// image_id -> early error message for jobs that cannot be embedded yet
|
||||
let mut pre_failed: HashMap<i64, String> = HashMap::new();
|
||||
|
||||
for (i, (job, result)) in jobs.iter().zip(source_results.into_iter()).enumerate() {
|
||||
for (i, (job, result)) in jobs.iter().zip(source_results).enumerate() {
|
||||
match result {
|
||||
Ok(path) => {
|
||||
embeddable_indices.push(i);
|
||||
@@ -904,16 +1099,13 @@ fn process_embedding_batch(
|
||||
|
||||
match embedder.embed_images(&embeddable_paths) {
|
||||
Ok(embeddings) => {
|
||||
for (job, embedding) in embeddable_jobs.iter().zip(embeddings.into_iter()) {
|
||||
for (job, embedding) in embeddable_jobs.iter().zip(embeddings) {
|
||||
embed_results.insert(job.image_id, Ok(embedding));
|
||||
}
|
||||
}
|
||||
Err(batch_error) => {
|
||||
log::error!("Embedding batch fallback to per-image mode: {batch_error}");
|
||||
for (job, source_path) in embeddable_jobs
|
||||
.into_iter()
|
||||
.zip(embeddable_paths.into_iter())
|
||||
{
|
||||
for (job, source_path) in embeddable_jobs.into_iter().zip(embeddable_paths) {
|
||||
embed_results.insert(job.image_id, embedder.embed_image(&source_path));
|
||||
}
|
||||
}
|
||||
@@ -1087,7 +1279,7 @@ fn process_tagging_batch(
|
||||
app: &AppHandle,
|
||||
pool: &DbPool,
|
||||
app_data_dir: &Path,
|
||||
tagger_instance: &mut Option<WdTagger>,
|
||||
tagger_instance: &mut Option<Box<dyn Tagger>>,
|
||||
) -> Result<bool> {
|
||||
if !tagger::tagger_model_status(app_data_dir).ready {
|
||||
return Ok(false);
|
||||
@@ -1099,20 +1291,23 @@ fn process_tagging_batch(
|
||||
|
||||
// Exclude actively-indexing folders for the same reason as the other
|
||||
// workers: don't compete with a running scan.
|
||||
let batch_started_at = Instant::now();
|
||||
let mut excluded_folders = paused_folder_ids("tagging");
|
||||
excluded_folders.extend(active_indexing_folders());
|
||||
let batch_size = crate::tagger::tagger_batch_size(app_data_dir);
|
||||
let claim_started_at = Instant::now();
|
||||
let jobs = with_db_write_lock(|| {
|
||||
let mut conn = pool.get()?;
|
||||
db::claim_tagging_jobs(&mut conn, &excluded_folders, batch_size)
|
||||
})?;
|
||||
let claim_elapsed = claim_started_at.elapsed();
|
||||
|
||||
if jobs.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
if tagger_instance.is_none() {
|
||||
match WdTagger::new(app_data_dir) {
|
||||
match tagger::create_active_tagger(app_data_dir) {
|
||||
Ok(model) => *tagger_instance = Some(model),
|
||||
Err(error) => {
|
||||
with_db_write_lock(|| {
|
||||
@@ -1139,16 +1334,45 @@ fn process_tagging_batch(
|
||||
.as_mut()
|
||||
.expect("tagger should be initialized before tagging batch processing");
|
||||
|
||||
let tag_results = jobs
|
||||
// Resolve each job's source image (AVIF can't be decoded directly, so it
|
||||
// falls back to its thumbnail), then tag the batch in small chunks (below).
|
||||
let source_paths: Vec<PathBuf> = jobs
|
||||
.iter()
|
||||
.map(|job| {
|
||||
(
|
||||
job.clone(),
|
||||
tagger_ref.run(Path::new(&job.path), tagger::DEFAULT_MAX_TAGS),
|
||||
)
|
||||
if is_avif_path(Path::new(&job.path)) {
|
||||
PathBuf::from(job.thumbnail_path.as_deref().unwrap_or(&job.path))
|
||||
} else {
|
||||
PathBuf::from(&job.path)
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
.collect();
|
||||
|
||||
// Tag in small micro-batches instead of one wide forward pass. On a shared
|
||||
// GPU every DirectML dispatch blocks the WebView2 compositor for its whole
|
||||
// duration, so a 16-wide batch freezes the UI for seconds; small chunks keep
|
||||
// each GPU lock short (and bound peak decode memory) while a brief yield
|
||||
// between them lets the UI and other workers grab the GPU/CPU. The model is
|
||||
// compute-bound here, so this costs almost no throughput.
|
||||
let infer_started_at = Instant::now();
|
||||
let mut outputs = Vec::with_capacity(source_paths.len());
|
||||
let mut chunks = source_paths.chunks(tagger::TAGGER_INFER_CHUNK).peekable();
|
||||
while let Some(chunk) = chunks.next() {
|
||||
outputs.extend(tagger_ref.run_batch(chunk, tagger::DEFAULT_MAX_TAGS));
|
||||
if chunks.peek().is_some() {
|
||||
std::thread::sleep(std::time::Duration::from_millis(
|
||||
tagger::TAGGER_INFER_YIELD_MS,
|
||||
));
|
||||
}
|
||||
}
|
||||
let infer_elapsed = infer_started_at.elapsed();
|
||||
|
||||
// Attribute the tags to the model that actually produced them, not a
|
||||
// hardcoded one (WD vs JoyTag are both possible).
|
||||
let tagger_model_name = tagger_ref.model_name();
|
||||
|
||||
let tag_results = jobs.iter().cloned().zip(outputs).collect::<Vec<_>>();
|
||||
|
||||
let write_started_at = Instant::now();
|
||||
let updated_images = with_db_write_lock(|| {
|
||||
let mut conn = pool.get()?;
|
||||
let tx = conn.transaction()?;
|
||||
@@ -1178,7 +1402,7 @@ fn process_tagging_batch(
|
||||
job.image_id,
|
||||
&tag_pairs,
|
||||
&output.rating,
|
||||
tagger::WD_TAGGER_MODEL_NAME,
|
||||
tagger_model_name,
|
||||
)?;
|
||||
}
|
||||
Err(error) => {
|
||||
@@ -1200,6 +1424,7 @@ fn process_tagging_batch(
|
||||
db::requeue_tagging_jobs(&conn, &image_ids)
|
||||
});
|
||||
})?;
|
||||
let write_elapsed = write_started_at.elapsed();
|
||||
|
||||
if !updated_images.is_empty() {
|
||||
let folder_ids = updated_images
|
||||
@@ -1215,6 +1440,15 @@ fn process_tagging_batch(
|
||||
emit_folder_job_progress(app, pool, &folder_ids.into_iter().collect::<Vec<_>>(), true);
|
||||
}
|
||||
|
||||
log::info!(
|
||||
"Tagging batch timing: {} items, claim {:?}, tag {:?}, write {:?}, total {:?}",
|
||||
jobs.len(),
|
||||
claim_elapsed,
|
||||
infer_elapsed,
|
||||
write_elapsed,
|
||||
batch_started_at.elapsed()
|
||||
);
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
@@ -1285,7 +1519,7 @@ fn max_worker_fetch_size(active_folders: &HashSet<i64>) -> usize {
|
||||
.unwrap_or(StorageProfile::Balanced.worker_fetch_size())
|
||||
}
|
||||
|
||||
fn with_db_write_lock<T>(operation: impl FnOnce() -> Result<T>) -> Result<T> {
|
||||
pub fn with_db_write_lock<T>(operation: impl FnOnce() -> Result<T>) -> Result<T> {
|
||||
let lock = DB_WRITE_LOCK.get_or_init(|| Mutex::new(()));
|
||||
let _guard = lock.lock().unwrap();
|
||||
operation()
|
||||
@@ -1372,7 +1606,6 @@ fn mime_for_ext(ext: &str) -> &'static str {
|
||||
"webp" => "image/webp",
|
||||
"tiff" | "tif" => "image/tiff",
|
||||
"avif" => "image/avif",
|
||||
"heic" | "heif" => "image/heif",
|
||||
"mp4" | "m4v" => "video/mp4",
|
||||
"mov" => "video/quicktime",
|
||||
"webm" => "video/webm",
|
||||
@@ -1491,6 +1724,10 @@ pub fn start_watcher(app: AppHandle, pool: DbPool, thumb_dir: PathBuf) -> Watche
|
||||
|
||||
// Spawn the debounce loop on its own thread.
|
||||
let folder_map_thread = Arc::clone(&folder_map);
|
||||
// `thumb_dir` is `<app data>/thumbnails`; its parent is the app-data root.
|
||||
// Watched roots can be ancestors of it (e.g. a whole user profile), so we
|
||||
// drop any event inside that subtree to avoid re-indexing our own cache.
|
||||
let app_data_dir = thumb_dir.parent().map(Path::to_path_buf);
|
||||
std::thread::spawn(move || {
|
||||
// path → deadline: the earliest instant at which this path should be processed.
|
||||
let mut pending: HashMap<PathBuf, Instant> = HashMap::new();
|
||||
@@ -1533,7 +1770,22 @@ pub fn start_watcher(app: AppHandle, pool: DbPool, thumb_dir: PathBuf) -> Watche
|
||||
{
|
||||
let old = event.paths[0].clone();
|
||||
let new = event.paths[1].clone();
|
||||
if is_supported_media(&old) || is_supported_media(&new) {
|
||||
let old_in_app = is_within_app_data(&old, app_data_dir.as_deref());
|
||||
let new_in_app = is_within_app_data(&new, app_data_dir.as_deref());
|
||||
if old_in_app && new_in_app {
|
||||
// Internal app-data churn (e.g. thumbnail cache) — ignore.
|
||||
} else if old_in_app || new_in_app {
|
||||
// Only one side is app-data, so the rename pairing is
|
||||
// meaningless (we don't track app-data files). Handle the
|
||||
// legitimate side as an independent create/delete via the
|
||||
// normal debounce queue: a file moved out of app-data is
|
||||
// indexed as a create; one moved in is processed as a
|
||||
// delete (process_watcher_path sees it no longer exists).
|
||||
let legit = if old_in_app { new } else { old };
|
||||
if is_supported_media(&legit) {
|
||||
pending.insert(legit, now + WATCHER_DEBOUNCE);
|
||||
}
|
||||
} else if is_supported_media(&old) || is_supported_media(&new) {
|
||||
// Remove either side from regular pending so it isn't
|
||||
// processed as an independent delete/create.
|
||||
pending.remove(&old);
|
||||
@@ -1542,7 +1794,9 @@ pub fn start_watcher(app: AppHandle, pool: DbPool, thumb_dir: PathBuf) -> Watche
|
||||
}
|
||||
} else {
|
||||
for path in event.paths {
|
||||
if is_supported_media(&path) {
|
||||
if is_supported_media(&path)
|
||||
&& !is_within_app_data(&path, app_data_dir.as_deref())
|
||||
{
|
||||
pending.insert(path, now + WATCHER_DEBOUNCE);
|
||||
}
|
||||
}
|
||||
@@ -1741,3 +1995,42 @@ fn process_watcher_rename(
|
||||
Err(e) => log::error!("Watcher rename: post-update fetch error: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn supported_media_matches_known_extensions_case_insensitively() {
|
||||
for path in ["a.jpg", "b.JPEG", "c.PNG", "d.avif", "e.mp4", "f.WEBM"] {
|
||||
assert!(
|
||||
is_supported_media(Path::new(path)),
|
||||
"{path} should be supported"
|
||||
);
|
||||
}
|
||||
for path in ["notes.txt", "archive.zip", "no_extension", "clip.mkv"] {
|
||||
assert!(
|
||||
!is_supported_media(Path::new(path)),
|
||||
"{path} should be skipped"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn media_kind_splits_video_from_image_extensions() {
|
||||
for ext in ["mp4", "MOV", "m4v", "webm"] {
|
||||
assert_eq!(media_kind_for_ext(ext), "video");
|
||||
}
|
||||
for ext in ["jpg", "PNG", "webp", "avif"] {
|
||||
assert_eq!(media_kind_for_ext(ext), "image");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mime_types_map_per_extension() {
|
||||
assert_eq!(mime_for_ext("JPG"), "image/jpeg");
|
||||
assert_eq!(mime_for_ext("png"), "image/png");
|
||||
assert_eq!(mime_for_ext("mov"), "video/quicktime");
|
||||
assert_eq!(mime_for_ext("m4v"), "video/mp4");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
mod ai_tag_filter;
|
||||
mod captioner;
|
||||
mod color;
|
||||
mod commands;
|
||||
mod db;
|
||||
mod download;
|
||||
mod embedder;
|
||||
mod hnsw_index;
|
||||
mod indexer;
|
||||
mod media;
|
||||
mod onnx_runtime;
|
||||
mod storage;
|
||||
mod tagger;
|
||||
mod thumbnail;
|
||||
@@ -45,6 +49,32 @@ pub fn run() {
|
||||
.plugin(tauri_plugin_fs::init())
|
||||
.plugin(tauri_plugin_notification::init())
|
||||
.setup(|app| {
|
||||
// Fresh installs open at the fixed config size (1280×800) because the
|
||||
// window-state plugin has nothing saved yet — too tall for laptops
|
||||
// like 1366×768. Clamp the window to the monitor's work area (which
|
||||
// already excludes the taskbar) and re-center it there, but only when
|
||||
// it actually overflows, so a restored size/position on a roomier
|
||||
// display is left untouched. Sizes are physical pixels on both sides,
|
||||
// so this stays correct across display scaling.
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
if let Ok(Some(monitor)) = window.current_monitor() {
|
||||
let area = monitor.work_area();
|
||||
let max_w = area.size.width.saturating_sub(32);
|
||||
let max_h = area.size.height.saturating_sub(32);
|
||||
if let Ok(size) = window.outer_size() {
|
||||
if size.width > max_w || size.height > max_h {
|
||||
let new_w = size.width.min(max_w);
|
||||
let new_h = size.height.min(max_h);
|
||||
let _ = window.set_size(tauri::PhysicalSize::new(new_w, new_h));
|
||||
let _ = window.set_position(tauri::PhysicalPosition::new(
|
||||
area.position.x + (area.size.width as i32 - new_w as i32) / 2,
|
||||
area.position.y + (area.size.height as i32 - new_h as i32) / 2,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let app_dir = app
|
||||
.path()
|
||||
.app_data_dir()
|
||||
@@ -53,7 +83,7 @@ pub fn run() {
|
||||
std::fs::create_dir_all(&app_dir).expect("Failed to create app data dir");
|
||||
|
||||
// FFmpeg provisioning happens in the background so the window
|
||||
// appears immediately; workers gate video jobs on readiness and
|
||||
// appears immediately; workers gate video/AVIF jobs on readiness and
|
||||
// the onboarding/Settings UI shows progress and retry.
|
||||
media::spawn_ffmpeg_provision(app.handle().clone());
|
||||
|
||||
@@ -65,6 +95,16 @@ pub fn run() {
|
||||
let conn = pool.get().expect("Failed to get connection for migration");
|
||||
db::migrate(&conn).expect("Failed to run migrations");
|
||||
db::reset_inflight_jobs(&conn).expect("Failed to reset inflight jobs");
|
||||
let repaired_deferred = db::repair_deferred_embedding_jobs(&conn)
|
||||
.expect("Failed to repair deferred embedding jobs");
|
||||
if repaired_deferred > 0 {
|
||||
log::info!("Requeued {repaired_deferred} deferred embedding jobs.");
|
||||
}
|
||||
let repaired_avif =
|
||||
db::repair_avif_jobs(&conn).expect("Failed to repair AVIF jobs");
|
||||
if repaired_avif > 0 {
|
||||
log::info!("Requeued {repaired_avif} AVIF jobs.");
|
||||
}
|
||||
let backfilled =
|
||||
db::backfill_embedding_jobs(&conn).expect("Failed to backfill embedding jobs");
|
||||
if backfilled > 0 {
|
||||
@@ -81,6 +121,7 @@ pub fn run() {
|
||||
|
||||
let thumb_dir = app_dir.join("thumbnails");
|
||||
std::fs::create_dir_all(&thumb_dir).expect("Failed to create thumbnail dir");
|
||||
commands::restore_persisted_worker_pauses(&app_dir);
|
||||
|
||||
// The asset protocol scope is no longer a blanket "**": thumbnails
|
||||
// are allowed statically in tauri.conf.json, and each indexed
|
||||
@@ -112,6 +153,8 @@ pub fn run() {
|
||||
// Caption worker disabled — UI removed; keeping backend code intact for future use.
|
||||
// indexer::start_caption_worker(app.handle().clone(), pool.clone(), app_dir.clone());
|
||||
indexer::start_tagging_worker(app.handle().clone(), pool.clone(), app_dir.clone());
|
||||
// Backfill color palettes for images indexed before color search existed.
|
||||
indexer::start_color_backfill(app.handle().clone(), pool.clone());
|
||||
|
||||
let watcher_handle = indexer::start_watcher(app.handle().clone(), pool.clone(), thumb_dir.clone());
|
||||
|
||||
@@ -123,7 +166,10 @@ pub fn run() {
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
commands::add_folder,
|
||||
commands::add_folders,
|
||||
commands::list_directories,
|
||||
commands::get_folders,
|
||||
commands::reorder_folders,
|
||||
commands::get_background_job_progress,
|
||||
commands::remove_folder,
|
||||
commands::get_images,
|
||||
@@ -152,13 +198,19 @@ pub fn run() {
|
||||
commands::suggest_image_tags,
|
||||
commands::set_worker_paused,
|
||||
commands::get_worker_states,
|
||||
commands::get_tag_cloud,
|
||||
commands::get_worker_pauses_persist,
|
||||
commands::set_worker_pauses_persist,
|
||||
commands::get_visual_clusters,
|
||||
commands::get_explore_tags,
|
||||
commands::get_related_tags,
|
||||
commands::get_images_by_ids,
|
||||
commands::get_failed_embedding_images,
|
||||
commands::get_failed_tagging_images,
|
||||
commands::get_tagger_model_status,
|
||||
commands::get_tagger_acceleration,
|
||||
commands::set_tagger_acceleration,
|
||||
commands::get_tagger_model,
|
||||
commands::set_tagger_model,
|
||||
commands::probe_tagger_runtime,
|
||||
commands::get_tagger_threshold,
|
||||
commands::set_tagger_threshold,
|
||||
@@ -168,9 +220,26 @@ pub fn run() {
|
||||
commands::delete_tagger_model,
|
||||
commands::queue_tagging_jobs,
|
||||
commands::clear_tagging_jobs,
|
||||
commands::reset_ai_tags,
|
||||
commands::get_image_tags,
|
||||
commands::add_user_tag,
|
||||
commands::remove_tag,
|
||||
commands::rename_tag,
|
||||
commands::delete_tag,
|
||||
commands::get_image_exif,
|
||||
commands::list_albums,
|
||||
commands::create_album,
|
||||
commands::rename_album,
|
||||
commands::delete_album,
|
||||
commands::delete_albums,
|
||||
commands::reorder_albums,
|
||||
commands::add_images_to_album,
|
||||
commands::remove_images_from_album,
|
||||
commands::get_album_images,
|
||||
commands::bulk_update_details,
|
||||
commands::bulk_add_tags,
|
||||
commands::bulk_remove_tag,
|
||||
commands::get_build_variant,
|
||||
commands::search_tags_autocomplete,
|
||||
commands::find_duplicates,
|
||||
commands::load_duplicate_scan_cache,
|
||||
@@ -183,8 +252,11 @@ pub fn run() {
|
||||
commands::get_tagging_queue_folder_ids,
|
||||
commands::set_tagging_queue_folder_ids,
|
||||
commands::open_app_data_folder,
|
||||
commands::open_map_location,
|
||||
commands::open_changelog_url,
|
||||
commands::get_database_info,
|
||||
commands::vacuum_database,
|
||||
commands::rebuild_semantic_index,
|
||||
commands::get_orphaned_thumbnails_info,
|
||||
commands::cleanup_orphaned_thumbnails,
|
||||
commands::get_muted_folder_ids,
|
||||
@@ -193,6 +265,8 @@ pub fn run() {
|
||||
commands::retry_ffmpeg_download,
|
||||
commands::get_onboarding_completed,
|
||||
commands::set_onboarding_completed,
|
||||
commands::get_last_seen_version,
|
||||
commands::set_last_seen_version,
|
||||
commands::get_notifications_paused,
|
||||
commands::set_notifications_paused,
|
||||
])
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
//! Shared ONNX Runtime provisioning: downloading the runtime + DirectML DLLs
|
||||
//! and initializing `ort` from them.
|
||||
//!
|
||||
//! Both ONNX consumers go through here — the tagger (live) and the Florence-2
|
||||
//! captioner (backend intact, UI disabled). The DLLs are Windows/DirectML
|
||||
//! specific; a future cross-platform build needs a per-OS runtime strategy.
|
||||
|
||||
use crate::download;
|
||||
use anyhow::Result;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
|
||||
const ONNX_RUNTIME_NUGET_URL: &str =
|
||||
"https://www.nuget.org/api/v2/package/Microsoft.ML.OnnxRuntime.DirectML/1.24.2";
|
||||
const DIRECTML_NUGET_URL: &str =
|
||||
"https://www.nuget.org/api/v2/package/Microsoft.AI.DirectML/1.15.4";
|
||||
|
||||
pub const ONNX_RUNTIME_DLL_FILE: &str = "onnxruntime/onnxruntime.dll";
|
||||
pub const ONNX_RUNTIME_PROVIDERS_DLL_FILE: &str = "onnxruntime/onnxruntime_providers_shared.dll";
|
||||
pub const DIRECTML_DLL_FILE: &str = "onnxruntime/DirectML.dll";
|
||||
|
||||
/// The shared runtime DLLs, as paths relative to [`runtime_dir`].
|
||||
pub const RUNTIME_DLLS: &[&str] = &[
|
||||
ONNX_RUNTIME_DLL_FILE,
|
||||
ONNX_RUNTIME_PROVIDERS_DLL_FILE,
|
||||
DIRECTML_DLL_FILE,
|
||||
];
|
||||
|
||||
/// `(destination_file, nuget_package_url, path_inside_package)` for each DLL.
|
||||
pub const ONNX_RUNTIME_FILES: &[(&str, &str, &str)] = &[
|
||||
(
|
||||
ONNX_RUNTIME_DLL_FILE,
|
||||
ONNX_RUNTIME_NUGET_URL,
|
||||
"runtimes/win-x64/native/onnxruntime.dll",
|
||||
),
|
||||
(
|
||||
ONNX_RUNTIME_PROVIDERS_DLL_FILE,
|
||||
ONNX_RUNTIME_NUGET_URL,
|
||||
"runtimes/win-x64/native/onnxruntime_providers_shared.dll",
|
||||
),
|
||||
(
|
||||
DIRECTML_DLL_FILE,
|
||||
DIRECTML_NUGET_URL,
|
||||
"bin/x64-win/DirectML.dll",
|
||||
),
|
||||
];
|
||||
|
||||
// Mutex<bool> rather than OnceLock<Result>: a failed attempt (DLL not yet
|
||||
// downloaded) must NOT be cached, or a later successful download could never
|
||||
// recover within the same app session.
|
||||
static ORT_RUNTIME_INIT: Mutex<bool> = Mutex::new(false);
|
||||
|
||||
/// Directory the shared runtime DLLs are provisioned into.
|
||||
///
|
||||
/// Historically the DLLs were downloaded as part of the Florence-2 caption
|
||||
/// model, so they live inside that model's directory
|
||||
/// (`models/florence-2-base-ft/onnxruntime/`). The location is kept even
|
||||
/// though the tagger is now the main consumer, so existing installs don't
|
||||
/// have to re-download the runtime.
|
||||
pub fn runtime_dir(app_data_dir: &Path) -> PathBuf {
|
||||
crate::captioner::model_dir(app_data_dir)
|
||||
}
|
||||
|
||||
/// Initialize `ort` from the already-downloaded runtime DLL in `local_dir`.
|
||||
/// Fails if the DLL is missing — use [`provision_onnx_runtime_with_progress`]
|
||||
/// to download it first on a clean install.
|
||||
pub fn ensure_onnx_runtime(local_dir: &Path) -> Result<()> {
|
||||
let mut initialized = ORT_RUNTIME_INIT
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("ONNX runtime init lock poisoned"))?;
|
||||
if *initialized {
|
||||
return Ok(());
|
||||
}
|
||||
let dll_path = local_dir.join(ONNX_RUNTIME_DLL_FILE);
|
||||
if !dll_path.exists() {
|
||||
anyhow::bail!("ONNX Runtime DLL is missing: {}", dll_path.display());
|
||||
}
|
||||
ort::environment::init_from(&dll_path)
|
||||
.map_err(|error| anyhow::anyhow!(error.to_string()))?
|
||||
.with_name("phokus-florence")
|
||||
.commit();
|
||||
*initialized = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Download any ONNX Runtime DLLs missing from `local_dir`, reporting per-file
|
||||
/// byte progress as `(short_label, downloaded_bytes, total_bytes)`.
|
||||
/// `total_bytes` is `None` when the server omits Content-Length. Unlike
|
||||
/// `ensure_onnx_runtime` (init only), this actually provisions the files —
|
||||
/// callers that can run on a clean install must call this first. The callback
|
||||
/// fires per chunk; callers should throttle.
|
||||
pub fn provision_onnx_runtime_with_progress(
|
||||
local_dir: &Path,
|
||||
mut on_progress: impl FnMut(&str, u64, Option<u64>),
|
||||
) -> Result<()> {
|
||||
for (destination_file, source_url, archive_path) in ONNX_RUNTIME_FILES {
|
||||
let destination = local_dir.join(destination_file);
|
||||
if destination.exists() {
|
||||
continue;
|
||||
}
|
||||
// Strip the "onnxruntime/" prefix for a clean label.
|
||||
let label = destination_file
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.unwrap_or(destination_file);
|
||||
download::download_nuget_file(
|
||||
source_url,
|
||||
archive_path,
|
||||
&destination,
|
||||
|downloaded, total| on_progress(label, downloaded, total),
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Number of ONNX Runtime DLLs still missing from `local_dir` (for progress
|
||||
/// step counts before downloading).
|
||||
pub fn missing_onnx_runtime_count(local_dir: &Path) -> usize {
|
||||
ONNX_RUNTIME_FILES
|
||||
.iter()
|
||||
.filter(|(destination_file, _, _)| !local_dir.join(destination_file).exists())
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Download all missing runtime DLLs without progress reporting.
|
||||
pub fn download_onnx_runtime_files(local_dir: &Path) -> Result<()> {
|
||||
if !cfg!(target_os = "windows") {
|
||||
anyhow::bail!("ONNX Runtime DLL download is currently configured for Windows builds");
|
||||
}
|
||||
|
||||
for (destination_file, source_url, archive_path) in ONNX_RUNTIME_FILES {
|
||||
let destination = local_dir.join(destination_file);
|
||||
download::download_nuget_file(source_url, archive_path, &destination, |_, _| {})?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -122,3 +122,53 @@ fn fallback_profile_for_path(path: &Path) -> StorageProfile {
|
||||
|
||||
StorageProfile::Balanced
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn thumbnail_workers_scale_with_parallelism_within_clamps() {
|
||||
assert_eq!(StorageProfile::Fast.thumbnail_workers(3), 2);
|
||||
assert_eq!(StorageProfile::Fast.thumbnail_workers(12), 4);
|
||||
assert_eq!(StorageProfile::Fast.thumbnail_workers(64), 4);
|
||||
assert_eq!(StorageProfile::Balanced.thumbnail_workers(4), 2);
|
||||
assert_eq!(StorageProfile::Balanced.thumbnail_workers(12), 3);
|
||||
assert_eq!(StorageProfile::Balanced.thumbnail_workers(64), 3);
|
||||
assert_eq!(StorageProfile::Conservative.thumbnail_workers(64), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adaptive_profile_tracks_scan_speed() {
|
||||
let mut adaptive = RuntimeAdaptiveProfile::new(StorageProfile::Balanced);
|
||||
assert_eq!(adaptive.profile(), StorageProfile::Balanced);
|
||||
|
||||
// 1 ms/item → fast storage.
|
||||
adaptive.observe_scan_batch(10, Duration::from_millis(10));
|
||||
assert_eq!(adaptive.profile(), StorageProfile::Fast);
|
||||
|
||||
// A very slow batch drags the EMA over the conservative threshold.
|
||||
adaptive.observe_scan_batch(1, Duration::from_millis(100));
|
||||
assert_eq!(adaptive.profile(), StorageProfile::Conservative);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adaptive_profile_ignores_empty_batches() {
|
||||
let mut adaptive = RuntimeAdaptiveProfile::new(StorageProfile::Fast);
|
||||
adaptive.observe_scan_batch(0, Duration::from_secs(10));
|
||||
assert_eq!(adaptive.profile(), StorageProfile::Fast);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fallback_profile_treats_unc_paths_as_conservative() {
|
||||
assert_eq!(
|
||||
fallback_profile_for_path(Path::new("\\\\server\\share\\photos")),
|
||||
StorageProfile::Conservative
|
||||
);
|
||||
assert_eq!(
|
||||
fallback_profile_for_path(Path::new("C:\\photos")),
|
||||
StorageProfile::Balanced
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,9 @@ pub struct GeneratedThumbnail {
|
||||
pub path: PathBuf,
|
||||
pub width: Option<i64>,
|
||||
pub height: Option<i64>,
|
||||
/// Dominant-color palette `(r, g, b, weight)` sampled while resizing. Empty
|
||||
/// when the thumbnail already existed (the color backfill handles those).
|
||||
pub palette: Vec<(u8, u8, u8, f32)>,
|
||||
}
|
||||
|
||||
pub fn generate_image_thumbnail(image_path: &Path, cache_dir: &Path) -> Result<GeneratedThumbnail> {
|
||||
@@ -28,6 +31,7 @@ pub fn generate_image_thumbnail(image_path: &Path, cache_dir: &Path) -> Result<G
|
||||
path: out_path,
|
||||
width: original_dimensions.0,
|
||||
height: original_dimensions.1,
|
||||
palette: Vec::new(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -47,6 +51,12 @@ pub fn generate_image_thumbnail(image_path: &Path, cache_dir: &Path) -> Result<G
|
||||
let thumb = image::RgbImage::from_raw(dst_width, dst_height, dst.buffer().to_vec())
|
||||
.ok_or_else(|| anyhow!("failed to construct resized thumbnail buffer"))?;
|
||||
|
||||
// Sample the dominant-color palette from the resized buffer before encoding.
|
||||
let palette = crate::color::extract_palette(&thumb, crate::color::PALETTE_SIZE)
|
||||
.into_iter()
|
||||
.map(|color| (color.r, color.g, color.b, color.weight))
|
||||
.collect();
|
||||
|
||||
if let Some(parent) = out_path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
@@ -58,6 +68,7 @@ pub fn generate_image_thumbnail(image_path: &Path, cache_dir: &Path) -> Result<G
|
||||
path: out_path,
|
||||
width: original_dimensions.0,
|
||||
height: original_dimensions.1,
|
||||
palette,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -166,6 +177,7 @@ pub fn generate_video_thumbnail(
|
||||
path: out_path,
|
||||
width: None,
|
||||
height: None,
|
||||
palette: Vec::new(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -231,6 +243,7 @@ pub fn generate_video_thumbnail(
|
||||
path: out_path,
|
||||
width: None,
|
||||
height: None,
|
||||
palette: Vec::new(),
|
||||
});
|
||||
}
|
||||
last_error = String::from_utf8_lossy(&output.stderr).to_string();
|
||||
@@ -241,6 +254,100 @@ pub fn generate_video_thumbnail(
|
||||
))
|
||||
}
|
||||
|
||||
pub fn generate_avif_thumbnail(
|
||||
tools: &MediaTools,
|
||||
image_path: &Path,
|
||||
cache_dir: &Path,
|
||||
) -> Result<GeneratedThumbnail> {
|
||||
let path_str = image_path.to_string_lossy();
|
||||
let out_path = thumb_path(cache_dir, &path_str);
|
||||
let original_dimensions = ffprobe_dimensions(tools, image_path);
|
||||
|
||||
if out_path.exists() {
|
||||
return Ok(GeneratedThumbnail {
|
||||
path: out_path,
|
||||
width: original_dimensions.0,
|
||||
height: original_dimensions.1,
|
||||
palette: Vec::new(),
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(parent) = out_path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
|
||||
let output_path = out_path.to_string_lossy().into_owned();
|
||||
let output = tools
|
||||
.ffmpeg_command()
|
||||
.args([
|
||||
"-y",
|
||||
"-threads",
|
||||
"2",
|
||||
"-i",
|
||||
path_str.as_ref(),
|
||||
"-frames:v",
|
||||
"1",
|
||||
"-vf",
|
||||
"scale=320:-1:force_original_aspect_ratio=decrease",
|
||||
"-q:v",
|
||||
"4",
|
||||
&output_path,
|
||||
])
|
||||
.output()?;
|
||||
|
||||
if output.status.success() && out_path.exists() {
|
||||
// AVIF is decoded by FFmpeg, so there's no in-memory RGB buffer here;
|
||||
// sample the palette by reading the JPEG thumbnail we just wrote.
|
||||
let palette =
|
||||
crate::color::extract_palette_from_file(&out_path, crate::color::PALETTE_SIZE)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|color| (color.r, color.g, color.b, color.weight))
|
||||
.collect();
|
||||
return Ok(GeneratedThumbnail {
|
||||
path: out_path,
|
||||
width: original_dimensions.0,
|
||||
height: original_dimensions.1,
|
||||
palette,
|
||||
});
|
||||
}
|
||||
|
||||
Err(anyhow!(
|
||||
"ffmpeg failed generating AVIF thumbnail for {path_str}: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
))
|
||||
}
|
||||
|
||||
fn ffprobe_dimensions(tools: &MediaTools, image_path: &Path) -> (Option<i64>, Option<i64>) {
|
||||
let output = tools
|
||||
.ffprobe_command()
|
||||
.args([
|
||||
"-v",
|
||||
"error",
|
||||
"-select_streams",
|
||||
"v:0",
|
||||
"-show_entries",
|
||||
"stream=width,height",
|
||||
"-of",
|
||||
"csv=p=0:s=x",
|
||||
&image_path.to_string_lossy(),
|
||||
])
|
||||
.output();
|
||||
let Ok(output) = output else {
|
||||
return (None, None);
|
||||
};
|
||||
|
||||
if !output.status.success() {
|
||||
return (None, None);
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let mut parts = stdout.trim().split('x');
|
||||
let width = parts.next().and_then(|part| part.parse::<i64>().ok());
|
||||
let height = parts.next().and_then(|part| part.parse::<i64>().ok());
|
||||
(width, height)
|
||||
}
|
||||
|
||||
pub fn thumb_path(cache_dir: &Path, image_path: &str) -> PathBuf {
|
||||
thumb_path_with_ext(cache_dir, image_path, "jpg")
|
||||
}
|
||||
@@ -276,6 +383,26 @@ fn fit_dimensions(width: u32, height: u32, max_size: u32) -> (u32, u32) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn fit_dimensions_preserves_aspect_ratio_within_max() {
|
||||
// Already small enough: unchanged.
|
||||
assert_eq!(fit_dimensions(100, 50, THUMB_SIZE), (100, 50));
|
||||
// Landscape and portrait scale to the max on their long edge.
|
||||
assert_eq!(fit_dimensions(6400, 3200, THUMB_SIZE), (320, 160));
|
||||
assert_eq!(fit_dimensions(3200, 6400, THUMB_SIZE), (160, 320));
|
||||
// Extreme ratios never collapse to zero.
|
||||
assert_eq!(fit_dimensions(1, 100_000, 320), (1, 320));
|
||||
assert_eq!(fit_dimensions(100_000, 1, 320), (320, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_jpeg_checks_extension_only() {
|
||||
assert!(is_jpeg(Path::new("photo.jpg")));
|
||||
assert!(is_jpeg(Path::new("photo.JPEG")));
|
||||
assert!(!is_jpeg(Path::new("photo.png")));
|
||||
assert!(!is_jpeg(Path::new("photo")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scale_numerator_picks_smallest_sufficient() {
|
||||
assert_eq!(scale_numerator(6000, THUMB_SIZE), 1);
|
||||
|
||||
@@ -36,6 +36,18 @@ pub fn migrate(conn: &Connection) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drop and recreate the vector tables at the current `CLIP_VECTOR_DIM`. Used by
|
||||
/// the "Rebuild semantic index" maintenance action when stored vectors no longer
|
||||
/// match the active model's dimension (e.g. after switching embedding models),
|
||||
/// so the columns are rebuilt to the right size before embeddings regenerate.
|
||||
pub fn rebuild_tables(conn: &Connection) -> Result<()> {
|
||||
conn.execute_batch(
|
||||
"DROP TABLE IF EXISTS image_vec;
|
||||
DROP TABLE IF EXISTS caption_vec;",
|
||||
)?;
|
||||
migrate(conn)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn delete_embedding(conn: &Connection, image_id: i64) -> Result<()> {
|
||||
conn.execute("DELETE FROM image_vec WHERE image_id = ?1", [image_id])?;
|
||||
@@ -251,6 +263,44 @@ pub fn get_embedding_revision(conn: &Connection) -> Result<String> {
|
||||
|
||||
/// Returns all stored image embeddings with their image IDs, optionally filtered to one folder.
|
||||
/// Each entry is `(image_id, normalized_f32_embedding)`.
|
||||
/// Returns `(count, hash)` over the stored embedding image IDs for the scope in a
|
||||
/// single ordered pass, without loading any embedding blobs. The hash covers the
|
||||
/// exact set of IDs, so it is membership-sensitive: adding, removing, or moving an
|
||||
/// image between folders changes it even when the count happens to stay the same.
|
||||
/// Used (together with the embedding revision, which catches an image being
|
||||
/// re-embedded in place) as the cheap visual-cluster cache key so a cache hit doesn't
|
||||
/// have to read and unpack hundreds of MB of embeddings just to validate freshness.
|
||||
pub fn embedding_ids_signature(conn: &Connection, folder_id: Option<i64>) -> Result<(i64, u64)> {
|
||||
use xxhash_rust::xxh3::Xxh3;
|
||||
let mut hasher = Xxh3::new();
|
||||
let mut count: i64 = 0;
|
||||
let mut hash_row = |id: i64| {
|
||||
hasher.update(&id.to_le_bytes());
|
||||
count += 1;
|
||||
};
|
||||
match folder_id {
|
||||
Some(fid) => {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT image_id FROM image_vec
|
||||
WHERE image_id IN (SELECT id FROM images WHERE folder_id = ?1)
|
||||
ORDER BY image_id",
|
||||
)?;
|
||||
let mut rows = stmt.query([fid])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
hash_row(row.get(0)?);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let mut stmt = conn.prepare("SELECT image_id FROM image_vec ORDER BY image_id")?;
|
||||
let mut rows = stmt.query([])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
hash_row(row.get(0)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((count, hasher.digest()))
|
||||
}
|
||||
|
||||
pub fn get_all_image_embeddings_with_ids(
|
||||
conn: &Connection,
|
||||
folder_id: Option<i64>,
|
||||
@@ -360,6 +410,41 @@ pub fn search_image_ids_by_embedding_in_folder(
|
||||
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}
|
||||
|
||||
/// Brute-force cosine search scoped to a single album (membership via
|
||||
/// `album_images`), ordered by ascending distance. Mirrors the folder-scoped
|
||||
/// variant for region-based similarity search.
|
||||
pub fn search_image_ids_by_embedding_in_album(
|
||||
conn: &Connection,
|
||||
embedding: &[f32],
|
||||
album_id: i64,
|
||||
exclude_image_id: Option<i64>,
|
||||
limit: usize,
|
||||
) -> Result<Vec<i64>> {
|
||||
if embedding.len() != CLIP_VECTOR_DIM {
|
||||
return Err(anyhow!(
|
||||
"expected {}-dimensional embedding, got {}",
|
||||
CLIP_VECTOR_DIM,
|
||||
embedding.len()
|
||||
));
|
||||
}
|
||||
|
||||
let packed = pack_f32(embedding);
|
||||
let exclude_id = exclude_image_id.unwrap_or(-1);
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT v.image_id
|
||||
FROM image_vec v
|
||||
JOIN album_images ai ON ai.image_id = v.image_id
|
||||
WHERE ai.album_id = ?2
|
||||
AND v.image_id != ?3
|
||||
ORDER BY vec_distance_cosine(v.embedding, vec_f32(?1)) ASC
|
||||
LIMIT ?4",
|
||||
)?;
|
||||
let rows = stmt.query_map((&packed, album_id, exclude_id, limit as i64), |row| {
|
||||
row.get::<_, i64>(0)
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn search_caption_ids_by_embedding(
|
||||
conn: &Connection,
|
||||
@@ -477,3 +562,81 @@ fn pack_f32(values: &[f32]) -> Vec<u8> {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::db::test_support::{test_conn, test_image};
|
||||
|
||||
#[test]
|
||||
fn pack_unpack_roundtrip() {
|
||||
let values = vec![0.0f32, 1.5, -2.25, f32::MIN_POSITIVE, 1e10];
|
||||
assert_eq!(unpack_f32(&pack_f32(&values)), values);
|
||||
assert!(unpack_f32(&pack_f32(&[])).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upsert_embedding_rejects_wrong_dimension() {
|
||||
let conn = test_conn();
|
||||
let error = upsert_embedding(&conn, 1, &[0.5f32; 3]).unwrap_err();
|
||||
assert!(error.to_string().contains("dimension"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upsert_and_delete_embedding_roundtrip() {
|
||||
let conn = test_conn();
|
||||
let embedding = vec![0.25f32; CLIP_VECTOR_DIM];
|
||||
upsert_embedding(&conn, 42, &embedding).unwrap();
|
||||
assert!(has_image_vector(&conn, 42).unwrap());
|
||||
|
||||
// Upsert replaces rather than duplicates.
|
||||
upsert_embedding(&conn, 42, &embedding).unwrap();
|
||||
let rows: i64 = conn
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM image_vec WHERE image_id = 42",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(rows, 1);
|
||||
|
||||
delete_embedding(&conn, 42).unwrap();
|
||||
assert!(!has_image_vector(&conn, 42).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_similar_image_ids_ranks_by_cosine_distance() {
|
||||
let conn = test_conn();
|
||||
let folder_id = crate::db::insert_folder(&conn, "C:/a", "a").unwrap();
|
||||
let base_id =
|
||||
crate::db::upsert_image(&conn, &test_image(folder_id, "C:/a/base.jpg")).unwrap();
|
||||
let close_id =
|
||||
crate::db::upsert_image(&conn, &test_image(folder_id, "C:/a/close.jpg")).unwrap();
|
||||
let far_id =
|
||||
crate::db::upsert_image(&conn, &test_image(folder_id, "C:/a/far.jpg")).unwrap();
|
||||
|
||||
let mut base = vec![0.0f32; CLIP_VECTOR_DIM];
|
||||
base[0] = 1.0;
|
||||
let mut close = vec![0.0f32; CLIP_VECTOR_DIM];
|
||||
close[0] = 1.0;
|
||||
close[1] = 0.2;
|
||||
let mut far = vec![0.0f32; CLIP_VECTOR_DIM];
|
||||
far[1] = 1.0;
|
||||
upsert_embedding(&conn, base_id, &base).unwrap();
|
||||
upsert_embedding(&conn, close_id, &close).unwrap();
|
||||
upsert_embedding(&conn, far_id, &far).unwrap();
|
||||
|
||||
// Global KNN path: nearest first, query image excluded.
|
||||
let global = find_similar_image_ids(&conn, base_id, 2, None).unwrap();
|
||||
assert_eq!(global, vec![close_id, far_id]);
|
||||
|
||||
// Folder-scoped brute-force path returns the same ranking.
|
||||
let scoped = find_similar_image_ids(&conn, base_id, 2, Some(folder_id)).unwrap();
|
||||
assert_eq!(scoped, vec![close_id, far_id]);
|
||||
|
||||
// Images without an embedding yield no matches instead of an error.
|
||||
assert!(find_similar_image_ids(&conn, 9999, 5, None)
|
||||
.unwrap()
|
||||
.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,82 +1,100 @@
|
||||
import { useEffect } from "react";
|
||||
import { useGalleryStore } from "./store";
|
||||
import { Sidebar } from "./components/Sidebar";
|
||||
import { BackgroundTasks } from "./components/BackgroundTasks";
|
||||
import { Toolbar } from "./components/Toolbar";
|
||||
import { Gallery } from "./components/Gallery";
|
||||
import { Lightbox } from "./components/Lightbox";
|
||||
import { TagCloud } from "./components/TagCloud";
|
||||
import { DuplicateFinder } from "./components/DuplicateFinder";
|
||||
import { Timeline } from "./components/Timeline";
|
||||
import { TitleBar } from "./components/TitleBar";
|
||||
import { SettingsModal } from "./components/SettingsModal";
|
||||
import { UpdateToast } from "./components/UpdateToast";
|
||||
import { OnboardingOverlay } from "./components/onboarding/OnboardingOverlay";
|
||||
import { DemoPanel } from "./components/DemoPanel";
|
||||
import { initializeNotifications } from "./notifications";
|
||||
import { useEffect } from 'react'
|
||||
import { useGalleryStore } from './store'
|
||||
import { Sidebar } from './components/Sidebar'
|
||||
import { BackgroundTasks } from './components/BackgroundTasks'
|
||||
import { Toolbar } from './components/Toolbar'
|
||||
import { Gallery } from './components/Gallery'
|
||||
import { Lightbox } from './components/Lightbox'
|
||||
import { ExploreView } from './components/ExploreView'
|
||||
import { DuplicateFinder } from './components/DuplicateFinder'
|
||||
import { Timeline } from './components/Timeline'
|
||||
import { TitleBar } from './components/TitleBar'
|
||||
import { SettingsModal } from './components/SettingsModal'
|
||||
import { FolderPickerModal } from './components/FolderPickerModal'
|
||||
import { UpdateToast } from './components/UpdateToast'
|
||||
import { WhatsNewToast } from './components/WhatsNewToast'
|
||||
import { WhatsNewModal } from './components/WhatsNewModal'
|
||||
import { OnboardingOverlay } from './components/onboarding/OnboardingOverlay'
|
||||
import { DemoPanel } from './dev/DemoPanel'
|
||||
import { initializeNotifications } from './notifications'
|
||||
|
||||
export default function App() {
|
||||
const loadFolders = useGalleryStore((state) => state.loadFolders);
|
||||
const loadBackgroundJobProgress = useGalleryStore((state) => state.loadBackgroundJobProgress);
|
||||
const loadImages = useGalleryStore((state) => state.loadImages);
|
||||
const loadCaptionModelStatus = useGalleryStore((state) => state.loadCaptionModelStatus);
|
||||
const loadDuplicateScanCache = useGalleryStore((state) => state.loadDuplicateScanCache);
|
||||
const loadMutedFolderIds = useGalleryStore((state) => state.loadMutedFolderIds);
|
||||
const loadNotificationsPaused = useGalleryStore((state) => state.loadNotificationsPaused);
|
||||
const subscribeToProgress = useGalleryStore((state) => state.subscribeToProgress);
|
||||
const loadAppVersion = useGalleryStore((state) => state.loadAppVersion);
|
||||
const checkForUpdates = useGalleryStore((state) => state.checkForUpdates);
|
||||
const loadFfmpegStatus = useGalleryStore((state) => state.loadFfmpegStatus);
|
||||
const loadOnboardingCompleted = useGalleryStore((state) => state.loadOnboardingCompleted);
|
||||
const activeView = useGalleryStore((state) => state.activeView);
|
||||
const loadFolders = useGalleryStore((state) => state.loadFolders)
|
||||
const loadBackgroundJobProgress = useGalleryStore((state) => state.loadBackgroundJobProgress)
|
||||
const loadImages = useGalleryStore((state) => state.loadImages)
|
||||
const loadCaptionModelStatus = useGalleryStore((state) => state.loadCaptionModelStatus)
|
||||
const loadTaggerModelStatus = useGalleryStore((state) => state.loadTaggerModelStatus)
|
||||
const loadTaggerModel = useGalleryStore((state) => state.loadTaggerModel)
|
||||
const loadDuplicateScanCache = useGalleryStore((state) => state.loadDuplicateScanCache)
|
||||
const loadAlbums = useGalleryStore((state) => state.loadAlbums)
|
||||
const loadMutedFolderIds = useGalleryStore((state) => state.loadMutedFolderIds)
|
||||
const loadNotificationsPaused = useGalleryStore((state) => state.loadNotificationsPaused)
|
||||
const loadWorkerPausesPersist = useGalleryStore((state) => state.loadWorkerPausesPersist)
|
||||
const subscribeToProgress = useGalleryStore((state) => state.subscribeToProgress)
|
||||
const loadAppVersion = useGalleryStore((state) => state.loadAppVersion)
|
||||
const checkForUpdates = useGalleryStore((state) => state.checkForUpdates)
|
||||
const loadFfmpegStatus = useGalleryStore((state) => state.loadFfmpegStatus)
|
||||
const loadOnboardingCompleted = useGalleryStore((state) => state.loadOnboardingCompleted)
|
||||
const initWhatsNew = useGalleryStore((state) => state.initWhatsNew)
|
||||
const activeView = useGalleryStore((state) => state.activeView)
|
||||
|
||||
useEffect(() => {
|
||||
void initializeNotifications();
|
||||
void loadMutedFolderIds();
|
||||
void loadNotificationsPaused();
|
||||
void loadAppVersion();
|
||||
void loadFfmpegStatus();
|
||||
void loadOnboardingCompleted();
|
||||
void initializeNotifications()
|
||||
void loadMutedFolderIds()
|
||||
void loadNotificationsPaused()
|
||||
void loadWorkerPausesPersist()
|
||||
void loadFfmpegStatus()
|
||||
void loadOnboardingCompleted()
|
||||
// Load the app version first so the What's New toast/modal (which read
|
||||
// appVersion from the store) have it before the greeting can appear.
|
||||
void loadAppVersion().then(() => initWhatsNew())
|
||||
// Quiet launch check — dev builds have no signed artifacts to update to.
|
||||
if (import.meta.env.PROD) {
|
||||
void checkForUpdates({ quiet: true });
|
||||
void checkForUpdates({ quiet: true })
|
||||
}
|
||||
loadFolders().then(() => {
|
||||
void loadBackgroundJobProgress();
|
||||
void loadCaptionModelStatus();
|
||||
void loadDuplicateScanCache();
|
||||
return loadImages(true);
|
||||
});
|
||||
let unlisten: (() => void) | undefined;
|
||||
loadFolders().then(async () => {
|
||||
void loadBackgroundJobProgress()
|
||||
void loadCaptionModelStatus()
|
||||
void loadTaggerModel()
|
||||
void loadTaggerModelStatus()
|
||||
void loadDuplicateScanCache()
|
||||
await loadAlbums()
|
||||
await loadImages(true)
|
||||
if (import.meta.env.MODE === 'ui') {
|
||||
const { applyMockScenario } = await import('./dev/applyMockScenario')
|
||||
applyMockScenario()
|
||||
}
|
||||
})
|
||||
let unlisten: (() => void) | undefined
|
||||
subscribeToProgress().then((fn) => {
|
||||
unlisten = fn;
|
||||
});
|
||||
unlisten = fn
|
||||
})
|
||||
return () => {
|
||||
unlisten?.();
|
||||
};
|
||||
}, []);
|
||||
unlisten?.()
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="flex h-screen flex-col bg-gray-950 text-white overflow-hidden select-none">
|
||||
<div className="flex h-screen flex-col overflow-hidden bg-gray-950 text-white select-none">
|
||||
{/* Custom title bar — sits at the very top */}
|
||||
<TitleBar />
|
||||
|
||||
{/* Main app content below the title bar */}
|
||||
<div className="flex flex-1 min-h-0">
|
||||
<div className="flex min-h-0 flex-1">
|
||||
<Sidebar />
|
||||
<main className="flex-1 flex flex-col min-w-0">
|
||||
{activeView === "timeline" ? (
|
||||
<main className="flex min-w-0 flex-1 flex-col">
|
||||
{activeView === 'timeline' ? (
|
||||
<>
|
||||
<Toolbar />
|
||||
<BackgroundTasks />
|
||||
<Timeline />
|
||||
</>
|
||||
) : activeView === "explore" ? (
|
||||
) : activeView === 'explore' ? (
|
||||
<>
|
||||
<BackgroundTasks />
|
||||
<TagCloud />
|
||||
<ExploreView />
|
||||
</>
|
||||
) : activeView === "duplicates" ? (
|
||||
) : activeView === 'duplicates' ? (
|
||||
<>
|
||||
<BackgroundTasks />
|
||||
<DuplicateFinder />
|
||||
@@ -93,9 +111,12 @@ export default function App() {
|
||||
|
||||
<Lightbox />
|
||||
<SettingsModal />
|
||||
<FolderPickerModal />
|
||||
<UpdateToast />
|
||||
<WhatsNewToast />
|
||||
<WhatsNewModal />
|
||||
<OnboardingOverlay />
|
||||
{import.meta.env.DEV && <DemoPanel />}
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getChangelogForVersion } from './changelog'
|
||||
|
||||
describe('getChangelogForVersion', () => {
|
||||
it('returns null for a null/undefined version', () => {
|
||||
expect(getChangelogForVersion(null)).toBeNull()
|
||||
expect(getChangelogForVersion(undefined)).toBeNull()
|
||||
})
|
||||
|
||||
it('never surfaces the in-progress Unreleased section', () => {
|
||||
expect(getChangelogForVersion('Unreleased')).toBeNull()
|
||||
expect(getChangelogForVersion('unreleased')).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for a version with no matching entry', () => {
|
||||
expect(getChangelogForVersion('99.9.9')).toBeNull()
|
||||
})
|
||||
|
||||
it('resolves a plain released version', () => {
|
||||
const entry = getChangelogForVersion('0.1.1')
|
||||
expect(entry?.version).toBe('0.1.1')
|
||||
expect(entry?.date).toBe('2026-06-23')
|
||||
})
|
||||
|
||||
it('strips a leading "v" from the version string', () => {
|
||||
expect(getChangelogForVersion('v0.1.1')?.version).toBe('0.1.1')
|
||||
})
|
||||
|
||||
it('strips dev/UI-lab build suffixes so they resolve to the base version', () => {
|
||||
expect(getChangelogForVersion('0.1.1-dev')?.version).toBe('0.1.1')
|
||||
expect(getChangelogForVersion('0.1.1-ui')?.version).toBe('0.1.1')
|
||||
expect(getChangelogForVersion('0.1.1-beta.1')?.version).toBe('0.1.1')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,176 @@
|
||||
// Parses the project CHANGELOG.md (imported raw at build time) into structured
|
||||
// data so the "What's New" UI can render it nicely instead of dumping markdown.
|
||||
// Keeping the changelog as the single source of truth means there's no separate
|
||||
// per-release copy to maintain — whatever ships in CHANGELOG.md is what users see.
|
||||
import changelogRaw from '../CHANGELOG.md?raw'
|
||||
|
||||
export interface ChangelogItem {
|
||||
/** The bold lead-in at the start of a bullet (e.g. "Custom multi-folder picker"), if any. */
|
||||
lead: string | null
|
||||
/** The remaining descriptive text. May still contain inline `code` / **bold** markers. */
|
||||
body: string
|
||||
}
|
||||
|
||||
export interface ChangelogSection {
|
||||
/** "Added" | "Changed" | "Fixed" | "Removed" | "Deprecated" | "Security" */
|
||||
title: string
|
||||
items: ChangelogItem[]
|
||||
}
|
||||
|
||||
export interface ChangelogEntry {
|
||||
version: string
|
||||
date: string | null
|
||||
sections: ChangelogSection[]
|
||||
}
|
||||
|
||||
// "## [0.1.1] — 2026-06-23" / "## [Unreleased]"
|
||||
const VERSION_HEADING = /^##\s+\[([^\]]+)\]\s*(?:[—–-]\s*(.+?)\s*)?$/
|
||||
// "### Added"
|
||||
const SECTION_HEADING = /^###\s+(.+?)\s*$/
|
||||
// "- bullet text"
|
||||
const BULLET = /^[-*]\s+(.*)$/
|
||||
// Leading "**Title**" optionally followed by an em dash, used as the item's lead-in.
|
||||
// (Item text is whitespace-collapsed before matching, so no dotAll flag needed.)
|
||||
const LEAD = /^\*\*(.+?)\*\*\s*(?:[—–-]\s*)?(.*)$/
|
||||
|
||||
function toItem(text: string): ChangelogItem {
|
||||
const collapsed = text.replace(/\s+/g, ' ').trim()
|
||||
const match = collapsed.match(LEAD)
|
||||
if (match) {
|
||||
return { lead: match[1].trim(), body: match[2].trim() }
|
||||
}
|
||||
return { lead: null, body: collapsed }
|
||||
}
|
||||
|
||||
function parseChangelog(raw: string): ChangelogEntry[] {
|
||||
const lines = raw.split(/\r?\n/)
|
||||
const entries: ChangelogEntry[] = []
|
||||
|
||||
let entry: ChangelogEntry | null = null
|
||||
let section: ChangelogSection | null = null
|
||||
let buffer: string[] = []
|
||||
|
||||
const flushItem = () => {
|
||||
if (section && buffer.length > 0) {
|
||||
section.items.push(toItem(buffer.join(' ')))
|
||||
}
|
||||
buffer = []
|
||||
}
|
||||
|
||||
for (const line of lines) {
|
||||
const versionMatch = line.match(VERSION_HEADING)
|
||||
if (versionMatch) {
|
||||
flushItem()
|
||||
section = null
|
||||
entry = {
|
||||
version: versionMatch[1].trim(),
|
||||
date: versionMatch[2]?.trim() ?? null,
|
||||
sections: [],
|
||||
}
|
||||
entries.push(entry)
|
||||
continue
|
||||
}
|
||||
|
||||
// Stop collecting once we leave the changelog body (e.g. link-reference defs at EOF).
|
||||
if (!entry) continue
|
||||
|
||||
const sectionMatch = line.match(SECTION_HEADING)
|
||||
if (sectionMatch) {
|
||||
flushItem()
|
||||
section = { title: sectionMatch[1].trim(), items: [] }
|
||||
entry.sections.push(section)
|
||||
continue
|
||||
}
|
||||
|
||||
const bulletMatch = line.match(BULLET)
|
||||
if (bulletMatch) {
|
||||
flushItem()
|
||||
buffer.push(bulletMatch[1])
|
||||
continue
|
||||
}
|
||||
|
||||
if (line.trim() === '') {
|
||||
// A blank line ends a (possibly wrapped) multi-line bullet.
|
||||
flushItem()
|
||||
continue
|
||||
}
|
||||
|
||||
// Indented continuation of the current wrapped bullet.
|
||||
if (buffer.length > 0) {
|
||||
buffer.push(line.trim())
|
||||
}
|
||||
}
|
||||
|
||||
flushItem()
|
||||
return entries.map((e) => ({ ...e, sections: e.sections.filter((s) => s.items.length > 0) }))
|
||||
}
|
||||
|
||||
const ENTRIES = parseChangelog(changelogRaw)
|
||||
|
||||
// Synthetic small release for UI Lab (`?changelog=small`). The What's New modal
|
||||
// switches layout by release size, and every real entry in CHANGELOG.md is
|
||||
// large — so the compact single-column layout can't be exercised from real
|
||||
// data. This stays below the modal's rail threshold on purpose.
|
||||
const SMALL_PREVIEW_ENTRY: ChangelogEntry = {
|
||||
version: '0.0.0-preview',
|
||||
date: '2026-01-01',
|
||||
sections: [
|
||||
{
|
||||
title: 'Added',
|
||||
items: [
|
||||
{
|
||||
lead: 'Sample setting',
|
||||
body: 'a small toggle that exists purely so this preview has an Added section.',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Changed',
|
||||
items: [
|
||||
{
|
||||
lead: 'Snappier previews',
|
||||
body: 'the preview fixture now loads instantly, because it is made up.',
|
||||
},
|
||||
{ lead: null, body: 'A plain full-sentence bullet without a bold lead, for coverage.' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Fixed',
|
||||
items: [
|
||||
{
|
||||
lead: 'Hotfix-sized fix',
|
||||
body: 'a believable one-liner about a bug that never shipped.',
|
||||
},
|
||||
{
|
||||
lead: 'Another small fix',
|
||||
body: 'keeps the total item count comfortably under the rail threshold.',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
// UI Lab affordance (browser-only `ui` mode): `?changelog=` previews an entry
|
||||
// other than the running version's, mirroring the `?scenario=` pattern.
|
||||
// ?changelog=unreleased — the in-progress [Unreleased] notes (large release)
|
||||
// ?changelog=small — synthetic hotfix-sized entry (compact layout)
|
||||
// ?changelog=0.1.1 — any specific released version
|
||||
function previewOverride(): ChangelogEntry | null {
|
||||
if (import.meta.env.MODE !== 'ui') return null
|
||||
const preview = new URLSearchParams(window.location.search).get('changelog')
|
||||
if (!preview) return null
|
||||
if (preview === 'small') return SMALL_PREVIEW_ENTRY
|
||||
return ENTRIES.find((e) => e.version.toLowerCase() === preview.toLowerCase()) ?? null
|
||||
}
|
||||
|
||||
export function getChangelogForVersion(version: string | null | undefined): ChangelogEntry | null {
|
||||
const override = previewOverride()
|
||||
if (override) return override
|
||||
if (!version) return null
|
||||
// Strip leading "v" and any build suffix (e.g. "-ui", "-dev", "-beta.1") so
|
||||
// dev/UI-lab builds still resolve to the correct changelog entry.
|
||||
const normalized = version.replace(/^v/, '').replace(/-[a-z].*/i, '')
|
||||
// Never surface the in-progress [Unreleased] section to users.
|
||||
if (normalized.toLowerCase() === 'unreleased') return null
|
||||
return ENTRIES.find((e) => e.version.replace(/^v/, '') === normalized) ?? null
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { useState } from 'react'
|
||||
import { useGalleryStore } from '../store'
|
||||
|
||||
/**
|
||||
* Album list plus a create-new-album form. The host decides what picking
|
||||
* means — the bulk bar adds the current selection; a newly created album is
|
||||
* picked immediately.
|
||||
*/
|
||||
export function AlbumPicker({ onPick }: { onPick: (albumId: number) => Promise<void> | void }) {
|
||||
const albums = useGalleryStore((state) => state.albums)
|
||||
const createAlbum = useGalleryStore((state) => state.createAlbum)
|
||||
const [creating, setCreating] = useState(false)
|
||||
const [newAlbumName, setNewAlbumName] = useState('')
|
||||
|
||||
const handleCreate = async () => {
|
||||
const name = newAlbumName.trim()
|
||||
if (!name || creating) return
|
||||
setCreating(true)
|
||||
try {
|
||||
const album = await createAlbum(name)
|
||||
setNewAlbumName('')
|
||||
await onPick(album.id)
|
||||
} finally {
|
||||
setCreating(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="max-h-48 overflow-y-auto">
|
||||
{albums.length === 0 ? (
|
||||
<p className="px-2 py-2 text-[11px] text-gray-600">No albums yet — create one below.</p>
|
||||
) : (
|
||||
albums.map((album) => (
|
||||
<button
|
||||
key={album.id}
|
||||
className="flex w-full items-center justify-between gap-2 rounded-md px-2 py-1.5 text-left text-xs text-gray-300 transition-colors hover:bg-white/5 hover:text-white"
|
||||
onClick={() => void onPick(album.id)}
|
||||
>
|
||||
<span className="truncate">{album.name}</span>
|
||||
<span className="shrink-0 text-[10px] text-gray-600">{album.image_count}</span>
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
<form
|
||||
className="mt-1 flex gap-1 border-t border-white/[0.06] pt-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
void handleCreate()
|
||||
}}
|
||||
>
|
||||
<input
|
||||
className="min-w-0 flex-1 rounded-md border border-white/10 bg-white/5 px-2 py-1 text-xs text-white placeholder-gray-600 focus:border-white/20 focus:outline-none"
|
||||
placeholder="New album…"
|
||||
value={newAlbumName}
|
||||
onChange={(event) => setNewAlbumName(event.target.value)}
|
||||
disabled={creating}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
className="rounded-md border border-white/10 bg-white/5 px-2 py-1 text-xs text-gray-300 transition-colors hover:bg-white/10 hover:text-white disabled:opacity-50"
|
||||
disabled={creating || !newAlbumName.trim()}
|
||||
>
|
||||
Add
|
||||
</button>
|
||||
</form>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,524 +1,155 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { useGalleryStore, WorkerKey } from "../store";
|
||||
|
||||
const WORKER_FOR_STAGE: Record<string, WorkerKey> = {
|
||||
Thumbnails: "thumbnail",
|
||||
Metadata: "metadata",
|
||||
Embeddings: "embedding",
|
||||
Tags: "tagging",
|
||||
};
|
||||
|
||||
interface TaskStage {
|
||||
label: string;
|
||||
detail: string;
|
||||
progress: number | null; // 0–100, or null for indeterminate
|
||||
failed: boolean;
|
||||
}
|
||||
|
||||
interface Task {
|
||||
id: number;
|
||||
name: string;
|
||||
stages: TaskStage[];
|
||||
hasFailedEmbeddings: boolean;
|
||||
hasFailedTagging: boolean;
|
||||
hasFailedCaptions: boolean;
|
||||
pendingMediaWork: number;
|
||||
embeddingProcessed: number;
|
||||
embeddingTotal: number;
|
||||
currentFile: string | null;
|
||||
snapshot: string;
|
||||
}
|
||||
|
||||
interface FailedEmbeddingItem {
|
||||
image_id: number;
|
||||
filename: string;
|
||||
error: string | null;
|
||||
}
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
import { useGalleryStore, type WorkerKey } from '../store'
|
||||
import { BackgroundTaskSummary } from './backgroundTasks/BackgroundTaskSummary'
|
||||
import { ExpandedTaskPanel } from './backgroundTasks/ExpandedTaskPanel'
|
||||
import {
|
||||
buildDuplicateScanTask,
|
||||
buildFolderTasks,
|
||||
taskHasTerminalFailure,
|
||||
taskProgress,
|
||||
} from './backgroundTasks/taskModel'
|
||||
import type { BackgroundTask, FailedWorkerItem } from './backgroundTasks/types'
|
||||
|
||||
export function BackgroundTasks() {
|
||||
const folders = useGalleryStore((state) => state.folders);
|
||||
const indexingProgress = useGalleryStore((state) => state.indexingProgress);
|
||||
const mediaJobProgress = useGalleryStore((state) => state.mediaJobProgress);
|
||||
const retryFailedEmbeddings = useGalleryStore((state) => state.retryFailedEmbeddings);
|
||||
const queueTaggingJobs = useGalleryStore((state) => state.queueTaggingJobs);
|
||||
const duplicateScanning = useGalleryStore((state) => state.duplicateScanning);
|
||||
const duplicateScanProgress = useGalleryStore((state) => state.duplicateScanProgress);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [dismissed, setDismissed] = useState<Record<number, string>>({});
|
||||
const [failedItems, setFailedItems] = useState<Record<number, FailedEmbeddingItem[]>>({});
|
||||
|
||||
const workerPaused = useGalleryStore((state) => state.workerPaused);
|
||||
const loadWorkerStates = useGalleryStore((state) => state.loadWorkerStates);
|
||||
const setWorkerPaused = useGalleryStore((state) => state.setWorkerPaused);
|
||||
const folders = useGalleryStore((state) => state.folders)
|
||||
const indexingProgress = useGalleryStore((state) => state.indexingProgress)
|
||||
const mediaJobProgress = useGalleryStore((state) => state.mediaJobProgress)
|
||||
const retryFailedEmbeddings = useGalleryStore((state) => state.retryFailedEmbeddings)
|
||||
const queueTaggingJobs = useGalleryStore((state) => state.queueTaggingJobs)
|
||||
const showFailedTagging = useGalleryStore((state) => state.showFailedTagging)
|
||||
const duplicateScanning = useGalleryStore((state) => state.duplicateScanning)
|
||||
const duplicateScanProgress = useGalleryStore((state) => state.duplicateScanProgress)
|
||||
const workerPaused = useGalleryStore((state) => state.workerPaused)
|
||||
const loadWorkerStates = useGalleryStore((state) => state.loadWorkerStates)
|
||||
const setWorkerPaused = useGalleryStore((state) => state.setWorkerPaused)
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
const [dismissed, setDismissed] = useState<Record<number, string>>({})
|
||||
const [failedEmbeddingItems, setFailedEmbeddingItems] = useState<
|
||||
Record<number, FailedWorkerItem[]>
|
||||
>({})
|
||||
const [failedTaggingItems, setFailedTaggingItems] = useState<Record<number, FailedWorkerItem[]>>(
|
||||
{}
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
void loadWorkerStates();
|
||||
}, [folders, loadWorkerStates]);
|
||||
void loadWorkerStates()
|
||||
}, [folders, loadWorkerStates])
|
||||
|
||||
// Fetch failed embedding filenames whenever the expanded panel opens or failure counts change.
|
||||
const failedCounts = useMemo(
|
||||
const failedEmbeddingCounts = useMemo(
|
||||
() =>
|
||||
Object.fromEntries(
|
||||
Object.entries(mediaJobProgress).map(([id, p]) => [id, p?.embedding_failed ?? 0]),
|
||||
Object.entries(mediaJobProgress).map(([id, progress]) => [
|
||||
id,
|
||||
progress?.embedding_failed ?? 0,
|
||||
])
|
||||
),
|
||||
[mediaJobProgress],
|
||||
);
|
||||
[mediaJobProgress]
|
||||
)
|
||||
const failedTaggingCounts = useMemo(
|
||||
() =>
|
||||
Object.fromEntries(
|
||||
Object.entries(mediaJobProgress).map(([id, progress]) => [
|
||||
id,
|
||||
progress?.tagging_failed ?? 0,
|
||||
])
|
||||
),
|
||||
[mediaJobProgress]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!expanded) return;
|
||||
for (const [folderId, count] of Object.entries(failedCounts)) {
|
||||
if (!expanded) return
|
||||
for (const [folderId, count] of Object.entries(failedEmbeddingCounts)) {
|
||||
if (count > 0) {
|
||||
invoke<FailedEmbeddingItem[]>("get_failed_embedding_images", {
|
||||
invoke<FailedWorkerItem[]>('get_failed_embedding_images', {
|
||||
folderId: Number(folderId),
|
||||
})
|
||||
.then((items) => setFailedItems((prev) => ({ ...prev, [folderId]: items })))
|
||||
.catch(() => undefined);
|
||||
.then((items) => setFailedEmbeddingItems((prev) => ({ ...prev, [folderId]: items })))
|
||||
.catch(() => undefined)
|
||||
}
|
||||
}
|
||||
}, [expanded, failedCounts]);
|
||||
for (const [folderId, count] of Object.entries(failedTaggingCounts)) {
|
||||
if (count > 0) {
|
||||
invoke<FailedWorkerItem[]>('get_failed_tagging_images', {
|
||||
folderId: Number(folderId),
|
||||
})
|
||||
.then((items) => setFailedTaggingItems((prev) => ({ ...prev, [folderId]: items })))
|
||||
.catch(() => undefined)
|
||||
}
|
||||
}
|
||||
}, [expanded, failedEmbeddingCounts, failedTaggingCounts])
|
||||
|
||||
const isWorkerPaused = (folderId: number, worker: WorkerKey) => {
|
||||
return workerPaused[folderId]?.[worker] ?? false;
|
||||
};
|
||||
const folderTasks = useMemo(
|
||||
() =>
|
||||
buildFolderTasks({
|
||||
dismissed,
|
||||
folders,
|
||||
indexingProgress,
|
||||
mediaJobProgress,
|
||||
workerPaused,
|
||||
}),
|
||||
[dismissed, folders, indexingProgress, mediaJobProgress, workerPaused]
|
||||
)
|
||||
|
||||
const duplicateScanTask = useMemo(
|
||||
() => buildDuplicateScanTask(duplicateScanning, duplicateScanProgress),
|
||||
[duplicateScanning, duplicateScanProgress]
|
||||
)
|
||||
const allTasks = duplicateScanTask ? [duplicateScanTask, ...folderTasks] : folderTasks
|
||||
|
||||
if (allTasks.length === 0) return null
|
||||
|
||||
const isWorkerPaused = (folderId: number, worker: WorkerKey) =>
|
||||
workerPaused[folderId]?.[worker] ?? false
|
||||
|
||||
const toggleWorker = (folderId: number, worker: WorkerKey) => {
|
||||
setWorkerPaused(folderId, worker, !isWorkerPaused(folderId, worker));
|
||||
};
|
||||
|
||||
const dismissTask = (id: number, snapshot: string) => {
|
||||
if (id < 0) return; // system tasks (duplicate scan) cannot be dismissed
|
||||
setDismissed((prev) => ({ ...prev, [id]: snapshot }));
|
||||
setExpanded(false);
|
||||
};
|
||||
|
||||
const tasks = useMemo<Task[]>(() => {
|
||||
return folders
|
||||
.map((folder): Task | null => {
|
||||
const index = indexingProgress[folder.id];
|
||||
const jobs = mediaJobProgress[folder.id];
|
||||
|
||||
const thumbnailPending = jobs?.thumbnail_pending ?? 0;
|
||||
const metadataPending = jobs?.metadata_pending ?? 0;
|
||||
const embeddingPending = jobs?.embedding_pending ?? 0;
|
||||
const embeddingReady = jobs?.embedding_ready ?? 0;
|
||||
const embeddingFailed = jobs?.embedding_failed ?? 0;
|
||||
const taggingPending = jobs?.tagging_pending ?? 0;
|
||||
const taggingReady = jobs?.tagging_ready ?? 0;
|
||||
const taggingFailed = jobs?.tagging_failed ?? 0;
|
||||
const captionPending = jobs?.caption_pending ?? 0;
|
||||
const captionReady = jobs?.caption_ready ?? 0;
|
||||
const captionFailed = jobs?.caption_failed ?? 0;
|
||||
|
||||
const pendingMediaWork = thumbnailPending + metadataPending + embeddingPending + taggingPending + captionPending;
|
||||
const embeddingProcessed = embeddingReady + embeddingFailed;
|
||||
const embeddingTotal = embeddingProcessed + embeddingPending;
|
||||
const taggingProcessed = taggingReady + taggingFailed;
|
||||
const taggingTotal = taggingProcessed + taggingPending;
|
||||
const captionProcessed = captionReady + captionFailed;
|
||||
const captionTotal = captionProcessed + captionPending;
|
||||
const hasFailedEmbeddings = embeddingFailed > 0;
|
||||
const hasFailedTagging = taggingFailed > 0;
|
||||
const hasFailedCaptions = captionFailed > 0;
|
||||
|
||||
if (!index && pendingMediaWork === 0 && !hasFailedEmbeddings && !hasFailedTagging && !hasFailedCaptions) return null;
|
||||
|
||||
const stages: TaskStage[] = [];
|
||||
|
||||
if (index && !index.done) {
|
||||
const pct = index.total > 0 ? (index.indexed / index.total) * 100 : 0;
|
||||
stages.push({
|
||||
label: "Scanning",
|
||||
detail: `${index.indexed.toLocaleString()} / ${index.total.toLocaleString()}`,
|
||||
progress: pct,
|
||||
failed: false,
|
||||
});
|
||||
setWorkerPaused(folderId, worker, !isWorkerPaused(folderId, worker))
|
||||
}
|
||||
|
||||
if (thumbnailPending > 0) {
|
||||
stages.push({
|
||||
label: "Thumbnails",
|
||||
detail: thumbnailPending.toLocaleString(),
|
||||
progress: null,
|
||||
failed: false,
|
||||
});
|
||||
const dismissTask = (task: BackgroundTask) => {
|
||||
if (task.id < 0) return
|
||||
setDismissed((prev) => ({ ...prev, [task.id]: task.snapshot }))
|
||||
setExpanded(false)
|
||||
}
|
||||
|
||||
if (metadataPending > 0) {
|
||||
stages.push({
|
||||
label: "Metadata",
|
||||
detail: metadataPending.toLocaleString(),
|
||||
progress: null,
|
||||
failed: false,
|
||||
});
|
||||
const retryTask = (task: BackgroundTask) => {
|
||||
if (task.hasFailedEmbeddings) void retryFailedEmbeddings(task.id)
|
||||
if (task.hasFailedTagging) void queueTaggingJobs(task.id)
|
||||
}
|
||||
|
||||
if (embeddingPending > 0) {
|
||||
const pct = embeddingTotal > 0 ? (embeddingProcessed / embeddingTotal) * 100 : 0;
|
||||
stages.push({
|
||||
label: "Embeddings",
|
||||
detail: `${embeddingProcessed.toLocaleString()} / ${embeddingTotal.toLocaleString()}`,
|
||||
progress: pct,
|
||||
failed: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (taggingPending > 0) {
|
||||
const pct = taggingTotal > 0 ? (taggingProcessed / taggingTotal) * 100 : 0;
|
||||
stages.push({
|
||||
label: "Tags",
|
||||
detail: `${taggingProcessed.toLocaleString()} / ${taggingTotal.toLocaleString()}`,
|
||||
progress: pct,
|
||||
failed: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (captionPending > 0) {
|
||||
const pct = captionTotal > 0 ? (captionProcessed / captionTotal) * 100 : 0;
|
||||
stages.push({
|
||||
label: "Captions",
|
||||
detail: `${captionProcessed.toLocaleString()} / ${captionTotal.toLocaleString()}`,
|
||||
progress: pct,
|
||||
failed: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (hasFailedEmbeddings && pendingMediaWork === 0) {
|
||||
stages.push({
|
||||
label: "Failed",
|
||||
detail: `${embeddingFailed.toLocaleString()} embeddings`,
|
||||
progress: null,
|
||||
failed: true,
|
||||
});
|
||||
}
|
||||
|
||||
if (hasFailedTagging && pendingMediaWork === 0) {
|
||||
stages.push({
|
||||
label: "Failed",
|
||||
detail: `${taggingFailed.toLocaleString()} tags`,
|
||||
progress: null,
|
||||
failed: true,
|
||||
});
|
||||
}
|
||||
|
||||
if (hasFailedCaptions && pendingMediaWork === 0) {
|
||||
stages.push({
|
||||
label: "Failed",
|
||||
detail: `${captionFailed.toLocaleString()} captions`,
|
||||
progress: null,
|
||||
failed: true,
|
||||
});
|
||||
}
|
||||
|
||||
const snapshot = `${pendingMediaWork}:${embeddingFailed}:${taggingFailed}:${captionFailed}`;
|
||||
|
||||
return {
|
||||
id: folder.id,
|
||||
name: folder.name,
|
||||
stages,
|
||||
hasFailedEmbeddings,
|
||||
hasFailedTagging,
|
||||
hasFailedCaptions,
|
||||
pendingMediaWork,
|
||||
embeddingProcessed,
|
||||
embeddingTotal,
|
||||
currentFile: index && !index.done ? (index.current_file || null) : null,
|
||||
snapshot,
|
||||
};
|
||||
})
|
||||
.filter((t): t is Task => t !== null)
|
||||
.filter((t) => dismissed[t.id] !== t.snapshot);
|
||||
}, [folders, indexingProgress, mediaJobProgress, dismissed]);
|
||||
|
||||
// Synthetic task for duplicate scanning — negative id so dismiss/retry are suppressed
|
||||
const duplicateScanTask: Task | null = duplicateScanning ? {
|
||||
id: -1,
|
||||
name: "Duplicate Scan",
|
||||
stages: [{
|
||||
label: duplicateScanProgress?.phase === "checking"
|
||||
? "Checking"
|
||||
: duplicateScanProgress?.phase === "confirming"
|
||||
? "Confirming"
|
||||
: "Hashing",
|
||||
detail: duplicateScanProgress
|
||||
? `${duplicateScanProgress.processed.toLocaleString()} / ${duplicateScanProgress.total.toLocaleString()}${duplicateScanProgress.skipped > 0 ? ` · ${duplicateScanProgress.skipped.toLocaleString()} skipped` : ""}`
|
||||
: "Starting…",
|
||||
progress: duplicateScanProgress && duplicateScanProgress.total > 0
|
||||
? (duplicateScanProgress.processed / duplicateScanProgress.total) * 100
|
||||
: null,
|
||||
failed: false,
|
||||
}],
|
||||
hasFailedEmbeddings: false,
|
||||
hasFailedTagging: false,
|
||||
hasFailedCaptions: false,
|
||||
pendingMediaWork: 1,
|
||||
embeddingProcessed: 0,
|
||||
embeddingTotal: 0,
|
||||
currentFile: null,
|
||||
snapshot: "",
|
||||
} : null;
|
||||
|
||||
const allTasks = duplicateScanTask ? [duplicateScanTask, ...tasks] : tasks;
|
||||
|
||||
if (allTasks.length === 0) return null;
|
||||
|
||||
const primary = allTasks[0];
|
||||
const extraCount = allTasks.length - 1;
|
||||
const hasFailed = tasks.some((t) => (t.hasFailedEmbeddings || t.hasFailedTagging || t.hasFailedCaptions) && t.pendingMediaWork === 0);
|
||||
|
||||
// Best progress bar value: use embedding progress if available (most informative),
|
||||
// otherwise tagging progress, otherwise fall back to scanning progress, otherwise indeterminate.
|
||||
const embeddingStage = primary.stages.find((s) => s.label === "Embeddings");
|
||||
const taggingStage = primary.stages.find((s) => s.label === "Tags");
|
||||
const scanningStage = primary.stages.find((s) => s.label === "Scanning");
|
||||
const duplicateStage = primary.id === -1 ? primary.stages[0] : null;
|
||||
const barProgress = embeddingStage?.progress ?? taggingStage?.progress ?? scanningStage?.progress ?? duplicateStage?.progress ?? null;
|
||||
const primary = allTasks[0]
|
||||
const hasFailed = folderTasks.some(taskHasTerminalFailure)
|
||||
const barProgress = taskProgress(primary)
|
||||
|
||||
return (
|
||||
<div className="shrink-0 border-b border-white/[0.06]">
|
||||
{/* Slim bar */}
|
||||
<div
|
||||
className={`group flex items-center gap-3 px-5 h-11 cursor-pointer select-none transition-colors ${
|
||||
expanded ? "bg-white/[0.03]" : "hover:bg-white/[0.02]"
|
||||
}`}
|
||||
onClick={() => setExpanded((v) => !v)}
|
||||
>
|
||||
{/* Pulse dot */}
|
||||
<div className="relative shrink-0">
|
||||
<div className={`h-1.5 w-1.5 rounded-full ${hasFailed ? "bg-amber-400" : "bg-blue-400"}`} />
|
||||
<div className={`absolute inset-0 h-1.5 w-1.5 rounded-full animate-ping opacity-60 ${hasFailed ? "bg-amber-400" : "bg-blue-400"}`} />
|
||||
</div>
|
||||
|
||||
{/* Folder name */}
|
||||
<span className="text-[13px] font-medium text-white/60 shrink-0">{primary.name}</span>
|
||||
|
||||
{/* Stage tags — all active stages visible simultaneously */}
|
||||
<div className="flex items-center gap-1.5 flex-1 min-w-0 overflow-hidden">
|
||||
{primary.stages.map((stage) => {
|
||||
const workerKey = WORKER_FOR_STAGE[stage.label];
|
||||
const isPaused = workerKey ? isWorkerPaused(primary.id, workerKey) : false;
|
||||
return (
|
||||
<span
|
||||
key={stage.label}
|
||||
className={`flex items-center gap-1 rounded-md px-2 py-0.5 text-[11px] shrink-0 ${
|
||||
stage.failed
|
||||
? "bg-amber-500/10 text-amber-400"
|
||||
: isPaused
|
||||
? "bg-white/4 text-gray-600"
|
||||
: "bg-white/5 text-gray-400"
|
||||
}`}
|
||||
>
|
||||
<span>{stage.label}</span>
|
||||
<span className={`tabular-nums ${stage.failed ? "text-amber-500" : isPaused ? "text-gray-700" : "text-gray-600"}`}>
|
||||
{stage.detail}
|
||||
</span>
|
||||
{workerKey && (
|
||||
<button
|
||||
className="ml-0.5 opacity-0 group-hover:opacity-100 hover:text-white transition-opacity"
|
||||
title={isPaused ? `Resume ${stage.label}` : `Pause ${stage.label}`}
|
||||
onClick={(e) => { e.stopPropagation(); toggleWorker(primary.id, workerKey); }}
|
||||
>
|
||||
{isPaused ? (
|
||||
<svg className="h-2.5 w-2.5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="h-2.5 w-2.5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Progress bar — embedding or scanning progress, pulsing if indeterminate */}
|
||||
<div className="w-24 h-px bg-white/8 rounded-full overflow-hidden shrink-0">
|
||||
<div
|
||||
className={`h-full rounded-full transition-all duration-500 ${
|
||||
hasFailed
|
||||
? "bg-amber-400/60"
|
||||
: barProgress === null
|
||||
? "bg-blue-500/40 animate-pulse w-full"
|
||||
: "bg-blue-500"
|
||||
}`}
|
||||
style={barProgress !== null ? { width: `${barProgress}%` } : undefined}
|
||||
<BackgroundTaskSummary
|
||||
expanded={expanded}
|
||||
extraCount={allTasks.length - 1}
|
||||
hasFailed={hasFailed}
|
||||
isWorkerPaused={isWorkerPaused}
|
||||
onDismiss={dismissTask}
|
||||
onLocate={showFailedTagging}
|
||||
onRetry={retryTask}
|
||||
onToggleExpanded={() => setExpanded((value) => !value)}
|
||||
onToggleWorker={toggleWorker}
|
||||
primary={primary}
|
||||
progress={barProgress}
|
||||
taskCount={allTasks.length}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Extra folders badge */}
|
||||
{extraCount > 0 && (
|
||||
<span className="rounded-full bg-white/8 px-2 py-0.5 text-[10px] text-gray-500 shrink-0">
|
||||
+{extraCount}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{/* Retry (failed embeddings only) */}
|
||||
{primary.hasFailedEmbeddings && primary.pendingMediaWork === 0 && (
|
||||
<button
|
||||
className="rounded-lg border border-amber-500/20 bg-amber-500/10 px-2.5 py-1 text-[11px] text-amber-300 hover:bg-amber-500/20 transition-colors shrink-0"
|
||||
onClick={(e) => { e.stopPropagation(); void retryFailedEmbeddings(primary.id); }}
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Expand chevron (only when multiple tasks) */}
|
||||
{allTasks.length > 1 && (
|
||||
<svg
|
||||
className={`h-3.5 w-3.5 text-gray-600 transition-transform duration-200 shrink-0 ${expanded ? "rotate-180" : ""}`}
|
||||
fill="none" viewBox="0 0 24 24" stroke="currentColor"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
|
||||
</svg>
|
||||
)}
|
||||
|
||||
{/* Dismiss — hidden for system tasks like duplicate scan */}
|
||||
{primary.id >= 0 && (
|
||||
<button
|
||||
className="p-1 rounded-md text-gray-600 hover:text-gray-300 hover:bg-white/8 transition-colors shrink-0"
|
||||
title="Dismiss"
|
||||
onClick={(e) => { e.stopPropagation(); dismissTask(primary.id, primary.snapshot); }}
|
||||
>
|
||||
<svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Expanded panel — one row per folder */}
|
||||
{expanded && (
|
||||
<div className="border-t border-white/[0.06] bg-white/[0.02] px-5 py-3 space-y-3">
|
||||
{allTasks.map((task) => {
|
||||
const taskEmbeddingStage = task.stages.find((s) => s.label === "Embeddings");
|
||||
const taskTaggingStage = task.stages.find((s) => s.label === "Tags");
|
||||
const taskScanningStage = task.stages.find((s) => s.label === "Scanning");
|
||||
const taskDuplicateStage = task.id === -1 ? task.stages[0] : null;
|
||||
const taskBarProgress = taskEmbeddingStage?.progress ?? taskTaggingStage?.progress ?? taskScanningStage?.progress ?? taskDuplicateStage?.progress ?? null;
|
||||
const taskHasFailed = (task.hasFailedEmbeddings || task.hasFailedTagging || task.hasFailedCaptions) && task.pendingMediaWork === 0;
|
||||
|
||||
return (
|
||||
<div key={task.id}>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-[12px] text-white/50 w-28 truncate shrink-0">{task.name}</span>
|
||||
|
||||
<div className="flex items-center gap-1.5 flex-1 min-w-0 overflow-hidden">
|
||||
{task.stages.map((stage) => {
|
||||
const workerKey = WORKER_FOR_STAGE[stage.label];
|
||||
const isPaused = workerKey ? isWorkerPaused(task.id, workerKey) : false;
|
||||
return (
|
||||
<span
|
||||
key={stage.label}
|
||||
className={`flex items-center gap-1 rounded-md px-2 py-0.5 text-[11px] shrink-0 ${
|
||||
stage.failed
|
||||
? "bg-amber-500/10 text-amber-400"
|
||||
: isPaused
|
||||
? "bg-white/4 text-gray-600"
|
||||
: "bg-white/5 text-gray-500"
|
||||
}`}
|
||||
>
|
||||
{isPaused && (
|
||||
<svg className="h-2 w-2 text-gray-600" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z" />
|
||||
</svg>
|
||||
)}
|
||||
<span>{stage.label}</span>
|
||||
<span className={`tabular-nums ${stage.failed ? "text-amber-500" : "text-gray-600"}`}>
|
||||
{stage.detail}
|
||||
</span>
|
||||
{workerKey && (
|
||||
<button
|
||||
className="ml-0.5 text-gray-600 hover:text-white transition-colors"
|
||||
title={isPaused ? `Resume ${stage.label}` : `Pause ${stage.label}`}
|
||||
onClick={() => toggleWorker(task.id, workerKey)}
|
||||
>
|
||||
{isPaused ? (
|
||||
<svg className="h-2.5 w-2.5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="h-2.5 w-2.5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="w-20 h-px bg-white/8 rounded-full overflow-hidden shrink-0">
|
||||
<div
|
||||
className={`h-full rounded-full transition-all duration-500 ${
|
||||
taskHasFailed
|
||||
? "bg-amber-400/60"
|
||||
: taskBarProgress === null
|
||||
? "bg-blue-500/40 animate-pulse w-full"
|
||||
: "bg-blue-500"
|
||||
}`}
|
||||
style={taskBarProgress !== null ? { width: `${taskBarProgress}%` } : undefined}
|
||||
{expanded ? (
|
||||
<ExpandedTaskPanel
|
||||
failedEmbeddingItems={failedEmbeddingItems}
|
||||
failedTaggingItems={failedTaggingItems}
|
||||
isWorkerPaused={isWorkerPaused}
|
||||
onDismiss={dismissTask}
|
||||
onLocate={showFailedTagging}
|
||||
onRetry={retryTask}
|
||||
onToggleWorker={toggleWorker}
|
||||
tasks={allTasks}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{taskHasFailed && (
|
||||
<button
|
||||
className="rounded-lg border border-amber-500/20 bg-amber-500/10 px-2 py-0.5 text-[11px] text-amber-300 hover:bg-amber-500/20 transition-colors shrink-0"
|
||||
onClick={() => {
|
||||
if (task.hasFailedEmbeddings) void retryFailedEmbeddings(task.id);
|
||||
if (task.hasFailedTagging) void queueTaggingJobs(task.id);
|
||||
}}
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
)}
|
||||
|
||||
{task.id >= 0 && (
|
||||
<button
|
||||
className="p-1 rounded-md text-gray-600 hover:text-gray-300 hover:bg-white/8 transition-colors shrink-0"
|
||||
title="Dismiss"
|
||||
onClick={() => dismissTask(task.id, task.snapshot)}
|
||||
>
|
||||
<svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{task.currentFile && (
|
||||
<p className="text-[10px] text-gray-600 truncate mt-1 pl-[calc(7rem+0.75rem)]">
|
||||
{task.currentFile}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Failed embedding file list */}
|
||||
{taskHasFailed && failedItems[task.id] && failedItems[task.id].length > 0 && (
|
||||
<div className="mt-2 pl-[calc(7rem+0.75rem)] space-y-0.5">
|
||||
{failedItems[task.id].map((item) => (
|
||||
<div key={item.image_id} className="flex items-start gap-1.5 min-w-0">
|
||||
<svg className="h-2.5 w-2.5 text-amber-500 shrink-0 mt-px" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5}
|
||||
d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />
|
||||
</svg>
|
||||
<div className="min-w-0">
|
||||
<p className="text-[10px] text-amber-400/80 truncate font-medium">{item.filename}</p>
|
||||
{item.error && (
|
||||
<p className="text-[9px] text-gray-600 truncate">{item.error}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useGalleryStore } from '../store'
|
||||
import { BulkAlbumPopover } from './bulk/BulkAlbumPopover'
|
||||
import { BulkDeleteConfirm } from './bulk/BulkDeleteConfirm'
|
||||
import { BulkRatingPopover } from './bulk/BulkRatingPopover'
|
||||
import { BulkSelectionSummary } from './bulk/BulkSelectionSummary'
|
||||
import { BulkTagPopover } from './bulk/BulkTagPopover'
|
||||
import { type BulkPanel } from './bulk/types'
|
||||
import { useDismissable } from './menu'
|
||||
import { Tooltip } from './Tooltip'
|
||||
import { CloseIcon } from './icons'
|
||||
|
||||
export function BulkActionBar() {
|
||||
const selectedCount = useGalleryStore((state) => state.gallerySelectedIds.size)
|
||||
const selectedIds = useGalleryStore((state) => state.gallerySelectedIds)
|
||||
const clearGallerySelection = useGalleryStore((state) => state.clearGallerySelection)
|
||||
const selectAllGallery = useGalleryStore((state) => state.selectAllGallery)
|
||||
const loadedCount = useGalleryStore((state) => state.loadedCount)
|
||||
const totalImages = useGalleryStore((state) => state.totalImages)
|
||||
const bulkSetFavorite = useGalleryStore((state) => state.bulkSetFavorite)
|
||||
const bulkSetRating = useGalleryStore((state) => state.bulkSetRating)
|
||||
const bulkDeleteSelected = useGalleryStore((state) => state.bulkDeleteSelected)
|
||||
const activeView = useGalleryStore((state) => state.activeView)
|
||||
const selectedAlbumId = useGalleryStore((state) => state.selectedAlbumId)
|
||||
const addToAlbum = useGalleryStore((state) => state.addToAlbum)
|
||||
const removeFromAlbum = useGalleryStore((state) => state.removeFromAlbum)
|
||||
|
||||
const [panel, setPanel] = useState<BulkPanel>(null)
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
const barRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
// Close any open popover when clicking outside the bar or pressing Escape.
|
||||
useDismissable(barRef, () => setPanel(null), panel !== null)
|
||||
|
||||
// Reset transient UI whenever the selection empties.
|
||||
useEffect(() => {
|
||||
if (selectedCount === 0) setPanel(null)
|
||||
}, [selectedCount])
|
||||
|
||||
if (selectedCount === 0) return null
|
||||
|
||||
const ids = Array.from(selectedIds)
|
||||
const inAlbumView = activeView === 'album' && selectedAlbumId !== null
|
||||
const togglePanel = (next: Exclude<BulkPanel, null>) =>
|
||||
setPanel((current) => (current === next ? null : next))
|
||||
|
||||
const handleDelete = async () => {
|
||||
setDeleting(true)
|
||||
try {
|
||||
await bulkDeleteSelected()
|
||||
} finally {
|
||||
setDeleting(false)
|
||||
setPanel(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handlePickAlbum = async (albumId: number) => {
|
||||
await addToAlbum(albumId, ids)
|
||||
setPanel(null)
|
||||
}
|
||||
|
||||
const btn = 'rounded-md px-2.5 py-1.5 text-xs font-medium transition-colors'
|
||||
const btnIdle = `${btn} text-gray-300 hover:bg-white/10 hover:text-white`
|
||||
const btnActive = `${btn} bg-white/10 text-white`
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={barRef}
|
||||
className="pointer-events-auto absolute bottom-6 left-1/2 z-30 flex -translate-x-1/2 items-center gap-1 rounded-xl border border-white/10 bg-gray-950/95 px-2 py-1.5 shadow-2xl shadow-black/50 backdrop-blur"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<BulkSelectionSummary
|
||||
loadedCount={loadedCount}
|
||||
selectedCount={selectedCount}
|
||||
totalImages={totalImages}
|
||||
onSelectAll={selectAllGallery}
|
||||
/>
|
||||
|
||||
<div className="h-5 w-px bg-white/10" />
|
||||
|
||||
<div className="relative">
|
||||
<button
|
||||
className={panel === 'tag' ? btnActive : btnIdle}
|
||||
onClick={() => togglePanel('tag')}
|
||||
>
|
||||
Tag
|
||||
</button>
|
||||
{panel === 'tag' ? <BulkTagPopover onClose={() => setPanel(null)} /> : null}
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<button
|
||||
className={panel === 'rating' ? btnActive : btnIdle}
|
||||
onClick={() => togglePanel('rating')}
|
||||
>
|
||||
Rating
|
||||
</button>
|
||||
{panel === 'rating' ? (
|
||||
<BulkRatingPopover onSetRating={bulkSetRating} onClose={() => setPanel(null)} />
|
||||
) : null}
|
||||
</div>
|
||||
<Tooltip label="Mark as favorite" followCursor>
|
||||
<button className={btnIdle} onClick={() => void bulkSetFavorite(true)}>
|
||||
Favorite
|
||||
</button>
|
||||
</Tooltip>
|
||||
<div className="relative">
|
||||
<button
|
||||
className={panel === 'album' ? btnActive : btnIdle}
|
||||
onClick={() => togglePanel('album')}
|
||||
>
|
||||
Add to album
|
||||
</button>
|
||||
{panel === 'album' ? <BulkAlbumPopover onPick={handlePickAlbum} /> : null}
|
||||
</div>
|
||||
|
||||
{inAlbumView ? (
|
||||
<button
|
||||
className={`${btn} text-amber-300/90 hover:bg-amber-500/10 hover:text-amber-200`}
|
||||
onClick={() => void removeFromAlbum(selectedAlbumId, ids)}
|
||||
>
|
||||
Remove from album
|
||||
</button>
|
||||
) : null}
|
||||
|
||||
<div className="h-5 w-px bg-white/10" />
|
||||
|
||||
<div className="relative">
|
||||
<Tooltip label="Delete files from disk" followCursor>
|
||||
<button
|
||||
className={
|
||||
panel === 'delete'
|
||||
? `${btn} bg-red-500/15 text-red-300`
|
||||
: `${btn} text-gray-300 hover:bg-red-500/10 hover:text-red-300`
|
||||
}
|
||||
onClick={() => togglePanel('delete')}
|
||||
disabled={deleting}
|
||||
>
|
||||
{deleting ? 'Deleting…' : 'Delete'}
|
||||
</button>
|
||||
</Tooltip>
|
||||
{panel === 'delete' ? (
|
||||
<BulkDeleteConfirm
|
||||
deleting={deleting}
|
||||
selectedCount={selectedCount}
|
||||
onCancel={() => setPanel(null)}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<Tooltip label="Clear selection" followCursor>
|
||||
<button
|
||||
className="rounded-md p-1.5 text-gray-500 transition-colors hover:bg-white/[0.06] hover:text-white"
|
||||
onClick={clearGallerySelection}
|
||||
>
|
||||
<CloseIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import { AnimatePresence, motion } from 'framer-motion'
|
||||
import { useGalleryStore } from '../store'
|
||||
import { useDismissable } from './menu'
|
||||
import { Tooltip } from './Tooltip'
|
||||
|
||||
type Rgb = [number, number, number]
|
||||
|
||||
// Representative colors for the quick-pick swatches. Each is just an RGB the
|
||||
// distance filter matches against — not a hard bucket.
|
||||
const SWATCHES: { name: string; rgb: Rgb }[] = [
|
||||
{ name: 'Red', rgb: [226, 59, 59] },
|
||||
{ name: 'Orange', rgb: [232, 134, 46] },
|
||||
{ name: 'Yellow', rgb: [242, 207, 46] },
|
||||
{ name: 'Green', rgb: [76, 175, 80] },
|
||||
{ name: 'Teal', rgb: [31, 182, 166] },
|
||||
{ name: 'Blue', rgb: [59, 125, 216] },
|
||||
{ name: 'Purple', rgb: [139, 92, 246] },
|
||||
{ name: 'Pink', rgb: [236, 72, 153] },
|
||||
{ name: 'Brown', rgb: [139, 90, 43] },
|
||||
{ name: 'Black', rgb: [26, 26, 26] },
|
||||
{ name: 'White', rgb: [245, 245, 245] },
|
||||
{ name: 'Gray', rgb: [154, 160, 166] },
|
||||
]
|
||||
|
||||
function rgbEquals(a: Rgb | null, b: Rgb): boolean {
|
||||
return a !== null && a[0] === b[0] && a[1] === b[1] && a[2] === b[2]
|
||||
}
|
||||
|
||||
function toHex([r, g, b]: Rgb): string {
|
||||
return `#${[r, g, b].map((n) => n.toString(16).padStart(2, '0')).join('')}`
|
||||
}
|
||||
|
||||
function fromHex(hex: string): Rgb {
|
||||
const n = parseInt(hex.slice(1), 16)
|
||||
return [(n >> 16) & 255, (n >> 8) & 255, n & 255]
|
||||
}
|
||||
|
||||
export function ColorFilter() {
|
||||
const colorFilter = useGalleryStore((state) => state.colorFilter)
|
||||
const setColorFilter = useGalleryStore((state) => state.setColorFilter)
|
||||
const colorBackfill = useGalleryStore((state) => state.colorBackfill)
|
||||
const [open, setOpen] = useState(false)
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
|
||||
const isActive = colorFilter !== null
|
||||
const isCustom = isActive && !SWATCHES.some((swatch) => rgbEquals(colorFilter, swatch.rgb))
|
||||
|
||||
// Collapse the panel when clicking elsewhere or pressing Escape.
|
||||
useDismissable(ref, () => setOpen(false), open)
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className="relative ml-1 flex shrink-0 items-center border-l border-white/6 pl-2"
|
||||
>
|
||||
{/* Trigger — a single palette icon; shows the active color as a dot when a
|
||||
filter is applied so the collapsed state still communicates it. */}
|
||||
<Tooltip
|
||||
label={isActive ? 'Color filter active' : 'Filter by color'}
|
||||
delay={400}
|
||||
anchorToCursor
|
||||
>
|
||||
<button
|
||||
className={`relative flex items-center gap-1.5 rounded-lg px-2 py-1.5 transition-colors ${
|
||||
open || isActive
|
||||
? 'bg-white/10 text-white'
|
||||
: 'text-gray-500 hover:bg-white/5 hover:text-gray-200'
|
||||
}`}
|
||||
onClick={() => setOpen((value) => !value)}
|
||||
aria-label="Filter by color"
|
||||
>
|
||||
<svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={1.6}
|
||||
d="M12 3a9 9 0 100 18c.83 0 1.5-.67 1.5-1.5 0-.39-.15-.74-.39-1.01-.23-.26-.39-.61-.39-1 0-.83.67-1.5 1.5-1.5H16a5 5 0 005-5c0-4.42-4.03-8-9-8z"
|
||||
/>
|
||||
<circle cx="7.5" cy="11.5" r="1" fill="currentColor" stroke="none" />
|
||||
<circle cx="11.5" cy="7.5" r="1" fill="currentColor" stroke="none" />
|
||||
<circle cx="15.5" cy="9.5" r="1" fill="currentColor" stroke="none" />
|
||||
</svg>
|
||||
{isActive ? (
|
||||
<span
|
||||
className="h-3 w-3 rounded-full border border-white/30"
|
||||
style={{ backgroundColor: toHex(colorFilter as Rgb) }}
|
||||
/>
|
||||
) : null}
|
||||
</button>
|
||||
</Tooltip>
|
||||
|
||||
<AnimatePresence initial={false}>
|
||||
{open ? (
|
||||
// Right-aligned popover so it never widens the toolbar row or gets
|
||||
// pushed off-screen on narrow windows. Swatches wrap into a compact
|
||||
// grid instead of a single long horizontal strip.
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: -4, scale: 0.98 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
exit={{ opacity: 0, y: -4, scale: 0.98 }}
|
||||
transition={{ duration: 0.14, ease: 'easeOut' }}
|
||||
className="light-theme:border-gray-700/50 absolute top-full right-0 z-30 mt-2 w-max rounded-xl border border-white/10 bg-gray-950/98 p-2.5 shadow-2xl backdrop-blur"
|
||||
>
|
||||
<div className="grid grid-cols-7 gap-1.5">
|
||||
{SWATCHES.map((swatch) => {
|
||||
const active = rgbEquals(colorFilter, swatch.rgb)
|
||||
return (
|
||||
<Tooltip label={swatch.name} followCursor>
|
||||
<button
|
||||
key={swatch.name}
|
||||
aria-label={`Filter by ${swatch.name}`}
|
||||
className={`h-5 w-5 shrink-0 rounded-full border transition-transform ${
|
||||
active
|
||||
? 'scale-110 border-white/40 ring-2 ring-white/70'
|
||||
: 'border-white/15 hover:scale-110'
|
||||
}`}
|
||||
style={{ backgroundColor: toHex(swatch.rgb) }}
|
||||
onClick={() => setColorFilter(active ? null : swatch.rgb)}
|
||||
/>
|
||||
</Tooltip>
|
||||
)
|
||||
})}
|
||||
<Tooltip label="Custom Colour" followCursor>
|
||||
{/* Custom color picker — rainbow until a custom color is chosen. */}
|
||||
<label
|
||||
className={`relative h-5 w-5 shrink-0 cursor-pointer overflow-hidden rounded-full border ${
|
||||
isCustom
|
||||
? 'border-white/40 ring-2 ring-white/70'
|
||||
: 'border-white/15 hover:scale-110'
|
||||
}`}
|
||||
style={
|
||||
isCustom
|
||||
? { backgroundColor: toHex(colorFilter as Rgb) }
|
||||
: {
|
||||
background:
|
||||
'conic-gradient(red, orange, yellow, lime, cyan, blue, magenta, red)',
|
||||
}
|
||||
}
|
||||
>
|
||||
<input
|
||||
type="color"
|
||||
className="absolute inset-0 cursor-pointer opacity-0"
|
||||
value={colorFilter ? toHex(colorFilter) : '#3b7dd8'}
|
||||
onChange={(event) => setColorFilter(fromHex(event.target.value))}
|
||||
/>
|
||||
</label>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
{isActive || (colorBackfill && colorBackfill.total > 0) ? (
|
||||
<div className="light-theme:border-gray-700/40 mt-2 flex items-center justify-between gap-3 border-t border-white/6 pt-2">
|
||||
{colorBackfill && colorBackfill.total > 0 ? (
|
||||
<Tooltip
|
||||
label="Sampling colours from existing thumbnails — colour search fills in as this runs"
|
||||
anchorToCursor
|
||||
>
|
||||
<span className="text-[10px] text-gray-600">
|
||||
sampling {colorBackfill.processed.toLocaleString()}/
|
||||
{colorBackfill.total.toLocaleString()}
|
||||
</span>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
{isActive ? (
|
||||
<Tooltip label="Clear colour filter" anchorToCursor>
|
||||
<button
|
||||
className="shrink-0 rounded px-1 text-[11px] text-gray-500 transition-colors hover:text-gray-200"
|
||||
onClick={() => setColorFilter(null)}
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</motion.div>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,291 +1,125 @@
|
||||
import { useState } from "react";
|
||||
import { convertFileSrc } from "@tauri-apps/api/core";
|
||||
import { DuplicateGroup, useGalleryStore } from "../store";
|
||||
import { FolderScopeDropdown } from "./FolderScopeDropdown";
|
||||
import { useRef, useState } from 'react'
|
||||
import { useVirtualizer } from '@tanstack/react-virtual'
|
||||
import { useGalleryStore } from '../store'
|
||||
import {
|
||||
DuplicateScanEmptyState,
|
||||
DuplicateScanIntroState,
|
||||
DuplicateScanLoadingState,
|
||||
} from './duplicateFinder/DuplicateFinderEmptyStates'
|
||||
import { DuplicateFinderHeader } from './duplicateFinder/DuplicateFinderHeader'
|
||||
import { DuplicateGroupCard } from './duplicateFinder/DuplicateGroupCard'
|
||||
import { duplicateProgressLabel } from './duplicateFinder/format'
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes >= 1_073_741_824) return `${(bytes / 1_073_741_824).toFixed(1)} GB`;
|
||||
if (bytes >= 1_048_576) return `${(bytes / 1_048_576).toFixed(1)} MB`;
|
||||
if (bytes >= 1024) return `${(bytes / 1024).toFixed(0)} KB`;
|
||||
return `${bytes} B`;
|
||||
export function DuplicateFinder() {
|
||||
const duplicateGroups = useGalleryStore((state) => state.duplicateGroups)
|
||||
const duplicateScanning = useGalleryStore((state) => state.duplicateScanning)
|
||||
const duplicateScanProgress = useGalleryStore((state) => state.duplicateScanProgress)
|
||||
const duplicateScanError = useGalleryStore((state) => state.duplicateScanError)
|
||||
const duplicateScanWarning = useGalleryStore((state) => state.duplicateScanWarning)
|
||||
const duplicateSelectedIds = useGalleryStore((state) => state.duplicateSelectedIds)
|
||||
const duplicateLastScanned = useGalleryStore((state) => state.duplicateLastScanned)
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId)
|
||||
const scanDuplicates = useGalleryStore((state) => state.scanDuplicates)
|
||||
const clearDuplicateSelection = useGalleryStore((state) => state.clearDuplicateSelection)
|
||||
const selectKeepFirstAllGroups = useGalleryStore((state) => state.selectKeepFirstAllGroups)
|
||||
const deleteSelectedDuplicates = useGalleryStore((state) => state.deleteSelectedDuplicates)
|
||||
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
const [confirmingDelete, setConfirmingDelete] = useState(false)
|
||||
const [deleteResult, setDeleteResult] = useState<string | null>(null)
|
||||
|
||||
// Virtualize the group list so a large result set (e.g. thousands of pairs)
|
||||
// only mounts the on-screen cards. Group cards vary in height (number of
|
||||
// copies wraps across rows), so heights are measured dynamically.
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
const virtualizer = useVirtualizer({
|
||||
count: duplicateGroups.length,
|
||||
getScrollElement: () => scrollRef.current,
|
||||
estimateSize: () => 220,
|
||||
overscan: 4,
|
||||
})
|
||||
|
||||
const selectedCount = duplicateSelectedIds.size
|
||||
const hasResults = duplicateGroups.length > 0
|
||||
const hasScanned =
|
||||
hasResults ||
|
||||
duplicateLastScanned !== null ||
|
||||
(!duplicateScanning && duplicateScanProgress !== null)
|
||||
const handleDelete = async () => {
|
||||
setDeleting(true)
|
||||
setConfirmingDelete(false)
|
||||
setDeleteResult(null)
|
||||
try {
|
||||
const deleted = await deleteSelectedDuplicates()
|
||||
setDeleteResult(`Deleted ${deleted} file${deleted === 1 ? '' : 's'}.`)
|
||||
} catch (e) {
|
||||
setDeleteResult(String(e))
|
||||
} finally {
|
||||
setDeleting(false)
|
||||
}
|
||||
}
|
||||
|
||||
function DuplicateGroupCard({ group }: { group: DuplicateGroup }) {
|
||||
const selectedIds = useGalleryStore((state) => state.duplicateSelectedIds);
|
||||
const toggleDuplicateSelected = useGalleryStore((state) => state.toggleDuplicateSelected);
|
||||
const selectAllDuplicates = useGalleryStore((state) => state.selectAllDuplicates);
|
||||
const groupSelectedCount = group.images.filter((img) => selectedIds.has(img.id)).length;
|
||||
const noneSelected = groupSelectedCount === 0;
|
||||
|
||||
// "Keep all but the first" — a common quick action
|
||||
const handleKeepFirst = () => {
|
||||
const toDelete = group.images.slice(1).map((img) => img.id);
|
||||
// Clear any selection for this group first, then add the ones to delete
|
||||
for (const img of group.images) {
|
||||
if (selectedIds.has(img.id)) toggleDuplicateSelected(img.id);
|
||||
}
|
||||
selectAllDuplicates(toDelete);
|
||||
};
|
||||
const progressLabel = duplicateProgressLabel(duplicateScanProgress)
|
||||
|
||||
return (
|
||||
<div className="rounded-2xl border border-white/[0.07] bg-white/[0.02] p-4">
|
||||
{/* Group header */}
|
||||
<div className="mb-3 flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="rounded-md border border-white/10 bg-white/[0.04] px-2 py-0.5 text-[11px] text-gray-400">
|
||||
{group.images.length} copies
|
||||
</span>
|
||||
<span className="text-[11px] text-white/30">{formatBytes(group.file_size)} each</span>
|
||||
<span className="text-[11px] text-white/20">
|
||||
{formatBytes(group.file_size * (group.images.length - 1))} wasted
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{noneSelected ? (
|
||||
<button
|
||||
className="text-[11px] text-white/35 transition-colors hover:text-white/70"
|
||||
onClick={handleKeepFirst}
|
||||
>
|
||||
Keep first
|
||||
</button>
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-gray-950">
|
||||
<DuplicateFinderHeader
|
||||
confirmingDelete={confirmingDelete}
|
||||
deleteResult={deleteResult}
|
||||
deleting={deleting}
|
||||
duplicateGroups={duplicateGroups}
|
||||
duplicateLastScanned={duplicateLastScanned}
|
||||
duplicateScanError={duplicateScanError}
|
||||
duplicateScanning={duplicateScanning}
|
||||
duplicateScanProgress={duplicateScanProgress}
|
||||
duplicateScanWarning={duplicateScanWarning}
|
||||
hasResults={hasResults}
|
||||
hasScanned={hasScanned}
|
||||
onClearSelection={clearDuplicateSelection}
|
||||
onConfirmDelete={() => setConfirmingDelete(false)}
|
||||
onDelete={handleDelete}
|
||||
onScan={() => {
|
||||
setDeleteResult(null)
|
||||
void scanDuplicates(selectedFolderId)
|
||||
}}
|
||||
onSelectKeepFirstAll={selectKeepFirstAllGroups}
|
||||
selectedCount={selectedCount}
|
||||
setConfirmingDelete={setConfirmingDelete}
|
||||
/>
|
||||
|
||||
{duplicateScanning && !hasResults ? (
|
||||
<DuplicateScanLoadingState progressLabel={progressLabel} />
|
||||
) : !hasScanned ? (
|
||||
<DuplicateScanIntroState />
|
||||
) : duplicateGroups.length === 0 ? (
|
||||
<DuplicateScanEmptyState />
|
||||
) : (
|
||||
<button
|
||||
className="text-[11px] text-white/35 transition-colors hover:text-white/70"
|
||||
onClick={() => {
|
||||
for (const img of group.images) {
|
||||
if (selectedIds.has(img.id)) toggleDuplicateSelected(img.id);
|
||||
}
|
||||
<div ref={scrollRef} className="overflow-y-auto px-6 py-5">
|
||||
<div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
|
||||
{virtualizer.getVirtualItems().map((virtualItem) => {
|
||||
const group = duplicateGroups[virtualItem.index]
|
||||
if (!group) return null
|
||||
return (
|
||||
<div
|
||||
key={group.file_hash}
|
||||
data-index={virtualItem.index}
|
||||
ref={virtualizer.measureElement}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: '100%',
|
||||
transform: `translateY(${virtualItem.start}px)`,
|
||||
paddingBottom: 16,
|
||||
}}
|
||||
>
|
||||
Deselect all
|
||||
</button>
|
||||
)}
|
||||
<DuplicateGroupCard group={group} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Image grid */}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{group.images.map((image) => {
|
||||
const isSelected = selectedIds.has(image.id);
|
||||
const src = image.thumbnail_path ? convertFileSrc(image.thumbnail_path) : null;
|
||||
return (
|
||||
<button
|
||||
key={image.id}
|
||||
className={`group relative overflow-hidden rounded-xl border transition-all ${
|
||||
isSelected
|
||||
? "border-red-400/50 ring-1 ring-red-400/30"
|
||||
: "border-white/8 hover:border-white/20"
|
||||
}`}
|
||||
style={{ width: 140, height: 105 }}
|
||||
onClick={() => toggleDuplicateSelected(image.id)}
|
||||
title={image.path}
|
||||
>
|
||||
{src ? (
|
||||
<img src={src} alt="" className="h-full w-full object-cover" draggable={false} />
|
||||
) : (
|
||||
<div className="h-full w-full bg-white/[0.03]" />
|
||||
)}
|
||||
{/* Delete overlay */}
|
||||
{isSelected ? (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-red-950/60">
|
||||
<svg className="h-6 w-6 text-red-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
|
||||
</svg>
|
||||
</div>
|
||||
) : null}
|
||||
{/* Path tooltip on hover */}
|
||||
<div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/90 to-transparent px-2 pb-1.5 pt-4 opacity-0 transition-opacity group-hover:opacity-100">
|
||||
<p className="truncate text-[9px] text-white/60">{image.path.split(/[\\/]/).slice(-2).join("/")}</p>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatRelativeTime(unixSecs: number): string {
|
||||
const diff = Math.floor(Date.now() / 1000) - unixSecs;
|
||||
if (diff < 60) return "just now";
|
||||
if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
|
||||
if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
|
||||
return `${Math.floor(diff / 86400)}d ago`;
|
||||
}
|
||||
|
||||
export function DuplicateFinder() {
|
||||
const duplicateGroups = useGalleryStore((state) => state.duplicateGroups);
|
||||
const duplicateScanning = useGalleryStore((state) => state.duplicateScanning);
|
||||
const duplicateScanProgress = useGalleryStore((state) => state.duplicateScanProgress);
|
||||
const duplicateScanError = useGalleryStore((state) => state.duplicateScanError);
|
||||
const duplicateScanWarning = useGalleryStore((state) => state.duplicateScanWarning);
|
||||
const duplicateSelectedIds = useGalleryStore((state) => state.duplicateSelectedIds);
|
||||
const duplicateLastScanned = useGalleryStore((state) => state.duplicateLastScanned);
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId);
|
||||
const scanDuplicates = useGalleryStore((state) => state.scanDuplicates);
|
||||
const clearDuplicateSelection = useGalleryStore((state) => state.clearDuplicateSelection);
|
||||
const selectKeepFirstAllGroups = useGalleryStore((state) => state.selectKeepFirstAllGroups);
|
||||
const deleteSelectedDuplicates = useGalleryStore((state) => state.deleteSelectedDuplicates);
|
||||
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [deleteResult, setDeleteResult] = useState<string | null>(null);
|
||||
|
||||
const selectedCount = duplicateSelectedIds.size;
|
||||
const hasResults = duplicateGroups.length > 0;
|
||||
const hasScanned = hasResults || duplicateLastScanned !== null || (!duplicateScanning && duplicateScanProgress !== null);
|
||||
const totalWasted = duplicateGroups.reduce(
|
||||
(sum, g) => sum + g.file_size * (g.images.length - 1),
|
||||
0,
|
||||
);
|
||||
const totalDuplicateImages = duplicateGroups.reduce((sum, g) => sum + g.images.length - 1, 0);
|
||||
|
||||
const handleDelete = async () => {
|
||||
setDeleting(true);
|
||||
setDeleteResult(null);
|
||||
try {
|
||||
const deleted = await deleteSelectedDuplicates();
|
||||
setDeleteResult(`Deleted ${deleted} file${deleted === 1 ? "" : "s"}.`);
|
||||
} catch (e) {
|
||||
setDeleteResult(String(e));
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const progressPercent =
|
||||
duplicateScanProgress && duplicateScanProgress.total > 0
|
||||
? Math.round((duplicateScanProgress.processed / duplicateScanProgress.total) * 100)
|
||||
: 0;
|
||||
const progressLabel = duplicateScanProgress
|
||||
? duplicateScanProgress.phase === "checking"
|
||||
? "Checking file sizes"
|
||||
: duplicateScanProgress.phase === "hashing"
|
||||
? "Hashing duplicate candidates"
|
||||
: "Confirming exact matches"
|
||||
: null;
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-[#07080f]">
|
||||
{/* Header */}
|
||||
<div className="shrink-0 border-b border-white/[0.05] px-6 py-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-[15px] font-semibold text-white">Duplicate Finder</h2>
|
||||
<p className="mt-0.5 text-[11px] text-white/30">
|
||||
{duplicateScanning
|
||||
? duplicateScanProgress
|
||||
? `${progressLabel}… ${duplicateScanProgress.processed.toLocaleString()} / ${duplicateScanProgress.total.toLocaleString()}${duplicateScanProgress.skipped > 0 ? ` · ${duplicateScanProgress.skipped.toLocaleString()} skipped` : ""}`
|
||||
: "Starting scan…"
|
||||
: hasResults
|
||||
? `${duplicateGroups.length} group${duplicateGroups.length === 1 ? "" : "s"} · ${formatBytes(totalWasted)} reclaimable`
|
||||
: duplicateLastScanned !== null
|
||||
? "No duplicates found"
|
||||
: "Scan your library for identical files"}
|
||||
</p>
|
||||
{!duplicateScanning && duplicateLastScanned !== null && (
|
||||
<p className="mt-0.5 text-[10px] text-white/20">
|
||||
Last scanned {formatRelativeTime(duplicateLastScanned)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<FolderScopeDropdown />
|
||||
{/* Batch select — only shown when there are groups and nothing is selected yet */}
|
||||
{hasResults && selectedCount === 0 && !deleting && (
|
||||
<button
|
||||
className="rounded-lg border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs text-gray-400 transition-colors hover:bg-white/[0.07] hover:text-white"
|
||||
onClick={selectKeepFirstAllGroups}
|
||||
title={`Mark ${totalDuplicateImages} duplicate${totalDuplicateImages === 1 ? "" : "s"} for deletion across all groups (keeps first in each)`}
|
||||
>
|
||||
Select all duplicates
|
||||
</button>
|
||||
)}
|
||||
{selectedCount > 0 ? (
|
||||
<>
|
||||
<span className="text-[11px] text-white/40">{selectedCount} marked for deletion</span>
|
||||
<button
|
||||
className="rounded-lg border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs text-gray-400 transition-colors hover:bg-white/[0.07] hover:text-white disabled:opacity-40"
|
||||
onClick={clearDuplicateSelection}
|
||||
disabled={deleting}
|
||||
>
|
||||
Deselect all
|
||||
</button>
|
||||
<button
|
||||
className="rounded-lg border border-red-400/25 bg-red-500/10 px-3 py-1.5 text-xs text-red-300 transition-colors hover:bg-red-500/15 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
onClick={handleDelete}
|
||||
disabled={deleting}
|
||||
>
|
||||
{deleting ? "Deleting…" : `Delete ${selectedCount} file${selectedCount === 1 ? "" : "s"}`}
|
||||
</button>
|
||||
</>
|
||||
) : null}
|
||||
<button
|
||||
className="rounded-lg border border-white/10 bg-white/[0.055] px-3 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/10 hover:text-white disabled:cursor-not-allowed disabled:opacity-40"
|
||||
onClick={() => { setDeleteResult(null); void scanDuplicates(selectedFolderId); }}
|
||||
disabled={duplicateScanning}
|
||||
>
|
||||
{duplicateScanning ? "Scanning…" : hasScanned ? "Rescan" : "Scan for duplicates"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Progress bar */}
|
||||
{duplicateScanning && duplicateScanProgress ? (
|
||||
<div className="mt-3 h-px overflow-hidden rounded-full bg-white/[0.07]">
|
||||
<div
|
||||
className="h-full rounded-full bg-blue-500/60 transition-[width] duration-200"
|
||||
style={{ width: `${progressPercent}%` }}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{duplicateScanError ? (
|
||||
<p className="mt-2 text-[11px] text-red-400/80">{duplicateScanError}</p>
|
||||
) : null}
|
||||
{duplicateScanWarning ? (
|
||||
<p className="mt-2 text-[11px] text-amber-300/70">{duplicateScanWarning}</p>
|
||||
) : null}
|
||||
{deleteResult ? (
|
||||
<p className="mt-2 text-[11px] text-white/40">{deleteResult}</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
{duplicateScanning && !hasResults ? (
|
||||
<div className="flex flex-1 items-center justify-center gap-3 text-white/25">
|
||||
<div className="h-5 w-5 animate-spin rounded-full border-2 border-white/15 border-t-white/50" />
|
||||
<span className="text-sm">{progressLabel ? `${progressLabel}…` : "Preparing scan…"}</span>
|
||||
</div>
|
||||
) : !hasScanned ? (
|
||||
<div className="flex flex-1 items-center justify-center px-8">
|
||||
<div className="max-w-sm text-center">
|
||||
<svg className="mx-auto mb-4 h-10 w-10 text-white/10" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1}
|
||||
d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
|
||||
</svg>
|
||||
<p className="text-sm text-white/30">
|
||||
Finds files with identical content regardless of filename or location.
|
||||
Click <strong className="text-white/50">Scan for duplicates</strong> to begin.
|
||||
</p>
|
||||
<p className="mt-2 text-xs text-white/20">
|
||||
Large libraries may take a minute — files are hashed from disk.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : duplicateGroups.length === 0 ? (
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<p className="text-sm text-white/25">No duplicate files found.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-y-auto px-6 py-5">
|
||||
<div className="space-y-4">
|
||||
{duplicateGroups.map((group) => (
|
||||
<DuplicateGroupCard key={group.file_hash} group={group} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useGalleryStore } from '../store'
|
||||
import { FolderScopeDropdown } from './FolderScopeDropdown'
|
||||
import { ClusterCloud } from './explore/ClusterCloud'
|
||||
import { ExploreLoadingPanel } from './explore/ExploreLoadingPanel'
|
||||
import { TagAtlas, TAG_ATLAS_MAX_VISIBLE } from './explore/TagAtlas'
|
||||
import { TagManageList } from './explore/TagManageList'
|
||||
|
||||
export function ExploreView() {
|
||||
const exploreMode = useGalleryStore((state) => state.exploreMode)
|
||||
const setExploreMode = useGalleryStore((state) => state.setExploreMode)
|
||||
const visualClusterEntries = useGalleryStore((state) => state.visualClusterEntries)
|
||||
const visualClusterLoading = useGalleryStore((state) => state.visualClusterLoading)
|
||||
const loadVisualClusters = useGalleryStore((state) => state.loadVisualClusters)
|
||||
const exploreTagEntries = useGalleryStore((state) => state.exploreTagEntries)
|
||||
const exploreTagLoading = useGalleryStore((state) => state.exploreTagLoading)
|
||||
const loadExploreTags = useGalleryStore((state) => state.loadExploreTags)
|
||||
const loadRelatedTags = useGalleryStore((state) => state.loadRelatedTags)
|
||||
const showVisualCluster = useGalleryStore((state) => state.showVisualCluster)
|
||||
const searchForTag = useGalleryStore((state) => state.searchForTag)
|
||||
const renameTag = useGalleryStore((state) => state.renameTag)
|
||||
const deleteTag = useGalleryStore((state) => state.deleteTag)
|
||||
const resetAiTags = useGalleryStore((state) => state.resetAiTags)
|
||||
const folders = useGalleryStore((state) => state.folders)
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId)
|
||||
// Manage mode lives in the store so it can be opened from elsewhere (Settings).
|
||||
const manageTags = useGalleryStore((state) => state.tagManagerOpen)
|
||||
const setManageTags = useGalleryStore((state) => state.setTagManagerOpen)
|
||||
const handleDeleteTag = async (tag: string) => {
|
||||
await deleteTag(tag)
|
||||
}
|
||||
const tagManagerScopeLabel =
|
||||
selectedFolderId === null
|
||||
? 'all media'
|
||||
: (folders.find((folder) => folder.id === selectedFolderId)?.name ?? 'the current folder')
|
||||
const handleResetAiTags = async () => {
|
||||
const count = await resetAiTags(selectedFolderId)
|
||||
await loadExploreTags({ force: true })
|
||||
return count
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (exploreMode === 'visual') void loadVisualClusters()
|
||||
else void loadExploreTags()
|
||||
}, [exploreMode, selectedFolderId, loadVisualClusters, loadExploreTags])
|
||||
|
||||
const loading = exploreMode === 'visual' ? visualClusterLoading : exploreTagLoading
|
||||
const hasEntries =
|
||||
exploreMode === 'visual' ? visualClusterEntries.length > 0 : exploreTagEntries.length > 0
|
||||
const entryCount =
|
||||
exploreMode === 'visual' ? visualClusterEntries.length : exploreTagEntries.length
|
||||
const visibleTagCount = Math.min(exploreTagEntries.length, TAG_ATLAS_MAX_VISIBLE)
|
||||
|
||||
return (
|
||||
<div className="explore-view flex min-h-0 flex-1 flex-col overflow-hidden bg-[radial-gradient(ellipse_at_top,rgba(59,130,246,0.08),transparent_50%),radial-gradient(ellipse_at_80%_75%,rgba(168,85,247,0.07),transparent_40%),#07080f]">
|
||||
{/* Header — `relative z-10` keeps the folder-scope dropdown above the
|
||||
cluster canvas, whose cards use a high z-index of their own. */}
|
||||
<div className="explore-header relative z-10 shrink-0 border-b border-white/[0.05] px-6 py-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="min-w-0">
|
||||
<h2 className="explore-title text-[15px] font-semibold text-white">Explore</h2>
|
||||
<p className="explore-subtitle mt-0.5 truncate text-[11px] text-white/30">
|
||||
{loading
|
||||
? exploreMode === 'visual'
|
||||
? 'Computing visual clusters…'
|
||||
: 'Loading tags…'
|
||||
: hasEntries
|
||||
? exploreMode === 'visual'
|
||||
? `${entryCount} cluster${entryCount !== 1 ? 's' : ''} — click any to open`
|
||||
: manageTags
|
||||
? `${entryCount} tag${entryCount !== 1 ? 's' : ''} available to manage`
|
||||
: visibleTagCount < entryCount
|
||||
? `${visibleTagCount} of ${entryCount} tags shown — click any to search`
|
||||
: `${entryCount} tag${entryCount !== 1 ? 's' : ''} — click any to search`
|
||||
: exploreMode === 'visual'
|
||||
? 'No clusters — images need embeddings first'
|
||||
: 'No tags — run the AI tagger or add tags manually'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
{exploreMode === 'tags' && hasEntries ? (
|
||||
<button
|
||||
className={`rounded-lg border px-3 py-1.5 text-xs transition-colors ${
|
||||
manageTags
|
||||
? 'border-white/15 bg-white/10 text-white'
|
||||
: 'border-white/8 bg-white/[0.03] text-gray-500 hover:text-gray-300'
|
||||
}`}
|
||||
onClick={() => setManageTags(!manageTags)}
|
||||
>
|
||||
{manageTags ? 'Done' : 'Manage'}
|
||||
</button>
|
||||
) : null}
|
||||
<FolderScopeDropdown />
|
||||
<div className="explore-mode-toggle flex rounded-lg border border-white/8 bg-white/[0.03] p-0.5">
|
||||
<button
|
||||
className={`explore-mode-button rounded-md px-3 py-1.5 text-xs transition-colors ${
|
||||
exploreMode === 'visual'
|
||||
? 'bg-white/10 text-white'
|
||||
: 'text-gray-500 hover:text-gray-300'
|
||||
}`}
|
||||
onClick={() => setExploreMode('visual')}
|
||||
>
|
||||
Clusters
|
||||
</button>
|
||||
<button
|
||||
className={`explore-mode-button rounded-md px-3 py-1.5 text-xs transition-colors ${
|
||||
exploreMode === 'tags'
|
||||
? 'bg-white/10 text-white'
|
||||
: 'text-gray-500 hover:text-gray-300'
|
||||
}`}
|
||||
onClick={() => setExploreMode('tags')}
|
||||
>
|
||||
Tag Cloud
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading && !hasEntries ? (
|
||||
<ExploreLoadingPanel mode={exploreMode} />
|
||||
) : !hasEntries ? (
|
||||
<div className="flex flex-1 items-center justify-center px-8">
|
||||
<p className="explore-empty max-w-xs text-center text-sm leading-relaxed text-white/25">
|
||||
{exploreMode === 'visual'
|
||||
? 'No visual clusters yet. Images need embeddings before they can be grouped. Check indexing progress in the sidebar.'
|
||||
: 'No tags yet. Run the AI tagger from Settings, or add tags manually in the image preview.'}
|
||||
</p>
|
||||
</div>
|
||||
) : exploreMode === 'visual' ? (
|
||||
<div className="relative flex min-h-0 flex-1 flex-col">
|
||||
<ClusterCloud entries={visualClusterEntries} onOpen={showVisualCluster} />
|
||||
</div>
|
||||
) : manageTags ? (
|
||||
<div className="relative flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
<TagManageList
|
||||
entries={exploreTagEntries}
|
||||
onSearch={searchForTag}
|
||||
onRename={renameTag}
|
||||
onDelete={handleDeleteTag}
|
||||
onResetAiTags={handleResetAiTags}
|
||||
scopeLabel={tagManagerScopeLabel}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<TagAtlas
|
||||
entries={exploreTagEntries}
|
||||
onSearch={searchForTag}
|
||||
loadRelatedTags={loadRelatedTags}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
import { useVirtualizer } from '@tanstack/react-virtual'
|
||||
import { Tooltip } from './Tooltip'
|
||||
import { CloseIcon } from './icons'
|
||||
import { FolderRow } from './folderPicker/FolderRow'
|
||||
import { StagedFoldersPanel } from './folderPicker/StagedFoldersPanel'
|
||||
import { StatusLine } from './folderPicker/StatusLine'
|
||||
import { normalizePath } from './folderPicker/pathUtils'
|
||||
import { useFolderPicker } from './folderPicker/useFolderPicker'
|
||||
|
||||
export function FolderPickerModal() {
|
||||
const folderPicker = useFolderPicker()
|
||||
|
||||
const virtualizer = useVirtualizer({
|
||||
count: folderPicker.entries.length,
|
||||
getScrollElement: () => folderPicker.scrollRef.current,
|
||||
estimateSize: () => 48,
|
||||
overscan: 8,
|
||||
})
|
||||
|
||||
if (!folderPicker.folderPickerOpen) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-[80] flex items-center justify-center bg-black/65 px-6 backdrop-blur-sm"
|
||||
onClick={() => folderPicker.setFolderPickerOpen(false)}
|
||||
>
|
||||
<div
|
||||
className="light-theme:border-gray-300/70 relative flex h-[min(82vh,760px)] w-[min(90vw,1180px)] flex-col overflow-hidden rounded-lg border border-white/10 bg-gray-950 shadow-2xl shadow-black/60"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<header className="light-theme:border-gray-200 border-b border-white/[0.07] px-5 py-4">
|
||||
<div className="flex items-start justify-between gap-6">
|
||||
<div className="min-w-0">
|
||||
<p className="text-base font-semibold text-white">Add media folders</p>
|
||||
<p className="light-theme:text-gray-600 mt-1 text-xs text-gray-500">
|
||||
Choose folders from any location, then add them together.
|
||||
</p>
|
||||
</div>
|
||||
<Tooltip label="Close folder picker" anchorToCursor>
|
||||
<button
|
||||
type="button"
|
||||
className="light-theme:hover:bg-gray-900 light-theme:hover:text-white rounded-md p-1.5 text-gray-500 transition-colors hover:bg-white/[0.06] hover:text-white"
|
||||
onClick={() => folderPicker.setFolderPickerOpen(false)}
|
||||
>
|
||||
<CloseIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="flex min-h-0 flex-1 flex-col lg:flex-row">
|
||||
<main className="flex min-h-0 flex-1 flex-col px-5 py-4">
|
||||
<div className="mb-4 flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 rounded-md border border-white/10 bg-white/[0.035] px-2.5 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/[0.07] hover:text-white disabled:cursor-not-allowed disabled:opacity-40"
|
||||
onClick={() => folderPicker.setCurrentPath(folderPicker.listing?.parent ?? null)}
|
||||
disabled={!folderPicker.listing?.current}
|
||||
>
|
||||
Up
|
||||
</button>
|
||||
{folderPicker.addressEditing ? (
|
||||
<form
|
||||
className="flex min-w-0 flex-1 items-center gap-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
folderPicker.navigateToAddress()
|
||||
}}
|
||||
>
|
||||
<label className="sr-only" htmlFor="folder-picker-address">
|
||||
Folder path
|
||||
</label>
|
||||
<input
|
||||
ref={folderPicker.addressInputRef}
|
||||
id="folder-picker-address"
|
||||
className="light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:placeholder-gray-500 light-theme:focus:bg-gray-800 min-w-0 flex-1 rounded-md border border-white/10 bg-white/[0.035] px-3 py-1.5 font-mono text-xs text-gray-200 placeholder-gray-600 transition-colors outline-none focus:border-white/25 focus:bg-white/[0.055]"
|
||||
value={folderPicker.addressDraft}
|
||||
onChange={(event) => folderPicker.updateAddressDraft(event.target.value)}
|
||||
placeholder="Paste or type a folder path"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
className="light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 rounded-md border border-white/10 bg-white/[0.035] px-2.5 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/[0.07] hover:text-white disabled:cursor-not-allowed disabled:opacity-40"
|
||||
disabled={folderPicker.loading}
|
||||
>
|
||||
Go
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<div className="light-theme:border-gray-300/70 light-theme:bg-gray-900 flex min-w-0 flex-1 items-center gap-1 overflow-hidden rounded-md border border-white/10 bg-white/[0.025] px-2 py-1.5">
|
||||
<nav className="flex min-w-0 items-center gap-1 overflow-hidden">
|
||||
{folderPicker.breadcrumbs.map((crumb, index) => (
|
||||
<span
|
||||
key={`${crumb.path ?? 'root'}-${index}`}
|
||||
className="flex min-w-0 items-center gap-1"
|
||||
>
|
||||
{index > 0 ? (
|
||||
<span className="light-theme:text-gray-400 text-gray-700">/</span>
|
||||
) : null}
|
||||
<Tooltip label={crumb.path ?? 'Roots'} anchorToCursor>
|
||||
<button
|
||||
type="button"
|
||||
className="light-theme:text-gray-500 light-theme:hover:bg-gray-800 light-theme:hover:text-white max-w-40 truncate rounded px-1.5 py-0.5 text-xs text-gray-400 transition-colors hover:bg-white/[0.06] hover:text-white"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
folderPicker.setCurrentPath(crumb.path)
|
||||
}}
|
||||
>
|
||||
{crumb.label}
|
||||
</button>
|
||||
</Tooltip>
|
||||
</span>
|
||||
))}
|
||||
</nav>
|
||||
<button
|
||||
type="button"
|
||||
className="min-w-10 flex-1 cursor-text self-stretch rounded px-1"
|
||||
onClick={folderPicker.beginAddressEdit}
|
||||
aria-label="Edit folder path"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-emerald-400/35 bg-emerald-500/15 px-2.5 py-1.5 text-xs text-emerald-200 transition-colors hover:bg-emerald-500/25 disabled:cursor-not-allowed disabled:opacity-45"
|
||||
onClick={() => folderPicker.stagePath(folderPicker.addressPath)}
|
||||
disabled={
|
||||
!folderPicker.addressPath ||
|
||||
folderPicker.addressAlreadyAdded ||
|
||||
folderPicker.addressAlreadyStaged
|
||||
}
|
||||
>
|
||||
Select
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{folderPicker.error ? (
|
||||
<div className="light-theme:border-amber-600/40 light-theme:bg-amber-100 light-theme:text-amber-800 mb-3 rounded-md border border-amber-400/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-200">
|
||||
{folderPicker.error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div
|
||||
ref={folderPicker.scrollRef}
|
||||
className="light-theme:border-gray-300/70 light-theme:bg-gray-900/50 min-h-0 flex-1 overflow-auto rounded-md border border-white/[0.07] bg-white/[0.018] p-2"
|
||||
>
|
||||
{folderPicker.loading ? (
|
||||
<div className="flex h-full items-center justify-center text-sm text-gray-500">
|
||||
Loading folders...
|
||||
</div>
|
||||
) : folderPicker.entries.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center text-sm text-gray-500">
|
||||
No folders found here.
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className="relative w-full"
|
||||
style={{ height: `${virtualizer.getTotalSize()}px` }}
|
||||
>
|
||||
{virtualizer.getVirtualItems().map((virtualItem) => {
|
||||
const entry = folderPicker.entries[virtualItem.index]
|
||||
const normalized = normalizePath(entry.path)
|
||||
return (
|
||||
<div
|
||||
key={virtualItem.key}
|
||||
className="absolute top-0 left-0 w-full px-0.5"
|
||||
style={{
|
||||
height: `${virtualItem.size}px`,
|
||||
transform: `translateY(${virtualItem.start}px)`,
|
||||
}}
|
||||
>
|
||||
<FolderRow
|
||||
entry={entry}
|
||||
selected={folderPicker.stagedSet.has(normalized)}
|
||||
alreadyAdded={folderPicker.libraryPaths.has(normalized)}
|
||||
onToggle={() => folderPicker.togglePath(entry.path)}
|
||||
onNavigate={() => folderPicker.setCurrentPath(entry.path)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<StagedFoldersPanel
|
||||
stagedPaths={folderPicker.stagedPaths}
|
||||
onRemove={folderPicker.removeStagedPath}
|
||||
onClear={folderPicker.clearStagedPaths}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<footer className="light-theme:border-gray-200 border-t border-white/[0.07] px-5 py-4">
|
||||
<div className="flex items-end justify-between gap-4">
|
||||
<div className="min-w-0 flex-1">
|
||||
<StatusLine results={folderPicker.results} />
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 rounded-md border border-white/10 bg-white/[0.035] px-3 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/[0.07] hover:text-white"
|
||||
onClick={() => folderPicker.setFolderPickerOpen(false)}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 rounded-md border border-white/15 bg-white/[0.08] px-3 py-1.5 text-xs text-white transition-colors hover:bg-white/[0.12] disabled:cursor-not-allowed disabled:opacity-45"
|
||||
onClick={() => void folderPicker.confirmAdd()}
|
||||
disabled={folderPicker.stagedPaths.length === 0 || folderPicker.adding}
|
||||
>
|
||||
{folderPicker.adding ? 'Adding...' : `Add ${folderPicker.stagedPaths.length}`}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useGalleryStore } from "../store";
|
||||
import { useMemo } from 'react'
|
||||
import { useGalleryStore } from '../store'
|
||||
import { Dropdown, DropdownOption } from './menu'
|
||||
|
||||
/**
|
||||
* In-view folder scope picker for feature views (Timeline / Explore /
|
||||
@@ -7,92 +8,48 @@ import { useGalleryStore } from "../store";
|
||||
* current view active — unlike sidebar folder clicks, which jump to Gallery.
|
||||
*/
|
||||
export function FolderScopeDropdown() {
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const folders = useGalleryStore((state) => state.folders)
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId)
|
||||
const setViewFolderScope = useGalleryStore((state) => state.setViewFolderScope)
|
||||
|
||||
const folders = useGalleryStore((state) => state.folders);
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId);
|
||||
const setViewFolderScope = useGalleryStore((state) => state.setViewFolderScope);
|
||||
|
||||
useEffect(() => {
|
||||
const close = (e: MouseEvent) => {
|
||||
if (!ref.current?.contains(e.target as Node)) setOpen(false);
|
||||
};
|
||||
window.addEventListener("pointerdown", close);
|
||||
return () => window.removeEventListener("pointerdown", close);
|
||||
}, []);
|
||||
|
||||
const currentLabel =
|
||||
selectedFolderId === null
|
||||
? "All Media"
|
||||
: folders.find((folder) => folder.id === selectedFolderId)?.name ?? "All Media";
|
||||
|
||||
const select = (folderId: number | null) => {
|
||||
setViewFolderScope(folderId);
|
||||
setOpen(false);
|
||||
};
|
||||
const options = useMemo<DropdownOption<number | null>[]>(
|
||||
() => [
|
||||
{ value: null, label: 'All Media' },
|
||||
...folders.map((folder) => ({
|
||||
value: folder.id,
|
||||
label: folder.name,
|
||||
hint: <span className="tabular-nums">{folder.image_count.toLocaleString()}</span>,
|
||||
})),
|
||||
],
|
||||
[folders]
|
||||
)
|
||||
|
||||
return (
|
||||
<div ref={ref} className="relative">
|
||||
<button
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className={`flex max-w-56 items-center gap-1.5 rounded-lg border px-3 py-1.5 text-xs transition-colors ${
|
||||
open
|
||||
? "border-white/15 bg-white/8 text-white"
|
||||
: "border-white/8 bg-transparent text-gray-400 hover:border-white/15 hover:text-gray-200"
|
||||
}`}
|
||||
title="Change folder scope"
|
||||
>
|
||||
<svg className="h-3.5 w-3.5 shrink-0 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
|
||||
</svg>
|
||||
<span className="truncate">{currentLabel}</span>
|
||||
<Dropdown
|
||||
value={selectedFolderId}
|
||||
options={options}
|
||||
onChange={setViewFolderScope}
|
||||
ariaLabel="Folder scope"
|
||||
trigger="ghost"
|
||||
size="md"
|
||||
triggerTooltip="Change folder scope"
|
||||
triggerClassName="max-w-56"
|
||||
panelClassName="min-w-52 max-h-80 overflow-y-auto"
|
||||
triggerIcon={
|
||||
<svg
|
||||
className={`h-3 w-3 shrink-0 text-gray-500 transition-transform duration-150 ${open ? "rotate-180" : ""}`}
|
||||
fill="none" viewBox="0 0 24 24" stroke="currentColor"
|
||||
className="h-3.5 w-3.5 shrink-0 text-gray-500"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
{open ? (
|
||||
<div className="absolute right-0 top-full z-30 mt-1.5 max-h-80 min-w-52 overflow-y-auto rounded-xl border border-white/10 bg-gray-950/98 p-1 shadow-2xl backdrop-blur">
|
||||
<button
|
||||
className={`flex w-full items-center justify-between gap-3 rounded-lg px-3 py-2 text-left text-sm transition-colors ${
|
||||
selectedFolderId === null ? "bg-white/6 text-white" : "text-gray-400 hover:bg-white/5 hover:text-white"
|
||||
}`}
|
||||
onClick={() => select(null)}
|
||||
>
|
||||
All Media
|
||||
{selectedFolderId === null ? (
|
||||
<svg className="h-3.5 w-3.5 shrink-0 text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
) : null}
|
||||
</button>
|
||||
{folders.map((folder) => {
|
||||
const active = selectedFolderId === folder.id;
|
||||
return (
|
||||
<button
|
||||
key={folder.id}
|
||||
className={`flex w-full items-center justify-between gap-3 rounded-lg px-3 py-2 text-left text-sm transition-colors ${
|
||||
active ? "bg-white/6 text-white" : "text-gray-400 hover:bg-white/5 hover:text-white"
|
||||
}`}
|
||||
onClick={() => select(folder.id)}
|
||||
>
|
||||
<span className="min-w-0 truncate">{folder.name}</span>
|
||||
<span className="flex shrink-0 items-center gap-2">
|
||||
<span className="text-[11px] tabular-nums text-gray-600">{folder.image_count.toLocaleString()}</span>
|
||||
{active ? (
|
||||
<svg className="h-3.5 w-3.5 text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
) : null}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,400 +1,149 @@
|
||||
import { useEffect, useRef, useCallback, useState } from "react";
|
||||
import { convertFileSrc } from "@tauri-apps/api/core";
|
||||
import { ImageRecord, parseSearchValue, tileSizeForZoom, useGalleryStore } from "../store";
|
||||
import { useEffect, useLayoutEffect, useRef, useCallback, useMemo, useState } from 'react'
|
||||
import { useVirtualizer } from '@tanstack/react-virtual'
|
||||
import { ImageRecord, parseSearchValue, tileSizeForZoom, useGalleryStore } from '../store'
|
||||
import { BulkActionBar } from './BulkActionBar'
|
||||
import { ImageContextMenu } from './ImageContextMenu'
|
||||
import { GalleryEmptyState, GalleryLoadingState } from './gallery/GalleryEmptyState'
|
||||
import { ImageTile } from './gallery/ImageTile'
|
||||
|
||||
const GAP = 6;
|
||||
|
||||
function formatDuration(durationMs: number | null): string | null {
|
||||
if (!durationMs || durationMs <= 0) return null;
|
||||
const totalSeconds = Math.floor(durationMs / 1000);
|
||||
const seconds = totalSeconds % 60;
|
||||
const minutes = Math.floor(totalSeconds / 60) % 60;
|
||||
const hours = Math.floor(totalSeconds / 3600);
|
||||
if (hours > 0) {
|
||||
return `${hours}:${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
|
||||
}
|
||||
return `${minutes}:${seconds.toString().padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function ContextMenu({
|
||||
x,
|
||||
y,
|
||||
image,
|
||||
onClose,
|
||||
}: {
|
||||
x: number;
|
||||
y: number;
|
||||
image: ImageRecord;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const openImage = useGalleryStore((state) => state.openImage);
|
||||
const updateImageDetails = useGalleryStore((state) => state.updateImageDetails);
|
||||
const loadSimilarImages = useGalleryStore((state) => state.loadSimilarImages);
|
||||
const similarScope = useGalleryStore((state) => state.similarScope);
|
||||
const canFindSimilar = image.embedding_status === "ready";
|
||||
|
||||
return (
|
||||
<div
|
||||
data-gallery-context-menu
|
||||
className="fixed z-40 min-w-52 rounded-xl border border-white/10 bg-gray-950/98 p-1 shadow-2xl backdrop-blur"
|
||||
style={{ left: x, top: y }}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<button
|
||||
className="w-full rounded-lg px-3 py-2 text-left text-sm text-gray-200 hover:bg-white/5 hover:text-white transition-colors"
|
||||
onClick={() => { openImage(image); onClose(); }}
|
||||
>
|
||||
Open Preview
|
||||
</button>
|
||||
<button
|
||||
className="w-full rounded-lg px-3 py-2 text-left text-sm text-gray-200 hover:bg-white/5 hover:text-white transition-colors"
|
||||
onClick={async () => { await updateImageDetails(image.id, { favorite: !image.favorite }); onClose(); }}
|
||||
>
|
||||
{image.favorite ? "Remove Favorite" : "Add to Favorites"}
|
||||
</button>
|
||||
<button
|
||||
className={`w-full rounded-lg px-3 py-2 text-left text-sm transition-colors ${
|
||||
canFindSimilar
|
||||
? "text-gray-200 hover:bg-white/5 hover:text-white"
|
||||
: "text-gray-600 cursor-not-allowed"
|
||||
}`}
|
||||
onClick={async () => {
|
||||
if (!canFindSimilar) return;
|
||||
await loadSimilarImages(image.id, similarScope === "current_folder" ? image.folder_id : null, true, image.folder_id);
|
||||
onClose();
|
||||
}}
|
||||
disabled={!canFindSimilar}
|
||||
>
|
||||
{canFindSimilar ? "Find Similar" : "Embeddings not ready"}
|
||||
</button>
|
||||
<div className="my-1 h-px bg-white/[0.06]" />
|
||||
<div className="px-3 py-1 text-[10px] uppercase tracking-[0.18em] text-gray-600">Rating</div>
|
||||
<div className="flex items-center gap-0.5 px-2 pb-1.5">
|
||||
{Array.from({ length: 5 }, (_, index) => {
|
||||
const rating = index + 1;
|
||||
return (
|
||||
<button
|
||||
key={rating}
|
||||
className="rounded-md p-1 transition-colors hover:bg-white/5"
|
||||
onClick={async () => { await updateImageDetails(image.id, { rating }); onClose(); }}
|
||||
title={`Set ${rating} star rating`}
|
||||
>
|
||||
<svg
|
||||
className={`h-4 w-4 ${rating <= image.rating ? "text-amber-300" : "text-white/20 hover:text-white/40"}`}
|
||||
fill="currentColor" viewBox="0 0 20 20"
|
||||
>
|
||||
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.176 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81H7.03a1 1 0 00.951-.69l1.07-3.292z" />
|
||||
</svg>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{image.rating > 0 ? (
|
||||
<button
|
||||
className="ml-1 rounded-md p-1 text-gray-600 hover:bg-white/5 hover:text-gray-300 transition-colors"
|
||||
onClick={async () => { await updateImageDetails(image.id, { rating: 0 }); onClose(); }}
|
||||
title="Remove rating"
|
||||
>
|
||||
<svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ImageTile({
|
||||
image,
|
||||
onClick,
|
||||
onContextMenu,
|
||||
}: {
|
||||
image: ImageRecord;
|
||||
onClick: () => void;
|
||||
onContextMenu: (event: React.MouseEvent<HTMLButtonElement>) => void;
|
||||
}) {
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const [errored, setErrored] = useState(false);
|
||||
const loadSimilarImages = useGalleryStore((state) => state.loadSimilarImages);
|
||||
const similarScope = useGalleryStore((state) => state.similarScope);
|
||||
const canFindSimilar = image.embedding_status === "ready";
|
||||
|
||||
const src = image.thumbnail_path
|
||||
? convertFileSrc(image.thumbnail_path)
|
||||
: image.media_kind === "image" && image.path
|
||||
? convertFileSrc(image.path)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<button
|
||||
className="group relative overflow-hidden rounded-xl bg-white/[0.04] text-left focus:outline-none"
|
||||
style={{ width: "100%", aspectRatio: "1 / 1" }}
|
||||
onClick={onClick}
|
||||
onContextMenu={onContextMenu}
|
||||
title={image.filename}
|
||||
>
|
||||
{/* Image / placeholder */}
|
||||
{src && !errored ? (
|
||||
<>
|
||||
{!loaded && <div className="absolute inset-0 animate-pulse bg-white/[0.04]" />}
|
||||
<img
|
||||
src={src}
|
||||
alt={image.filename}
|
||||
className={`h-full w-full object-cover transition-all duration-300 ${
|
||||
loaded ? "opacity-100 scale-100" : "opacity-0 scale-[1.02]"
|
||||
} group-hover:scale-[1.03]`}
|
||||
loading="lazy"
|
||||
onLoad={() => setLoaded(true)}
|
||||
onError={() => setErrored(true)}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-white/[0.03] text-white/20">
|
||||
{image.media_kind === "video" ? (
|
||||
<svg className="h-7 w-7" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="h-7 w-7" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1}
|
||||
d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
|
||||
</svg>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Video play icon — subtle at rest, visible on hover */}
|
||||
{image.media_kind === "video" && (
|
||||
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
||||
<div className="rounded-full bg-black/40 p-3 text-white backdrop-blur-sm opacity-50 group-hover:opacity-90 transition-opacity duration-200">
|
||||
<svg className="h-5 w-5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Persistent badges — only shown when meaningful */}
|
||||
<div className="absolute top-2 right-2 flex flex-col items-end gap-1 pointer-events-none">
|
||||
{image.favorite && (
|
||||
<div className="rounded-full bg-black/50 p-1 text-rose-400 backdrop-blur-sm">
|
||||
<svg className="h-2.5 w-2.5" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path d="M3.172 5.172a4 4 0 015.656 0L10 6.343l1.172-1.171a4 4 0 115.656 5.656L10 17.657l-6.828-6.829a4 4 0 010-5.656z" />
|
||||
</svg>
|
||||
</div>
|
||||
)}
|
||||
{image.rating > 0 && (
|
||||
<div className="flex items-center gap-0.5 rounded-md bg-black/60 px-1.5 py-1 text-amber-300 backdrop-blur-sm">
|
||||
{Array.from({ length: image.rating }, (_, index) => (
|
||||
<svg key={index} className="h-2.5 w-2.5" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.176 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81H7.03a1 1 0 00.951-.69l1.07-3.292z" />
|
||||
</svg>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{image.media_kind === "video" && image.duration_ms && (
|
||||
<div className="rounded-md bg-black/60 px-1.5 py-0.5 text-[10px] font-medium text-white/80 backdrop-blur-sm">
|
||||
{formatDuration(image.duration_ms)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Embedding failed badge — top-left */}
|
||||
{image.embedding_status === "failed" && (
|
||||
<div
|
||||
className="absolute top-2 left-2 pointer-events-none"
|
||||
title={image.embedding_error ?? "Embedding failed"}
|
||||
>
|
||||
<div className="flex items-center gap-1 rounded-md bg-black/60 px-1.5 py-0.5 text-[10px] font-medium text-amber-400 backdrop-blur-sm">
|
||||
<svg className="h-2.5 w-2.5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5}
|
||||
d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Hover overlay — slides up from bottom */}
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-black/85 via-black/30 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none" />
|
||||
|
||||
{/* Hover info — appears with overlay */}
|
||||
<div className="absolute bottom-0 left-0 right-0 p-2.5 translate-y-1 group-hover:translate-y-0 opacity-0 group-hover:opacity-100 transition-all duration-200">
|
||||
<p className="truncate text-[12px] font-medium text-white leading-tight">{image.filename}</p>
|
||||
<div className="mt-1.5 flex items-center justify-between gap-2">
|
||||
{image.rating > 0 ? (
|
||||
<div className="flex items-center gap-0.5">
|
||||
{Array.from({ length: image.rating }, (_, i) => (
|
||||
<svg key={i} className="h-2.5 w-2.5 text-amber-300" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.176 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81H7.03a1 1 0 00.951-.69l1.07-3.292z" />
|
||||
</svg>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
<button
|
||||
className={`rounded-md px-2 py-0.5 text-[10px] transition-colors pointer-events-auto backdrop-blur-sm ${
|
||||
canFindSimilar
|
||||
? "bg-white/10 text-white/80 hover:bg-white/20 hover:text-white"
|
||||
: "bg-white/5 text-white/30 cursor-not-allowed"
|
||||
}`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
if (!canFindSimilar) return;
|
||||
void loadSimilarImages(image.id, similarScope === "current_folder" ? image.folder_id : null, true, image.folder_id);
|
||||
}}
|
||||
disabled={!canFindSimilar}
|
||||
>
|
||||
Similar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
const GAP = 6
|
||||
|
||||
export function Gallery() {
|
||||
const images = useGalleryStore((state) => state.images);
|
||||
const loadMoreImages = useGalleryStore((state) => state.loadMoreImages);
|
||||
const openImage = useGalleryStore((state) => state.openImage);
|
||||
const totalImages = useGalleryStore((state) => state.totalImages);
|
||||
const loadingImages = useGalleryStore((state) => state.loadingImages);
|
||||
const zoomPreset = useGalleryStore((state) => state.zoomPreset);
|
||||
const search = useGalleryStore((state) => state.search);
|
||||
const collectionTitle = useGalleryStore((state) => state.collectionTitle);
|
||||
const imageLoadError = useGalleryStore((state) => state.imageLoadError);
|
||||
const galleryScrollResetKey = useGalleryStore((state) => state.galleryScrollResetKey);
|
||||
const isSimilarResults = collectionTitle === "Similar Images";
|
||||
const parsedSearch = parseSearchValue(search);
|
||||
const images = useGalleryStore((state) => state.images)
|
||||
const loadMoreImages = useGalleryStore((state) => state.loadMoreImages)
|
||||
const openImage = useGalleryStore((state) => state.openImage)
|
||||
const totalImages = useGalleryStore((state) => state.totalImages)
|
||||
const loadingImages = useGalleryStore((state) => state.loadingImages)
|
||||
const zoomPreset = useGalleryStore((state) => state.zoomPreset)
|
||||
const search = useGalleryStore((state) => state.search)
|
||||
const collectionTitle = useGalleryStore((state) => state.collectionTitle)
|
||||
const imageLoadError = useGalleryStore((state) => state.imageLoadError)
|
||||
const galleryScrollResetKey = useGalleryStore((state) => state.galleryScrollResetKey)
|
||||
const isSimilarResults = collectionTitle === 'Similar Images'
|
||||
const parsedSearch = parseSearchValue(search)
|
||||
|
||||
const parentRef = useRef<HTMLDivElement>(null);
|
||||
const [contextMenu, setContextMenu] = useState<{ x: number; y: number; image: ImageRecord } | null>(null);
|
||||
const parentRef = useRef<HTMLDivElement>(null)
|
||||
const [containerWidth, setContainerWidth] = useState(0)
|
||||
const [contextMenu, setContextMenu] = useState<{
|
||||
x: number
|
||||
y: number
|
||||
image: ImageRecord
|
||||
} | null>(null)
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = parentRef.current
|
||||
if (!el) return
|
||||
setContainerWidth(el.clientWidth)
|
||||
const ro = new ResizeObserver((entries) => {
|
||||
setContainerWidth(entries[0].contentRect.width)
|
||||
})
|
||||
ro.observe(el)
|
||||
return () => ro.disconnect()
|
||||
}, [])
|
||||
|
||||
const tileSize = tileSizeForZoom(zoomPreset)
|
||||
const cols = useMemo(
|
||||
() => Math.max(1, Math.floor((containerWidth - GAP) / (tileSize + GAP))),
|
||||
[containerWidth, tileSize]
|
||||
)
|
||||
const rowCount = Math.ceil(images.length / cols)
|
||||
|
||||
const estimateSize = useCallback(() => tileSize + GAP, [tileSize])
|
||||
|
||||
const virtualizer = useVirtualizer({
|
||||
count: rowCount,
|
||||
getScrollElement: () => parentRef.current,
|
||||
estimateSize,
|
||||
overscan: 3,
|
||||
paddingStart: GAP,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
virtualizer.measure()
|
||||
}, [cols, virtualizer])
|
||||
|
||||
useEffect(() => {
|
||||
parentRef.current?.scrollTo({ top: 0, left: 0 })
|
||||
}, [galleryScrollResetKey])
|
||||
|
||||
const handleScroll = useCallback(() => {
|
||||
const element = parentRef.current;
|
||||
if (!element) return;
|
||||
if (element.scrollTop < 24) return;
|
||||
const nearBottom = element.scrollTop + element.clientHeight >= element.scrollHeight - 600;
|
||||
const el = parentRef.current
|
||||
if (!el) return
|
||||
if (el.scrollTop < 24) return
|
||||
const nearBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 600
|
||||
if (nearBottom && !loadingImages && images.length < totalImages) {
|
||||
void loadMoreImages();
|
||||
void loadMoreImages()
|
||||
}
|
||||
}, [images.length, loadMoreImages, loadingImages, totalImages]);
|
||||
}, [images.length, loadMoreImages, loadingImages, totalImages])
|
||||
|
||||
useEffect(() => {
|
||||
const element = parentRef.current;
|
||||
if (!element) return;
|
||||
element.addEventListener("scroll", handleScroll, { passive: true });
|
||||
return () => element.removeEventListener("scroll", handleScroll);
|
||||
}, [handleScroll]);
|
||||
|
||||
useEffect(() => {
|
||||
parentRef.current?.scrollTo({ top: 0, left: 0 });
|
||||
}, [galleryScrollResetKey]);
|
||||
|
||||
useEffect(() => {
|
||||
const close = (event: PointerEvent) => {
|
||||
if ((event.target as HTMLElement | null)?.closest("[data-gallery-context-menu]")) return;
|
||||
setContextMenu(null);
|
||||
};
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") setContextMenu(null);
|
||||
};
|
||||
window.addEventListener("pointerdown", close);
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => {
|
||||
window.removeEventListener("pointerdown", close);
|
||||
window.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, []);
|
||||
const el = parentRef.current
|
||||
if (!el) return
|
||||
el.addEventListener('scroll', handleScroll, { passive: true })
|
||||
return () => el.removeEventListener('scroll', handleScroll)
|
||||
}, [handleScroll])
|
||||
|
||||
return (
|
||||
<div ref={parentRef} className="relative flex-1 overflow-y-auto overflow-x-hidden min-h-0 bg-[#07080f]">
|
||||
{images.length === 0 && loadingImages ? (
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-4 text-center px-8 absolute inset-0">
|
||||
<div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-8 min-w-72">
|
||||
<div className="h-5 w-5 mx-auto rounded-full border-2 border-white/20 border-t-white/60 animate-spin" />
|
||||
<p className="mt-4 text-sm text-white/40 font-medium">
|
||||
{isSimilarResults
|
||||
? "Finding similar images"
|
||||
: parsedSearch.mode === "semantic" && parsedSearch.query.length > 0
|
||||
? `Searching for matches to "${parsedSearch.query}"`
|
||||
: parsedSearch.mode === "tag" && parsedSearch.query.length > 0
|
||||
? `Searching tags for "${parsedSearch.query}"`
|
||||
: "Loading media"}
|
||||
</p>
|
||||
<p className="text-xs text-white/20 mt-1">
|
||||
{isSimilarResults
|
||||
? "Comparing visual embeddings"
|
||||
: parsedSearch.mode === "semantic" && parsedSearch.query.length > 0
|
||||
? "Semantic search can take a little longer than filename search"
|
||||
: parsedSearch.mode === "tag" && parsedSearch.query.length > 0
|
||||
? "Matching against AI and user tags"
|
||||
: "Fetching results"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : images.length === 0 && !loadingImages ? (
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-4 text-center px-8 absolute inset-0">
|
||||
<div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-8">
|
||||
<svg className="h-12 w-12 mx-auto text-white/10 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={0.75}
|
||||
d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
|
||||
</svg>
|
||||
<p className="text-sm text-white/30 font-medium">
|
||||
{imageLoadError
|
||||
? "Could not load results"
|
||||
: isSimilarResults
|
||||
? "No similar images found"
|
||||
: parsedSearch.mode === "semantic" && parsedSearch.query.length > 0
|
||||
? "No semantic matches found"
|
||||
: parsedSearch.mode === "tag" && parsedSearch.query.length > 0
|
||||
? "No tag matches found"
|
||||
: "No media found"}
|
||||
</p>
|
||||
<p className="text-xs text-white/15 mt-1">
|
||||
{imageLoadError
|
||||
? imageLoadError
|
||||
: isSimilarResults
|
||||
? "This item may be visually isolated, or more embeddings may need to finish processing"
|
||||
: parsedSearch.mode === "semantic" && parsedSearch.query.length > 0
|
||||
? "Try a broader phrase, or wait for more embeddings to finish processing"
|
||||
: parsedSearch.mode === "tag" && parsedSearch.query.length > 0
|
||||
? "Try a shorter tag, or wait for more tagging jobs to finish"
|
||||
: "Try adjusting your filters or add a new folder"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="relative min-h-0 flex-1">
|
||||
<div
|
||||
className="grid content-start"
|
||||
ref={parentRef}
|
||||
className="absolute inset-0 overflow-x-hidden overflow-y-auto bg-gray-950"
|
||||
>
|
||||
{images.length === 0 && loadingImages ? (
|
||||
<GalleryLoadingState isSimilarResults={isSimilarResults} parsedSearch={parsedSearch} />
|
||||
) : images.length === 0 && !loadingImages ? (
|
||||
<GalleryEmptyState
|
||||
imageLoadError={imageLoadError}
|
||||
isSimilarResults={isSimilarResults}
|
||||
parsedSearch={parsedSearch}
|
||||
/>
|
||||
) : (
|
||||
<div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
|
||||
{virtualizer.getVirtualItems().map((virtualRow) => {
|
||||
const startIndex = virtualRow.index * cols
|
||||
const rowImages = images.slice(startIndex, startIndex + cols)
|
||||
return (
|
||||
<div
|
||||
key={virtualRow.key}
|
||||
style={{
|
||||
padding: GAP,
|
||||
position: 'absolute',
|
||||
top: virtualRow.start,
|
||||
width: '100%',
|
||||
height: virtualRow.size,
|
||||
display: 'grid',
|
||||
gridTemplateColumns: `repeat(${cols}, ${tileSize}px)`,
|
||||
gap: GAP,
|
||||
gridTemplateColumns: `repeat(auto-fill, minmax(${tileSizeForZoom(zoomPreset)}px, 1fr))`,
|
||||
paddingLeft: GAP,
|
||||
paddingRight: GAP,
|
||||
paddingBottom: GAP,
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
>
|
||||
{images.map((image) => (
|
||||
{rowImages.map((image) => (
|
||||
<ImageTile
|
||||
key={image.id}
|
||||
image={image}
|
||||
onClick={() => openImage(image)}
|
||||
onContextMenu={(event) => {
|
||||
event.preventDefault();
|
||||
setContextMenu({ x: event.clientX, y: event.clientY, image });
|
||||
event.preventDefault()
|
||||
setContextMenu({ x: event.clientX, y: event.clientY, image })
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{images.length > 0 && loadingImages ? (
|
||||
<div className="flex justify-center py-8">
|
||||
<div className="h-4 w-4 rounded-full border-2 border-white/20 border-t-white/60 animate-spin" />
|
||||
<div className="h-4 w-4 animate-spin rounded-full border-2 border-white/20 border-t-white/60" />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{contextMenu ? (
|
||||
<ContextMenu
|
||||
<ImageContextMenu
|
||||
x={contextMenu.x}
|
||||
y={contextMenu.y}
|
||||
image={contextMenu.image}
|
||||
@@ -402,5 +151,10 @@ export function Gallery() {
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
|
||||
{/* Pinned to the bottom of the gallery viewport — outside the scroll
|
||||
container so it stays put while the grid scrolls. */}
|
||||
<BulkActionBar />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { ImageRecord, useGalleryStore } from '../store'
|
||||
import { ContextMenu, MenuItem, MenuLabel, MenuSeparator, SubMenu } from './menu'
|
||||
import { Tooltip } from './Tooltip'
|
||||
import { CloseIcon, StarIcon } from './icons'
|
||||
|
||||
/** Right-click menu for an image tile. Shared by the Gallery grid and the Timeline. */
|
||||
export function ImageContextMenu({
|
||||
x,
|
||||
y,
|
||||
image,
|
||||
onClose,
|
||||
}: {
|
||||
x: number
|
||||
y: number
|
||||
image: ImageRecord
|
||||
onClose: () => void
|
||||
}) {
|
||||
const openImage = useGalleryStore((state) => state.openImage)
|
||||
const updateImageDetails = useGalleryStore((state) => state.updateImageDetails)
|
||||
const findSimilar = useGalleryStore((state) => state.findSimilar)
|
||||
const albums = useGalleryStore((state) => state.albums)
|
||||
const addToAlbum = useGalleryStore((state) => state.addToAlbum)
|
||||
const canFindSimilar = image.embedding_status === 'ready'
|
||||
|
||||
return (
|
||||
<ContextMenu x={x} y={y} onClose={onClose}>
|
||||
<MenuItem label="Open Preview" onSelect={() => openImage(image)} />
|
||||
<MenuItem
|
||||
label={image.favorite ? 'Remove Favorite' : 'Add to Favorites'}
|
||||
onSelect={() => void updateImageDetails(image.id, { favorite: !image.favorite })}
|
||||
/>
|
||||
<MenuItem
|
||||
label={canFindSimilar ? 'Find Similar' : 'Embeddings not ready'}
|
||||
disabled={!canFindSimilar}
|
||||
onSelect={() => findSimilar(image.id, image.folder_id)}
|
||||
/>
|
||||
<SubMenu label="Add to Album" panelClassName="max-h-64 overflow-y-auto">
|
||||
{albums.length === 0 ? (
|
||||
<MenuItem label="No albums yet" disabled />
|
||||
) : (
|
||||
albums.map((album) => (
|
||||
<MenuItem
|
||||
key={album.id}
|
||||
label={album.name}
|
||||
hint={album.image_count.toLocaleString()}
|
||||
onSelect={() => void addToAlbum(album.id, [image.id])}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</SubMenu>
|
||||
<MenuSeparator />
|
||||
<MenuLabel>Rating</MenuLabel>
|
||||
<div className="flex items-center gap-0.5 px-2 pb-1.5">
|
||||
{Array.from({ length: 5 }, (_, index) => {
|
||||
const rating = index + 1
|
||||
return (
|
||||
<Tooltip key={rating} label={`Set ${rating} star rating`} followCursor>
|
||||
<button
|
||||
className="rounded-md p-1 transition-colors hover:bg-white/5"
|
||||
onClick={async () => {
|
||||
await updateImageDetails(image.id, { rating })
|
||||
onClose()
|
||||
}}
|
||||
>
|
||||
<StarIcon
|
||||
className={`h-4 w-4 ${rating <= image.rating ? 'text-amber-300' : 'text-white/20 hover:text-white/40'}`}
|
||||
/>
|
||||
</button>
|
||||
</Tooltip>
|
||||
)
|
||||
})}
|
||||
{image.rating > 0 ? (
|
||||
<Tooltip label="Remove rating" followCursor>
|
||||
<button
|
||||
className="ml-1 rounded-md p-1 text-gray-600 transition-colors hover:bg-white/5 hover:text-gray-300"
|
||||
onClick={async () => {
|
||||
await updateImageDetails(image.id, { rating: 0 })
|
||||
onClose()
|
||||
}}
|
||||
>
|
||||
<CloseIcon className="h-3 w-3" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
</ContextMenu>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Compact Confirm/Cancel pair for destructive row actions (remove folder,
|
||||
* delete album). Swap it in where the hover actions normally sit.
|
||||
*/
|
||||
export function InlineConfirm({
|
||||
onConfirm,
|
||||
onCancel,
|
||||
}: {
|
||||
onConfirm: () => void
|
||||
onCancel: () => void
|
||||
}) {
|
||||
return (
|
||||
<div className="flex shrink-0 items-center gap-1" onClick={(event) => event.stopPropagation()}>
|
||||
<button
|
||||
className="rounded bg-red-500/20 px-1.5 py-0.5 text-[10px] text-red-400 transition-colors hover:bg-red-500/30 hover:text-red-300"
|
||||
onClick={onConfirm}
|
||||
>
|
||||
Confirm
|
||||
</button>
|
||||
<button
|
||||
className="rounded bg-white/5 px-1.5 py-0.5 text-[10px] text-gray-500 transition-colors hover:bg-white/10 hover:text-gray-300"
|
||||
onClick={onCancel}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
|
||||
/**
|
||||
* In-place rename input for sidebar rows (folders, albums). Mount it in
|
||||
* place of the row label while renaming: commits on Enter or blur (only when
|
||||
* the trimmed name is non-empty and actually changed), cancels on Escape.
|
||||
*/
|
||||
export function InlineRename({
|
||||
name,
|
||||
onRename,
|
||||
onClose,
|
||||
}: {
|
||||
name: string
|
||||
onRename: (next: string) => Promise<void> | void
|
||||
onClose: () => void
|
||||
}) {
|
||||
const [value, setValue] = useState(name)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
inputRef.current?.focus()
|
||||
inputRef.current?.select()
|
||||
}, [])
|
||||
|
||||
const commit = async () => {
|
||||
const trimmed = value.trim()
|
||||
if (trimmed && trimmed !== name) {
|
||||
await onRename(trimmed)
|
||||
}
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<input
|
||||
ref={inputRef}
|
||||
className="w-full rounded bg-white/10 px-1 py-0 text-[13px] leading-tight font-medium text-white ring-1 ring-blue-500/60 outline-none"
|
||||
value={value}
|
||||
onChange={(event) => setValue(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault()
|
||||
void commit()
|
||||
}
|
||||
if (event.key === 'Escape') onClose()
|
||||
}}
|
||||
onBlur={() => void commit()}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
/>
|
||||
)
|
||||
}
|
||||