Skip to content

refactor: deduplicate shortcuts and manage timer completion timeouts#79

Merged
VariableThe merged 3 commits into
mainfrom
refactor/code-quality-and-tests
Jun 29, 2026
Merged

refactor: deduplicate shortcuts and manage timer completion timeouts#79
VariableThe merged 3 commits into
mainfrom
refactor/code-quality-and-tests

Conversation

@VariableThe

@VariableThe VariableThe commented Jun 29, 2026

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • Bug Fixes

    • Global shortcuts now behave more consistently when triggered, improving window focus and action handling.
    • Completed timers are cleaned up more reliably, reducing cases where expired timers linger.
    • Variable evaluation now handles nested expressions and fallback values more predictably.
  • Tests

    • Added coverage for variable scope merging and expression parsing behavior.

@coderabbitai

coderabbitai Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@VariableThe, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 46 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3621b75b-28f7-4ce7-bb96-e645e0967255

📥 Commits

Reviewing files that changed from the base of the PR and between 0317342 and 2a9b9a8.

📒 Files selected for processing (3)
  • AUDIT_LOG.md
  • CHANGELOG.md
  • src/lib/editor/VariableScope.test.ts
📝 Walkthrough

Walkthrough

Three independent quality improvements: shortcuts.rs extracts duplicated shortcut-pressed inline logic into a handle_shortcut_trigger helper; useTimerStore.ts adds a completionTimeouts map and clearCompletionTimeout helper to properly track and cancel per-timer cleanup timeouts; and a new VariableScope.test.ts suite covers scope merging, debounced expression evaluation, and parse-failure fallback.

Changes

Shortcut Trigger Deduplication

Layer / File(s) Summary
handle_shortcut_trigger helper and call sites
src-tauri/src/commands/shortcuts.rs
New private helper centralizes show/focus, toggle, and emit logic; update_global_shortcut and resume_shortcuts callbacks replaced with single calls to it.

Timer Completion Timeout Lifecycle

Layer / File(s) Summary
completionTimeouts tracking and store method updates
src/store/useTimerStore.ts
Adds completionTimeouts map and clearCompletionTimeout helper; completeTimer cancels and reschedules, removeTimer clears on delete, cleanExpiredTimers explicitly clears before filtering.

VariableScope Unit Tests

Layer / File(s) Summary
VariableScope test harness and cases
src/lib/editor/VariableScope.test.ts
Vitest suite with fake timers covering getScope merging precedence, debounced numeric expression evaluation, and raw-string fallback on parse failure.

Changelog and Audit Log

Layer / File(s) Summary
Documentation updates
CHANGELOG.md, AUDIT_LOG.md
New [Unreleased] Changed entry and dated audit section document all three changes.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~15 minutes

Possibly related PRs

  • VariableThe/PaperCache#76: Modifies useTimerStore.ts completed-timer cleanup scheduling, directly overlapping with the timeout lifecycle changes here.
  • VariableThe/PaperCache#77: Also refactors useTimerStore.ts timer cleanup behavior, sharing the same per-timer lifecycle code path modified in this PR.

Poem

🐇 Hop hop, no duplicates remain,
The shortcut helper shares one lane.
Timers cleared with proper care,
No phantom callbacks lurking there.
VariableScope tests now in place —
A tidy warren, every trace! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly reflects the two main code changes: shortcut deduplication and timer completion timeout management.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/code-quality-and-tests

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
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/store/useTimerStore.ts (1)

50-61: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Avoid side effects inside the set updater.

clearCompletionTimeout(t.id) is invoked from within the filter predicate that runs inside the set((state) => ...) updater. Zustand expects the updater to be a pure state transform; performing timer-cancellation side effects there is an anti-pattern that can misbehave if the updater is ever re-invoked (e.g., under middleware). Compute the set of expired ids first, clear their timeouts, then return the new state.

♻️ Proposed refactor
   cleanExpiredTimers: () => {
     const now = Date.now()
-    set((state) => ({
-      timers: state.timers.filter((t) => {
-        if (t.status === 'completed' && now - t.endsAt >= COMPLETED_TIMER_CLEANUP_MS) {
-          clearCompletionTimeout(t.id)
-          return false
-        }
-        return true
-      }),
-    }))
+    const expiredIds = new Set(
+      useTimerStore
+        .getState()
+        .timers.filter(
+          (t) => t.status === 'completed' && now - t.endsAt >= COMPLETED_TIMER_CLEANUP_MS
+        )
+        .map((t) => t.id)
+    )
+    expiredIds.forEach((id) => clearCompletionTimeout(id))
+    set((state) => ({
+      timers: state.timers.filter((t) => !expiredIds.has(t.id)),
+    }))
   },
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/store/useTimerStore.ts` around lines 50 - 61, The cleanExpiredTimers
updater in useTimerStore mixes state updates with the side effect of calling
clearCompletionTimeout inside the filter predicate. Refactor it so the set
callback is a pure transform: first derive the expired completed timer ids from
state.timers, then clear their timeouts outside the set updater, and finally
return the filtered timers array from cleanExpiredTimers without invoking side
effects during the state calculation.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/lib/editor/VariableScope.test.ts`:
- Around line 44-53: Update the VariableScope fallback test to assert the real
trim behavior, not just a pre-trimmed input. In VariableScope.test.ts, change
the doc string used with VariableScope.triggerScopeUpdate() so the raw RHS
includes leading/trailing spaces and still expects getNoteScope() to store the
trimmed value. This will verify that triggerScopeUpdate() continues to call
.trim() when expression parsing fails.

---

Nitpick comments:
In `@src/store/useTimerStore.ts`:
- Around line 50-61: The cleanExpiredTimers updater in useTimerStore mixes state
updates with the side effect of calling clearCompletionTimeout inside the filter
predicate. Refactor it so the set callback is a pure transform: first derive the
expired completed timer ids from state.timers, then clear their timeouts outside
the set updater, and finally return the filtered timers array from
cleanExpiredTimers without invoking side effects during the state calculation.
🪄 Autofix (Beta)

✅ Autofix completed


ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c238c9de-78f3-4656-9026-7758dd021b20

📥 Commits

Reviewing files that changed from the base of the PR and between 5feed52 and 0317342.

📒 Files selected for processing (5)
  • AUDIT_LOG.md
  • CHANGELOG.md
  • src-tauri/src/commands/shortcuts.rs
  • src/lib/editor/VariableScope.test.ts
  • src/store/useTimerStore.ts

Comment thread src/lib/editor/VariableScope.test.ts
@coderabbitai

coderabbitai Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

Note

Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.

Fixes Applied Successfully

Fixed 1 file(s) based on 1 unresolved review comment.

Files modified:

  • src/lib/editor/VariableScope.test.ts

Commit: be9f97eda10129a6b261ddb7ba237c96dd3da390

The changes have been pushed to the refactor/code-quality-and-tests branch.

Time taken: 2m 10s

coderabbitai Bot and others added 2 commits June 29, 2026 10:09
Fixed 1 file(s) based on 1 unresolved review comment.

Co-authored-by: CodeRabbit <noreply@coderabbit.ai>
@VariableThe VariableThe merged commit dbcf870 into main Jun 29, 2026
4 checks passed
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