Skip to content

refactor(app): move the alerts and notification state into a hook - #1768

Merged
devswha merged 1 commit into
mainfrom
refactor/app-alerts-hook
Oct 23, 2026
Merged

devswha merged 1 commit into
mainfrom
refactor/app-alerts-hook

Conversation

@devswha

@devswha devswha commented Oct 23, 2026

Copy link
Copy Markdown
Owner

Wave 5 of the App.tsx split. The plan is .omo/plans/app-stores-split.md in the maintainer's workspace, and plan-reviewer approved it. It follows PR #1766.

This wave moves this device's alert and notification state out of src/App.tsx into src/lib/useAlerts.ts. It also moves what the event stream does for alerts when a pane's status changes or a pane exits.

This is not purely moved code. The event-stream effect stays in App, and three pieces of its handler become calls to hook callbacks, so this PR waits for a review. Every line the pieces held moves byte for byte, apart from indentation.

What moves

Six blocks move verbatim, in source order, into useAlerts:

  • (A) the alert preferences: alerts, alertsRef, alertsOn and alertsOnRef.
  • (B) notifications, pushOn and pushOnRef.
  • (C) the status refs: statusRef, turnStartRef, lastTurnRef, alertInAppRef and alertSoundRef. followFocusRef stays in App.
  • (D) dropIn, the alert-sound player effect, chime, and the sound-unlock effect.
  • (E) enableNotifications, disableNotifications, and the push re-registration effect.
  • (F) the bell, bellVisible and alertsOffDot.

In the event-stream effect, three pieces become calls at exactly the points the lines stood:

  • Roster: onRoster(payload.machines) is the roster's seedStatuses line. The only token that changes is payload.machines, which becomes the parameter machines.
  • Pane status: onPaneStatus(machine, message, takeNotificationTargetRef) covers the status bookkeeping, the in-app drop and chime, and the system notification. The setMachines(applyPaneStatus…) update stays in App, right after the call.
  • Pane exit: onPaneExited(machine, message, takeNotificationTargetRef) covers the ended-turn drop and chime, then the ended notification. The herdr-usage-changed dispatch stays in App, before the call.

takeNotificationTargetRef is declared later in App, so the effect passes the ref object at event time. The moved lines still read takeNotificationTargetRef.current at the same moment as before.

Why behaviour is unchanged

Hook call position: the hook is called where notifications was declared, before App's followFocusRef. The alert values were not read anywhere between their old declaration and that point. Everything the hook takes is declared before it: settings, updateSettings, t, locked, selectionRef, drawerOpenRef, splitRef, splitShownRef and machinesRef.

No resubscription: dropIn, chime, onRoster, onPaneStatus and onPaneExited are all useCallback(..., []). The event-stream effect's dependency list [locked, scheduleRefetch, dropIn, chime, reorderCoordinator] is unchanged, so the stream does not resubscribe. enableNotifications and disableNotifications keep [updateSettings].

Effect order: three effects now run earlier in a commit than before:

  • The alert-sound player effect and the sound-unlock effect now run before App's load-and-health effect. They only create a player and listen for taps, independent of loading.
  • The push re-registration effect now runs before the load-and-health effect and the event-stream effect.
    • On first load it returns at once, because locked is still null.
    • When the lock opens, it and the event-stream effect re-run in the same commit, in the opposite order. Both only start asynchronous network calls (a push subscription; an EventSource) and share no state.

The bell: it is computed during render. It reads only values the hook owns, plus settings and t.

Hook ceiling: APP_HOOK_CEILING drops from 163 to 144. That is the 19 hook calls that moved: 3 in A, 3 in B, 5 in C, 5 in D and 3 in E.

