Skip to content

Implement offline activity package download manager for Learn #1224

Open

Description

@KanishJebaMathewM

Context

The Learn Offline-First roadmap now has three prerequisite foundations in progress:

  • PR #1218: service-worker app shell and offline navigation.
  • PR #1221: versioned native IndexedDB storage foundation.
  • PR #1223: authorized offline activity package manifest API from #1222.

The manifest describes activity resources, eligibility, availability, retrieval URLs, and integrity metadata. Learn now needs a core download manager that can materialize an authorized activity package for offline use without coupling the first implementation to UI, background sync, or offline quiz behavior.

Problem statement

A manifest alone does not make learning materials available offline. Learners need a reliable workflow that fetches only eligible resources, stores response bodies durably, records package state, retries interrupted downloads, verifies reliable content hashes, and removes incomplete or deleted packages safely.

The implementation must keep response-body storage separate from metadata/state storage and must not assume that a previously downloaded package remains authorized forever. It must report partial, failed, revoked, and deleted states explicitly rather than presenting an incomplete package as ready.

Proposed architecture

Implement a reusable, UI-independent downloader module in learn/public/js/.

Manifest and authorization

  • Fetch GET /api/activities/:id/offline-package with the current authenticated session.
  • Treat the server manifest as the authorization source; do not construct download URLs from client-supplied activity or R2 keys.
  • Download only resources whose manifest state is downloadable: true and availability: "available".
  • Treat online_only and unavailable resources as non-downloadable and preserve their states in package progress.
  • If the manifest request returns 401 or 403, do not download or retain new package content and report authorization failure.
  • Do not persist bearer tokens or credentials in IndexedDB or Cache Storage.

Storage responsibilities

  • Use a dedicated versioned Cache Storage namespace for downloaded first-party resource responses, separate from the service-worker shell/navigation caches used by PR feat(learn): add service-worker offline app shell #1218.
  • Use the feat(learn): add versioned IndexedDB storage foundation #1221 IndexedDB wrapper for package metadata and download state. Until domain-specific stores exist, use a documented namespace within the foundation metadata store rather than changing authentication storage or inventing a second persistence layer.
  • Store package identity, manifest version, resource identifiers, expected size/hash metadata, per-resource state, timestamps, failure reason, and completion status.
  • Use deterministic cache keys derived from the server-provided package/resource identity. Never expose or persist private R2 bucket keys.
  • Keep Cache Storage response bodies and IndexedDB metadata consistent: an asset is complete only after its response is stored and its metadata transaction commits.

Download workflow

  • Start from a freshly fetched manifest and create or resume a package record.
  • Reuse already cached resources when their package/resource identity, revision, and integrity metadata still match.
  • Fetch resources sequentially or with a documented small concurrency limit to avoid exhausting low-connectivity devices.
  • Expose progress callbacks/events containing total eligible resources, completed resources, bytes when response lengths are available, and current resource state.
  • Handle network failures, non-success responses, aborted requests, malformed responses, and Cache Storage failures per resource.
  • Retry failed resources explicitly with bounded retry behavior; do not create an unbounded automatic retry loop.
  • Preserve resumable package state after interruption, but never mark a package ready until every eligible downloadable resource succeeds.
  • Verify a supplied reliable SHA-256 content hash before marking an asset complete. If the manifest has no reliable hash, document that integrity verification is unavailable rather than inventing one.
  • Detect manifest changes before resume and invalidate or redownload resources whose revision, URL, size, hash, availability, or downloadability changed.
  • Revalidate the manifest before resuming or completing a package so access changes can be observed.

Deletion

  • Provide an API to delete a package and all cache entries owned by that package.
  • Remove associated IndexedDB state only after Cache Storage deletion succeeds or is confirmed absent.
  • Make deletion idempotent and safe after partial downloads.
  • Do not delete service-worker shell/navigation caches or assets belonging to another package.

Suggested files

  • learn/public/js/learn-downloads.js — core downloader and package-state API.
  • learn/tests/test_downloads.mjs — focused Node tests using real Cache Storage/IndexedDB-compatible test adapters where available, or narrowly scoped test dependencies if required.
  • learn/README.md — architecture, state model, retry/integrity behavior, and local validation commands.

Modify learn/public/activity-detail.html only if a minimal integration seam is needed for a later UI contribution. Do not add visible download controls in this issue.

Package and resource states

Use a documented state model such as:

  • Package: idle, downloading, partial, ready, failed, unauthorized, stale, deleted.
  • Resource: pending, downloading, complete, online_only, unavailable, failed, stale.

The exact names may be refined during implementation, but transitions must be explicit, testable, and must not expose incomplete content as ready.

