Skip to content

feat(autoscan): periodic Radarr/Sonarr import + rename rescans - #43

Closed
fluxis wants to merge 33 commits into
Silo-Server:mainfrom
fluxis:feat/autoscan-arr-polling
Closed

fluxis wants to merge 33 commits into
Silo-Server:mainfrom
fluxis:feat/autoscan-arr-polling

Conversation

@fluxis

@fluxis fluxis commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds Autoscan: a periodic poller that watches each configured Radarr/Sonarr instance's history for changes and triggers targeted Silo library rescans, so newly-imported or renamed files appear without waiting for a full scan.

The feature reuses the existing request_integrations rows as its arr sources (no second place to configure server URLs/keys) and is off by default — operators opt in per instance from the Requests admin surface.

Three layers, built bottom-up:

  1. Polling core — every N minutes, for each enabled source, read /api/v3/history/since, map arr-side paths to Silo paths via per-instance path rewrites, dedup to parent folders, and enqueue scans through the existing scantrigger → scanqueue pipeline. Redis-backed debounce suppresses repeat scans of the same (folder, path) within a TTL.
  2. Rewrite-sync — a convenience that queries an instance's arr root folders and suffix-matches each to a Silo media folder to propose path rewrites. Additive and manual-preserving: synced rows never overwrite operator-entered rewrites; the operator stays the source of truth.
  3. Rename-handling — history polling also surfaces episodeFileRenamed / movieFileRenamed events (both the new path and the old sourcePath), since a rename moves a file with no import event and can cross folders.

Why this approach

  • Reuses request integrations as sources. Arr base URL + Fernet-encrypted API key already live in request_integrations; Autoscan references them by FK (ON DELETE CASCADE) instead of duplicating credential storage.
  • Targeted scans, not full rescans. Resolving each changed path to its owning MediaFolder and enqueueing a subtree/file scan keeps the feature cheap under load — consistent with the repo's performance-first priority.
  • Generic, no deployment constants. Path rewrites and suffix-matching are driven entirely by what each arr instance and the Silo catalog report at runtime; nothing about any specific host topology is baked in.

Schema

migrations/171_autoscan.{up,down}.sql (no collision — main tops out at 170):

  • autoscan_settings — singleton row (id boolean PRIMARY KEY CHECK (id)): enabled, poll_interval_minutes (CHECK > 0), debounce_seconds (CHECK >= 0). Seeded disabled.
  • autoscan_sources — integration_id PK/FK → request_integrations(id) ON DELETE CASCADE; enabled, path_rewrites jsonb, last_poll_at.

API (admin-gated, under /admin)

Method Path Purpose
GET /admin/autoscan/settings read global settings
PUT /admin/autoscan/settings update settings
GET /admin/autoscan/sources list sources (joined to integrations)
PUT /admin/autoscan/sources/{id} upsert per-source enable + rewrites
POST /admin/autoscan/trigger run one poll cycle now (async, 202)
GET /admin/autoscan/status poll/interval status
GET /admin/autoscan/sources/{id}/rewrite-suggestions suggest rewrites from arr root folders

Frontend

New Autoscan tab in the Requests admin page (AdminRequests.tsx): global enable + interval/debounce, per-source enable, and a collapsible path-rewrite editor with a "Sync rewrites" action that previews proposed / unmatched / ambiguous / already-covered matches before applying. Types + React Query hooks in web/src/api/types.ts and web/src/hooks/queries/useAutoscan.ts.

Testing

  • Go unit tests across internal/autoscan: poll cycle (dedup, distinct-paths-same-folder, disabled no-op, source-failure-doesn't-advance, release-claim-on-enqueue-failure), history parsing (imports + renames, ignores unrelated events), suffix-match suggester (unique/ambiguous/covered/no-op/normalization), rewrite + dedupe helpers, and handler tests (FK → 404, trigger dispatch).
  • Full Go suite green — 59 packages, 0 failures, including -race. Note: the autoscan handler tests live in internal/api/handlers, which links libvips via CGO; run tests in an environment with libvips-dev (CI / the Docker golang:1.26 build stage). A bare host without it reports [build failed] for those packages and skips their tests.
  • go vet + gofmt clean.

Risks / follow-ups

  • Poll window is bounded (overlap buffer + 24h max-lookback floor) so a long outage can't produce an oversized history response; worst case is a missed pre-window change, recoverable by a manual scan.
  • Client repos (silo-android, silo-apple) need no changes — admin-only server feature, no client-visible API surface.

Note on the diff

This branch was cut before the vitest-4 hotfix (#42) merged, so the diff includes one unrelated file, web/src/lib/recipes.test.ts. That is the exact change in #42; once #42 merges and this branch is rebased onto main, git drops it as a duplicate. It does not double-apply.

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • New Features
    • Autoscan: Automatically triggers library scans when new media is detected from enabled integrations
    • Added Autoscan admin tab with global settings (enable/disable, poll interval, debounce), per-source configuration, manual trigger, and status display
    • Path rewrite suggestions to help map import paths to media folders

@coderabbitai

coderabbitai Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This pull request implements autoscan polling and rewrite suggestions for Silo. It adds a new internal/autoscan package with polling orchestration, path rewriting, Radarr/Sonarr history polling, database persistence, and Redis-backed suppression. A new admin UI tab provides settings management, per-source configuration, and interactive rewrite suggestion syncing. Database migrations define new autoscan_settings and autoscan_sources tables. The implementation includes comprehensive tests and design documentation.

Changes

Autoscan polling and rewrite sync

Layer / File(s) Summary
Schema, types, and persistence
internal/autoscan/types.go, internal/autoscan/errors.go, internal/autoscan/repository.go, migrations/171_autoscan.*
Core data types (Settings, PathRewrite, Source), error sentinel, and Postgres-backed repository with methods for reading/writing global settings, querying all or enabled sources, upserting sources, and advancing last-poll timestamps.
Path helpers and ARR history polling
internal/autoscan/dedupe.go, internal/autoscan/dedupe_test.go, internal/autoscan/rewrite.go, internal/autoscan/rewrite_test.go, internal/autoscan/history.go, internal/autoscan/history_test.go
Deduplicates imported paths by parent directory, applies first-matching path rewrite rules at segment boundaries, and polls Radarr/Sonarr history via /api/v3/history/since to extract changed file paths from import/rename events.
Suppression and poll orchestration
internal/autoscan/suppress.go, internal/autoscan/service.go, internal/autoscan/service_test.go
Implements Redis-backed TTL-based suppression (fail-open) and Service.PollOnce that retrieves enabled sources, fetches history, rewrites/dedupes paths, resolves scan targets, claims suppression keys, enqueues scans, and advances last-poll timestamps; includes tests for deduping, disabled no-op, source failures, and enqueue rollback.
Rewrite suggestion matching and adapters
internal/autoscan/suggest.go, internal/autoscan/suggest_deps.go, internal/autoscan/suggest_test.go
Pure suffix-based matcher normalizing paths and classifying roots as proposed (unique best match), ambiguous (tied matches), unmatched, or covered (already rewritten); adapters fetch Radarr root folders and Silo catalog paths; Service.SuggestRewrites orchestrates API key resolution and returns suggestions.
HTTP handlers, routing, and task wiring
internal/api/handlers/autoscan.go, internal/api/handlers/autoscan_test.go, internal/api/router.go, internal/taskmanager/tasks/autoscan_poll.go, cmd/silo/main.go
Handlers for settings (get/update), sources (list/upsert), trigger (manual poll), status, and rewrite suggestions; error mapping for 404/502; periodic task registration; conditional service/task wiring when FolderRepo and LibraryScanQueue are available.
Frontend API types, hooks, and admin UI
web/src/api/types.ts, web/src/hooks/queries/keys.ts, web/src/hooks/queries/useAutoscan.ts, web/src/pages/AdminRequests.tsx
TypeScript interfaces for autoscan settings, sources, and rewrite suggestions; React Query hooks for querying/mutating settings, sources, and suggestions; admin request page tab and AutoscanTab UI component with global settings form, per-source editor with rewrite list management, rewrite suggestion sync/preview/selection, and last-poll display.
Polling and rewrite-sync implementation plans
docs/superpowers/plans/2026-06-02-autoscan-arr-polling.md, docs/superpowers/plans/2026-06-02-autoscan-rewrite-sync.md
End-to-end implementation roadmaps covering database design, Go types, helpers, history client, repository, suppression, service, task wiring, API handlers, frontend hooks/UI, verification steps, and test expectations.
Polling and rewrite-sync design specifications
docs/superpowers/specs/2026-06-02-autoscan-arr-polling-design.md, docs/superpowers/specs/2026-06-02-autoscan-rewrite-sync-design.md
Architecture documentation describing poll cycle semantics, task scheduling, Redis suppression, admin API surface, path normalization rules, matching algorithm, error mappings, frontend preview/merge behavior, test strategy, and risks.

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

  • Silo-Server/silo-server#8: Introduces internal/scantrigger and scan queue interfaces that autoscan polling depends on to resolve and enqueue target folder scans.

Poem

🐰 A scan that polls the ARR with care,
Finds paths imported hiding there,
Rewrites with sync to map the way,
While Redis dampens scans that stray,
Now folders dance in perfect time!
✨ Automation sublime!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 19.35% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'feat(autoscan): periodic Radarr/Sonarr import + rename rescans' is a concise, specific summary that clearly describes the main change: adding autoscan functionality for periodic polling of Radarr/Sonarr to trigger rescans. It is directly related to the primary objective of the changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

fluxis and others added 29 commits June 2, 2026 21:38
Periodic poller over autoscan-enabled Radarr/Sonarr instances (reusing
request_integrations) that maps import paths to Silo media folders and
enqueues targeted scans via the existing scantrigger + scanqueue. Lean
single-service model: no cross-node fan-out guard or retry queue.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Adds ErrIntegrationNotFound sentinel (errors.Is) instead of string matching.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…ure trigger on interval change; skip source on key-resolution error

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…p, boundary-safe rewrites, GREATEST cursor guard, async trigger, quiet unresolved-path skip, FK->404

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rs, re-seed source editor on save

Addresses minor code-review findings: Windows backslash paths now normalized
before rewrite/dedupe; HandleStatus returns repository errors instead of 200;
the per-source editor re-seeds from server data after a save.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add suggestRewrites / commonSuffixLen for Task 1 of the autoscan
arr-polling feature. Pure function: matches arr root-folder paths to
Silo media folder paths by longest common trailing segment count,
adjusted for depth-delta so coincidental same-named segments at
different structural levels don't inflate confidence. Categorises
each arr root as Proposed, Ambiguous, Unmatched, or Covered by an
existing PathRewrite rule. TDD: test file written first, verified
failing, then implementation added.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Add GET /autoscan/sources/{id}/rewrite-suggestions admin endpoint: extend
the autoscanTriggerer interface with SuggestRewrites, wire SetRewriteResolvers
in the router, and add handler + test.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…p no-op suggestions

Addresses final-review edge cases: coveredBy normalizes the existing rewrite's
From (so a stored Windows/dup-slash rule still covers a root); duplicate arr
roots and duplicate Silo folder paths are de-duplicated; an arr path that already
equals its Silo path is not proposed as a no-op rewrite.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
fluxis and others added 4 commits June 2, 2026 21:38
- suggestRewrites initializes Proposed/Unmatched/Ambiguous/Covered to empty
  slices so the JSON response is [] not null — fixes the 'Something went wrong'
  crash when every root is already covered (frontend mapped over null).
- Move the sync button into the Path rewrites card beside 'Add rewrite' and
  rename it 'Sync rewrites'; guard the proposed map with ?? [].

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rites on load

- Root-folder fetch for sync uses a 2-min timeout: Radarr/Sonarr compute
  unmappedFolders by scanning all roots, so a large library's /rootfolder takes
  20-30s+ and tripped arrclient's 30s default (Sonarr 502'd at exactly 30s).
- Spin the sync icon + show 'Syncing…' while the request is in flight.
- Path rewrites card starts collapsed on page load.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
History polling previously only tracked downloadFolderImported events. A
rename in Sonarr/Radarr (episodeFileRenamed / movieFileRenamed) moves a
file without an import event, leaving the library folder stale until the
next full scan.

Extend the history client to also surface renamed paths: both the new
path and the old sourcePath, since a rename can move a file between
folders and both parents may need rescanning. Delete events are still
skipped — upgrade-deletes are covered by the paired import, and standalone
deletes carry no file path in arr history.

Renames the interface method ImportedPaths -> ChangedPaths to reflect the
broader scope.

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

HandleTrigger dispatches PollOnce on a detached goroutine and responds 202
immediately. The test read trig.called straight after the handler returned,
racing the goroutine (usually 'PollOnce was not invoked') and reading the
field without synchronization (a data race under -race).

Signal completion through a channel the fake sends on when PollOnce runs;
the test waits on it (bounded) before asserting. The channel send
happens-before the receive, so the subsequent read of called is race-free.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@fluxis
fluxis force-pushed the feat/autoscan-arr-polling branch from d3ee373 to 98251d0 Compare June 2, 2026 19:39

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 16

🧹 Nitpick comments (2)
internal/autoscan/rewrite_test.go (1)

5-35: ⚡ Quick win

Add test coverage for trailing slashes in To field.

The current tests don't cover the scenario where PathRewrite.To contains a trailing slash. This would help catch the potential double-slash issue flagged in rewrite.go.

🧪 Suggested test case
// Test trailing slash in To field
trailing := []PathRewrite{{From: "/data/media", To: "/mnt/media/"}}
if got := applyRewrites("/data/media/x", trailing); got != "/mnt/media/x" {
	t.Fatalf("trailing slash: got %q, want %q", got, "/mnt/media/x")
}
🤖 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/autoscan/rewrite_test.go` around lines 5 - 35, Add a unit test to
cover trailing slashes in PathRewrite.To: update
internal/autoscan/rewrite_test.go to include a case where PathRewrite{From:
"/data/media", To: "/mnt/media/"} (note trailing slash) is applied via
applyRewrites and assert that applyRewrites("/data/media/x", trailing) returns
"/mnt/media/x" (no double slash). Place this alongside existing cases (e.g., the
"boundary" tests) so we validate trimming/concatenation behavior for
applyRewrites and ensure the function handles trailing slashes in PathRewrite.To
correctly.
internal/autoscan/service_test.go (1)

83-111: ⚡ Quick win

Add a first-enable regression test.

The suite never covers LastPollAt == nil, so it won't catch a poll window that replays history on initial opt-in. A small test double that records the since passed to ChangedPaths would lock in the intended “start at now on first enable” behavior.

🤖 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/autoscan/service_test.go` around lines 83 - 111, Add a test that
covers the initial-enable case where LastPollAt is nil so we verify PollOnce
uses "now" as the since parameter: create a fakeHistory that records the time
argument passed to ChangedPaths, set up a store/advanced entry for an
integration (e.g., "i1") with LastPollAt == nil, call svc.PollOnce, and assert
the recorded since is non-nil and within a small delta of time.Now; reference
the test harness symbols TestPollOnceEnqueuesDedupedFolders (or add
TestPollOnceFirstEnableUsesNow), fakeHistory.ChangedPaths, LastPollAt,
NewService and PollOnce to locate and implement the check.
🤖 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 1335-1344: The autoscan service is being constructed with a nil
debounce/suppressor because deps.RedisClient is not initialized; initialize and
pass the real Redis client into autoscan.NewRedisSuppressor before creating
autoscan.NewService (or replace deps.RedisClient with the existing initialized
Redis client instance used elsewhere), ensuring the symbol chain
autoscan.NewRedisSuppressor(deps.RedisClient) receives a live client prior to
taskMgr.Register(tasks.NewAutoscanPollTask(...)); update the startup sequence so
the Redis client is created/assigned on deps (or use the global/factory helper
that builds the Redis client) before constructing autoscanSvc.

In `@docs/superpowers/plans/2026-06-02-autoscan-arr-polling.md`:
- Line 1019: This line still includes the absolute path /tmp/go/bin (fourth
occurrence); search for and remove any hardcoded /tmp/go/bin usages and replace
them with a non-absolute alternative (e.g., rely on go build ./... without a
hardcoded bin path or use the environment-aware GOBIN/GOPATH via go env) so the
"go build ./..." line and any other occurrences no longer contain an absolute
filesystem path.
- Line 13: Replace the absolute path "/tmp/go/bin" with an environment-agnostic
phrasing: update the sentence that currently reads "The Go toolchain may be at
`/tmp/go/bin` — prepend it to `PATH` if `go` is not found." to something like
"The Go toolchain location may need to be added to PATH if `go` is not found."
so the doc (in docs/superpowers/plans/2026-06-02-autoscan-arr-polling.md) no
longer includes any local absolute filesystem paths and remains
environment-agnostic.
- Line 568: Replace the absolute filesystem path "/tmp/go/bin" used in this
document with a generic placeholder or environment variable reference (e.g.
$GOBIN or <gobin-path>) everywhere it appears; locate the occurrence referenced
alongside the SQL snippet containing "VALUES ($1, $2, $3, now())" and update
that literal path to the placeholder to comply with the docs/superpowers
guidelines.

In `@docs/superpowers/plans/2026-06-02-autoscan-rewrite-sync.md`:
- Line 662: The line "export PATH=$PATH:/tmp/go/bin" contains a local absolute
filesystem path; replace it with a generic placeholder or environment variable
(e.g., export PATH=$PATH:$GOBIN or export PATH=$PATH:<your-go-bin-path>) so the
docs do not include an absolute local path and follow the guideline for docs in
specs/plans.
- Line 13: Remove the local absolute path referenced in the sentence "The Go
toolchain may be at `/tmp/go/bin` — prepend to `PATH` if `go` is missing." and
replace it with environment-agnostic guidance: state that the Go toolchain must
be available on PATH and, if installed in a non-standard location, users should
add its bin directory to PATH or install Go via their platform's package
manager; update the sentence in the docs/superpowers/plans file accordingly
(look for the sentence containing `/tmp/go/bin`) so no absolute filesystem paths
remain.

In `@internal/api/handlers/autoscan_test.go`:
- Around line 154-157: The test creates a request without a chi route context so
HandleUpsertSource’s call to chi.URLParam("id") isn’t exercised; fix the test by
creating a chi RouteContext, calling ctx.URLParams.Add("id","missing") (or
equivalent), and attaching it to the request context before calling
HandleUpsertSource so the handler reads the intended id via chi.URLParam; update
the existing test snippet around httptest.NewRequest/rec to set the route
context on req's context prior to invoking HandleUpsertSource.

In `@internal/api/handlers/autoscan.go`:
- Around line 76-82: The handler currently ignores failures from
h.triggers.UpdateTriggers("autoscan_poll", ...) and returns success even though
the persisted updated.PollIntervalMinutes may not be applied; change this to
either roll back the stored poll interval to the previous value or return an
error to the client. Concretely: capture the previous poll interval before
persisting, call h.triggers.UpdateTriggers(...) and if it returns an error,
attempt to restore the previous value in the same storage/update path you used
earlier (or call the same repo/save method with the previous interval), log the
rollback error if that fails, and return a non-200 error response (e.g., HTTP
500) instead of success; if you cannot implement rollback, immediately return an
error response after logging the UpdateTriggers error so stored config and live
schedule cannot diverge. Ensure you update the code around
h.triggers.UpdateTriggers, autoscan_poll and use updated.PollIntervalMinutes and
the captured previous value to perform the rollback or error response.

In `@internal/api/router.go`:
- Around line 422-436: The autoscan handler is being created even when
deps.TaskManager is nil; update the wiring to require the scheduler by adding a
check for deps.TaskManager != nil to the existing condition that checks
deps.FolderRepo and deps.LibraryScanQueue so autoscan.NewService(...),
autoscanSvc.SetRewriteResolvers(...), and handlers.NewAutoscanHandler(...) only
run when a TaskManager is present; ensure autoscanHandler remains nil when
TaskManager is absent so the admin/polling UI won’t expose periodic features it
cannot configure.

In `@internal/autoscan/repository.go`:
- Around line 159-168: AdvanceLastPoll currently returns a generic error when
Exec fails; mirror GetSource/UpsertSource behavior by mapping a
foreign-key/foreign key violation on integration_id to ErrIntegrationNotFound.
After the r.pool.Exec call in Repository.AdvanceLastPoll, inspect the returned
error (e.g., via errors.As into *pgconn.PgError or by checking SQLSTATE
"23503"/FK constraint name) and if it indicates a FK violation for the
integration_id, return ErrIntegrationNotFound instead of wrapping the original
error; otherwise wrap/return the original error as before. Ensure you reference
Repository.AdvanceLastPoll, r.pool.Exec and ErrIntegrationNotFound so the change
is easy to locate.
- Around line 46-50: The SQL fragment in sourceSelect currently returns all
request_integrations rows; restrict it to supported integration kinds by adding
a WHERE clause filtering ri.kind to the allowed set (e.g., 'radarr' and
'sonarr') in the sourceSelect constant so only those integrations are selected
for the autoscan read path, and ensure any write/update code that creates or
updates autoscan_sources uses the same allowed-kind whitelist so the read and
write boundaries remain consistent (refer to the sourceSelect constant and the
code paths that insert/update autoscan_sources/integration rows).

In `@internal/autoscan/rewrite.go`:
- Around line 14-28: applyRewrites can produce a double slash when rw.To ends
with '/' because the code returns strings.TrimSpace(rw.To) +
strings.TrimPrefix(path, trimmed); normalize rw.To before concatenation by
trimming trailing slashes (e.g., use strings.TrimRight(strings.TrimSpace(rw.To),
"/")) and then concatenate with a single '/' delimiter when needed (or ensure
the trimmed suffix of path has its leading '/' preserved via strings.TrimPrefix
and add '/' only if the normalized rw.To is non-empty and does not already end
with '/'); update the logic in applyRewrites to use the normalized rw.To to
avoid producing "//".

In `@internal/autoscan/service.go`:
- Around line 77-83: The current logic always subtracts pollOverlap from since
even when src.LastPollAt is nil, causing newly-enabled sources to backdate the
first poll; change the logic so that the overlap subtraction only happens when
src.LastPollAt is non-nil: set since = cycleStart by default, and if
src.LastPollAt != nil set since = src.LastPollAt and then apply since =
since.Add(-pollOverlap) (i.e., move the Add(-pollOverlap) inside the LastPollAt
!= nil branch) while keeping the same variable names (since, cycleStart,
pollOverlap, src.LastPollAt) so a newly enabled source won’t replay history.
- Around line 186-191: In SuggestRewrites, secret resolution currently ignores
errors and proceeds with the unresolved APIKeyRef; update the block around
s.secrets.Get to fail fast: when s.secrets != nil and apiKey != "" call
s.secrets.Get(ctx, apiKey) and if rerr != nil return the error (or wrap with
context) instead of treating it as success, otherwise use resolved when
non-empty; this mirrors the behavior in PollOnce and prevents probing Arr with
an unresolved reference (refer to SuggestRewrites and s.secrets.Get).

In `@web/src/hooks/queries/useAutoscan.ts`:
- Around line 87-99: useTriggerAutoscan currently only shows a toast on success
but doesn’t refresh cached autoscan data; inject a QueryClient by calling
useQueryClient() inside useTriggerAutoscan and in the onSuccess handler call
queryClient.invalidateQueries(...) for the same query key used by the autoscan
query (the key used by your useAutoscan / autoscan-related useQuery) so the
admin screen is refetched immediately after a successful trigger.

In `@web/src/pages/AdminRequests.tsx`:
- Around line 1471-1475: handleSave currently filters path_rewrites with a
predicate that allows entries where only one side is filled; update the filter
so only fully-specified mappings are saved by requiring both trimmed fields to
be non-empty (i.e. change the predicate on rewrites.map(...) from
"rewrite.from.length > 0 || rewrite.to.length > 0" to require both non-empty),
keeping the existing trim and then call updateSource.mutate(...) as before
(referencing handleSave, path_rewrites, rewrites, and
updateSource.mutate/source.integration_id).

---

Nitpick comments:
In `@internal/autoscan/rewrite_test.go`:
- Around line 5-35: Add a unit test to cover trailing slashes in PathRewrite.To:
update internal/autoscan/rewrite_test.go to include a case where
PathRewrite{From: "/data/media", To: "/mnt/media/"} (note trailing slash) is
applied via applyRewrites and assert that applyRewrites("/data/media/x",
trailing) returns "/mnt/media/x" (no double slash). Place this alongside
existing cases (e.g., the "boundary" tests) so we validate
trimming/concatenation behavior for applyRewrites and ensure the function
handles trailing slashes in PathRewrite.To correctly.

In `@internal/autoscan/service_test.go`:
- Around line 83-111: Add a test that covers the initial-enable case where
LastPollAt is nil so we verify PollOnce uses "now" as the since parameter:
create a fakeHistory that records the time argument passed to ChangedPaths, set
up a store/advanced entry for an integration (e.g., "i1") with LastPollAt ==
nil, call svc.PollOnce, and assert the recorded since is non-nil and within a
small delta of time.Now; reference the test harness symbols
TestPollOnceEnqueuesDedupedFolders (or add TestPollOnceFirstEnableUsesNow),
fakeHistory.ChangedPaths, LastPollAt, NewService and PollOnce to locate and
implement the check.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 59afd7ab-a07d-4de0-ad2f-bbbea3ae3c37

📥 Commits

Reviewing files that changed from the base of the PR and between d297192 and d3ee373.

📒 Files selected for processing (31)
  • cmd/silo/main.go
  • docs/superpowers/plans/2026-06-02-autoscan-arr-polling.md
  • docs/superpowers/plans/2026-06-02-autoscan-rewrite-sync.md
  • docs/superpowers/specs/2026-06-02-autoscan-arr-polling-design.md
  • docs/superpowers/specs/2026-06-02-autoscan-rewrite-sync-design.md
  • internal/api/handlers/autoscan.go
  • internal/api/handlers/autoscan_test.go
  • internal/api/router.go
  • internal/autoscan/dedupe.go
  • internal/autoscan/dedupe_test.go
  • internal/autoscan/errors.go
  • internal/autoscan/history.go
  • internal/autoscan/history_test.go
  • internal/autoscan/repository.go
  • internal/autoscan/rewrite.go
  • internal/autoscan/rewrite_test.go
  • internal/autoscan/service.go
  • internal/autoscan/service_test.go
  • internal/autoscan/suggest.go
  • internal/autoscan/suggest_deps.go
  • internal/autoscan/suggest_test.go
  • internal/autoscan/suppress.go
  • internal/autoscan/types.go
  • internal/taskmanager/tasks/autoscan_poll.go
  • migrations/171_autoscan.down.sql
  • migrations/171_autoscan.up.sql
  • web/src/api/types.ts
  • web/src/hooks/queries/keys.ts
  • web/src/hooks/queries/useAutoscan.ts
  • web/src/lib/recipes.test.ts
  • web/src/pages/AdminRequests.tsx

Comment thread cmd/silo/main.go Resolved

**Spec:** `docs/superpowers/specs/2026-06-02-autoscan-arr-polling-design.md`

**Commands assume the repository root is the cwd.** Go tests: `go test ./internal/autoscan/...`. Full lint: `make lint`. Frontend: `cd web && pnpm run lint`. The Go toolchain may be at `/tmp/go/bin` — prepend it to `PATH` if `go` is not found. Use the project's disposable test DB for migrations; never touch a live database.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Remove the absolute filesystem path.

The reference to /tmp/go/bin violates the guideline for these documents. As per coding guidelines, docs in docs/superpowers/{specs,plans}/ should never include local absolute filesystem paths. Consider rewording to be environment-agnostic, such as: "The Go toolchain location may need to be added to PATH if go is not found."

Suggested rewording
-**Commands assume the repository root is the cwd.** Go tests: `go test ./internal/autoscan/...`. Full lint: `make lint`. Frontend: `cd web && pnpm run lint`. The Go toolchain may be at `/tmp/go/bin` — prepend it to `PATH` if `go` is not found. Use the project's disposable test DB for migrations; never touch a live database.
+**Commands assume the repository root is the cwd.** Go tests: `go test ./internal/autoscan/...`. Full lint: `make lint`. Frontend: `cd web && pnpm run lint`. The Go toolchain location may need to be added to `PATH` if `go` is not found. Use the project's disposable test DB for migrations; never touch a live database.

As per coding guidelines: When creating or editing docs/superpowers/specs/ or docs/superpowers/plans/, never include local absolute filesystem paths or transient worktree IDs.

📝 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.

Suggested change
**Commands assume the repository root is the cwd.** Go tests: `go test ./internal/autoscan/...`. Full lint: `make lint`. Frontend: `cd web && pnpm run lint`. The Go toolchain may be at `/tmp/go/bin` — prepend it to `PATH` if `go` is not found. Use the project's disposable test DB for migrations; never touch a live database.
**Commands assume the repository root is the cwd.** Go tests: `go test ./internal/autoscan/...`. Full lint: `make lint`. Frontend: `cd web && pnpm run lint`. The Go toolchain location may need to be added to `PATH` if `go` is not found. Use the project's disposable test DB for migrations; never touch a live database.
🤖 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-02-autoscan-arr-polling.md` at line 13,
Replace the absolute path "/tmp/go/bin" with an environment-agnostic phrasing:
update the sentence that currently reads "The Go toolchain may be at
`/tmp/go/bin` — prepend it to `PATH` if `go` is not found." to something like
"The Go toolchain location may need to be added to PATH if `go` is not found."
so the doc (in docs/superpowers/plans/2026-06-02-autoscan-arr-polling.md) no
longer includes any local absolute filesystem paths and remains
environment-agnostic.

}
if _, err := r.pool.Exec(ctx, `
INSERT INTO autoscan_sources (integration_id, enabled, path_rewrites, updated_at)
VALUES ($1, $2, $3, now())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Remove the absolute filesystem path.

Same issue as line 13—the /tmp/go/bin reference violates the guideline. Consider using a generic placeholder or environment variable. As per coding guidelines, never include local absolute filesystem paths in docs/superpowers/{specs,plans}/ documents.

Suggested fix
-export PATH=$PATH:/tmp/go/bin
+# Add the Go toolchain to PATH if needed:
+# export PATH=$PATH:<go-toolchain-location>

As per coding guidelines: When creating or editing docs/superpowers/specs/ or docs/superpowers/plans/, never include local absolute filesystem paths.

🤖 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-02-autoscan-arr-polling.md` at line 568,
Replace the absolute filesystem path "/tmp/go/bin" used in this document with a
generic placeholder or environment variable reference (e.g. $GOBIN or
<gobin-path>) everywhere it appears; locate the occurrence referenced alongside
the SQL snippet containing "VALUES ($1, $2, $3, now())" and update that literal
path to the placeholder to comply with the docs/superpowers guidelines.

- [ ] **Step 9.3: Build the whole server**

```bash
go build ./... # requires libvips locally; if unavailable, build ./internal/... ./cmd/... minus the bimg-dependent packages, and rely on CI/Docker for the full build

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Remove the absolute filesystem path.

Fourth occurrence of /tmp/go/bin. Apply the same fix as previous comments to maintain consistency. As per coding guidelines, avoid absolute filesystem paths in these documents.

As per coding guidelines: When creating or editing docs/superpowers/specs/ or docs/superpowers/plans/, never include local absolute filesystem paths.

🤖 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-02-autoscan-arr-polling.md` at line 1019, This
line still includes the absolute path /tmp/go/bin (fourth occurrence); search
for and remove any hardcoded /tmp/go/bin usages and replace them with a
non-absolute alternative (e.g., rely on go build ./... without a hardcoded bin
path or use the environment-aware GOBIN/GOPATH via go env) so the "go build
./..." line and any other occurrences no longer contain an absolute filesystem
path.


**Spec:** `docs/superpowers/specs/2026-06-02-autoscan-rewrite-sync-design.md`

**Commands assume the repository root is the cwd.** Go tests: `go test ./internal/autoscan/...`. Frontend: `cd web && pnpm exec tsc -b && pnpm run lint`. The Go toolchain may be at `/tmp/go/bin` — prepend to `PATH` if `go` is missing. `internal/api`/`internal/api/handlers` cannot be compiled without libvips; verify those via `gofmt` + the Docker build.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Remove the absolute filesystem path.

The reference to /tmp/go/bin violates the guideline. As per coding guidelines, docs in docs/superpowers/{specs,plans}/ should never include local absolute filesystem paths. Use environment-agnostic wording instead.

Suggested rewording
-**Commands assume the repository root is the cwd.** Go tests: `go test ./internal/autoscan/...`. Frontend: `cd web && pnpm exec tsc -b && pnpm run lint`. The Go toolchain may be at `/tmp/go/bin` — prepend to `PATH` if `go` is missing. `internal/api`/`internal/api/handlers` cannot be compiled without libvips; verify those via `gofmt` + the Docker build.
+**Commands assume the repository root is the cwd.** Go tests: `go test ./internal/autoscan/...`. Frontend: `cd web && pnpm exec tsc -b && pnpm run lint`. The Go toolchain location may need to be added to `PATH` if `go` is missing. `internal/api`/`internal/api/handlers` cannot be compiled without libvips; verify those via `gofmt` + the Docker build.

As per coding guidelines: When creating or editing docs/superpowers/specs/ or docs/superpowers/plans/, never include local absolute filesystem paths or transient worktree IDs.

📝 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.

Suggested change
**Commands assume the repository root is the cwd.** Go tests: `go test ./internal/autoscan/...`. Frontend: `cd web && pnpm exec tsc -b && pnpm run lint`. The Go toolchain may be at `/tmp/go/bin` — prepend to `PATH` if `go` is missing. `internal/api`/`internal/api/handlers` cannot be compiled without libvips; verify those via `gofmt` + the Docker build.
**Commands assume the repository root is the cwd.** Go tests: `go test ./internal/autoscan/...`. Frontend: `cd web && pnpm exec tsc -b && pnpm run lint`. The Go toolchain location may need to be added to `PATH` if `go` is missing. `internal/api`/`internal/api/handlers` cannot be compiled without libvips; verify those via `gofmt` + the Docker build.
🤖 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-02-autoscan-rewrite-sync.md` at line 13,
Remove the local absolute path referenced in the sentence "The Go toolchain may
be at `/tmp/go/bin` — prepend to `PATH` if `go` is missing." and replace it with
environment-agnostic guidance: state that the Go toolchain must be available on
PATH and, if installed in a non-standard location, users should add its bin
directory to PATH or install Go via their platform's package manager; update the
sentence in the docs/superpowers/plans file accordingly (look for the sentence
containing `/tmp/go/bin`) so no absolute filesystem paths remain.

Comment on lines +14 to +28
func applyRewrites(path string, rewrites []PathRewrite) string {
for _, rw := range rewrites {
from := strings.TrimSpace(rw.From)
if from == "" {
continue
}
// Match only at a path-segment boundary: exact, or prefix followed by '/'.
// This prevents From="/data/media" from rewriting "/data/media2/x".
trimmed := strings.TrimSuffix(from, "/")
if path == trimmed || strings.HasPrefix(path, trimmed+"/") {
return strings.TrimSpace(rw.To) + strings.TrimPrefix(path, trimmed)
}
}
return path
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Potential double-slash in rewritten paths when To has a trailing slash.

Line 24 trims whitespace from rw.To but does not trim trailing slashes. When To ends with / and the path has a prefix match, the result will contain a double slash.

Example:

  • From: /data/media, To: /mnt/media/, path: /data/media/Movies/file.mkv
  • Result: /mnt/media//Movies/file.mkv (double slash)
🔧 Proposed fix to normalize trailing slashes
 func applyRewrites(path string, rewrites []PathRewrite) string {
 	for _, rw := range rewrites {
 		from := strings.TrimSpace(rw.From)
 		if from == "" {
 			continue
 		}
+		to := strings.TrimSpace(strings.TrimSuffix(rw.To, "/"))
 		// Match only at a path-segment boundary: exact, or prefix followed by '/'.
 		// This prevents From="/data/media" from rewriting "/data/media2/x".
 		trimmed := strings.TrimSuffix(from, "/")
 		if path == trimmed || strings.HasPrefix(path, trimmed+"/") {
-			return strings.TrimSpace(rw.To) + strings.TrimPrefix(path, trimmed)
+			return to + strings.TrimPrefix(path, trimmed)
 		}
 	}
 	return path
 }
🤖 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/autoscan/rewrite.go` around lines 14 - 28, applyRewrites can produce
a double slash when rw.To ends with '/' because the code returns
strings.TrimSpace(rw.To) + strings.TrimPrefix(path, trimmed); normalize rw.To
before concatenation by trimming trailing slashes (e.g., use
strings.TrimRight(strings.TrimSpace(rw.To), "/")) and then concatenate with a
single '/' delimiter when needed (or ensure the trimmed suffix of path has its
leading '/' preserved via strings.TrimPrefix and add '/' only if the normalized
rw.To is non-empty and does not already end with '/'); update the logic in
applyRewrites to use the normalized rw.To to avoid producing "//".

Comment on lines +77 to +83
// First enable: last_poll_at null -> floor at cycleStart (don't replay history).
since := cycleStart
if src.LastPollAt != nil {
since = *src.LastPollAt
}
// Overlap buffer absorbs clock skew so boundary events aren't missed.
since = since.Add(-pollOverlap)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don't backdate the first poll window.

When LastPollAt is nil, this still subtracts pollOverlap, so a newly enabled source replays the last two minutes of Arr history despite the comment saying “don't replay history.” That can enqueue stale imports immediately after opt-in.

Suggested fix
 		// First enable: last_poll_at null -> floor at cycleStart (don't replay history).
 		since := cycleStart
 		if src.LastPollAt != nil {
-			since = *src.LastPollAt
+			since = *src.LastPollAt
+			// Overlap buffer absorbs clock skew so boundary events aren't missed.
+			since = since.Add(-pollOverlap)
 		}
-		// Overlap buffer absorbs clock skew so boundary events aren't missed.
-		since = since.Add(-pollOverlap)
 		// Floor the window so a long outage can't produce an oversized history
 		// response that arrclient truncates (permanent stall otherwise).
 		if floor := cycleStart.Add(-maxLookback); since.Before(floor) {
📝 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.

Suggested change
// First enable: last_poll_at null -> floor at cycleStart (don't replay history).
since := cycleStart
if src.LastPollAt != nil {
since = *src.LastPollAt
}
// Overlap buffer absorbs clock skew so boundary events aren't missed.
since = since.Add(-pollOverlap)
// First enable: last_poll_at null -> floor at cycleStart (don't replay history).
since := cycleStart
if src.LastPollAt != nil {
since = *src.LastPollAt
// Overlap buffer absorbs clock skew so boundary events aren't missed.
since = since.Add(-pollOverlap)
}
// Floor the window so a long outage can't produce an oversized history
// response that arrclient truncates (permanent stall otherwise).
if floor := cycleStart.Add(-maxLookback); since.Before(floor) {
🤖 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/autoscan/service.go` around lines 77 - 83, The current logic always
subtracts pollOverlap from since even when src.LastPollAt is nil, causing
newly-enabled sources to backdate the first poll; change the logic so that the
overlap subtraction only happens when src.LastPollAt is non-nil: set since =
cycleStart by default, and if src.LastPollAt != nil set since = src.LastPollAt
and then apply since = since.Add(-pollOverlap) (i.e., move the Add(-pollOverlap)
inside the LastPollAt != nil branch) while keeping the same variable names
(since, cycleStart, pollOverlap, src.LastPollAt) so a newly enabled source won’t
replay history.

Comment on lines +186 to +191
apiKey := src.APIKeyRef
if s.secrets != nil && apiKey != "" {
if resolved, rerr := s.secrets.Get(ctx, apiKey); rerr == nil && resolved != "" {
apiKey = resolved
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Fail fast when secret resolution breaks in SuggestRewrites.

Unlike PollOnce, this silently ignores SecretResolver.Get failures and continues with APIKeyRef as the Arr API key. That turns a secret-resolution failure into a misleading “Arr unreachable” path and can probe Arr with the unresolved reference string.

Suggested fix
 	apiKey := src.APIKeyRef
 	if s.secrets != nil && apiKey != "" {
-		if resolved, rerr := s.secrets.Get(ctx, apiKey); rerr == nil && resolved != "" {
-			apiKey = resolved
-		}
+		resolved, rerr := s.secrets.Get(ctx, apiKey)
+		if rerr != nil {
+			return RewriteSuggestions{}, fmt.Errorf("autoscan: resolve api key: %w", rerr)
+		}
+		if resolved != "" {
+			apiKey = resolved
+		}
 	}
📝 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.

Suggested change
apiKey := src.APIKeyRef
if s.secrets != nil && apiKey != "" {
if resolved, rerr := s.secrets.Get(ctx, apiKey); rerr == nil && resolved != "" {
apiKey = resolved
}
}
apiKey := src.APIKeyRef
if s.secrets != nil && apiKey != "" {
resolved, rerr := s.secrets.Get(ctx, apiKey)
if rerr != nil {
return RewriteSuggestions{}, fmt.Errorf("autoscan: resolve api key: %w", rerr)
}
if resolved != "" {
apiKey = resolved
}
}
🤖 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/autoscan/service.go` around lines 186 - 191, In SuggestRewrites,
secret resolution currently ignores errors and proceeds with the unresolved
APIKeyRef; update the block around s.secrets.Get to fail fast: when s.secrets !=
nil and apiKey != "" call s.secrets.Get(ctx, apiKey) and if rerr != nil return
the error (or wrap with context) instead of treating it as success, otherwise
use resolved when non-empty; this mirrors the behavior in PollOnce and prevents
probing Arr with an unresolved reference (refer to SuggestRewrites and
s.secrets.Get).

Comment on lines +87 to +99
export function useTriggerAutoscan() {
return useMutation({
mutationFn: () =>
api<{ status: string }>("/admin/autoscan/trigger", {
method: "POST",
}),
onSuccess: () => {
toast.success("Autoscan triggered");
},
onError: (err) => {
toast.error(err instanceof Error ? err.message : "Failed to trigger autoscan");
},
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Invalidate autoscan queries after a manual trigger.

A successful trigger changes autoscan state immediately, but this hook only shows a toast. The admin screen will keep showing stale source data until the 30s stale window expires or the user refreshes.

Suggested fix
 export function useTriggerAutoscan() {
+  const queryClient = useQueryClient();
   return useMutation({
     mutationFn: () =>
       api<{ status: string }>("/admin/autoscan/trigger", {
         method: "POST",
       }),
     onSuccess: () => {
       toast.success("Autoscan triggered");
+      queryClient.invalidateQueries({ queryKey: adminKeys.autoscanSources() });
+      queryClient.invalidateQueries({ queryKey: adminKeys.autoscanSettings() });
     },
     onError: (err) => {
       toast.error(err instanceof Error ? err.message : "Failed to trigger autoscan");
     },
   });
 }
📝 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.

Suggested change
export function useTriggerAutoscan() {
return useMutation({
mutationFn: () =>
api<{ status: string }>("/admin/autoscan/trigger", {
method: "POST",
}),
onSuccess: () => {
toast.success("Autoscan triggered");
},
onError: (err) => {
toast.error(err instanceof Error ? err.message : "Failed to trigger autoscan");
},
});
export function useTriggerAutoscan() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: () =>
api<{ status: string }>("/admin/autoscan/trigger", {
method: "POST",
}),
onSuccess: () => {
toast.success("Autoscan triggered");
queryClient.invalidateQueries({ queryKey: adminKeys.autoscanSources() });
queryClient.invalidateQueries({ queryKey: adminKeys.autoscanSettings() });
},
onError: (err) => {
toast.error(err instanceof Error ? err.message : "Failed to trigger autoscan");
},
});
}
🤖 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/hooks/queries/useAutoscan.ts` around lines 87 - 99,
useTriggerAutoscan currently only shows a toast on success but doesn’t refresh
cached autoscan data; inject a QueryClient by calling useQueryClient() inside
useTriggerAutoscan and in the onSuccess handler call
queryClient.invalidateQueries(...) for the same query key used by the autoscan
query (the key used by your useAutoscan / autoscan-related useQuery) so the
admin screen is refetched immediately after a successful trigger.

Comment on lines +1471 to +1475
function handleSave() {
const path_rewrites = rewrites
.map((rewrite) => ({ from: rewrite.from.trim(), to: rewrite.to.trim() }))
.filter((rewrite) => rewrite.from.length > 0 || rewrite.to.length > 0);
updateSource.mutate({ id: source.integration_id, body: { enabled, path_rewrites } });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don't submit half-filled path rewrites.

The current filter keeps rows when either side is non-empty, so entries like from="/arr", to="" still get saved. Those cannot map paths correctly and are easy to create from the blank-row editor.

🧩 Minimal fix
     const path_rewrites = rewrites
       .map((rewrite) => ({ from: rewrite.from.trim(), to: rewrite.to.trim() }))
-      .filter((rewrite) => rewrite.from.length > 0 || rewrite.to.length > 0);
+      .filter((rewrite) => rewrite.from.length > 0 && rewrite.to.length > 0);
📝 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.

Suggested change
function handleSave() {
const path_rewrites = rewrites
.map((rewrite) => ({ from: rewrite.from.trim(), to: rewrite.to.trim() }))
.filter((rewrite) => rewrite.from.length > 0 || rewrite.to.length > 0);
updateSource.mutate({ id: source.integration_id, body: { enabled, path_rewrites } });
function handleSave() {
const path_rewrites = rewrites
.map((rewrite) => ({ from: rewrite.from.trim(), to: rewrite.to.trim() }))
.filter((rewrite) => rewrite.from.length > 0 && rewrite.to.length > 0);
updateSource.mutate({ id: source.integration_id, body: { enabled, path_rewrites } });
🤖 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/AdminRequests.tsx` around lines 1471 - 1475, handleSave
currently filters path_rewrites with a predicate that allows entries where only
one side is filled; update the filter so only fully-specified mappings are saved
by requiring both trimmed fields to be non-empty (i.e. change the predicate on
rewrites.map(...) from "rewrite.from.length > 0 || rewrite.to.length > 0" to
require both non-empty), keeping the existing trim and then call
updateSource.mutate(...) as before (referencing handleSave, path_rewrites,
rewrites, and updateSource.mutate/source.integration_id).

coderabbitai[bot]