Checks

  • --color-moved: git diff --color-moved=plain --color-moved-ws=allow-indentation-change origin/main...HEAD shows 361 lines as moved. The other 57 lines are:

    • App's narrowed imports, the new import and the call;
    • the three event-stream calls and the onRoster line;
    • the new file's imports, params interface, message types, signature, the three callback headers and closers, the doc comment and the return;
    • the ceiling.
  • Moved lines are exact: blocks A-F appear byte for byte in the hook (lines 225-232, 496-500, 509-518, 604-647, 744-787 and 1317-1343 of App.tsx on 53b85127e). The event-stream lines 677-689, 704-709 and 711-714 appear apart from indentation.

  • Typecheck: bun run typecheck passes.

  • Unit tests: 129 pass, 0 fail across 9 files, from:

    HERDR_TEST_MODE=unit bun test src/app-hooks.test.ts src/conventions.test.ts src/lib/notifications.test.ts src/lib/droplet.test.ts src/lib/alertTurns.test.ts src/lib/alertSound.test.ts src/lib/push.test.ts src/lib/notificationTarget.test.ts src/lib/i18n.test.ts

  • Ceiling test: adding const zz = useState(false); to App.tsx makes src/app-hooks.test.ts fail.

  • bun run check fast: passes after the rebase (unit 6253 pass, 0 fail, 13 skip in 443 files, 8 at a time, 57.5s)

  • bun run check integration browser: the browser lane exits 0 (every browser script passed, 1816 s), including the alert scripts: the Alerts item off/on, blocked-permission switch, Settings push test, notification startup, a tapped pane alert opening chat/terminal/workspace, in-app alerts (open pane spared, drop-in, flick, close, timeout, off stays off, split half spared) and the alert sound (no sound before a tap, Settings toggle with preview, two tabs chime once). It ran on this commit before its rebase onto the latest main, which changed only PaneTerminal files. The integration lane's only failure is server/api.contract.test.ts "creates, edits, searches, inspects, and closes an owned workspace" (line 1540), which fails the same way on unchanged origin/main on this PC; CI runs that lane in its own environment.

Outside PRs that touch the same files

No other maintainer PR touches these files. One outside contributor's PR touches src/App.tsx: #1427. It already conflicts with main there, and in eight other files, so it needs a rebase either way.

No changelog fragment: users see no change.

Move the alert prefs, notification and push state, the droplet and chime callbacks, the sound effects, the push registration and the Alerts item's bell into src/lib/useAlerts.ts, called where the notifications state stood.
The event stream calls onRoster/onPaneStatus/onPaneExited at the exact points the lines stood, with takeNotificationTargetRef passed at event time.
The four callbacks (dropIn, chime, onRoster/onPaneStatus/onPaneExited) are useCallback([]) so the stream does not resubscribe.
App's now-unused alerting copy and imports are dropped; the hook ceiling is lowered to 144.
Plan .omo/plans/app-stores-split.md wave 5.
@coderabbitai

coderabbitai Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

📝 Summary

Summary by CodeRabbit

  • Refactor
    • Alert preferences, browser notification permissions, push notifications, in-app alerts, and pane status notifications are now managed through a unified alert system. Notifications continue to respect the currently viewed pane, and alert controls remain available in the app.

App now delegates alert state, notification controls, alert-menu values, and roster and pane event handling to the new useAlerts hook. The hook contains the notification lifecycle, in-app alert handling, and status tracking previously implemented inline.

Changes: Alert handling

Layer / File(s) Summary
Alert lifecycle and event handling
src/lib/useAlerts.ts
useAlerts manages alert preferences, browser permission and push subscriptions, in-app droplets and sounds, turn-duration tracking, pane status and exit handling, and alert-menu values.
App integration
src/App.tsx, src/app-hooks.test.ts
App uses the hook's returned values and forwards roster, pane-status, and pane-exit events to its handlers. The hook-call ceiling changes from 163 to 144.

Priority: ⬇️ Low

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Merge Risk: ⚪ Minimal · up to fee0c

No current alert-behavior regression is established; this change is mergeable after normal checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly and concisely describes the primary change: moving alert and notification state into a hook.
Description check Passed The description explains the change, scope, behavior-preservation rationale, and validation results. It uses a "Checks" heading instead of the template's "Validation" heading, but it provides the requ…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description explains the change, scope, behavior-preservation rationale, and validation results. It uses a "Checks" heading instead of the template's "Validation" heading, but it provides the required validation information and is otherwise complete.

✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔇 Additional comments: 3
src/lib/useAlerts.ts: 1

1-221: LGTM!

src/app-hooks.test.ts: 1

5-5: LGTM!

src/App.tsx: 1

