Commit graph

13672 commits

Author SHA1 Message Date
Johannes Millan
59681d47a4 fix(tasks): render colored dots for tags in chip-list-input (#7424)
Replace plain title text with <tag> in chip rows and autocomplete
options so the recurring task config (and the two other consumers of
chip-list-input) show colored dots for both selected chips and dropdown
suggestions, matching the rest of the app.
2026-05-01 19:35:27 +02:00
Johannes Millan
2788ff1e65 feat(tasks): show project icons in move-to-project menu
Closes #7425
2026-05-01 19:35:27 +02:00
Johannes Millan
917d44c259 feat(planner): speed up auto-scroll while dragging tasks
Closes #7422
2026-05-01 19:35:27 +02:00
Johannes Millan
28cc431915 fix(planner): prevent estimate hover input from being clipped
Right-anchor the inline-input when used inside the planner time cell so
the expanding edit field grows leftward instead of bleeding past the
planner-day overflow:hidden boundary.
2026-05-01 19:35:27 +02:00
Johannes Millan
a5fb3c4a05 fix(main-header): restore play button on mobile when time tracking is on (#7404)
Reverts d74a621d68. Hiding the play button until a task is being
tracked made starting the timer a 2-step gesture (swipe + menu) on
mobile. Users who don't want the button can already disable it via
app features.
2026-05-01 19:35:27 +02:00
Dastan Medetbekov
c457c6fb36
Update CYBR theme (#7446)
* Update CYBR

Co-authored-by: Copilot <copilot@github.com>

* Changed CYBR theme metadata

---------

Co-authored-by: Copilot <copilot@github.com>
2026-05-01 19:26:02 +02:00
Johannes Millan
b9516b5ac7
Improve OAuth error handling and reporting (#7445)
* fix(plugin-oauth): surface real error and propagate state on local errors

Clicking "Connect Google Account" could show the generic
"Authentication failed!" snack with no detail. Two issues caused this:

1. The catch in connectOAuth swallowed the actual error. Log it and
   include the message in the snack so failures are diagnosable.
2. When the Electron main process emitted a local OAuth error
   (invalid_auth_url, failed_to_open_browser), the IPC payload had no
   state, and handleRedirectError silently dropped any callback whose
   state did not match. Echo the state from the auth URL on the main
   side, and treat missing-state errors as trusted local failures on
   the renderer side (they are not CSRF-relevant). This rejects the
   pending flow immediately instead of waiting for the 5-minute timeout.

* fix(plugin-oauth): apply review feedback on connect-OAuth UX

- Split the try block in connectOAuth so a failure of _loadDynamicOptions
  no longer surfaces as an "Authentication failed" snack on top of the
  success snack. The OAuth connection itself succeeded; loadOptions has
  its own per-field error reporting.
- Sanitize the surfaced error: collapse whitespace and cap to 200 chars
  so a long HttpErrorResponse message doesn't blow up the snack.
- Log the message field instead of the raw Error, per CLAUDE.md
  anti-pattern #11 (log history is exportable).
- Use undefined instead of null for the state echo in the main process
  to match the renderer/preload signatures.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-01 18:45:11 +02:00
David Vornholt
f33fb79dba
fix(schedule): clamp schedule event titles (#7356) 2026-05-01 13:10:11 +02:00
Florian Bachmann
79c6d903a6
Accept config schema for uploaded plugin (#7414)
* fix(plugin-config): Adds two-way binding of plugin config dialog

* feature(plugin-config): Adds config-schema support for uploaded plugins
2026-05-01 13:07:50 +02:00
Florian Bachmann
6c1a0b54f9
Caldav subtask import (#7409)
* fix(electron): disable webSecurity in dev mode to suppress CORS preflights

* feat(CalDAV): Option to import sub-tasks along with parent

* test(CalDAV): Adds specs for option to import subtasks along with parent

* doc(CalDAV): Adds notion on automatic sub-task import

* feat(CalDAV): Handles grandchildren and ignores subtasks of archived tasks.

* fix(setup): removes policy violating code

* fix(caldav):_resolve N+1 issue

* test(caldav):_adds more tests

* fix(electron):_fix task-widget mock in electron test
2026-05-01 13:07:03 +02:00
Johannes Millan
fcb4b7265b style: fix lint errors in spec files 2026-04-29 21:23:28 +02:00
Johannes Millan
e91134290d Merge branch 'feat/make-the-task-widget-setting-a-per-7a02b7'
* feat/make-the-task-widget-setting-a-per-7a02b7:
  feat(task-widget): make settings per-instance and fix Mac drag/resize
2026-04-29 21:17:11 +02:00
Johannes Millan
258a6c8949 feat(task-widget): make settings per-instance and fix Mac drag/resize
OS behavior (transparency, native drag/resize) differs enough between
platforms that syncing one shared value across devices makes no sense.
Move taskWidget settings out of the synced GlobalConfigState into a
localStorage-backed TaskWidgetSettingsService and a dedicated
UPDATE_TASK_WIDGET_SETTINGS IPC channel.

On macOS, transparent + frameless BrowserWindows do not support native
edge resize or window drag (Electron docs: "Transparent windows are not
resizable"). Use transparent: false on Mac and apply user-set opacity
via BrowserWindow.setOpacity() so native drag/resize keep working.

GlobalConfigFormSectionKey is split from GlobalConfigSectionKey so that
'taskWidget' cannot leak into updateGlobalConfigSection action payloads
(which would create phantom GLOBAL_CONFIG_UPDATE_SECTION ops).

No data migration: users previously configuring the widget will see
defaults and reconfigure once.
2026-04-29 21:16:12 +02:00
Johannes Millan
a27be2ac51 fix(sync): suppress effects during the resume-trigger gap
A long-suspended Android client could produce dozens of LWW conflicts
on TAG:TODAY when it resumed mid-day. Trace from the incident log:

  +0ms    androidInterface.onResume$ emits (I_RESUME_APP)
  +106ms  visibilitychange → todayDateStr$ → DAY_CHANGE
  +112ms  setTodayString action dispatched
  +117ms  repairTodayTagConsistency$ fires with stale local taskIds
  +124ms  ...creating a [Tag] Update Tag op in the local op log
  +241ms  SyncWrapperService.sync() actually runs and downloads
          ~600 remote ops, 22 of them TAG:TODAY updates from other
          clients during the day → 22-way LWW conflict

The repair effect is gated on `HydrationStateService.isInSyncWindow`,
but on resume that window opened too late: the trigger pipeline has
`debounceTime(100)` plus exhaustMap latency, so the synchronous
visibility-change → repair cascade finishes before sync() runs.

Add a third phase (`_isSyncWindowOpen`) to `isInSyncWindow`. Open it
via `openSyncWindow()` from three places that all fire ahead of the
cascade:

  1. The tap right after `_immediateSyncTrigger$` in
     `SyncTriggerService.getSyncTrigger$()`, before debounceTime.
  2. Direct subscriptions to `androidInterface.onResume$` and
     `ipcResume$` in the SyncTriggerService constructor — covers
     the cold-start case where (1)'s switchMap chain is not yet
     subscribed.
  3. `SyncWrapperService.sync()` itself, before any async work.

`closeSyncWindow()` runs in `SyncWrapperService.sync()`'s finally
block. The 2s failsafe inside `openSyncWindow()` handles triggers
that get debounced/throttled out before reaching `sync()`. When
`sync()` opens the window itself, it passes failsafeMs=0 to opt out
of the timer — its own `finally` is the authoritative close, and a
slow sync (provider I/O > 2s) would otherwise expire the timer
mid-sync and leave a stale-state gap.

Also adds a verbose log in `skipDuringSyncWindow` so silent drops
of legitimate emissions during the wider window are observable in
the field.

Tests: 29 hydration-state, 100 sync-wrapper, 14 tag.effects (incl. an
integration test that drives the real HydrationStateService through
the gate end-to-end), 15 sync-trigger, 11 skip-during-sync-window —
all green. Verified against multi-agent code review (6 Claude
reviewers + Codex CLI).
2026-04-29 21:15:26 +02:00
Johannes Millan
fe0a62d6d7 feat(task-repeat-cfg): support Nth weekday of month recurrence (#6040)
Adds the ability to schedule monthly recurring tasks anchored to a
specific ordinal weekday — "first Thursday", "last Monday", "second
Monday" — alongside the existing same-numeric-day-of-month recurrence.

Model: two optional fields on TaskRepeatCfg, monthlyWeekOfMonth (1..4
or -1 for last) and monthlyWeekday (0=Sun..6=Sat). Anchor presence is
the single discriminator — both fields set and in range means "Nth
weekday", anything else falls back to legacy day-of-month behavior.

Calc: a shared findMonthlyNthWeekdayOccurrence helper walks months
forward/backward computing each month's Nth-weekday candidate; the
three recurrence calc utils (next/first/newest-possible-due-date) pass
their own accept predicate. hasNthWeekdayAnchor is a narrowing type
guard that also validates ranges, so a malformed sync payload falls
back to day-of-month rather than producing wrong dates from arithmetic
on garbage inputs. data-repair strips the legacy monthlyMode
discriminator field from any cfg persisted by an in-development build.

UI: a "(Day of month)" sentinel option in the week-of-month select acts
as the toggle; the weekday select hides when no ordinal is picked. One
new quick-setting "Every month on the {ordinal} {weekday}" infers the
anchor from the start date. The save flow normalizes the form's null
sentinel back to undefined so existing cfgs don't dispatch spurious
change diffs.
2026-04-29 16:30:06 +02:00
Johannes Millan
49095c5842 refactor(calendar): allow undefined for showBannerBeforeThreshold
The duration formly component clears empty input to undefined, so the
type should reflect that. Functionally a no-op since the only consumer
coalesces falsy values to 0.
2026-04-29 16:17:56 +02:00
Johannes Millan
55ccaaf12a fix(calendar): allow disabling iCal event notification
The "Show a notification X before the event" field could not be cleared:
the form's onInit hook reset any falsy-but-not-null value back to 2h on
reopen. The duration formly component clears empty input to undefined
(not null), so the \!== null guard never matched and the user's blank
value was always overwritten.

Removing the hook lets cleared values persist. New providers still get
the 2h default from DEFAULT_CALENDAR_CFG.

Closes #7410
2026-04-29 16:17:56 +02:00
Johannes Millan
2e5a1a7b77 fix(focusMode): make break Complete button exit to planning (#7295)
Both end-of-break buttons dispatched the same completeBreak action and
auto-started the next cycle. Wire the secondary button to
exitBreakToPlanning, relabel it "Complete focus session", and let the
button row wrap on narrow viewports while hiding "Reset cycles" below
600px.
2026-04-29 16:17:56 +02:00
Johannes Millan
766ecf2271 fix(reminder): skip Capacitor permission checks on legacy Android WebView
The legacy `FullscreenActivity` shell exposes the SUPAndroid bridge but
hosts no Capacitor bridge, so `LocalNotifications.checkPermissions()` and
`checkExactNotificationSetting()` fall back to their web implementations.
Web Notifications API is unimplemented in Android WebView (Chromium issue
#434712), so `Notification.permission` reads 'default' regardless of the
OS POST_NOTIFICATIONS state. That produced two false-positive cold-start
snackbars and silently bailed out of the reminder/due-date scheduling
effects.

Reminders on this path go through AlarmManager via
`androidInterface.scheduleNativeReminder`, which the OS gates with
POST_NOTIFICATIONS at fire time. Trust it: short-circuit
`ensurePermissions()` and `ensureExactAlarmPermission()` to true on the
legacy WebView. Trade-off: a user with OS notifications actually disabled
gets no in-app warning, but the existing snackbar didn't deep-link to
settings anyway.

Inject `IS_ANDROID_WEB_VIEW_TOKEN` so the discriminator is overrideable
via standard Angular DI in tests, matching the pattern in
`task-reminder.effects.ts`.

Refs #7408
2026-04-29 16:17:56 +02:00
Johannes Millan
bd34a20ec9 feat(focusMode): simplify clock styles and improve for #7403 2026-04-29 16:17:56 +02:00
Johannes Millan
a217206a44 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.
2026-04-29 16:17:56 +02:00
Johannes Millan
3fc1bb6e94 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.
2026-04-29 16:17:56 +02:00
Johannes Millan
9d3cf64986 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
2026-04-29 16:17:56 +02:00
Johannes Millan
053d523d03 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').
2026-04-29 16:17:56 +02:00
Johannes Millan
ee58cc3acf 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.
2026-04-29 16:17:56 +02:00
Johannes Millan
db329ec5ff 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.
2026-04-29 16:17:56 +02:00
Johannes Millan
c8ecc1608c 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.
2026-04-29 16:17:56 +02:00
Iván Velázquez
f8f405c623
feat: add sections in projects (#6066)
* feat(sections): Introduce core section state, model, and persistence

* feat(sections): Implement SectionService and link sectionId to Task model

* feat(sections): Add 'Add Section' functionality to project context menu

* feat(sections): Implement cascading task deletion for sections

* feat(sections): Enable drag & drop for tasks into sections

* feat(sections): Display, manage, and reorder sections in Work View

* refactor(tasks): Add guard for invalid subtask moves in reducer

* feat(markdown): Add interfaces for markdown sections

* feat(markdown): Implement markdown section parsing utility

* feat(section): Add helper methods to SectionService

* feat(markdown): Add i18n for markdown section paste confirmation

* refactor(markdown): Prepare MarkdownPasteService for section support

* feat(markdown): Implement markdown section paste handling in MarkdownPasteService

* feat(markdown): Update paste detection to include markdown sections

* test(markdown): Add simple test for markdown section parsing utility

* fix(sections): post-merge type errors and stray file cleanup

- model-config.ts: drop unsupported `validate` field on section ModelCfg;
  validators are looked up via validateAppDataProperty(key, data) instead.
- app-data-mock.ts: add `section: createEmptyEntity()` so AppDataComplete is satisfied.
- Remove test-sections.js (development artifact from the original PR).

* refactor(sections): atomize section deletion via meta-reducer

Replace the dispatch-chained section.effects.ts with a section-shared
meta-reducer that removes the section entity and cascade-deletes its
tasks (and subtasks) plus their references in projects and tags in a
single reducer pass.

Why:
- The previous effect used inject(Actions), so it would re-fire during
  remote sync replay and double-delete tasks.
- It dispatched a separate deleteTasks action, producing two operations
  in the sync log; a partial sync between them could leave a tree of
  orphaned tasks pointing at a vanished section.

Changes:
- Add src/app/root-store/meta/task-shared-meta-reducers/section-shared.reducer.ts
- Register sectionSharedMetaReducer in Phase 5 of meta-reducer-registry.ts
- Remove src/app/features/section/store/section.effects.ts and its
  EffectsModule.forFeature registration in feature-stores.module.ts

* refactor(sections): visual layer model + tag/today support

Make sections a pure visual grouping (analogous to boards) rather than a
property of tasks. This eliminates the cross-entity coupling that drove
most of the original PR's sync-correctness issues.

Section model:
- Drop Task.sectionId entirely. Sections own their membership via
  Section.taskIds: string[].
- Generalize Section.projectId → contextId + contextType ('PROJECT' | 'TAG').
  This unblocks sections in tag and TODAY views.
- New addTaskToSection action atomically removes the task from any other
  section and inserts it into the target at the requested position via
  adapter.updateMany — one reducer pass, one sync operation. Replaces the
  old project.effects moveProjectTaskToSection effect, which dispatched
  two persistent actions and was non-atomic.

Section deletion:
- Pure entity removal; no task cascade. Tasks in the deleted section
  simply become "no section" tasks (DELETE_SECTION confirmation reflects
  this; the now-obsolete DELETE_SECTION_CASCADE string is removed).

Section-shared meta-reducer (Phase 5):
- Repurposed from the previous deleteSection cascade handler. Now listens
  for TaskSharedActions.deleteTask/deleteTasks and prunes deleted task IDs
  from any section.taskIds, keeping section state consistent without
  requiring an effect.

Selector / perf:
- selectSectionsByContextId is backed by a single memoized
  selectSectionsByContextIdMap. Replaces the per-call factory pattern that
  broke memoization across consumers.
- WorkViewComponent.undoneTasksBySection now indexes section→task in
  O(n + m) using a Map keyed by taskId.

WorkContextMenu:
- Drop the @if (isForProject) gate on Add Section. The menu now offers it
  for tags (incl. TODAY) and propagates the appropriate contextType.

Cleanup:
- Add takeUntilDestroyed to all dialog .subscribe() chains in
  work-view.component.ts and work-context-menu.component.ts.
- Drop unused MatMenu/MatMenuTrigger/MatMenuItem imports.
- Yield the event loop every 10 sections during markdown imports.
- Revert the es.json edits added by the original PR (en-only policy).

* test(sections): cover reducer + meta-reducer behavior

- sectionReducer: addSection (default empty taskIds), deleteSection
  (entity-only, no cascade), updateSection partial changes,
  updateSectionOrder scoped to one context, addTaskToSection (anchor
  positioning, uniqueness across sections, intra-section moves, ungrouping
  on null sectionId, no-op when target missing).
- sectionSharedMetaReducer: deleteTask removes the id from any section,
  cascades through subtasks, deleteTasks bulk variant, passes through
  unrelated actions unchanged.

* fix(sections): wire new entity through suite-wide invariants

Fixes 11 unit-test failures introduced by adding the section model:

- ActionType enum gains SECTION_ADD_TASK (the new atomic move action)
  and a corresponding ACTION_TYPE_TO_CODE entry; spec member-count
  expectation bumps from 136 → 141 to match.
- extractEntityKeysFromState now emits SECTION:<id> keys so
  OperationLogCompactionService recognizes section as a valid model.
- task-list enterPredicate distinguishes section drop-lists from
  subtask drop-lists via drop.data.listId. Parent tasks may drop
  into PARENT_ALLOWED_LISTS or any parent-level (section) drop-list,
  but never into a subtask drop-list (listId === 'SUB').
- Add section: { ids: [], entities: {} } to the empty-state helper in
  validate-state.service.spec; without it Typia validation fails
  because section is now a required slice of AppDataComplete.
- Add activeWorkContextId$: of(null) to the WorkContextService mock
  in work-view.component.spec; the section signal subscribes to that
  observable in the constructor.
- Add 'section' → 'SECTION' to the modelToEntityType map in
  operation-log-compaction.service.spec.

Five immediate-upload.service.spec.ts failures remain; they reproduce
on master with identical files, so they're unrelated to this branch.

* fix(sections): apply multi-review C1-C4 + harden taskIds reads

C1: Move sectionSharedMetaReducer before taskSharedCrudMetaReducer.
At Phase 5 it ran AFTER the task entity was already removed, so
state.task.entities[id]?.subTaskIds was always undefined and section
references to deleted subtasks leaked. The section spec passed only
because its mock reducer didn't apply the cascade.

C2: Tighten task-list enterPredicate. Subtasks may now drop only into
another subtask drop-list (listId === 'SUB') or appear as top-level
in DONE/UNDONE. Section drop-lists (listId === 'PARENT' with a section
id) reject subtask drags so section.taskIds stays parent-only.

C3: Add cdkDropListEnterPredicate to the sections-wrapper. Without it,
a task drag could land on the section-reorder list and dropSection
would treat a Task as a Section, corrupting ordering. The new
acceptSectionDragOnly predicate brand-checks the drag's data.

C4 + cleanup: drop the unused Section.isCollapsed field; remove the
redundant `// 1.` `// 2.` comments in section.reducer; tighten the
`(state as any).section` cast (AppStateSnapshot already declares the
field); fix the misleading meta-reducer-registry comment.

Plus a reported runtime crash: cleanupSectionTaskIds threw on
undefined `s.taskIds` for sections persisted before this branch added
the field. Defensive `?? []` everywhere that reads `taskIds`, and a
normalizeLoadedSections pass on `loadAllData` so old persisted state
is brought up to the current shape.

* fix(sections): Add Section button — drop takeUntilDestroyed on dialog sub

WorkContextMenuComponent lives inside a <mat-menu>. The menu (and the
component) is destroyed the moment the dialog opens, so
takeUntilDestroyed(this._destroyRef) tore down the afterClosed()
subscription before it could ever emit the typed title. Result: the
dialog appeared, the user typed, clicked Save — but no section was
ever dispatched.

MatDialog cleans up its own subscription once the dialog closes, so
the explicit teardown is unnecessary here. WorkViewComponent's similar
dialog subscriptions are unaffected (that component is not inside a
mat-menu).

* style(sections): move Add Section above Settings in context menu

* fix(sections): clean up orphan sections on project/tag deletion

Closes the cleanup gap surfaced by user audit: until now, deleting a
project or tag left behind its sections — they kept their stale
contextId and contextType but no longer matched any context, piling up
in state and the sync log. Section-level cleanup was only wired for
task deletion.

sectionSharedMetaReducer now also handles:
- TaskSharedActions.deleteProject → remove sections where
  contextType='PROJECT' and contextId === projectId.
- deleteTag (single) → remove sections where contextType='TAG' and
  contextId === id.
- deleteTags (bulk) → remove sections where contextType='TAG' and
  contextId is in ids.

contextType is matched explicitly so a project and a tag that happen
to share the same id (theoretical, but possible) don't cross-pollute.
Added 3 specs covering each path, including the same-id collision case.

* fix(sections): clean section.taskIds on task move + tag removal

Two more cleanup paths surfaced by the user audit:

1. Task moves to another project (TaskSharedActions.moveToOtherProject):
   the moved task and its subtasks were left lingering in any section
   owned by the previous project. Now the meta-reducer reads the task's
   old projectId from state (action runs before taskSharedCrud) and
   strips the task ids from project-scoped sections in that project.
   Tag-scoped sections are intentionally untouched because tag
   membership doesn't change on a project move.

2. Task tagIds change (TaskSharedActions.updateTask): when a tag is
   removed from a task, any section owned by that tag still kept the
   task id. Now we diff oldTagIds vs new tagIds, and for each removed
   tag, strip the task id from sections matching contextType='TAG' and
   contextId === removedTagId. Tag additions are not auto-joined to a
   section — that stays a user action.

The new cleanupTaskIdsInContexts helper does both jobs (restricting
edits to a specific contextType + a set of contextIds), keeping the
logic narrow.

Specs cover: project move strips only old-project sections (and
subtasks), tag removal strips only the dropped tags' sections, and
updateTask without a tagIds change is a no-op.

* refactor(sections): replace SectionContextType with WorkContextType

Drop the parallel `SectionContextType = 'PROJECT' | 'TAG'` union in
favour of the existing `WorkContextType` enum, which has identical
string values. Same on-disk shape (the Typia validator's literal-string
serialization is unchanged), but the model now reuses the canonical
work-context taxonomy and consumers can pass `activeWorkContextType`
straight through without translation ternaries.

Touches: section.model + section.service signature, the section-shared
meta-reducer's helpers and handlers (`WorkContextType.PROJECT/TAG`
instead of literals), the work-context-menu / work-view / markdown-paste
call sites (drop the `=== WorkContextType.PROJECT ? 'PROJECT' : 'TAG'`
ternary), and the spec fixtures.

* refactor(sections): split addTaskToSection — drop the 'NONE' sentinel

The 'NONE' string sentinel for ungrouped op-log entries had two
problems: (1) two clients ungrouping different tasks concurrently
both wrote ops keyed on entityId='NONE', so LWW conflict resolution
collapsed them and one ungroup was discarded; (2) magic string with
no constant or test pinning it.

Split into two persistent actions:
- addTaskToSection({ sectionId, taskId, afterTaskId? }) — sectionId
  is now non-nullable; entityId tracks the destination section. The
  reducer still atomically strips the task from any other section
  (uniqueness invariant), so a single op covers a full move.
- removeTaskFromSection({ sectionId, taskId }) — entityId is the
  source section. Concurrent ungroups from different sources are now
  independent ops with distinct entityIds; LWW conflict resolution
  treats them correctly.

The drag-drop call site already knows both source and target list ids
(srcIsSection / targetIsSection), so the SectionService just exposes
two narrow methods: `addTaskToSection(target, ...)` and
`removeTaskFromSection(source, ...)`. The work-view caller uses
addTaskToSection only (markdown paste never ungroups).

Two new specs cover removeTaskFromSection: strips only the named
section, no-op when the task isn't there, no-op when the section is
missing.

* fix(sections): apply round-2 review batch

Addresses ten findings from the second multi-review pass.

Security
- Replace plain-object grouping caches with Map<string, …> so a
  malicious sync peer can't poison Object.prototype via crafted
  contextIds like '__proto__'. Affects selectSectionsByContextIdMap;
  the per-call factory selector is removed (see Performance below).

Correctness
- normalizeLoadedSections defends against state.ids === undefined
  (very old persisted shapes wrote `section: {}`).
- Section meta-reducer now also handles TaskSharedActions.updateTasks
  (bulk). Previously only updateTask fired the tag-removal cleanup;
  a future bulk dispatcher mutating tagIds would silently leak orphan
  task ids in tag-context sections. Spec covers it.

Architecture
- Phase 3.5 promoted to a named phase in the registry doc block.
- validateMetaReducerOrdering pins sectionSharedMetaReducer to run
  before taskSharedCrudMetaReducer; any future reorder fails
  dev-mode validation. The handlers' pre-CRUD state read is now
  documented at the top of section-shared.reducer.ts.

Alternatives + Performance
- Drop the per-call selectSectionsByContextId factory. The service
  selects selectSectionsByContextIdMap and pipes map(...) — no fresh
  MemoizedSelector per call, no leak.
- addTaskToSection reducer breaks out of the uniqueness scan after
  the first removal (a task is in at most one section at a time).
- Pre-filter sectionSharedMetaReducer on a static
  HANDLED_ACTION_TYPES Set so the 99% of dispatches that don't match
  short-circuit before allocating the handler dispatch table.

Simplicity
- Collapse SectionService.{addSection, addSectionWithId,
  generateSectionId} into a single addSection that returns the new
  id synchronously. Markdown-paste consumes it directly.
- Remove collectTaskAndSubtaskIds (single-task path is just
  collectAffectedTaskIds with a one-element array).
- dropSection drops the object spread + extra map; reorder ids in
  place.
- Tighten ExtendedState — SECTION_FEATURE_NAME is always registered,
  so the optional-typing dance and the four `if (\!sectionState)`
  early-returns inside helpers are removed.

* fix(sections): apply round-3 review batch

Fixes from a multi-reviewer pass (codex + claude + code-reviewer
sub-agent) on the sections feature.

Critical
- task-list: subtask-to-subtask drag was being misidentified as a
  section move. _move() now takes srcListId/targetListId and only
  treats a non-reserved listModelId as a section when listId is
  PARENT. Subtask drop-lists ('SUB') fall through to moveSubTask.
- parse-markdown-tasks: tasks before the first markdown header were
  silently dropped by parseMarkdownWithSections. They now flush into
  a top-of-list "No Section" entry. Also broaden the header regex
  from /^#\s+/ to /^#{1,6}\s+/ so H2-H6 are recognized.
- section.actions/reducer/service: addTaskToSection now carries an
  explicit sourceSectionId. The reducer strips from that source
  rather than searching state, making replay deterministic. Action
  meta sets entityIds: [src, dest] when src is provided so vector-
  clock conflict detection covers both. Callers in task-list and
  markdown-paste pass the actual source (or null for new tasks).

Warnings / cleanups
- section-shared meta-reducer: handle removeTasksFromTodayTag and
  localRemoveOverdueFromToday — TODAY is virtual so the existing
  tagIds path doesn't catch them. Doc enumerates the residual gap
  (scheduling/planner/short-syntax/crud/lww) and proposes a future
  Phase 6.5 diff-based meta-reducer for full coverage.
- section-shared reducer: typed as MetaReducer<RootState> /
  ActionReducer<RootState, Action> instead of any.
- markdown-paste: yield every 30 dispatches (was: every 10 sections)
  per CLAUDE.md rule #11. Type the reduce accumulator as number.
- task-list: extract RESERVED_LIST_IDS constant; comment why it
  diverges from PARENT_ALLOWED_LISTS on LATER_TODAY.
- en.json/es.json: restore trailing newlines (es.json now identical
  to master).

Tests
- parse-markdown-tasks.spec: 6 cases for parseMarkdownWithSections
  (H1, H2/H3, pre-header tasks, empty sections, null input).
- section.reducer.spec: 4 cases for sourceSectionId behavior
  (explicit source, null, omitted, intra-section reorder).
- section-shared.reducer.spec: 3 cases for TODAY removal cleanup.
- task-list.component.spec: 5 cases for _move() routing
  (subtask vs section disambiguation, source propagation).

* fix(sections): apply round-3 review nits

- task-list: type RESERVED_LIST_IDS values via `satisfies
  DropListModelSource[]` so adding a new variant to the union
  surfaces a typo here without forcing casts at every `.has()`.
- section.actions: tighten addTaskToSection doc — the `entityIds:
  [src, dest]` claim only holds when src is a non-null string
  different from dest; intra-section / null fall back to
  single-entity meta.
- task-list spec: add two anchor cases for `_move` so
  `getAnchorFromDragDrop` is actually exercised on section drops
  (previous tests passed `[taskId]` only, which short-circuited to
  null).

* fix(sections): apply round-4 review batch

High-severity sync/UX fixes:
- deleteProject now also strips cascaded task ids from tag-context
  sections (one extra cleanupSectionTaskIds pass in the meta-reducer);
  + unit test
- Edit Section dialog prefill: val → txtValue
- Markdown paste: drop yieldIfNeeded mid-loop (widened the sync
  interleave window); residual atomic-bulk-action gap documented
- Add Section menu item guarded against TODAY_TAG
- Paste hook switched from id-prefix scan to data-task-id attribute
- New section referential validators + auto-repair (data-repair)
- Section view bypasses customizer when filter/sort active
- Parser hardening: input cap, CRLF/BOM normalization, reduce-based
  min-indent (avoids RangeError on huge spreads), JSDoc fix
- moveSubTask guard now also rejects self-moves; console.warn →
  TaskLog.warn
- Work-view styling: use --s/--s3 tokens, narrow \!important rules
- Drop dead loadSections action + SectionService.sections$
- Trailing-space prettier nits in sync.model.ts + feature-stores.module

* fix(sections): apply multi-review batch — moveToArchive + cleanup

- moveToArchive: add handler in section-shared meta-reducer so archived
  tasks (and their subtasks) no longer leak as stale ids in
  section.taskIds until dataRepair clears them.
- Collapse the dual HANDLED_ACTION_TYPES + handlers map into a single
  ACTION_HANDLERS record; the prior split is what allowed moveToArchive
  to drift out of sync.
- Make addTaskToSection's sourceSectionId required (string | null) and
  delete the legacy defensive sweep branch in the reducer.
- updateSectionOrder now keeps other-context sections in their slot in
  state.ids instead of pushing them to the front.
- Sanitize section titles (trim + 200-char cap) on add/update.
- Remove dead addSection() in work-view.component.ts (template only
  wires editSection/deleteSection; addSection lives on work-context-menu).
- Remove dead translation keys WW.ADD_SECTION and WW.ADD_SOME_TASKS.
- Drop hasHeaders field from MarkdownWithSections (null return already
  encodes header-less input).
- Drop normalizeLoadedSections + ?? [] guards (Section is brand-new, no
  legacy persisted shape exists) and unused entity adapter exports.

* perf(sections): apply perf review batch — drop-list coalesce + meta-reducer hot paths

- DropListService: coalesce burst register/unregister calls via a
  microtask flush. Mounting 50 sections previously emitted 50 times
  through the BehaviorSubject; cdkDropListConnectedTo rebuilds its
  sibling graph per emission, so first paint cost was ~O(L²). Now
  one downstream emission per CD pass.
- section-shared meta-reducer: replace Object.values(entities) sweeps
  with `for-of state.ids` (no intermediate array alloc on every matched
  task action) and collapse `.some + .filter` double-walk into a single
  pass that returns null when nothing changed. Halves walk count on
  affected sections under op-log replay.
- updateTasks handler: aggregate (taskId → removedTagIds) across the
  batch into a `tagId → tasksToRemove` map, then sweep candidate
  sections once with a single adapter.updateMany. Drops a 50-task
  batch from O(N·S) to O(N + S).
- section.service: stable EMPTY_SECTIONS constant for contexts with no
  sections, so OnPush downstream isn't broken by a fresh `[]` per
  emission.
- work-view template: drop `|| []` on dict[section.id] — the dict is
  pre-populated per section, so the fallback was allocating a fresh
  array reference per CD pass for every empty section.
- acceptSectionDragOnly: bind [cdkDragData]="section" and reduce the
  predicate to one property read; was running shape-validation on
  every dragOver tick.
- markdown paste: cheap regex pre-screen in isMarkdownTaskList so
  plain-text Ctrl+V pastes bail before invoking the parser, and
  memoise the sectioned-parse result by string reference so the
  immediately-following handleMarkdownPaste doesn't re-parse.

* feat(sections): project-only Add Section + empty main-list hint

- work-context-menu: tighten Add Section gating from
  `isForProject || contextId \!== TODAY_TAG_ID` to `isForProject`. The
  menu item is now hidden for the today list and for tag contexts in
  general; sections in tag contexts can still arrive via markdown paste.
- work-view: when the sectioned view's no-section bucket is empty
  (every task lives in a section), render a small italic hint
  ("All tasks are organized into sections") instead of leaving the
  area silently empty.

* fix(sections): keep no-section drop target alive when empty

Previously the no-section area swapped task-list for a <p> hint when
empty, removing the cdkDropList. That blocked drops from sections back
into the main list. Restore the always-rendered task-list and pass the
hint via its built-in [noTasksMsg]:
- task-list keeps its drop target so cross-section moves work.
- The hint is muted via task-list's existing .no-tasks styling
  (var(--text-color-muted)).
- The hint is hidden when undoneTasks() is empty so it doesn't
  duplicate the horizon "no tasks planned" empty state.

* feat(sections): show Add Section in every work-context menu

Drop the gate around the Add Section menu item so it shows for
projects, regular tags, and the today list. Sections in TODAY are
stored as TAG-context sections under the TODAY tag id, matching the
existing tag-section flow.

* fix(sections): apply round-6 multi-review batch

Critical:
- enterPredicate rejects backlog → section drops; previous path left
  the task in both backlog and section.taskIds.
- editSection / addSection trim whitespace before the truthy check
  (sanitizeSectionTitle would otherwise produce empty titles).
- TODAY_TAG cleanup: post-reducer diff in section-shared meta-reducer
  catches every flow that removes ids from TODAY (scheduling, planner,
  short-syntax, undo, lww), closing the documented residual gap. Bulk
  action handlers retained — handler + diff are idempotent.

Sync-replay defense:
- updateSectionOrder accepts partial / out-of-date payloads via dedup +
  append-missing instead of a fragile cursor walk; new tests cover
  shorter and stale payloads.
- sanitizeSectionTitle moved to section.model and applied inside the
  reducer for addSection / updateSection so remote ops can't bypass
  the 200-char cap.

Cleanup:
- markdown-paste memo moved from module scope to instance state, with
  explicit clear after consumption (clipboard content no longer
  retained for the rest of the session).
- undoneTasksBySection bound once via @let in the work-view template.
- Factory selector selectSectionsForContext(contextId) replaces the
  whole-map mapping in SectionService.
- Drop log-only validateSections (data-repair already cleans).

Follow-ups documented inline (not in this PR):
- task.sectionId membership model (W4)
- removeTaskFromSection → addTaskToSection consolidation (W3)
- marked-based parseMarkdownWithSections (S1)

* fix(sections): guard TODAY-tag diff against undefined state slices

`diffRemovedTodayTaskIds`, `applyTodayTagSectionCleanup`, and
`collectAffectedTaskIds` all assumed their slices existed. During
early boot / undo / hydration paths the tag, task, or section slice
can be undefined, causing the meta-reducer to crash on
`prevTagState.entities[...]`. The crash cascaded into selector
errors (idleTime, activeType, isShowAddTaskBar) because subsequent
reducer passes never ran.

Bail out early when slices are absent — there's nothing to clean up
yet.

* test(sections): add e2e coverage for basic section flows

Covers the core user-visible section behavior:
- create section via project header context menu
- reject whitespace-only titles (verifies the C2 trim fix)
- edit section title via the per-section menu
- delete section after dialog confirmation
- drag a task into a section (Angular CDK drag-drop helper, since
  Playwright's `dragTo` uses HTML5 drag events that CDK ignores)
- sections persist across a page reload (IndexedDB hydration)

The reverse drag (section → no-section bucket) is fixme'd: forward
drag passes, but the reverse target's bounding box collapses to a
hint message when empty and the CDK drop won't register reliably
in headless. Reducer-level coverage in section.reducer.spec.ts
(`removeTaskFromSection`) substitutes for now.

* fix(sections): apply round-7 multi-review batch

Hardening:
- Reducer-side `sanitizeSectionTitle` now coerces non-string input
  (null / undefined) to "" instead of throwing. A malformed remote op
  (`addSection({ section: { title: undefined } })`) was the threat
  model the cap was added for; previously it crashed the reducer.
- `updateSection` now sanitizes on key-presence (`'title' in changes`)
  rather than `typeof === 'string'` so a peer shipping `title: null`
  cannot bypass the cap and corrupt the entity's typed contract.
- Single dispatcher-level boot guard in `sectionSharedMetaReducer`
  catches every action handler that touches task / tag / section
  slices, replacing the asymmetric per-function guards from round 6.

Cleanup:
- Revert the round-6 `selectSectionsForContext` factory selector. It
  allocated a fresh `MemoizedSelector` per `getSectionsByContextId$`
  call, undermining the memoization the simplification claimed. The
  service's previous `.pipe(map(m => m.get(id) ?? EMPTY))` shape is
  one fewer layer with identical behavior — single consumer, no win.
- Move `sanitizeSectionTitle` + `MAX_SECTION_TITLE_LENGTH` to
  `section.utils.ts` (model files in this repo are pure type files).
- Inline `_clearSectionsCache()` (single caller).
- Drop the redundant 5-step settle-move at the end of the e2e
  `cdkDragTo` helper.

Tests:
- Pin the actual ordering in the `updateSectionOrder` partial-payload
  test (was only checking dedupe count, missed the explicit shape).
- New: empty-string title passes through (legitimate clear).
- New: null/undefined title is coerced, not stored as null.
- New: malformed remote op with undefined title doesn't crash addSection.
- Replace `waitForTimeout(500)` in the e2e whitespace-rejection test
  with a polling `toHaveCount(0)` assertion (project rule violation).
- Strengthen the `updateSection` cap test with leading-whitespace input.

Deferred (tracked as follow-ups):
- W2: explicit `handleRemoveFromTodayTag` redundant with the diff —
  keep both for now; soak the diff before unifying.

* test(sections): drop unused eslint-disable directives

Use `as unknown as string` casts instead of `as any` + eslint-disable
in the malformed-input reducer tests. Same intent (force the type
assertion to model what a malicious peer's payload looks like at
runtime), no lint suppression needed.

* style(sections): drop redundant message from Add Section dialog

The Add Section dialog passed both `placeholder: T.G.TITLE` and
`message: T.CONFIRM.ADD_SECTION` to DialogPromptComponent. The
message was redundant — its text ("Add Section") duplicated the
dialog's contextual purpose, and showing it forced the
mat-dialog-content out of `.isNoMsg` mode, adding outer padding
that the Add Tag dialog doesn't have.

Drop the message so the Add Section dialog matches the Add Tag
visual pattern (no outer padding, just the input field). Also
remove the now-unused `T.CONFIRM.ADD_SECTION` translation key.

* fix(sections): apply round-8 multi-review batch

Hardening:
- `sanitizeSectionTitle` swaps `String(title ?? '')` for a
  `typeof === 'string'` fast-path. Closes two real defense gaps:
  - `String(Symbol())` would throw and crash the reducer.
  - `String({toString: () => 'x'.repeat(2**27)})` would materialize
    a ~256 MB string before the slice. JSON op-log payloads can
    smuggle 2 MB+ literal strings that survive the wire.
  Same behavior for the documented `null` / `undefined` cases.
- Reducer + service now share a `hasTitleChange()` helper using
  `Object.hasOwn` instead of `'title' in changes`. Strictly better
  semantics — `'in'` walks the prototype chain, so a peer payload
  with `Object.create({title: 'x'})` would have triggered
  sanitization on a key the entity doesn't carry.
- Service-side `updateSection` now uses the same key-presence check
  as the reducer (was `typeof === 'string'`); removes a future
  reader's "why two checks?" smell.

UX / a11y:
- Add Section dialog now passes `placeholder: T.WW.ADD_SECTION_TITLE`
  ("Add Section") instead of generic `T.G.TITLE` ("Title"). The
  dialog has no title element and no message text, so the
  placeholder is the only context users (especially screen-reader
  users) get for what they're naming. Mirrors the Add Tag pattern
  ("Add new Tag" placeholder).

Convention:
- Rename `section.utils.ts` → `section.util.ts`. Repo uses singular
  `*.util.ts` (60+ files) vs plural `*.utils.ts` (was 2 outliers).

* feat(sections): Add Section in work-view background context menu

Right-click on the empty area of the work-view (project, tag, or
Today view) now opens a small context menu with one item: "Add
Section". This is a discoverability complement to the side-nav
overflow button — the work-view is where the user is already
focused when they decide they need a section, so the action should
be reachable without navigating back to the side-nav.

Implementation:
- `(contextmenu)` listener on `.task-list-wrapper` calls
  `onBgContextMenu`, which skips when the click target is inside
  an interactive element (task, button, input, drag handle, …) so
  per-element context menus and native form behavior aren't shadowed.
- A hidden `[matMenuTriggerFor]` div is positioned at the cursor
  via signals (`bgContextMenuX`, `bgContextMenuY`).
- `addSection()` reuses the same DialogPromptComponent shape as
  the side-nav addSection (no `message`, descriptive placeholder),
  and reads `activeWorkContextId` / `activeWorkContextType` from
  `WorkContextService` so it works across project / tag / Today.

E2E test: right-click → menu item → submit dialog → assert the
section is rendered.

* fix(sections): initialize section slice in dataRepair for legacy migrations

Legacy 'pf' databases predate the sections feature and don't carry
a section field. After Typia validation rejects the missing field,
`dataRepair` was supposed to fix it — but `_repairSections` early-
returned on missing state instead of initializing it, so re-validation
failed and `OperationLogMigrationService._performMigration` aborted
with "Migration failed."

Match the existing init pattern (archiveYoung, archiveOld, reminders):
populate `dataOut.section = { ids: [], entities: {} }` if absent
before per-slice repair runs.

Verified by running e2e/tests/migration/legacy-data-migration.spec.ts.

* fix(sections): apply round-9 thorough review batch

Critical:
- Reject section → BACKLOG drag in `enterPredicate`. The handler
  was removing the task from `section.taskIds` but never dispatching
  `moveProjectTaskToBacklogList`, so the task vanished from the
  section without appearing in the backlog. Mirrors the existing
  BACKLOG → section guard.

Warnings:
- `section.reducer.ts: loadAllData` now falls back to
  `initialSectionState` when the payload omits `section`. Previous
  behavior preserved stale local state, violating SYNC_IMPORT /
  BACKUP_IMPORT semantics ("complete fresh start").
- `markdown-paste.service.ts` checks `sectionTitle?.trim()` before
  calling `addSection`, so headers like `## ​` (zero-width space)
  fall through to the noSection bucket instead of creating a
  titleless section.
- `moveToArchive` section cleanup unions payload subtasks with the
  state-derived expansion. Robust under both threat models: replay
  where the parent entity is gone from state (payload carries the
  tree) AND callers passing `subTasks: []` (state lookup is the
  only signal).

Suggestions:
- Section overflow button gets an `aria-label="Section options"`
  (new `T.WW.SECTION_OPTIONS` translation key).
- `_repairSections` now does `Array.isArray(taskIds)` instead of
  `?? []` — defends against malformed remote payloads where
  `taskIds` is a truthy non-array value.
- `acceptSectionDragOnly` discriminates on `'contextType' in data`
  rather than `Array.isArray(data.taskIds)`. The latter would
  silently accept Task drags if Task ever gained a `taskIds` field.

Documentation:
- Added LWW conflict-resolution gap to the section-shared
  meta-reducer's KNOWN FOLLOW-UPs block. Project- and non-TODAY-tag-
  context section.taskIds can leak phantom references after LWW
  resolves a tagIds / projectId update; the diff catches TODAY but
  not other contexts. Visible impact bounded by render-time
  intersection in `undoneTasksBySection`. Cleaned by next
  `dataRepair` pass.

False positive: `extract-entity-keys.ts` already guards via
`entityState?.ids` optional chain — no change needed.

Verified: 24 reducer tests, 17 meta-reducer tests, 51 data-repair
tests, 35 task-list tests, 7 work-view tests, 7 active section
e2e tests + migration e2e all pass.

* refactor(sections): simplification pass — drop micro-helpers + comment cleanup

A focused simplification review of the branch found small wins
that the correctness-focused rounds had accreted around.

Removed:
- `hasTitleChange()` helper. Single-line `Object.hasOwn(c, 'title')`
  is clearer at the two call sites than a 3-line wrapper.
- `_parseSectionsCached` instance memo + private fields in
  `MarkdownPasteService`. The `MARKDOWN_TASK_OR_HEADER_RE` pre-screen
  already gates plain-text pastes; for genuine sectioned input the
  parser walks once cheaply and the dialog wait dwarfs parse time.
  Removes mutable instance state and the `MarkdownWithSections` type
  import that only existed for the cache.

Comment trimming (74 LOC removed across 5 sites, no behavior change):
- `addTaskToSection`: 22 → 8 lines (the architectural follow-up was
  duplicated elsewhere; kept the essential meta-shape note).
- `Phase 3.5 placement` block: 11 → 3 lines (runtime
  `validateMetaReducerOrdering()` already enforces it).
- `moveToArchive` handler: tightened the union-rationale.
- `acceptSectionDragOnly`: 8 → 2 lines.
- `updateSection` reducer: 6 → 2 lines.
- `updateSection` service: dropped redundant explainer.

Things considered and intentionally kept (defended):
- `section.util.ts` — file is clean (one constant + one normalizer);
  matches the codebase's per-feature util pattern.
- `section.service.ts` — codebase has a service per feature.
- `EMPTY_SECTIONS` frozen const — a fresh `[]` per emission would
  cause downstream computed signals to recompute even for empty
  contexts.
- Reducer-side `sanitizeSectionTitle(unknown)` — defends the real
  schema-evolution case where a peer ships malformed payloads.
- Boot-guard 3-slice check — needed because the diff path
  dereferences tag state.

Verified: 24 reducer tests, 17 meta-reducer tests pass.

* refactor(sections): restrict scope to projects + TODAY tag

Custom-tag sections added per-tag cleanup machinery (deleteTag /
deleteTags handlers, handleTaskTagsChange, handleBulkTaskTagsChange,
removeTasksFromTodayTag/localRemoveOverdueFromToday explicit handlers)
and broadened the validation surface for limited end-user value.

- Add isValidSectionContext helper enforcing PROJECT or TODAY-only.
- Guard at all entry points: SectionService.addSection (returns null),
  section.reducer (rejects invalid contextId/Type), data-repair drops
  invalid sections on import.
- Hide "Add Section" in custom-tag context menu and suppress the
  work-view bg right-click menu there.
- Drop tag-scope handlers from section-shared meta-reducer; rely on
  the existing diff-based TODAY_TAG.taskIds path for TODAY cleanup.
- Update unit tests to match.

Net: -243 LOC.

* refactor(sections): drop markdown section paste

The H1-grouped markdown paste path created sections + tasks atomically
from a hand-rolled parser, but the feature is niche, the parser is
duplicated logic next to the existing flat-list and structured paste
paths, and the documented atomicity caveat (partial state on
concurrent sync) was never resolved.

Falls back to the existing flat-list / sub-task paste paths, which
cover the dominant use case.

- Remove parseMarkdownWithSections + MarkdownWithSections /
  SectionWithTasks types.
- Drop the section-paste branch and SectionService /
  WorkContextService deps from MarkdownPasteService.
- Drop CONFIRM_SECTIONS i18n key.
- Drop spec coverage for the removed parser.

Net: -251 LOC.

* refactor(sections): post-review hardening + cleanups

Apply five findings from the latest cross-reviewer pass.

- loadAllData filters imported sections through isValidSectionContext.
  Typia validates structure but not invariants, so a backup from an
  older client could otherwise smuggle custom-tag sections back in.
- updateSection rejects payloads that touch contextId/contextType.
  No legitimate flow rewrites a section's context — a malformed peer
  would otherwise morph a project section into a custom-tag one.
- Add 'section' to ENTITY_STATE_KEYS so _resetEntityIdsFromObjects
  reconciles ids ↔ entities like every other entity slice.
- Drop redundant service-side sanitize in updateSection — the reducer
  is authoritative.
- Refresh stale addSection JSDoc (markdown-paste reference removed
  with the section paste path in 16a0011d5f).

* refactor(sections): drop YAGNI defenses against non-existent older clients

The Sections feature is brand new on this branch — no released version
ever produced custom-tag sections, so loadAllData filtering and an
updateSection contextId/contextType reject defend against a threat that
cannot exist. Trust internal code per project guidelines.

Reverts two of the five defenses added in d4c9680837. The other three
(ENTITY_STATE_KEYS section parity, redundant service-side sanitize,
stale JSDoc) stay — they're not threat-defensive.

* refactor(sections): drop redundant addSection reducer context guard

The service-level guard at section.service.ts:44 is the only dispatch
path; layering a hot-path reducer guard on top defends against a
"developer dispatches the action directly past the service" scenario
that doesn't exist. Trust internal code per project guidelines.

Data-repair keeps its custom-tag check — that module's design contract
is defensive cleanup of impossible state, a different category.

* refactor(sections): merge bg right-click menu with Settings menu

Two background context menus existed: app-level "Change Settings" and
work-view-level "Add Section". Combine them into the single existing
app-level menu, gating "Add Section" by PROJECT or TODAY context.

- Move addSection() to AppComponent (mirrors openSettings).
- Add the gated "Add Section" item to the backgroundContextMenu
  template.
- Remove the work-view bg trigger, signals, viewChild, handler, and
  matching template block.
- Update the right-click section e2e to dispatchEvent on
  .task-list-wrapper (the merged menu uses target.matches, not
  target.closest, so the previous position-based click was fragile
  against the empty-state placeholder).

---------

Co-authored-by: Johannes Millan <johannes.millan@gmail.com>
2026-04-29 15:02:33 +02:00
Johannes Millan
fb61ed7d92 fix(boards): re-enable Save in Eisenhower Matrix edit dialog (#7380)
The conditionally-required match-mode and sortDir radios placed
`defaultValue` inside `props`, which Formly ignores — its core extension
reads `field.defaultValue`. So opening any board with >=2 included or
excluded tags left those required fields undefined and the Save button
disabled. Even with the default lifted, Formly skips defaults for
fields hidden at init and on hidden→visible transitions unless
`resetOnHide: true` is set, so picking a sortBy re-locked the form.

Lift `defaultValue` to field level and add `resetOnHide: true` on
`includedTagsMatch`, `excludedTagsMatch`, and `sortDir`. Add a unit
spec exercising the panel fieldGroup and a Playwright e2e that drives
the dialog end-to-end.
2026-04-27 15:04:06 +02:00
Het Savani
baaafbab44
feat:Add a keyboard shortcut to collapse/expand groups (#7370)
* feat:Add a keyboard shortcut to collapse/expand groups

* fix(collapsible): scope group behavior to isGroup and address review feedback

* fix(collapsible): scope group behavior, fix a11y focus, clean CSS, and update docs

* feat(work-view): apply isGroup to Overdue/Later/Done/Recurring sections

Aligns implementation with the wiki keyboard-shortcuts docs added in this
PR — those sections are described as participating in the expand/collapse-all
group shortcuts but were missing the [isGroup]="true" input.

* feat(tasks): ArrowLeft on top-level task collapses parent group

When a top-level task (no parent) is focused and the existing arrow
handling would otherwise call focusPrevious, hand off to the closest
ancestor collapsible group instead: collapse it and move focus to the
group header. Makes the new group shortcuts reachable from the normal
task-driven keyboard flow rather than requiring a Tab to the header.

Sub-tasks and selected-task hide-detail behavior are unchanged.

* feat(collapsible): ArrowUp/Down on group header focuses adjacent task

When a group header is focused, ArrowDown moves focus into the next
<task> element in document order (the first task of the group when
expanded; the next group's first task when collapsed). ArrowUp moves
focus to the previous task. Pairs with the ArrowLeft hand-off so the
group shortcut and task navigation form a single continuous keyboard
flow.

* feat(tasks): ArrowUp/Down on group-edge task focuses the header

ArrowUp on the first task of a group focuses the current group's
header; ArrowDown on the last task focuses the next group's header.
Routed through new handleArrowUp/handleArrowDown methods so other
focusPrevious/focusNext callsites (move-to-backlog, etc.) keep their
existing semantics.

* refactor(util): extract findAdjacentFocusable for arrow nav

Three places had near-identical DOM-walking logic for "find the next/prev
focusable element across tasks and group headers". Consolidates them
into a single utility with 9 unit tests, plus a shared GROUP_NAV_SELECTOR
constant exported from collapsible.component.

Behavior change: ArrowUp/Down on a group header now considers other
collapsed group headers as next-focusable (previously walked only across
<task> elements). For an all-collapsed list, ArrowDown on a header now
moves to the next header instead of skipping to a far-away task.

* refactor: trim findAdjacentFocusable + tighten collapsible API surface

Multi-agent review consensus:
- Drop the compareDocumentPosition fallback in findAdjacentFocusable.
  Both real callers pass an element matching the selector; the fallback
  branch only existed to satisfy a synthetic test. Util shrinks to ~10
  lines of obvious code.
- Re-privatize setAllGroupExpanded and expandIfCollapsed — neither is
  called from outside CollapsibleComponent.
- Scope focusHeader's selector to ':scope > .collapsible-header' so a
  nested collapsible projected through ng-content can't steal focus.

---------

Co-authored-by: Johannes Millan <johannes.millan@gmail.com>
2026-04-27 14:38:44 +02:00
aakhter
2226db7a14
feat(mentions): substring match in tag/project/date autocomplete (#7376)
* feat(mentions): match substrings instead of only prefixes

The default mention autocomplete filter (used by #tags, @due dates,
and +projects in task titles) only matched items whose label started
with the search string. Switch to substring matching so typing 'aa'
matches a tag named 'xxaaxx'.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(mentions): rank prefix matches above mid-string matches

Sort filtered results by indexOf(searchString) ascending so items whose
label starts with the query appear above items where the match is in the
middle. The pre-existing alphabetical ordering from addConfig() is
preserved as a tiebreaker via the stable sort.

Refactors the filter to share a single getLabel() helper between the
filter and sort steps.

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Johannes Millan <johannes.millan@gmail.com>
2026-04-27 14:38:18 +02:00
Johannes Millan
513e079f4f feat(boards): drag-and-drop reorder of board tabs
Mirrors the issue-panel tab-drag pattern: cdkDropList on the mat-tab-group
with cdkDrag on each user-board label. Drop dispatches a new BoardsActions.sortBoards
action persisted via op-log (OpType.Move, isBulk).

Closes #4163
2026-04-27 13:18:58 +02:00
Johannes Millan
216dde16ef fix(schedule): guard formatDate against unregistered locale (NG0701)
Non-default locale data is registered lazily via requestIdleCallback
(commit d989c064f3). If the schedule view renders before the idle
callback fires — e.g. cold start with zh-cn during initial sync replay —
formatDate(date, fmt, locale) throws NG0701 "Missing locale data".

Wrap the four schedule formatDate call sites in a safeFormatDate helper
that falls back to DEFAULT_LOCALE on throw. After the idle callback
registers the user's locale, any signal change re-runs the computed
and the user's locale takes effect.

Refs #7383
2026-04-27 13:18:58 +02:00
Johannes Millan
c2d678ab3a fix(focus-mode): respect isSkipPreparation in sync flow (#7384)
When 'sync focus sessions with time tracking' was enabled, selecting a
task auto-started the session and bypassed the preparation screen even
if 'skip preparation screen' was off. The two settings should be
independent.

syncTrackingStartToSession$ now early-returns when isSkipPreparation is
off, leaving the user on the preparation screen (already shown by
autoShowOverlay$) so they must click 'Start' to trigger the rocket
animation — matching the manual-start flow in focus-mode-main.
2026-04-27 13:18:58 +02:00
Johannes Millan
59ce653351 fix(logs): show log dialog with copy & share options (#7372)
Replace the misleading "downloaded to documents folder" toast with a
dialog that displays the logs in a textarea and offers Copy and (on
native) Share file actions, so users can always retrieve logs even
when the system share sheet fails silently or app-private storage
is invisible to file managers on Android 11+.

Copy uses ShareService.copyToClipboard so the execCommand fallback
covers older Android WebViews — the same class of silent-failure
platform that motivated the dialog.
2026-04-27 13:18:58 +02:00
Johannes Millan
856786fa6c fix(task-repeat-cfg): only dispatch changed fields on edit save
The edit dialog dispatched updateTaskRepeatCfg with the entire
TaskRepeatCfg object as the changes payload. rescheduleTaskOnRepeatCfgUpdate$
filters by `field in changes`, so every save matched the filter — even when
only the time changed. The effect then asked getNextRepeatOccurrence for the
next slot with lastTaskCreationDay === today, which always returns tomorrow,
shifting today's instance forward by one day per save.

Compute and dispatch a true delta. Reuse distinctUntilChangedObject for
deep array comparison. Derive isRelevantChangesForUpdateAllTasks from the
delta so we don't diff twice.

Fixes #7373
2026-04-27 13:18:58 +02:00
Johannes Millan
60b724887a feat(bottom-panel): smooth mobile swipe-to-close gesture
Real-time drag tracking with velocity-based dismiss decision for the
mobile bottom sheet:

- Custom pointer-event handler on the panel header drags the sheet
  height in 1:1 with the finger; touch-action: none on the header lets
  pointermove be passive (no main-thread arbitration per event).
- Pointer listeners run outside the Angular zone — drag state is not
  template-bound, so per-event change detection was pure overhead.
- Single-pointer gesture with setPointerCapture; multi-touch and
  cross-pointer events are rejected.
- pointercancel resets state without invoking the close decision so
  OS-interrupted gestures do not dismiss the sheet.
- Release decision: upward fling expands; downward close requires
  velocity floor AND projected end-position past the close zone
  (Apple WWDC18 / Vaul / Android BottomSheetBehavior pattern). Held
  finger and slow drags never trigger close.
- Close animation uses translateY for compositor-only paint, with
  velocity-coupled duration and easing for natural inertia. Reads
  offsetHeight directly so the slide-off matches the rendered height.
- A .closing class lifts min-height: 20vh through the close animation;
  hand-off from .dragging to .closing is one step to avoid a one-frame
  snap to 20vh between dragend and slide-off.
- Regrab during a close/expand animation cancels the in-flight timers
  and clears residual styles before starting a new drag.
2026-04-26 19:17:21 +02:00
Spyros Seimenis
fede2c6ada
feat(gitea): add label-based include and exclude filters (#7359)
* feat(gitea): add label-based include and exclude filters

Adds two optional config fields to the Gitea issue provider. filterLabels
is a comma-separated allowlist forwarded to the issues endpoint as the
`labels` query param (AND-matched server-side). excludeLabels is a
comma-separated denylist applied client-side, since Gitea/Forgejo's
issues endpoint has no negation syntax. Scoped labels (scope/name) work
with both.

This lets users point multiple Gitea integrations at the same repository
and route disjoint subsets of issues into different Super Productivity
projects, e.g. one project filtering `project/foo` and another excluding
it.

Filters apply only to ingestion (search suggestions and auto-import of
open issues). Already-imported tasks keep refreshing regardless of label
changes, matching how the existing `scope` filter behaves.

* docs(gitea): document label include/exclude filtering

Update the issue-integration comparison page with the new label
allowlist and denylist filters, including scoped-label support.

* feat(gitea): enforce filterLabels AND match client-side

Gitea's two issue endpoints (`/repos/{o}/{r}/issues` and
`/repos/issues/search`) parse the `labels=` query param into different
internal fields and produce different semantics (AND vs OR), so the
same `filterLabels` config behaved differently on auto-import vs
manual search. The AND on the auto-import path is also a Gitea bug
(go-gitea/gitea#33509) that may flip to OR upstream at any time.

Apply AND-matching on the client (mirroring how `excludeLabels`
already filters client-side) so behavior is consistent across both
endpoints and independent of server version. The `labels=` query is
still sent as a coarse pre-filter (always a superset of the right
answer regardless of server semantics). Forgejo inherits the same
endpoints from Gitea, so the same fix covers it.
2026-04-26 19:10:18 +02:00
Ivan Noleto
92dea833e8
chore(i18n): update and improve pt-BR translation based on en.json (#7368)
- Synced pt-br.json with the latest en.json keys
- Fixed outdated or incorrect translations
- Improved grammar, clarity, and natural phrasing
- Standardized recurring UI terms for consistency
- Ensured placeholders and interpolation tokens remain correct

This update brings pt-BR translation closer to the source and improves overall UX for Brazilian users.
2026-04-26 11:23:01 +02:00
philkonczyk
4d170e6599
Add 'Print Tasks' plugin (#7369)
* Update community-plugins.json - Add Print Tasks Plugin

* Update community-plugins.json - update print tasks plugin text
2026-04-26 11:19:03 +02:00
Johannes Millan
81560f97af 18.3.0 2026-04-25 22:42:18 +02:00
Johannes Millan
3ae246d030
Feat/issue 7362 9d46d3 (#7363)
* test(e2e): open attachment dialog via detail panel after #7314

The attach-dialog entry point moved out of the task context menu in
PR #7314 and now lives in the detail panel. Update the WebDAV sync
attachment test to use openTaskDetailPanel() and click the attachment
input-item instead of right-clicking and looking for an "Attach" menu
item that no longer exists.

* refactor(tasks): drop dead addAttachment from task context menu

Leftover from #7314, which moved the attach dialog into the detail
panel. The method, its TaskAttachmentService injection, and the
DialogEditTaskAttachmentComponent import are unreachable from the
template.

* fix(api): reject inherited fields when creating subtask via REST

POST /tasks with parentId silently dropped any supplied projectId/tagIds
(the reducer forces tagIds=[] and projectId=parent.projectId), so callers
got 201 with values different from what they sent. Reject the request
with 400 UNSUPPORTED_FIELD instead, symmetric with how subTaskIds and
parentId-on-PATCH are handled.

* refactor(simple-counter): inline countdown wrapper, document set invariant

Inline the single-call-site `_hasStartedRepeatedCountdown` private wrapper.
Promote the `setCountdownRemaining` invariant note to JSDoc so it surfaces
in IDE tooltips at every call site — paused-display is gated by
`hasStartedCountdown`, and writing through `setCountdownRemaining` without
a prior `startCountdown` call would silently leave the value invisible.

* ci(plugins): run unit tests when plugin code changes

New workflow runs each plugin's `npm test` in a parallel matrix when
its directory or a shared package (plugin-api, vite-plugin) changes
on a PR. Detects per-plugin changes via three-dot `git diff` against
the PR base.

* fix(sync): break iOS WebDAV conflict-dialog loop (#7339)

Two compounding bugs trapped iOS WebDAV users in a per-minute conflict
dialog that no button could resolve:

1. FileBasedSyncAdapter's snapshotReplacement heuristic re-fires
   gapDetected on every sync from a non-writing client (clientId \!=
   excludeClient is true forever), so the download keeps coming back
   with snapshotState and OperationLogSyncService keeps throwing
   LocalDataConflictError despite the local clock already dominating
   the remote snapshot. Skip hydration and conflict when
   compareVectorClocks(local, remote) is EQUAL or GREATER_THAN, gated
   on both clocks being non-empty so a fresh client still hydrates a
   legacy/clockless snapshot.

2. SyncWrapperService._openConflictDialog$ filtered undefined out of
   the afterClosed() stream, so a programmatic close (iOS WebView
   lifecycle, re-entry) collapsed the observable and firstValueFrom
   threw EmptyError — the user's Use Local/Use Remote/Cancel click
   never reached the resolution branches. Drop the filter so undefined
   flows through to the existing cancellation path.

The dominate-skip deliberately does NOT append result.newOps to the
op log: VectorClockService.getEntityFrontier is last-write-wins by
seq, and writing historical remote ops at the current tail would
regress per-entity frontiers and let future LWW resolution overwrite
local data. Trade-off documented inline.

Adds an adapter-level integration reproducer that asserts gapDetected
re-fires forever for a non-writing client (the upstream loop trigger),
a 3-client WebDAV e2e that reproduces the loop end-to-end against a
real provider, plus service-level tests for the dominate-skip, the
empty-clock guard, the concurrent-clock conservative path, and
consecutive-sync loop prevention.

* fix(sync): improve Dropbox auth dialog UX on sandboxed Linux (#7139)

The "Get Authorization Code" button silently failed on Flatpak because
shell.openExternal rejects without renderer feedback when the
org.freedesktop.portal.Desktop talk-name isn't granted. After the user
gave up and reopened the dialog, the second attempt failed again with
`invalid_grant: invalid code verifier` because each call to
Dropbox.getAuthHelper() generated a fresh PKCE verifier that no longer
matched the originally-shown URL's challenge.

Three changes:

- Cache the in-flight PKCE Promise on the Dropbox provider so concurrent
  callers and consecutive dialog opens share one verifier+URL pair.
  Cleared on successful exchange, on clearAuthCredentials(), and on a
  rejected generation (so a one-time crypto failure doesn't poison the
  session). Five regression tests cover reuse, success-clear, explicit
  clear, concurrent calls, and rejection-recovery.

- Render the auth URL as user-selectable text under a <details>
  disclosure. Escape hatch when both shell.openExternal and the
  clipboard portal are denied — the user can triple-click to select and
  Ctrl+C the URL into a manually-opened browser. Adds
  D_AUTH_CODE.MANUAL_URL_HINT translation key.

- Pipe shell.openExternal rejections through
  errorHandlerWithFrontendInform so the existing IPC.ERROR snack
  channel surfaces a "Could not open the link in your browser" message
  instead of swallowing the failure to electron-log. Wrapped in a
  try/catch since errorHandlerWithFrontendInform throws synchronously
  if the renderer isn't ready.

The Flathub manifest also needs --talk-name=org.freedesktop.portal.Desktop
and --socket=wayland to fully fix the user-reported issue, but that
change lives in the flathub repo.

* refactor(sync): rename dialog-sync-initial-cfg to dialog-sync-cfg

Pure rename — no behavior change. The component is the canonical sync
config dialog, used both for first-time setup and editing. The "Initial"
qualifier was misleading once it became the only sync-config surface
(see #7362).

* refactor(sync): consolidate sync actions into the sync dialog

Move Re-authenticate, Force overwrite, and Restore from history into
DialogSyncCfgComponent so the dialog is the canonical surface for sync
configuration and management.

- Re-authenticate (OAuth providers, currently Dropbox) shown inline
  when the active provider has getAuthHelper() and is already authed.
  Bypasses the dirty-form gate so credentials can refresh without
  losing in-progress edits.
- Force overwrite and Restore from history live in a new "Advanced"
  section gated on isWasEnabled() (existing config) and disabled when
  the form is dirty with a "Save changes first" tooltip. Restore stays
  SuperSync-only.
- Force overwrite reuses the existing native confirm in
  SyncWrapperService.forceUpload() — no extra confirmation dialog to
  avoid double-confirm on the other 5 internal callers.

The legacy buttons on the settings page are removed in a follow-up
commit.

Refs #7362

* refactor(sync): move WebDAV Test Connection button into the sync dialog

Test Connection was previously injected into the inline sync form on
the settings page. It needs to live wherever the sync form is
rendered. The next commit removes the inline form, so move the
injection into DialogSyncCfgComponent first.

No user-visible change: the button still appears in the WebDAV
section of the sync form, just sourced from the dialog component now.

* refactor(config-page): replace inline sync form with status row + buttons

The Sync & Backup tab now hosts a compact status surface, not a full
form clone:

- When sync is disabled or unconfigured: empty-state hint + "Set up
  sync" primary button.
- When configured: provider name, optional "Authentication required"
  pill (OAuth providers) and "Encrypted" pill, then "Sync now" primary
  button + "Configure" secondary button.

The dialog is the canonical sync config surface — reachable from this
tab, the header sync icon (right-click / long-press), or
SyncWrapperService when first-time setup is needed. Force overwrite
and Restore from history live inside the dialog now (see prior commit).

Removes _buildSyncFormConfig (~250 lines of formly button injection),
the empty authStatus placeholder field in SYNC_FORM, and the unused
tour-syncSection class.

Refs #7362

* refactor(sync): consolidate BTN_FORCE_OVERWRITE translation key

The SUPER_SYNC.BTN_FORCE_OVERWRITE key was a duplicate with no
consumers — its English copy ("Force Overwrite Server") even drifted
from the canonical F.SYNC.S.BTN_FORCE_OVERWRITE ("Force Overwrite").

The third occurrence under D_ENTER_PASSWORD ("Use Local Data") stays
— that's a different conflict-resolution action, not a duplicate.

Refs #7362

* refactor(sync): simplify sync dialog — collapse advanced fields, kebab menu

The previous "Advanced" zone (hr + heading + hint + button stack) plus
always-visible interval/manual-only/compression toggles made the dialog
visually noisy. Two changes:

- Move syncInterval and isManualSyncOnly into the existing
  "Advanced Config" collapsible alongside compression. The collapsible
  is hidden for SuperSync (which uses fixed settings) — most users
  never need to expand it.
- Move Force overwrite + Restore from history out of the dialog body
  into a kebab (more_vert) menu in the dialog title row. They act on
  saved config — the kebab placement makes that scope clear and removes
  the dirty-form gate / "Save changes first" ambiguity.

The kebab is hidden during first-time setup (gated on isWasEnabled).
The Re-authenticate button stays inline as before.

Drops three translation keys added in the prior commit (ADVANCED,
ADVANCED_HINT, SAVE_FIRST_HINT) — no longer referenced.

Refs #7362

* fix(sync): drop primary color from Cancel button in sync dialog

Cancel is a secondary action; only the affirmative button (Save)
should carry the primary color.

* fix(sync): clarify Dropbox info text for the new dialog flow

The previous copy said "Click the button below to authenticate" — but
in the consolidated dialog there is no inline Authenticate button for
first-time setup; OAuth runs as part of Save. Make the copy describe
the actual flow instead of pointing at a button that no longer exists.

* refactor(sync): move Force overwrite + Restore into the Advanced collapsible

The kebab menu introduced earlier hid Force overwrite and Restore from
history behind a small icon and required users to know that "more_vert"
in the dialog title contained sync actions. Fold them into the existing
top-level collapsible instead — the same one that already hosts sync
interval, manual-only, and compression toggles.

- Rename the collapsible's label from "Advanced Config" to "Advanced"
  via a new sync-specific translation key (the global ADVANCED_CFG key
  is shared with issue providers, so we don't touch it).
- The dialog component appends Force overwrite (warn) and Restore from
  history (SuperSync only) to the collapsible's fieldGroup in edit
  mode. First-time setup keeps the original SuperSync hide so the
  collapsible never appears empty.

Re-authenticate stays as an inline button below the form because its
visibility depends on an async provider.isReady() check that doesn't
fit Formly's sync hideExpression.

Refs #7362

* refactor(sync): single Advanced collapsible per provider, all actions inside

Each provider now has exactly one "Advanced" collapsible:
- non-SuperSync: top-level (interval, manual-only, compression,
  enable-encryption, plus injected Re-authenticate / Force overwrite
  in edit mode)
- SuperSync: nested in the SuperSync section (server URL, plus injected
  Force overwrite / Restore from history in edit mode)

The inner SuperSync collapsible's label switches from "Advanced Config"
to "Advanced" so both surfaces read the same. Re-authenticate moves
from a button below the form into the non-SuperSync Advanced collapsible
as a Formly button gated on `syncProvider === Dropbox`. Drops the async
provider.isReady() check — re-auth is shown for Dropbox in edit mode
regardless, since `force=true` works for both stale-token and switching
accounts.

Honors the rule that no buttons sit below the Advanced collapsible
inside the dialog.

Refs #7362

* refactor(sync): use stroked style for all dialog buttons + add Nextcloud test

- Every action button inside the sync dialog now uses btnStyle: 'stroked'
  for a consistent outlined appearance: Re-authenticate, Force overwrite,
  Restore from history, WebDAV/Nextcloud Test connection, file-based and
  SuperSync Enable encryption, SuperSync Get token, LocalFile folder
  pickers.
- Force overwrite keeps btnType: 'warn' so it stays warn-coloured but as
  an outline rather than a filled warn button.
- The conditional stroked-when-token-set toggle on Get token is dropped
  in favour of always-stroked.
- Re-authenticate and Restore previously misused btnType: 'stroked' (a
  color slot) instead of btnStyle: 'stroked' (the actual style flag) —
  the formly-btn template ignored the unrecognised color, so they
  rendered as filled buttons. Fixed.
- Adds a Test Connection button to the Nextcloud section, matching the
  WebDAV one — Nextcloud's serverUrl + userName are translated into the
  WebDAV-shaped baseUrl client-side before invoking WebdavApi.testConnection.

Refs #7362

* refactor(sync): apply multi-review fixes — fragility, races, dedup, lifecycle

Cross-validated findings from the multi-agent review:

**Correctness / lifecycle**
- `fields` becomes a `computed` signal of `_getFields(isWasEnabled())`,
  removing the manual `fields.set()` re-sync after the enabled flag
  flips. Single source of truth.
- Reset `_tmpUpdatedCfg._isInitialSetup = false` when the dialog opens
  in edit mode so SuperSync encryption-warning hideExpressions stop
  treating returning users as first-timers.
- Replace ad-hoc `Subscription` aggregator with `takeUntilDestroyed` on
  both subscriptions in the dialog component.

**Race conditions**
- `syncSettingsForm$` subscription on the settings page now goes through
  `switchMap` so a fresh emission cancels any in-flight `provider.isReady()`
  probe — late callbacks can no longer overwrite newer state.
- Drop the redundant `_cd.markForCheck()` after `signal.set()` — signals
  integrate with OnPush automatically.
- Use `??` instead of `||` when preserving `globalCfg` flags during
  provider switch, so an explicit `false` is honoured.

**De-duplication**
- Promote `NextcloudProvider._buildNextcloudBaseUrl` to a public static
  `buildBaseUrl()`. Dialog's `_testNextcloudConnection` now imports it
  rather than duplicating the URL-building logic.
- New `OAUTH_SYNC_PROVIDERS` set in `provider.const.ts`. Re-auth button's
  hideExpression and the settings-page `requiresAuth` derivation can both
  reference it instead of hard-coding `Dropbox`.

**Simplicity**
- Settings page `syncStatus` collapses from 5 fields to 3 (providerId,
  needsAuth, isEncrypted) — empty state derives from `providerId === null`.
- Drop redundant `D_INITIAL_CFG.ADVANCED` translation key in favour of
  the existing `T.G.ADVANCED_CFG`.

**Security / logging**
- Re-auth catch path now logs `{ name: e.name }` instead of the raw error
  object — log history is exportable, no auth detail leakage.

Refs #7362

* refactor(sync): apply pass-2 review fixes — error paths, marker, factory

Cross-validated findings from the second multi-agent review:

**Correctness — keep the syncStatus stream alive on probe failure**
- Wrap the inner async block in try/catch. Previously, a rejected
  `provider.isReady()` would propagate as an observable error through
  switchMap, killing the outer subscription and freezing the status
  pill. On failure, default to `needsAuth: true` so the row stays
  meaningful.
- Replace the imperative `subscribe + .set` bridge with `toSignal()`.

**Security — finish the redaction**
- The first pass only redacted SyncLog.err; the snack `translateParams`
  still passed raw `e.message` into a `[innerHtml]` sink. Snack copy
  now uses the same `_redactErrorName(e)` helper so neither surface
  carries token/URL/stack details. Helper handles `null`/`undefined`
  thrown values explicitly.

**Architecture — structural marker decouples routing from i18n**
- Both Advanced collapsibles now carry `props.syncRole: 'advanced'`.
  The dialog routes on this stable identifier instead of the shared
  `T.G.ADVANCED_CFG` translation key (also used by Jira/Azure DevOps
  forms — a global rename would have silently broken sync).

**Simplicity — collapse 5 button factories into one**
- New `_actionBtn({ text, onClick, btnType?, hideExpression?, className? })`
  helper. Each per-action factory becomes a 3-4 line call site. ~60
  lines net reduction in the dialog component.
- Drop the orphan `props: { dropboxAuth: true }` marker on the Dropbox
  fieldGroup — its consumer (`_buildSyncFormConfig`) was deleted.

Refs #7362

* refactor(sync): apply pass-3 review fixes — auth label asymmetry, dead snack param

Pass-3 review surfaced two real findings on top of polish:

**Correctness — non-OAuth providers no longer mislabelled "needs auth"**
- The pass-2 try/catch returned `needsAuth: true` unconditionally on
  probe failure, which would surface "Authentication required" for
  WebDAV/Nextcloud/LocalFile — providers that don't have an auth
  helper. Now we capture `requiresAuth` BEFORE the throwable
  `isReady()` call and reuse it in the catch, so non-OAuth providers
  fall through to `needsAuth: false` even on transient failures.

**Simplicity — drop the dead snack translateParams**
- The `INCOMPLETE_CFG` translation key has no `{{error}}` placeholder,
  so the redacted error name was silently dropped by the translation
  pipe. Removing the param documents the actual contract: the snack
  shows static credentials-missing copy; the discriminator goes only
  to the (redacted) log.

**Polish — cleaner types, tighter helper**
- `_redactErrorName` collapses to two-arm helper: `Error.name` for
  Error instances, `'UnknownError'` for everything else. The
  null/undefined/typeof branches were exporting internal jargon to
  the user.
- The `props.syncRole` marker now uses a typed `SyncCollapsibleProps
  extends FormlyFieldProps` interface (exported from sync-form.const)
  instead of a `Record<string, unknown>` cast. Eliminates the cast at
  both write and read sites.

Refs #7362

* refactor(sync): polish round — shareReplay, subscription cleanup, doc tightening

Three deferred items from prior reviews now applied:

- shareReplay({bufferSize:1, refCount:true}) on syncSettingsForm$. The
  config-page subscribes long-term and the dialog re-subscribes per
  open; previously the no-provider branch re-fetched the
  sync-config-default-override.json asset on every fresh subscription.
  Cold-start cost is now amortised across both consumers.
- Drop the manual Subscription aggregator on ConfigPageComponent. The
  remaining cfg$ + queryParams subscriptions now use
  takeUntilDestroyed(this._destroyRef); ngOnDestroy + OnDestroy go
  away.
- Tighten dialog _isInitialSetup handling. Pass-3 review noted the
  pre-set + Object.assign pattern reads as if order matters when it
  doesn't. Move the flag into the spread payload so the intent is
  obvious at the call site, and use \!v.isEnabled directly so the
  semantics are explicit (true ⇔ first-time setup).
- JSDoc on forceOverwrite() documenting why no Material confirm is
  added — SyncWrapperService.forceUpload already gates the action with
  a native confirmDialog, and that gate also serves the 5 internal
  snackbar callers (LockPresentError / EmptyRemoteBody / JsonParse /
  LegacySyncFormatDetected / retry). Wrapping here would double-confirm.

Refs #7362

* refactor(sync): pass-4 polish — refCount:false, widen updateTmpCfg, trim docs

Cross-validated findings from the fourth review pass:

- shareReplay flips to refCount:false. Pass-4 reviewer noted that
  refCount:true only deduplicated the rare case where the dialog
  opens *while the settings page is mounted*. The far more common
  path — header-icon → dialog with no settings page open — saw the
  dialog become the sole subscriber, complete via .pipe(first()),
  and drop refCount to 0, so the next open re-fetched the JSON
  default-override anyway. With refCount:false the cached value is
  retained for the lifetime of SyncConfigService, matching the
  comment's stated intent at negligible memory cost.
- updateTmpCfg signature widens to `SyncConfig & { _isInitialSetup?:
  boolean }`. Drops the call-site cast (a code smell that pretended
  the type was wider than it was) and documents that _isInitialSetup
  is a real, expected payload field.
- Trim the misleading comment around `_isInitialSetup: \!v.isEnabled`.
  The "Spread last so Object.assign honours this" line wasn't true —
  it's an object literal property, not a spread. New comment states
  the actual semantics: first-time setup ⇔ sync was previously
  disabled.
- Trim forceOverwrite() JSDoc from 6 lines to 2 — same content,
  matches the project's preference for terse method comments.

Refs #7362
2026-04-25 22:39:22 +02:00
Johannes Millan
b642415702 fix(sync): improve Dropbox auth dialog UX on sandboxed Linux (#7139)
The "Get Authorization Code" button silently failed on Flatpak because
shell.openExternal rejects without renderer feedback when the
org.freedesktop.portal.Desktop talk-name isn't granted. After the user
gave up and reopened the dialog, the second attempt failed again with
`invalid_grant: invalid code verifier` because each call to
Dropbox.getAuthHelper() generated a fresh PKCE verifier that no longer
matched the originally-shown URL's challenge.

Three changes:

- Cache the in-flight PKCE Promise on the Dropbox provider so concurrent
  callers and consecutive dialog opens share one verifier+URL pair.
  Cleared on successful exchange, on clearAuthCredentials(), and on a
  rejected generation (so a one-time crypto failure doesn't poison the
  session). Five regression tests cover reuse, success-clear, explicit
  clear, concurrent calls, and rejection-recovery.

- Render the auth URL as user-selectable text under a <details>
  disclosure. Escape hatch when both shell.openExternal and the
  clipboard portal are denied — the user can triple-click to select and
  Ctrl+C the URL into a manually-opened browser. Adds
  D_AUTH_CODE.MANUAL_URL_HINT translation key.

- Pipe shell.openExternal rejections through
  errorHandlerWithFrontendInform so the existing IPC.ERROR snack
  channel surfaces a "Could not open the link in your browser" message
  instead of swallowing the failure to electron-log. Wrapped in a
  try/catch since errorHandlerWithFrontendInform throws synchronously
  if the renderer isn't ready.

The Flathub manifest also needs --talk-name=org.freedesktop.portal.Desktop
and --socket=wayland to fully fix the user-reported issue, but that
change lives in the flathub repo.
2026-04-25 22:36:14 +02:00
Johannes Millan
654f4d80ee fix(sync): break iOS WebDAV conflict-dialog loop (#7339)
Two compounding bugs trapped iOS WebDAV users in a per-minute conflict
dialog that no button could resolve:

1. FileBasedSyncAdapter's snapshotReplacement heuristic re-fires
   gapDetected on every sync from a non-writing client (clientId \!=
   excludeClient is true forever), so the download keeps coming back
   with snapshotState and OperationLogSyncService keeps throwing
   LocalDataConflictError despite the local clock already dominating
   the remote snapshot. Skip hydration and conflict when
   compareVectorClocks(local, remote) is EQUAL or GREATER_THAN, gated
   on both clocks being non-empty so a fresh client still hydrates a
   legacy/clockless snapshot.

2. SyncWrapperService._openConflictDialog$ filtered undefined out of
   the afterClosed() stream, so a programmatic close (iOS WebView
   lifecycle, re-entry) collapsed the observable and firstValueFrom
   threw EmptyError — the user's Use Local/Use Remote/Cancel click
   never reached the resolution branches. Drop the filter so undefined
   flows through to the existing cancellation path.

The dominate-skip deliberately does NOT append result.newOps to the
op log: VectorClockService.getEntityFrontier is last-write-wins by
seq, and writing historical remote ops at the current tail would
regress per-entity frontiers and let future LWW resolution overwrite
local data. Trade-off documented inline.

Adds an adapter-level integration reproducer that asserts gapDetected
re-fires forever for a non-writing client (the upstream loop trigger),
a 3-client WebDAV e2e that reproduces the loop end-to-end against a
real provider, plus service-level tests for the dominate-skip, the
empty-clock guard, the concurrent-clock conservative path, and
consecutive-sync loop prevention.
2026-04-25 22:36:14 +02:00
Johannes Millan
6365d8a7ee refactor(simple-counter): inline countdown wrapper, document set invariant
Inline the single-call-site `_hasStartedRepeatedCountdown` private wrapper.
Promote the `setCountdownRemaining` invariant note to JSDoc so it surfaces
in IDE tooltips at every call site — paused-display is gated by
`hasStartedCountdown`, and writing through `setCountdownRemaining` without
a prior `startCountdown` call would silently leave the value invisible.
2026-04-25 22:36:14 +02:00
Johannes Millan
b3dfeaaf18 fix(api): reject inherited fields when creating subtask via REST
POST /tasks with parentId silently dropped any supplied projectId/tagIds
(the reducer forces tagIds=[] and projectId=parent.projectId), so callers
got 201 with values different from what they sent. Reject the request
with 400 UNSUPPORTED_FIELD instead, symmetric with how subTaskIds and
parentId-on-PATCH are handled.
2026-04-25 22:36:14 +02:00
Johannes Millan
f2a89d56e2 refactor(tasks): drop dead addAttachment from task context menu
Leftover from #7314, which moved the attach dialog into the detail
panel. The method, its TaskAttachmentService injection, and the
DialogEditTaskAttachmentComponent import are unreachable from the
template.
2026-04-25 22:36:14 +02:00
Het Savani
f49683c93b
fix:google calendar text exceeding background (#7361)
* fix:google calendar text exceeding background

* Chore: removed comments

* fix(issue-panel): wrap long provider names instead of clipping

Replace the clip-and-tooltip approach with white-space: normal on the
button label so long provider names (e.g. "Google Calendar (iCal)")
wrap to a second line rather than overflowing or being silently cut
off. Also reverts unrelated package-lock, source-map, and lint-comment
changes that snuck into the original PR.

Refs #7331

---------

Co-authored-by: Johannes Millan <johannes.millan@gmail.com>
2026-04-25 16:14:59 +02:00
Artur Martins
d0cb24e770
Change AutoPlan plugin URLs to Codeberg (#7347)
Updated URLs for AutoPlan plugin to point to Codeberg since the github repo https://github.com/00sapo/sp-autoplan was archived on the 22nd Feb 2026.
2026-04-25 15:50:31 +02:00
Spyros Seimenis
b86b74130c
fix(plugins): pass issueNumber into ctx for plugin field mappings (#7360)
The plugin-api contract for fieldMapping.toTaskValue/toIssueValue declares
ctx as { issueId: string; issueNumber?: number }, but the host adapter
was constructing ctx with issueId only at both call sites
(_extractTaskFieldsFromIssueWithSyncValues and _applyFieldMappingPull).

This caused mappings that interpolated ctx.issueNumber, like the GitHub
plugin's title mapping (`#${ctx.issueNumber} ${title}`), to render
"#undefined ..." whenever the title was pulled via the update path.
The initial add-task path was unaffected because titles came pre-formatted
from mapSearchResult.

Reads issue.number from the PluginIssue record at both sites and
includes it in ctx, falling back to undefined when absent so non-GitHub
plugins are unaffected.
2026-04-25 15:45:40 +02:00