Repository navigation
[codex] Add IntroDB marker integration and dialogue-aware Chromaprint refinement - #57
Conversation
… & TheIntroDB contribution
…, best candidate) Honor TVDB ids in /media lookups (previously dropped — anime/TheTVDB-first libraries got no markers), decode and use the real per-segment confidence and submission_count instead of a hardcoded 0.9, and pick the most-submitted / highest-confidence candidate when several are returned. Adds httptest coverage for the introdb client and provider. Phase 1 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…t provenance Add marker_provider_config (per-provider fetch enable/priority + contribute gates, contribution off by default) and a cached ProviderConfigStore. Add Registry.FetchMerged: query all fetch-enabled providers concurrently and keep the best candidate per segment (submission_count, then confidence, then fetch priority), stamping each winning marker with its provider/algorithm. Thread per-segment provenance through MarkerUpdatePayload and scanner.MarkerUpdate (additive SegmentProvenance overrides) so a merged result writes correct per-segment provider/confidence/algorithm; the legacy shared columns keep a summary. The lazy-playback path now uses FetchMerged. With only TheIntroDB enabled, behavior is unchanged. Phase 2 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ice engine Add a markers.Submitter capability and implement it on the introdb provider (POST /v3/submit, GET /v3/user/stats; key required, usage-limit aware, applies the null start/end conventions). Add the marker_contributions audit table and a value-hash-keyed ContributionStore for idempotency. Add ContributionService: resolves enabled submitter providers, gates eligibility (never re-submit online-sourced markers; auto runs require contribute_auto_local + scanner-intro above the per-provider confidence threshold), checks idempotency, submits, and records. Wired in main.go; no trigger yet (admin API and task follow). Phase 3 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…dpoints
Add the RequireAdmin marker API: GET/PUT /admin/files/{id}/markers (read with
provenance; manual upsert where a segment object sets and null clears),
DELETE .../markers/{segment}, POST .../contribute and GET .../contributions,
plus GET/PUT /admin/markers/providers[/{provider}] and a
.../validate key-check returning user stats. Manual writes go through the
priority-gated UpsertMarkers (source=manual) and notify live sessions; a new
FileRepository.ClearMarkers nulls a segment's columns. Validation mirrors the
contribution rules.
Phase 4 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add ContributeMarkersTask (daily 04:00, after local detection): when a provider has contribute_enabled + contribute_auto_local, page through episode files with a scanner intro marker at/above the provider's confidence threshold (new ContributionStore.CandidateLocalIntroFiles keyset query) and run them through ContributionService with Auto=true. No-op when no provider opts in; idempotent and resumable across runs. Phase 5 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds provider-configured merged marker fetch, plugin-backed providers, per-segment provenance and write-path, contribution service/store/admin APIs and background task, chromaprint dialogue refinement with subtitle parsing, router/main wiring, migrations, and web UI/editor/player changes. ChangesMarkers platform end-to-end
Estimated code review effort Possibly related PRs
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
|
|
To use Codex here, create an environment for this repo. |
|
✅ Action performedReview finished.
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 399de77b50
ℹ️ 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".
| // Re-validate the resolved primary file through the authorizer so item-id | ||
| // edits are access-checked the same way file-id edits are. | ||
| if h.Authorizer != nil { | ||
| return h.authorizeFile(w, r, files[0].ID) |
There was a problem hiding this comment.
Choose an accessible file for item marker edits
When a visible movie/episode has multiple file versions and the first media_files row is outside the current viewer scope (for example due to a profile quality ceiling or disabled library), the new /markers/items/{id} path authorizes only files[0] and returns 404 even though another version of the same item is accessible. This breaks the detail-page marker editor for otherwise playable items; iterate the resolved files and use the first one that authorizes (or filter before selecting) instead of failing on the inaccessible first row.
Useful? React with 👍 / 👎.
| return &models.MediaFile{ID: fileID} | ||
| } | ||
| if h.Notifier != nil { | ||
| h.Notifier.MarkersUpdated(ctx, refreshed) |
There was a problem hiding this comment.
Notify players when the last marker is cleared
When this path clears the final remaining marker for a file, MarkersUpdated currently drops the update because all four ranges are nil, so other active playback sessions keep showing stale skip regions until they reload. The realtime protocol and client already accept null ranges, so the manual clear path needs to emit an update even for the all-cleared state.
Useful? React with 👍 / 👎.
| // correction hashes differently (submitted as a new value). | ||
| func ContentHash(segmentKind string, startMs, endMs, durationMs *int64) string { | ||
| h := sha256.New() | ||
| fmt.Fprintf(h, "%s|%s|%s|%s", segmentKind, ptrIntStr(startMs), ptrIntStr(endMs), ptrIntStr(durationMs)) |
There was a problem hiding this comment.
Include the target identity in contribution idempotency
Because the idempotency hash excludes the external IDs being submitted to, a file that was previously contributed while matched to the wrong TMDB item will be treated as already submitted after it is rematched if the marker bounds are unchanged. In that rematch scenario AlreadySubmitted skips the corrected contribution for the new target content; include the resolved provider identity (at least TMDB/season/episode or movie kind) in the hash/key or stored row used for de-duplication.
Useful? React with 👍 / 👎.
| ); err != nil { | ||
| return fmt.Errorf("update marker provider config: %w", err) | ||
| } | ||
| return s.Reload(ctx) |
There was a problem hiding this comment.
Propagate provider config changes to other nodes
In a multi-instance deployment this update only refreshes the in-process cache on the node that handled the admin request; other API/worker nodes keep their old fetch/contribute flags until restart. That means disabling contribution or online fetch can still leave requests/tasks on another node using the stale enabled config, so this needs the same kind of cross-node invalidation/reload path used for settings or a non-stale read strategy.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Actionable comments posted: 15
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/scanner/file_repo.go (1)
1167-1168:⚠️ Potential issue | 🟠 Major | ⚡ Quick winRecompute shared marker attribution from the post-patch segment state.
This still uses the legacy
update-level summary, so adding a lower-confidence segment can downgrademarkers_confidenceeven when a higher-confidence segment of the same source remains on the row. That leaves the shared metadata wrong and can weaken later same-source overwrite gating for segments that still fall back to the legacy fields.Suggested fix
- anyApplied := introApplied || creditsApplied || recapApplied || previewApplied - nextSource, nextConfidence := nextSharedMarkerAttribution(existingSource, existingConfidence, update, anyApplied) + anyApplied := introApplied || creditsApplied || recapApplied || previewApplied + nextSource, nextConfidence := existingSource, existingConfidence + if anyApplied { + nextSource, nextConfidence = recomputeSharedMarkerAttribution( + existingSource, + existingConfidence, + intro, + credits, + recap, + preview, + ) + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/scanner/file_repo.go` around lines 1167 - 1168, The shared marker attribution call uses the legacy `update` summary and can be downgraded by a low-confidence segment; change `nextSharedMarkerAttribution(existingSource, existingConfidence, update, anyApplied)` to recompute the source-level state from the post-patch segments instead of the `update` object: derive the effective source and highest confidence for that source by scanning the row's segments after applying the patch (e.g. compute max confidence and presence for the same `existingSource` across remaining segments or use the segment-level metadata instead of `update`), then pass those recomputed values into `nextSharedMarkerAttribution` (keep `anyApplied` logic intact).
🧹 Nitpick comments (6)
internal/markers/contribute.go (1)
189-191: 💤 Low valueConsider adding a comment explaining the TMDB requirement.
The code enforces TMDB ID presence (line 189), but the reason isn't immediately clear to future maintainers. A brief comment would help:
// IntroDB and other providers require TMDB as the canonical external ID. if strings.TrimSpace(ids.TmdbID) == "" { return ContributionOutcome{...}, true }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/markers/contribute.go` around lines 189 - 191, Add a brief clarifying comment above the TMDB check (the if using ids.TmdbID) explaining why TMDB is required (e.g., "IntroDB and other providers treat TMDB as the canonical external ID used for matching/contributions"), then keep the existing early return (returning ContributionOutcome with Provider: providerID, Segment: seg.kind, Status: OutcomeStatusSkipped, Reason: "tmdb id required"); place the comment immediately above the ids.TmdbID check so future maintainers understand the constraint without changing logic.internal/markers/introdb/submit_test.go (1)
55-56: Clarify zero-start normalization in IntroDB JSONThe expectation that
Start: ptrDur(0)results ingotBody.StartMs == nilis aligned with IntroDB behavior:nulland0start times are treated equivalently (both mean “start at the beginning”), so this shouldn’t be misinterpreted as anything else. Add a short comment in the test to document this normalization intent for future readers.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/markers/introdb/submit_test.go` around lines 55 - 56, Add a brief inline comment in the test near the assertion that checks gotBody.StartMs (the block that expects gotBody.StartMs == nil when Start: ptrDur(0) is used) explaining that IntroDB normalizes zero start times to null (i.e., Start: ptrDur(0) and explicit null are treated equivalently as "start at the beginning"), so the test intentionally expects nil; place the comment next to the assertion referencing gotBody.StartMs and the test input Start: ptrDur(0).internal/markers/introdb/client_test.go (1)
20-21: ⚡ Quick winClose the test clients.
NewClient()starts the cache sweeper goroutine. These tests never callClose(), so the goroutines live until process exit and can start tripping leak detectors as the suite grows. Adddefer c.Close()after each client is created.Also applies to: 44-45, 65-66, 83-84
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/markers/introdb/client_test.go` around lines 20 - 21, Tests create clients with NewClient("") which spawn a cache sweeper goroutine but never call Close(), leaking goroutines; after each client creation (calls to NewClient("") assigned to variable c in client_test.go, e.g. the instances at the locations corresponding to the code around NewClient("") / c.SetBaseURL(...)) add a defer c.Close() immediately after creating and configuring the client to ensure its goroutine is stopped; apply this change to the four occurrences mentioned so each test defers c.Close().internal/markers/types_test.go (1)
87-146: ⚡ Quick winAdd tie-break coverage for confidence and configured fetch priority.
These tests only exercise the submission-count branch. Regressions in the other two ranking rules would still pass, especially the provider-priority path that depends on
UseConfigStore.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/markers/types_test.go` around lines 87 - 146, Tests only cover submission-count tie-break; add cases exercising the other ranking rules by creating providers (fakeProvider with Result/Markers) that tie on SubmissionCount but differ in Confidence and by configured fetch priority, then call Registry.FetchMerged and assert the chosen Marker comes from the provider with higher Confidence and, separately, from the higher-priority provider when UseConfigStore is enabled. Concretely, extend or add tests alongside TestRegistryFetchMergedKeepsBestPerSegment that: (1) create two providers with equal SubmissionCount but Confidence 0.9 vs 0.7 and verify MarkerKindIntro picks the 0.9 provider; and (2) create two providers with equal Confidence and SubmissionCount, enable the config-based priority path (UseConfigStore/NewRegistry configured to use a config store) and set provider fetch priorities so FetchMerged picks the configured higher-priority provider; assert provider IDs on the merged result accordingly. Ensure the tests reference fakeProvider, Result, MarkerKindIntro/MarkerKindCredits, NewRegistry, UseConfigStore (or the registry constructor flag), Request and ItemKindEpisode so they exercise the intended tie-break branches.web/src/components/markers/MarkerEditor.tsx (1)
135-179: ⚡ Quick winWrap inputs in a
<form>element for better keyboard accessibility.The input fields are not wrapped in a
<form>element, so pressing Enter in a text field won't trigger submission. Adding a form withonSubmit={handleSave}would improve accessibility (screen reader announcements, keyboard navigation) and user experience (Enter key submit).♻️ Suggested refactor
return ( - <> + <form onSubmit={(e) => { e.preventDefault(); handleSave(); }}> <div className="grid gap-3 py-1"> {MARKER_KINDS.map((kind) => ( <div key={kind} className="grid grid-cols-[5.5rem_1fr_1fr_auto] items-center gap-2"> <span className="text-sm font-medium">{MARKER_LABELS[kind]}</span> <Input aria-label={`${MARKER_LABELS[kind]} start`} placeholder="start" value={fields[kind].start} onChange={(e) => setField(kind, "start", e.target.value)} /> <Input aria-label={`${MARKER_LABELS[kind]} end`} placeholder="end" value={fields[kind].end} onChange={(e) => setField(kind, "end", e.target.value)} /> <Button type="button" variant="ghost" size="icon" aria-label={`Clear ${MARKER_LABELS[kind]}`} onClick={() => clearKind(kind)} > <Trash2 className="size-4" /> </Button> </div> ))} </div> {error && <p className="text-destructive text-sm">{error}</p>} <DialogFooter> <Button variant="outline" onClick={onClose}> Cancel </Button> - <Button onClick={handleSave} disabled={setMarkers.isPending}> + <Button type="submit" disabled={setMarkers.isPending}> {setMarkers.isPending && <Loader2 className="size-4 animate-spin" />} Save </Button> </DialogFooter> - </> + </form> );🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/components/markers/MarkerEditor.tsx` around lines 135 - 179, The inputs in MarkerEditor are not wrapped in a form so Enter won't submit; wrap the area containing MARKER_KINDS inputs and the error message inside a <form> with onSubmit={handleSave} and ensure the Save button remains type="submit" (or remove its onClick) while keeping Cancel (onClose) as type="button"; also prevent duplicate action by keeping handleSave idempotent or returning false on invalid data and ensure setMarkers.isPending still disables the submit and renders the Loader2 as before.migrations/182_marker_contributions.up.sql (1)
4-21: ⚡ Quick winConsider adding CHECK constraints for enumerated text fields.
The
provider,segment_kind,source, andstatuscolumns are documented as having specific allowed values (e.g.,statusispending | accepted | rejected | error), but the schema uses unconstrainedTEXT. AddingCHECKconstraints would prevent invalid values from being inserted if application-layer validation is bypassed or has bugs.🛡️ Proposed constraints
CREATE TABLE public.marker_contributions ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), media_file_id integer NOT NULL REFERENCES media_files(id) ON DELETE CASCADE, provider text NOT NULL, - segment_kind text NOT NULL, -- intro | recap | credits | preview - source text NOT NULL, -- what we contributed: scanner | manual + segment_kind text NOT NULL CHECK (segment_kind IN ('intro', 'recap', 'credits', 'preview')), + source text NOT NULL CHECK (source IN ('scanner', 'manual')), submitted_start_ms bigint, submitted_end_ms bigint, video_duration_ms bigint, content_hash text NOT NULL, -- hash(segment_kind, start_ms, end_ms, duration_ms) submission_id text, -- id returned by the provider - status text NOT NULL, -- pending | accepted | rejected | error + status text NOT NULL CHECK (status IN ('pending', 'accepted', 'rejected', 'error')), http_status integer,🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@migrations/182_marker_contributions.up.sql` around lines 4 - 21, Add CHECK constraints to the marker_contributions table to enforce allowed values for the enumerated text columns: add checks on provider (allowed provider values), segment_kind (intro, recap, credits, preview), source (scanner, manual), and status (pending, accepted, rejected, error); implement these either by updating the CREATE TABLE to include column-level CHECK clauses or by issuing ALTER TABLE ... ADD CONSTRAINT statements with explicit constraint names (e.g., marker_contributions_segment_kind_check, marker_contributions_status_check) and ensure the constraints and names reference the existing columns media_file_id, provider, segment_kind, source, status so the migration fails fast on invalid inserts.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@docs/superpowers/plans/2026-06-06-marker-introdb-readpath-correctness.md`:
- Line 618: Remove the dangling untyped fenced code block marker ``` at the end
of the file: either delete the trailing backticks or convert them to a properly
typed/closed fenced block (e.g., ```md or ```text plus matching closing fence)
so the file no longer ends with an open/untyped ``` that triggers MD040 and
breaks rendering.
In
`@docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md`:
- Line 75: The Task headings like "### Task 1.1 — Type plumbing" are jumping a
level and violating markdownlint MD001; update these to use a single-level
increment (e.g., change "### Task 1.1 — Type plumbing" to "## Task 1.1 — Type
plumbing") or alternatively demote the surrounding phase headers so the relative
depth is consistent; apply the same fix to the other occurrences mentioned (the
headings at the other noted locations) so all task headings follow the same
h2/h3 scheme.
- Line 483: There is an unterminated/empty fenced code block (a bare "```" at
the end of the file) causing MD040; either remove that trailing "```" entirely
or replace it with a properly typed/closed fenced block by adding a language
identifier (e.g., "```text" or "```json") and a matching closing fence so the
block is valid.
In `@internal/api/handlers/markers.go`:
- Around line 406-414: reloadAndNotify currently fabricates an empty
models.MediaFile on reload failure which leads callers to treat the operation as
successful; change reloadAndNotify to return (nil, error) by propagating the
error from h.Files.GetByID (or a wrapped error if refreshed==nil), update its
signature from func (h *MarkersHandler) reloadAndNotify(ctx context.Context,
fileID int) *models.MediaFile to return (*models.MediaFile, error), and ensure
callers that invoked reloadAndNotify handle the error path and avoid calling
h.Notifier.MarkersUpdated or returning 200 on failure; reference
functions/fields: reloadAndNotify, h.Files.GetByID, h.Notifier.MarkersUpdated,
and models.MediaFile.
- Around line 305-318: The handler currently calls h.Writer.UpsertMarkers and
h.Writer.ClearMarkers separately so a failure in ClearMarkers can leave a
partial successful UpsertMarkers and still return 500; make the mutation atomic
by adding and using a single combined operation on the writer (e.g., add a
method like UpsertAndClearMarkers(ctx, fileID, upsertUpdate, clearSegments) or
WrapMarkersInTx that performs both UpsertMarkers and ClearMarkers in one DB
transaction) and replace the two independent calls in the markers handler with
one call to that new atomic method (referencing UpsertMarkers, ClearMarkers, and
h.Writer to locate where to implement the combined operation).
- Around line 363-368: In HandleContributeFile in markers.go, stop gating JSON
decoding on r.ContentLength; always attempt
json.NewDecoder(r.Body).Decode(&body) and treat io.EOF as the only “no body”
case (leave body at zero values), but return a BadRequest on any other decode
error; this prevents skipping decoding for chunked/unknown-length requests and
avoids mistakenly interpreting nil/empty opts.Segments as “all segments.” Ensure
you reference the variables body, opts.Segments and the function
markers.ContributeFile when making the change.
In `@internal/intromarkers/repository.go`:
- Around line 596-621: The current logic compares patch.Confidence vs
*row.IntroMarkersConfidence before considering scannerAlgorithmPriority, causing
high-confidence low-priority markers to block higher-priority algorithms; change
the ordering to compute existingAlgorithm (from row.IntroMarkersAlgorithm), call
scannerAlgorithmPriority for patch.Algorithm and existingAlgorithm first and
compare patchPriority vs existingPriority, returning when priorities differ,
then if priorities are equal compare confidences (and finally handle the special
case when patchPriority == 0 and algorithms differ, and the introRangeDiffers
check). Ensure the same reordered logic is applied in the duplicate block around
lines 627-642 that mirrors this logic.
In `@internal/markers/introdb/client.go`:
- Around line 280-286: When handling HTTP 429 in submitSegment(), don't return a
RetryAfterError with RetryAfter == 0 when usageResetSeconds(resp) yields 0;
instead apply the same positive fallback used in fetch() so callers back off.
Update the block that builds &markers.RetryAfterError (in submitSegment) to
compute after := time.Duration(usageResetSeconds(resp)) * time.Second and if
after == 0 set after = the same non-zero fallback value used by fetch(); then
pass that adjusted after into RetryAfter and the log/message (keeping ProviderID
and Message formatting intact). Ensure the same change is also applied to the
analogous 429 handling at the other site (lines ~343-352) so both paths use the
positive fallback.
In `@internal/markers/introdb/provider.go`:
- Around line 184-202: The current logic in provider.go that normalizes
req.Start/req.End (used when building body.StartMs/body.EndMs) silently converts
out-of-range values like start < 0 or end > req.Duration into boundary
submissions; instead, update the validation to only canonicalize exact
boundaries (treat start == 0 as nil for "beginning" and end == req.Duration as
nil for "to EOF") and otherwise return a validation error (fail fast) when start
< 0 or end > req.Duration or when start > end; specifically, in the block
handling req.Segment (and before assigning body.StartMs/body.EndMs), add
explicit checks on req.Start and req.End for negativity/overshoot and reject
invalid ranges rather than setting them to nil, preserving the conversion to
milliseconds only for valid, non-boundary values.
In `@web/src/hooks/queries/admin/markers.ts`:
- Around line 34-41: The onSuccess handler for the provider-save mutation fails
to evict the cached validation entry, so markerProviderValidation(...) can
remain stale; update the onSuccess in the mutation (the async handler that
currently calls queryClient.invalidateQueries for adminKeys.markerProviders()
and adminKeys.markerProvider(variables.provider)) to also call
queryClient.invalidateQueries for
adminKeys.markerProviderValidation(variables.provider) (or the correct
markerProviderValidation key shape) as part of the Promise.all so the validation
cache is invalidated whenever provider settings change.
In `@web/src/player/components/MarkerEditPanel.tsx`:
- Around line 34-66: The handleDragStart adds document-level listeners
(onMove/onUp) but doesn't guarantee they are removed if the component unmounts
during a drag; update the component to track the active listeners (e.g., store
onMove and onUp in refs or a single "isDragging" ref) and add a useEffect
cleanup that removes document.removeEventListener("pointermove", onMove) and
document.removeEventListener("pointerup", onUp) on unmount; ensure you still
remove them in the existing onUp handler and reference the same handler
instances (from refs) so removal succeeds; relevant symbols: handleDragStart,
onMove, onUp, panelRef, setOffset.
In `@web/src/player/components/PlayerControls.tsx`:
- Around line 346-356: The marker-edit button currently only updates data-active
but isn't exposed as a toggled control to assistive tech; update the button
rendered when markerEditAvailable && onToggleMarkerEdit to include
aria-pressed={markerEditActive} (use the boolean markerEditActive, not a string)
alongside the existing attributes so screen readers can announce its on/off
state (refer to the button that uses markerEditActive, onToggleMarkerEdit and
Tags in PlayerControls).
In `@web/src/player/components/SeekBar.tsx`:
- Around line 418-440: MarkerHandle currently exposes slider semantics but lacks
focus/keyboard support; remove the misleading interactive attributes instead of
faking a slider. In the MarkerHandle component remove role="slider",
aria-valuenow and tabIndex={-1} (and any other slider-specific ARIA attributes)
so it is not announced as a slider; keep aria-label or convert it to a
non-interactive attribute (or use aria-hidden if purely decorative). This change
touches the MarkerHandle function and its root div element.
In `@web/src/player/hooks/useMarkerEditor.ts`:
- Around line 155-182: The save() function currently calls onSaved?.(draft)
inside the try block so any exception from the callback or timing of parent
refresh can be treated as a failed save and leave originalRef stale; instead,
after the playerFetch resolves but before invoking any external callbacks,
update the local baseline by committing the draft into originalRef.current (and
clear editing state via setEditing(false)), then call onSaved?.(draft) outside
the request-failure path and guard it with its own try/catch so callback errors
do not flip setError or setSaving; keep playerFetch, draft, originalRef,
onSaved, setEditing, setSaving, and setError as the referenced symbols to locate
where to apply the change.
- Around line 107-123: The setEdge callback can produce starts/ends outside [0,
duration] after enforcing MIN_GAP (e.g., when duration < MIN_GAP); update
setEdge (used with setDraft and PlayerTimeRange) to re-clamp the computed
next.start and next.end to the valid range after applying the MIN_GAP adjustment
(or early-return/short-circuit when duration <= MIN_GAP) so final values are
always bounded by 0 and duration; ensure you reference MIN_GAP, NEW_MARKER_SPAN
and duration when computing the corrected clamped range.
---
Outside diff comments:
In `@internal/scanner/file_repo.go`:
- Around line 1167-1168: The shared marker attribution call uses the legacy
`update` summary and can be downgraded by a low-confidence segment; change
`nextSharedMarkerAttribution(existingSource, existingConfidence, update,
anyApplied)` to recompute the source-level state from the post-patch segments
instead of the `update` object: derive the effective source and highest
confidence for that source by scanning the row's segments after applying the
patch (e.g. compute max confidence and presence for the same `existingSource`
across remaining segments or use the segment-level metadata instead of
`update`), then pass those recomputed values into `nextSharedMarkerAttribution`
(keep `anyApplied` logic intact).
---
Nitpick comments:
In `@internal/markers/contribute.go`:
- Around line 189-191: Add a brief clarifying comment above the TMDB check (the
if using ids.TmdbID) explaining why TMDB is required (e.g., "IntroDB and other
providers treat TMDB as the canonical external ID used for
matching/contributions"), then keep the existing early return (returning
ContributionOutcome with Provider: providerID, Segment: seg.kind, Status:
OutcomeStatusSkipped, Reason: "tmdb id required"); place the comment immediately
above the ids.TmdbID check so future maintainers understand the constraint
without changing logic.
In `@internal/markers/introdb/client_test.go`:
- Around line 20-21: Tests create clients with NewClient("") which spawn a cache
sweeper goroutine but never call Close(), leaking goroutines; after each client
creation (calls to NewClient("") assigned to variable c in client_test.go, e.g.
the instances at the locations corresponding to the code around NewClient("") /
c.SetBaseURL(...)) add a defer c.Close() immediately after creating and
configuring the client to ensure its goroutine is stopped; apply this change to
the four occurrences mentioned so each test defers c.Close().
In `@internal/markers/introdb/submit_test.go`:
- Around line 55-56: Add a brief inline comment in the test near the assertion
that checks gotBody.StartMs (the block that expects gotBody.StartMs == nil when
Start: ptrDur(0) is used) explaining that IntroDB normalizes zero start times to
null (i.e., Start: ptrDur(0) and explicit null are treated equivalently as
"start at the beginning"), so the test intentionally expects nil; place the
comment next to the assertion referencing gotBody.StartMs and the test input
Start: ptrDur(0).
In `@internal/markers/types_test.go`:
- Around line 87-146: Tests only cover submission-count tie-break; add cases
exercising the other ranking rules by creating providers (fakeProvider with
Result/Markers) that tie on SubmissionCount but differ in Confidence and by
configured fetch priority, then call Registry.FetchMerged and assert the chosen
Marker comes from the provider with higher Confidence and, separately, from the
higher-priority provider when UseConfigStore is enabled. Concretely, extend or
add tests alongside TestRegistryFetchMergedKeepsBestPerSegment that: (1) create
two providers with equal SubmissionCount but Confidence 0.9 vs 0.7 and verify
MarkerKindIntro picks the 0.9 provider; and (2) create two providers with equal
Confidence and SubmissionCount, enable the config-based priority path
(UseConfigStore/NewRegistry configured to use a config store) and set provider
fetch priorities so FetchMerged picks the configured higher-priority provider;
assert provider IDs on the merged result accordingly. Ensure the tests reference
fakeProvider, Result, MarkerKindIntro/MarkerKindCredits, NewRegistry,
UseConfigStore (or the registry constructor flag), Request and ItemKindEpisode
so they exercise the intended tie-break branches.
In `@migrations/182_marker_contributions.up.sql`:
- Around line 4-21: Add CHECK constraints to the marker_contributions table to
enforce allowed values for the enumerated text columns: add checks on provider
(allowed provider values), segment_kind (intro, recap, credits, preview), source
(scanner, manual), and status (pending, accepted, rejected, error); implement
these either by updating the CREATE TABLE to include column-level CHECK clauses
or by issuing ALTER TABLE ... ADD CONSTRAINT statements with explicit constraint
names (e.g., marker_contributions_segment_kind_check,
marker_contributions_status_check) and ensure the constraints and names
reference the existing columns media_file_id, provider, segment_kind, source,
status so the migration fails fast on invalid inserts.
In `@web/src/components/markers/MarkerEditor.tsx`:
- Around line 135-179: The inputs in MarkerEditor are not wrapped in a form so
Enter won't submit; wrap the area containing MARKER_KINDS inputs and the error
message inside a <form> with onSubmit={handleSave} and ensure the Save button
remains type="submit" (or remove its onClick) while keeping Cancel (onClose) as
type="button"; also prevent duplicate action by keeping handleSave idempotent or
returning false on invalid data and ensure setMarkers.isPending still disables
the submit and renders the Loader2 as before.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 1017d515-404e-43eb-970d-77534cfa22b8
📒 Files selected for processing (64)
cmd/silo/main.godocs/superpowers/plans/2026-06-06-marker-introdb-readpath-correctness.mddocs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.mddocs/superpowers/specs/2026-06-06-marker-sources-and-contribution-design.mdinternal/api/handlers/admin_marker_providers.gointernal/api/handlers/admin_marker_providers_test.gointernal/api/handlers/markers.gointernal/api/handlers/markers_test.gointernal/api/handlers/playback_lazy_markers.gointernal/api/router.gointernal/intromarkers/analyzer.gointernal/intromarkers/analyzer_test.gointernal/intromarkers/dialogue.gointernal/intromarkers/dialogue_test.gointernal/intromarkers/repository.gointernal/intromarkers/repository_test.gointernal/intromarkers/types.gointernal/markers/contribute.gointernal/markers/contribute_test.gointernal/markers/contribution_repo.gointernal/markers/introdb/client.gointernal/markers/introdb/client_test.gointernal/markers/introdb/provider.gointernal/markers/introdb/provider_test.gointernal/markers/introdb/submit_test.gointernal/markers/introdb/types.gointernal/markers/provider_config.gointernal/markers/provider_config_test.gointernal/markers/types.gointernal/markers/types_test.gointernal/markers/write.gointernal/markers/write_test.gointernal/scanner/file_repo.gointernal/scanner/file_repo_test.gointernal/scanner/types.gointernal/subtitles/ai/engine.gointernal/subtitles/ai/srt.gointernal/subtitles/cues.gointernal/taskmanager/tasks/contribute_markers.gointernal/taskmanager/tasks/contribute_markers_test.gomigrations/181_marker_provider_config.down.sqlmigrations/181_marker_provider_config.up.sqlmigrations/182_marker_contributions.down.sqlmigrations/182_marker_contributions.up.sqlweb/src/api/types.tsweb/src/components/markers/MarkerEditor.tsxweb/src/hooks/queries/admin/markers.tsweb/src/hooks/queries/keys.tsweb/src/hooks/queries/markers.tsweb/src/lib/markers.tsweb/src/pages/ItemDetail/EpisodeContent.tsxweb/src/pages/ItemDetail/MovieContent.tsxweb/src/pages/ItemDetail/components/ActionBar.tsxweb/src/pages/admin-settings/AdminSettingsLayout.tsxweb/src/pages/admin-settings/IntegrationsSettings.tsxweb/src/pages/admin-settings/IntroSettings.tsxweb/src/pages/admin-settings/ScannerSettings.tsxweb/src/player/components/MarkerEditPanel.tsxweb/src/player/components/PlayerControls.tsxweb/src/player/components/SeekBar.tsxweb/src/player/components/VideoPlayer.tsxweb/src/player/components/WatchPage.tsxweb/src/player/hooks/useMarkerEditor.tsweb/src/player/types.ts
💤 Files with no reviewable changes (2)
- web/src/pages/admin-settings/IntegrationsSettings.tsx
- web/src/pages/admin-settings/ScannerSettings.tsx
| `internal/markers/types.go` (modify, add `Marker.SubmissionCount`), | ||
| `internal/markers/introdb/{client_test.go,provider_test.go}` (create). | ||
|
|
||
| ### Task 1.1 — Type plumbing |
There was a problem hiding this comment.
Fix heading depth progression to satisfy markdownlint MD001.
These task headings jump levels (expected h2, found h3). Use a single-level increment strategy (e.g., make these ##, or demote phase headers and keep these as ###) so lint passes consistently.
Also applies to: 124-124, 251-251, 365-365, 411-411
🧰 Tools
🪛 markdownlint-cli2 (0.22.1)
[warning] 75-75: Heading levels should only increment by one level at a time
Expected: h2; Actual: h3
(MD001, heading-increment)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md`
at line 75, The Task headings like "### Task 1.1 — Type plumbing" are jumping a
level and violating markdownlint MD001; update these to use a single-level
increment (e.g., change "### Task 1.1 — Type plumbing" to "## Task 1.1 — Type
plumbing") or alternatively demote the surrounding phase headers so the relative
depth is consistent; apply the same fix to the other occurrences mentioned (the
headings at the other noted locations) so all task headings follow the same
h2/h3 scheme.
Source: Linters/SAST tools
There was a problem hiding this comment.
Actionable comments posted: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
internal/markers/types.go (1)
369-375:⚠️ Potential issue | 🟠 Major | ⚡ Quick win
FetchMergeddrops single-provider result metadata.This path always returns a fresh
Result{SourceClass: ...}without restoring top-levelProviderIDorAlgorithm. With one enabled provider, that no longer matchesFetchFirstHit, despite the documented contract on Lines 317-319. Any caller still readingResult.ProviderID,Result.Algorithm, or the originalSourceClasswill regress even though the per-marker fields are stamped correctly.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/markers/types.go` around lines 369 - 375, FetchMerged currently constructs a fresh Result (merged := Result{SourceClass: models.MarkerSourceOnline}) and returns that, which drops top-level metadata such as ProviderID and Algorithm and can misrepresent SourceClass; instead, preserve the original result metadata when merging. Locate FetchMerged and the merged variable, and copy ProviderID, Algorithm and the original SourceClass from the input Result (or from the single-provider winner in best[kind]) into merged before returning (or initialize merged by cloning the original Result and then replace/append Markers), ensuring per-marker fields remain stamped but top-level ProviderID, Algorithm and SourceClass are retained.internal/api/handlers/admin_marker_providers_test.go (1)
46-48:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winParse the response JSON instead of matching raw fragments.
This assertion is brittle against harmless encoder changes like float rendering or spacing, and it does not verify the field in its actual object location. Unmarshal the body and assert the
acceptance_ratekey/value directly.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/api/handlers/admin_marker_providers_test.go` around lines 46 - 48, The test currently checks rec.Body.String() with brittle string matching for `"acceptance_rate":0.7`; instead, unmarshal the response JSON body (e.g., into a map[string]interface{} or a small struct) and assert the acceptance_rate field value directly; in the test around variables rec and body, replace the raw string Contains check with json.Unmarshal(bodyBytes, &m) and then check m["acceptance_rate"] (or struct.AcceptanceRate) equals the expected numeric value, failing the test if the key is missing or the value mismatches.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@cmd/silo/main.go`:
- Around line 2047-2049: The sort comparators currently dereference slice
elements (e.g., installations[i].ID in the sort.Slice comparator) without
checking for nil, which can panic if a nil entry exists; update the
comparator(s) to first guard against nils (e.g., if installations[i] == nil &&
installations[j] == nil { return false } if installations[i] == nil { return
false } if installations[j] == nil { return true }) so nils are consistently
ordered (typically after non-nils), or pre-filter nil entries out of the slice
before calling sort.Slice; apply the same nil-guard pattern to the other
provider/capability comparator that dereferences elements to avoid nil-pointer
panics.
In `@internal/api/handlers/admin_marker_providers_test.go`:
- Around line 56-68: The test in admin_marker_providers_test.go currently
verifies DisplayName, SourceType, PluginInstallationID, CapabilityID and
IsSubmitter but omits PluginID; update the assertions after calling
toProviderConfigResponse (or wherever resp is produced) to also assert
resp.PluginID == "silo.plugin.markers" so the test ensures
toProviderConfigResponse preserves the PluginID field from
markers.ProviderDescriptor.
In `@internal/markers/plugin_provider.go`:
- Around line 244-271: The markerFromPluginSegment function currently accepts
negative start times and end times beyond the media duration; update
markerFromPluginSegment to validate and reject segments with start < 0 or end >
duration (in addition to the existing end <= start check) — use
secondsDuration(segment.GetStartSeconds()) and
secondsDuration(segment.GetEndSeconds()) to compute start/end, then if start < 0
or end > duration return (Marker{}, false); alternatively clamp to [0,duration]
only if you want to accept corrected values, but be explicit in code (refer to
markerFromPluginSegment, start, end, duration, secondsDuration and the end <=
start check) so invalid external plugin ranges cannot propagate.
In `@internal/markers/types.go`:
- Around line 248-270: SetProviders currently validates and builds the
replacement slice before taking r.mu, allowing a concurrent writer like Register
to mutate r.providers and be lost; fix by acquiring the registry write lock
(r.mu.Lock()) at the start of SetProviders (after the nil-receiver check),
perform the validation/build of next while holding the lock, assign r.providers
= next, then unlock (defer r.mu.Unlock() is fine). This serializes SetProviders
with Register and any other writers so updates are not lost.
In `@internal/plugins/service.go`:
- Around line 90-99: OnLifecycleChange currently runs lifecycleHooks directly so
a panic in any hook can escape; update the loop that iterates over hooks (the
hook variable in OnLifecycleChange) to invoke each hook inside a panic-safe
wrapper: defer a recover() for each call so a panic is caught and does not
propagate, and, if the Service exposes a logger (e.g., s.logger or similar), log
the recovered panic and stack trace; otherwise silently swallow the panic and
continue to the next hook to preserve the best-effort behavior.
In `@web/src/pages/admin-settings/IntroSettings.tsx`:
- Around line 94-95: Replace the loose parseInt logic for fetchPriority: stop
using Number.parseInt(fetchPriority, 10) and instead perform strict numeric
validation (e.g. test the raw string with a digits-only regex like /^[+-]?\d+$/
to reject scientific notation such as "1e2", then parse with Number or parseInt
once validated). Update the constants parsedFetchPriority and priorityValid in
IntroSettings.tsx so parsedFetchPriority = Number(fetchPriority) (or parseInt
after the regex check) and priorityValid = Number.isInteger(parsedFetchPriority)
&& /^[+-]?\d+$/.test(fetchPriority), ensuring the component only accepts real
integer strings before sending fetch_priority.
---
Outside diff comments:
In `@internal/api/handlers/admin_marker_providers_test.go`:
- Around line 46-48: The test currently checks rec.Body.String() with brittle
string matching for `"acceptance_rate":0.7`; instead, unmarshal the response
JSON body (e.g., into a map[string]interface{} or a small struct) and assert the
acceptance_rate field value directly; in the test around variables rec and body,
replace the raw string Contains check with json.Unmarshal(bodyBytes, &m) and
then check m["acceptance_rate"] (or struct.AcceptanceRate) equals the expected
numeric value, failing the test if the key is missing or the value mismatches.
In `@internal/markers/types.go`:
- Around line 369-375: FetchMerged currently constructs a fresh Result (merged
:= Result{SourceClass: models.MarkerSourceOnline}) and returns that, which drops
top-level metadata such as ProviderID and Algorithm and can misrepresent
SourceClass; instead, preserve the original result metadata when merging. Locate
FetchMerged and the merged variable, and copy ProviderID, Algorithm and the
original SourceClass from the input Result (or from the single-provider winner
in best[kind]) into merged before returning (or initialize merged by cloning the
original Result and then replace/append Markers), ensuring per-marker fields
remain stamped but top-level ProviderID, Algorithm and SourceClass are retained.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: aed4f449-a156-4bae-ad62-335ee5c410d2
📒 Files selected for processing (28)
cmd/silo/main.gocmd/silo/marker_plugin_migration_test.gointernal/api/handlers/admin_marker_providers.gointernal/api/handlers/admin_marker_providers_test.gointernal/api/handlers/playback_lazy_markers.gointernal/markers/contribute.gointernal/markers/contribute_test.gointernal/markers/introdb/client.gointernal/markers/introdb/provider.gointernal/markers/introdb/types.gointernal/markers/plugin_provider.gointernal/markers/plugin_provider_test.gointernal/markers/provider_config.gointernal/markers/types.gointernal/markers/types_test.gointernal/markers/write.gointernal/markers/write_test.gointernal/pluginhost/client.gointernal/pluginhost/client_test.gointernal/pluginhost/handshake.gointernal/plugins/service.gointernal/plugins/service_hot_reload_test.gointernal/scanner/file_repo.gointernal/scanner/file_repo_test.gointernal/scanner/types.goweb/src/api/types.tsweb/src/hooks/queries/admin/markers.tsweb/src/pages/admin-settings/IntroSettings.tsx
💤 Files with no reviewable changes (3)
- internal/markers/introdb/types.go
- internal/markers/introdb/provider.go
- internal/markers/introdb/client.go
✅ Files skipped from review due to trivial changes (1)
- internal/pluginhost/handshake.go
🚧 Files skipped from review as they are similar to previous changes (5)
- internal/scanner/types.go
- internal/markers/write_test.go
- web/src/api/types.ts
- web/src/hooks/queries/admin/markers.ts
- internal/markers/contribute_test.go
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/markers/plugin_provider_test.go (1)
88-127: ⚡ Quick winConsider adding test case for
start >= duration.The implementation rejects segments where
start >= duration, but this edge case isn't covered. Adding a test case like{name: "start at duration", segment: &pluginv1.MarkerSegment{Segment: "intro", StartSeconds: &sixtySeconds}, wantOK: false}would complete the out-of-bounds coverage.🧪 Suggested test case addition
validStart := 50.0 duration := time.Minute + atDuration := 60.0 tests := []struct { name string segment *pluginv1.MarkerSegment wantOK bool wantEnd time.Duration }{ { name: "negative start", segment: &pluginv1.MarkerSegment{Segment: "intro", StartSeconds: &negativeStart}, }, { name: "end past duration", segment: &pluginv1.MarkerSegment{Segment: "intro", StartSeconds: &start10, EndSeconds: &end61}, }, + { + name: "start at duration", + segment: &pluginv1.MarkerSegment{Segment: "intro", StartSeconds: &atDuration}, + }, { name: "default end uses duration", segment: &pluginv1.MarkerSegment{Segment: "credits", StartSeconds: &validStart}, wantOK: true, wantEnd: duration, }, }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/markers/plugin_provider_test.go` around lines 88 - 127, Add a test for the "start >= duration" boundary inside TestPluginProviderRejectsOutOfBoundsSegments: create a new test case (e.g., name "start at duration") that supplies a MarkerSegment with StartSeconds equal to the duration (e.g., 60s) and expect wantOK false, then run the existing markerFromPluginSegment(duration) assertions as in the other cases to validate the implementation rejects this segment; update the tests slice in TestPluginProviderRejectsOutOfBoundsSegments accordingly so the loop exercises this edge case.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@internal/markers/plugin_provider_test.go`:
- Around line 88-127: Add a test for the "start >= duration" boundary inside
TestPluginProviderRejectsOutOfBoundsSegments: create a new test case (e.g., name
"start at duration") that supplies a MarkerSegment with StartSeconds equal to
the duration (e.g., 60s) and expect wantOK false, then run the existing
markerFromPluginSegment(duration) assertions as in the other cases to validate
the implementation rejects this segment; update the tests slice in
TestPluginProviderRejectsOutOfBoundsSegments accordingly so the loop exercises
this edge case.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 6d5564ff-22dd-44f9-91ff-a597edc50b76
📒 Files selected for processing (29)
cmd/silo/main.godocs/superpowers/plans/2026-06-06-marker-introdb-readpath-correctness.mddocs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.mdinternal/api/handlers/admin_marker_providers.gointernal/api/handlers/admin_marker_providers_test.gointernal/api/handlers/markers.gointernal/api/handlers/markers_test.gointernal/api/router.gointernal/cache/redis.gointernal/intromarkers/repository.gointernal/intromarkers/repository_test.gointernal/markers/contribute.gointernal/markers/contribute_test.gointernal/markers/contribution_repo.gointernal/markers/plugin_provider.gointernal/markers/plugin_provider_test.gointernal/markers/types.gointernal/playback/marker_update_notifier.gointernal/playback/marker_update_notifier_test.gointernal/plugins/service.gointernal/plugins/service_lifecycle_test.gointernal/scanner/file_repo.gomigrations/182_marker_contributions.up.sqlweb/src/hooks/queries/admin/markers.tsweb/src/pages/admin-settings/IntroSettings.tsxweb/src/player/components/MarkerEditPanel.tsxweb/src/player/components/PlayerControls.tsxweb/src/player/components/SeekBar.tsxweb/src/player/hooks/useMarkerEditor.ts
💤 Files with no reviewable changes (3)
- internal/playback/marker_update_notifier.go
- web/src/player/components/SeekBar.tsx
- docs/superpowers/plans/2026-06-06-marker-introdb-readpath-correctness.md
✅ Files skipped from review due to trivial changes (1)
- docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md
🚧 Files skipped from review as they are similar to previous changes (16)
- migrations/182_marker_contributions.up.sql
- internal/api/router.go
- web/src/hooks/queries/admin/markers.ts
- internal/markers/contribution_repo.go
- internal/plugins/service.go
- internal/intromarkers/repository.go
- internal/api/handlers/markers_test.go
- web/src/player/hooks/useMarkerEditor.ts
- internal/markers/contribute_test.go
- web/src/player/components/PlayerControls.tsx
- cmd/silo/main.go
- web/src/player/components/MarkerEditPanel.tsx
- internal/api/handlers/admin_marker_providers.go
- internal/markers/types.go
- web/src/pages/admin-settings/IntroSettings.tsx
- internal/markers/plugin_provider.go
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
internal/scanner/file_repo.go (2)
1143-1189:⚠️ Potential issue | 🟠 Major | ⚡ Quick winCompute
changedfrom the final state diff, not from the requested operation.This path currently marks every accepted patch and every clear as a write, even when the segment is byte-for-byte identical to what is already stored. That makes idempotent retries rewrite
updated_at, and theCASE ... NOW()logic inwriteMarkerMutationStatewill also bump*_markers_detected_aton unchanged markers. Snapshot the original segment states and derivechangedwithsegmentEqualafter all mutations are applied.Suggested fix
state, err := loadMarkerMutationState(ctx, tx, fileID) if err != nil { return false, err } - changed := markerSegmentFlags{} + original := state if hasUpdate { - applied, err := applyMarkerUpdateToMutationState(update, &state) + _, err := applyMarkerUpdateToMutationState(update, &state) if err != nil { return false, err } - changed.intro = changed.intro || applied.intro - changed.credits = changed.credits || applied.credits - changed.recap = changed.recap || applied.recap - changed.preview = changed.preview || applied.preview } if clearFlags.intro { clearSegmentState(&state.intro) - changed.intro = true } if clearFlags.credits { clearSegmentState(&state.credits) - changed.credits = true } if clearFlags.recap { clearSegmentState(&state.recap) - changed.recap = true } if clearFlags.preview { clearSegmentState(&state.preview) - changed.preview = true } + changed := markerSegmentFlags{ + intro: !segmentEqual(original.intro, state.intro), + credits: !segmentEqual(original.credits, state.credits), + recap: !segmentEqual(original.recap, state.recap), + preview: !segmentEqual(original.preview, state.preview), + } if !changed.any() { if err := tx.Commit(ctx); err != nil { return false, fmt.Errorf("commit marker no-op transaction: %w", err) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/scanner/file_repo.go` around lines 1143 - 1189, Snapshot the original segment states immediately after loadMarkerMutationState (store copies of state.intro, state.credits, state.recap, state.preview), then apply applyMarkerUpdateToMutationState and clearSegmentState as before, but DO NOT set markerSegmentFlags based on the requested ops; after all mutations compute each changed flag by comparing the original snapshot to the final state using segmentEqual (e.g. changed.intro = !segmentEqual(originalIntro, state.intro), etc.), and only call writeMarkerMutationState / commit when changed.any() is true so unchanged, idempotent operations do not update timestamps or write.
1026-1031:⚠️ Potential issue | 🟠 Major | ⚡ Quick winCarry forward the legacy shared confidence in the priority check.
When a pre-segment-provenance row falls back to
legacySharedSource, it still passesstate.confidenceintoCanWriteMarker. That drops the existing shared confidence on the floor, so a lower-confidence write from the same source can overwrite a stronger legacy marker because the current confidence looksnil.Suggested fix
func applySegmentPatch( state *segmentState, legacySharedSource *string, + legacySharedConfidence *float64, source string, provider *string, confidence *float64, algorithm string, @@ - effectiveSource := state.source + effectiveSource := state.source + effectiveConfidence := state.confidence if effectiveSource == nil && state.start != nil && state.end != nil { effectiveSource = legacySharedSource + if effectiveConfidence == nil { + effectiveConfidence = legacySharedConfidence + } } - if !markers.CanWriteMarker(effectiveSource, state.confidence, source, confidence) { + if !markers.CanWriteMarker(effectiveSource, effectiveConfidence, source, confidence) { return false, nil }and pass
state.existingConfidencefromapplyMarkerUpdateToMutationState.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/scanner/file_repo.go` around lines 1026 - 1031, The priority check is using state.confidence even when effectiveSource is set to legacySharedSource, which drops the legacy shared confidence; change the CanWriteMarker call to pass state.existingConfidence when effectiveSource == legacySharedSource (i.e. preserve the carried-forward legacy confidence), and ensure applyMarkerUpdateToMutationState populates state.existingConfidence appropriately so markers.CanWriteMarker(effectiveSource, appropriateConfidence, source, confidence) receives the legacy confidence instead of nil.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@web/src/player/components/SeekBar.tsx`:
- Around line 43-48: Replace the duplicated MARKER_LABELS in SeekBar.tsx with a
single shared source: move the label map currently defined in useMarkerEditor.ts
(the map keyed by MarkerKind) into a new utility under web/src/lib or
web/src/utils (e.g., export getMarkerLabels or MARKER_LABELS constant), then
import and use that shared symbol in both useMarkerEditor (where it currently
lives) and SeekBar.tsx (replace the local MARKER_LABELS), and also update the
live-drag tooltip rendering path to consume the same label map so both hover
tooltip and drag tooltip show identical, centralized labels.
---
Outside diff comments:
In `@internal/scanner/file_repo.go`:
- Around line 1143-1189: Snapshot the original segment states immediately after
loadMarkerMutationState (store copies of state.intro, state.credits,
state.recap, state.preview), then apply applyMarkerUpdateToMutationState and
clearSegmentState as before, but DO NOT set markerSegmentFlags based on the
requested ops; after all mutations compute each changed flag by comparing the
original snapshot to the final state using segmentEqual (e.g. changed.intro =
!segmentEqual(originalIntro, state.intro), etc.), and only call
writeMarkerMutationState / commit when changed.any() is true so unchanged,
idempotent operations do not update timestamps or write.
- Around line 1026-1031: The priority check is using state.confidence even when
effectiveSource is set to legacySharedSource, which drops the legacy shared
confidence; change the CanWriteMarker call to pass state.existingConfidence when
effectiveSource == legacySharedSource (i.e. preserve the carried-forward legacy
confidence), and ensure applyMarkerUpdateToMutationState populates
state.existingConfidence appropriately so
markers.CanWriteMarker(effectiveSource, appropriateConfidence, source,
confidence) receives the legacy confidence instead of nil.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 0a24e6b2-eae9-4d10-a8c0-1cf3d11f6575
📒 Files selected for processing (2)
internal/scanner/file_repo.goweb/src/player/components/SeekBar.tsx
| const MARKER_LABELS: Record<MarkerKind, string> = { | ||
| intro: "Intro", | ||
| recap: "Recap", | ||
| credits: "Credits / Outro", | ||
| preview: "Preview", | ||
| }; |
There was a problem hiding this comment.
Use one shared label source for marker kinds.
This adds a second MARKER_LABELS map even though web/src/player/hooks/useMarkerEditor.ts:10-15 already defines the same labels, and only this hover tooltip uses it. The live drag tooltip still renders the raw enum (credits, preview, etc.), so the same marker kind already shows different copy within the editor. Please centralize the labels and consume that shared source in both tooltip paths.
As per coding guidelines, "keep shared utilities in web/src/lib or web/src/utils".
Also applies to: 311-323
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/player/components/SeekBar.tsx` around lines 43 - 48, Replace the
duplicated MARKER_LABELS in SeekBar.tsx with a single shared source: move the
label map currently defined in useMarkerEditor.ts (the map keyed by MarkerKind)
into a new utility under web/src/lib or web/src/utils (e.g., export
getMarkerLabels or MARKER_LABELS constant), then import and use that shared
symbol in both useMarkerEditor (where it currently lives) and SeekBar.tsx
(replace the local MARKER_LABELS), and also update the live-drag tooltip
rendering path to consume the same label map so both hover tooltip and drag
tooltip show identical, centralized labels.
Source: Coding guidelines
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/api/handlers/markers.go (1)
374-410:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winReject unknown marker keys instead of silently no-oping them.
This loop only processes the four known segment names, so a body like
{"outtro": {...}}returns200with no mutation. That makes client typos look successful.Suggested fix
var raw map[string]json.RawMessage if err := json.NewDecoder(r.Body).Decode(&raw); err != nil { writeError(w, http.StatusBadRequest, "bad_request", "Invalid request body") return } + for key := range raw { + if !isMarkerSegment(key) { + writeError(w, http.StatusBadRequest, "bad_request", "Unknown marker segment "+key) + return + } + } duration := float64(file.Duration)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/api/handlers/markers.go` around lines 374 - 410, The handler currently decodes the request into raw (map[string]json.RawMessage) and only iterates known markerSegmentNames, silently ignoring any unknown keys; change the validation so after decoding raw you iterate the keys in raw and reject (writeError 400) any key that is not in markerSegmentNames (or allowed keys like other known fields), before proceeding to parse segments and using normalizeManualSegment/applyManualSegment; reference raw, markerSegmentNames, normalizeManualSegment, and applyManualSegment to locate where to add the unknown-key check and return a bad_request when an unexpected key is present.
🧹 Nitpick comments (1)
migrations/183_marker_edit_audit.up.sql (1)
1-2:permissionscolumn DEFAULT is overwritten by migration 183 (not extended).
ALTER COLUMN permissions SET DEFAULT ARRAY['marker_edit']::text[]replaces the entire default. In this repo the prior default was'{}'::text[](migrations/001_schema.up.sql, migrations/140_user_permissions.up.sql), and the down migration resets it back to'{}'::text[]. If future migrations need the default to include additional permissions, this will override that baseline—consider concatenating/preserving existing defaults if that’s the intent.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@migrations/183_marker_edit_audit.up.sql` around lines 1 - 2, The migration overwrites the users.permissions default (ALTER COLUMN permissions SET DEFAULT ARRAY['marker_edit']::text[]) instead of extending it; update migrations/183_marker_edit_audit.up.sql so the default preserves existing entries and appends 'marker_edit' (use array concatenation/array_cat with COALESCE to handle NULL or '{}' defaults) rather than replacing the whole default, and ensure the down migration restores the previous baseline default ('{}'::text[]) as intended.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/api/handlers/markers.go`:
- Around line 298-300: The current permission check collapses GetByID errors
into a 403; change the logic in the markers handler so that when
h.Users.GetByID(ctx, claims.UserID) returns a non-nil err you return a 500 via
writeError (internal server error) and only treat user == nil or
!auth.HasEffectivePermission(user, auth.PermissionMarkerEdit) as a 403;
specifically update the block that calls h.Users.GetByID,
auth.HasEffectivePermission, and writeError so errors from GetByID are handled
and logged/returned as a 500 while real permission failures remain 403.
In `@web/src/components/markers/MarkerEditor.tsx`:
- Around line 76-79: The current MarkerEditor passes history={isAdmin ?
(history.data ?? []) : []} which masks fetch errors from useItemMarkerHistory
and shows a false empty audit log; update MarkerEditor to detect history.error
(from useItemMarkerHistory) and avoid passing an empty array on error—e.g., pass
undefined or null for history and set historyLoading/showHistory appropriately,
and surface an error prop or conditional UI for MarkerHistory so 403/500
responses are shown as an error state instead of "No marker edits recorded.";
ensure updates reference the useItemMarkerHistory return (history.data,
history.isLoading, history.error) and the MarkerHistory props (history,
historyLoading, showHistory, and/or add an error prop).
In `@web/src/pages/AdminUserDetail.tsx`:
- Around line 284-291: The UI is using hasAssignedPermission(user.permissions,
PERMISSION_MARKER_EDIT) which only checks explicit assignment and can show
admins as "Not allowed"; replace that check with the effective-permission helper
(e.g. hasEffectivePermission or userHasEffectivePermission) so the Marker
Editing row uses hasEffectivePermission(user, PERMISSION_MARKER_EDIT) (or the
equivalent app utility) instead of hasAssignedPermission, and update the other
similar rows (lines ~1011-1027) to use the same effective-permission function.
---
Outside diff comments:
In `@internal/api/handlers/markers.go`:
- Around line 374-410: The handler currently decodes the request into raw
(map[string]json.RawMessage) and only iterates known markerSegmentNames,
silently ignoring any unknown keys; change the validation so after decoding raw
you iterate the keys in raw and reject (writeError 400) any key that is not in
markerSegmentNames (or allowed keys like other known fields), before proceeding
to parse segments and using normalizeManualSegment/applyManualSegment; reference
raw, markerSegmentNames, normalizeManualSegment, and applyManualSegment to
locate where to add the unknown-key check and return a bad_request when an
unexpected key is present.
---
Nitpick comments:
In `@migrations/183_marker_edit_audit.up.sql`:
- Around line 1-2: The migration overwrites the users.permissions default (ALTER
COLUMN permissions SET DEFAULT ARRAY['marker_edit']::text[]) instead of
extending it; update migrations/183_marker_edit_audit.up.sql so the default
preserves existing entries and appends 'marker_edit' (use array
concatenation/array_cat with COALESCE to handle NULL or '{}' defaults) rather
than replacing the whole default, and ensure the down migration restores the
previous baseline default ('{}'::text[]) as intended.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 6de207e6-0844-41da-811d-bf1e7d33df64
📒 Files selected for processing (35)
internal/api/handlers/admin.gointernal/api/handlers/markers.gointernal/api/handlers/markers_test.gointernal/api/router.gointernal/auth/permissions.gointernal/auth/permissions_test.gointernal/auth/repository.gointernal/scanner/file_repo.gointernal/scanner/file_repo_test.gointernal/scanner/marker_audit.gomigrations/183_marker_edit_audit.down.sqlmigrations/183_marker_edit_audit.up.sqlweb/src/App.tsxweb/src/api/types.tsweb/src/components/AdminSidebar.test.tsxweb/src/components/AdminSidebar.tsxweb/src/components/markers/MarkerEditor.tsxweb/src/hooks/queries/admin/markers.tsweb/src/hooks/queries/keys.tsweb/src/hooks/queries/markers.tsweb/src/lib/documentTitle.tsweb/src/lib/permissions.test.tsweb/src/lib/permissions.tsweb/src/pages/AdminMarkerHistory.tsxweb/src/pages/AdminUserDetail.tsxweb/src/pages/AdminUsers.tsxweb/src/pages/ItemDetail/EpisodeContent.tsxweb/src/pages/ItemDetail/MovieContent.test.tsxweb/src/pages/ItemDetail/MovieContent.tsxweb/src/playback/WatchPlaybackChrome.tsxweb/src/player/components/PlayerControls.test.tsxweb/src/player/components/VideoPlayer.tsxweb/src/player/components/WatchPage.tsxweb/src/player/hooks/useMarkerEditor.tsweb/src/player/types.ts
✅ Files skipped from review due to trivial changes (3)
- web/src/lib/permissions.test.ts
- migrations/183_marker_edit_audit.down.sql
- web/src/api/types.ts
🚧 Files skipped from review as they are similar to previous changes (6)
- web/src/pages/ItemDetail/EpisodeContent.tsx
- web/src/player/types.ts
- web/src/player/components/WatchPage.tsx
- web/src/hooks/queries/admin/markers.ts
- web/src/player/components/VideoPlayer.tsx
- internal/api/router.go
| user, err := h.Users.GetByID(r.Context(), claims.UserID) | ||
| if err != nil || user == nil || !auth.HasEffectivePermission(user, auth.PermissionMarkerEdit) { | ||
| writeError(w, http.StatusForbidden, "forbidden", "Marker editing permission required") |
There was a problem hiding this comment.
Return 500 when the permission lookup itself fails.
Line 298 collapses h.Users.GetByID(...) failures into the same 403 path as a real permission miss. A transient user-store error will deny valid editors with a misleading auth response.
Suggested fix
user, err := h.Users.GetByID(r.Context(), claims.UserID)
- if err != nil || user == nil || !auth.HasEffectivePermission(user, auth.PermissionMarkerEdit) {
+ if err != nil {
+ h.logger.Error("markers: load permission user failed", "user_id", claims.UserID, "error", err)
+ writeError(w, http.StatusInternalServerError, "internal_error", "Failed to verify marker editing permission")
+ return false
+ }
+ if user == nil || !auth.HasEffectivePermission(user, auth.PermissionMarkerEdit) {
writeError(w, http.StatusForbidden, "forbidden", "Marker editing permission required")
return false
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| user, err := h.Users.GetByID(r.Context(), claims.UserID) | |
| if err != nil || user == nil || !auth.HasEffectivePermission(user, auth.PermissionMarkerEdit) { | |
| writeError(w, http.StatusForbidden, "forbidden", "Marker editing permission required") | |
| user, err := h.Users.GetByID(r.Context(), claims.UserID) | |
| if err != nil { | |
| h.logger.Error("markers: load permission user failed", "user_id", claims.UserID, "error", err) | |
| writeError(w, http.StatusInternalServerError, "internal_error", "Failed to verify marker editing permission") | |
| return false | |
| } | |
| if user == nil || !auth.HasEffectivePermission(user, auth.PermissionMarkerEdit) { | |
| writeError(w, http.StatusForbidden, "forbidden", "Marker editing permission required") | |
| return false | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/api/handlers/markers.go` around lines 298 - 300, The current
permission check collapses GetByID errors into a 403; change the logic in the
markers handler so that when h.Users.GetByID(ctx, claims.UserID) returns a
non-nil err you return a 500 via writeError (internal server error) and only
treat user == nil or !auth.HasEffectivePermission(user,
auth.PermissionMarkerEdit) as a 403; specifically update the block that calls
h.Users.GetByID, auth.HasEffectivePermission, and writeError so errors from
GetByID are handled and logged/returned as a 500 while real permission failures
remain 403.
| history={isAdmin ? (history.data ?? []) : []} | ||
| historyLoading={isAdmin && history.isLoading} | ||
| showHistory={isAdmin} | ||
| onClose={() => onOpenChange(false)} |
There was a problem hiding this comment.
Don't render history fetch failures as an empty audit log.
If useItemMarkerHistory errors, this falls back to [] and MarkerHistory shows No marker edits recorded. Admins will see a false empty state for 403/500s.
Suggested fix
<MarkerEditorForm
key={data.file_id}
itemId={itemId}
data={data}
history={isAdmin ? (history.data ?? []) : []}
historyLoading={isAdmin && history.isLoading}
+ historyError={isAdmin && history.isError}
showHistory={isAdmin}
onClose={() => onOpenChange(false)}
/>
@@
history,
historyLoading,
+ historyError,
showHistory,
onClose,
}: {
itemId: string;
data: FileMarkersResponse;
history: MarkerEditAuditEntry[];
historyLoading: boolean;
+ historyError: boolean;
showHistory: boolean;
onClose: () => void;
}) {
@@
- {showHistory && <MarkerHistory rows={history} isLoading={historyLoading} />}
+ {showHistory && (
+ <MarkerHistory rows={history} isLoading={historyLoading} isError={historyError} />
+ )}
@@
-function MarkerHistory({ rows, isLoading }: { rows: MarkerEditAuditEntry[]; isLoading: boolean }) {
+function MarkerHistory({
+ rows,
+ isLoading,
+ isError,
+}: {
+ rows: MarkerEditAuditEntry[];
+ isLoading: boolean;
+ isError: boolean;
+}) {
return (
<div className="border-border mt-2 border-t pt-3">
@@
- {rows.length === 0 && !isLoading ? (
+ {isError ? (
+ <p className="text-destructive text-sm">Failed to load recent marker changes.</p>
+ ) : rows.length === 0 && !isLoading ? (
<p className="text-muted-foreground text-sm">No marker edits recorded.</p>
) : (Also applies to: 202-235
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/components/markers/MarkerEditor.tsx` around lines 76 - 79, The
current MarkerEditor passes history={isAdmin ? (history.data ?? []) : []} which
masks fetch errors from useItemMarkerHistory and shows a false empty audit log;
update MarkerEditor to detect history.error (from useItemMarkerHistory) and
avoid passing an empty array on error—e.g., pass undefined or null for history
and set historyLoading/showHistory appropriately, and surface an error prop or
conditional UI for MarkerHistory so 403/500 responses are shown as an error
state instead of "No marker edits recorded."; ensure updates reference the
useItemMarkerHistory return (history.data, history.isLoading, history.error) and
the MarkerHistory props (history, historyLoading, showHistory, and/or add an
error prop).
| <DetailRow | ||
| label="Marker Editing" | ||
| value={ | ||
| hasAssignedPermission(user.permissions, PERMISSION_MARKER_EDIT) | ||
| ? "Allowed" | ||
| : "Not allowed" | ||
| } | ||
| /> |
There was a problem hiding this comment.
Use effective marker-edit permission semantics for admin users.
Backend auth grants marker_edit to every admin via HasEffectivePermission, but these branches only check explicit assignment. Admins can therefore show as Not allowed here and get a toggle that doesn't reflect runtime behavior.
Suggested fix
- <DetailRow
- label="Marker Editing"
- value={
- hasAssignedPermission(user.permissions, PERMISSION_MARKER_EDIT)
- ? "Allowed"
- : "Not allowed"
- }
- />
+ <DetailRow
+ label="Marker Editing"
+ value={
+ user.role === "admin" ||
+ hasAssignedPermission(user.permissions, PERMISSION_MARKER_EDIT)
+ ? "Allowed"
+ : "Not allowed"
+ }
+ />+ const markerEditAllowed =
+ role === "admin" || hasAssignedPermission(permissions, PERMISSION_MARKER_EDIT);
+
<div className="border-border flex items-center justify-between rounded-md border px-3 py-2">
<div>
<Label htmlFor={markerEditId}>Marker Editing</Label>
<p className="text-muted-foreground text-xs">
Edit intro, recap, credits, and preview markers within assigned libraries.
</p>
</div>
<Switch
id={markerEditId}
- checked={hasAssignedPermission(permissions, PERMISSION_MARKER_EDIT)}
+ checked={markerEditAllowed}
+ disabled={role === "admin"}
onCheckedChange={(checked) =>
setPermissions((current) =>
setAssignedPermission(current, PERMISSION_MARKER_EDIT, checked),
)
}
/>
</div>Also applies to: 1011-1027
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/pages/AdminUserDetail.tsx` around lines 284 - 291, The UI is using
hasAssignedPermission(user.permissions, PERMISSION_MARKER_EDIT) which only
checks explicit assignment and can show admins as "Not allowed"; replace that
check with the effective-permission helper (e.g. hasEffectivePermission or
userHasEffectivePermission) so the Marker Editing row uses
hasEffectivePermission(user, PERMISSION_MARKER_EDIT) (or the equivalent app
utility) instead of hasAssignedPermission, and update the other similar rows
(lines ~1011-1027) to use the same effective-permission function.
… refinement (Silo-Server#57) * docs(markers): design + implementation plans for multi-source markers & TheIntroDB contribution * fix(markers): TheIntroDB read-path correctness (TVDB, real confidence, best candidate) Honor TVDB ids in /media lookups (previously dropped — anime/TheTVDB-first libraries got no markers), decode and use the real per-segment confidence and submission_count instead of a hardcoded 0.9, and pick the most-submitted / highest-confidence candidate when several are returned. Adds httptest coverage for the introdb client and provider. Phase 1 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(markers): multi-source dispatch, per-provider config, per-segment provenance Add marker_provider_config (per-provider fetch enable/priority + contribute gates, contribution off by default) and a cached ProviderConfigStore. Add Registry.FetchMerged: query all fetch-enabled providers concurrently and keep the best candidate per segment (submission_count, then confidence, then fetch priority), stamping each winning marker with its provider/algorithm. Thread per-segment provenance through MarkerUpdatePayload and scanner.MarkerUpdate (additive SegmentProvenance overrides) so a merged result writes correct per-segment provider/confidence/algorithm; the legacy shared columns keep a summary. The lazy-playback path now uses FetchMerged. With only TheIntroDB enabled, behavior is unchanged. Phase 2 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(markers): TheIntroDB submission client, contribution audit, service engine Add a markers.Submitter capability and implement it on the introdb provider (POST /v3/submit, GET /v3/user/stats; key required, usage-limit aware, applies the null start/end conventions). Add the marker_contributions audit table and a value-hash-keyed ContributionStore for idempotency. Add ContributionService: resolves enabled submitter providers, gates eligibility (never re-submit online-sourced markers; auto runs require contribute_auto_local + scanner-intro above the per-provider confidence threshold), checks idempotency, submits, and records. Wired in main.go; no trigger yet (admin API and task follow). Phase 3 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(api): admin marker editing, contribution, and provider config endpoints Add the RequireAdmin marker API: GET/PUT /admin/files/{id}/markers (read with provenance; manual upsert where a segment object sets and null clears), DELETE .../markers/{segment}, POST .../contribute and GET .../contributions, plus GET/PUT /admin/markers/providers[/{provider}] and a .../validate key-check returning user stats. Manual writes go through the priority-gated UpsertMarkers (source=manual) and notify live sessions; a new FileRepository.ClearMarkers nulls a segment's columns. Validation mirrors the contribution rules. Phase 4 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(markers): daily auto-contribution task for local intro markers Add ContributeMarkersTask (daily 04:00, after local detection): when a provider has contribute_enabled + contribute_auto_local, page through episode files with a scanner intro marker at/above the provider's confidence threshold (new ContributionStore.CandidateLocalIntroFiles keyset query) and run them through ContributionService with Auto=true. No-op when no provider opts in; idempotent and resumable across runs. Phase 5 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(intromarkers): refine chromaprint starts with dialogue cues * feat(markers): finish marker management backend * feat(web): add marker editing UI * feat(markers): use plugin marker providers * fix(markers): address PR review feedback * feat(player): show marker labels on seek hover * fix(markers): type nullable marker mutation params * feat(markers): audit marker edits and add permission --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
… refinement (#57) * docs(markers): design + implementation plans for multi-source markers & TheIntroDB contribution * fix(markers): TheIntroDB read-path correctness (TVDB, real confidence, best candidate) Honor TVDB ids in /media lookups (previously dropped — anime/TheTVDB-first libraries got no markers), decode and use the real per-segment confidence and submission_count instead of a hardcoded 0.9, and pick the most-submitted / highest-confidence candidate when several are returned. Adds httptest coverage for the introdb client and provider. Phase 1 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(markers): multi-source dispatch, per-provider config, per-segment provenance Add marker_provider_config (per-provider fetch enable/priority + contribute gates, contribution off by default) and a cached ProviderConfigStore. Add Registry.FetchMerged: query all fetch-enabled providers concurrently and keep the best candidate per segment (submission_count, then confidence, then fetch priority), stamping each winning marker with its provider/algorithm. Thread per-segment provenance through MarkerUpdatePayload and scanner.MarkerUpdate (additive SegmentProvenance overrides) so a merged result writes correct per-segment provider/confidence/algorithm; the legacy shared columns keep a summary. The lazy-playback path now uses FetchMerged. With only TheIntroDB enabled, behavior is unchanged. Phase 2 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(markers): TheIntroDB submission client, contribution audit, service engine Add a markers.Submitter capability and implement it on the introdb provider (POST /v3/submit, GET /v3/user/stats; key required, usage-limit aware, applies the null start/end conventions). Add the marker_contributions audit table and a value-hash-keyed ContributionStore for idempotency. Add ContributionService: resolves enabled submitter providers, gates eligibility (never re-submit online-sourced markers; auto runs require contribute_auto_local + scanner-intro above the per-provider confidence threshold), checks idempotency, submits, and records. Wired in main.go; no trigger yet (admin API and task follow). Phase 3 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(api): admin marker editing, contribution, and provider config endpoints Add the RequireAdmin marker API: GET/PUT /admin/files/{id}/markers (read with provenance; manual upsert where a segment object sets and null clears), DELETE .../markers/{segment}, POST .../contribute and GET .../contributions, plus GET/PUT /admin/markers/providers[/{provider}] and a .../validate key-check returning user stats. Manual writes go through the priority-gated UpsertMarkers (source=manual) and notify live sessions; a new FileRepository.ClearMarkers nulls a segment's columns. Validation mirrors the contribution rules. Phase 4 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(markers): daily auto-contribution task for local intro markers Add ContributeMarkersTask (daily 04:00, after local detection): when a provider has contribute_enabled + contribute_auto_local, page through episode files with a scanner intro marker at/above the provider's confidence threshold (new ContributionStore.CandidateLocalIntroFiles keyset query) and run them through ContributionService with Auto=true. No-op when no provider opts in; idempotent and resumable across runs. Phase 5 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(intromarkers): refine chromaprint starts with dialogue cues * feat(markers): finish marker management backend * feat(web): add marker editing UI * feat(markers): use plugin marker providers * fix(markers): address PR review feedback * feat(player): show marker labels on seek hover * fix(markers): type nullable marker mutation params * feat(markers): audit marker edits and add permission --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
… refinement (#57) * docs(markers): design + implementation plans for multi-source markers & TheIntroDB contribution * fix(markers): TheIntroDB read-path correctness (TVDB, real confidence, best candidate) Honor TVDB ids in /media lookups (previously dropped — anime/TheTVDB-first libraries got no markers), decode and use the real per-segment confidence and submission_count instead of a hardcoded 0.9, and pick the most-submitted / highest-confidence candidate when several are returned. Adds httptest coverage for the introdb client and provider. Phase 1 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(markers): multi-source dispatch, per-provider config, per-segment provenance Add marker_provider_config (per-provider fetch enable/priority + contribute gates, contribution off by default) and a cached ProviderConfigStore. Add Registry.FetchMerged: query all fetch-enabled providers concurrently and keep the best candidate per segment (submission_count, then confidence, then fetch priority), stamping each winning marker with its provider/algorithm. Thread per-segment provenance through MarkerUpdatePayload and scanner.MarkerUpdate (additive SegmentProvenance overrides) so a merged result writes correct per-segment provider/confidence/algorithm; the legacy shared columns keep a summary. The lazy-playback path now uses FetchMerged. With only TheIntroDB enabled, behavior is unchanged. Phase 2 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(markers): TheIntroDB submission client, contribution audit, service engine Add a markers.Submitter capability and implement it on the introdb provider (POST /v3/submit, GET /v3/user/stats; key required, usage-limit aware, applies the null start/end conventions). Add the marker_contributions audit table and a value-hash-keyed ContributionStore for idempotency. Add ContributionService: resolves enabled submitter providers, gates eligibility (never re-submit online-sourced markers; auto runs require contribute_auto_local + scanner-intro above the per-provider confidence threshold), checks idempotency, submits, and records. Wired in main.go; no trigger yet (admin API and task follow). Phase 3 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(api): admin marker editing, contribution, and provider config endpoints Add the RequireAdmin marker API: GET/PUT /admin/files/{id}/markers (read with provenance; manual upsert where a segment object sets and null clears), DELETE .../markers/{segment}, POST .../contribute and GET .../contributions, plus GET/PUT /admin/markers/providers[/{provider}] and a .../validate key-check returning user stats. Manual writes go through the priority-gated UpsertMarkers (source=manual) and notify live sessions; a new FileRepository.ClearMarkers nulls a segment's columns. Validation mirrors the contribution rules. Phase 4 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(markers): daily auto-contribution task for local intro markers Add ContributeMarkersTask (daily 04:00, after local detection): when a provider has contribute_enabled + contribute_auto_local, page through episode files with a scanner intro marker at/above the provider's confidence threshold (new ContributionStore.CandidateLocalIntroFiles keyset query) and run them through ContributionService with Auto=true. No-op when no provider opts in; idempotent and resumable across runs. Phase 5 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(intromarkers): refine chromaprint starts with dialogue cues * feat(markers): finish marker management backend * feat(web): add marker editing UI * feat(markers): use plugin marker providers * fix(markers): address PR review feedback * feat(player): show marker labels on seek hover * fix(markers): type nullable marker mutation params * feat(markers): audit marker edits and add permission --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
… refinement (#57) * docs(markers): design + implementation plans for multi-source markers & TheIntroDB contribution * fix(markers): TheIntroDB read-path correctness (TVDB, real confidence, best candidate) Honor TVDB ids in /media lookups (previously dropped — anime/TheTVDB-first libraries got no markers), decode and use the real per-segment confidence and submission_count instead of a hardcoded 0.9, and pick the most-submitted / highest-confidence candidate when several are returned. Adds httptest coverage for the introdb client and provider. Phase 1 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(markers): multi-source dispatch, per-provider config, per-segment provenance Add marker_provider_config (per-provider fetch enable/priority + contribute gates, contribution off by default) and a cached ProviderConfigStore. Add Registry.FetchMerged: query all fetch-enabled providers concurrently and keep the best candidate per segment (submission_count, then confidence, then fetch priority), stamping each winning marker with its provider/algorithm. Thread per-segment provenance through MarkerUpdatePayload and scanner.MarkerUpdate (additive SegmentProvenance overrides) so a merged result writes correct per-segment provider/confidence/algorithm; the legacy shared columns keep a summary. The lazy-playback path now uses FetchMerged. With only TheIntroDB enabled, behavior is unchanged. Phase 2 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(markers): TheIntroDB submission client, contribution audit, service engine Add a markers.Submitter capability and implement it on the introdb provider (POST /v3/submit, GET /v3/user/stats; key required, usage-limit aware, applies the null start/end conventions). Add the marker_contributions audit table and a value-hash-keyed ContributionStore for idempotency. Add ContributionService: resolves enabled submitter providers, gates eligibility (never re-submit online-sourced markers; auto runs require contribute_auto_local + scanner-intro above the per-provider confidence threshold), checks idempotency, submits, and records. Wired in main.go; no trigger yet (admin API and task follow). Phase 3 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(api): admin marker editing, contribution, and provider config endpoints Add the RequireAdmin marker API: GET/PUT /admin/files/{id}/markers (read with provenance; manual upsert where a segment object sets and null clears), DELETE .../markers/{segment}, POST .../contribute and GET .../contributions, plus GET/PUT /admin/markers/providers[/{provider}] and a .../validate key-check returning user stats. Manual writes go through the priority-gated UpsertMarkers (source=manual) and notify live sessions; a new FileRepository.ClearMarkers nulls a segment's columns. Validation mirrors the contribution rules. Phase 4 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(markers): daily auto-contribution task for local intro markers Add ContributeMarkersTask (daily 04:00, after local detection): when a provider has contribute_enabled + contribute_auto_local, page through episode files with a scanner intro marker at/above the provider's confidence threshold (new ContributionStore.CandidateLocalIntroFiles keyset query) and run them through ContributionService with Auto=true. No-op when no provider opts in; idempotent and resumable across runs. Phase 5 of docs/superpowers/plans/2026-06-06-marker-sources-and-contribution-implementation.md Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(intromarkers): refine chromaprint starts with dialogue cues * feat(markers): finish marker management backend * feat(web): add marker editing UI * feat(markers): use plugin marker providers * fix(markers): address PR review feedback * feat(player): show marker labels on seek hover * fix(markers): type nullable marker mutation params * feat(markers): audit marker edits and add permission --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…changes The SDK commit merges the final heads of Silo-Server/silo-plugin-sdk #57-#62: the event catalog, scoped host API keys, notification channels, conditional instance state writes, default task schedules and host viewer headers. Plugin event names now need a publisher and an event name; every name the server uses already has both. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Root Cause
Chromaprint correctly finds shared audio, but some episodes start the intro music bed before the actual title sequence while dialogue is still active. The local detector was treating that shared music onset as the user-facing intro start. The new refinement keeps Chromaprint as the coarse audio detector and moves only the start boundary forward to the last early dialogue cue when a matching non-SDH text subtitle sidecar is available.
Validation
go test ./internal/api/handlers ./internal/markers ./internal/markers/introdb ./internal/scanner ./internal/taskmanager/tasks ./internal/intromarkers ./internal/subtitles ./internal/subtitles/aicd web && pnpm exec prettier --check src/api/types.ts src/hooks/queries/keys.ts src/hooks/queries/markers.ts src/hooks/queries/admin/markers.ts src/lib/markers.ts src/components/markers/MarkerEditor.tsx src/pages/ItemDetail/EpisodeContent.tsx src/pages/ItemDetail/MovieContent.tsx src/pages/ItemDetail/components/ActionBar.tsx src/pages/admin-settings/AdminSettingsLayout.tsx src/pages/admin-settings/IntegrationsSettings.tsx src/pages/admin-settings/ScannerSettings.tsx src/pages/admin-settings/IntroSettings.tsx src/player/components/PlayerControls.tsx src/player/components/SeekBar.tsx src/player/components/VideoPlayer.tsx src/player/components/WatchPage.tsx src/player/components/MarkerEditPanel.tsx src/player/hooks/useMarkerEditor.ts src/player/types.tscd web && pnpm run lintexits 0 with existing warnings.cd web && pnpm run format:checkstill fails on 18 pre-existing frontend files outside this PR diff.636600has English audio plus an English non-SDH SRT sidecar, and the bad322.014sChromaprint start refines to330.852safter the final early dialogue cue.Commit Grouping
fix(intromarkers): refine chromaprint starts with dialogue cuesfeat(markers): finish marker management backendfeat(web): add marker editing UINotes
Summary by CodeRabbit
New Features
Bug Fixes
Documentation