Skip to content

Add a per-repository "Notifications" setting that filters notification generation (Repositories → Settings) #2457

Closed

Description

@propr-dev

Context

ProPR currently generates Inbox notifications and Web Push deliveries for every monitored repository. The single producer of repository-scoped lifecycle notifications is NotificationProjectionService (packages/api/services/notificationProjectionService.ts), which turns draft, task, and indexing lifecycle events into durable notification events.

Teams that monitor many repositories want to keep automation running for a repository (issues processed, PRs reviewed, indexing kept fresh) while silencing its notification noise. Today the only way to do that is to turn off the entire notification category in personal Settings, which is global and affects every repository.

This issue adds a per-repository Notifications toggle to the Repositories → Settings tab. It behaves exactly like the existing repository-level automation toggles (Auto CI follow-up, Visual previews): it is stored in the monitored-repository configuration, shared across all branch entries of the same repository, and written through POST /api/config/repos.

Key behaviours requested:

  1. The option lives in the Repositories → Settings tab for the selected repository.
  2. It is enabled by default. Existing repositories, and repositories created before this change, must behave exactly as they do today.
  3. Because it is on by default, it is not shown in the Add Repository modal.
  4. When disabled it acts as a pure filter: no notification is generated (and therefore none is pushed) for that repository.

Requirements

Functional

  • A new boolean notificationsEnabled field on monitored repository configuration, defaulting to true.
  • A toggle in RepositorySettingsBar labelled Notifications, with helper text explaining that it controls Inbox and push notifications for this repository.
  • The toggle is shared across all configured branch entries of the same repository (identical to autoFollowupOnFailedCi and visualPreview). Toggling it writes the same value to every entry whose repository name matches (case-insensitively).
  • When notificationsEnabled is false, NotificationProjectionService must not create:
    • plan-ready notifications for drafts in that repository,
    • task failure / implementation-completed / review-completed / PR-attention notifications for that repository,
    • indexing-failure notifications for that repository,
    • stalled task or stalled indexing notifications for that repository.
  • System-health notifications (system_failure, including the ProPR Connect seat-limit card) are not repository-scoped and must continue to be produced regardless of this setting.
  • The value round-trips through GET /api/config/repos, POST /api/config/repos, the instance catalog (member view), the CLI, and the MCP update_repository_configuration tool.
  • Read-only users (demo mode, or users without instance.manage_settings) see the toggle but cannot change it.

Non-functional / constraints

  • No database migration. Monitored repositories are stored as JSON in the system_configs table, so the new field is additive and requires no schema change.
  • The filter lookup runs inside the notification background worker. It must not block the API event loop, must use the injected Knex connection (not the @propr/core module singleton), must be cached with a short TTL, and must fail open (generate the notification) if the configuration cannot be read — silently swallowing notifications on a transient read error would be worse than a small amount of extra noise.
  • Backwards compatibility: a stored repository entry that omits notificationsEnabled, or a legacy string entry ("owner/repo"), is treated as enabled.

Implementation Specification

Files to touch, in dependency order:

Layer File Change
Core types packages/core/src/config/configManager.ts (RepoToMonitor) Add optional notificationsEnabled?: boolean
API validation packages/api/routes/configRepoValidation.ts Normalize + validate the field; add preserveRepoNotifications
API persistence packages/api/routes/configRoutes.ts Apply the new preserve helper alongside the existing ones
Notification filter packages/api/services/notificationProjectionService.ts Cached repository lookup + guards in every repository-scoped projection
UI types propr-ui/src/api/proprTypes.ts (MonitoredRepo) Add notificationsEnabled?: boolean
UI merge rules propr-ui/src/hooks/repositoryVisualPreview.ts Resolve + unify the value across branch entries
UI state propr-ui/src/hooks/useRepositoryManagement.ts Parse, expose, and toggle the value
UI control propr-ui/src/components/RepositorySettingsBar.tsx Render the toggle
UI page wiring propr-ui/src/pages/RepositoriesPage.tsx Pass the handler through
CLI packages/cli/src/api/repos.ts, packages/cli/src/commands/repoCommands.ts Type, defaults, --no-notifications, list column

The exact code, with reasoning, is in the Implementation section below.

Resolution rule (must be identical on both sides)

A repository may have several configuration entries (one per monitored branch). Define:

Notifications are disabled for a repository only when every configured entry for that repository name has notificationsEnabled === false. Otherwise they are enabled.

This rule is deliberately fail-open: any entry that is missing the field, or explicitly true, keeps notifications on. The UI writes the same value to every entry, so the two sides can never diverge in practice; the rule only matters for hand-edited or legacy configuration.

Acceptance Criteria

  1. Selecting a repository in Repositories → Settings shows a Notifications toggle, checked by default for every existing repository.
  2. Turning the toggle off persists notificationsEnabled: false to all configuration entries of that repository (verified by the POST /api/config/repos body), and the save-status footer reports Saved.
  3. Reloading the page keeps the toggle off.
  4. With the toggle off, none of the following create a row in notification_events for that repository: a completed/failed task, a completed review, a PR ready for review, a plan reaching review, a failed indexing run, or a stalled task/indexing sweep.
  5. With the toggle off, an unhealthy system-health snapshot still creates a system_failure notification.
  6. With the toggle on (default), notification behaviour is byte-for-byte unchanged from before this issue.
  7. The Add Repository modal is unchanged — no Notifications control is added there — and newly added repositories are persisted with notificationsEnabled: true.
  8. Read-only users see the toggle rendered and disabled; no POST /api/config/repos request is issued when they click it.
  9. GET /api/config/repos returns notificationsEnabled for every repository, defaulting to true for entries stored without the field.
  10. propr repo list shows the notification state, and propr repo add owner/name --no-notifications persists false.
  11. All new and existing tests pass: npm run test:server, npm run test:notifications, npm --workspace propr-ui test, and the repositories-settings.pw.ts Playwright suite.