636-636: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

⚠️ Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.

Update the SSE effect dependencies to match the new callbacks.

The effect body now calls onRoster, onPaneStatus and onPaneExited, but the dependency array does not list them. The array still lists dropIn and chime, which the body no longer references.

This is not a runtime bug today. All three callbacks are useCallback(..., []) in useAlerts, so their identity never changes and the stream does not resubscribe. The mismatch has two costs:

  • react-hooks/exhaustive-deps cannot treat values returned from a custom hook as stable. It will report the missing entries.
  • If a later edit adds a dependency to one of these callbacks, the stream keeps the old callback and its stale closure.

Replace the stale entries with the callbacks the effect uses. After that, dropIn and chime may no longer need to be destructured in App.

♻️ Proposed change
-  }, [locked, scheduleRefetch, dropIn, chime, reorderCoordinator]);
+  }, [locked, scheduleRefetch, onRoster, onPaneStatus, onPaneExited, reorderCoordinator]);

Source: Learnings


ℹ️ Review info
⚙️ Run configuration
📥 Commits

Reviewing files that changed from the base of the PR and between 5e44913 and fee0c61.

📒 Files selected for processing: 3
  • src/App.tsx
  • src/app-hooks.test.ts
  • src/lib/useAlerts.ts

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

@devswha

devswha commented Oct 23, 2026

Copy link
Copy Markdown
Owner Author

Hold this PR for one more push, please. I found it does not follow the plan's rule R1 exactly.

The rule: every contiguous moved block becomes its own hook call, at that block's original line, so effect order stays identical.

What this PR does instead: it calls one useAlerts at the notifications line, which moves three effects earlier in a commit. The PR body argues that this is harmless. The plan asks for no such argument to be needed.

The coming push: it keeps src/lib/useAlerts.ts and the same moved lines, but exports one hook per block, each called at that block's own line:

  • the alert prefs;
  • the notification state;
  • the status refs;
  • the in-app signals, which also hold the three event-stream callbacks;
  • the notification switch, with the push effect;
  • the bell.

With that, every effect and listener keeps its exact registration order. I'll update the body with it.

@devswha

devswha commented Oct 23, 2026

Copy link
Copy Markdown
Owner Author

Merge pass: this PR isn't purely moved code. Three pieces of the event-stream handler become hook callbacks, so this comment records the review.

Gate review, by a reviewer on a different model than the author's:

  • Moved blocks: all six match their originals exactly, in source order.
  • takeNotificationTargetRef: read at click time, as before.
  • Hook count: counted on the TypeScript AST, 163 → 144.
  • Browser regression: alert-sound, freshly built, passes.

Stale closures, checked by the merge pass:

  • onRoster, onPaneStatus and onPaneExited are [] callbacks that read only:
    • refs (statusRef, alertsRef, alertsOnRef, pushOnRef, the turn refs);
    • module-level helpers;
    • dropIn/chime, which are themselves [] callbacks with stable identity.
  • No state, t or settings value is captured, so freezing them at first render goes stale nowhere.
  • The event-stream effect's dependency array is unchanged on both sides: [locked, scheduleRefetch, dropIn, chime, reorderCoordinator].

Tests at this head: 76 unit tests (app-hooks, droplet, notifications, alertTurns, alertSound, conventions) and the typecheck pass.

All required checks are green and no review thread is open.

@devswha
devswha merged commit d64e9ed into main Oct 23, 2026
9 checks passed
@devswha
devswha deleted the refactor/app-alerts-hook branch October 23, 2026 15:55
devswha added a commit that referenced this pull request Oct 23, 2026
A follow-up to PR #1768, wave 5 of the App.tsx split. The plan is
`.omo/plans/app-stores-split.md` in the maintainer's workspace.

The plan's rule R1 says every contiguous block moved out of
`src/App.tsx` becomes its own hook call, placed at that block's original
line, so effect and listener order stay exactly as they were. PR #1768
broke that rule:
- **What it did:** it gathered six separate blocks into one `useAlerts`
call at the `notifications` line.
- **What changed as a result:** three effects ran earlier in a commit
than before:
  - the alert-sound player effect;
  - the sound-unlock effect;
- the push re-registration effect, which also moved ahead of the
event-stream effect.
- **Harm found:** none. PR #1768's body and the merge pass's review
found no behaviour change from this.

This PR restores the exact order anyway, so no such argument is needed.

## What changes

`src/lib/useAlerts.ts` now exports one hook per block. Each is called in
`App.tsx` at its block's original line (the line numbers are from before
PR #1768):

| Block | Hook | Called where the block stood |
|---|---|---|
| alert prefs (`alerts`, `alertsRef`, `alertsOn`, `alertsOnRef`) |
`useAlertPrefs({ settings })` | right after `useSettings()` |
| `notifications`, `pushOn`, `pushOnRef` | `useNotificationState()` |
after the connection chip |
| status and turn refs, in-app and sound switches | `useAlertRefs({
settings })` | after `lockedRef`, before `followFocusRef` |
| `dropIn`, the sound player effect, `chime`, the sound-unlock effect,
plus the three event-stream callbacks | `useAlertSignals({ … })` |
before the event-stream effect |
| `enableNotifications`, `disableNotifications`, the push
re-registration effect | `useNotificationSwitch({ … })` | after the
event-stream effect and `handleServerMessage` |
| the bell, `bellVisible`, `alertsOffDot` (no hooks) | plain
`alertsBell({ … })` | where the bell was computed |

- **Moved lines:** none changes. Each hook's body is its block's lines
from PR #1768.
- **Effects and callbacks:** every effect is back at its original line.
The three event-stream callbacks (`onRoster`, `onPaneStatus`,
`onPaneExited`) are `useCallback([])` hooks without effects, so where
they sit inside `useAlertSignals` changes no order.
- **Hook ceiling:** unchanged at 144, because the same hook calls left
App.

## Checks

- **`--color-moved`:** `git diff --color-moved=plain
--color-moved-ws=allow-indentation-change origin/main...HEAD` shows
only:
  - the single call replaced by six calls;
  - the import line;
- `useAlerts` split into hook signatures, params interfaces, doc
comments and returns.

  The block bodies show as moved, or as unchanged in place.
- **Moved blocks are exact:** all six blocks match `App.tsx` before PR
#1768 (`53b85127e`) byte for byte, at lines 225-232, 496-500, 509-518,
604-647, 744-787 and 1317-1343.
- **Positions:** the line before each new call is the line that came
before its block on `53b85127e`.
- **Typecheck:** `bun run typecheck` passes.
- **Unit tests:** **129 pass, 0 fail across 9 files**, from:

`HERDR_TEST_MODE=unit bun test src/app-hooks.test.ts
src/conventions.test.ts src/lib/notifications.test.ts
src/lib/droplet.test.ts src/lib/alertTurns.test.ts
src/lib/alertSound.test.ts src/lib/push.test.ts
src/lib/notificationTarget.test.ts src/lib/i18n.test.ts`
- `bun run check fast`: passes (unit 6253 pass, 0 fail, 13 skip in 443
files, 8 at a time, 68.4s)
- **Alert browser scripts:** each run with `bun run check run --build
bun scripts/<name>.ts`: `alert-sound-regression`, `droplet-regression`,
`droplet-demo-regression`, `notification-startup-regression`,
`notification-view-regression` and `push-settings-regression` each exit
0.

No changelog fragment: users see no change.
devswha added a commit that referenced this pull request Oct 23, 2026
…ks (#1770)

Wave 6 of the App.tsx split. The plan is
`.omo/plans/app-stores-split.md` in the maintainer's workspace, and
plan-reviewer approved it. It follows PR #1768 and PR #1769.

This wave moves the state behind the dialogs, the file panels, the
command palette and the pane-coverage check out of `src/App.tsx`. That
is seven blocks, into five new files.

Following the plan's rule R1:
- Each contiguous block becomes one hook, called at that block's own
line.
- The new-session area has three separate blocks, so its file exports
three hooks.

Effect and listener registration order stay identical. That includes the
`popstate` listeners that `useFileViewer` and `useRepoDiffViewer`
register, and the coverage MutationObserver.

## What moves

| File | Hook | Block (App.tsx on `41189ee36`) | Contents |
|---|---|---|---|
| `src/lib/useMachineDialog.ts` | `useMachineDialog()` | 246-255 |
`machineDialog`, `addPcFocusReturn`, `closeMachineDialog` |
| `src/lib/useNewSessionDialog.ts` | `useNewSessionMachine()` | 256 |
`newSessionMachineId` |
| `src/lib/useCommandPalette.ts` | `useCommandPalette()` | 395-397 |
`paletteOpen`, `paletteQuery`, `openPalette` |
| `src/lib/useFilePanels.ts` | `useFilePanels({ settings,
filePanelAvailable, selectedPaneId, selectedMachineId })` | 405-463 |
`filesOpen`; the `useFileViewer`, `useRepoDiffViewer` and
`useFocusReturn` calls; `presentation`, `fileDocked` and both
docked-close effects; `webPage` and `openWebPage`; `collapsing` and its
effect; `presentFile`, `reportFileKind`, `toggleFilePresentation`,
`viewFile` |
| `src/lib/useNewSessionDialog.ts` | `useNewSessionState({ initialLink
})` | 465-475 | `newSessionOpen`, `newPrefill`, `newFields`,
`pendingCreate`, `newTab`, `sessionHistory` |
| `src/lib/usePaneCoverage.ts` | `usePaneCoverage({ contentKey })` |
866-879 | `dialogCover`, `contentReady`, the MutationObserver effect |
| `src/lib/useNewSessionDialog.ts` | `useSessionHistoryList({ … })` |
1352-1367 | `closeNewSession`, `closeSessionHistory`,
`useRecentResumes`, the away-PC probe effect, `sessionHistoryWorkspace`
and its effect |

- **What stays in App, as the plan says:**
  - the `pendingCreate` effect, whose deps include `actions`;
  - `contentKey`;
  - `paneInFront`;
  - every call site.
- **Dependency lists and returned refs:** every `useCallback`/`useMemo`
dependency list is unchanged. `openWebPage` and `viewFile` are context
values, and keep their exact deps. Refs (`addPcFocusReturn`,
`pendingCreate`, `collapsing`) are returned as the same objects.
- **Imports:** App drops the imports only the moved code used.
- **Hook ceiling:** `APP_HOOK_CEILING` drops from 144 to 113, after
moving 31 builtin hook calls.

## Checks

- **`--color-moved`:** `git diff --color-moved=plain
--color-moved-ws=allow-indentation-change origin/main...HEAD` shows 228
lines as moved. The other 99 lines are:
  - App's narrowed imports, the five new imports and the seven calls;
  - the ceiling;
  - the new files' imports, params types, signatures and returns.
- **Moved blocks are exact:** all seven blocks appear byte for byte in
their hooks.
- **Positions:** the line before and after each call is the line that
surrounded its block on `41189ee36`.
- **Typecheck:** `bun run typecheck` passes.
- **Unit tests:** `HERDR_TEST_MODE=unit bun test src/app-hooks.test.ts
src/conventions.test.ts src/lib/i18n.test.ts
src/lib/filePresentation.test.ts src/lib/webPanel.test.ts
src/lib/paletteSeed.test.ts`: 42 pass, 0 fail.
- **Ceiling test:** adding `const zz = useState(false);` to App.tsx
makes `src/app-hooks.test.ts` fail.
- `bun run check fast`: passes (unit 6253 pass, 0 fail, 13 skip in 443
files, 8 at a time, 57.9s)
- **`bun run check integration browser`:** the browser lane exits 0
(every browser script passed, 1815 s), including the file viewer, repo
diff, files prompt, palette, machine dialog, session history,
new-session, recent folders, deep link and sidebar activity scripts. The
integration lane's only failure is `server/api.contract.test.ts`
"creates, edits, searches, inspects, and closes an owned workspace"
(line 1540), which fails the same way on unchanged `origin/main` on this
PC; CI runs that lane in its own environment.

## Outside PRs that touch the same files

No other maintainer PR touches these files. One outside contributor's PR
touches `src/App.tsx`: #1427. It already conflicts with main, and needs
a rebase either way.

Move-only: moved blocks plus imports, hook signatures and returns, seven
calls and the lowered ceiling. No changelog fragment: users see no
change.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant