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
This commit is contained in:
Johannes Millan 2026-04-25 22:39:22 +02:00 committed by GitHub
parent f9514ae477
commit 3ae246d030
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 816 additions and 719 deletions

View file

@ -331,7 +331,7 @@ export class SuperSyncPage extends BasePage {
await this.page.waitForTimeout(1000);
// Define locators for dialogs we might see
const configDialog = this.page.locator('dialog-sync-initial-cfg');
const configDialog = this.page.locator('dialog-sync-cfg');
const passwordDialog = this.page.locator('dialog-enter-encryption-password');
const enableEncryptionDialog = this.page.locator('dialog-enable-encryption');
@ -903,7 +903,7 @@ export class SuperSyncPage extends BasePage {
}
// Client B: legacy password dialog (dialog-enter-encryption-password vs
// dialog-sync-initial-cfg password prompt)
// dialog-sync-cfg password prompt)
const legacyPwVisible = await passwordDialog.isVisible().catch(() => false);
if (legacyPwVisible) {
console.log('[SuperSyncPage] Password dialog — entering password');

View file

@ -222,9 +222,9 @@ export class MainHeaderComponent implements OnDestroy {
if (this.dialogSyncCfgRef) {
return;
}
const { DialogSyncInitialCfgComponent } =
await import('../../imex/sync/dialog-sync-initial-cfg/dialog-sync-initial-cfg.component');
this.dialogSyncCfgRef = this.matDialog.open(DialogSyncInitialCfgComponent);
const { DialogSyncCfgComponent } =
await import('../../imex/sync/dialog-sync-cfg/dialog-sync-cfg.component');
this.dialogSyncCfgRef = this.matDialog.open(DialogSyncCfgComponent);
this._subs.add(
this.dialogSyncCfgRef.afterClosed().subscribe(() => {
this.dialogSyncCfgRef = null;

View file

@ -8,7 +8,16 @@ import {
loadSyncProviders,
LocalFileSyncPicker,
} from '../../../op-log/sync-providers/sync-providers.factory';
import { FormlyFieldConfig } from '@ngx-formly/core';
import { FormlyFieldConfig, FormlyFieldProps } from '@ngx-formly/core';
/**
* Stable structural marker on the "Advanced" collapsibles so the dialog
* component can route action-button injection without depending on the
* (globally shared) translation key in `props.label`.
*/
export interface SyncCollapsibleProps extends FormlyFieldProps {
syncRole?: 'advanced';
}
import { IS_NATIVE_PLATFORM } from '../../../util/is-native-platform';
import { SUPER_SYNC_DEFAULT_BASE_URL } from '../../../op-log/sync-providers/super-sync/super-sync.model';
import {
@ -168,6 +177,7 @@ export const SYNC_FORM: ConfigFormSection<SyncConfig> = {
key: 'syncFolderPath',
templateOptions: {
text: T.F.SYNC.FORM.LOCAL_FILE.L_SYNC_FOLDER_PATH,
btnStyle: 'stroked',
onClick: async () => {
const providers = await loadSyncProviders();
const localProvider = providers.find(
@ -203,6 +213,7 @@ export const SYNC_FORM: ConfigFormSection<SyncConfig> = {
key: 'safFolderUri',
templateOptions: {
text: T.F.SYNC.FORM.LOCAL_FILE.L_SYNC_FOLDER_PATH,
btnStyle: 'stroked',
onClick: async () => {
// NOTE: this actually sets the value in the model
const providers = await loadSyncProviders();
@ -309,8 +320,6 @@ export const SYNC_FORM: ConfigFormSection<SyncConfig> = {
hideExpression: (m, v, field) =>
field?.parent?.model.syncProvider !== SyncProviderId.Dropbox,
resetOnHide: false,
// Custom marker for identifying this field group in config-page.component.ts
props: { dropboxAuth: true } as any,
fieldGroup: [
{
type: 'tpl',
@ -319,49 +328,9 @@ export const SYNC_FORM: ConfigFormSection<SyncConfig> = {
text: T.F.SYNC.FORM.DROPBOX.INFO_TEXT,
},
},
{
type: 'tpl',
key: 'authStatus',
className: 'auth-status-indicator',
templateOptions: {
tag: 'p',
// Text will be set dynamically in config-page.component.ts
text: '',
},
},
// Authentication button will be added programmatically in config-page.component.ts
],
},
{
key: 'syncInterval',
type: 'duration',
// NOTE: we don't hide because model updates don't seem to work properly for this
// hideExpression: ((model: DropboxSyncConfig) => !model.accessToken),
// Hide for SuperSync (uses fixed interval) and when manual sync only is enabled
hideExpression: (m, v, field) =>
field?.parent?.model.syncProvider === SyncProviderId.SuperSync ||
field?.parent?.model.isManualSyncOnly === true,
resetOnHide: true,
templateOptions: {
required: true,
isAllowSeconds: true,
label: T.F.SYNC.FORM.L_SYNC_INTERVAL,
description: T.G.DURATION_DESCRIPTION,
},
},
{
key: 'isManualSyncOnly',
type: 'checkbox',
// Only show for file-based providers (Dropbox, WebDAV, LocalFile)
hideExpression: (m, v, field) =>
field?.parent?.model.syncProvider === SyncProviderId.SuperSync ||
field?.parent?.model.syncProvider === null,
templateOptions: {
label: T.F.SYNC.FORM.L_MANUAL_SYNC_ONLY,
},
},
// Encryption status box - shown when encryption is enabled (for any provider)
{
hideExpression: (m: any, v: any, field?: FormlyFieldConfig) =>
@ -423,13 +392,40 @@ export const SYNC_FORM: ConfigFormSection<SyncConfig> = {
},
// COMMON SETTINGS
// Hide for SuperSync - uses fixed settings (no compression config, encryption handled separately)
// Hide for SuperSync during first-time setup (uses fixed settings; no buttons to host).
// The dialog component drops this hide in edit mode and appends action buttons.
{
type: 'collapsible',
hideExpression: (m, v, field) =>
field?.parent?.model.syncProvider === SyncProviderId.SuperSync,
props: { label: T.G.ADVANCED_CFG },
// syncRole is a stable structural marker the dialog routes on, so a
// future global rename of T.G.ADVANCED_CFG cannot silently break it.
props: { label: T.G.ADVANCED_CFG, syncRole: 'advanced' } as SyncCollapsibleProps,
fieldGroup: [
{
key: 'syncInterval',
type: 'duration',
// Hide when manual sync only is enabled (parent.parent reaches the form root)
hideExpression: (m, v, field) =>
field?.parent?.parent?.model?.isManualSyncOnly === true,
resetOnHide: true,
templateOptions: {
required: true,
isAllowSeconds: true,
label: T.F.SYNC.FORM.L_SYNC_INTERVAL,
description: T.G.DURATION_DESCRIPTION,
},
},
{
key: 'isManualSyncOnly',
type: 'checkbox',
// Only show for file-based providers (Dropbox, WebDAV, LocalFile, Nextcloud)
hideExpression: (m, v, field) =>
field?.parent?.parent?.model?.syncProvider === null,
templateOptions: {
label: T.F.SYNC.FORM.L_MANUAL_SYNC_ONLY,
},
},
{
key: 'isCompressionEnabled',
type: 'checkbox',
@ -447,6 +443,7 @@ export const SYNC_FORM: ConfigFormSection<SyncConfig> = {
templateOptions: {
text: T.F.SYNC.FORM.FILE_BASED.BTN_ENABLE_ENCRYPTION,
btnType: 'primary',
btnStyle: 'stroked',
onClick: async (field: FormlyFieldConfig) => {
const result = await openEnableEncryptionDialogForFileBased();
if (result?.success && field?.model) {
@ -473,16 +470,13 @@ export const SYNC_FORM: ConfigFormSection<SyncConfig> = {
text: T.F.SYNC.FORM.SUPER_SYNC.BTN_GET_TOKEN,
tooltip: T.F.SYNC.FORM.SUPER_SYNC.LOGIN_INSTRUCTIONS,
btnType: 'primary',
btnStyle: 'stroked',
centerBtn: true,
onClick: (field: any) => {
const baseUrl = field.model.baseUrl || SUPER_SYNC_DEFAULT_BASE_URL;
window.open(baseUrl, '_blank');
},
},
expressionProperties: {
'templateOptions.btnStyle': (model: any) =>
model.accessToken ? 'stroked' : undefined,
},
},
{
hideExpression: (m, v, field) =>
@ -526,6 +520,7 @@ export const SYNC_FORM: ConfigFormSection<SyncConfig> = {
templateOptions: {
text: T.F.SYNC.FORM.SUPER_SYNC.BTN_ENABLE_ENCRYPTION,
btnType: 'primary',
btnStyle: 'stroked',
onClick: async (field: FormlyFieldConfig) => {
const result = await openEnableEncryptionDialog();
if (result?.success && field?.model) {
@ -540,7 +535,10 @@ export const SYNC_FORM: ConfigFormSection<SyncConfig> = {
type: 'collapsible',
hideExpression: (m, v, field) =>
field?.parent?.parent?.model.syncProvider !== SyncProviderId.SuperSync,
props: { label: T.G.ADVANCED_CFG },
props: {
label: T.G.ADVANCED_CFG,
syncRole: 'advanced',
} as SyncCollapsibleProps,
fieldGroup: [
// Server URL
{

View file

@ -1,4 +1,3 @@
<!--<h1 mat-dialog-title>{{T.F.SYNC.D_CONFLICT.TITLE|translate}}</h1>-->
<h1 mat-dialog-title>{{ T.F.SYNC.D_INITIAL_CFG.TITLE | translate }}</h1>
<mat-dialog-content>
@ -19,7 +18,6 @@
<div class="wrap-buttons">
<button
(click)="close()"
color="primary"
mat-button
>
{{ T.G.CANCEL | translate }}

View file

@ -1,25 +1,28 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { provideNoopAnimations } from '@angular/platform-browser/animations';
import { MatDialogRef } from '@angular/material/dialog';
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
import { TranslateModule } from '@ngx-translate/core';
import { FormlyModule } from '@ngx-formly/core';
import { of } from 'rxjs';
import { DialogSyncInitialCfgComponent } from './dialog-sync-initial-cfg.component';
import { DialogSyncCfgComponent } from './dialog-sync-cfg.component';
import { SyncConfigService } from '../sync-config.service';
import { SyncWrapperService } from '../sync-wrapper.service';
import { SyncProviderManager } from '../../../op-log/sync-providers/provider-manager.service';
import { GlobalConfigService } from '../../../features/config/global-config.service';
import { SyncProviderId } from '../../../op-log/sync-providers/provider.const';
import { SyncConfig } from '../../../features/config/global-config.model';
import { SnackService } from '../../../core/snack/snack.service';
describe('DialogSyncInitialCfgComponent', () => {
let component: DialogSyncInitialCfgComponent;
let fixture: ComponentFixture<DialogSyncInitialCfgComponent>;
let mockDialogRef: jasmine.SpyObj<MatDialogRef<DialogSyncInitialCfgComponent>>;
describe('DialogSyncCfgComponent', () => {
let component: DialogSyncCfgComponent;
let fixture: ComponentFixture<DialogSyncCfgComponent>;
let mockDialogRef: jasmine.SpyObj<MatDialogRef<DialogSyncCfgComponent>>;
let mockSyncConfigService: jasmine.SpyObj<SyncConfigService>;
let mockSyncWrapperService: jasmine.SpyObj<SyncWrapperService>;
let mockProviderManager: jasmine.SpyObj<SyncProviderManager>;
let mockGlobalConfigService: jasmine.SpyObj<GlobalConfigService>;
let mockSnackService: jasmine.SpyObj<SnackService>;
let mockMatDialog: jasmine.SpyObj<MatDialog>;
const baseSyncConfig: SyncConfig = {
isEnabled: false,
@ -55,9 +58,12 @@ describe('DialogSyncInitialCfgComponent', () => {
sync$: of(baseSyncConfig),
});
mockSnackService = jasmine.createSpyObj('SnackService', ['open']);
mockMatDialog = jasmine.createSpyObj('MatDialog', ['open']);
TestBed.configureTestingModule({
imports: [
DialogSyncInitialCfgComponent,
DialogSyncCfgComponent,
TranslateModule.forRoot(),
FormlyModule.forRoot(),
],
@ -68,16 +74,18 @@ describe('DialogSyncInitialCfgComponent', () => {
{ provide: SyncWrapperService, useValue: mockSyncWrapperService },
{ provide: SyncProviderManager, useValue: mockProviderManager },
{ provide: GlobalConfigService, useValue: mockGlobalConfigService },
{ provide: SnackService, useValue: mockSnackService },
{ provide: MatDialog, useValue: mockMatDialog },
],
});
// Replace the Formly-based template with a minimal placeholder so we can
// test the save() business logic without registering every Formly field type.
TestBed.overrideComponent(DialogSyncInitialCfgComponent, {
TestBed.overrideComponent(DialogSyncCfgComponent, {
set: { template: '' },
});
await TestBed.compileComponents();
fixture = TestBed.createComponent(DialogSyncInitialCfgComponent);
fixture = TestBed.createComponent(DialogSyncCfgComponent);
component = fixture.componentInstance;
});

View file

@ -0,0 +1,510 @@
import {
AfterViewInit,
ChangeDetectionStrategy,
Component,
computed,
DestroyRef,
inject,
signal,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
MatDialog,
MatDialogActions,
MatDialogContent,
MatDialogRef,
MatDialogTitle,
} from '@angular/material/dialog';
import { MatButton } from '@angular/material/button';
import { MatIcon } from '@angular/material/icon';
import { TranslatePipe } from '@ngx-translate/core';
import { T } from '../../../t.const';
import {
SYNC_FORM,
SyncCollapsibleProps,
} from '../../../features/config/form-cfgs/sync-form.const';
import { FormGroup, ReactiveFormsModule } from '@angular/forms';
import { FormlyFieldConfig, FormlyModule } from '@ngx-formly/core';
import { SyncConfig } from '../../../features/config/global-config.model';
import {
OAUTH_SYNC_PROVIDERS,
SyncProviderId,
} from '../../../op-log/sync-providers/provider.const';
import { SyncConfigService } from '../sync-config.service';
import { SyncWrapperService } from '../sync-wrapper.service';
import { first, skip } from 'rxjs/operators';
import { toSyncProviderId } from '../../../op-log/sync-exports';
import { SyncLog } from '../../../core/log';
import { SyncProviderManager } from '../../../op-log/sync-providers/provider-manager.service';
import { GlobalConfigService } from '../../../features/config/global-config.service';
import { isOnline } from '../../../util/is-online';
import { SnackService } from '../../../core/snack/snack.service';
import { DialogRestorePointComponent } from '../dialog-restore-point/dialog-restore-point.component';
import { WebdavApi } from '../../../op-log/sync-providers/file-based/webdav/webdav-api';
import { WebdavPrivateCfg } from '../../../op-log/sync-providers/file-based/webdav/webdav.model';
import { NextcloudPrivateCfg } from '../../../op-log/sync-providers/file-based/webdav/nextcloud.model';
import { NextcloudProvider } from '../../../op-log/sync-providers/file-based/webdav/nextcloud';
@Component({
selector: 'dialog-sync-cfg',
templateUrl: './dialog-sync-cfg.component.html',
styleUrls: ['./dialog-sync-cfg.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
MatDialogTitle,
MatDialogContent,
MatDialogActions,
MatButton,
MatIcon,
TranslatePipe,
ReactiveFormsModule,
FormlyModule,
],
})
export class DialogSyncCfgComponent implements AfterViewInit {
syncConfigService = inject(SyncConfigService);
syncWrapperService = inject(SyncWrapperService);
private _providerManager = inject(SyncProviderManager);
private _globalConfigService = inject(GlobalConfigService);
private _matDialog = inject(MatDialog);
private _snackService = inject(SnackService);
private _destroyRef = inject(DestroyRef);
T = T;
isWasEnabled = signal(false);
// Single source of truth — buttons appear/disappear automatically when
// edit mode flips, no manual fields.set() required.
fields = computed<FormlyFieldConfig[]>(() => {
const includeEnabledToggle = this.isWasEnabled();
return SYNC_FORM.items!.filter(
(f) => includeEnabledToggle || f.key !== 'isEnabled',
).map((item) => this._injectProviderHelpers(item));
});
form = new FormGroup({});
/**
* Adds helpers into the formly field tree:
* - Test Connection button inside WebDAV/Nextcloud sections.
* - Re-authenticate, Force Overwrite (and Restore for SuperSync) inside the
* active "Advanced" collapsible (edit mode only first-time setup gets no
* action buttons since there is no saved config to act on).
*
* Each provider has exactly one Advanced collapsible:
* - non-SuperSync: top-level (compression, interval, manual-only) + actions
* - SuperSync: nested inside the SuperSync provider section (server URL) + actions
*/
private _injectProviderHelpers(item: FormlyFieldConfig): FormlyFieldConfig {
if (item.key === 'webDav' && item.fieldGroup) {
return {
...item,
fieldGroup: [...item.fieldGroup, this._webDavTestConnectionBtn()],
};
}
if (item.key === 'nextcloud' && item.fieldGroup) {
return {
...item,
fieldGroup: [...item.fieldGroup, this._nextcloudTestConnectionBtn()],
};
}
if (
item.type === 'collapsible' &&
(item.props as SyncCollapsibleProps | undefined)?.syncRole === 'advanced' &&
this.isWasEnabled()
) {
return {
...item,
fieldGroup: [
...(item.fieldGroup ?? []),
this._reauthBtn(),
this._forceOverwriteBtn(),
],
};
}
if (item.key === 'superSync' && item.fieldGroup && this.isWasEnabled()) {
return {
...item,
fieldGroup: item.fieldGroup.map((child) =>
child.type === 'collapsible' &&
(child.props as SyncCollapsibleProps | undefined)?.syncRole === 'advanced'
? {
...child,
fieldGroup: [
...(child.fieldGroup ?? []),
this._forceOverwriteBtn(),
this._restoreBtn(),
],
}
: child,
),
};
}
return item;
}
/**
* Single helper for every action button rendered inside the form. All
* buttons in the dialog use the stroked style; the caller may add a
* warn `btnType`, a custom className, or a `hideExpression` for
* conditional visibility.
*/
private _actionBtn(opts: {
text: string;
onClick: (model: unknown) => void | Promise<void>;
className?: string;
btnType?: 'warn';
hideExpression?: FormlyFieldConfig['hideExpression'];
}): FormlyFieldConfig {
return {
type: 'btn',
className: opts.className ?? 'mt2 block',
hideExpression: opts.hideExpression,
templateOptions: {
text: opts.text,
btnStyle: 'stroked',
btnType: opts.btnType,
required: false,
onClick: (_field: unknown, _form: unknown, model: unknown) => opts.onClick(model),
},
};
}
private _webDavTestConnectionBtn(): FormlyFieldConfig {
return this._actionBtn({
text: T.F.SYNC.FORM.WEB_DAV.L_TEST_CONNECTION,
className: 'mt3 block',
onClick: (model) => this._testWebDavConnection(model as WebdavPrivateCfg),
});
}
private _nextcloudTestConnectionBtn(): FormlyFieldConfig {
return this._actionBtn({
text: T.F.SYNC.FORM.WEB_DAV.L_TEST_CONNECTION,
className: 'mt3 block',
onClick: (model) => this._testNextcloudConnection(model as NextcloudPrivateCfg),
});
}
private _forceOverwriteBtn(): FormlyFieldConfig {
return this._actionBtn({
text: T.F.SYNC.S.BTN_FORCE_OVERWRITE,
btnType: 'warn',
onClick: () => this.forceOverwrite(),
});
}
private _restoreBtn(): FormlyFieldConfig {
return this._actionBtn({
text: T.F.SYNC.BTN_RESTORE_FROM_HISTORY,
onClick: () => this.restoreFromHistory(),
});
}
// Re-auth is OAuth-only. Gating via OAUTH_SYNC_PROVIDERS keeps this UI
// in lockstep with the provider-side definition without an async probe.
private _reauthBtn(): FormlyFieldConfig {
return this._actionBtn({
text: T.F.SYNC.FORM.DROPBOX.BTN_REAUTHENTICATE,
onClick: () => this.reauth(),
hideExpression: (m, v, field) => {
const id = field?.parent?.parent?.model?.syncProvider as
| SyncProviderId
| undefined;
return !id || !OAUTH_SYNC_PROVIDERS.has(id);
},
});
}
private async _testNextcloudConnection(cfg: NextcloudPrivateCfg): Promise<void> {
if (!cfg?.serverUrl || !cfg?.userName || !cfg?.password || !cfg?.syncFolderPath) {
this._snackService.open({
type: 'ERROR',
msg: T.F.SYNC.FORM.WEB_DAV.S_FILL_ALL_FIELDS,
});
return;
}
await this._testWebDavConnection({
...cfg,
baseUrl: NextcloudProvider.buildBaseUrl(cfg),
} as unknown as WebdavPrivateCfg);
}
private async _testWebDavConnection(webDavCfg: WebdavPrivateCfg): Promise<void> {
if (
!webDavCfg?.baseUrl ||
!webDavCfg?.userName ||
!webDavCfg?.password ||
!webDavCfg?.syncFolderPath
) {
this._snackService.open({
type: 'ERROR',
msg: T.F.SYNC.FORM.WEB_DAV.S_FILL_ALL_FIELDS,
});
return;
}
try {
const api = new WebdavApi(async () => webDavCfg);
const result = await api.testConnection(webDavCfg);
if (result.success) {
this._snackService.open({
type: 'SUCCESS',
msg: T.F.SYNC.FORM.WEB_DAV.S_TEST_SUCCESS,
translateParams: { url: result.fullUrl },
});
} else {
this._snackService.open({
type: 'ERROR',
msg: T.F.SYNC.FORM.WEB_DAV.S_TEST_FAIL,
translateParams: {
error: result.error || 'Unknown error',
url: result.fullUrl,
},
});
}
} catch (e) {
this._snackService.open({
type: 'ERROR',
msg: T.F.SYNC.FORM.WEB_DAV.S_TEST_FAIL,
translateParams: {
error: e instanceof Error ? e.message : 'Unexpected error',
url: (webDavCfg.baseUrl as string) || 'N/A',
},
});
}
}
// Note: _isInitialSetup flag is checked by sync-form.const.ts hideExpressions
// to hide the encryption button/warning (encryption is handled by _promptSuperSyncEncryptionIfNeeded after sync)
_tmpUpdatedCfg: SyncConfig & { _isInitialSetup?: boolean } = {
isEnabled: true,
syncProvider: SyncProviderId.SuperSync,
syncInterval: 300000,
encryptKey: '',
isEncryptionEnabled: false,
localFileSync: {},
webDav: {},
nextcloud: {},
superSync: {},
_isInitialSetup: true,
};
private _matDialogRef = inject<MatDialogRef<DialogSyncCfgComponent>>(MatDialogRef);
constructor() {
this.syncConfigService.syncSettingsForm$
.pipe(first(), takeUntilDestroyed(this._destroyRef))
.subscribe((v) => {
if (v.isEnabled) {
this.isWasEnabled.set(true);
}
// First-time setup ⇔ sync was previously disabled. Encryption-warning
// hideExpressions in sync-form.const.ts read this flag to suppress
// the post-save SuperSync encryption prompt during initial setup.
this.updateTmpCfg({
...v,
isEnabled: true,
_isInitialSetup: !v.isEnabled,
});
});
}
ngAfterViewInit(): void {
// Setup provider change listener after the form is initialized by Formly
// Using setTimeout to ensure the form control exists
setTimeout(() => {
const syncProviderControl = this.form.get('syncProvider');
if (!syncProviderControl) {
SyncLog.warn('syncProvider form control not found');
return;
}
// Listen for provider changes and reload provider-specific configuration
syncProviderControl.valueChanges
.pipe(skip(1), takeUntilDestroyed(this._destroyRef))
.subscribe(async (newProvider: SyncProviderId | null) => {
if (!newProvider) {
return;
}
// Get the current configuration for this provider
const providerId = toSyncProviderId(newProvider);
if (!providerId) {
return;
}
// Load the provider's stored configuration
const provider = await this._providerManager.getProviderById(providerId);
if (!provider) {
// Provider not yet configured, keep current form state
return;
}
const privateCfg = await provider.privateCfg.load();
const globalCfg = await this._globalConfigService.sync$
.pipe(first())
.toPromise();
// Create provider-specific config based on provider type
let providerSpecificUpdate: Partial<SyncConfig> = {};
if (newProvider === SyncProviderId.SuperSync && privateCfg) {
providerSpecificUpdate = {
superSync: privateCfg as any,
encryptKey: privateCfg.encryptKey || '',
// SuperSync stores isEncryptionEnabled in privateCfg, not globalCfg
isEncryptionEnabled: (privateCfg as any).isEncryptionEnabled || false,
};
} else if (newProvider === SyncProviderId.WebDAV && privateCfg) {
providerSpecificUpdate = {
webDav: privateCfg as any,
encryptKey: privateCfg.encryptKey || '',
};
} else if (newProvider === SyncProviderId.LocalFile && privateCfg) {
providerSpecificUpdate = {
localFileSync: privateCfg as any,
encryptKey: privateCfg.encryptKey || '',
};
} else if (newProvider === SyncProviderId.Nextcloud && privateCfg) {
providerSpecificUpdate = {
nextcloud: privateCfg as any,
encryptKey: privateCfg.encryptKey || '',
};
} else if (newProvider === SyncProviderId.Dropbox && privateCfg) {
providerSpecificUpdate = {
encryptKey: privateCfg.encryptKey || '',
};
}
// Update the model, preserving non-provider-specific fields
this._tmpUpdatedCfg = {
...this._tmpUpdatedCfg,
...providerSpecificUpdate,
syncProvider: newProvider,
// Preserve global settings (?? not || so explicit `false` is honoured)
isEnabled: this._tmpUpdatedCfg.isEnabled,
syncInterval: globalCfg?.syncInterval ?? this._tmpUpdatedCfg.syncInterval,
isManualSyncOnly:
globalCfg?.isManualSyncOnly ?? this._tmpUpdatedCfg.isManualSyncOnly,
isCompressionEnabled:
globalCfg?.isCompressionEnabled ?? this._tmpUpdatedCfg.isCompressionEnabled,
};
// For non-SuperSync providers, update encryption from global config
if (newProvider !== SyncProviderId.SuperSync) {
this._tmpUpdatedCfg = {
...this._tmpUpdatedCfg,
isEncryptionEnabled: globalCfg?.isEncryptionEnabled ?? false,
};
}
});
}, 0);
}
close(): void {
this._matDialogRef.close();
}
async save(): Promise<void> {
// Check if form is valid
if (!this.form.valid) {
// Mark all fields as touched to show validation errors
this.form.markAllAsTouched();
SyncLog.err('Sync form validation failed', this.form.errors);
return;
}
// Explicitly sync form values to _tmpUpdatedCfg in case modelChange didn't fire
// This is especially important on Android WebView where change detection can be unreliable
this._tmpUpdatedCfg = {
...this._tmpUpdatedCfg,
...this.form.value,
};
// Strip _isInitialSetup before saving — it's only for form hideExpressions
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { _isInitialSetup, ...cfgWithoutFlag } = this._tmpUpdatedCfg;
const configToSave = {
...cfgWithoutFlag,
isEnabled: this._tmpUpdatedCfg.isEnabled || !this.isWasEnabled(),
};
const providerId = toSyncProviderId(this._tmpUpdatedCfg.syncProvider);
if (providerId && this._tmpUpdatedCfg.isEnabled) {
await this.syncWrapperService.configuredAuthForSyncProviderIfNecessary(providerId);
// If the provider requires auth (e.g. Dropbox) and is still not ready,
// the auth dialog was cancelled or failed. Keep the dialog open so the
// user can retry, and do not persist isEnabled:true with missing credentials
// (which would trigger the "Sync credentials are missing" snack loop — issue #7131).
const provider = await this._providerManager.getProviderById(providerId);
if (provider?.getAuthHelper && !(await provider.isReady())) {
return;
}
}
await this.syncConfigService.updateSettingsFromForm(configToSave as SyncConfig, true);
this._matDialogRef.close();
if (isOnline()) {
this.syncWrapperService.sync();
}
}
updateTmpCfg(cfg: SyncConfig & { _isInitialSetup?: boolean }): void {
// Use Object.assign to preserve the object reference for Formly
// This ensures Formly detects changes to the model
Object.assign(this._tmpUpdatedCfg, cfg);
}
async reauth(): Promise<void> {
const providerId = toSyncProviderId(this._tmpUpdatedCfg.syncProvider);
if (!providerId) {
return;
}
try {
const result =
await this.syncWrapperService.configuredAuthForSyncProviderIfNecessary(
providerId,
true,
);
if (result.wasConfigured) {
this._snackService.open({
type: 'SUCCESS',
msg: T.F.SYNC.FORM.DROPBOX.REAUTH_SUCCESS,
});
}
} catch (e) {
// Log history is exportable, so log only a redacted discriminator —
// never raw `Error.message` (which can carry tokens / URLs / stacks).
// The user-facing snack just shows the static "credentials missing"
// copy; INCOMPLETE_CFG has no error placeholder, so no leak path.
SyncLog.err('Re-auth failed', { name: _redactErrorName(e) });
this._snackService.open({
type: 'ERROR',
msg: T.F.SYNC.S.INCOMPLETE_CFG,
});
}
}
/** Confirmation handled inside `SyncWrapperService.forceUpload` (native
* confirm, shared with snackbar action callers). */
forceOverwrite(): void {
this.syncWrapperService.forceUpload();
}
restoreFromHistory(): void {
this._matDialog.open(DialogRestorePointComponent, {
width: '500px',
maxWidth: '90vw',
});
}
}
/**
* Coarse, redacted discriminator for an unknown thrown value safe for
* exportable log history. Returns the Error subclass name for instances
* (e.g. "TypeError") and a single bucket for everything else.
*/
const _redactErrorName = (e: unknown): string =>
e instanceof Error ? e.name : 'UnknownError';

View file

@ -1,249 +0,0 @@
import {
AfterViewInit,
ChangeDetectionStrategy,
Component,
inject,
signal,
} from '@angular/core';
import {
MatDialogActions,
MatDialogContent,
MatDialogRef,
MatDialogTitle,
} from '@angular/material/dialog';
import { MatButton } from '@angular/material/button';
import { MatIcon } from '@angular/material/icon';
import { TranslatePipe } from '@ngx-translate/core';
import { T } from '../../../t.const';
import { SYNC_FORM } from '../../../features/config/form-cfgs/sync-form.const';
import { FormGroup, ReactiveFormsModule } from '@angular/forms';
import { FormlyFieldConfig, FormlyModule } from '@ngx-formly/core';
import { SyncConfig } from '../../../features/config/global-config.model';
import { SyncProviderId } from '../../../op-log/sync-providers/provider.const';
import { SyncConfigService } from '../sync-config.service';
import { SyncWrapperService } from '../sync-wrapper.service';
import { Subscription } from 'rxjs';
import { first, skip } from 'rxjs/operators';
import { toSyncProviderId } from '../../../op-log/sync-exports';
import { SyncLog } from '../../../core/log';
import { SyncProviderManager } from '../../../op-log/sync-providers/provider-manager.service';
import { GlobalConfigService } from '../../../features/config/global-config.service';
import { isOnline } from '../../../util/is-online';
@Component({
selector: 'dialog-sync-initial-cfg',
templateUrl: './dialog-sync-initial-cfg.component.html',
styleUrls: ['./dialog-sync-initial-cfg.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
MatDialogTitle,
MatDialogContent,
MatDialogActions,
MatButton,
MatIcon,
TranslatePipe,
ReactiveFormsModule,
FormlyModule,
],
})
export class DialogSyncInitialCfgComponent implements AfterViewInit {
syncConfigService = inject(SyncConfigService);
syncWrapperService = inject(SyncWrapperService);
private _providerManager = inject(SyncProviderManager);
private _globalConfigService = inject(GlobalConfigService);
T = T;
isWasEnabled = signal(false);
fields = signal(this._getFields(false));
form = new FormGroup({});
private _getFields(includeEnabledToggle: boolean): FormlyFieldConfig[] {
return SYNC_FORM.items!.filter((f) => includeEnabledToggle || f.key !== 'isEnabled');
}
// Note: _isInitialSetup flag is checked by sync-form.const.ts hideExpressions
// to hide the encryption button/warning (encryption is handled by _promptSuperSyncEncryptionIfNeeded after sync)
_tmpUpdatedCfg: SyncConfig & { _isInitialSetup?: boolean } = {
isEnabled: true,
syncProvider: SyncProviderId.SuperSync,
syncInterval: 300000,
encryptKey: '',
isEncryptionEnabled: false,
localFileSync: {},
webDav: {},
nextcloud: {},
superSync: {},
_isInitialSetup: true,
};
private _matDialogRef =
inject<MatDialogRef<DialogSyncInitialCfgComponent>>(MatDialogRef);
private _subs = new Subscription();
constructor() {
this._subs.add(
this.syncConfigService.syncSettingsForm$.pipe(first()).subscribe((v) => {
if (v.isEnabled) {
this.isWasEnabled.set(true);
this.fields.set(this._getFields(true));
}
this.updateTmpCfg({
...v,
isEnabled: true,
});
}),
);
}
ngAfterViewInit(): void {
// Setup provider change listener after the form is initialized by Formly
// Using setTimeout to ensure the form control exists
setTimeout(() => {
const syncProviderControl = this.form.get('syncProvider');
if (!syncProviderControl) {
SyncLog.warn('syncProvider form control not found');
return;
}
// Listen for provider changes and reload provider-specific configuration
this._subs.add(
syncProviderControl.valueChanges
.pipe(skip(1))
.subscribe(async (newProvider: SyncProviderId | null) => {
if (!newProvider) {
return;
}
// Get the current configuration for this provider
const providerId = toSyncProviderId(newProvider);
if (!providerId) {
return;
}
// Load the provider's stored configuration
const provider = await this._providerManager.getProviderById(providerId);
if (!provider) {
// Provider not yet configured, keep current form state
return;
}
const privateCfg = await provider.privateCfg.load();
const globalCfg = await this._globalConfigService.sync$
.pipe(first())
.toPromise();
// Create provider-specific config based on provider type
let providerSpecificUpdate: Partial<SyncConfig> = {};
if (newProvider === SyncProviderId.SuperSync && privateCfg) {
providerSpecificUpdate = {
superSync: privateCfg as any,
encryptKey: privateCfg.encryptKey || '',
// SuperSync stores isEncryptionEnabled in privateCfg, not globalCfg
isEncryptionEnabled: (privateCfg as any).isEncryptionEnabled || false,
};
} else if (newProvider === SyncProviderId.WebDAV && privateCfg) {
providerSpecificUpdate = {
webDav: privateCfg as any,
encryptKey: privateCfg.encryptKey || '',
};
} else if (newProvider === SyncProviderId.LocalFile && privateCfg) {
providerSpecificUpdate = {
localFileSync: privateCfg as any,
encryptKey: privateCfg.encryptKey || '',
};
} else if (newProvider === SyncProviderId.Nextcloud && privateCfg) {
providerSpecificUpdate = {
nextcloud: privateCfg as any,
encryptKey: privateCfg.encryptKey || '',
};
} else if (newProvider === SyncProviderId.Dropbox && privateCfg) {
providerSpecificUpdate = {
encryptKey: privateCfg.encryptKey || '',
};
}
// Update the model, preserving non-provider-specific fields
this._tmpUpdatedCfg = {
...this._tmpUpdatedCfg,
...providerSpecificUpdate,
syncProvider: newProvider,
// Preserve global settings
isEnabled: this._tmpUpdatedCfg.isEnabled,
syncInterval: globalCfg?.syncInterval || this._tmpUpdatedCfg.syncInterval,
isManualSyncOnly:
globalCfg?.isManualSyncOnly || this._tmpUpdatedCfg.isManualSyncOnly,
isCompressionEnabled:
globalCfg?.isCompressionEnabled ||
this._tmpUpdatedCfg.isCompressionEnabled,
};
// For non-SuperSync providers, update encryption from global config
if (newProvider !== SyncProviderId.SuperSync) {
this._tmpUpdatedCfg = {
...this._tmpUpdatedCfg,
isEncryptionEnabled: globalCfg?.isEncryptionEnabled || false,
};
}
}),
);
}, 0);
}
close(): void {
this._matDialogRef.close();
}
async save(): Promise<void> {
// Check if form is valid
if (!this.form.valid) {
// Mark all fields as touched to show validation errors
this.form.markAllAsTouched();
SyncLog.err('Sync form validation failed', this.form.errors);
return;
}
// Explicitly sync form values to _tmpUpdatedCfg in case modelChange didn't fire
// This is especially important on Android WebView where change detection can be unreliable
this._tmpUpdatedCfg = {
...this._tmpUpdatedCfg,
...this.form.value,
};
// Strip _isInitialSetup before saving — it's only for form hideExpressions
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { _isInitialSetup, ...cfgWithoutFlag } = this._tmpUpdatedCfg;
const configToSave = {
...cfgWithoutFlag,
isEnabled: this._tmpUpdatedCfg.isEnabled || !this.isWasEnabled(),
};
const providerId = toSyncProviderId(this._tmpUpdatedCfg.syncProvider);
if (providerId && this._tmpUpdatedCfg.isEnabled) {
await this.syncWrapperService.configuredAuthForSyncProviderIfNecessary(providerId);
// If the provider requires auth (e.g. Dropbox) and is still not ready,
// the auth dialog was cancelled or failed. Keep the dialog open so the
// user can retry, and do not persist isEnabled:true with missing credentials
// (which would trigger the "Sync credentials are missing" snack loop — issue #7131).
const provider = await this._providerManager.getProviderById(providerId);
if (provider?.getAuthHelper && !(await provider.isReady())) {
return;
}
}
await this.syncConfigService.updateSettingsFromForm(configToSave as SyncConfig, true);
this._matDialogRef.close();
if (isOnline()) {
this.syncWrapperService.sync();
}
}
updateTmpCfg(cfg: SyncConfig): void {
// Use Object.assign to preserve the object reference for Formly
// This ensures Formly detects changes to the model
Object.assign(this._tmpUpdatedCfg, cfg);
}
}

View file

@ -3,7 +3,7 @@ import { SyncProviderManager } from '../../op-log/sync-providers/provider-manage
import { GlobalConfigService } from '../../features/config/global-config.service';
import { combineLatest, from, Observable, of } from 'rxjs';
import { SyncConfig } from '../../features/config/global-config.model';
import { switchMap, tap } from 'rxjs/operators';
import { shareReplay, switchMap, tap } from 'rxjs/operators';
import {
CurrentProviderPrivateCfg,
PrivateCfgByProviderId,
@ -234,6 +234,11 @@ export class SyncConfigService {
this._lastSettings = v;
SyncLog.log('syncSettingsForm$', redactSensitiveFields(v));
}),
// Cache the latest emission across all subscribers (refCount:false) so a
// dialog opened later from the header — when the settings page is not
// mounted — can replay without re-running combineLatest and re-fetching
// /assets/sync-config-default-override.json.
shareReplay({ bufferSize: 1, refCount: false }),
);
async updateEncryptionPassword(

View file

@ -569,14 +569,14 @@ export class SyncWrapperService {
msg: T.F.SYNC.S.AUTH_TOKEN_REJECTED,
translateParams: { reason: error.message },
type: 'ERROR',
actionFn: () => this._openSyncInitialCfgDialog(),
actionFn: () => this._openSyncCfgDialog(),
actionStr: T.F.SYNC.S.BTN_CONFIGURE,
});
} else {
this._snackService.open({
msg: T.F.SYNC.S.INCOMPLETE_CFG,
type: 'ERROR',
actionFn: () => this._openSyncInitialCfgDialog(),
actionFn: () => this._openSyncCfgDialog(),
actionStr: T.F.SYNC.S.BTN_CONFIGURE,
});
}
@ -886,10 +886,10 @@ export class SyncWrapperService {
* Handle incoherent timestamps dialog with proper async error handling.
* Uses fire-and-forget pattern but logs errors instead of swallowing them.
*/
private async _openSyncInitialCfgDialog(): Promise<void> {
const { DialogSyncInitialCfgComponent } =
await import('./dialog-sync-initial-cfg/dialog-sync-initial-cfg.component');
this._matDialog.open(DialogSyncInitialCfgComponent);
private async _openSyncCfgDialog(): Promise<void> {
const { DialogSyncCfgComponent } =
await import('./dialog-sync-cfg/dialog-sync-cfg.component');
this._matDialog.open(DialogSyncCfgComponent);
}
private _handleIncoherentTimestampsDialog(): void {

View file

@ -34,7 +34,7 @@ export class NextcloudProvider extends WebdavBaseProvider<SyncProviderId.WebDAV>
* Builds the full WebDAV base URL from serverUrl + userName.
* e.g., https://cloud.example.com -> https://cloud.example.com/remote.php/dav/files/john/
*/
private _buildNextcloudBaseUrl(cfg: NextcloudPrivateCfg): string {
static buildBaseUrl(cfg: Pick<NextcloudPrivateCfg, 'serverUrl' | 'userName'>): string {
let serverUrl = cfg.serverUrl.trim();
if (serverUrl.endsWith('/')) {
serverUrl = serverUrl.slice(0, -1);
@ -69,7 +69,7 @@ export class NextcloudProvider extends WebdavBaseProvider<SyncProviderId.WebDAV>
}
return {
...cfg,
baseUrl: this._buildNextcloudBaseUrl(cfg),
baseUrl: NextcloudProvider.buildBaseUrl(cfg),
};
}

View file

@ -7,6 +7,15 @@ export enum SyncProviderId {
'Nextcloud' = 'Nextcloud',
}
/**
* Providers that authenticate via OAuth and expose `getAuthHelper()` on the
* runtime provider. Listed here so UI gates (e.g. Re-authenticate button)
* stay in lockstep with the provider implementations without an async probe.
*/
export const OAUTH_SYNC_PROVIDERS: ReadonlySet<SyncProviderId> = new Set([
SyncProviderId.Dropbox,
]);
/**
* Type-safe conversion from string-based sync provider value to SyncProviderId.
* Validates that a persisted string value is a valid SyncProviderId at runtime.

View file

@ -186,14 +186,60 @@
<h2 class="mat-h2 section-title">
{{ 'PS.TABS.SYNC_BACKUP' | translate }}
</h2>
<section class="config-section tour-syncSection">
@let syncSettingsForm = syncSettingsService.syncSettingsForm$ | async;
@if (syncSettingsForm && globalSyncConfigFormCfg(); as syncCfg) {
<config-section
(save)="syncSettingsService.updateSettingsFromForm($event.config)"
[cfg]="syncSettingsForm"
[section]="syncCfg"
></config-section>
<section class="config-section sync-summary">
@let status = syncStatus();
@if (!status.providerId) {
<p class="sync-summary__intro">
{{ 'PS.SYNC.EMPTY_STATE_HINT' | translate }}
</p>
<div class="sync-summary__actions">
<button
(click)="openSyncCfgDialog()"
color="primary"
mat-raised-button
type="button"
>
<mat-icon>cloud_sync</mat-icon>
{{ 'PS.SYNC.SET_UP_SYNC' | translate }}
</button>
</div>
} @else {
<div class="sync-summary__status">
<span class="sync-summary__provider">
<mat-icon>cloud_sync</mat-icon>
{{ status.providerId }}
</span>
@if (status.needsAuth) {
<span class="sync-summary__pill sync-summary__pill--warn">
{{ 'PS.SYNC.NEEDS_AUTH' | translate }}
</span>
}
@if (status.isEncrypted) {
<span class="sync-summary__pill">
<mat-icon>lock</mat-icon>
{{ 'PS.SYNC.ENCRYPTED' | translate }}
</span>
}
</div>
<div class="sync-summary__actions">
<button
(click)="triggerSync()"
color="primary"
mat-raised-button
type="button"
>
<mat-icon>sync</mat-icon>
{{ 'F.SYNC.BTN_SYNC_NOW' | translate }}
</button>
<button
(click)="openSyncCfgDialog()"
mat-stroked-button
type="button"
>
<mat-icon>tune</mat-icon>
{{ 'PS.SYNC.CONFIGURE' | translate }}
</button>
</div>
}
</section>

View file

@ -106,6 +106,63 @@
}
}
.sync-summary {
padding: var(--s2);
&__intro {
margin: 0 0 var(--s2);
color: var(--text-color-muted);
}
&__status {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--s2);
margin-bottom: var(--s2);
}
&__provider {
display: inline-flex;
align-items: center;
gap: var(--s-half);
font-weight: 500;
mat-icon {
font-size: 20px;
width: 20px;
height: 20px;
}
}
&__pill {
display: inline-flex;
align-items: center;
gap: var(--s-half);
padding: var(--s-half) var(--s);
border: 1px solid var(--divider-color);
border-radius: 999px;
font-size: 12px;
mat-icon {
font-size: 14px;
width: 14px;
height: 14px;
}
&--warn {
border-color: var(--color-warning);
color: var(--color-warning);
}
}
&__actions {
display: flex;
flex-wrap: wrap;
gap: var(--s);
}
}
.version-footer {
margin-top: auto;
text-align: center;

View file

@ -6,28 +6,39 @@ import { SyncProviderManager } from '../../op-log/sync-providers/provider-manage
import { GlobalConfigService } from '../../features/config/global-config.service';
import { ActivatedRoute } from '@angular/router';
import { PluginBridgeService } from '../../plugins/plugin-bridge.service';
import { WebdavApi } from '../../op-log/sync-providers/file-based/webdav/webdav-api';
import { of } from 'rxjs';
import { signal } from '@angular/core';
import { SyncWrapperService } from '../../imex/sync/sync-wrapper.service';
import { ShareService } from '../../core/share/share.service';
import { UserProfileService } from '../../features/user-profile/user-profile.service';
import { MatDialog } from '@angular/material/dialog';
import { SyncProviderId } from '../../op-log/sync-providers/provider.const';
import { TranslateService } from '@ngx-translate/core';
describe('ConfigPageComponent', () => {
let component: ConfigPageComponent;
let mockSyncConfigService: jasmine.SpyObj<SyncConfigService>;
let mockSyncWrapperService: jasmine.SpyObj<SyncWrapperService>;
let mockMatDialog: jasmine.SpyObj<MatDialog>;
let mockProviderManager: jasmine.SpyObj<SyncProviderManager>;
beforeEach(async () => {
mockSyncConfigService = jasmine.createSpyObj(
const mockSyncConfigService = jasmine.createSpyObj(
'SyncConfigService',
['updateSettingsFromForm'],
{ syncSettingsForm$: of({}) },
);
mockSyncConfigService.updateSettingsFromForm.and.returnValue(Promise.resolve());
mockSyncWrapperService = jasmine.createSpyObj('SyncWrapperService', ['sync']);
mockMatDialog = jasmine.createSpyObj('MatDialog', ['open']);
mockProviderManager = jasmine.createSpyObj(
'SyncProviderManager',
['getProviderById'],
{
currentProviderPrivateCfg$: of(null),
},
);
mockProviderManager.getProviderById.and.returnValue(Promise.resolve(undefined));
await TestBed.configureTestingModule({
providers: [
{ provide: SyncConfigService, useValue: mockSyncConfigService },
@ -35,16 +46,7 @@ describe('ConfigPageComponent', () => {
provide: SnackService,
useValue: jasmine.createSpyObj('SnackService', ['open']),
},
{
provide: SyncProviderManager,
useValue: (() => {
const spy = jasmine.createSpyObj('SyncProviderManager', ['getProviderById'], {
currentProviderPrivateCfg$: of(null),
});
spy.getProviderById.and.returnValue(Promise.resolve(undefined));
return spy;
})(),
},
{ provide: SyncProviderManager, useValue: mockProviderManager },
{
provide: GlobalConfigService,
useValue: jasmine.createSpyObj('GlobalConfigService', ['updateSection'], {
@ -54,13 +56,10 @@ describe('ConfigPageComponent', () => {
},
{ provide: ActivatedRoute, useValue: { queryParams: of({}) } },
{ provide: PluginBridgeService, useValue: { shortcuts: signal([]) } },
{ provide: SyncWrapperService, useValue: {} },
{ provide: SyncWrapperService, useValue: mockSyncWrapperService },
{ provide: ShareService, useValue: {} },
{ provide: UserProfileService, useValue: {} },
{
provide: MatDialog,
useValue: jasmine.createSpyObj('MatDialog', ['open']),
},
{ provide: MatDialog, useValue: mockMatDialog },
{
provide: TranslateService,
useValue: jasmine.createSpyObj('TranslateService', ['instant']),
@ -75,54 +74,18 @@ describe('ConfigPageComponent', () => {
component = TestBed.createComponent(ConfigPageComponent).componentInstance;
});
describe('WebDAV Test Connection button', () => {
it('should save settings after successful connection test', async () => {
// Arrange
spyOn(WebdavApi.prototype, 'testConnection').and.returnValue(
Promise.resolve({
success: true,
fullUrl: 'https://webdav.example.com/sp-test',
}),
);
it('should expose an empty syncStatus by default', () => {
expect(component.syncStatus().providerId).toBeNull();
expect(component.syncStatus().needsAuth).toBe(false);
});
const webDavCfg = {
baseUrl: 'https://webdav.example.com',
userName: 'testuser',
password: 'testpass',
syncFolderPath: '/sp-test',
};
it('triggerSync() should call SyncWrapperService.sync()', () => {
component.triggerSync();
expect(mockSyncWrapperService.sync).toHaveBeenCalled();
});
const fullSyncModel = {
isEnabled: true,
syncProvider: SyncProviderId.WebDAV,
syncInterval: 600000,
webDav: webDavCfg,
};
const mockField = {
parent: { parent: { model: fullSyncModel } },
};
// Wait for async sync form config to be built
await new Promise((resolve) => setTimeout(resolve, 0));
// Find the WebDAV Test Connection button onClick handler
const webDavItem = component
.globalSyncConfigFormCfg()!
.items!.find((item: any) => item.key === 'webDav');
const testConnectionBtn = webDavItem!.fieldGroup!.find(
(item: any) => item.type === 'btn',
);
const onClick = testConnectionBtn!.templateOptions!.onClick;
// Act
await onClick(mockField, {}, webDavCfg);
// Assert
expect(mockSyncConfigService.updateSettingsFromForm).toHaveBeenCalledWith(
fullSyncModel,
true,
);
});
it('openSyncCfgDialog() should open DialogSyncCfgComponent', async () => {
await component.openSyncCfgDialog();
expect(mockMatDialog.open).toHaveBeenCalled();
});
});

View file

@ -2,11 +2,10 @@ import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
DestroyRef,
effect,
inject,
OnDestroy,
OnInit,
signal,
} from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { GlobalConfigService } from '../../features/config/global-config.service';
@ -20,13 +19,13 @@ import {
} from '../../features/config/global-config-form-config.const';
import {
ConfigFormConfig,
ConfigFormSection,
GlobalConfigSectionKey,
GlobalConfigState,
GlobalSectionConfig,
SyncConfig,
} from '../../features/config/global-config.model';
import { combineLatest, firstValueFrom, Observable, Subscription } from 'rxjs';
import { firstValueFrom, from, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
import { ProjectCfgFormKey } from '../../features/project/project.model';
import { T } from '../../t.const';
import { versions } from '../../../environments/versions';
@ -36,15 +35,10 @@ import { getAutomaticBackUpFormCfg } from '../../features/config/form-cfgs/autom
import { getAppVersionStr } from '../../util/get-app-version-str';
import { ConfigSectionComponent } from '../../features/config/config-section/config-section.component';
import { ConfigSoundFormComponent } from '../../features/config/config-sound-form/config-sound-form.component';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { SYNC_FORM } from '../../features/config/form-cfgs/sync-form.const';
import { TranslatePipe } from '@ngx-translate/core';
import { EXPERIMENTAL_APP_FEATURE_KEYS } from '../../features/config/form-cfgs/app-features-form.const';
import { SyncProviderManager } from '../../op-log/sync-providers/provider-manager.service';
import { map } from 'rxjs/operators';
import { SyncConfigService } from '../../imex/sync/sync-config.service';
import { WebdavApi } from '../../op-log/sync-providers/file-based/webdav/webdav-api';
import { WebdavPrivateCfg } from '../../op-log/sync-providers/file-based/webdav/webdav.model';
import { AsyncPipe } from '@angular/common';
import { PluginManagementComponent } from '../../plugins/ui/plugin-management/plugin-management.component';
import { PluginBridgeService } from '../../plugins/plugin-bridge.service';
import { createPluginShortcutFormItems } from '../../features/config/form-cfgs/plugin-keyboard-shortcuts';
@ -58,12 +52,12 @@ import { SyncWrapperService } from '../../imex/sync/sync-wrapper.service';
import { UserProfileService } from '../../features/user-profile/user-profile.service';
import { MatDialog } from '@angular/material/dialog';
import { DialogDisableProfilesConfirmationComponent } from '../../features/user-profile/dialog-disable-profiles-confirmation/dialog-disable-profiles-confirmation.component';
import { DialogRestorePointComponent } from '../../imex/sync/dialog-restore-point/dialog-restore-point.component';
import { SyncProviderId } from '../../op-log/sync-providers/provider.const';
import { DialogConfirmComponent } from '../../ui/dialog-confirm/dialog-confirm.component';
import { MatTab, MatTabGroup, MatTabLabel } from '@angular/material/tabs';
import { MatIcon } from '@angular/material/icon';
import { MatTooltip } from '@angular/material/tooltip';
import { MatButton } from '@angular/material/button';
@Component({
selector: 'config-page',
@ -75,16 +69,16 @@ import { MatTooltip } from '@angular/material/tooltip';
ConfigSectionComponent,
ConfigSoundFormComponent,
TranslatePipe,
AsyncPipe,
PluginManagementComponent,
MatTabGroup,
MatTab,
MatTabLabel,
MatIcon,
MatTooltip,
MatButton,
],
})
export class ConfigPageComponent implements OnInit, OnDestroy {
export class ConfigPageComponent implements OnInit {
private readonly _cd = inject(ChangeDetectorRef);
private readonly _route = inject(ActivatedRoute);
private readonly _providerManager = inject(SyncProviderManager);
@ -94,7 +88,6 @@ export class ConfigPageComponent implements OnInit, OnDestroy {
private readonly _shareService = inject(ShareService);
private readonly _userProfileService = inject(UserProfileService);
private readonly _matDialog = inject(MatDialog);
private readonly _translateService = inject(TranslateService);
readonly configService = inject(GlobalConfigService);
readonly syncSettingsService = inject(SyncConfigService);
@ -112,31 +105,47 @@ export class ConfigPageComponent implements OnInit, OnDestroy {
pluginsShortcutsFormCfg: ConfigFormConfig;
globalImexFormCfg: ConfigFormConfig;
globalProductivityConfigFormCfg: ConfigFormConfig;
globalSyncConfigFormCfg = signal<ConfigFormSection<SyncConfig> | undefined>(undefined);
globalCfg?: GlobalConfigState;
// `providerId === null` ⇒ empty state (sync disabled or no provider chosen).
// switchMap drops stale signal writes if a new sync-config emission arrives
// before the previous provider probe resolves — the underlying probe promise
// still runs to completion in the background; only the result is ignored.
// try/catch keeps the stream alive when isReady() rejects (otherwise the
// observable error would kill the subscription and freeze the status).
syncStatus = toSignal(
this.syncSettingsService.syncSettingsForm$.pipe(
switchMap((sync) => {
const providerId = sync.isEnabled
? (sync.syncProvider as SyncProviderId | null)
: null;
const isEncrypted = !!sync.isEncryptionEnabled;
if (!providerId) {
return of({ providerId: null, needsAuth: false, isEncrypted });
}
return from(
(async () => {
const provider = await this._providerManager.getProviderById(providerId);
const requiresAuth = !!provider?.getAuthHelper;
try {
const isAuthed = !!(await provider?.isReady());
return { providerId, needsAuth: requiresAuth && !isAuthed, isEncrypted };
} catch {
// Don't claim a non-OAuth provider needs auth — only surface
// the auth pill if the provider could plausibly require it.
return { providerId, needsAuth: requiresAuth, isEncrypted };
}
})(),
);
}),
),
{ initialValue: { providerId: null, needsAuth: false, isEncrypted: false } },
);
appVersion: string = getAppVersionStr();
versions?: typeof versions = versions;
// TODO needs to contain all sync providers....
// TODO maybe handling this in an effect would be better????
syncFormCfg$: Observable<Record<string, unknown>> = combineLatest([
this._providerManager.currentProviderPrivateCfg$,
this.configService.sync$,
]).pipe(
map(([currentProviderCfg, syncCfg]) => {
if (!currentProviderCfg) {
return syncCfg as unknown as Record<string, unknown>;
}
return {
...(syncCfg as unknown as Record<string, unknown>),
[currentProviderCfg.providerId]: currentProviderCfg.privateCfg,
};
}),
);
private _subs: Subscription = new Subscription();
private readonly _destroyRef = inject(DestroyRef);
constructor() {
// Initialize tab-specific form configurations
@ -147,17 +156,6 @@ export class ConfigPageComponent implements OnInit, OnDestroy {
this.globalProductivityConfigFormCfg = GLOBAL_PRODUCTIVITY_FORM_CONFIG.slice();
this.globalTasksFormCfg = GLOBAL_TASKS_FORM_CONFIG.slice();
// Build sync form config asynchronously (providers are lazy-loaded)
this._buildSyncFormConfig()
.then((cfg) => this.globalSyncConfigFormCfg.set(cfg))
.catch((err) => {
Log.err('Failed to build sync form config:', err);
this._snackService.open({
type: 'ERROR',
msg: T.GLOBAL_SNACK.OPEN_SETTINGS_ERROR,
});
});
// NOTE: needs special handling cause of the async stuff
if (IS_ANDROID_WEB_VIEW) {
this.globalImexFormCfg = [...this.globalImexFormCfg, getAutomaticBackUpFormCfg()];
@ -180,16 +178,16 @@ export class ConfigPageComponent implements OnInit, OnDestroy {
}
ngOnInit(): void {
this._subs.add(
this.configService.cfg$.subscribe((cfg) => {
this.configService.cfg$
.pipe(takeUntilDestroyed(this._destroyRef))
.subscribe((cfg) => {
this.globalCfg = cfg;
// this._cd.detectChanges();
}),
);
});
// Check for tab query parameter and set selected tab
this._subs.add(
this._route.queryParams.subscribe((params) => {
this._route.queryParams
.pipe(takeUntilDestroyed(this._destroyRef))
.subscribe((params) => {
if (params['tab'] !== undefined) {
const tabIndex = parseInt(params['tab'], 10);
if (!isNaN(tabIndex) && tabIndex >= 0 && tabIndex < 5) {
@ -201,8 +199,7 @@ export class ConfigPageComponent implements OnInit, OnDestroy {
this.expandedSection = params['section'];
this._cd.detectChanges();
}
}),
);
});
}
private _updateKeyboardFormWithPluginShortcuts(shortcuts: PluginShortcutCfg[]): void {
@ -263,264 +260,14 @@ export class ConfigPageComponent implements OnInit, OnDestroy {
this._cd.detectChanges();
}
ngOnDestroy(): void {
this._subs.unsubscribe();
async openSyncCfgDialog(): Promise<void> {
const { DialogSyncCfgComponent } =
await import('../../imex/sync/dialog-sync-cfg/dialog-sync-cfg.component');
this._matDialog.open(DialogSyncCfgComponent);
}
private async _buildSyncFormConfig(): Promise<typeof SYNC_FORM> {
// Pre-load dropbox provider for use in the form config
await this._providerManager.getProviderById(SyncProviderId.Dropbox);
// Deep clone the SYNC_FORM items to avoid mutating the original
const items = SYNC_FORM.items!.map((item) => {
// Find the WebDAV fieldGroup and add the Test Connection button
if (item.key === 'webDav' && item.fieldGroup) {
return {
...item,
fieldGroup: [
...item.fieldGroup,
{
type: 'btn',
className: 'mt3 block',
templateOptions: {
text: T.F.SYNC.FORM.WEB_DAV.L_TEST_CONNECTION,
required: false,
onClick: async (_field: unknown, _form: unknown, model: unknown) => {
const webDavCfg = model as WebdavPrivateCfg;
if (
!webDavCfg?.baseUrl ||
!webDavCfg?.userName ||
!webDavCfg?.password ||
!webDavCfg?.syncFolderPath
) {
this._snackService.open({
type: 'ERROR',
msg: T.F.SYNC.FORM.WEB_DAV.S_FILL_ALL_FIELDS,
});
return;
}
try {
// Create a temporary WebdavApi instance for testing
const api = new WebdavApi(async () => webDavCfg);
const result = await api.testConnection(webDavCfg);
if (result.success) {
this._snackService.open({
type: 'SUCCESS',
msg: T.F.SYNC.FORM.WEB_DAV.S_TEST_SUCCESS,
translateParams: { url: result.fullUrl },
});
// Save settings after successful connection test.
// Formly hierarchy: _field (button) -> parent (group wrapper) -> parent (root form) -> model
const fullSyncModel = (
_field as { parent?: { parent?: { model?: SyncConfig } } }
)?.parent?.parent?.model;
if (fullSyncModel) {
await this.syncSettingsService.updateSettingsFromForm(
fullSyncModel,
true,
);
}
} else {
this._snackService.open({
type: 'ERROR',
msg: T.F.SYNC.FORM.WEB_DAV.S_TEST_FAIL,
translateParams: {
error: result.error || 'Unknown error',
url: result.fullUrl,
},
});
}
} catch (e) {
this._snackService.open({
type: 'ERROR',
msg: T.F.SYNC.FORM.WEB_DAV.S_TEST_FAIL,
translateParams: {
error: e instanceof Error ? e.message : 'Unexpected error',
url: (webDavCfg.baseUrl as string) || 'N/A',
},
});
}
},
},
},
],
};
}
// Find the Dropbox fieldGroup and add the authentication button
if ((item as any).props?.dropboxAuth && item.fieldGroup) {
// Check if Dropbox is already authenticated
// We need to check auth status asynchronously, so we'll set initial state
// and update it when the form is rendered
let isAuthenticated = false;
this._providerManager
.getProviderById(SyncProviderId.Dropbox)
.then(async (dropboxProvider) => {
const ready = await dropboxProvider?.isReady();
isAuthenticated = !!ready;
// Update the status field text after checking
const statusField = item.fieldGroup?.find(
(f: any) => f.key === 'authStatus',
) as any;
if (statusField?.templateOptions) {
statusField.templateOptions.text = isAuthenticated
? '✓ ' +
this._translateService.instant(T.F.SYNC.FORM.DROPBOX.STATUS_CONFIGURED)
: '⚠ ' +
this._translateService.instant(
T.F.SYNC.FORM.DROPBOX.STATUS_NOT_CONFIGURED,
);
}
})
.catch((e) => console.error('Failed to check Dropbox auth status:', e));
return {
...item,
fieldGroup: [
...item.fieldGroup,
{
type: 'btn',
className: 'mt3 block e2e-dropbox-auth-btn',
templateOptions: {
// Button text will be determined by checking if already authenticated
text: T.F.SYNC.FORM.DROPBOX.BTN_AUTHENTICATE,
btnType: 'primary',
onClick: async (_field: unknown, _form: unknown, model: unknown) => {
try {
// Check current auth status before opening dialog
const dropboxProvider = await this._providerManager.getProviderById(
SyncProviderId.Dropbox,
);
const isCurrentlyAuth = await dropboxProvider?.isReady();
const result =
await this._syncWrapperService.configuredAuthForSyncProviderIfNecessary(
SyncProviderId.Dropbox,
true, // force re-authentication even if already configured
);
if (result.wasConfigured) {
this._snackService.open({
type: 'SUCCESS',
msg: isCurrentlyAuth
? T.F.SYNC.FORM.DROPBOX.REAUTH_SUCCESS
: T.F.SYNC.FORM.DROPBOX.AUTH_SUCCESS,
});
// Update the status field to show configured
const statusField = item.fieldGroup?.find(
(f: any) => f.key === 'authStatus',
) as any;
if (statusField?.templateOptions) {
statusField.templateOptions.text =
'✓ ' +
this._translateService.instant(
T.F.SYNC.FORM.DROPBOX.STATUS_CONFIGURED,
);
}
// Update button text to "Re-authenticate"
const btnField = _field as any;
if (btnField?.templateOptions) {
btnField.templateOptions.text =
T.F.SYNC.FORM.DROPBOX.BTN_REAUTHENTICATE;
}
// Save the updated credentials to persist them
const fullSyncModel = (
_field as { parent?: { parent?: { model?: SyncConfig } } }
)?.parent?.parent?.model;
if (fullSyncModel) {
await this.syncSettingsService.updateSettingsFromForm(
fullSyncModel!,
true,
);
}
}
} catch (e) {
// Log error for debugging (storage failures, auth errors, etc.)
Log.err('Dropbox authentication failed:', e);
// Show user-friendly error with actual error message for context
this._snackService.open({
type: 'ERROR',
msg: T.F.SYNC.S.INCOMPLETE_CFG,
translateParams: {
error: e instanceof Error ? e.message : String(e),
},
});
}
},
},
hooks: {
// Update button text based on auth status when form initializes
onInit: async (field: any) => {
const dropboxProv = await this._providerManager.getProviderById(
SyncProviderId.Dropbox,
);
const isAuth = await dropboxProv?.isReady();
if (field?.templateOptions && isAuth) {
field.templateOptions.text = T.F.SYNC.FORM.DROPBOX.BTN_REAUTHENTICATE;
}
},
},
},
],
};
}
return item;
});
return {
...SYNC_FORM,
items: [
...items,
{
hideExpression: (m: Record<string, unknown>, _v: unknown, field: unknown) =>
!m.isEnabled || !(field as { form?: { valid?: boolean } })?.form?.valid,
type: 'btn',
className: 'mt3 block',
templateOptions: {
text: T.F.SYNC.BTN_SYNC_NOW,
required: false,
onClick: () => {
this._syncWrapperService.sync();
},
},
},
{
hideExpression: (m: Record<string, unknown>, _v: unknown, field: unknown) =>
!m.isEnabled || !(field as { form?: { valid?: boolean } })?.form?.valid,
type: 'btn',
className: 'mt2 block',
templateOptions: {
text: T.F.SYNC.S.BTN_FORCE_OVERWRITE,
btnType: 'warn',
required: false,
onClick: () => {
this._syncWrapperService.forceUpload();
},
},
},
{
hideExpression: (m: Record<string, unknown>) =>
!m.isEnabled || m.syncProvider !== SyncProviderId.SuperSync,
type: 'btn',
className: 'mt2 block',
templateOptions: {
text: T.F.SYNC.BTN_RESTORE_FROM_HISTORY,
btnType: 'stroked',
required: false,
onClick: () => {
this._openRestoreDialog();
},
},
},
],
} as typeof SYNC_FORM;
triggerSync(): void {
this._syncWrapperService.sync();
}
async saveGlobalCfg($event: {
@ -633,11 +380,4 @@ export class ConfigPageComponent implements OnInit, OnDestroy {
});
}
}
private _openRestoreDialog(): void {
this._matDialog.open(DialogRestorePointComponent, {
width: '500px',
maxWidth: '90vw',
});
}
}

View file

@ -1281,7 +1281,6 @@ const T = {
BTN_CHANGE_PASSWORD: 'F.SYNC.FORM.SUPER_SYNC.BTN_CHANGE_PASSWORD',
BTN_DISABLE_ENCRYPTION: 'F.SYNC.FORM.SUPER_SYNC.BTN_DISABLE_ENCRYPTION',
BTN_ENABLE_ENCRYPTION: 'F.SYNC.FORM.SUPER_SYNC.BTN_ENABLE_ENCRYPTION',
BTN_FORCE_OVERWRITE: 'F.SYNC.FORM.SUPER_SYNC.BTN_FORCE_OVERWRITE',
BTN_GET_TOKEN: 'F.SYNC.FORM.SUPER_SYNC.BTN_GET_TOKEN',
CHANGE_PASSWORD_SUCCESS: 'F.SYNC.FORM.SUPER_SYNC.CHANGE_PASSWORD_SUCCESS',
CHANGE_PASSWORD_WARNING: 'F.SYNC.FORM.SUPER_SYNC.CHANGE_PASSWORD_WARNING',
@ -2698,6 +2697,13 @@ const T = {
PROJECT_SETTINGS: 'PS.PROJECT_SETTINGS',
PROVIDE_FEEDBACK: 'PS.PROVIDE_FEEDBACK',
RELOAD: 'PS.RELOAD',
SYNC: {
CONFIGURE: 'PS.SYNC.CONFIGURE',
EMPTY_STATE_HINT: 'PS.SYNC.EMPTY_STATE_HINT',
ENCRYPTED: 'PS.SYNC.ENCRYPTED',
NEEDS_AUTH: 'PS.SYNC.NEEDS_AUTH',
SET_UP_SYNC: 'PS.SYNC.SET_UP_SYNC',
},
SYNC_EXPORT: 'PS.SYNC_EXPORT',
TABS: {
GENERAL: 'PS.TABS.GENERAL',

View file

@ -1177,7 +1177,7 @@
"AUTH_SUCCESS": "Dropbox authentication successful! Credentials saved.",
"BTN_AUTHENTICATE": "Authenticate with Dropbox",
"BTN_REAUTHENTICATE": "Re-authenticate with Dropbox",
"INFO_TEXT": "Dropbox authentication uses OAuth. Click the button below to authenticate with your Dropbox account.",
"INFO_TEXT": "Dropbox uses OAuth. Saving your settings will open Dropbox in your browser to authorize access.",
"L_ACCESS_TOKEN": "Access Token (generated from Auth Code)",
"REAUTH_SUCCESS": "Dropbox re-authentication successful! Credentials updated.",
"STATUS_CONFIGURED": "Dropbox is configured and ready to sync",
@ -1255,7 +1255,6 @@
"BTN_CHANGE_PASSWORD": "Change Password",
"BTN_DISABLE_ENCRYPTION": "Disable Encryption",
"BTN_ENABLE_ENCRYPTION": "Enable Encryption",
"BTN_FORCE_OVERWRITE": "Force Overwrite Server",
"BTN_GET_TOKEN": "Open Server & Get Token",
"CHANGE_PASSWORD_SUCCESS": "Encryption password changed successfully",
"CHANGE_PASSWORD_WARNING": "WARNING: This will permanently delete ALL sync history and backups on the server! Previous versions cannot be recovered. Your current data will be re-uploaded with the new password. All other devices will need the new password.",
@ -2645,6 +2644,13 @@
"PROJECT_SETTINGS": "Project Specific Settings",
"PROVIDE_FEEDBACK": "Provide Feedback",
"RELOAD": "Reload",
"SYNC": {
"CONFIGURE": "Configure",
"EMPTY_STATE_HINT": "Sync your data with Dropbox, WebDAV, Nextcloud, or a local file.",
"ENCRYPTED": "Encrypted",
"NEEDS_AUTH": "Authentication required",
"SET_UP_SYNC": "Set up sync"
},
"SYNC_EXPORT": "Sync & Export",
"TABS": {
"GENERAL": "General",