Out of scope (do not implement here)

  • Retroactive cleanup. Notifications created before the toggle was turned off remain in the Inbox. They can be dismissed normally. Add a follow-up issue if bulk dismissal on disable is wanted.
  • Desktop native task alerts. DesktopTaskNotificationAdapter renders OS-level alerts from the live task socket stream, not from NotificationProjectionService. That path is not filtered by this setting. Keep the UI helper text accurate ("Inbox and push notifications") so the scope is not overstated. A follow-up can plumb the repository filter into the desktop adapter.
  • No new database migration.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Sep 22, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    Why this shape. The setting is stored as one more optional boolean on the existing monitored-repository configuration object rather than in a new table. That configuration is already a JSON document in system_configs, already has two precedents for the exact same pattern (autoFollowupOnFailedCi, visualPreview), and already flows through the API, the instance catalog, the CLI and the MCP management tools. Reusing it means zero migrations, automatic propagation to every client, and a UI change that is a copy of code the team already reviews.

    Why filter in NotificationProjectionService and nowhere else. That service is the single producer of repository-scoped lifecycle notifications (plan/task/review/pull_request/indexing). Filtering at that one choke point guarantees the promise in the issue — no notification is generated — without having to audit every call site that publishes a lifecycle event. It also automatically suppresses Web Push, because push delivery jobs are only fanned out when a notification event is created.

    Alternatives considered and rejected:

    • Filtering at the Inbox read/API layer. Rejected: the issue explicitly says notifications must not be generated. Read-time filtering would still write rows, still fan out push jobs, and would silently resurface everything if the setting were re-enabled.
    • Filtering at each producer (worker jobs, webhook handlers). Rejected: many call sites, easy to miss one, and duplicated config reads.
    • A new repository_notification_settings table. Rejected: a migration, a second source of truth for repository settings, and a second write path to keep in sync with POST /api/config/repos.

    Why a locally cached, injected-connection lookup. The projection service runs in a dedicated worker thread against a createBackgroundDatabase connection whose busy_timeout is 0 specifically so SQLite contention fails fast instead of blocking. Calling @propr/core's config manager from there would open the module-singleton connection with default blocking semantics and reintroduce the stalls that notificationBackgroundService was built to avoid. So the service reads system_configs through its own injected Knex, caches the result for a few seconds, and fails open on error.

    Why the value is shared across branch entries. autoFollowupOnFailedCi and visualPreview are already unified across branch entries by buildRepositoriesForDisplay, and users think in terms of repositories, not repo@branch rows. Making notifications per-branch would be a surprising, unrequested distinction.


    1. Core type

    File: packages/core/src/config/configManager.ts

    Why this file: RepoToMonitor is the shared shape used by the API validator, the daemon config loader, the CLI and the MCP tools. Adding the field here is what makes every downstream consumer type-check.

    Find the RepoToMonitor interface (search for autoFollowupOnFailedCi to locate it) and add the new optional field.

     export interface RepoToMonitor {
       id?: string;
       name: string;
       enabled: boolean;
       alias?: string;
       baseBranch?: string;
       autoFollowupOnFailedCi?: boolean;
    +  // Optional so every configuration written before this feature keeps working:
    +  // `undefined` must be read as "enabled", which is also the product default.
    +  // A non-optional field would force a data backfill we deliberately avoid.
    +  notificationsEnabled?: boolean;
       visualPreview?: RepoVisualPreviewSettings;
     }

    2. API validation and persistence

    File: packages/api/routes/configRepoValidation.ts

    Why this file: normalizeRepoConfig is the trust boundary for everything written to repos_to_monitor. Validating here means the CLI, the Web UI and the MCP update_repository_configuration tool all get the same guarantees, and the stored document can never contain a non-boolean in this field.

    Add the normalization inside normalizeRepoConfig, right next to where autoFollowupOnFailedCi is handled, and add a preserveRepoNotifications helper next to preserveRepoAutoFollowup. Match the exact signature of the existing preserveRepoAutoFollowup helper — the snippet below shows the intent, not necessarily the literal parameter list in your working copy.

    // --- inside normalizeRepoConfig, alongside the autoFollowupOnFailedCi check ---
    
    // Reject non-booleans loudly instead of coercing. A coerced value here would be
    // persisted forever and could silently disable a repository's notifications,
    // which is exactly the class of bug this validator exists to prevent.
    if (raw.notificationsEnabled !== undefined && typeof raw.notificationsEnabled !== 'boolean') {
      throw new ConfigRouteError(400, 'notificationsEnabled must be a boolean');
    }
    
    // Default to `true` rather than leaving it undefined so that responses from
    // GET /api/config/repos are explicit. The UI then never has to guess, and the
    // "enabled by default" product rule is expressed in exactly one place.
    const notificationsEnabled = raw.notificationsEnabled !== false;
    
    // ...and include it in the returned RepoToMonitor object:
    //   return { id, name, enabled, alias, baseBranch, autoFollowupOnFailedCi,
    //            notificationsEnabled, visualPreview };
    /**
     * Repository-wide notification policy. A client may submit a partial entry
     * (for example the CLI updating only `enabled`, or a legacy client that knows
     * nothing about this field). Without this helper, normalizeRepoConfig's
     * `true` default would silently re-enable notifications the user turned off.
     *
     * The rule mirrors `preserveRepoAutoFollowup`: when the incoming payload did
     * not express an opinion, keep whatever is already stored for the same
     * repository name.
     */
    export function preserveRepoNotifications(
      incoming: RepoToMonitor,
      submitted: Record<string, unknown>,
      storedByRepository: Map<string, boolean>,
    ): RepoToMonitor {
      if (typeof submitted.notificationsEnabled === 'boolean') return incoming;
      const stored = storedByRepository.get(incoming.name.toLowerCase());
      return stored === undefined ? incoming : { ...incoming, notificationsEnabled: stored };
    }

    File: packages/api/routes/configRoutes.ts

    Why this file: this is where the preserve helpers are actually applied before persistence. Skipping it would make the validator's preservation logic dead code.

    Locate the block that calls preserveRepoAutoFollowup / preserveRepoVisualPreview while building the list to persist, and add the new helper to the same pipeline.

       const normalized = submittedRepos.map((submitted, index) => {
         const repo = normalizeRepoConfig(submitted, index);
         const withFollowup = preserveRepoAutoFollowup(repo, submitted, storedFollowupByRepository);
    -    return preserveRepoVisualPreview(withFollowup, submitted, storedPreviewByRepository);
    +    const withNotifications = preserveRepoNotifications(
    +      withFollowup,
    +      submitted as Record<string, unknown>,
    +      storedNotificationsByRepository,
    +    );
    +    return preserveRepoVisualPreview(withNotifications, submitted, storedPreviewByRepository);
       });

    Build storedNotificationsByRepository the same way the existing stored-value maps are built from the currently persisted configuration (lower-cased repository name → boolean, using the resolution rule: false only when every stored entry for that name is explicitly false).

    Note: packages/api/routes/configRoutesRepos.ts (loadReposWithAttachmentCapacity) already returns normalized repositories, so GET /api/config/repos picks up the new field automatically once normalizeRepoConfig emits it. No change is needed there.


    3. The notification filter

    File: packages/api/services/notificationProjectionService.ts

    Why this file: this is the single producer of repository-scoped notification events. Every guard added here is one the rest of the system inherits for free, including Web Push, because push delivery jobs are only created as a side effect of createNotificationEvent.

    3a. Constants and options

     const DEFAULT_STALLED_AFTER_MS = 30 * 60 * 1000;
     const MIN_STALLED_CHECK_INTERVAL_MS = 5_000;
     const MAX_STALLED_CHECK_INTERVAL_MS = 60_000;
    +// Repository configuration changes are rare and the projection runs on a hot
    +// lifecycle path, so a short TTL removes almost all reads while still applying
    +// an operator's change within a few seconds of them saving it.
    +const REPOSITORY_NOTIFICATION_CACHE_TTL_MS = 5_000;
    +// Monitored repositories live in the same system_configs document the config
    +// routes write. Reading it directly keeps this worker off the @propr/core
    +// singleton connection, whose blocking busy_timeout is what the background
    +// worker was introduced to avoid in the first place.
    +const MONITORED_REPOS_CONFIG_KEY = 'repos_to_monitor';
     const TERMINAL_ACTIVITY_STATUSES = new Set([ 'completed', 'failed', 'cancelled' ]);
     export interface NotificationProjectionOptions {
       database: Knex;
       notificationService?: NotificationEventWriter;
       now?: () => Date;
       stalledAfterMs?: number;
       stalledCheckIntervalMs?: number;
       logger?: ProjectionLogger;
       contentionRetryDelaysMs?: readonly number[];
    +  /**
    +   * Test seam. Production leaves this undefined and uses the cached
    +   * system_configs reader below, so the real read path is exercised by the
    +   * integration tests that seed the configuration row directly.
    +   */
    +  repositoryNotificationsEnabled?: (repository: string) => Promise<boolean>;
     }

    3b. The cached, fail-open lookup

    Add these fields and methods to the NotificationProjectionService class (private members go next to the existing stalledTimer field; the methods next to the other private helpers).

      private readonly repositoryNotificationsEnabled?: (repository: string) => Promise<boolean>;
      private disabledRepositories: ReadonlySet<string> | null = null;
      private disabledRepositoriesLoadedAt = 0;
      private disabledRepositoriesLoad: Promise<ReadonlySet<string>> | null = null;

    In the constructor:

         this.contentionRetryDelaysMs = options.contentionRetryDelaysMs
           ?? SQLITE_CONTENTION_RETRY_DELAYS_MS;
    +    this.repositoryNotificationsEnabled = options.repositoryNotificationsEnabled;
      /**
       * Whether repository-scoped notifications may be produced for `repository`.
       *
       * Deliberately fails open. A transient SQLite read failure must never make a
       * failed task silently disappear from a user's Inbox; losing a notification is
       * strictly worse than emitting one the user asked to suppress.
       */
      private async notificationsEnabledFor(repository: string): Promise<boolean> {
        if (this.repositoryNotificationsEnabled) {
          return this.repositoryNotificationsEnabled(repository);
        }
        const disabled = await this.loadDisabledNotificationRepositories();
        return !disabled.has(repository.toLowerCase());
      }
    
      private loadDisabledNotificationRepositories(): Promise<ReadonlySet<string>> {
        const now = this.now().getTime();
        if (
          this.disabledRepositories !== null
          && now - this.disabledRepositoriesLoadedAt < REPOSITORY_NOTIFICATION_CACHE_TTL_MS
        ) {
          return Promise.resolve(this.disabledRepositories);
        }
        // Share one in-flight read across concurrent projections. A burst of task
        // updates would otherwise issue one query each against a connection that is
        // configured to fail fast under contention.
        this.disabledRepositoriesLoad ??= this.readDisabledNotificationRepositories()
          .then(disabled => {
            this.disabledRepositories = disabled;
            this.disabledRepositoriesLoadedAt = this.now().getTime();
            return disabled;
          })
          .catch(() => {
            // Fail open, and cache the empty set for the TTL so a persistent read
            // failure cannot turn into a query storm on the hot path.
            this.logger.warn('[NotificationProjection] Failed to read repository notification settings');
            this.disabledRepositories = new Set<string>();
            this.disabledRepositoriesLoadedAt = this.now().getTime();
            return this.disabledRepositories;
          })
          .finally(() => { this.disabledRepositoriesLoad = null; });
        return this.disabledRepositoriesLoad;
      }
    
      private async readDisabledNotificationRepositories(): Promise<ReadonlySet<string>> {
        const row = await this.database('system_configs')
          .where({ key: MONITORED_REPOS_CONFIG_KEY })
          .first() as { value?: unknown } | undefined;
        if (row?.value === undefined || row.value === null) return new Set<string>();
    
        // The column stores JSON; some drivers hand it back already parsed.
        const parsed: unknown = typeof row.value === 'string'
          ? JSON.parse(row.value) as unknown
          : row.value;
        // Accept both the bare array and an envelope object so this keeps working
        // whichever shape configManager persists. Confirm the actual shape once in
        // packages/core/src/config/configManager.ts and keep the tolerant branch.
        const entries: unknown[] = Array.isArray(parsed)
          ? parsed
          : Array.isArray((parsed as { repos_to_monitor?: unknown })?.repos_to_monitor)
            ? (parsed as { repos_to_monitor: unknown[] }).repos_to_monitor
            : [];
    
        // Resolution rule, mirrored in propr-ui/src/hooks/repositoryVisualPreview.ts:
        // a repository is disabled only when EVERY configured entry for its name is
        // explicitly false. Any entry that omits the field, or sets true, wins.
        const enabledByRepository = new Map<string, boolean>();
        for (const entry of entries) {
          const record = typeof entry === 'object' && entry !== null
            ? entry as Record<string, unknown>
            : null;
          const name = typeof entry === 'string'
            ? entry
            : typeof record?.name === 'string'
              ? record.name
              : typeof record?.full_name === 'string' ? record.full_name : undefined;
          if (name === undefined) continue;
          const key = name.toLowerCase();
          const enabled = record?.notificationsEnabled !== false;
          enabledByRepository.set(key, (enabledByRepository.get(key) ?? false) || enabled);
        }
    
        return new Set(
          [...enabledByRepository].flatMap(([name, enabled]) => enabled ? [] : [name]),
        );
      }

    3c. Guards on every repository-scoped projection

    Plans. The payload has no repository, so the guard must run after the draft row is loaded.

         if (typeof draft?.user_id !== 'string' || typeof draft.repository !== 'string') return;
    +    // Repository-level opt-out. Checked before any write so a suppressed plan
    +    // leaves no trace at all, which is what "won't generate any notifications"
    +    // means in the issue.
    +    if (!await this.notificationsEnabledFor(draft.repository)) return;
         const occurredAt = normalizeISO8601Timestamp(payload.timestamp);

    Tasks. The notification_source_activity upsert is deliberately left running. Those rows are the bookkeeping that drives stalled detection and resolution cleanup; skipping them would leave a repository's activity rows permanently non-terminal if the setting were toggled mid-flight, producing a spurious stalled card later.

         if (!accepted) return;
     
    +    // Activity bookkeeping above is intentionally unconditional; only the
    +    // user-visible notification is filtered here.
    +    if (!await this.notificationsEnabledFor(context.repository)) return;
    +
         const recipients = await this.loadInstanceMemberRecipients();

    Indexing.

         if (!accepted || payload.phase !== 'failed') return;
    +    if (!await this.notificationsEnabledFor(payload.repository)) return;
         const recipients = await this.loadAdministratorRecipients();

    Stalled sweep. The sweep reads rows that may have been recorded before the setting changed, so it needs its own guard.

         for (const row of rows) {
    +      // Rows can predate the operator disabling notifications for this
    +      // repository, so re-check rather than relying on the producer guards.
    +      if (!await this.notificationsEnabledFor(row.repository)) continue;
           const metadata = sourceMetadata(row);

    projectSystemSnapshot is intentionally untouched. system_failure notifications target a component, not a repository, and are the operator's only signal that the instance itself is unhealthy.


    4. Web UI

    File: propr-ui/src/api/proprTypes.ts

    Why this file: MonitoredRepo is the contract every repository component reads. Without this, the settings bar and the management hook will not type-check.

     export interface MonitoredRepo {
       id: string;
       name: string;
       enabled: boolean;
       alias?: string;
       baseBranch?: string;
       autoFollowupOnFailedCi?: boolean;
    +  /** Undefined means enabled: the product default, and the legacy behaviour. */
    +  notificationsEnabled?: boolean;
       starred?: boolean;
       hidden?: boolean;
       visualPreview?: { ... };
     }

    File: propr-ui/src/hooks/repositoryVisualPreview.ts

    Why this file: this module already owns the "one repository, many branch entries" merge rules used by buildRepositoriesForDisplay. Putting the notification rule anywhere else would let the displayed state drift from the displayed visual-preview and auto-CI state.

    /**
     * Resolve the repository-wide notification state from all of its branch entries.
     *
     * Kept identical to the server rule in notificationProjectionService.ts: only a
     * repository whose every entry is explicitly false reads as disabled. The UI
     * always writes all entries together, so divergence can only come from legacy
     * or hand-edited configuration — and in that case erring towards "enabled"
     * matches the default and never hides work from the user.
     */
    export function resolveRepositoryNotificationsEnabled(
      repos: readonly ManagedRepo[],
      repositoryKey: string,
    ): boolean {
      const entries = repos.filter(repo => getRepositoryConfigKey(repo.name) === repositoryKey);
      return entries.length === 0 || entries.some(repo => repo.notificationsEnabled !== false);
    }

    Then, inside buildRepositoriesForDisplay, unify the field exactly as autoFollowupOnFailedCi and visualPreview are unified today:

       return repos.map(repo => {
         const key = getRepositoryConfigKey(repo.name);
         return {
           ...repo,
           autoFollowupOnFailedCi: /* existing unification */,
    +      // Displayed state must match what the toggle will write, otherwise the
    +      // checkbox appears to "bounce back" after a save on multi-branch repos.
    +      notificationsEnabled: resolveRepositoryNotificationsEnabled(repos, key),
           visualPreview: /* existing unification */,
         };
       });

    File: propr-ui/src/hooks/useRepositoryManagement.ts

    Why this file: this hook owns loading, optimistic state and auto-save for repository configuration. Everything the settings bar renders comes from here.

    Parsing — both branches of loadRepos (the admin getRepoConfig path and the member getInstanceCatalog path go through the same mapper):

             .map((repo: unknown): Repo | null => {
               if (typeof repo === 'string') {
                 const userPref = prefs[repo] || {};
    -            return { id: generateId(), name: repo, enabled: true, autoFollowupOnFailedCi: false, visualPreview: defaultVisualPreview(), starred: userPref.starred, hidden: userPref.hidden };
    +            // Legacy string entries predate every per-repository option, so
    +            // they must read as the default: notifications on.
    +            return { id: generateId(), name: repo, enabled: true, autoFollowupOnFailedCi: false, notificationsEnabled: true, visualPreview: defaultVisualPreview(), starred: userPref.starred, hidden: userPref.hidden };
               } else if (repo && typeof repo === 'object') {
                 const repoObj = repo as Record<string, unknown>;
                 const name = (repoObj.name as string) || (repoObj.full_name as string);
                 const enabled = typeof repoObj.enabled === 'boolean' ? repoObj.enabled : true;
                 const autoFollowupOnFailedCi = repoObj.autoFollowupOnFailedCi === true;
    +            // `!== false` rather than `=== true`: an absent field is enabled.
    +            // Using `=== true` here would silence every pre-existing repository.
    +            const notificationsEnabled = repoObj.notificationsEnabled !== false;
                 const visualPreview = parseVisualPreview(repoObj.visualPreview);
                 ...
                 if (name) {
    -              return { id, name, enabled, autoFollowupOnFailedCi, visualPreview, alias, baseBranch, starred: userPref.starred, hidden: userPref.hidden };
    +              return { id, name, enabled, autoFollowupOnFailedCi, notificationsEnabled, visualPreview, alias, baseBranch, starred: userPref.starred, hidden: userPref.hidden };
                 }
               }
               return null;
             })

    Toggle handler — placed next to handleToggleAutoCiFollowup:

      const handleToggleNotifications = (repoId: string) => {
        // Configuration writes require instance.manage_settings; bail out silently
        // for read-only users exactly as the sibling handlers do, so an accidental
        // click never produces a 403 toast.
        if (!canManageRepositories) return;
        const targetRepo = repos.find(repo => repo.id === repoId);
        if (!targetRepo) return;
        const repositoryKey = getRepositoryConfigKey(targetRepo.name);
        // Flip the resolved repository-wide value so the write always converges
        // every branch entry onto one state, even if they started out divergent.
        const notificationsEnabled = !resolveRepositoryNotificationsEnabled(repos, repositoryKey);
        const newRepos = repos.map(repo => getRepositoryConfigKey(repo.name) === repositoryKey
          ? { ...repo, notificationsEnabled }
          : repo);
        setRepos(newRepos);
        performAutoSave(newRepos);
      };

    Import resolveRepositoryNotificationsEnabled from ./repositoryVisualPreview, add handleToggleNotifications: (repoId: string) => void; to UseRepositoryManagementResult, and include it in the returned object.

    handleAddRepo keeps the modal untouched but must still persist the default explicitly, so the stored document is self-describing:

         const newEntry: Repo = {
           id: generateId(),
           name: newRepo,
           enabled: true,
           autoFollowupOnFailedCi,
    +      // Not surfaced in the Add Repository modal by design (see the issue);
    +      // written explicitly so GET /api/config/repos is unambiguous.
    +      notificationsEnabled: true,
           visualPreview,
           alias: newAlias.trim() || undefined,
           baseBranch: newBaseBranch.trim() || undefined
         };

    File: propr-ui/src/components/RepositorySettingsBar.tsx

    Why this file: this renders the Settings tab content for the selected repository. The toggle is placed in its own Notifications group rather than inside Automation, because the whole Automation block is hidden for read-only users while this control must stay visible-but-disabled (consistent with Monitor repository, Star, and Hide).

       onToggleAutoCiFollowup: (repoId: string) => void;
    +  onToggleNotifications: (repoId: string) => void;
       onUpdateVisualPreview: (repoId: string, settings: RepositoryVisualPreviewSettings) => void;
       isReadOnly: boolean;
     }
     
     export const RepositorySettingsBar: React.FC<RepositorySettingsBarProps> = ({
       repo, indexingStatus, onToggle, onRemove, onStopIndexing, onReindex,
    -  onToggleStar, onToggleHidden, onToggleAutoCiFollowup, onUpdateVisualPreview, isReadOnly,
    +  onToggleStar, onToggleHidden, onToggleAutoCiFollowup, onToggleNotifications,
    +  onUpdateVisualPreview, isReadOnly,
     }) => {

    Insert the new section immediately after the closing </div> of the Repository group and before the Automation block:

               </label>
             </div>
     
    +        <div className="mt-8 border-t border-slate-200 pt-6">
    +          <h3 className="mb-2 text-[10px] uppercase font-bold tracking-widest text-slate-500">Notifications</h3>
    +          <label className="flex items-center justify-between gap-4 py-2 text-xs text-slate-600">
    +            <span className="min-w-0">
    +              <span className="block">Notifications</span>
    +              {/* The copy names the exact surfaces this filter covers. Desktop
    +                  native task alerts come from the live socket stream and are
    +                  explicitly out of scope, so they are not promised here. */}
    +              <span className="mt-1 block text-slate-500">
    +                Generate Inbox and push notifications for this repository. Turning this off silences
    +                plan, task, review, pull request, and indexing notifications without changing automation.
    +              </span>
    +            </span>
    +            <input
    +              type="checkbox"
    +              checked={repo.notificationsEnabled !== false}
    +              onChange={() => onToggleNotifications(repo.id)}
    +              disabled={isReadOnly}
    +              aria-label={`Notifications for ${repo.name}`}
    +              className="sr-only peer"
    +            />
    +            <span className={toggleClassName} />
    +          </label>
    +        </div>
    +
             {!isReadOnly && (
               <div className="mt-8 border-t border-slate-200 pt-6">
                 <h3 className="mb-2 text-[10px] uppercase font-bold tracking-widest text-slate-500">Automation</h3>

    toggleClassName is the module-level constant already used by the Monitor/Star/Hide rows, and it already handles peer-disabled styling — reusing it is what keeps the disabled read-only state visually correct without new CSS.

    File: propr-ui/src/pages/RepositoriesPage.tsx

    Why this file: it builds settingsContent and is the only place that wires hook handlers into the settings bar.

       const {
         repos, loading, error, availableRepos, indexingStatuses, saveStatus, showHiddenRepos,
         filteredRepos, hiddenCount, handleStopIndexing, handleReindexRepo, handleAddRepo,
         handleRemoveRepo, handleToggleRepo, handleToggleStar, handleToggleHidden,
    -    handleToggleAutoCiFollowup, handleUpdateVisualPreview,
    +    handleToggleAutoCiFollowup, handleToggleNotifications, handleUpdateVisualPreview,
         handleToggleShowHidden, handleRetry
       } = useRepositoryManagement();
           onToggleAutoCiFollowup={handleToggleAutoCiFollowup}
    +      onToggleNotifications={handleToggleNotifications}
           onUpdateVisualPreview={handleUpdateVisualPreview}

    5. CLI

    File: packages/cli/src/api/repos.ts

    Why this file: addRepo/updateRepo re-submit the whole repository list. If they drop the new field, a propr repo toggle would silently re-enable notifications a user turned off in the UI — the same class of bug preserveRepoNotifications guards against server-side.

     export interface Repository {
       id?: string;
       name: string;
       enabled: boolean;
       alias?: string;
       baseBranch?: string;
       autoFollowupOnFailedCi?: boolean;
    +  notificationsEnabled?: boolean;
       visualPreview?: RepositoryVisualPreview;
     }
       const newRepo: Repository = {
         name,
         enabled: true,
         autoFollowupOnFailedCi: options.autoFollowupOnFailedCi ?? false,
    +    // Explicit rather than omitted so the persisted document states the
    +    // product default instead of relying on every reader's fallback.
    +    notificationsEnabled: options.notificationsEnabled ?? true,
         ...
       };

    In updateRepo, merge notificationsEnabled alongside the other optional fields: apply it only when the caller supplied it, so unrelated updates preserve the stored value.

    File: packages/cli/src/commands/repoCommands.ts

       repo.command('add <repository>')
         .option('--alias <alias>', 'Friendly name for this repository')
         .option('--base-branch <branch>', 'Branch to monitor')
         .option('--auto-followup-on-failed-ci', 'Send an automatic follow-up when CI fails', false)
    +    // Commander turns `--no-notifications` into `options.notifications === false`,
    +    // which expresses "on by default, opt out" without an extra boolean parser.
    +    .option('--no-notifications', 'Do not generate Inbox or push notifications for this repository')

    In the action handler pass notificationsEnabled: options.notifications !== false, and add a Notifications column to displayReposTable rendering On / Off from repo.notificationsEnabled !== false.


    6. Tests

    These are the regressions that matter. Add each one to the file named.

    packages/api/test/configRepoValidation.test.ts

    test('defaults notificationsEnabled to true and accepts an explicit opt-out', () => {
      // The default is the entire backwards-compatibility guarantee of this feature.
      assert.equal(normalizeRepoConfig({ name: 'integry/propr', enabled: true }, 0).notificationsEnabled, true);
      assert.equal(
        normalizeRepoConfig({ name: 'integry/propr', enabled: true, notificationsEnabled: false }, 0).notificationsEnabled,
        false,
      );
    });
    
    test('rejects a non-boolean notificationsEnabled instead of coercing it', () => {
      // A coerced value would be persisted forever; failing loudly is cheaper.
      assert.throws(() => normalizeRepoConfig(
        { name: 'integry/propr', enabled: true, notificationsEnabled: 'false' }, 0,
      ));
    });

    packages/api/test/configRepoRoutes.test.ts

    • GET returns notificationsEnabled: true for a stored entry that omits the field.
    • POST with notificationsEnabled: false on one branch entry persists false on every entry of that repository name and leaves other repositories untouched.
    • POST from a client that omits the field preserves a stored false (covers preserveRepoNotifications).

    packages/api/test/notificationProjectionService.test.ts

    Use the existing harness and seed the configuration row before projecting:

    test('produces no repository notifications when the repository opts out', async () => {
      await database('system_configs').insert({
        key: 'repos_to_monitor',
        value: JSON.stringify([{ name: 'integry/propr', enabled: true, notificationsEnabled: false }]),
      });
    
      // One representative event per repository-scoped projection path.
      await projection.projectTaskUpdate({ /* completed task in integry/propr */ });
      await projection.projectIndexingUpdate({ /* failed indexing in integry/propr */ });
      await projection.projectDraftUpdate({ /* draft reaching review in integry/propr */ });
      clock += 45 * 60_000;
      await projection.detectStalledActivities();
    
      assert.equal(await countNotificationEvents(database), 0);
    
      // System health is not repository-scoped and must survive the filter,
      // otherwise an operator could silence their only instance-health signal by
      // muting a repository.
      await projection.projectSystemSnapshot({ timestamp: iso(), redis: 'disconnected' });
      assert.equal(
        await database('notification_events').where({ kind: 'system_failure' }).count('* as count')
          .first().then(row => Number(row?.count)),
        1,
      );
    });
    
    test('still records source activity while notifications are suppressed', async () => {
      // Bookkeeping must keep running so re-enabling the setting does not resurrect
      // a stale "stalled" card for work that already finished.
    });
    
    test('fails open when the repository configuration cannot be read', async () => {
      // Drop or corrupt the system_configs row and assert the notification is
      // still created and a single warning is logged.
    });

    propr-ui/src/hooks/useRepositoryManagement.test.tsx

    it('defaults notifications on for legacy entries and writes the toggle to every branch entry', async () => {
      mockGetRepoConfig.mockResolvedValue({ repos_to_monitor: [
        { id: 'repo-main', name: 'integry/propr', enabled: true, baseBranch: 'main' },
        { id: 'repo-release', name: 'INTEGRY/PROPR', enabled: true, baseBranch: 'release' },
        { id: 'repo-other', name: 'integry/other', enabled: true },
      ]});
      const { result } = renderHook(() => useRepositoryManagement());
      await waitFor(() => expect(result.current.loading).toBe(false));
      expect(result.current.repos.map(r => r.notificationsEnabled)).toEqual([true, true, true]);
    
      act(() => result.current.handleToggleNotifications('repo-main'));
      await waitFor(() => expect(mockUpdateRepoConfig).toHaveBeenCalledTimes(1));
      // Case-insensitive name matching is what keeps duplicate-cased entries in sync.
      expect(mockUpdateRepoConfig.mock.calls[0][0].map(r => r.notificationsEnabled))
        .toEqual([false, false, true]);
    });

    propr-ui/e2e/repositories-settings.pw.ts

    • Add an assertion in the shared-settings test that toggling Notifications writes notificationsEnabled: false to both branch entries.
    • Add to the read-only test: await expect(page.getByRole('checkbox', { name: 'Notifications for integry/propr', exact: true })).toBeDisabled(); — note the existing /Automatic CI follow-up|Visual previews/ count assertion stays valid because the new control has a distinct accessible name.

    7. Documentation

    • CHANGELOG.md: add an Added entry under Unreleased describing the per-repository notification filter and its default-on behaviour.
    • packages/api/README.md (Web Push section): note that repository-scoped notifications are additionally gated by the repository's notificationsEnabled setting, and that system_failure notifications are not.
  2. propr-dev commented on Sep 22, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using claude agent with claude-opus-5 model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: claude
    • Model: claude-opus-5
    • Branch: 2457/claude-opus-5-add-a-per-repository-noti-20260922-0837-1wb
    • Base Branch: main
    • Worktree: issue-2457-20260922-0837-claude-opus-5-1wb

    🔍 Track Task Execution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions