[BW-DL-04] Project WorkManager waiting and retry state into Downloads UX #19

Open
opened 2026-09-18 08:46:09 +02:00 by alexander · 1 comment
Owner

Migrated from GitHub issue #109. Forgejo issue: #19. GitHub source content synchronized on 2026-09-19. Migrated issue references below use Forgejo numbers where an equivalent issue exists; historical references without a Forgejo counterpart remain explicit GitHub links.

Classification

Active follow-up from #15 / GitHub PR #106.

Problem / opportunity

BookDownloader marks a retryable transfer attempt Failed before BookDownloadWorker returns Result.retry(). WorkManager then owns backoff/retry. Network constraints can also hold a request waiting for Wi-Fi/unmetered service. The current Downloads UI reads only the durable manifest, so it can say Failed while WorkManager is already retrying, or merely Incomplete while work is intentionally waiting for network conditions.

User value

Listeners can tell the difference between 'BookWave will continue automatically', 'waiting for Wi-Fi', and 'this needs me to retry'.

Scope

  • Add a narrow read-only WorkManager execution-state adapter for the unique work name (server,item).
  • Expose only the facts the presentation policy needs: queued/enqueued, running, constraint-blocked/waiting, retry/backoff where knowable, terminal finished/cancelled.
  • Combine this transient evidence with BW-DL-02's durable recovery presentation state.
  • Show truthful waiting/retrying copy without persisting WorkManager state into Room.
  • Keep the adapter bounded to downloads; do not leak WorkInfo throughout UI/domain code.

Explicitly out of scope

  • Do not mirror WorkManager's state machine in the download manifest/database.
  • Do not alter retry policy/backoff timings unless a separate defect is proven.
  • Do not change network policy settings.
  • No notification/widget work in this slice.
  • No removable-storage handling.

Dependencies

  • BW-DL-02 / #17 — presentation policy.
  • BW-DL-03 / #18 recommended first so row actions are already correct; implementation may be rebased/stacked as appropriate.
  • Parent audit #15 / GitHub PR #106.

Architecture seams affected

  • WorkManagerDownloadScheduler / unique work naming contract.
  • New narrow execution reader/observer at the Android app boundary.
  • Downloads ViewModel/presentation combination.

Server / API assumptions

None. This is Android execution-state evidence only.

Storage / migration implications

None. WorkManager remains the execution source; Room remains the durable manifest/file source.

Privacy / security

WorkInfo tags/input data include profile/server/item identity internally. UI/logging must not expose raw server IDs, item IDs, titles or profile identifiers when the active profile cannot see them. Presentation should use generic state text on title-hidden rows.

Automated-test level

  • Pure tests for durable-state + execution-state precedence.
  • WorkManager adapter tests using supported WorkManager test APIs where practical.
  • Regression: retry-scheduled + manifest Failed renders Retrying, not terminal Failed.
  • Regression: unmetered constraint renders Waiting for Wi-Fi/network rather than Failed.
  • Regression: Paused remains Paused even if stale cancelled WorkInfo exists.

Device / platform acceptance

  • Queue a Wi-Fi-only/manual or smart download with no unmetered network; verify waiting state.
  • Restore Wi-Fi and verify transition to Running/Complete without manual intervention.
  • Force a retryable server/network failure; verify Retrying/backoff rather than terminal Failed.
  • Process restart while constrained/retrying; UI reconstructs from WorkManager + manifest.

Estimated effort

Medium.

Implementation risk

Medium. WorkManager observation can become lifecycle-heavy or state-duplicative if its types leak upward.

After #17/#18.

Acceptance criteria

  • UI distinguishes automatic retry/waiting from terminal failure.
  • WorkManager remains the sole owner of transient execution state.
  • No new Room columns mirror WorkInfo state.
  • Process restart reconstructs the same truthful presentation.
  • Existing exponential retry/network-policy behavior is unchanged.
> Migrated from [GitHub issue #109](https://github.com/AlexanderWilhelmsenBerg/Audiobookshelf-Manager-Claude/issues/109). Forgejo issue: #19. GitHub source content synchronized on 2026-09-19. Migrated issue references below use Forgejo numbers where an equivalent issue exists; historical references without a Forgejo counterpart remain explicit GitHub links. ## Classification Active follow-up from #15 / [GitHub PR #106](https://github.com/AlexanderWilhelmsenBerg/Audiobookshelf-Manager-Claude/pull/106). ## Problem / opportunity `BookDownloader` marks a retryable transfer attempt Failed before `BookDownloadWorker` returns `Result.retry()`. WorkManager then owns backoff/retry. Network constraints can also hold a request waiting for Wi-Fi/unmetered service. The current Downloads UI reads only the durable manifest, so it can say **Failed** while WorkManager is already retrying, or merely Incomplete while work is intentionally waiting for network conditions. ## User value Listeners can tell the difference between 'BookWave will continue automatically', 'waiting for Wi-Fi', and 'this needs me to retry'. ## Scope - Add a narrow read-only WorkManager execution-state adapter for the unique work name `(server,item)`. - Expose only the facts the presentation policy needs: queued/enqueued, running, constraint-blocked/waiting, retry/backoff where knowable, terminal finished/cancelled. - Combine this transient evidence with BW-DL-02's durable recovery presentation state. - Show truthful waiting/retrying copy without persisting WorkManager state into Room. - Keep the adapter bounded to downloads; do not leak WorkInfo throughout UI/domain code. ## Explicitly out of scope - Do not mirror WorkManager's state machine in the download manifest/database. - Do not alter retry policy/backoff timings unless a separate defect is proven. - Do not change network policy settings. - No notification/widget work in this slice. - No removable-storage handling. ## Dependencies - **BW-DL-02 / #17** — presentation policy. - **BW-DL-03 / #18** recommended first so row actions are already correct; implementation may be rebased/stacked as appropriate. - Parent audit #15 / [GitHub PR #106](https://github.com/AlexanderWilhelmsenBerg/Audiobookshelf-Manager-Claude/pull/106). ## Architecture seams affected - `WorkManagerDownloadScheduler` / unique work naming contract. - New narrow execution reader/observer at the Android app boundary. - Downloads ViewModel/presentation combination. ## Server / API assumptions None. This is Android execution-state evidence only. ## Storage / migration implications None. WorkManager remains the execution source; Room remains the durable manifest/file source. ## Privacy / security WorkInfo tags/input data include profile/server/item identity internally. UI/logging must not expose raw server IDs, item IDs, titles or profile identifiers when the active profile cannot see them. Presentation should use generic state text on title-hidden rows. ## Automated-test level - Pure tests for durable-state + execution-state precedence. - WorkManager adapter tests using supported WorkManager test APIs where practical. - Regression: retry-scheduled + manifest Failed renders Retrying, not terminal Failed. - Regression: unmetered constraint renders Waiting for Wi-Fi/network rather than Failed. - Regression: Paused remains Paused even if stale cancelled WorkInfo exists. ## Device / platform acceptance - Queue a Wi-Fi-only/manual or smart download with no unmetered network; verify waiting state. - Restore Wi-Fi and verify transition to Running/Complete without manual intervention. - Force a retryable server/network failure; verify Retrying/backoff rather than terminal Failed. - Process restart while constrained/retrying; UI reconstructs from WorkManager + manifest. ## Estimated effort Medium. ## Implementation risk Medium. WorkManager observation can become lifecycle-heavy or state-duplicative if its types leak upward. ## Recommended sequence After #17/#18. ## Acceptance criteria - UI distinguishes automatic retry/waiting from terminal failure. - WorkManager remains the sole owner of transient execution state. - No new Room columns mirror WorkInfo state. - Process restart reconstructs the same truthful presentation. - Existing exponential retry/network-policy behavior is unchanged. ## Links - Parent audit: #15 - Audit PR: [GitHub #106](https://github.com/AlexanderWilhelmsenBerg/Audiobookshelf-Manager-Claude/issues/106) - Depends on: #17, recommended after #18
Author
Owner

BW-DL-04 canonical implementation-readiness record

Status of this record: canonical investigation result. It supersedes the broad implementation sketch in the migrated issue body where current main is more specific.

Investigated main: 88ae231ddc

No branch, production code, PR or CI run was created for this investigation.

1. Prerequisite and overlap status

Item Current Forgejo truth
#17 BW-DL-02 Closed and implemented on current main. The recovery model, safe failure copy, and durable/transient precedence seam are present in domain/download/DownloadRecovery.kt and its tests. I found no Forgejo PR record for the migrated implementation commits; do not invent one. Current code is the proof.
#18 BW-DL-03 Closed and merged. Forgejo PR #55, merge commit df949add9d. Running -> Pause, Paused -> Resume, Failed -> Retry; Queued/Waiting/Retrying/Complete are actionless.
#15 audit Closed. Its durable Room vs transient WorkManager ownership finding still matches current main.
#20 Open removable-storage correctness work. No overlap should be pulled into #19.
#21 Open device-copy semantics work, product-decision blocked. No overlap.
#22 Open discard-partials recovery action. No overlap.
#29 Open live queue/progress/notification work. It explicitly depends on #19. Do not implement #29 here.
Current open PRs PR #90 exists, but its changed files are Android Auto/playback/library startup files only; no #19 implementation seam overlap.

One stale specification detail must not drive this implementation: PRODUCT_SPEC DL-005 still contains a candidate-algorithm line describing uniqueness by profile/server/item. Current production code and ADR-0018 intentionally use one physical work identity per server/item, with profile identity captured only as authorization input. #19 must follow the current code/ADR ownership model.

2. Confirmed current architecture

Current flow is:

User Download/Resume/Retry
→ DownloadsViewModel / DownloadBookUseCase
→ DownloadRepository.request + durable manifest
→ DownloadRepository.markQueued only when resuming durable Paused
→ DownloadScheduler
→ WorkManagerDownloadScheduler
→ unique OneTimeWorkRequest
→ BookDownloadWorker
→ BookDownloader / FileDownloader
→ Room manifest + file rows
→ DownloadsViewModel
→ DownloadRecoveryPolicy
→ DownloadRow / DownloadsScreen

Current seams and ownership:

Path / seam Current responsibility Truth owned
domain/usecase/DownloadBookUseCase.kt Resolves active authorizing profile, permission, assets, free space, durable request/claim, then enqueue Domain orchestration; not execution state
domain/usecase/PauseDownloadUseCase.kt Writes durable Paused before cancelling unique work Durable listener intent
domain/download/DownloadScheduler.kt Platform-neutral enqueue/cancel boundary No state
app/download/WorkManagerDownloadScheduler.kt Creates one-time work, constraints, backoff, unique-work policy WorkManager scheduling
app/download/BookDownloadWorker.kt Runs downloader; Success -> success, retryable AppError -> retry, otherwise failure WorkManager attempt outcome
data/downloads/BookDownloader.kt Transfers incomplete files; on a file failure records durable Failed before returning the AppError Durable manifest outcome
data/downloads/FileDownloader.kt .part/resume/verify/commit; writes file rows Durable file truth
data/downloads/DefaultDownloadRepository.kt Room manifest owner Durable download truth
core/database/dao/DownloadDao.kt Device-wide download manifest queries Durable persistence
core/model/download/OfflineDownload.kt OfflineBook/OfflineFile and durable DownloadState Durable model only
domain/download/DownloadRecovery.kt Pure durable + optional transient presentation policy Presentation policy, no Android type
app/feature/downloads/DownloadsViewModel.kt Device-wide stored rows + active-profile metadata visibility; currently passes no execution evidence Presentation orchestration
app/feature/downloads/DownloadsScreen.kt Renders rows/actions; currently collapses most nonterminal states to “incomplete” UI only
core/common/connectivity/NetworkMonitor.kt Current validated-online and unmetered facts Live connectivity evidence

Important current-main correction: production code does not currently write the book-level durable DownloadState.Running. File rows move while the book row normally remains Queued until Complete, Failed or Paused. Therefore truthful “Downloading” is genuinely transient execution evidence today. Keep support for durable Running because the enum and compatibility policy contain it, but do not add a Room write merely to make Running appear.

The root defect is now exact: BookDownloader records durable Failed whenever a transfer attempt fails. BookDownloadWorker then returns Result.retry() for a retryable AppError. The same logical download is therefore legitimately durable Failed + WorkManager ENQUEUED for another attempt. Current DownloadsViewModel omits executionEvidence when calling DownloadRecoveryPolicy, so it shows terminal Failed even though WorkManager will continue. Constraints have the analogous gap.

3. Unique-work identity contract

The authoritative physical-download identity is BookDownloadWorker.nameFor(serverId, itemId):

download::

Current request contract:

Field Current value
Unique work name BookDownloadWorker.nameFor(serverId, itemId)
Worker BookDownloadWorker
Input profileId authorizing profile captured at enqueue
Input serverId server identity
Input itemId media item identity
Explicit custom tags none today
Network constraint CONNECTED when the category may use cellular; otherwise UNMETERED
Backoff EXPONENTIAL, 30 seconds
Expedited RUN_AS_NON_EXPEDITED_WORK_REQUEST fallback
Normal existing-work policy KEEP
Manual relaxation case REPLACE only when manual cellular is allowed while the existing smart-download policy can be stricter
Cancel cancelUniqueWork(the same name)

Profile identity is not part of physical work identity. A later profile switch must not make the adapter look for a different job. The work request’s profileId is the credential/authorization owner for that attempt.

WorkManager lifecycle implications verified against AndroidX WorkManager APIs:

  • Result.retry() reschedules the same WorkRequest; runAttemptCount becomes useful evidence that ENQUEUED work has already attempted to run.
  • KEEP does nothing when unfinished work with the unique name already exists.
  • REPLACE cancels and deletes pending work with the unique name, then inserts the replacement.
  • cancelUniqueWork may leave terminal/cancelled WorkInfo queryable until pruning.
  • finished WorkInfo can be pruned; missing WorkInfo is normal and must not erase durable Room truth.
  • this worker is one-time work. Periodic-work semantics are irrelevant to #19.

4. Chosen ownership model

The ownership invariant is unchanged:

Room / OfflineBook owns durable physical truth. WorkManager owns transient execution truth. DownloadRecoveryPolicy combines them for presentation. Neither is allowed to impersonate the other.

Consequences:

  • no Room column for WorkInfo state, attempt count, backoff, constraints, work UUID or next-run time;
  • no worker terminal state is used to manufacture durable Complete/Failed;
  • no WorkManager state is exposed outside the Android adapter;
  • no raw WorkInfo, WorkQuery, Constraints, UUID, unique-work name or Android WorkManager type enters ViewModel/domain UI contracts;
  • Finished/cancelled/missing WorkInfo falls back to durable state;
  • durable Paused always wins stale execution evidence;
  • durable valid Complete always wins stale execution evidence.

5. Chosen domain adapter contract

Create:

domain/src/main/kotlin/com/example/shelfplayer/domain/download/DownloadExecutionObserver.kt

with the exact platform-neutral shape:

data class DownloadExecutionKey(
    val serverId: ServerId,
    val itemId: LibraryItemId,
)

interface DownloadExecutionObserver {
    fun observe(
        keys: Set<DownloadExecutionKey>,
    ): Flow<Map<DownloadExecutionKey, DownloadExecutionEvidence>>
}

Semantics:

  • a missing map entry means no known execution evidence;
  • the adapter returns evidence only for requested keys;
  • it never creates a UI row;
  • keys are physical server/item identities, never profile identities;
  • the interface remains download-specific. Do not generalize it into an app-wide WorkManager abstraction.

The existing transient model in domain/download/DownloadRecovery.kt is already the correct narrow model and should be reused unchanged:

DownloadExecutionEvidence Meaning
Queued Work exists and is waiting to be scheduled; no currently provable network blocker and no prior run implying automatic continuation
Running WorkInfo is RUNNING
Waiting ENQUEUED and the request’s known BookWave network constraint is currently unmet
Retrying ENQUEUED, required BookWave network constraint is currently met, and runAttemptCount > 0
Finished WorkInfo is SUCCEEDED or FAILED; durable state decides the user-facing terminal truth
Cancelled WorkInfo is CANCELLED/stale; durable state decides
missing map entry no WorkInfo known / pruned / not discoverable

Do not add Succeeded or Failed as durable-like execution evidence in #19. WorkInfo terminal status says what happened to a WorkRequest, not whether the durable media manifest is valid. BookDownloadWorker also deliberately returns success for malformed/missing identity input, so WorkInfo SUCCEEDED is not sufficient authority for “Downloaded”.

6. Exact WorkInfo mapping

Android WorkManager does not expose “waiting for Wi-Fi” as a WorkInfo.State reason. ENQUEUED only says the work is eligible when constraints/resources allow it. BLOCKED means unfinished prerequisite work, not “constraints are unmet”.

Map WorkInfo as follows:

WorkInfo evidence Adapter result
RUNNING Running
ENQUEUED + required network UNMETERED + NetworkMonitor.isUnmetered == false Waiting
ENQUEUED + required network CONNECTED + NetworkMonitor.isOnline == false Waiting
ENQUEUED + network requirement currently satisfied + runAttemptCount > 0 Retrying
ENQUEUED + network requirement currently satisfied + runAttemptCount == 0 Queued
BLOCKED Queued + generic diagnostic warning; current standalone BookDownloadWorker has no prerequisites, so BLOCKED is unexpected and must not be mislabeled Waiting
SUCCEEDED Finished
FAILED Finished
CANCELLED Cancelled

If an ENQUEUED request has runAttemptCount > 0 and its network constraint is currently unmet, Waiting wins because the present reason BookWave can prove is “cannot run on this network”; when the network becomes allowed it naturally becomes Retrying until WorkManager starts it.

Current scheduler creates only CONNECTED or UNMETERED download constraints. If a future/foreign constraint value appears, #19 must not guess a waiting reason it cannot prove; treat network as not proven-blocking and continue with Queued/Retrying classification, plus a generic non-identifying diagnostic if useful.

Do not use stopReason as the core contract. It is not needed for this distinction, has platform-version limitations, and Result.retry() is not represented as a useful “retry reason” there.

Do not expose nextScheduleTimeMillis as an ETA. Android defines it as the earliest scheduling time after delay/period/backoff, and it does not include every constraint/system condition. It may be useful in adapter tests/diagnostics but not user copy.

Platform references checked during this investigation:

Repository WorkManager version at this SHA is 2.11.2. The APIs required above exist in that version. Do not turn #19 into a WorkManager dependency-upgrade task.

7. Observation and lifecycle design

Forward identity metadata

Modify WorkManagerDownloadScheduler so every new BookDownloadWorker request adds one explicit tag equal to the already-authoritative unique work name:

tag = BookDownloadWorker.nameFor(serverId, itemId)

Compute the name once and use that exact string for both addTag(name) and enqueueUniqueWork(name, ...).

This does not create a second identity scheme and does not change scheduling behavior. It only makes the logical identity recoverable from WorkInfo.tags, because WorkInfo does not expose inputData or the unique-work name itself.

Do not put profileId in tags.

Aggregate observation

The Android implementation belongs in:

app/src/main/kotlin/com/example/shelfplayer/download/WorkManagerDownloadExecutionObserver.kt

It should:

  1. receive only the set of current physical DownloadExecutionKey values whose durable states can be refined (Queued, Running, Failed);
  2. derive each exact authoritative work name with BookDownloadWorker.nameFor;
  3. build one WorkQuery.fromTags(identityTags) and collect WorkManager.getWorkInfosFlow(query);
  4. map each WorkInfo back to a requested key by matching the exact identity tag; never parse serverId/itemId back out of the tag;
  5. combine that aggregate WorkInfo stream with NetworkMonitor.isOnline and NetworkMonitor.isUnmetered;
  6. reduce any WorkInfos for one key deterministically to one DownloadExecutionEvidence;
  7. emit only requested keys.

Reduction if multiple WorkInfo records are returned for one key:

Running > Waiting > Retrying > Queued > Finished > Cancelled

Unique work should prevent multiple active requests. The reduction exists only to be deterministic around retained terminal history/replacement. If multiple simultaneously active records are ever observed, log a generic anomaly count without identities.

This produces one long-lived WorkManager observer for tagged current work, not one observer per row.

Upgrade compatibility for work already enqueued before #19

Current main requests have no explicit identity tag, and a waiting/retrying job may survive an app upgrade/process restart. Do not ignore that case.

At observer start or whenever the requested key set changes:

  • for a key not represented by tagged WorkInfo, perform a bounded one-shot getWorkInfosForUniqueWork(authoritativeName);
  • map the returned legacy WorkInfo UUID(s) to that already-known key at the Android boundary;
  • observe the discovered legacy UUID set with one aggregate getWorkInfosFlow(WorkQuery.fromIds(ids));
  • merge legacy evidence with tagged evidence using the same reduction;
  • limit/constrain the one-shot discovery work rather than launching hundreds of simultaneous lookups on a very large Downloads screen.

No legacy UUID/name mapping is persisted. After a replacement/re-enqueue on #19 code, the new request has the identity tag and naturally moves to the normal aggregate path.

Rejected alternatives:

Alternative Why rejected
One getWorkInfosForUniqueWorkFlow per row O(number of rows) long-lived WorkManager observers; avoidable
Batch query by unique names only WorkInfo does not carry the unique-work name, so returned rows cannot be safely mapped back to server/item
Read WorkInfo inputData WorkInfo does not expose request input data
Infer identity by splitting the string tag/name Duplicates/depends on serialization details; use exact-name lookup from known keys instead
Persist WorkRequest UUID or WorkInfo state in Room Violates the issue’s ownership invariant
New tags only, no legacy bootstrap Misreports already-enqueued work after an app upgrade
Generic app-wide WorkManager observer abstraction Out of scope and unnecessary

ViewModel lifecycle

Inject DownloadExecutionObserver into DownloadsViewModel.

Use downloads.observeAll() as the durable row source. For each durable emission, derive the set of keys needing transient refinement and flatMapLatest into executionObserver.observe(keys). Combine the resulting durable rows + execution map with existing totalBytes and active-profile visibleBooks.

Collection remains governed by the existing Downloads uiState:

viewModelScope + SharingStarted.WhileSubscribed(5_000)

Expected lifecycle:

  • entering/collecting Downloads starts Room + execution observation;
  • leaving it cancels observation after the existing five-second stop timeout;
  • flatMapLatest cancels the old key-set observer when device download rows change;
  • NetworkMonitor callbackFlows clean themselves up on cancellation;
  • process restart rebuilds transient evidence from WorkManager’s own database + current network state; no in-memory cache is authoritative.

A profile switch should normally not change the execution key set, because this screen is device-wide. It changes visibleBooks/title access only.

8. Durable × transient presentation truth table

This is the complete required policy. It matches the existing DownloadRecoveryPolicy and should remain the single owner.

Durable manifest no evidence Queued Waiting Running Retrying Finished Cancelled
Complete + all manifest files complete Complete Complete Complete Complete Complete Complete Complete
Complete + manifest files not all complete Failed Failed Failed Failed Failed Failed Failed
Paused Paused Paused Paused Paused Paused Paused Paused
Queued Queued Queued Waiting Running Retrying Queued Queued
Running Running Queued Waiting Running Retrying Running Running
Failed Failed Queued Waiting Running Retrying Failed Failed

Required scenario interpretations:

Scenario Required UX
manifest Failed + WorkManager automatic retry/backoff Retrying; no terminal failure copy/action
manifest Failed + no automatic WorkManager execution Failed; Retry action
incomplete/Queued + unmet requested network Waiting
incomplete/Queued + RUNNING WorkInfo Running
Paused + stale CANCELLED/RUNNING/ENQUEUED WorkInfo Paused
Complete + stale WorkInfo Complete
missing/pruned WorkInfo durable fallback
cancelled WorkInfo durable fallback
WorkInfo SUCCEEDED before Room Flow emits Complete Finished collapses to durable fallback briefly; never manufacture Complete from WorkInfo
process restart reconstruct from WorkManager + Room
user Retry from durable Failed durable may remain Failed; active new WorkInfo refines to Queued/Waiting/Running/Retrying until Room reaches Complete or terminal Failed
user Resume from Paused markQueued changes durable Paused -> Queued before enqueue; execution then refines it
automatic retry succeeds while UI absent Room Complete on reopen; Complete wins even if WorkInfo is terminal/pruned

Invalid/unexpected combinations degrade conservatively rather than writing state back:

  • Complete + active WorkInfo: Complete wins; assume execution evidence is stale.
  • Paused + active/cancelled WorkInfo: Paused wins; explicit listener intent is durable.
  • Complete book row whose files are not actually complete: Failed wins; existing conservative #17 rule.
  • BLOCKED WorkInfo: Queued, not Waiting; current download work has no prerequisite chain.
  • durable Running + terminal/missing work: keep durable Running. Production does not currently write this state, so this is compatibility/conservative behavior, not a reason for #19 to invent a repair transition.
  • durable Queued + terminal/missing work: keep Queued. If that becomes a persistent real-world orphan, record a separate scheduler/repair defect rather than making #19 mutate Room.

9. User-facing copy and actions

Do not redesign the row. Replace the generic “incomplete” projection with explicit recovery-state copy.

Exact English semantic copy for this slice:

Recovery state Row status
Complete no new status label
Paused existing “Paused”
Queued “Queued”
Running “Downloading”
Waiting “Waiting for an allowed network”
Retrying “Retrying automatically”
Failed with visible safe summary existing safe failure summary
Failed without exposed summary, including title-hidden row “Download failed”

“Waiting for an allowed network” is deliberate. The project already treats Android metering state as source of truth: Wi-Fi can be metered and cellular can be unmetered. Literal “Waiting for Wi-Fi” can therefore be false even when the UNMETERED constraint is the real rule.

Add equivalent Norwegian Bokmål strings in values-nb.

Keep #18 row actions exactly:

State Action
Running Pause
Paused Resume
Failed Retry
Queued none
Waiting none
Retrying none
Complete none

Automatic continuation must not expose Retry while BookWave/WorkManager is already going to continue.

No percent/bytes/live progress, no queue section redesign, no notification changes. Those belong to #29.

10. Privacy and profile isolation

The Downloads screen intentionally shows device-wide physical rows, while title/author visibility comes from the active profile. #19 must preserve this exact split.

Rules:

  • Execution evidence may only refine a Room row already present in downloads.observeAll(). WorkInfo alone never creates a row.
  • Never scope physical work observation by active profile.
  • Never put profileId in WorkManager tags.
  • Never log the unique work name, identity tag, inputData, WorkInfo.toString(), serverId, itemId or profileId.
  • Generic adapter diagnostics may log state/anomaly counts only.
  • The explicit identity tag contains the same raw server/item identity already present in the internal unique-work name. Treat it as internal sensitive implementation data and never surface it.
  • A title-hidden/locked/inaccessible row keeps title and author null and keeps failureSummary redacted exactly as today.
  • Generic state text such as Waiting, Retrying or Download failed is allowed on a hidden row because it reveals execution condition, not media identity.
  • Do not put raw identities into Compose content descriptions, semantics/test tags, notification copy or error messages.
  • Profile switch changes metadata visibility, not WorkManager ownership. A worker continues with the profileId captured when it was enqueued.

11. Process-death and stale-state acceptance model

Timeline Required result
Waiting on an allowed/unmetered network → process killed → reopen still constrained Waiting
Retrying/backoff → process killed → reopen before retry Retrying
Retry succeeds while UI absent → reopen Complete from Room, regardless of pruned/terminal WorkInfo
User pauses → cancellation remains queryable Paused immediately and after restart
WorkInfo pruned, manifest remains durable fallback; Complete/Failed/Paused remain truthful
Profile switch while previous profile-authorized work exists same physical row/execution state; metadata re-redacted for the new profile
Worker enters RUNNING between Room and WorkInfo emissions Running may refine stale Queued/Failed as soon as execution Flow emits
Room reaches Complete before stale WorkInfo clears Complete wins immediately
User Retry from Failed Queued/Waiting/Running/Retrying while active; Failed only when no automatic continuation remains
User Resume from Paused Queued then execution-refined; partial/committed bytes preserved by existing downloader

12. Exact implementation surface

File Required change
domain/src/main/kotlin/com/example/shelfplayer/domain/download/DownloadExecutionObserver.kt Create. DownloadExecutionKey + DownloadExecutionObserver Flow<Map<...>> contract. No Android imports.
domain/src/main/kotlin/com/example/shelfplayer/domain/download/DownloadRecovery.kt Reuse existing DownloadExecutionEvidence and DownloadRecoveryPolicy. No new durable state. Only KDoc clarification if needed.
app/src/main/kotlin/com/example/shelfplayer/download/WorkManagerDownloadScheduler.kt Compute authoritative work name once; add the same name as explicit request tag; otherwise keep constraints/backoff/KEEP/REPLACE behavior unchanged.
app/src/main/kotlin/com/example/shelfplayer/download/WorkManagerDownloadExecutionObserver.kt Create. WorkManager + NetworkMonitor adapter, tagged aggregate observation, legacy UUID bootstrap, WorkInfo mapping/reduction, redacted diagnostics.
app/src/main/kotlin/com/example/shelfplayer/download/BookDownloadWorker.kt No behavior change required. Continue to own nameFor and input constants. Do not add presentation logic.
app/src/main/kotlin/com/example/shelfplayer/di/AppModule.kt Bind WorkManagerDownloadExecutionObserver as singleton DownloadExecutionObserver.
app/src/main/kotlin/com/example/shelfplayer/feature/downloads/DownloadsViewModel.kt Inject observer; combine durable rows with execution map; pass evidence into DownloadRecoveryPolicy.resolve; keep title/failure redaction and #18 action routing.
app/src/main/kotlin/com/example/shelfplayer/feature/downloads/DownloadsScreen.kt Render explicit recovery-state status copy. Keep row layout/actions otherwise unchanged.
app/src/main/res/values/strings.xml Add Queued / Downloading / Waiting for an allowed network / Retrying automatically / generic Download failed strings.
app/src/main/res/values-nb/strings.xml Add equivalent Bokmål copy.
gradle/libs.versions.toml Add androidx.work:work-testing alias at the existing androidxWork 2.11.2 version if the adapter integration tests use WorkManagerTestInitHelper.
app/build.gradle.kts Add work-testing as testImplementation if used. No production dependency change.
domain/src/test/kotlin/com/example/shelfplayer/domain/download/DownloadRecoveryPolicyTest.kt Keep/extend exhaustive precedence proof and explicit named regressions.
app/src/test/kotlin/com/example/shelfplayer/download/WorkManagerDownloadExecutionObserverTest.kt Create. Mapping, identity tags, aggregate/legacy reconstruction and WorkManager test proof.
app/src/test/kotlin/com/example/shelfplayer/download/DownloadWorkPolicyTest.kt Extend only as needed to prove enqueue metadata/identity-tag behavior; keep policy tests.
app/src/test/kotlin/com/example/shelfplayer/feature/downloads/DownloadsViewModelTest.kt Inject fake execution observer and prove durable/transient transitions, profile privacy and stale evidence.
app/src/test/kotlin/com/example/shelfplayer/feature/downloads/DownloadsScreenTest.kt Prove exact status copy and unchanged action semantics.
data/downloads/, core/database/, Room schemas/migrations No change. This is an acceptance invariant, not merely an optimization.
core/common/connectivity/NetworkMonitor.kt / AndroidNetworkMonitor.kt No change. Existing isOnline/isUnmetered facts are sufficient.
notification/foreground progress code No change. #29 owns live progress/notification redesign.

13. Ordered coding sequence

  1. Add the domain DownloadExecutionObserver contract/key without Android types.
  2. Tag newly scheduled BookDownloadWorker requests with the exact authoritative unique-work name; add scheduler metadata tests.
  3. Implement the WorkManager adapter and pure WorkInfo-to-evidence mapping.
  4. Add legacy untagged-work bootstrap and bounded aggregate ID observation.
  5. Bind the adapter in AppModule.
  6. Integrate execution evidence into DownloadsViewModel and feed existing DownloadRecoveryPolicy.
  7. Replace generic incomplete copy with explicit recovery-state copy in DownloadsScreen/strings.
  8. Add/extend pure policy, adapter, ViewModel and Compose tests.
  9. Run normal repository verification only when implementation work begins; this investigation did not start CI.
  10. Perform physical-device acceptance after automated gates are green.

14. Automated test contract

Existing coverage already audited includes:

  • domain DownloadRecoveryPolicyTest;
  • DownloadProfileOwnershipTest;
  • PauseDownloadUseCaseTest;
  • SmartDownloadUseCaseTest;
  • CleanUpDownloadsUseCaseTest;
  • app DownloadWorkPolicyTest;
  • DownloadsViewModelTest;
  • DownloadsScreenTest;
  • data/downloads BookDownloaderTest;
  • DefaultDownloadRepositoryTest;
  • DownloadFailureMappingTest;
  • DownloadStorageRootsTest;
  • DownloadVerifierTest;
  • FileDownloaderTest.

Required new/expanded deterministic proof:

Test Required assertion
Failed + Retrying recovery is Retrying, never terminal Failed; failureSummary absent
Failed + no execution recovery is Failed; Retry remains available
UNMETERED request + isUnmetered false Waiting, not Failed/Retrying
CONNECTED request + isOnline false Waiting
ENQUEUED attempt 0 + allowed network Queued
ENQUEUED attempt > 0 + allowed network Retrying
ENQUEUED attempt > 0 + blocked network Waiting
RUNNING Running
BLOCKED Queued, explicitly not Waiting
SUCCEEDED/FAILED Finished
CANCELLED Cancelled
Paused + stale Cancelled/Running Paused
Complete + any stale execution Complete
Complete row + incomplete files conservative Failed
missing/pruned WorkInfo durable fallback
automatic retry flow Failed durable + Retrying -> Running -> Room Complete
user Retry durable Failed can remain persisted while execution makes row Queued/Waiting/Running/Retrying
user Pause durable Paused wins cancellation race
process reconstruction a new observer instance reconstructs current WorkManager state; no in-memory state required
legacy pre-tag request one-shot unique-name discovery maps UUID and aggregate ID Flow continues tracking it
identity tag tag equals exact BookDownloadWorker.nameFor value; no profile tag
duplicate/retained WorkInfo deterministic active-first reduction
profile switch execution state remains attached to physical key; title/author/failure text is redacted when inaccessible
hidden failed row generic Download failed only; no stored safe detail if title is inaccessible
action semantics Running=Pause, Paused=Resume, Failed=Retry; Waiting/Retrying/Queued none
nextScheduleTime changing it alone does not alter classification
no persistence mirror no Room schema/entity state added for WorkManager

Use WorkManagerTestInitHelper / WorkManager work-testing where it proves WorkManager query/tag/reconstruction behavior. Keep the precedence policy and most state mapping cheap/pure.

Mutation-style proof is valuable in two places and does not require introducing a mutation framework: the domain truth-table tests must fail if active Retrying stops overriding durable Failed or if Paused stops overriding stale execution; the adapter tests must fail if runAttemptCount polarity is reversed or Waiting no longer outranks Retrying when the required network is unmet.

15. Physical/device acceptance plan

Scenario Pass condition
Start a download under Wi-Fi/unmetered-only policy while on disallowed/metered/offline network row says Waiting for an allowed network; no terminal failure/retry action
Restore allowed network Waiting transitions automatically toward Running without listener action
Drop network during an active retryable transfer after the failed attempt, UI says Retrying automatically (or Waiting if network is currently disallowed), not terminal Failed
Keep app alive through retry Retrying -> Running without manual Retry
Kill app while Waiting, reopen still constrained Waiting reconstructs
Kill app during backoff, reopen before next attempt Retrying reconstructs
Let retry finish while UI/app is absent, reopen Complete
Pause a running download Paused immediately; survives process death; stale CANCELLED WorkInfo never relabels it
Resume Paused existing partial/committed bytes are reused; row returns to queued/execution states
Force a non-retryable failure generic/safe failure copy + Retry action; not Retrying
Start in profile A, switch to profile B that cannot see the title physical row may retain generic execution status, but title/author/failure detail remain hidden
Inspect logcat during all scenarios no raw server ID, item ID, profile ID, unique-work name, identity tag or inaccessible title from #19 diagnostics

No removable-SD acceptance belongs here; #20 owns it. No multi-download live progress/notification acceptance belongs here; #29 owns it.

16. Explicit non-goals

  • #29 active queue, live percent/bytes and notification redesign;
  • #20 removable-storage unavailable semantics;
  • #21 device-wide destructive copy/pin semantics;
  • #22 discard-partials UI;
  • new retry/backoff policy;
  • new network-policy settings or “Ask” behavior;
  • Room columns/tables mirroring WorkManager;
  • changing physical-copy identity to include profile;
  • WorkManager 2.12 upgrade;
  • generic WorkManager abstraction for unrelated features;
  • worker progress publication to Downloads UI;
  • altering #18 action policy.

17. Known risks and guardrails

Risk Guardrail
Pre-#19 work has no identity tag bounded legacy unique-name bootstrap + aggregate ID Flow
Large device-wide download list one tagged WorkQuery Flow + at most one legacy ID WorkQuery Flow; no per-row long-lived observers
Raw IDs are present in internal work name/tag never log/surface work names, tags or WorkInfo dumps
Room and WorkManager Flows are not atomic Complete/Paused precedence prevents harmful relabeling; terminal WorkInfo never manufactures durable truth
Connectivity changes during ENQUEUED backoff current unmet allowed-network constraint maps Waiting; when allowed it maps Retrying
Retained historical WorkInfo active-first deterministic reduction; Finished/Cancelled fall back to durable truth
Unexpected BLOCKED Queued + generic diagnostic; never claim Wi-Fi/network waiting from BLOCKED
Durable Running exists in model but is not currently written in production keep compatibility handling; do not add Room writes
WorkManager state can be pruned missing evidence is first-class and falls back to durable state
Literal “Wi-Fi” copy can lie on metered Wi-Fi/unmetered cellular use “Waiting for an allowed network”

18. Unresolved questions

None blocking implementation.

The apparent “Waiting for Wi-Fi” wording ambiguity is resolved in favor of “Waiting for an allowed network” because current BookWave policy and AndroidNetworkMonitor already define Android metering state—not transport name—as the source of truth.

The historical #17 Forgejo-PR provenance gap is documentary only. The prerequisite implementation is present and tested on the exact current main investigated here.

#19 IMPLEMENTATION READY

# BW-DL-04 canonical implementation-readiness record Status of this record: canonical investigation result. It supersedes the broad implementation sketch in the migrated issue body where current main is more specific. Investigated main: **88ae231ddc01897d83e24968bed5443ea861aedd** No branch, production code, PR or CI run was created for this investigation. ## 1. Prerequisite and overlap status | Item | Current Forgejo truth | | --- | --- | | #17 BW-DL-02 | **Closed and implemented on current main.** The recovery model, safe failure copy, and durable/transient precedence seam are present in domain/download/DownloadRecovery.kt and its tests. I found no Forgejo PR record for the migrated implementation commits; do not invent one. Current code is the proof. | | #18 BW-DL-03 | **Closed and merged.** Forgejo PR #55, merge commit df949add9d07f01fd618caafad445d26095a1cd2. Running -> Pause, Paused -> Resume, Failed -> Retry; Queued/Waiting/Retrying/Complete are actionless. | | #15 audit | Closed. Its durable Room vs transient WorkManager ownership finding still matches current main. | | #20 | Open removable-storage correctness work. No overlap should be pulled into #19. | | #21 | Open device-copy semantics work, product-decision blocked. No overlap. | | #22 | Open discard-partials recovery action. No overlap. | | #29 | Open live queue/progress/notification work. It explicitly depends on #19. **Do not implement #29 here.** | | Current open PRs | PR #90 exists, but its changed files are Android Auto/playback/library startup files only; no #19 implementation seam overlap. | One stale specification detail must not drive this implementation: PRODUCT_SPEC DL-005 still contains a candidate-algorithm line describing uniqueness by profile/server/item. Current production code and ADR-0018 intentionally use **one physical work identity per server/item**, with profile identity captured only as authorization input. #19 must follow the current code/ADR ownership model. ## 2. Confirmed current architecture Current flow is: User Download/Resume/Retry → DownloadsViewModel / DownloadBookUseCase → DownloadRepository.request + durable manifest → DownloadRepository.markQueued only when resuming durable Paused → DownloadScheduler → WorkManagerDownloadScheduler → unique OneTimeWorkRequest<BookDownloadWorker> → BookDownloadWorker → BookDownloader / FileDownloader → Room manifest + file rows → DownloadsViewModel → DownloadRecoveryPolicy → DownloadRow / DownloadsScreen Current seams and ownership: | Path / seam | Current responsibility | Truth owned | | --- | --- | --- | | domain/usecase/DownloadBookUseCase.kt | Resolves active authorizing profile, permission, assets, free space, durable request/claim, then enqueue | Domain orchestration; not execution state | | domain/usecase/PauseDownloadUseCase.kt | Writes durable Paused **before** cancelling unique work | Durable listener intent | | domain/download/DownloadScheduler.kt | Platform-neutral enqueue/cancel boundary | No state | | app/download/WorkManagerDownloadScheduler.kt | Creates one-time work, constraints, backoff, unique-work policy | WorkManager scheduling | | app/download/BookDownloadWorker.kt | Runs downloader; Success -> success, retryable AppError -> retry, otherwise failure | WorkManager attempt outcome | | data/downloads/BookDownloader.kt | Transfers incomplete files; on a file failure records durable Failed before returning the AppError | Durable manifest outcome | | data/downloads/FileDownloader.kt | .part/resume/verify/commit; writes file rows | Durable file truth | | data/downloads/DefaultDownloadRepository.kt | Room manifest owner | Durable download truth | | core/database/dao/DownloadDao.kt | Device-wide download manifest queries | Durable persistence | | core/model/download/OfflineDownload.kt | OfflineBook/OfflineFile and durable DownloadState | Durable model only | | domain/download/DownloadRecovery.kt | Pure durable + optional transient presentation policy | Presentation policy, no Android type | | app/feature/downloads/DownloadsViewModel.kt | Device-wide stored rows + active-profile metadata visibility; currently passes no execution evidence | Presentation orchestration | | app/feature/downloads/DownloadsScreen.kt | Renders rows/actions; currently collapses most nonterminal states to “incomplete” | UI only | | core/common/connectivity/NetworkMonitor.kt | Current validated-online and unmetered facts | Live connectivity evidence | Important current-main correction: production code does **not** currently write the book-level durable DownloadState.Running. File rows move while the book row normally remains Queued until Complete, Failed or Paused. Therefore truthful “Downloading” is genuinely transient execution evidence today. Keep support for durable Running because the enum and compatibility policy contain it, but do not add a Room write merely to make Running appear. The root defect is now exact: BookDownloader records durable Failed whenever a transfer attempt fails. BookDownloadWorker then returns Result.retry() for a retryable AppError. The same logical download is therefore legitimately **durable Failed + WorkManager ENQUEUED for another attempt**. Current DownloadsViewModel omits executionEvidence when calling DownloadRecoveryPolicy, so it shows terminal Failed even though WorkManager will continue. Constraints have the analogous gap. ## 3. Unique-work identity contract The authoritative physical-download identity is BookDownloadWorker.nameFor(serverId, itemId): **download:<serverId>:<itemId>** Current request contract: | Field | Current value | | --- | --- | | Unique work name | BookDownloadWorker.nameFor(serverId, itemId) | | Worker | BookDownloadWorker | | Input profileId | authorizing profile captured at enqueue | | Input serverId | server identity | | Input itemId | media item identity | | Explicit custom tags | **none today** | | Network constraint | CONNECTED when the category may use cellular; otherwise UNMETERED | | Backoff | EXPONENTIAL, 30 seconds | | Expedited | RUN_AS_NON_EXPEDITED_WORK_REQUEST fallback | | Normal existing-work policy | KEEP | | Manual relaxation case | REPLACE only when manual cellular is allowed while the existing smart-download policy can be stricter | | Cancel | cancelUniqueWork(the same name) | Profile identity is **not** part of physical work identity. A later profile switch must not make the adapter look for a different job. The work request’s profileId is the credential/authorization owner for that attempt. WorkManager lifecycle implications verified against AndroidX WorkManager APIs: - Result.retry() reschedules the **same WorkRequest**; runAttemptCount becomes useful evidence that ENQUEUED work has already attempted to run. - KEEP does nothing when unfinished work with the unique name already exists. - REPLACE cancels and deletes pending work with the unique name, then inserts the replacement. - cancelUniqueWork may leave terminal/cancelled WorkInfo queryable until pruning. - finished WorkInfo can be pruned; missing WorkInfo is normal and must not erase durable Room truth. - this worker is one-time work. Periodic-work semantics are irrelevant to #19. ## 4. Chosen ownership model The ownership invariant is unchanged: **Room / OfflineBook owns durable physical truth. WorkManager owns transient execution truth. DownloadRecoveryPolicy combines them for presentation. Neither is allowed to impersonate the other.** Consequences: - no Room column for WorkInfo state, attempt count, backoff, constraints, work UUID or next-run time; - no worker terminal state is used to manufacture durable Complete/Failed; - no WorkManager state is exposed outside the Android adapter; - no raw WorkInfo, WorkQuery, Constraints, UUID, unique-work name or Android WorkManager type enters ViewModel/domain UI contracts; - Finished/cancelled/missing WorkInfo falls back to durable state; - durable Paused always wins stale execution evidence; - durable valid Complete always wins stale execution evidence. ## 5. Chosen domain adapter contract Create: **domain/src/main/kotlin/com/example/shelfplayer/domain/download/DownloadExecutionObserver.kt** with the exact platform-neutral shape: data class DownloadExecutionKey( val serverId: ServerId, val itemId: LibraryItemId, ) interface DownloadExecutionObserver { fun observe( keys: Set<DownloadExecutionKey>, ): Flow<Map<DownloadExecutionKey, DownloadExecutionEvidence>> } Semantics: - a missing map entry means **no known execution evidence**; - the adapter returns evidence only for requested keys; - it never creates a UI row; - keys are physical server/item identities, never profile identities; - the interface remains download-specific. Do not generalize it into an app-wide WorkManager abstraction. The existing transient model in domain/download/DownloadRecovery.kt is already the correct narrow model and should be reused unchanged: | DownloadExecutionEvidence | Meaning | | --- | --- | | Queued | Work exists and is waiting to be scheduled; no currently provable network blocker and no prior run implying automatic continuation | | Running | WorkInfo is RUNNING | | Waiting | ENQUEUED and the request’s **known BookWave network constraint is currently unmet** | | Retrying | ENQUEUED, required BookWave network constraint is currently met, and runAttemptCount > 0 | | Finished | WorkInfo is SUCCEEDED or FAILED; durable state decides the user-facing terminal truth | | Cancelled | WorkInfo is CANCELLED/stale; durable state decides | | missing map entry | no WorkInfo known / pruned / not discoverable | Do **not** add Succeeded or Failed as durable-like execution evidence in #19. WorkInfo terminal status says what happened to a WorkRequest, not whether the durable media manifest is valid. BookDownloadWorker also deliberately returns success for malformed/missing identity input, so WorkInfo SUCCEEDED is not sufficient authority for “Downloaded”. ## 6. Exact WorkInfo mapping Android WorkManager does not expose “waiting for Wi-Fi” as a WorkInfo.State reason. ENQUEUED only says the work is eligible when constraints/resources allow it. BLOCKED means unfinished **prerequisite work**, not “constraints are unmet”. Map WorkInfo as follows: | WorkInfo evidence | Adapter result | | --- | --- | | RUNNING | Running | | ENQUEUED + required network UNMETERED + NetworkMonitor.isUnmetered == false | Waiting | | ENQUEUED + required network CONNECTED + NetworkMonitor.isOnline == false | Waiting | | ENQUEUED + network requirement currently satisfied + runAttemptCount > 0 | Retrying | | ENQUEUED + network requirement currently satisfied + runAttemptCount == 0 | Queued | | BLOCKED | Queued + generic diagnostic warning; current standalone BookDownloadWorker has no prerequisites, so BLOCKED is unexpected and must **not** be mislabeled Waiting | | SUCCEEDED | Finished | | FAILED | Finished | | CANCELLED | Cancelled | If an ENQUEUED request has runAttemptCount > 0 **and** its network constraint is currently unmet, Waiting wins because the present reason BookWave can prove is “cannot run on this network”; when the network becomes allowed it naturally becomes Retrying until WorkManager starts it. Current scheduler creates only CONNECTED or UNMETERED download constraints. If a future/foreign constraint value appears, #19 must not guess a waiting reason it cannot prove; treat network as not proven-blocking and continue with Queued/Retrying classification, plus a generic non-identifying diagnostic if useful. Do not use stopReason as the core contract. It is not needed for this distinction, has platform-version limitations, and Result.retry() is not represented as a useful “retry reason” there. Do not expose nextScheduleTimeMillis as an ETA. Android defines it as the earliest scheduling time after delay/period/backoff, and it does not include every constraint/system condition. It may be useful in adapter tests/diagnostics but not user copy. Platform references checked during this investigation: - Android WorkInfo / State: https://developer.android.com/reference/androidx/work/WorkInfo - Android WorkManager query/Flow APIs: https://developer.android.com/reference/androidx/work/WorkManager - Android WorkQuery: https://developer.android.com/reference/androidx/work/WorkQuery - Android ExistingWorkPolicy: https://developer.android.com/reference/androidx/work/ExistingWorkPolicy - Retry/backoff: https://developer.android.com/develop/background-work/background-tasks/persistent/getting-started/define-work Repository WorkManager version at this SHA is **2.11.2**. The APIs required above exist in that version. Do not turn #19 into a WorkManager dependency-upgrade task. ## 7. Observation and lifecycle design ### Forward identity metadata Modify WorkManagerDownloadScheduler so every **new** BookDownloadWorker request adds one explicit tag equal to the already-authoritative unique work name: **tag = BookDownloadWorker.nameFor(serverId, itemId)** Compute the name once and use that exact string for both addTag(name) and enqueueUniqueWork(name, ...). This does not create a second identity scheme and does not change scheduling behavior. It only makes the logical identity recoverable from WorkInfo.tags, because WorkInfo does not expose inputData or the unique-work name itself. Do not put profileId in tags. ### Aggregate observation The Android implementation belongs in: **app/src/main/kotlin/com/example/shelfplayer/download/WorkManagerDownloadExecutionObserver.kt** It should: 1. receive only the set of current physical DownloadExecutionKey values whose durable states can be refined (Queued, Running, Failed); 2. derive each exact authoritative work name with BookDownloadWorker.nameFor; 3. build one WorkQuery.fromTags(identityTags) and collect WorkManager.getWorkInfosFlow(query); 4. map each WorkInfo back to a requested key by matching the exact identity tag; **never parse serverId/itemId back out of the tag**; 5. combine that aggregate WorkInfo stream with NetworkMonitor.isOnline and NetworkMonitor.isUnmetered; 6. reduce any WorkInfos for one key deterministically to one DownloadExecutionEvidence; 7. emit only requested keys. Reduction if multiple WorkInfo records are returned for one key: **Running > Waiting > Retrying > Queued > Finished > Cancelled** Unique work should prevent multiple active requests. The reduction exists only to be deterministic around retained terminal history/replacement. If multiple simultaneously active records are ever observed, log a generic anomaly count without identities. This produces one long-lived WorkManager observer for tagged current work, not one observer per row. ### Upgrade compatibility for work already enqueued before #19 Current main requests have no explicit identity tag, and a waiting/retrying job may survive an app upgrade/process restart. Do not ignore that case. At observer start or whenever the requested key set changes: - for a key not represented by tagged WorkInfo, perform a bounded one-shot getWorkInfosForUniqueWork(authoritativeName); - map the returned legacy WorkInfo UUID(s) to that already-known key **at the Android boundary**; - observe the discovered legacy UUID set with one aggregate getWorkInfosFlow(WorkQuery.fromIds(ids)); - merge legacy evidence with tagged evidence using the same reduction; - limit/constrain the one-shot discovery work rather than launching hundreds of simultaneous lookups on a very large Downloads screen. No legacy UUID/name mapping is persisted. After a replacement/re-enqueue on #19 code, the new request has the identity tag and naturally moves to the normal aggregate path. Rejected alternatives: | Alternative | Why rejected | | --- | --- | | One getWorkInfosForUniqueWorkFlow per row | O(number of rows) long-lived WorkManager observers; avoidable | | Batch query by unique names only | WorkInfo does not carry the unique-work name, so returned rows cannot be safely mapped back to server/item | | Read WorkInfo inputData | WorkInfo does not expose request input data | | Infer identity by splitting the string tag/name | Duplicates/depends on serialization details; use exact-name lookup from known keys instead | | Persist WorkRequest UUID or WorkInfo state in Room | Violates the issue’s ownership invariant | | New tags only, no legacy bootstrap | Misreports already-enqueued work after an app upgrade | | Generic app-wide WorkManager observer abstraction | Out of scope and unnecessary | ### ViewModel lifecycle Inject DownloadExecutionObserver into DownloadsViewModel. Use downloads.observeAll() as the durable row source. For each durable emission, derive the set of keys needing transient refinement and flatMapLatest into executionObserver.observe(keys). Combine the resulting durable rows + execution map with existing totalBytes and active-profile visibleBooks. Collection remains governed by the existing Downloads uiState: **viewModelScope + SharingStarted.WhileSubscribed(5_000)** Expected lifecycle: - entering/collecting Downloads starts Room + execution observation; - leaving it cancels observation after the existing five-second stop timeout; - flatMapLatest cancels the old key-set observer when device download rows change; - NetworkMonitor callbackFlows clean themselves up on cancellation; - process restart rebuilds transient evidence from WorkManager’s own database + current network state; no in-memory cache is authoritative. A profile switch should normally **not** change the execution key set, because this screen is device-wide. It changes visibleBooks/title access only. ## 8. Durable × transient presentation truth table This is the complete required policy. It matches the existing DownloadRecoveryPolicy and should remain the single owner. | Durable manifest | no evidence | Queued | Waiting | Running | Retrying | Finished | Cancelled | | --- | --- | --- | --- | --- | --- | --- | --- | | Complete + all manifest files complete | Complete | Complete | Complete | Complete | Complete | Complete | Complete | | Complete + manifest files not all complete | Failed | Failed | Failed | Failed | Failed | Failed | Failed | | Paused | Paused | Paused | Paused | Paused | Paused | Paused | Paused | | Queued | Queued | Queued | Waiting | Running | Retrying | Queued | Queued | | Running | Running | Queued | Waiting | Running | Retrying | Running | Running | | Failed | Failed | Queued | Waiting | Running | Retrying | Failed | Failed | Required scenario interpretations: | Scenario | Required UX | | --- | --- | | manifest Failed + WorkManager automatic retry/backoff | Retrying; no terminal failure copy/action | | manifest Failed + no automatic WorkManager execution | Failed; Retry action | | incomplete/Queued + unmet requested network | Waiting | | incomplete/Queued + RUNNING WorkInfo | Running | | Paused + stale CANCELLED/RUNNING/ENQUEUED WorkInfo | Paused | | Complete + stale WorkInfo | Complete | | missing/pruned WorkInfo | durable fallback | | cancelled WorkInfo | durable fallback | | WorkInfo SUCCEEDED before Room Flow emits Complete | Finished collapses to durable fallback briefly; never manufacture Complete from WorkInfo | | process restart | reconstruct from WorkManager + Room | | user Retry from durable Failed | durable may remain Failed; active new WorkInfo refines to Queued/Waiting/Running/Retrying until Room reaches Complete or terminal Failed | | user Resume from Paused | markQueued changes durable Paused -> Queued before enqueue; execution then refines it | | automatic retry succeeds while UI absent | Room Complete on reopen; Complete wins even if WorkInfo is terminal/pruned | Invalid/unexpected combinations degrade conservatively rather than writing state back: - Complete + active WorkInfo: Complete wins; assume execution evidence is stale. - Paused + active/cancelled WorkInfo: Paused wins; explicit listener intent is durable. - Complete book row whose files are not actually complete: Failed wins; existing conservative #17 rule. - BLOCKED WorkInfo: Queued, not Waiting; current download work has no prerequisite chain. - durable Running + terminal/missing work: keep durable Running. Production does not currently write this state, so this is compatibility/conservative behavior, not a reason for #19 to invent a repair transition. - durable Queued + terminal/missing work: keep Queued. If that becomes a persistent real-world orphan, record a separate scheduler/repair defect rather than making #19 mutate Room. ## 9. User-facing copy and actions Do not redesign the row. Replace the generic “incomplete” projection with explicit recovery-state copy. Exact English semantic copy for this slice: | Recovery state | Row status | | --- | --- | | Complete | no new status label | | Paused | existing “Paused” | | Queued | “Queued” | | Running | “Downloading” | | Waiting | “Waiting for an allowed network” | | Retrying | “Retrying automatically” | | Failed with visible safe summary | existing safe failure summary | | Failed without exposed summary, including title-hidden row | “Download failed” | “Waiting for an allowed network” is deliberate. The project already treats Android metering state as source of truth: Wi-Fi can be metered and cellular can be unmetered. Literal “Waiting for Wi-Fi” can therefore be false even when the UNMETERED constraint is the real rule. Add equivalent Norwegian Bokmål strings in values-nb. Keep #18 row actions exactly: | State | Action | | --- | --- | | Running | Pause | | Paused | Resume | | Failed | Retry | | Queued | none | | Waiting | none | | Retrying | none | | Complete | none | Automatic continuation must not expose Retry while BookWave/WorkManager is already going to continue. No percent/bytes/live progress, no queue section redesign, no notification changes. Those belong to #29. ## 10. Privacy and profile isolation The Downloads screen intentionally shows **device-wide physical rows**, while title/author visibility comes from the active profile. #19 must preserve this exact split. Rules: - Execution evidence may only refine a Room row already present in downloads.observeAll(). WorkInfo alone never creates a row. - Never scope physical work observation by active profile. - Never put profileId in WorkManager tags. - Never log the unique work name, identity tag, inputData, WorkInfo.toString(), serverId, itemId or profileId. - Generic adapter diagnostics may log state/anomaly counts only. - The explicit identity tag contains the same raw server/item identity already present in the internal unique-work name. Treat it as internal sensitive implementation data and never surface it. - A title-hidden/locked/inaccessible row keeps title and author null and keeps failureSummary redacted exactly as today. - Generic state text such as Waiting, Retrying or Download failed is allowed on a hidden row because it reveals execution condition, not media identity. - Do not put raw identities into Compose content descriptions, semantics/test tags, notification copy or error messages. - Profile switch changes metadata visibility, not WorkManager ownership. A worker continues with the profileId captured when it was enqueued. ## 11. Process-death and stale-state acceptance model | Timeline | Required result | | --- | --- | | Waiting on an allowed/unmetered network → process killed → reopen still constrained | Waiting | | Retrying/backoff → process killed → reopen before retry | Retrying | | Retry succeeds while UI absent → reopen | Complete from Room, regardless of pruned/terminal WorkInfo | | User pauses → cancellation remains queryable | Paused immediately and after restart | | WorkInfo pruned, manifest remains | durable fallback; Complete/Failed/Paused remain truthful | | Profile switch while previous profile-authorized work exists | same physical row/execution state; metadata re-redacted for the new profile | | Worker enters RUNNING between Room and WorkInfo emissions | Running may refine stale Queued/Failed as soon as execution Flow emits | | Room reaches Complete before stale WorkInfo clears | Complete wins immediately | | User Retry from Failed | Queued/Waiting/Running/Retrying while active; Failed only when no automatic continuation remains | | User Resume from Paused | Queued then execution-refined; partial/committed bytes preserved by existing downloader | ## 12. Exact implementation surface | File | Required change | | --- | --- | | domain/src/main/kotlin/com/example/shelfplayer/domain/download/DownloadExecutionObserver.kt | **Create.** DownloadExecutionKey + DownloadExecutionObserver Flow<Map<...>> contract. No Android imports. | | domain/src/main/kotlin/com/example/shelfplayer/domain/download/DownloadRecovery.kt | Reuse existing DownloadExecutionEvidence and DownloadRecoveryPolicy. No new durable state. Only KDoc clarification if needed. | | app/src/main/kotlin/com/example/shelfplayer/download/WorkManagerDownloadScheduler.kt | Compute authoritative work name once; add the same name as explicit request tag; otherwise keep constraints/backoff/KEEP/REPLACE behavior unchanged. | | app/src/main/kotlin/com/example/shelfplayer/download/WorkManagerDownloadExecutionObserver.kt | **Create.** WorkManager + NetworkMonitor adapter, tagged aggregate observation, legacy UUID bootstrap, WorkInfo mapping/reduction, redacted diagnostics. | | app/src/main/kotlin/com/example/shelfplayer/download/BookDownloadWorker.kt | **No behavior change required.** Continue to own nameFor and input constants. Do not add presentation logic. | | app/src/main/kotlin/com/example/shelfplayer/di/AppModule.kt | Bind WorkManagerDownloadExecutionObserver as singleton DownloadExecutionObserver. | | app/src/main/kotlin/com/example/shelfplayer/feature/downloads/DownloadsViewModel.kt | Inject observer; combine durable rows with execution map; pass evidence into DownloadRecoveryPolicy.resolve; keep title/failure redaction and #18 action routing. | | app/src/main/kotlin/com/example/shelfplayer/feature/downloads/DownloadsScreen.kt | Render explicit recovery-state status copy. Keep row layout/actions otherwise unchanged. | | app/src/main/res/values/strings.xml | Add Queued / Downloading / Waiting for an allowed network / Retrying automatically / generic Download failed strings. | | app/src/main/res/values-nb/strings.xml | Add equivalent Bokmål copy. | | gradle/libs.versions.toml | Add androidx.work:work-testing alias at the existing androidxWork 2.11.2 version if the adapter integration tests use WorkManagerTestInitHelper. | | app/build.gradle.kts | Add work-testing as testImplementation if used. No production dependency change. | | domain/src/test/kotlin/com/example/shelfplayer/domain/download/DownloadRecoveryPolicyTest.kt | Keep/extend exhaustive precedence proof and explicit named regressions. | | app/src/test/kotlin/com/example/shelfplayer/download/WorkManagerDownloadExecutionObserverTest.kt | **Create.** Mapping, identity tags, aggregate/legacy reconstruction and WorkManager test proof. | | app/src/test/kotlin/com/example/shelfplayer/download/DownloadWorkPolicyTest.kt | Extend only as needed to prove enqueue metadata/identity-tag behavior; keep policy tests. | | app/src/test/kotlin/com/example/shelfplayer/feature/downloads/DownloadsViewModelTest.kt | Inject fake execution observer and prove durable/transient transitions, profile privacy and stale evidence. | | app/src/test/kotlin/com/example/shelfplayer/feature/downloads/DownloadsScreenTest.kt | Prove exact status copy and unchanged action semantics. | | data/downloads/*, core/database/*, Room schemas/migrations | **No change.** This is an acceptance invariant, not merely an optimization. | | core/common/connectivity/NetworkMonitor.kt / AndroidNetworkMonitor.kt | **No change.** Existing isOnline/isUnmetered facts are sufficient. | | notification/foreground progress code | **No change.** #29 owns live progress/notification redesign. | ## 13. Ordered coding sequence 1. Add the domain DownloadExecutionObserver contract/key without Android types. 2. Tag newly scheduled BookDownloadWorker requests with the exact authoritative unique-work name; add scheduler metadata tests. 3. Implement the WorkManager adapter and pure WorkInfo-to-evidence mapping. 4. Add legacy untagged-work bootstrap and bounded aggregate ID observation. 5. Bind the adapter in AppModule. 6. Integrate execution evidence into DownloadsViewModel and feed existing DownloadRecoveryPolicy. 7. Replace generic incomplete copy with explicit recovery-state copy in DownloadsScreen/strings. 8. Add/extend pure policy, adapter, ViewModel and Compose tests. 9. Run normal repository verification only when implementation work begins; this investigation did not start CI. 10. Perform physical-device acceptance after automated gates are green. ## 14. Automated test contract Existing coverage already audited includes: - domain DownloadRecoveryPolicyTest; - DownloadProfileOwnershipTest; - PauseDownloadUseCaseTest; - SmartDownloadUseCaseTest; - CleanUpDownloadsUseCaseTest; - app DownloadWorkPolicyTest; - DownloadsViewModelTest; - DownloadsScreenTest; - data/downloads BookDownloaderTest; - DefaultDownloadRepositoryTest; - DownloadFailureMappingTest; - DownloadStorageRootsTest; - DownloadVerifierTest; - FileDownloaderTest. Required new/expanded deterministic proof: | Test | Required assertion | | --- | --- | | Failed + Retrying | recovery is Retrying, never terminal Failed; failureSummary absent | | Failed + no execution | recovery is Failed; Retry remains available | | UNMETERED request + isUnmetered false | Waiting, not Failed/Retrying | | CONNECTED request + isOnline false | Waiting | | ENQUEUED attempt 0 + allowed network | Queued | | ENQUEUED attempt > 0 + allowed network | Retrying | | ENQUEUED attempt > 0 + blocked network | Waiting | | RUNNING | Running | | BLOCKED | Queued, explicitly not Waiting | | SUCCEEDED/FAILED | Finished | | CANCELLED | Cancelled | | Paused + stale Cancelled/Running | Paused | | Complete + any stale execution | Complete | | Complete row + incomplete files | conservative Failed | | missing/pruned WorkInfo | durable fallback | | automatic retry flow | Failed durable + Retrying -> Running -> Room Complete | | user Retry | durable Failed can remain persisted while execution makes row Queued/Waiting/Running/Retrying | | user Pause | durable Paused wins cancellation race | | process reconstruction | a new observer instance reconstructs current WorkManager state; no in-memory state required | | legacy pre-tag request | one-shot unique-name discovery maps UUID and aggregate ID Flow continues tracking it | | identity tag | tag equals exact BookDownloadWorker.nameFor value; no profile tag | | duplicate/retained WorkInfo | deterministic active-first reduction | | profile switch | execution state remains attached to physical key; title/author/failure text is redacted when inaccessible | | hidden failed row | generic Download failed only; no stored safe detail if title is inaccessible | | action semantics | Running=Pause, Paused=Resume, Failed=Retry; Waiting/Retrying/Queued none | | nextScheduleTime | changing it alone does not alter classification | | no persistence mirror | no Room schema/entity state added for WorkManager | Use WorkManagerTestInitHelper / WorkManager work-testing where it proves WorkManager query/tag/reconstruction behavior. Keep the precedence policy and most state mapping cheap/pure. Mutation-style proof is valuable in two places and does not require introducing a mutation framework: the domain truth-table tests must fail if active Retrying stops overriding durable Failed or if Paused stops overriding stale execution; the adapter tests must fail if runAttemptCount polarity is reversed or Waiting no longer outranks Retrying when the required network is unmet. ## 15. Physical/device acceptance plan | Scenario | Pass condition | | --- | --- | | Start a download under Wi-Fi/unmetered-only policy while on disallowed/metered/offline network | row says Waiting for an allowed network; no terminal failure/retry action | | Restore allowed network | Waiting transitions automatically toward Running without listener action | | Drop network during an active retryable transfer | after the failed attempt, UI says Retrying automatically (or Waiting if network is currently disallowed), not terminal Failed | | Keep app alive through retry | Retrying -> Running without manual Retry | | Kill app while Waiting, reopen still constrained | Waiting reconstructs | | Kill app during backoff, reopen before next attempt | Retrying reconstructs | | Let retry finish while UI/app is absent, reopen | Complete | | Pause a running download | Paused immediately; survives process death; stale CANCELLED WorkInfo never relabels it | | Resume Paused | existing partial/committed bytes are reused; row returns to queued/execution states | | Force a non-retryable failure | generic/safe failure copy + Retry action; not Retrying | | Start in profile A, switch to profile B that cannot see the title | physical row may retain generic execution status, but title/author/failure detail remain hidden | | Inspect logcat during all scenarios | no raw server ID, item ID, profile ID, unique-work name, identity tag or inaccessible title from #19 diagnostics | No removable-SD acceptance belongs here; #20 owns it. No multi-download live progress/notification acceptance belongs here; #29 owns it. ## 16. Explicit non-goals - #29 active queue, live percent/bytes and notification redesign; - #20 removable-storage unavailable semantics; - #21 device-wide destructive copy/pin semantics; - #22 discard-partials UI; - new retry/backoff policy; - new network-policy settings or “Ask” behavior; - Room columns/tables mirroring WorkManager; - changing physical-copy identity to include profile; - WorkManager 2.12 upgrade; - generic WorkManager abstraction for unrelated features; - worker progress publication to Downloads UI; - altering #18 action policy. ## 17. Known risks and guardrails | Risk | Guardrail | | --- | --- | | Pre-#19 work has no identity tag | bounded legacy unique-name bootstrap + aggregate ID Flow | | Large device-wide download list | one tagged WorkQuery Flow + at most one legacy ID WorkQuery Flow; no per-row long-lived observers | | Raw IDs are present in internal work name/tag | never log/surface work names, tags or WorkInfo dumps | | Room and WorkManager Flows are not atomic | Complete/Paused precedence prevents harmful relabeling; terminal WorkInfo never manufactures durable truth | | Connectivity changes during ENQUEUED backoff | current unmet allowed-network constraint maps Waiting; when allowed it maps Retrying | | Retained historical WorkInfo | active-first deterministic reduction; Finished/Cancelled fall back to durable truth | | Unexpected BLOCKED | Queued + generic diagnostic; never claim Wi-Fi/network waiting from BLOCKED | | Durable Running exists in model but is not currently written in production | keep compatibility handling; do not add Room writes | | WorkManager state can be pruned | missing evidence is first-class and falls back to durable state | | Literal “Wi-Fi” copy can lie on metered Wi-Fi/unmetered cellular | use “Waiting for an allowed network” | ## 18. Unresolved questions **None blocking implementation.** The apparent “Waiting for Wi-Fi” wording ambiguity is resolved in favor of “Waiting for an allowed network” because current BookWave policy and AndroidNetworkMonitor already define Android metering state—not transport name—as the source of truth. The historical #17 Forgejo-PR provenance gap is documentary only. The prerequisite implementation is present and tested on the exact current main investigated here. #19 IMPLEMENTATION READY
Sign in to join this conversation.
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
alexander/Audiobookshelf-Manager-Claude#19
No description provided.