super-productivity/docs/plans
Johannes Millan b51bd2c9ca
New focus mode rework (#7411)
* fix(android): avoid false WebView version lockout

* fix(android): add WebView block recovery paths

Builds on the prior authoritative-vs-fallback fix with three layered
recovery mechanisms so users hit by a false BLOCK are never locked out
of their data:

- Last-known-good auto-recovery: persist the highest WebView version
  that has ever loaded the app on this device. A later transient
  mis-read that drops below MIN_CHROMIUM_VERSION is downgraded to WARN.
- "Try anyway" override: third button on the block screen opens an
  AlertDialog with an explicit risk acknowledgment (crashes, render
  failures, possible data loss). Confirming persists an override and
  relaunches the app. Hardened against tapjacking via
  filterTouchesWhenObscured on both the activity and dialog window.
- Override auto-clears once a healthy version is detected, so a future
  genuine block is not silently bypassed.

Also tightens the UA regex (drops the misleading Safari Version/X
fallback that always reads "4.0" and would falsely block) and adds
diagnostic logging gated by Log.isLoggable for field debugging.

Tests: 12 unit tests covering statusForVersion branches, all
applyOverrides paths, and parseMajorVersion edge cases.

Refs #7229

* fix(android): recover tracking after WebView cold start (#7390)

When the WebView is killed in the background (e.g. profile switch on
GrapheneOS) the JS-side state is lost on the next cold start, but the
native foreground tracking service keeps accumulating elapsed time. The
app previously discarded that elapsed time on cold start, leading to
silent data loss for the user.

Recovery flow:
- syncTrackingToService$ detects "no current task + native is tracking"
  on the first emission after hydration and emits a recovery request.
- syncOnResume$ does the same on warm resume.
- processRecovery$ drains requests with exhaustMap, coalescing concurrent
  triggers onto a single in-flight recovery.
- _doRecover syncs the native elapsed time onto the task and dispatches
  setCurrentId, restoring the JS-side tracking state.
- The null→task re-emission in syncTrackingToService$ then calls
  updateTrackingService instead of startTrackingService when native is
  already tracking the same task, preserving the just-reconciled native
  counter (Kotlin's startTracking otherwise resets accumulatedMs).

Supporting changes:
- onResume$ is now a ReplaySubject(1) so cold-start emissions delivered
  before the JS subscriber attaches are still received. The 4 existing
  consumers are idempotent native-queue drains and verified safe.
- parseNativeTrackingData extracted as a top-level pure function with
  shape validation; warning logs use a length-only fingerprint to avoid
  burning user content into the exportable log if the native contract
  ever changes.
- Diagnostic 'source' label ('cold-start' | 'resume') in the recovery
  log line for field triage of any future re-reports.

Tests: 12 unit tests for parseNativeTrackingData against the real
production code, plus 4 helper-level tests for the null→task transition
logic. The pipeline-level tests follow the file's existing pattern of
re-implementing logic due to the IS_ANDROID_WEB_VIEW gate.

Not addressed (out of scope, separate Kotlin work): write-side flush
reliability under aggressive OS kills (flushOnPause$ may not complete
before WebView termination). The recovery covers most cases by reading
the native counter as the source of truth.

* fix(sync): warn before destructive SYNC_IMPORT actions

Previously the 'Server Already Has Data' dialog described a destructive
SYNC_IMPORT as a 'merge' with a primary-colored 'Upload Local Data'
button — leading users to clobber syncing devices' data. The decrypt-
error 'Overwrite Remote' button had similarly understated copy and no
final confirmation gate.

- Rewrite D_SERVER_MIGRATION_CONFIRM body to call out 'overwrite' /
  'replace' / 'other devices'; affirmative button is now 'Replace
  Server Data' with color=warn.
- Rewrite D_DECRYPT_ERROR P3 + button label to make cross-device
  blast radius explicit.
- Gate updatePWAndForceUpload behind a confirmDialog with a stronger
  warning string.
- Add component spec for the migration dialog as a regression guard.

* fix(infra): close db-startup race in supersync e2e stack

pg_isready -U supersync without -d returned OK as soon as postgres
accepted connections to the default database, but during first-run
initdb the server briefly bounced while POSTGRES_DB was created.
supersync's prisma db push then race-failed with P1001.

- Healthcheck now runs psql -d supersync_db -c 'SELECT 1' so it only
  passes once the app's db is queryable.
- Dockerfile.test entrypoint retries prisma db push up to 15x before
  giving up — defense in depth if anything else ever races.

* chore(sync): instrument destructive-recovery paths for next incident

Adds read-only diagnostic logs at the four sites a sync-stuck incident
flows through, so the next occurrence is debuggable from a single log
file without forensic recovery:

- clean-slate.service: snapshot prior vector clock, count + opType
  breakdown of unsynced ops, syncImportReason — captured before any
  mutation
- sync-wrapper.service: forceUpload(triggerSource) typed union stamps
  which error class drove the user into destructive recovery
- remote-ops-processing.service: incoming full-state op shape +
  receiver's prior clock and unsynced-op tally about to be wiped
- credential-store.service: encryptKey state on every fresh disk load,
  length-redacted ([length=N] / [empty]) — surfaces the
  isEncryptionEnabled=true + empty-key smoking-gun signature

No behaviour change. Hot sync paths are untouched (full-state branch is
gated; load() short-circuits on cache). Existing redaction patterns
preserved — keys never logged in plaintext.

* fix(sync): apply incoming SYNC_IMPORT silently with no pending ops

Receiving clients with only already-synced data (no unsynced pending
changes) used to see a conflict dialog when an incoming SYNC_IMPORT
arrived. If the user picked USE_LOCAL — a natural reaction to "your
data may be lost" — forceUploadLocalState() re-uploaded the pre-import
state as a new SYNC_IMPORT, rolling back the import (e.g. encryption
change) for every device.

The originating device already gates the SYNC_IMPORT behind a strong
warning (D_SERVER_MIGRATION_CONFIRM, b761efd8). The receiving-side
dialog is now scoped to the case where unsynced pending user changes
would actually be lost; already-synced store data is no longer treated
as a conflict.

Switches the gate from _hasAnyMeaningfulData (pending OR store) to
_hasMeaningfulPendingOps (pending only) in both the download and
piggyback paths. Drops the now-redundant isEncryptionOnlyChange
short-circuit — under the new gate, PASSWORD_CHANGED SYNC_IMPORTs
without pending ops fall through to silent acceptance for free.

- New unit tests for the silent-accept path on both code paths
- New e2e regression guard (supersync-import-conflict-dialog) — fails
  if the gate ever reverts to including store contents
- supersync-scenarios.md D.1 / D.6 and the flowchart gate updated

* fix(infra): repair supersync test Dockerfile retry CMD

Two bugs in the prisma db push retry loop introduced in 81634a17f2:

1. Shell form CMD wraps the command in /bin/sh -c, so $(seq 1 15) was
   expanded by the outer shell into a multi-line value. Busybox's ash
   refuses `for i in 1\n2\n...\n15; do` with "expected do" and the
   container exited immediately. Switched to exec form so the inner
   sh -c does the expansion in unquoted context where word-splitting
   flattens the newlines.

2. After 15 failed attempts the loop's final exit status was the
   status of `sleep 2` (zero), so `&& node` would still launch the
   server against an unmigrated DB and surface as confusing Prisma
   errors at request time. Replaced break/&& with `exec node
   dist/src/index.js` on success so the loop cannot fall through,
   followed by an explicit exit 1 if the loop ends.

* refactor(sync): tighten SYNC_IMPORT gate naming and inline single-use helper

Inline _hasAnyMeaningfulData at its remaining caller (the snapshot/provider-
switch path) and rename _hasMeaningfulLocalData to _hasMeaningfulStoreData
for parallel naming with _hasMeaningfulPendingOps. Strengthen the silent-
accept piggyback test to assert kind === 'completed' rather than
\!== 'cancelled', and clarify the originating-device cross-reference in the
piggyback (D.6) doc and the IMPORT_CONFLICT diamond in the flowchart.

* test(e2e): use spinner cycle for SYNC_IMPORT silent-accept completion signal

Replace the syncCheckIcon-based completion race with a spinner visible→hidden
cycle. The check icon may be stale from a prior sync, which forced the test
to add a "wait for the new sync to start" guard; the spinner toggles per-sync
and is unambiguous. The conflict dialog still races against completion, so
the test fails fast if a regression brings the dialog back.

* test(schedule): bound safeFormatDate coverage for #7405

Parameterize the existing NG0701 regression spec across every
DateTimeLocales value to prove safeFormatDate handles any locale
a user could configure, and assert that 'en-us' itself never
triggers NG0701 (which would refute the #7405#7383 duplicate
diagnosis if the reporter's dateTimeLocale is 'en-us').

* fix(sync): flush pending writes before SYNC_IMPORT silent-apply gate

Without flushing first, an op captured in OperationCaptureService but not
yet drained to IndexedDB is invisible to getUnsynced(); the gate silently
accepts the import and SyncImportFilterService then discards the
just-landed op as CONCURRENT. Mirrors the upload-path flush.

* docs(sync): align SYNC_IMPORT scenarios with current gate semantics

Rename stale _hasMeaningfulLocalData() refs to _hasMeaningfulStoreData()
and remove the dead Encryption-only flowchart node — PASSWORD_CHANGED
SYNC_IMPORTs without pending ops now fall through the standard gate.

* feat(focusMode): simplify clock styles and improve for #7403

* feat(focusMode): always sync with tracking, add autoStartFocusOnPlay

Lifecycles between focus session and time tracking are now always
linked (pause↔pause, stop↔stop, resume↔resume). The
isSyncSessionWithTracking toggle is removed, which fixes #6731 by
construction (pause-focus now always stops tracking). A new opt-in
flag autoStartFocusOnPlay (default off) lets pressing the play
button on a task also spawn a focus session quietly — the workflow
asked for in #5737.

The settings form gets a two-tier layout: primary controls
(autoStartFocusOnPlay, focusModeSound) and a collapsed Advanced
section for isPauseTrackingDuringBreak, isStartInBackground,
isSkipPreparation, isManualBreakStart. The missing default for
isManualBreakStart is filled in.

Driven by discussion #6781 (~100% of polled Pomodoro+tracking users
want them synced). Design notes:
docs/plans/2026-04-29-focus-mode-time-tracking-sync.md. The
banner→dedicated indicator UI is deferred to a follow-up after the
community picks an anchor.

* feat(focusMode): replace session banner with focus-button countdown indicator

When a focus session is in flight and the rich overlay is closed, the
header focus button shows the inline countdown (with a small `#cycle`
prefix in Pomodoro mode). Clicking the button opens the overlay for
all other actions — pause/resume falls out naturally from the
play-button tracking sync, and skip-break / end-session are one extra
click away via the overlay.

The banner-based surface is removed entirely:
- BannerId.FocusMode and its priority entry are deleted.
- updateBanner$, _getBannerActions, and the banner-action helper
  methods (_handleStartAfterBreak, _handleStartAfterSessionComplete,
  _handlePlayPauseToggle, _handleSkipBreak, _handleEndSession,
  _handleOpenOverlay) are removed from FocusModeEffects.
- closeOverlay() in the overlay no longer spawns a banner — the
  focus-button indicator surfaces automatically when isOverlayShown
  flips to false.

Also fixes the priority-conflict raised in #6781 — focus-session
controls are no longer pre-empted by higher-priority banners
(TakeABreak, CalendarEvent, etc.).

* style: drop stray blank line in focus-mode.bug-5995 spec

* test(e2e): align focus-mode specs with banner-removal + always-sync

The focus-mode rework on this PR introduced three behavior changes that
broke nine existing e2e tests:

- Play button is now disabled until a task is current (sync between
  focus session and tracking is always on).
- The session/break banner surface was removed in favor of the header
  focus-button countdown indicator.
- The isSyncSessionWithTracking toggle no longer exists.

Updates:

- focus-mode-break.spec.ts: beforeEach now starts tracking the seeded
  task so the focus-mode play button is enabled.
- pomodoro-timer-sync-bug-5954.spec.ts: the two "no valid task" tests
  now assert the play button is disabled and the "select task to focus"
  placeholder is shown — the new prevention path replaces the
  showFocusOverlay-on-empty-task fix the original bug shipped.
- pomodoro-timer-sync-bug-5974.spec.ts: the close-overlay assertions
  now check focus-button .focus-running-label instead of <banner>.
- bug-5995-break-resume.spec.ts: skipped — the test exclusively
  exercised banner pause/resume of the break, which no longer exists.
  Break pause/resume from the in-overlay component is covered by the
  48 reducer + 14 component unit tests called out in
  focus-mode-break.spec.ts's existing note.

* test(focusMode): regression for #6731 — pause stops time tracking

Locks in the always-sync behavior promised by the rework: pause in the
focus overlay must clear the current task, even after the overlay is
closed. Without `syncSessionPauseToTracking$` firing this would regress
silently.

* feat(focusMode): migrate legacy isSyncSessionWithTracking flag

Existing users with isSyncSessionWithTracking: true relied on the play
button auto-spawning a focus session. Without a migration, dropping the
old flag would silently turn auto-spawn off for them. Backfill the new
autoStartFocusOnPlay opt-in from the legacy value during loadAllData and
strip the deprecated key from the resulting state.

Also fix stale comments in the bug-6575 spec referencing the removed flag.

* feat(focusMode): show focus-button on mobile while session is active

The header focus-button now doubles as the running-session indicator
(replacing the removed BannerId.FocusMode banner). On mobile it was
hidden to save space, leaving users with no surface to see or open a
running session after the overlay was closed. Surface it on mobile too
when a session/break is in flight; resting state on mobile is unchanged.

* chore(focusMode): drop dead isStartInBackground setting

Its only consumer (autoShowOverlay$) was removed in this rework, so the
checkbox in Advanced no longer affected anything — a footgun for users
who would toggle it expecting an effect. Remove from the form, default
config, translation key index, and en.json. Keep the field on the type
as @deprecated so old persisted configs still deserialize.

* fix(focusMode): migration ordering, paused-state indicator, dead SCSS

Issues caught in multi-agent review:

1. migrateFocusModeConfig was being called AFTER the default-spread, so
   `autoStartFocusOnPlay` was already `false` (from defaults) when the
   `?? \!\!isSyncSessionWithTracking` ran — the legacy `true` was always
   short-circuited away. Real persisted JSON never carries the new key.
   Run migration on the raw incoming config first, then merge defaults
   to backfill missing fields. Update the test fixture so the legacy key
   shape matches real persisted data (no explicit `undefined`); add a
   sanity check and a prototype-pollution defensive case.
   Switch the `in` check to `hasOwnProperty.call` for the same reason.
   Tighten the boolean coerce to `=== true` so a tampered non-bool
   (e.g. string from a hand-edited JSON) cannot flip the migration.

2. The header focus-button `circleVisible` and the new mobile
   `isFocusSessionActive` only counted running sessions/breaks. Pausing
   a focus session made the button vanish on mobile and go blank on
   desktop — the very failure mode the indicator was meant to fix.
   Include `isSessionPaused()` in both gates.

3. The `.focus-btn-wrapper` / `.focus-label` block in
   `main-header.component.scss` is dead code: `focus-button` is its own
   encapsulated component and already styles those classes. Remove.

* test(e2e): assert focus-button countdown stays visible while paused

Two changes:

1. Extend issue-6731 e2e to assert the header focus-button countdown is
   still visible after the user pauses + closes the overlay. This is
   the exact regression the previous commit fixed (paused work session
   used to make `circleVisible` go false, hiding the countdown).

2. Drop the stale "Sync focus sessions with time tracking (plural)"
   typo-verification test from bug-5974 — the label was removed in the
   focus-mode rework, the test was silently passing without asserting
   anything because of an `if (count > 0)` guard.

* test(focusMode): cover cycleLabel + autoStartFocusOnPlay end-to-end

Two new test files closing the highest-risk gaps the multi-agent review
flagged:

1. focus-button.component.spec.ts (unit, 9 cases): pin the cycleLabel
   contract — null for non-Pomodoro, current cycle for work, cycle-1 for
   break (the cycle that just finished), floor at 1, treat 0 as 1. Also
   add a regression guard for circleVisible covering the paused state
   so refactors of selectIsSessionPaused can't silently hide the
   countdown again.

2. auto-start-focus-on-play.spec.ts (e2e, 2 cases): the headline feature
   of the rework had no e2e — verify play→spawn happens with the opt-in
   on (and the overlay stays closed) and does NOT happen with the opt-in
   off (the default). Without this, refactors of
   syncTrackingStartToSession$ could break auto-spawn silently.

* fix(focusMode): restore _focusModeService injection lost in master merge

Master commit a5fb3c4a (#7404, "restore play button on mobile") reverted
the FocusModeService injection along with the isPlayButtonVisible logic
it was originally added for. After merging master into this branch,
isFocusSessionActive (added here for the mobile focus-button indicator)
referenced the deleted property, breaking the CI build with three
TS2339 errors at main-header.component.ts:168-170.

Re-add the import and the private readonly _focusModeService injection.
The need for it is now isolated to this PR's mobile-indicator computed,
not the reverted play-button logic.
2026-05-06 21:11:02 +02:00
..
2026-03-22-advanced-onboarding-design.md feat(onboarding): add lightweight onboarding hints 2026-03-22 19:50:24 +01:00
2026-04-21-schedule-week-range-header.md feat(schedule): add week number and date range to nav header 2026-04-21 21:50:52 +02:00
2026-04-29-focus-mode-time-tracking-sync.md New focus mode rework (#7411) 2026-05-06 21:11:02 +02:00