Skip to content

fix(historyimport): import Emby watch dates, episode favorites, and clear errors - #1329

Merged
Quick104 merged 3 commits into
mainfrom
t3code/audit-emby-history-import
Sep 23, 2026
Merged

Quick104 merged 3 commits into
mainfrom
t3code/audit-emby-history-import

Conversation

@Quick104

@Quick104 Quick104 commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: #1242
Validation tasks: changes #1242 C1–C3 and #1243 C2 before their first run; no passed case affected

Emby imports have never carried watch dates. Emby list queries leave out
ProductionYear, UserData.PlayCount, and UserData.LastPlayedDate unless the
request names them in Fields, and Silo only asked for ProviderIds. I saw the same
behavior on Emby 4.8.11, 4.9.5, and the current stable 4.10.0.40, so this is not a
regression from the recent Emby release. The results:

  • No Emby import created any watch history rows.
  • Every imported progress row was dated 1970-01-01, so re-running an import could
    never update anything. Progress made in Emby after the first import stayed stale.
  • Every record had year 0.

Testing the import end to end also turned up these problems:

  • Episode favorites were dropped, and season favorites were dropped without a word.
  • A played multi-episode file (S01E01-E02) only marked the first episode watched.
  • An Emby account without a password could not import (HTTP 500).
  • Through v2, an unreachable server returned a 500 "An unexpected error occurred." A
    wrong password showed "The request did not pass validation; see errors." because the
    web client displays the problem detail, and the real message was only in errors[].
  • Run warnings and unmatched reasons all read "An import item could not be processed."
    or "No matching catalog item was imported.", whatever the cause.
  • The progress counter counted skipped items twice ("21 / 13 processed" on a re-run),
    and a used Emby Connect session still showed "Connected" until the next run failed
    with 409.

Approach

  • Emby client: request the three missing fields. Page item lists (500 per page,
    trusting TotalRecordCount) and batch Ids= lookups (100). Before this, a large
    library came back as one unbounded response against a 30-second timeout.
  • Favorites: import movie, series, and episode favorites. Silo has no season
    favorites, so the run reports how many were skipped. Favorite episodes use series
    metadata for the series + SxxEyy fallback match.
  • Multi-episode files: a played file marks each episode in its range, up to ten,
    and splits the runtime between them. A partly watched file stays on its first
    episode, because its position can't be split.
  • Series metadata: a failed lookup is now a warning instead of failing the run.
    Episodes with their own IDs still match.
  • Passwords: a saved Emby server needs only a username.
  • Errors (v2 only):
    • Upstream call sites tag unreachable-source failures (ErrSourceUnreachable), so a
      database error in Silo still reports as an internal error.
    • The v2 adapter maps unreachable sources to 503 and ErrInvalidInput to 422 with
      its detail. It reads the cause that the shared seam's APIError wraps.
    • v2 validation problems repeat the specific message in detail.
    • The shared mapping still answers the frozen /api/v1 exactly as before.
  • Emby warnings: the favorites and series-metadata warnings store fixed text and
    log the upstream error, because v1 returns stored warnings verbatim.
  • Run monitors: they still never echo stored diagnostics, as docs/admin-api.md
    requires, but they now map each known diagnostic to a fixed summary of its cause.
    User-facing run errors pass through. Unmatched counts are grouped by cause, so 200
    missing movies show as one "Not matched (200)" line, not 20 lines of "(1)".
    Unmatched samples and logs keep the full reason.
  • Web page:
    • processed = matched + unmatched;
    • the Emby Connect session clears after a run starts;
    • the saved-server form requires a username and says the password can be blank;
    • the Emby card no longer offers a "direct server" option that doesn't exist.

Emby Connect login uses the same requests as before; they match Emby's published
Connect protocol.

Validation

End to end against Emby 4.10.0.40 (native build) and a real Silo backend on Postgres
with a seeded catalog.

Fixture

  • Movies: played, in progress, favorite only, missing from the Silo catalog, and one
    without provider IDs.
  • Three shows with specials, a two-episode file, and favorites on a show, a season,
    and episodes.
  • A passwordless Emby user.

Results on the same Emby state

main this branch
History rows 0 10, dated from Emby
Favorites 4 6 (adds 2 episodes)
Progress rows 9 10 (both episodes of the range file)
Warnings 2× "An import item could not be processed." season-favorite count and "Not matched (1): …" per cause

Other checks

  • Re-import after watching further in Emby: Dune moved from 10:00 to 20:00, and an
    episode marked played in Emby became watched. On main both runs report skipped.
  • Admin API-key mapping run: same results as the personal run. The passwordless user
    imported with the real date.
  • v2: a wrong password gets 422 with the specific detail, an unreachable server 503,
    and a blank username 422 "Choose a server and enter the Emby username." Through v1,
    the unreachable server and the blank username still get the same 500 as before.
  • Emby Connect was not tested live because no Connect account was available. The
    server-side /Connect/Exchange endpoint still exists on 4.10.

New tests

  • A fake Emby server that, like the real one, omits the fields unless asked. The Emby
    tests run against it.
  • Paging, page-size caps, ID batching, favorites, and multi-episode expansion.
  • Error mapping, summaries, and grouping unmatched items by cause.
  • Web: the progress count and the Connect session reset.

Gate

  • go build, gofmt, go vet, and make lint-changed (0 issues) pass.
  • make test-go passes except for two tests that also fail on main in the same
    environment: TestAdminResourceCapabilitiesAndScope fails on macOS, and
    TestResolveViewerScopeParity hit its 25 ms policy timeout under load. It passes
    3/3 in isolation on both branches.
  • internal/historyimport also passes with SILO_TEST_DATABASE_URL set. That run
    covers the new DB-gated tests, which CI skips.
  • make test-web (611 files), web lint, format check, and build pass.
  • verify-apiv2-openapi, verify-apiv2-contract, verify-apiv2-fixtures,
    TestCommittedArtifactMatchesRouter, route/offline/migration/settings/playback/
    scenario checks, and verify-local-paths pass.
  • After the follow-up commit, I reran historyimport, handlers, apiv2,
    lint-changed, the contract checks, and a live v1/v2 error check locally. CI covers
    the full suite.

Risks

  • The v2 problem detail, some v2 statuses (unreachable source 500 to 503, invalid
    input 500 to 422), and run warning text for history imports change; the structure
    doesn't. v1 responses are unchanged. Only the bundled web client consumes these
    operations. The API-contract doc records no Apple or Android history-import
    consumers, and the change doesn't reach the Jellyfin compatibility API.
  • Re-importing from Emby will now update progress rows that earlier imports stamped
    at the epoch, and add their history rows. That is the intended repair.
  • Emby keeps LastPlayedDate unchanged when an item is marked played through the API
    without a date. Emby's own clients send one, but a re-import can't see that change.

Follow-ups, not in this PR:

  • AC1 in [v1] Watch-history import (Plex / Jellyfin / Emby) #1239 asks for play counts. Silo stores none for any source, so that needs a
    data-model decision.
  • Jellyfin has the same password-required restriction and imports no favorites.
  • Silo's web UI can't show or toggle episode favorites.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.

AI Disclosure

  • Harness: Claude Code, run inside T3 Code
  • Tool(s): Claude Code, with its general-purpose subagents for a read-only UI/API audit
    and a read-only adversarial review of the diff
  • Model(s): claude-opus-5-5[1m]
  • Involvement: Fully AI-generated; maintainer review pending
  • Adversarial review: a separate read-only agent, on the same model, reviewed the full
    diff for correctness, regressions in the shared Jellyfin/Plex paths, leaks of raw
    upstream text, and test quality.
    • Fixed: database connection errors were being classified as an unreachable source
      (now tagged only at upstream call sites).
    • Fixed: unmatched warnings counted each ID separately (now grouped by cause).
    • Fixed: a favorite's full runtime replaced the per-episode share of a multi-episode
      file.
    • Fixed: a short page could end a list early (now trusts TotalRecordCount).
    • Fixed: a duplicated message string (now a constant).
    • Accepted: v1 run responses still return other stored warnings verbatim, as
      before this change.
    • Accepted: a crafted provider ID can change which fixed summary is chosen. The
      output is always fixed text.
  • Bot review: Codex review on the PR found two issues, both fixed in a follow-up
    commit.
    • The shared mapping had changed frozen v1 statuses; v2 now carries those mappings.
    • Emby upstream error bodies could reach v1 run warnings; those warnings now store
      fixed text.

🤖 Generated with Claude Code

…lear errors

Emby list queries omit ProductionYear, UserData.PlayCount, and
UserData.LastPlayedDate unless Fields names them (verified on Emby 4.8.11,
4.9.5, and 4.10.0.40). Silo only asked for ProviderIds, so every Emby import
created no history rows, stamped progress at the Unix epoch, and could never
update progress on a re-import.

- Request the missing fields; page item lists and batch ID lookups.
- Import episode favorites; report season favorites, which Silo cannot hold.
- Mark every episode of a played multi-episode file watched.
- Keep importing when Emby show details cannot be read.
- Accept Emby accounts without a password.
- Report unreachable sources and invalid input with specific messages
  instead of a 500, and put the message in the v2 problem detail.
- Show safe per-cause summaries for run warnings and unmatched items, and
  count unmatched items by cause.
- Web: count skipped items once, ask for a new Emby Connect sign-in after a
  run consumes the session, and fix the Emby card copy.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

Next included review available in 46 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 2 included reviews currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: 450a4b68-d72f-48ea-8b48-3fe8ee1f60e3

📥 Commits

Reviewing files that changed from the base of the PR and between 52264a8 and 5d67ff1.

📒 Files selected for processing (24)
  • contracts/api/v2/fixtures/get_system_info_ok.json
  • contracts/api/v2/openapi.json
  • docs/admin-api.md
  • docs/architecture/history-import-execution.md
  • internal/api/handlers/history_import_test.go
  • internal/apiv2/history_imports.go
  • internal/apiv2/history_imports_test.go
  • internal/historyimport/emby_client.go
  • internal/historyimport/emby_favorites_test.go
  • internal/historyimport/emby_provider.go
  • internal/historyimport/emby_provider_test.go
  • internal/historyimport/errors.go
  • internal/historyimport/matcher.go
  • internal/historyimport/public_messages.go
  • internal/historyimport/public_messages_test.go
  • internal/historyimport/repo.go
  • internal/historyimport/service.go
  • internal/historyimport/service_personal_auth.go
  • internal/historyimport/service_personal_auth_test.go
  • web/src/api/v2/schema.ts
  • web/src/pages/settings/HistoryImportSettings.test.tsx
  • web/src/pages/settings/HistoryImportSettings.tsx
  • web/src/pages/settings/HistoryImportSettings.utils.ts
  • web/src/pages/settings/HistoryImportSettings.v2.test.tsx

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-23T01:48:17.999193Z eac76b5 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 035b95cab4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/api/handlers/history_import.go Outdated
Comment on lines +312 to +316
case errors.Is(err, historyimport.ErrSourceUnreachable):
slog.Warn("history import: source unreachable", "error", err)
return HistoryImportUnreachableAPIError()
case errors.Is(err, historyimport.ErrInvalidInput):
return &APIError{Status: http.StatusBadRequest, Code: policyErrorBadRequest, Message: historyImportInputMessage(err), cause: err}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve the frozen v1 error responses

These cases run in the shared handler used by /api/v1: an unreachable source now changes from the previous 500/internal_error response to 502/bad_gateway, while ErrInvalidInput now changes previously unrecognized failures from 500 to 400 with new detail text. Clients can branch on these statuses and codes, but the repository requires the v1 bridge contract to remain unchanged; apply the richer mapping in the v2 adapter while retaining the existing v1 decision.

AGENTS.md reference: AGENTS.md:L206-L218

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in eac76b5. The shared mapping is back to the main decisions, so v1 still answers 500 for these. The v2 adapter now maps ErrSourceUnreachable (503) and ErrInvalidInput (422 with its detail) from the cause the seam's APIError wraps. A handler test pins the v1 decision.

Comment thread internal/historyimport/emby_provider.go Outdated
if err != nil {
return nil, nil, err
// Episodes carrying their own provider IDs still match without it.
warnings = append(warnings, warnEmbySeriesUnavailable+err.Error())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid persisting the Emby response body in series warnings

When the Ids series-metadata request returns a non-2xx response, embyHTTPError.Error() includes up to 2 KiB of the upstream body, and this line persists that entire string as a run warning. The v2 projection sanitizes it, but the v1 list/get-run handlers serialize historyimport.Run directly, so an Emby HTML error or stack response is exposed to the importing account; this path previously failed the run with a fixed user-facing message. Persist a stable diagnostic token and log the underlying error separately.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in eac76b5. The favorites and series-metadata warnings now store fixed text, and the upstream error is logged instead. Stored rows in the old favorites format still map to the same v2 summary.

The shared handler mapping also answers /api/v1, which is frozen. Restore its
decisions and map unreachable sources and invalid input in the v2 adapter,
which reads the cause the seam's APIError wraps.

Emby favorites and series-metadata warnings now store fixed text and log the
upstream error, since v1 returns stored warnings verbatim and Emby error
bodies can reach them.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: eac76b5f0b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

// Reasons name the item's IDs; count by cause so one warning
// covers every item that failed the same way. Samples and logs
// keep the full reason.
summary.UnmatchedReasonCounts[PublicUnmatchedReason(reason)]++

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve v1 unmatched warning semantics

When a v1 import has unmatched items, classifying each reason before persistence changes the shared run data that HandleListRuns and HandleGetRun serialize directly. For example, two missing movies with different provider IDs previously produced two diagnostic warning entries, but now collapse into one fixed-summary count; this affects Plex and Jellyfin runs as well as Emby. Keep the original reasons for the frozen v1 projection and perform classification/aggregation only for v2.

AGENTS.md reference: AGENTS.md:L206-L218

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping this as is. The v1 freeze covers the contract: routes, fields, types, and status and error codes. Warnings are free-text diagnostics whose content changes with any import fix; this PR changes the fetched, matched, and history counts in the same response. Grouping has to happen when the run is stored: runs keep at most 20 warnings, so keying by per-ID reason fills that cap with "(1)" entries and undercounts, and grouping at read time would inherit the undercount. The full per-item reasons remain in unmatched_samples and the server log.

Resolve the v2 contract digest conflict by regenerating the OpenAPI
document, fixtures, and web types from the merged router.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@Quick104 Quick104 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review summary

Reviewed head: 5d67ff1e0 (PR commits 035b95c and eac76b5, plus a merge from main)

No blocking defects found. I made two changes:

  • Merge conflict: contracts/api/v2/fixtures/get_system_info_ok.json conflicted with main on the contract digest. I merged main and regenerated the OpenAPI document, fixtures, and web types from the merged router (5d67ff1e0). verify-apiv2-openapi, verify-apiv2-contract, verify-apiv2-fixtures, and verify-apiv2-web-types pass.
  • PR body: added the Validation tasks: line that AGENTS.md now requires.

What I checked

  • v1 error decisions: historyImportAPIError has no case for ErrSourceUnreachable or ErrInvalidInput, so both still fall through to the 500 internal_error default. Only the v2 adapter maps them, by unwrapping the seam's APIError. This addresses the first Codex thread.
  • Emby warnings: favorites and series-metadata failures store fixed text and log the upstream error, so v1 no longer exposes Emby response bodies. This addresses the second Codex thread.
  • Paging stops on an empty page or once TotalRecordCount is reached, so a server that ignores StartIndex or Limit still ends the loop. The Jellyfin client already pages the same way. ID lookups go in chunks of 100.
  • Multi-episode expansion only applies to played episodes with a range of 2–10. mergeRecords keeps the watched record's per-episode runtime because the favorite copy's duration is zeroed. Favorite-only records still skip the watch pipeline (service.go, FavoriteOnly).
  • Episode favorites land in the same user_favorites store that v2 PUT /favorites/{item_id} writes for any catalog item, so they are not a new kind of data.
  • processed = matched + unmatched is correct: Skipped is counted only after a match.

Open thread: Codex's third comment, on v1 unmatched warning text, is still open. I agree with the author's reply. The v1 field keeps its type and meaning, and grouping has to happen before the 20-warning cap is applied. I'm leaving the thread for the participants to settle.

Validated features: no passed case is affected. Every Watch-history import task (#1240–#1244) is still "Not run". This PR changes the behavior #1242 C1–C3 and #1243 C2 will test.

Validation: on the merged tree, go build ./internal/..., go vet, internal/historyimport and internal/api/handlers tests, and the HistoryImportSettings web tests pass. internal/apiv2 fails only TestAdminResourceCapabilitiesAndScope, which fails the same way on main on macOS. golangci-lint was not available locally, so CI covers lint.

CI on 5d67ff1e0: Go lint, Go test, Go contract checks, Web, and both Web test shards pass. GitHub reports the PR as mergeable.

Mergeability: 9/10 — ready (head 5d67ff1e0). The Emby fixes target a real, reproducible data gap and stay inside historyimport. The frozen v1 decisions still hold, and only the v2 adapter maps the new errors. Tests exercise the upstream behavior the fix depends on (the fake Emby server omits fields unless asked). What remains: the open Codex thread on v1 warning text, and maintainer review of this AI-generated change. Emby Connect was not tested live, but its requests are unchanged.

Review by Claude Code (claude-opus-5-5), run inside T3 Code.

@Quick104
Quick104 merged commit 4259918 into main Sep 23, 2026
10 checks passed
@Quick104
Quick104 deleted the t3code/audit-emby-history-import branch September 23, 2026 16:03
Quick104 added a commit that referenced this pull request Sep 23, 2026
Run warnings now hold fixed diagnostics that PublicWarning maps to
monitor text (#1329), because v1 returns them verbatim and upstream
errors can carry response bodies. Log the Jellyfin favorites and
favorite-series lookup errors and store fixed warnings with their own
public summaries, as Emby does.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Quick104 added a commit that referenced this pull request Sep 23, 2026
…#1331)

* fix(historyimport): import Jellyfin favorites and support Jellyfin 12

Jellyfin imports skipped favorites, and several requests misbehaved
against Jellyfin 12:

- A rejected password was retried under the /emby prefix, which
  Jellyfin 12 removed, so a credentials error surfaced as a 404. On
  10.11 the retry counted as a second failed login.
- Items came from /Users/{userId}/Items, which Jellyfin 12.1 no longer
  lists in its OpenAPI document.
- A source address ending in "/" produced //Items requests that 404.
- Items without a LastPlayedDate were stamped with the import time, so a
  re-import could overwrite newer Silo progress.

Fetch IsFavorite movies, series, and episodes as favorite-only records
and keep the IsFavorite flag on watched items. Sign in once at the
entered address, read items through /Items?UserId=, trim trailing
slashes, leave UpdatedAt zero without a last-played date, and request
only ProviderIds.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(historyimport): keep favorite series lookup failures non-fatal

A favorite episode added its series ID to the series lookup that the
watch history depends on, so a failed lookup discarded the whole run
even though favorites are otherwise best-effort. Look up series needed
only by favorites separately and report a failure as a run warning.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(historyimport): store fixed text for Jellyfin favorite warnings

Run warnings now hold fixed diagnostics that PublicWarning maps to
monitor text (#1329), because v1 returns them verbatim and upstream
errors can carry response bodies. Log the Jellyfin favorites and
favorite-series lookup errors and store fixed warnings with their own
public summaries, as Emby does.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(historyimport): say Jellyfin favorites may be incomplete after a failed query

Watched items that Jellyfin marks as favorites still import as
favorites when the favorites query fails, so the run summary must not
claim none were imported.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant