Comic archive formats (.cbz, .cbr, .cb7, .cbt) and .kepub files were
falling through to the default case in extractMetadata(), which only
set the title from the filename. This meant ComicInfo.xml was never
parsed and no cover images were extracted for comics without a Calibre
metadata.opf sidecar file.
The fix adds dedicated switch cases:
- .cbz/.cbr/.cb7/.cbt: calls mergeMetadata() with nil, which triggers
existing ComicInfo.xml parsing (title, series, issue number, writer,
publisher, genre, reading direction, etc.) and cover image extraction
from the archive. Falls back to sidecar cover if no image is found.
- .kepub: treated the same as .epub since KEPUB is an EPUB variant,
enabling full metadata and cover extraction.
TestCollectionSearchLibraryFilter's 'invalid library_id' case was
expecting a 200 with empty results, but the search handler correctly
returns 404 when no results are found. The test also consumed the
response body for debug logging then tried to JSON-decode the same
body (causing EOF). Add expectedStatus field to the test struct and
return early when a specific non-200 status is expected.
Three issues fixed in processing_issues_test.go:
- Empty UUID: handler returns 400 (uuid.Parse rejects empty string), not 404.
Fix expectedStatus in both List and Stats validation tests.
- Path traversal: raw '../../' in URL creates extra path segments that don't
match the route. Use url.PathEscape so the string is treated as a single
path parameter, letting the handler reject it with 400.
- SQL injection: raw special characters (semicolons, quotes) caused
httptest.NewRequest to panic. url.PathEscape prevents the panic and the
handler rejects the decoded value via uuid.Parse.
- Remove unsupported 'audiobooks' library type from
TestProcessingIssuesDifferentLibraryTypes (only ebooks/comics/manga exist
in the database schema).
The setupTestServer() helper in test_helpers_test.go was not creating
a ProcessingIssuesHandler and not passing one to the router config,
causing a nil pointer dereference when any processing issues route was
hit during tests. Add handler creation and wire it into routerConfig
to match how cmd/server/main.go does it.
Both ListProcessingIssues and GetProcessingIssueStats were reading the
URL parameter 'libraryId', but the routes in internal/router/library.go
define the param as ':id'. This caused both endpoints to always fail with
an invalid library ID error since c.Param('libraryId') returns an empty
string that can't be parsed as a UUID.
Remove redundant type conversions that Go 1.26 makes unnecessary or that
were already no-ops:
- uuid.UUID(x.Bytes) → x.Bytes (uuid.UUID is [16]byte, same as pgtype UUID Bytes)
- pgtype.UUID{Bytes: [16]byte(u), Valid: true} → pgtype.UUID{Bytes: u, Valid: true}
- (*time.Time)(&x.Time) → &x.Time
- json.RawMessage(x) → x where x is already []byte
- []byte(stringVal) → stringVal where []byte is expected
- int()/int64()/byte() casts on values already of the target type
- Decompressor(fn) → fn (type is identical)
Handle previously ignored error returns:
- collections.go: check json.Unmarshal error in GetCollection
- conversion_service.go: check fileSize.Scan() error
- app_test.go: check app.Shutdown() error in benchmark
DismissAllResolved was calling ListSyncConflictsByUser which filters to
'unresolved' conflicts only, so it could never find the user_resolved or
bulk_resolved conflicts it was trying to delete. The query always returned
an empty set, making dismiss-all a no-op.
Fix the leading space in three SQL query name annotations (ListConflictsByUser,
ListAllConflictsByUserAndStatus, CheckForProgressConflicts) that prevented
sqlc from generating their Go functions. Regenerate the query code and swap
DismissAllResolved to use ListConflictsByUser (no status filter) — the
existing Go loop already filters by resolution_status.
The builder stage was previously bumped to Go 1.26 but the test-runner stage
remained on Go 1.25, causing 'go.mod requires go >= 1.26.0' errors during
test execution.
Go 1.26 introduced stricter validation of replace directives in dependency
go.mod files, which broke 'go install sqlc@latest' (sqlc v1.31.0 has replace
directives). Replace go install with a direct binary download from GitHub
releases, matching the existing kepubify download pattern.
Bump test-runner from golang:1.25-alpine to golang:1.26-alpine to match the
go.mod requirement.
Replace all unhandled resp.Body.Close() calls throughout the test suite:
- Deferred calls: replace 'defer VAR.Body.Close()' with a closure that explicitly
discards the error via 'defer func(Body io.ReadCloser) { _ = Body.Close() }(VAR.Body)'
- Immediate calls: replace 'VAR.Body.Close()' with '_ = VAR.Body.Close()'
Replace all unhandled json.NewDecoder(VAR.Body).Decode(&x) calls with error capture
and require.NoError assertion. Files using httptest.ResponseRecorder (collections_preview,
processing_issues) use 'err :=' declaration; suite-style tests (scanner_integration,
dashboard_integration) use s.T() instead of t.
Replace direct error equality check with errors.Is() in media_scanner_hash_test.
In analytics_test.go, improve defer patterns by capturing resp.Body as a named parameter
to avoid stale references, and add require.NoError() checks on all json.NewDecoder().Decode()
calls that were previously silently ignoring decode errors.
Replace direct error equality checks (err == pgx.ErrNoRows, err != http.ErrServerClosed)
with the idiomatic errors.Is() function throughout handlers, services, middleware, and app
startup. This correctly handles wrapped error chains.
Also replace a raw type assertion (*HTTPError) with errors.AsType[*HTTPError]() in the
error handler middleware for consistency.
Additionally, rename shadowed variables for clarity:
- sidecar.go: config -> sidecarConfig, systemConfig (shadowed package-level vars)
- media_scanner.go: uuid -> uuidString (shadowed the uuid package import)
Add the 'reading_mode' field with 'dark' | 'light' values to the
ReaderSettings TypeScript interface, preparing the frontend for a
dark/light reading mode toggle.
Two changes to EPUB metadata extraction:
1. Restructure extractMetadata so that fixed-layout detection and cover
extraction always run for EPUBs, even when extractEPUBMetadata returns
an error. Previously, a partial failure from the EPUB parser would skip
cover and format detection entirely, leaving books without covers.
2. Remove the language restriction (ja/jpn) from manga reading direction
detection. Manga tagged with 'manga' should default to RTL regardless
of the language metadata, since the tag is an explicit signal from the
user or metadata source.
In applyProgressResolution and applyResolution, currentPage and totalPages
were unconditionally read from existingProgress even when the preceding
query returned err (no rows). This caused a nil pointer dereference when
no existing reading progress existed for a media item. Now declare the
variables as zero-value pgtype.Int4 and only populate them from
existingProgress when err is nil.
Replace direct equality checks (err != pgx.ErrNoRows) with the idiomatic
errors.Is(err, pgx.ErrNoRows) pattern. This is the recommended Go practice
for error comparison as it correctly handles wrapped errors from error
chains, making the code more robust against future refactoring that might
wrap errors with fmt.Errorf and %w.
When opening a sevenzip archive, the init() method calls sr :=SevenZipReader()
but never checked if sr was nil before using it. This could cause a nil
pointer dereference when processing malformed or empty archives. Add an
explicit nil check returning errFormat early if the subreader is nil.
Also fixes a minor import grouping whitespace issue.
Replace the previous mock/httptest-based conflict tests with
integration tests that exercise the full HTTP stack against a live
test server with a real database. Changes include:
- Add shared test helpers (setupConflictTest, createTestConflict,
makeConflictData) to reduce boilerplate across test files
- Split monolithic TestConflictDetection and TestConflictsBulkOperations
into focused test functions per scenario
- Test conflict detection, bulk resolution (most_recent, highest_progress,
manual strategies), and edge cases (empty IDs, invalid UUIDs,
unauthorized access)
- Verify actual database state after resolution, not just HTTP response
Add table-driven tests for the conflict handler's source selection
methods: GetMostRecentSource, GetHighestProgressSource, and
GetEarliestSource. Covers cases where each device wins, ties, and
missing/invalid data.
strings.Title has been deprecated since Go 1.18 because it does not
handle Unicode properly. Replace it with cases.Title from
golang.org/x/text which correctly handles language-specific title
casing. Applied to breadcrumb generation and document title formatting.
Add a structured plan for translating Fish shell config.fish into
equivalent Zsh .zshrc syntax, preserving the existing Forge-managed
block in the target file.
Simplify pointer creation in media scanner validation messages and worker
job timestamps by using inline new() instead of local variable + address-of.
In media_scanner.go this cleans up three validation error message returns
(manga/comics library format checks). In worker.go it simplifies StartedAt
and CompletedAt timestamp assignments.
Simplify pointer creation across kobo, koreader, and queue handlers by
replacing the two-step pattern (assign to local, then take address) with
inline new() calls. This reduces verbosity without changing behavior:
Before:
remaining := int(a - b)
pagesRemaining = &remaining
After:
pagesRemaining = new(int(a - b))
Covers page calculations, chapter/progress fields, UUID formatting,
and timestamp string conversions.
Replace the original 5-theme allowlist (light, sepia, dark, night,
high-contrast) with a richer 20-theme palette organized into tonal
families: neutrals (light, paper, slate, oled), warm tones (sepia,
parchment, warm, candlelight), cool tones (azure, sky, arctic, frost),
and evening tones (dusk, sunset, twilight, forest, moss, solarized).
The backend validator in UpdateSettings now accepts all 20 theme names,
and the frontend Tailwind build is updated to include the new theme CSS
variables and preflight reset.
- Remove Playwrite NZ Guides test font and all references (FONT_MAP,
FONT_FILES, reader-fonts.css, dropdown option, font files)
- Move settings panel from left sidebar to right sidebar (left sidebar
now only contains TOC)
- Move Restore Defaults button from top bar icon to a styled button
inside the settings panel, side by side with Done button
The paginator renders inside a sandboxed iframe that blocks @font-face
URL fetches. Fonts were never loading — all font-family rules fell back
to the generic 'serif' system font, making every reading font identical.
Fix: fetch font files on the parent page, create blob: URLs via
URL.createObjectURL(), and use those blob URLs in the @font-face rules
injected into the iframe via setStyles(). Blob URLs are always
same-origin with the creating document, so the sandboxed iframe can
access them with allow-same-origin.
Also added Playwrite NZ Guides as a test font for verifying font
switching works.
Fonts weren't loading because the paginator renders inside a sandboxed
iframe. @font-face declarations in the parent page's CSS are invisible
to the iframe's document. Even injecting @font-face rules via
setStyles() may not trigger font loading in sandboxed iframes.
Fix: inject a <link> to reader-fonts.css directly into the iframe's
document on each section load, so @font-face declarations are parsed
in the iframe's own document context where font-family rules can
reference them.
Also:
- Remove foliate-themes.css entirely (no longer needed)
- Set viewport background color directly via JS using THEME_COLORS map
- Remove reading theme CSS classes from viewport element
background: none on html/body exposed the iframe's default black
background in gaps around the content. Now uses background-color
matching the theme color, and stops forcing background on body *
which caused black bars around page margins.
The paginator renders book content inside a sandboxed iframe within a
closed shadow DOM. @font-face declarations from the parent page's
reader-fonts.css are NOT available inside the iframe's document context.
All font-family rules fell back to the generic 'serif' system font,
making every reading font look identical.
Fix: prepend all @font-face declarations (Literata, Crimson Pro,
Source Serif 4, EB Garamond, Libertinus Serif, Noto Serif, Charis SIL,
IBM Plex Serif) into the CSS string returned by getCSS(), so they're
injected into the iframe via renderer.setStyles().
Comic Sans MS is a system font not available on Linux. The cursive
fallback rendered as a script font, giving false negatives. All 8
loaded reading fonts are serif fonts loaded via @font-face, so they
intentionally look similar — font switching is confirmed working.
Studied grimmory-tools/grimmory's ebook-reader style.service.ts and adopted
their approach:
- Replace CSS custom property resolution (getComputedStyle) with a hardcoded
THEME_COLORS map containing concrete fg/bg/link values for all 18 themes
in both light and dark modes. No more variable resolution failures.
- Font family now targets body + body * with !important, overriding book CSS
on every element (matching grimmory's approach).
- Colors use grimmory's aggressive pattern:
html, body { color: ... !important; background: none !important; }
body * { color: inherit !important; background-color: ... !important; }
This forces reading theme colors on ALL book elements, overriding inline
styles and book stylesheets.
- Line height uses !important on p, li, blockquote, dd to override book CSS.
- Removed fragile getComputedStyle calls entirely. getCSS() now receives
themeName and themeMode parameters for direct color lookup.
- Add Comic Sans MS as a test font option to verify font switching works
- Add !important to background-color and color in getCSS() to prevent
book CSS from overriding user's reading theme colors
- Expand font size range from 12-24px to 10-40px, bump default to 18px
- Expand line height range from 1.0-2.5 to 0.8-3.0
- Add restoreDefaults() method that resets reading theme, font, size,
line height, and justify/hyphenate to sensible defaults
- Add ↩️ restore defaults button in top bar underneath the settings gear
Two root causes fixed:
1. Reading theme CSS variables were on document.body, leaking font/color
into chrome UI. Now scoped to #reader-viewport so chrome keeps its own
theme (system font, --text-primary colors) while the reading area uses
reading theme colors/background.
2. getCSS() never received font family, font size, or line height settings.
The settings UI (dropdowns, sliders) saved values but they were never
injected into the book's shadow DOM. Now getCSS() accepts all four
settings and generates proper CSS rules for them.
Changes:
- Wrap foliate-view in #reader-viewport div (absolute positioned between
chrome bars)
- getCSS() reads computed style from #reader-viewport, not document.body
- getCSS() params expanded: fontFamily, fontSize, lineHeight, justify,
hyphenate (removed unused 'spacing')
- Added FONT_MAP to translate setting keys to CSS font-family values
- applyTheme() targets #reader-viewport instead of document.body
- Removed dead #reader-viewport typography rules from foliate-themes.css
(shadow DOM doesn't inherit outer styles), kept only background-color
- Position foliate-view with absolute inset-x-0 top-[52px] bottom-[52px]
so book content renders between the fixed header and footer bars instead
of behind them
- Confirmed removal of foliate-themes.css base typography was correct:
body color now comes from chrome theme's --text-primary (light for
dark chrome themes like tokyo-night)
Two fixes:
1. Remove base typography block from foliate-themes.css. The html/body
rules were unlayered CSS that overrode the chrome theme's layered
body styles, causing dark reading theme text colors (--reader-text)
to apply to the outer chrome UI on dark backgrounds. These styles
are only meant for the shadow DOM, which getCSS() already handles.
2. Move missing typography rules (img, blockquote, a, p orphans/widows)
into getCSS() so the shadow DOM still gets them.
3. Add sun/moon emoji indicators to the light/dark toggle switch.
Add explicit light/dark mode toggle switch to the reading theme settings.
The reading mode defaults based on the chrome theme (dark chrome themes
like tokyo-night default to dark reading mode).
- Add readingMode property to readerShell Alpine component
- Add toggleReadingMode() method that toggles dark class on body
- Add detectChromeDarkMode() to infer default from chrome theme
- Update applyTheme() to add/remove dark class and persist reading_mode
- Add toggle switch UI in settings panel (blue pill style, next to
Reading Theme heading)
- Add reading_mode to default settings in settings-manager
Books were failing to load because foliate-js fetches the file URL
without auth headers, getting rejected by JWT middleware. Also,
reading themes were not being applied because getCSS() didn't
inject background/text colors into the book iframe.
- Fetch book file with Bearer token, pass as File (not URL) to
view.open() so foliate-js can detect format via filename extension
- Add reading theme class to body so foliate-themes.css activates
the correct --reader-bg/--reader-text CSS variables
- Update getCSS() to read theme colors from outer page and embed
them in the iframe CSS string (background-color, color, link
color, selection color)
- Fix Alpine.start() deadlock: move call outside the alpine:init
listener so Alpine actually initializes
- Remove unused tocItem from relocate handler destructuring
- Replace apiGet/apiPut with direct fetch in settings-manager to
fix /api prefix mismatch (reader routes are at /readers/*, not
/api/readers/*)
The foliate-view custom element had no height, causing its shadow DOM
content to collapse to 0px. Books were loading but invisible.
- Add h-screen overflow-hidden to body for full viewport height
- Add block w-full h-full to foliate-view element
- Replace flex-grow with Tailwind grow class on progress slider
- Remove #progress-slider CSS rule from inline style block
(replaced by Tailwind grow utility)
Update NewDevDBSetup collection to create Ebook, Comic, and Manga
libraries with separate IDs (ebook_library_id, comic_library_id,
manga_library_id) instead of a single library_id.
- Fix CreateComicLibrary and CreateMangaLibrary to use correct
names, descriptions, and types instead of duplicating Ebook values
- Update NewDB.sh to run the full setup sequence: register user,
create all three libraries, add folders, then scan all
- Add AddEbookLibraryFolder, AddComicLibraryFolder, and
AddMangaLibraryFolder requests with per-type subfolder paths
- Add ScanAllLibraries request using bru.sendRequest() to scan
each library sequentially via the /api/scanner/scan endpoint
- Update Get Libraries (Admin) to save all three library IDs
- Update List Media Items requests to use ebook_library_id
- Rename library_id to ebook_library_id in Create Library and
Add Library Folder requests
- Add comic_library_id and manga_library_id to environment
Major rewrite of the web reader to properly interface with
@bookhoard/foliate-js, replacing the abandoned panel-detection
architecture with direct pan and zoom support built into the
foliate-js FixedLayout renderer.
Template (reader.templ):
- Fix critical bug: x-init config was using literal strings
'{ readerData.X }' inside a quoted attribute, which templ
treated as raw text and never interpolated. Values were never
actually passed to JavaScript. Now uses fmt.Sprintf() with
templ's expression attribute syntax ={ }.
- Pass fileUrl from server so foliate-js can open books directly.
- Redesign bottom bar with foliate-js parity: left/right navigation
buttons, progress slider with tick marks, and zoom controls
(zoom out, percentage display, zoom in, magnifier, pan/select
mode toggle for PDFs).
- Remove panel editor button and enablePanelDetection config.
- Add SVG icon styles for consistent reader controls.
Go types (templates/types.go):
- Expand ReaderMetadata with FormatGroup, MangaType,
ReadingDirection, FileURL, and LibraryID fields needed by
the reader frontend.
Router (internal/router/reader.go):
- Populate new ReaderMetadata fields from database values.
- Construct FileURL from library ID and file path for the
/uploads/library-{id}/* file serving route.
Reader JS (reader.ts):
- Full rewrite modeled on foliate-js Reader class, adapted for
Alpine.js. Opens books via view.open(fileUrl), accesses
view.renderer for zoom/pan/navigation, and wires up keyboard
shortcuts (+/-/0 for zoom, arrows for nav, Escape for magnifier).
- Uses view.isFixedLayout instead of importing FixedLayout class,
avoiding a TypeScript module resolution issue with the Vite alias.
Settings manager (settings-manager.ts):
- Remove dependency on deleted ReaderContext event bus.
- Export loadSettings/saveSettings/syncSettings directly as
standalone async functions.
Cleanup:
- Delete reader-context.ts and reader-events.ts (over-engineered
event system replaced by direct function calls).
- Remove panel_zoom_enabled from ReaderSettings type.
Update all library API request files to the current Bruno format
with proper settings blocks, updated sequence numbers, and cleaner
YAML formatting.
Add NewDevDBSetup collection with requests for creating comic, ebook,
and manga libraries, user registration, and folder configuration to
speed up development environment setup.
The string_to_array call in detect_fixed_layout_epub() had an extra
closing parenthesis after the '<img' delimiter, causing a SQL syntax
error that prevented the database container from initializing:
IF array_length(string_to_array(opf_content, '<img')), 1) - 1 > 50
Fixed to:
IF array_length(string_to_array(opf_content, '<img'), 1) - 1 > 50