Skip to content

feat: auto-follow active document in Auto Run sidebar (#347)#518

Open
kianhub wants to merge 7 commits intoRunMaestro:mainfrom
kianhub:feature/347-autorun-auto-focus-active-document
Open

feat: auto-follow active document in Auto Run sidebar (#347)#518
kianhub wants to merge 7 commits intoRunMaestro:mainfrom
kianhub:feature/347-autorun-auto-focus-active-document

Conversation

@kianhub
Copy link
Contributor

@kianhub kianhub commented Mar 5, 2026

Summary

Adds a "Follow active task" toggle to the Auto Run batch progress banner. When enabled, the sidebar automatically tracks the currently running document and scrolls to the active task — without stealing focus from the user's workspace.

Closes #347

What Changed

New: useAutoRunAutoFollow hook (src/renderer/hooks/batch/useAutoRunAutoFollow.ts)

Extracted, testable hook that encapsulates all auto-follow logic:

  • Tracks currentDocumentIndex changes in BatchRunState
  • Auto-selects the active document via onAutoRunSelectDocument
  • On batch start (when toggle is on): switches Right Bar to autorun tab, opens panel if closed, switches to preview mode

Modified: RightPanel.tsx

  • Integrates useAutoRunAutoFollow hook
  • Adds a checkbox toggle ("Follow active task") inside the batch progress banner at the bottom
  • Passes autoFollowEnabled to AutoRun via shared props

Modified: AutoRun.tsx

  • New autoFollowEnabled prop
  • Focus-safe scrolling: When auto-follow is active during a batch run, two existing useEffects that call .focus() (on mode change and document selection) are guarded to skip focus — preventing the sidebar from stealing focus from the user's main input or scratchpad
  • Scroll-to-active-task: New useEffect queries the preview for the first unchecked checkbox (input[type="checkbox"]:not(:checked)) and scrolls its parent li into view with scrollIntoView({ behavior: 'smooth', block: 'center' }) — this only scrolls the container, never moves DOM focus
  • Added to React.memo comparison function

New: Tests (useAutoRunAutoFollow.test.ts)

8 test cases covering:

  1. No auto-select when toggle is off (default)
  2. Auto-select on batch start when enabled
  3. Auto-select on document index change
  4. Skip when already on correct document
  5. Tab switch to autorun on batch start
  6. No tab switch when disabled
  7. Open right panel when closed
  8. Ref reset when batch ends

Design Decisions

Decision Rationale
Toggle (default off) instead of always-on Per Pedro's feedback — users often have scratchpads open during runs
scrollIntoView instead of manual scroll math Native API, smooth animation, and critically: does NOT steal focus
Guard existing .focus() calls with autoFollowEnabled && isRunning Simpler than ref-based flags; when auto-follow is active during a batch, focus should never move to the sidebar
Extracted hook instead of inline in RightPanel Testable in isolation with renderHook, keeps RightPanel clean
Preview mode auto-switch on batch start Scroll-to-task only works in preview mode (rendered markdown)

How to Test

  1. Open an Auto Run folder with multiple documents containing checkbox tasks
  2. Start a batch run
  3. Check the "Follow active task" checkbox in the progress banner
  4. Observe: the sidebar auto-selects each document as the batch progresses and scrolls to the first unchecked task
  5. Verify: typing in the main AI input is NOT interrupted by the scrolling
  6. Uncheck the toggle — sidebar stops following

Files Changed

File Change
src/renderer/hooks/batch/useAutoRunAutoFollow.ts New hook
src/renderer/hooks/batch/index.ts Export new hook
src/renderer/components/RightPanel.tsx Hook integration + toggle UI
src/renderer/components/AutoRun.tsx Focus guards + scroll-to-task
src/__tests__/renderer/hooks/useAutoRunAutoFollow.test.ts 8 test cases

Summary by CodeRabbit

  • New Features

    • Added "Follow active task" toggle in the right panel and batch modal to enable automatic task tracking during batch runs.
    • Auto-follow will select the active document, switch to the autorun tab, open the right panel if closed, and scroll to the first unchecked task in preview mode; setting is persisted in UI state.
  • Tests

    • Added comprehensive test coverage for auto-follow behavior across batch and navigation scenarios.

kianhub added 4 commits March 5, 2026 11:01
Add "Follow active task" checkbox to the Auto Run batch progress banner
that auto-selects the currently running document when the batch document
index changes. Includes state tracking refs for detecting batch start
and document transitions.
…RunMaestro#347)

- Add autoFollowEnabled prop to AutoRunProps interface
- Guard both focus-stealing useEffects (mode change + document selection)
  to skip .focus() when autoFollowEnabled && batchRunState.isRunning
- Add useEffect that scrolls to first unchecked checkbox in preview mode
  using scrollIntoView (focus-safe) with 150ms render delay
- Pass autoFollowEnabled through RightPanel autoRunSharedProps
- Add autoFollowEnabled to React.memo comparison function
…start (RunMaestro#347)

When auto-follow is enabled and a batch run starts, automatically:
- Switch the Right Bar to the Auto Run tab
- Open the right panel if it was closed
- Switch to preview mode if currently in edit mode

This only triggers on batch START (not on subsequent document transitions),
so users can freely switch tabs mid-run without being overridden.
…unMaestro#347)

Move auto-follow state, refs, and useEffect from RightPanel.tsx into a
dedicated hook for testability. Add 8 test cases covering document
auto-selection, tab switching, panel opening, and ref reset behavior.
@coderabbitai
Copy link

coderabbitai bot commented Mar 5, 2026

📝 Walkthrough

Walkthrough

Adds an opt-in "auto-follow" feature: a new hook detects batch start/document changes and, when enabled, auto-selects the active document, opens/switches the right panel to the Auto Run tab, and coordinates mode/scroll/focus behavior across AutoRun, RightPanel and the UI store.

Changes

Cohort / File(s) Summary
Auto-follow Hook
src/renderer/hooks/batch/useAutoRunAutoFollow.ts, src/renderer/hooks/batch/index.ts
New useAutoRunAutoFollow hook and types; detects batch start/end and document changes using refs; triggers callbacks (onAutoRunSelectDocument, setActiveRightTab, setRightPanelOpen, mode transitions) when enabled; exported from batch index.
UI Store
src/renderer/stores/uiStore.ts
Adds autoFollowEnabled boolean state and setAutoFollowEnabled action to central UI store.
Right Panel Integration
src/renderer/components/RightPanel.tsx
Wires the hook into RightPanel, exposes autoFollowEnabled/setter to downstream components, and adds a "Follow active task" checkbox to toggle the feature.
AutoRun Component
src/renderer/components/AutoRun.tsx
Adds optional autoFollowEnabled prop; suppresses automatic focus when auto-follow is enabled during runs and implements auto-scroll-to-first-unchecked-task in preview when running.
Batch Runner Modal
src/renderer/components/BatchRunnerModal.tsx
Reads/writes autoFollowEnabled from UI store; adds an inline auto-follow toggle and adjusts header/footer layout to include the control and hint.
Tests
src/__tests__/renderer/hooks/useAutoRunAutoFollow.test.ts
Comprehensive test suite covering enable/disable, batch start/end, document index changes, tab switching, panel opening, and state reset; includes factories and mocked callbacks.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant RightPanel
    participant Hook as useAutoRunAutoFollow
    participant AutoRun
    participant Batch as BatchState

    User->>RightPanel: Toggle "Follow active task" on
    RightPanel->>Hook: setAutoFollowEnabled(true)
    Hook->>Hook: update autoFollowEnabled

    Note over Batch,Hook: Batch starts (isRunning -> true)
    Batch->>Hook: currentDocumentIndex / isRunning update
    Hook->>Hook: detect batch start via refs

    alt autoFollowEnabled && batch started
        Hook->>RightPanel: setActiveRightTab("autorun")
        Hook->>RightPanel: setRightPanelOpen(true)
        Hook->>AutoRun: request mode -> "preview"
        Hook->>AutoRun: onAutoRunSelectDocument(activeDoc)
        AutoRun->>AutoRun: update selectedFile & scroll to first unchecked task
    end

    Note over Batch,Hook: Document changes while running
    Batch->>Hook: currentDocumentIndex changes
    alt autoFollowEnabled && doc changed
        Hook->>AutoRun: onAutoRunSelectDocument(newActiveDoc)
        AutoRun->>AutoRun: update selectedFile
    end

    Note over Batch,Hook: Batch ends then new batch starts
    Batch->>Hook: isRunning false -> refs reset -> isRunning true
    Hook->>Hook: re-trigger auto-selection for new batch
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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 Title clearly and concisely summarizes the main change: adding auto-follow functionality for active documents in the Auto Run sidebar with issue reference.
Linked Issues check ✅ Passed Pull request fully implements all coding objectives from issue #347: auto-follow hook, document selection sync, tab switching, panel opening, opt-in toggle, scroll without focus theft, and comprehensive tests.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing the auto-follow feature; no unrelated modifications or scope creep detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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 and usage tips.

@greptile-apps
Copy link

greptile-apps bot commented Mar 5, 2026

Greptile Summary

This PR adds a "Follow active task" toggle to the Auto Run sidebar that automatically tracks the currently running document during batch runs — selecting the active document, switching to preview mode, opening the right panel, and scrolling to the first unchecked task. The implementation is cleanly extracted into a dedicated useAutoRunAutoFollow hook with solid test coverage.

Key issues found:

  • State divergence in BatchRunnerModal: The modal initialises autoFollowEnabled from the store via useState(autoFollowFromStore) (a one-time snapshot), but the local state is never re-synced if the store changes (e.g., via the RightPanel toggle during a run). Clicking "Go" then writes the stale local value back to the store via setAutoFollowStore(autoFollowEnabled), silently overwriting whatever the user last set in the sidebar.
  • Hardcoded 150 ms scroll delay: The scrollIntoView effect in AutoRun.tsx fires 150 ms after currentDocumentIndex changes. For large documents or slower machines, the new content may not be fully rendered by then, causing the scroll to target stale or missing checkboxes.
  • Two independent UIs for the same setting: The BatchRunnerModal checkbox only writes to the store on "Go", while the RightPanel checkbox writes immediately. These asymmetric update paths are the root cause of the divergence issue above.

Confidence Score: 3/5

  • Mostly safe to merge — the feature is well-structured and tested, but the stale-state overwrite in BatchRunnerModal is a real correctness issue worth fixing before the next release.
  • The core hook logic is correct and well-tested, the focus-guard approach is sound, and the store addition is clean. The score is held back by the BatchRunnerModal local-state pattern that can cause the "Follow active task" preference set in the RightPanel to be silently overwritten the next time the user clicks "Go".
  • src/renderer/components/BatchRunnerModal.tsx — the local auto-follow state is never re-synced from the store after mount, creating a one-way data flow that can overwrite the user's in-run preference.

Important Files Changed

Filename Overview
src/renderer/hooks/batch/useAutoRunAutoFollow.ts New hook encapsulating auto-follow logic — correctly guards auto-select on isRunning, uses refs to track transitions, and the setAutoFollowEnabled callback avoids double-firing by keeping prevBatchDocIndexRef current even when disabled. Minor concern: many unstable dependencies (callbacks, rightPanelOpen, currentMode) in the effect array can cause unintended re-runs.
src/renderer/components/BatchRunnerModal.tsx Introduces a local copy of autoFollowEnabled initialized from the store but never re-synced — clicking "Go" can silently overwrite a more-recent in-run RightPanel toggle change with a stale modal value.
src/renderer/components/AutoRun.tsx Focus guards and scroll-to-task effect are well-structured; the 150 ms hardcoded delay in the scroll effect is a potential timing issue if document content loads slowly, but degrades gracefully (no crash, just missed scroll).
src/renderer/components/RightPanel.tsx Clean hook integration and checkbox toggle addition; autoFollowEnabled is correctly threaded through to AutoRun via shared props.
src/tests/renderer/hooks/useAutoRunAutoFollow.test.ts Comprehensive 8-case test suite using renderHook; covers all documented scenarios including ref reset and edge cases.

Sequence Diagram

sequenceDiagram
    participant User
    participant BatchRunnerModal
    participant UIStore
    participant useAutoRunAutoFollow
    participant RightPanel
    participant AutoRun

    User->>BatchRunnerModal: Check "Follow active task"
    Note over BatchRunnerModal: Updates local state only
    User->>BatchRunnerModal: Click "Go"
    BatchRunnerModal->>UIStore: setAutoFollowEnabled(true)
    BatchRunnerModal->>BatchRunnerModal: Start batch run

    loop Batch running
        BatchRunnerModal-->>useAutoRunAutoFollow: currentSessionBatchState changes
        useAutoRunAutoFollow->>UIStore: reads autoFollowEnabled
        useAutoRunAutoFollow->>RightPanel: onAutoRunSelectDocument(activeDoc)
        useAutoRunAutoFollow->>RightPanel: setActiveRightTab("autorun")
        useAutoRunAutoFollow->>RightPanel: setRightPanelOpen(true)
        useAutoRunAutoFollow->>RightPanel: onAutoRunModeChange("preview")
        RightPanel->>AutoRun: autoFollowEnabled=true prop
        AutoRun->>AutoRun: skip focus() calls
        AutoRun->>AutoRun: scrollIntoView first unchecked checkbox
    end

    User->>RightPanel: Toggle "Follow active task" off
    RightPanel->>UIStore: setAutoFollowEnabled(false) [immediate]
    Note over BatchRunnerModal: Local state still = true (diverged)
    User->>BatchRunnerModal: Click "Go" again
    BatchRunnerModal->>UIStore: setAutoFollowEnabled(true) [overwrites!]
Loading

Last reviewed commit: 4387ecf

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
src/renderer/hooks/batch/useAutoRunAutoFollow.ts (1)

4-14: Unused toggleRightPanel in interface.

The toggleRightPanel property is defined in UseAutoRunAutoFollowDeps but is never used within the hook. Only setRightPanelOpen is called (line 60). Consider removing toggleRightPanel from the interface to avoid confusion, or document why it's included for future use.

♻️ Suggested fix
 export interface UseAutoRunAutoFollowDeps {
 	currentSessionBatchState: BatchRunState | null | undefined;
 	onAutoRunSelectDocument: (filename: string) => void | Promise<void>;
 	selectedFile: string | null;
 	setActiveRightTab: (tab: RightPanelTab) => void;
 	rightPanelOpen: boolean;
 	setRightPanelOpen?: (open: boolean) => void;
-	toggleRightPanel?: () => void;
 	onAutoRunModeChange?: (mode: 'edit' | 'preview') => void;
 	currentMode?: 'edit' | 'preview';
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/renderer/hooks/batch/useAutoRunAutoFollow.ts` around lines 4 - 14, The
interface property toggleRightPanel in UseAutoRunAutoFollowDeps is unused in the
useAutoRunAutoFollow hook; remove toggleRightPanel from the
UseAutoRunAutoFollowDeps interface and any related type references, leaving
setRightPanelOpen as the single API used by the hook (update callers that pass
toggleRightPanel to stop passing it or map it to setRightPanelOpen), and run
type checks to ensure no remaining references to toggleRightPanel remain in the
codebase.
src/renderer/components/AutoRun.tsx (1)

981-1007: Consider adding a guard for empty preview content.

The scroll-to-task effect works well, but if previewRef.current exists but has no checkboxes (e.g., document has no tasks), the loop exits harmlessly. However, consider whether scrolling behavior should also be guarded against rapid re-triggers when localContent changes during the batch.

Currently the effect doesn't depend on localContent, so it won't re-run when content updates mid-task. This may cause the scroll position to become stale if the agent checks off multiple tasks quickly before the next currentTaskIndex update. This is a minor edge case and the current approach is reasonable for the initial implementation.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/renderer/components/AutoRun.tsx` around lines 981 - 1007, The effect
should early-return if preview has no checkboxes and should re-run when preview
content changes; update the useEffect body to check after previewRef.current is
defined that querySelectorAll('input[type="checkbox"]') yields length > 0 and
return early if zero, and add the relevant content state (e.g., localContent or
whatever holds the preview text) to the dependency array alongside
batchRunState, autoFollowEnabled, and mode so the scroll logic in AutoRun
(useEffect using previewRef, autoFollowEnabled, batchRunState, mode) retriggers
when the preview updates.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/renderer/components/AutoRun.tsx`:
- Around line 981-1007: The effect should early-return if preview has no
checkboxes and should re-run when preview content changes; update the useEffect
body to check after previewRef.current is defined that
querySelectorAll('input[type="checkbox"]') yields length > 0 and return early if
zero, and add the relevant content state (e.g., localContent or whatever holds
the preview text) to the dependency array alongside batchRunState,
autoFollowEnabled, and mode so the scroll logic in AutoRun (useEffect using
previewRef, autoFollowEnabled, batchRunState, mode) retriggers when the preview
updates.

In `@src/renderer/hooks/batch/useAutoRunAutoFollow.ts`:
- Around line 4-14: The interface property toggleRightPanel in
UseAutoRunAutoFollowDeps is unused in the useAutoRunAutoFollow hook; remove
toggleRightPanel from the UseAutoRunAutoFollowDeps interface and any related
type references, leaving setRightPanelOpen as the single API used by the hook
(update callers that pass toggleRightPanel to stop passing it or map it to
setRightPanelOpen), and run type checks to ensure no remaining references to
toggleRightPanel remain in the codebase.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 55e379b0-8ca4-4ba2-ada8-b5123f9ff42b

📥 Commits

Reviewing files that changed from the base of the PR and between 3b9a142 and 02581e4.

📒 Files selected for processing (5)
  • src/__tests__/renderer/hooks/useAutoRunAutoFollow.test.ts
  • src/renderer/components/AutoRun.tsx
  • src/renderer/components/RightPanel.tsx
  • src/renderer/hooks/batch/index.ts
  • src/renderer/hooks/batch/useAutoRunAutoFollow.ts

@kianhub kianhub marked this pull request as draft March 5, 2026 17:30
kianhub added 2 commits March 5, 2026 12:35
…tro#347)

- Lift autoFollowEnabled state from local useState to zustand uiStore
- Add checkbox in BatchRunnerModal footer, applied on Go
- Immediately jump to active task when toggling on during a running batch
…Panel (RunMaestro#347)

- Gate auto-select on isRunning to prevent spurious document navigation
  when toggling auto-follow after a batch ends
- Remove unused toggleRightPanel from UseAutoRunAutoFollowDeps interface
- Early-return in scroll-to-task effect when preview has no checkboxes
@kianhub kianhub marked this pull request as ready for review March 5, 2026 20:13
Copy link

@coderabbitai coderabbitai bot left a comment

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/__tests__/renderer/hooks/useAutoRunAutoFollow.test.ts (1)

68-99: Add one test for enabling auto-follow during an already-running batch.

Current tests mostly enable before transition-to-running. A direct assertion for the setter’s immediate path would lock in the new runtime behavior.

Suggested test case
+	it('should immediately jump to active document when enabling during a running batch', () => {
+		const onAutoRunSelectDocument = vi.fn();
+		const setActiveRightTab = vi.fn();
+		const setRightPanelOpen = vi.fn();
+		const deps = createDeps({
+			onAutoRunSelectDocument,
+			setActiveRightTab,
+			rightPanelOpen: false,
+			setRightPanelOpen,
+			currentMode: 'edit',
+			currentSessionBatchState: createBatchState({
+				isRunning: true,
+				documents: ['doc-a', 'doc-b'],
+				currentDocumentIndex: 1,
+			}),
+		});
+
+		const { result } = renderHook((props: UseAutoRunAutoFollowDeps) => useAutoRunAutoFollow(props), {
+			initialProps: deps,
+		});
+
+		act(() => {
+			result.current.setAutoFollowEnabled(true);
+		});
+
+		expect(onAutoRunSelectDocument).toHaveBeenCalledWith('doc-b');
+		expect(setActiveRightTab).toHaveBeenCalledWith('autorun');
+		expect(setRightPanelOpen).toHaveBeenCalledWith(true);
+	});

Also applies to: 100-135, 170-200, 229-261

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/__tests__/renderer/hooks/useAutoRunAutoFollow.test.ts` around lines 68 -
99, Add a test in the useAutoRunAutoFollow suite that verifies enabling
auto-follow while a batch is already running triggers immediate selection:
render the hook with deps where currentSessionBatchState represents a running
batch (use createBatchState with isRunning: true, documents: ['doc-a','doc-b'],
currentDocumentIndex: 0) and a spy for onAutoRunSelectDocument, then call
result.current.setAutoFollowEnabled(true) and assert onAutoRunSelectDocument was
called with 'doc-a'; reference the hook useAutoRunAutoFollow, the setter
setAutoFollowEnabled, and the callback onAutoRunSelectDocument so the test
exercises the immediate-path behavior when enabling auto-follow mid-run.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/renderer/components/BatchRunnerModal.tsx`:
- Around line 104-108: The local autoFollowEnabled state in BatchRunnerModal
(variables autoFollowEnabled and setAutoFollowEnabled) is initialized once from
useUIStore (autoFollowFromStore) and can become stale; remove the local state
and read/write directly from the store (useUIStore(autoFollowEnabled) and
setAutoFollowStore) or, if a local editable copy is needed, keep it synced by
adding a useEffect that updates setAutoFollowEnabled whenever
autoFollowFromStore changes and ensure the save handler (the "Go"/save action
that currently reads autoFollowEnabled) calls setAutoFollowStore with the latest
autoFollowFromStore (or the synced local value) instead of blindly persisting
the originally captured local state; update references in the component
(initialization and the save handler) to use the store-backed value or the
effect-synced local copy.

---

Nitpick comments:
In `@src/__tests__/renderer/hooks/useAutoRunAutoFollow.test.ts`:
- Around line 68-99: Add a test in the useAutoRunAutoFollow suite that verifies
enabling auto-follow while a batch is already running triggers immediate
selection: render the hook with deps where currentSessionBatchState represents a
running batch (use createBatchState with isRunning: true, documents:
['doc-a','doc-b'], currentDocumentIndex: 0) and a spy for
onAutoRunSelectDocument, then call result.current.setAutoFollowEnabled(true) and
assert onAutoRunSelectDocument was called with 'doc-a'; reference the hook
useAutoRunAutoFollow, the setter setAutoFollowEnabled, and the callback
onAutoRunSelectDocument so the test exercises the immediate-path behavior when
enabling auto-follow mid-run.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9d2e920b-be39-466e-8c63-f46ddc7ed3d4

📥 Commits

Reviewing files that changed from the base of the PR and between 02581e4 and 4387ecf.

📒 Files selected for processing (5)
  • src/__tests__/renderer/hooks/useAutoRunAutoFollow.test.ts
  • src/renderer/components/AutoRun.tsx
  • src/renderer/components/BatchRunnerModal.tsx
  • src/renderer/hooks/batch/useAutoRunAutoFollow.ts
  • src/renderer/stores/uiStore.ts

@kianhub kianhub requested a review from pedramamini March 5, 2026 20:29
@kianhub
Copy link
Contributor Author

kianhub commented Mar 5, 2026

ready for review, it's working well on my end @pedramamini

@kianhub
Copy link
Contributor Author

kianhub commented Mar 5, 2026

fixing new annotations

- Remove local autoFollowEnabled state in BatchRunnerModal to prevent
  stale overwrite of store value on Go action
- Wrap scroll-to-task setTimeout with requestAnimationFrame for more
  reliable DOM targeting after React render
- Add test for enabling auto-follow during an already-running batch
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/renderer/components/AutoRun.tsx`:
- Around line 945-954: The effect in AutoRun.tsx re-focuses on the batchRunState
true->false transition because batchRunState?.isRunning is in the dependency
array; remove batchRunState?.isRunning from this effect’s dependencies and
instead read the run state from a ref updated by a separate useEffect so the
focus effect only runs on mode or autoFollowEnabled changes; keep the same guard
(if (autoFollowEnabled && isRunningRef.current) return) and continue to focus
textareaRef or previewRef based on mode.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: fb56e78c-95c1-483b-90c0-4a47bf78e5b3

📥 Commits

Reviewing files that changed from the base of the PR and between 4387ecf and 2884790.

📒 Files selected for processing (3)
  • src/__tests__/renderer/hooks/useAutoRunAutoFollow.test.ts
  • src/renderer/components/AutoRun.tsx
  • src/renderer/components/BatchRunnerModal.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/renderer/components/BatchRunnerModal.tsx
  • src/tests/renderer/hooks/useAutoRunAutoFollow.test.ts

Comment on lines 945 to +954
useEffect(() => {
// Skip focus when auto-follow is driving changes during a batch run
if (autoFollowEnabled && batchRunState?.isRunning) return;

if (mode === 'edit' && textareaRef.current) {
textareaRef.current.focus();
} else if (mode === 'preview' && previewRef.current) {
previewRef.current.focus();
}
}, [mode]);
}, [mode, autoFollowEnabled, batchRunState?.isRunning]);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Avoid re-focusing the sidebar when the batch stops.

Adding batchRunState?.isRunning to this effect’s dependencies makes it run again on the true -> false transition. With auto-follow enabled, that focuses the preview/editor at batch completion even when mode did not change, which pulls keyboard focus back into Auto Run and breaks the “don’t steal focus” guarantee.

Suggested fix
+	const suppressAutoFocusRef = useRef(false);
+	suppressAutoFocusRef.current = !!autoFollowEnabled && !!batchRunState?.isRunning;
+
 	// Auto-focus the active element after mode change
 	useEffect(() => {
-		// Skip focus when auto-follow is driving changes during a batch run
-		if (autoFollowEnabled && batchRunState?.isRunning) return;
+		// Skip focus when auto-follow is driving changes during a batch run
+		if (suppressAutoFocusRef.current) return;
 
 		if (mode === 'edit' && textareaRef.current) {
 			textareaRef.current.focus();
 		} else if (mode === 'preview' && previewRef.current) {
 			previewRef.current.focus();
 		}
-	}, [mode, autoFollowEnabled, batchRunState?.isRunning]);
+	}, [mode]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
useEffect(() => {
// Skip focus when auto-follow is driving changes during a batch run
if (autoFollowEnabled && batchRunState?.isRunning) return;
if (mode === 'edit' && textareaRef.current) {
textareaRef.current.focus();
} else if (mode === 'preview' && previewRef.current) {
previewRef.current.focus();
}
}, [mode]);
}, [mode, autoFollowEnabled, batchRunState?.isRunning]);
const suppressAutoFocusRef = useRef(false);
suppressAutoFocusRef.current = !!autoFollowEnabled && !!batchRunState?.isRunning;
// Auto-focus the active element after mode change
useEffect(() => {
// Skip focus when auto-follow is driving changes during a batch run
if (suppressAutoFocusRef.current) return;
if (mode === 'edit' && textareaRef.current) {
textareaRef.current.focus();
} else if (mode === 'preview' && previewRef.current) {
previewRef.current.focus();
}
}, [mode]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/renderer/components/AutoRun.tsx` around lines 945 - 954, The effect in
AutoRun.tsx re-focuses on the batchRunState true->false transition because
batchRunState?.isRunning is in the dependency array; remove
batchRunState?.isRunning from this effect’s dependencies and instead read the
run state from a ref updated by a separate useEffect so the focus effect only
runs on mode or autoFollowEnabled changes; keep the same guard (if
(autoFollowEnabled && isRunningRef.current) return) and continue to focus
textareaRef or previewRef based on mode.

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.

Auto-run sidebar should auto-focus the currently running playbook/document

1 participant