Acceptance criteria

  • A reusable core download-manager API exists without requiring a UI.
  • It fetches and validates the authorized activity manifest before downloading.
  • It downloads only resources marked downloadable and available.
  • It uses a dedicated Cache Storage namespace, never the service-worker shell/navigation caches.
  • It stores package metadata and per-resource state through the feat(learn): add versioned IndexedDB storage foundation #1221 IndexedDB foundation without persisting credentials.
  • It supports deterministic package/resource cache keys and avoids duplicate downloads when metadata still matches.
  • It exposes meaningful progress state, including resource counts and available byte totals.
  • It handles interruption, failed responses, aborts, and storage failures without claiming completion.
  • It supports bounded retries for failed resources.
  • It verifies reliable supplied SHA-256 hashes before marking resources complete and reports unavailable integrity metadata honestly.
  • It detects manifest/revision changes and marks affected resources or packages stale for redownload.
  • It revalidates authorization before resuming or completing downloads.
  • It handles quota errors explicitly and leaves resumable state where safe.
  • It deletes a package idempotently without affecting other packages or service-worker caches.
  • Focused tests cover successful downloads, eligibility filtering, resume/deduplication, progress, retries, interruption, authorization failure, manifest changes, integrity success/failure, quota/cache failures, and deletion.
  • Documentation describes the API, state transitions, storage separation, limitations, and local testing.

Testing expectations

Add focused tests for:

  • Authorized manifest retrieval and rejection of 401/403.
  • Downloading only eligible available resources.
  • Online-only and unavailable resources remaining non-downloadable.
  • Deterministic cache keys and package isolation.
  • Reusing an unchanged cached resource without a duplicate fetch.
  • Resuming partial state after interruption.
  • Bounded retry behavior and retry exhaustion.
  • Non-success responses, malformed responses, aborts, and Cache Storage failures.
  • Progress reporting with known and unknown byte sizes.
  • SHA-256 verification success, mismatch, and missing-hash behavior.
  • Manifest revision changes, removed resources, and authorization revocation.
  • Quota errors and safe partial-state recovery.
  • Idempotent package deletion and preservation of shell/navigation caches.
  • No persisted authentication tokens, bearer headers, R2 keys, or unrelated learner data.

Use the existing Node test conventions and the actual #1221 wrapper behavior. Do not add a large browser-test framework solely for this feature. Document any browser-only limitations and manually validate Cache Storage and IndexedDB behavior over HTTP where necessary.

Run the focused tests, relevant Learn API/authentication tests, Python compilation if backend files change, and git diff --check.

Security and authorization requirements

  • The server manifest remains authoritative for eligibility and resource URLs.
  • A client must never manufacture an R2 URL or bypass enrollment checks.
  • Do not cache authenticated API responses through the generic service-worker caches.
  • Do not persist access tokens, session credentials, authorization headers, private bucket keys, quiz answer keys, or unrelated learner data.
  • Treat downloaded content as potentially stale after enrollment cancellation or manifest authorization failure; do not silently claim continued authorization.
  • Use same-origin response URLs and preserve normal browser credential/CORS behavior.

Scope boundaries

Explicitly out of scope:

  • Visible activity download buttons, progress UI, package browser, or storage management UI.
  • Service-worker changes or generic API caching.
  • Changes to the activity manifest contract or backend authorization rules except fixes strictly required for downloader compatibility.
  • New D1 migrations or download queue tables.
  • New IndexedDB domain stores if the feat(learn): add versioned IndexedDB storage foundation #1221 metadata foundation can support the necessary namespaced state.
  • Offline quiz-taking, quiz mutation queues, answer synchronization, background synchronization, and conflict resolution.
  • Automatic downloads or prefetching.
  • Cross-device synchronization.
  • Content transcoding, compression, or media streaming.

Dependencies

This work should begin only after the relevant prerequisite behavior is merged into main:

It must remain independently reviewable after those merges and must not be based on or modify the prerequisite branches. The later UI/storage-management contribution may depend on this core downloader API.

Relevant files

  • learn/public/js/learn-downloads.js
  • learn/public/js/learn-storage.js
  • learn/public/service-worker.js
  • learn/public/activity-detail.html
  • learn/tests/test_downloads.mjs
  • learn/tests/test_indexed_db.mjs
  • learn/tests/test_service_worker.mjs
  • learn/README.md
  • learn/wrangler.toml

This issue intentionally establishes the core download engine first. User-facing controls and package management should be a subsequent contribution built on its stable API.

Activity

  1. KanishJebaMathewM commented on Nov 7, 2026

    @KanishJebaMathewM
    Author

    Hi @A1L13N ,

    I've opened #1224 to work on the Offline Activity Package Download Manager.

    This implementation depends on three prerequisite PRs:

    I've completed the initial technical preparation, and the implementation is ready to proceed once these foundations are merged into main.

    Could you please take a look at these PRs when convenient and let me know if any changes or additional work are needed from my side before they can be merged?

    I'd like to get these foundational contributions reviewed and integrated so I can continue with #1224 without creating unnecessary dependencies or stacked PRs.

    Thanks!

  2. added
    2026-11
    on Nov 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    2026-11good first issue

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions