Skip to content

refactor: consolidate createMockSession test factories (Phase 03A)#815

Merged
reachrazamair merged 2 commits intoRunMaestro:rcfrom
jSydorowicz21:dedup/phase-03a-mock-session-factory
Apr 16, 2026
Merged

refactor: consolidate createMockSession test factories (Phase 03A)#815
reachrazamair merged 2 commits intoRunMaestro:rcfrom
jSydorowicz21:dedup/phase-03a-mock-session-factory

Conversation

@jSydorowicz21
Copy link
Copy Markdown
Contributor

@jSydorowicz21 jSydorowicz21 commented Apr 12, 2026

Summary

Test-only change. Zero production risk.

Introduces a shared createMockSession factory at src/__tests__/helpers/mockSession.ts and replaces per-file duplicate definitions across the renderer and integration test suites.

Net: -1,122 lines across 64 files

  • 60 test files now import from the shared helper
  • 7 files skipped (different Session types - broadcastService uses SessionBroadcastData, cue uses SessionInfo, web/mobile uses its own Session, RenameSessionModal has Session[] signature)
  • Files that need pre-populated overrides use createMockSession as baseCreateMockSession + thin wrapper

Test plan

  • npm run lint passes clean
  • npm run test - session-related tests pass (baseline flakes acceptable)

Risk

Zero - no production code changes.

Summary by CodeRabbit

  • Tests
    • Centralized mock session factory across the test suite, replacing many inline test fixtures to reduce duplication and harmonize test data setup, improving test consistency and maintainability.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 12, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 51795ca8-1c31-4af9-9059-3faf49d09dad

📥 Commits

Reviewing files that changed from the base of the PR and between 5695349 and b775d23.

📒 Files selected for processing (2)
  • src/__tests__/renderer/hooks/useMergeTransferHandlers.test.ts
  • src/__tests__/renderer/hooks/useModalHandlers.test.ts
✅ Files skipped from review due to trivial changes (1)
  • src/tests/renderer/hooks/useMergeTransferHandlers.test.ts

📝 Walkthrough

Walkthrough

This PR adds a shared test factory createMockSession (in src/__tests__/helpers/mockSession.ts) and re-exports it from the helpers barrel. ~50 test files are refactored to delegate their local createMockSession helpers to this shared factory, passing small test-specific overrides.

Changes

Cohort / File(s) Summary
Shared Test Helper
src/__tests__/helpers/mockSession.ts, src/__tests__/helpers/index.ts
Added createMockSession(overrides?: Partial<Session>): Session and re-exported it from the helpers barrel.
Integration Tests
src/__tests__/integration/AutoRunRightPanel.test.tsx, src/__tests__/integration/AutoRunSessionList.test.tsx
Replaced inline session factories with thin wrappers calling the shared helper and overriding auto-run/session fields.
Component Tests (Modals & Panels)
src/__tests__/renderer/components/... (many files, e.g., AppAgentModals.test.tsx, AppConfirmModals.test.tsx, FileExplorerPanel.test.tsx, MergeSessionModal.test.tsx, PromptComposerModal.test.tsx, QuickActionsModal.test.tsx, SendToAgentModal.test.tsx, SessionList.test.tsx, etc.)
Switched local createMockSession implementations to wrappers that call the shared factory, retaining only test-specific overrides and seeding (e.g., aiTabs, cwd, paths).
Hook Tests (various)
src/__tests__/renderer/hooks/... (many files, e.g., useActiveSession.test.ts, useAgentExecution.test.ts, useAutoRunHandlers.test.ts, useBatchHandlers.test.ts, useFileExplorerEffects.test.ts, useMergeTransferHandlers*.test.ts, useRemoteHandlers*.test.ts, useSessionLifecycle.test.ts, etc.)
Replaced inline session mocks with calls to the centralized helper; most tests now provide a small override object and rely on shared defaults.
Store & Utility Tests
src/__tests__/renderer/stores/..., src/__tests__/renderer/utils/... (e.g., agentStore.test.ts, sessionStore.test.ts, tabStore.test.ts, contextExtractor.test.ts, sessionValidation.test.ts, tabHelpers.test.ts, terminalTabHelpers.test.ts)
Removed local session factories and use the shared createMockSession for session fixtures; preserved existing test logic and assertions.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • reachrazamair

Poem

🐰 I stitched the mocks into one cozy nest,
Defaults in a helper make tests feel blessed,
No more copy-paste hopping from file to file,
One call to createMockSession—now that's worth a smile! 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'refactor: consolidate createMockSession test factories (Phase 03A)' accurately summarizes the PR's primary change: consolidating duplicate test factory definitions into a shared helper across 60+ test files.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit 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 and usage tips.

@jSydorowicz21 jSydorowicz21 force-pushed the dedup/phase-03a-mock-session-factory branch from 663e7fc to 6f56900 Compare April 13, 2026 19:27
@jSydorowicz21 jSydorowicz21 self-assigned this Apr 14, 2026
@jSydorowicz21 jSydorowicz21 marked this pull request as ready for review April 14, 2026 04:35
Copy link
Copy Markdown

@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 (5)
src/__tests__/helpers/mockSession.ts (1)

54-54: Strengthen type safety by removing the as Session assertion.

The type assertion bypasses compile-time checking for required fields. Using a typed variable instead—consistent with similar factories in src/__tests__/main/cue/cue-test-helpers.ts—ensures TypeScript catches missing fields if the Session interface evolves.

♻️ Proposed refactor
export function createMockSession(overrides: Partial<Session> = {}): Session {
-	return {
+	const session: Session = {
 		id: 'session-1',
 		name: 'Test Session',
 		toolType: 'claude-code',
 		state: 'idle',
 		cwd: '/test/project',
 		fullPath: '/test/project',
 		projectRoot: '/test/project',
 		createdAt: 0,
 		aiLogs: [],
 		shellLogs: [],
 		workLog: [],
 		contextUsage: 0,
 		inputMode: 'ai',
 		aiPid: 0,
 		terminalPid: 0,
 		port: 0,
 		isLive: false,
 		changedFiles: [],
 		isGitRepo: false,
 		fileTree: [],
 		fileExplorerExpanded: [],
 		fileExplorerScrollPos: 0,
 		executionQueue: [],
 		activeTimeMs: 0,
 		aiTabs: [],
 		activeTabId: '',
 		closedTabHistory: [],
 		filePreviewTabs: [],
 		activeFileTabId: null,
 		browserTabs: [],
 		activeBrowserTabId: null,
 		terminalTabs: [],
 		activeTerminalTabId: null,
 		unifiedTabOrder: [],
 		unifiedClosedTabHistory: [],
 		...overrides,
-	} as Session;
+	};
+	return session;
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/__tests__/helpers/mockSession.ts` at line 54, Remove the unsafe "as
Session" assertion and instead declare the created mock with the Session type so
the compiler enforces required fields; locate the factory that ends with " } as
Session;" in src/__tests__/helpers/mockSession.ts (the mock session creation
function/variable) and change it to a properly typed variable (e.g., const
mockSession: Session = { ... }) and add any missing required properties to match
the Session interface, mirroring the pattern used in
src/__tests__/main/cue/cue-test-helpers.ts.
src/__tests__/renderer/components/PromptComposerModal.test.tsx (1)

1149-1156: Remove as any from the wrapper to keep test types strict.

The wrapper can stay thin without escaping types by constraining toolType to Session['toolType'].

♻️ Proposed refactor
 		function createMockSession(
 			id: string,
 			name: string,
-			toolType: string = 'claude-code'
+			toolType: Session['toolType'] = 'claude-code'
 		): Session {
-			return baseCreateMockSession({ id, name, toolType: toolType as any });
+			return baseCreateMockSession({ id, name, toolType });
 		}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/__tests__/renderer/components/PromptComposerModal.test.tsx` around lines
1149 - 1156, The wrapper createMockSession currently casts toolType to any;
change the parameter type to Session['toolType'] and pass it directly to
baseCreateMockSession so you remove the unsafe "as any" cast—update the function
signature (createMockSession) to use toolType: Session['toolType'] and forward
that value into baseCreateMockSession({ id, name, toolType }) without casting.
src/__tests__/renderer/components/AgentSessionsModal.test.tsx (1)

56-56: Optional cleanup: remove redundant helper note comment.

The import on Line 5 already makes this clear, so this comment can be dropped to reduce noise.

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

In `@src/__tests__/renderer/components/AgentSessionsModal.test.tsx` at line 56,
Remove the redundant inline comment noting "// createMockSession imported from
shared helper" in the AgentSessionsModal test file; simply delete that comment
near the top of src/__tests__/renderer/components/AgentSessionsModal.test.tsx
(where createMockSession is imported) to reduce noise without changing imports
or test behavior.
src/__tests__/renderer/hooks/useMergeSession.test.ts (1)

114-122: Guard against empty tabs arrays in the helper.

Line 121 can throw if tabs is passed as []. A small guard keeps this helper robust for future test cases.

Proposed tweak
-	const resolvedTabs = tabs || [defaultTab];
+	const resolvedTabs = tabs?.length ? tabs : [defaultTab];
 	return baseCreateMockSession({
 		id,
 		name: `Session ${id}`,
 		toolType,
 		state,
 		aiTabs: resolvedTabs,
 		activeTabId: resolvedTabs[0].id,
 	});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/__tests__/renderer/hooks/useMergeSession.test.ts` around lines 114 - 122,
The helper currently sets resolvedTabs = tabs || [defaultTab] and then uses
resolvedTabs[0].id for activeTabId, which will throw when tabs is an empty
array; change the guard to treat empty arrays like undefined (e.g., compute
resolvedTabs = (tabs && tabs.length) ? tabs : [defaultTab]) and derive
activeTabId from resolvedTabs[0].id so baseCreateMockSession receives a
non-empty aiTabs and a valid activeTabId; update the lines around resolvedTabs,
aiTabs, and activeTabId accordingly (references: resolvedTabs, defaultTab,
baseCreateMockSession, activeTabId).
src/__tests__/integration/AutoRunSessionList.test.tsx (1)

229-240: Avoid aiTabs as any in test fixtures for better type safety.

Line 239 uses a cast that suppresses TypeScript checking for the AITab shape. The fixture is missing required fields: agentSessionId, starred, inputValue, stagedImages, createdAt, and state. Even though the test may pass, a future change to the AITab interface could silently break this fixture.

♻️ Suggested refactor
 const createMockSession = (overrides: Partial<Session> = {}): Session =>
 	baseCreateMockSession({
 		id: 'test-session-1',
 		name: 'Test Session 1',
 		cwd: '/test/path',
 		fullPath: '/test/path',
 		projectRoot: '/test/path',
 		isGitRepo: true,
 		aiPid: 1234,
 		terminalPid: 5678,
 		port: 3000,
-		aiTabs: [{ id: 'tab-1', name: 'Tab 1', logs: [] }] as any,
+		aiTabs: [
+			{
+				id: 'tab-1',
+				agentSessionId: null,
+				name: 'Tab 1',
+				starred: false,
+				logs: [],
+				inputValue: '',
+				stagedImages: [],
+				createdAt: Date.now(),
+				state: 'idle' as const,
+			},
+		],
 		activeTabId: 'tab-1',
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/__tests__/integration/AutoRunSessionList.test.tsx` around lines 229 -
240, Replace the unsafe cast in the test fixture by providing a properly typed
AITab object instead of using "aiTabs as any": update the aiTabs passed to
baseCreateMockSession to include the missing AITab fields (agentSessionId,
starred, inputValue, stagedImages, createdAt, state) and any expected defaults
(e.g., empty arrays/strings/false/ISO date) so the object matches the AITab
interface; locate the aiTabs property in the call to baseCreateMockSession (the
entry with id 'tab-1') and expand that single tab to a full AITab-shaped object
(or call a test helper like createMockAITab if available) to restore type
safety.
🤖 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/__tests__/helpers/mockSession.ts`:
- Line 54: Remove the unsafe "as Session" assertion and instead declare the
created mock with the Session type so the compiler enforces required fields;
locate the factory that ends with " } as Session;" in
src/__tests__/helpers/mockSession.ts (the mock session creation
function/variable) and change it to a properly typed variable (e.g., const
mockSession: Session = { ... }) and add any missing required properties to match
the Session interface, mirroring the pattern used in
src/__tests__/main/cue/cue-test-helpers.ts.

In `@src/__tests__/integration/AutoRunSessionList.test.tsx`:
- Around line 229-240: Replace the unsafe cast in the test fixture by providing
a properly typed AITab object instead of using "aiTabs as any": update the
aiTabs passed to baseCreateMockSession to include the missing AITab fields
(agentSessionId, starred, inputValue, stagedImages, createdAt, state) and any
expected defaults (e.g., empty arrays/strings/false/ISO date) so the object
matches the AITab interface; locate the aiTabs property in the call to
baseCreateMockSession (the entry with id 'tab-1') and expand that single tab to
a full AITab-shaped object (or call a test helper like createMockAITab if
available) to restore type safety.

In `@src/__tests__/renderer/components/AgentSessionsModal.test.tsx`:
- Line 56: Remove the redundant inline comment noting "// createMockSession
imported from shared helper" in the AgentSessionsModal test file; simply delete
that comment near the top of
src/__tests__/renderer/components/AgentSessionsModal.test.tsx (where
createMockSession is imported) to reduce noise without changing imports or test
behavior.

In `@src/__tests__/renderer/components/PromptComposerModal.test.tsx`:
- Around line 1149-1156: The wrapper createMockSession currently casts toolType
to any; change the parameter type to Session['toolType'] and pass it directly to
baseCreateMockSession so you remove the unsafe "as any" cast—update the function
signature (createMockSession) to use toolType: Session['toolType'] and forward
that value into baseCreateMockSession({ id, name, toolType }) without casting.

In `@src/__tests__/renderer/hooks/useMergeSession.test.ts`:
- Around line 114-122: The helper currently sets resolvedTabs = tabs ||
[defaultTab] and then uses resolvedTabs[0].id for activeTabId, which will throw
when tabs is an empty array; change the guard to treat empty arrays like
undefined (e.g., compute resolvedTabs = (tabs && tabs.length) ? tabs :
[defaultTab]) and derive activeTabId from resolvedTabs[0].id so
baseCreateMockSession receives a non-empty aiTabs and a valid activeTabId;
update the lines around resolvedTabs, aiTabs, and activeTabId accordingly
(references: resolvedTabs, defaultTab, baseCreateMockSession, activeTabId).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d48242d9-2285-43f0-9d0e-412a8f8c00c4

📥 Commits

Reviewing files that changed from the base of the PR and between b37cd16 and 6f56900.

📒 Files selected for processing (64)
  • src/__tests__/helpers/index.ts
  • src/__tests__/helpers/mockSession.ts
  • src/__tests__/integration/AutoRunRightPanel.test.tsx
  • src/__tests__/integration/AutoRunSessionList.test.tsx
  • src/__tests__/renderer/components/AgentSessionsModal.test.tsx
  • src/__tests__/renderer/components/AppAgentModals.test.tsx
  • src/__tests__/renderer/components/AppConfirmModals.test.tsx
  • src/__tests__/renderer/components/AppModals-selfSourced.test.tsx
  • src/__tests__/renderer/components/AppSessionModals.test.tsx
  • src/__tests__/renderer/components/AppWorktreeModals.test.tsx
  • src/__tests__/renderer/components/FileExplorerPanel.test.tsx
  • src/__tests__/renderer/components/GroupChatInput.test.tsx
  • src/__tests__/renderer/components/HistoryPanel.test.tsx
  • src/__tests__/renderer/components/InlineWizard/WizardInputPanel.test.tsx
  • src/__tests__/renderer/components/InputArea.test.tsx
  • src/__tests__/renderer/components/MergeSessionModal.test.tsx
  • src/__tests__/renderer/components/PromptComposerModal.test.tsx
  • src/__tests__/renderer/components/QuickActionsModal.test.tsx
  • src/__tests__/renderer/components/SendToAgentModal.test.tsx
  • src/__tests__/renderer/components/SessionItemCue.test.tsx
  • src/__tests__/renderer/components/SessionList.test.tsx
  • src/__tests__/renderer/components/ThinkingStatusPill.test.tsx
  • src/__tests__/renderer/components/WorktreeRunSection.test.tsx
  • src/__tests__/renderer/hooks/batch/useAutoRunHandlers.worktree.test.ts
  • src/__tests__/renderer/hooks/useActiveSession.test.ts
  • src/__tests__/renderer/hooks/useAgentExecution.test.ts
  • src/__tests__/renderer/hooks/useAgentListeners.test.ts
  • src/__tests__/renderer/hooks/useAgentSessionManagement.test.ts
  • src/__tests__/renderer/hooks/useAtMentionCompletion.test.ts
  • src/__tests__/renderer/hooks/useAutoRunAchievements.test.ts
  • src/__tests__/renderer/hooks/useAutoRunDocumentLoader.test.ts
  • src/__tests__/renderer/hooks/useAutoRunHandlers.test.ts
  • src/__tests__/renderer/hooks/useAvailableAgents.test.ts
  • src/__tests__/renderer/hooks/useBatchHandlers.test.ts
  • src/__tests__/renderer/hooks/useBatchProcessor.test.ts
  • src/__tests__/renderer/hooks/useFileExplorerEffects.test.ts
  • src/__tests__/renderer/hooks/useFileTreeManagement.test.ts
  • src/__tests__/renderer/hooks/useGitStatusPolling.test.ts
  • src/__tests__/renderer/hooks/useGroupManagement.test.ts
  • src/__tests__/renderer/hooks/useInputHandlers.test.ts
  • src/__tests__/renderer/hooks/useInputProcessing.test.ts
  • src/__tests__/renderer/hooks/useKeyboardNavigation.test.ts
  • src/__tests__/renderer/hooks/useMergeSession.test.ts
  • src/__tests__/renderer/hooks/useMergeTransferHandlers.test.ts
  • src/__tests__/renderer/hooks/useMergeTransferHandlers_stdin.test.ts
  • src/__tests__/renderer/hooks/useModalHandlers.test.ts
  • src/__tests__/renderer/hooks/useRemoteHandlers.test.ts
  • src/__tests__/renderer/hooks/useRemoteHandlers_stdin.test.ts
  • src/__tests__/renderer/hooks/useRemoteIntegration.test.ts
  • src/__tests__/renderer/hooks/useSendToAgent.test.ts
  • src/__tests__/renderer/hooks/useSessionLifecycle.test.ts
  • src/__tests__/renderer/hooks/useSessionRestoration.test.ts
  • src/__tests__/renderer/hooks/useSummarizeHandler.test.ts
  • src/__tests__/renderer/hooks/useTabCompletion.test.ts
  • src/__tests__/renderer/hooks/useTabExportHandlers.test.ts
  • src/__tests__/renderer/hooks/useTabHandlers.test.ts
  • src/__tests__/renderer/hooks/useWizardHandlers.test.ts
  • src/__tests__/renderer/stores/agentStore.test.ts
  • src/__tests__/renderer/stores/sessionStore.test.ts
  • src/__tests__/renderer/stores/tabStore.test.ts
  • src/__tests__/renderer/utils/contextExtractor.test.ts
  • src/__tests__/renderer/utils/sessionValidation.test.ts
  • src/__tests__/renderer/utils/tabHelpers.test.ts
  • src/__tests__/renderer/utils/terminalTabHelpers.test.ts

@greptile-apps
Copy link
Copy Markdown

greptile-apps bot commented Apr 14, 2026

Greptile Summary

This PR introduces a shared createMockSession factory at src/__tests__/helpers/mockSession.ts and migrates 60 test files away from their per-file duplicate definitions, removing ~1 122 lines of boilerplate. Files that need domain-specific defaults (pre-populated AI tabs, non-default IDs, etc.) keep a thin local wrapper that delegates to the canonical factory rather than duplicating defaults. No production code is touched.

Confidence Score: 5/5

  • Safe to merge — test-only change with zero production code impact.
  • The factory covers all required Session fields, the as Session cast is the correct pattern for a Partial-override factory, multi-session tests consistently override the id field to avoid collisions, and sampled migrations all follow the documented thin-wrapper convention. No production code was modified.
  • No files require special attention.

Important Files Changed

Filename Overview
src/tests/helpers/mockSession.ts New canonical Session factory covering all required interface fields; uses as Session cast (necessary due to Partial spread) and sensible hardcoded defaults. Clean implementation.
src/tests/helpers/index.ts Minimal barrel export for the new helpers directory; correctly re-exports createMockSession.
src/tests/renderer/utils/tabHelpers.test.ts Drops local factory entirely; all multi-session tests explicitly override id (e.g. { id: 'a' }, { id: 'b' }) — no ID collision risk.
src/tests/renderer/stores/sessionStore.test.ts Drops local factory; creates multiple sessions with explicit IDs throughout. Migration is correct.
src/tests/renderer/utils/contextExtractor.test.ts Uses thin wrapper to preserve the session-123 default ID that assertions rely on; correctly delegates to the base factory.
src/tests/renderer/components/SessionList.test.tsx Thin wrapper generates unique IDs via Math.random() — appropriate since SessionList tests create many sessions and need stable uniqueness.
src/tests/renderer/hooks/useAgentExecution.test.ts Thin wrapper pre-populates an AI tab so agent execution has a spawn target; correctly delegates remaining defaults to the shared factory.
src/tests/integration/AutoRunRightPanel.test.tsx Imports shared factory as baseCreateMockSession and wraps it locally; migration is correct and no logic changed.
src/tests/integration/AutoRunSessionList.test.tsx Same pattern as AutoRunRightPanel — wraps shared factory; migration correct.
src/tests/renderer/hooks/useSessionLifecycle.test.ts Thin wrapper adds groupId, aiTabs, and activeTabId defaults for lifecycle tests; clean delegation pattern.
src/tests/renderer/utils/terminalTabHelpers.test.ts Drops local factory; only uses single sessions per test so the hardcoded id: 'session-1' default is safe.
src/tests/renderer/hooks/useGroupManagement.test.ts Drops local factory; multi-session tests explicitly pass { id: 'session-1' } — redundant with the default but harmless and clear.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A["src/__tests__/helpers/mockSession.ts\n(canonical factory)"] --> B["src/__tests__/helpers/index.ts\n(barrel re-export)"]
    B --> C["12 test files\ndrop local factory,\nimport shared helper directly"]
    B --> D["48 test files\nretain thin local wrapper\n(delegates to baseCreateMockSession)"]
    D --> E["Pre-populated AI tabs\n(e.g. useAgentExecution)"]
    D --> F["Domain-specific defaults\n(e.g. contextExtractor: id='session-123')"]
    D --> G["Random unique IDs\n(e.g. SessionList: Math.random)"]
    C --> H["sessionStore, tabStore,\ntabHelpers, terminalTabHelpers,\nuseGroupManagement, etc."]
Loading

Reviews (1): Last reviewed commit: "chore: apply prettier formatting" | Re-trigger Greptile

@jSydorowicz21 jSydorowicz21 added refactor Clean-up needs ready to merge This PR is ready to merge labels Apr 15, 2026
Introduce shared `createMockSession` factory at
`src/__tests__/helpers/mockSession.ts` and replace per-file duplicates
across the renderer and integration test suites. Files that needed
pre-populated overrides now import `createMockSession as
baseCreateMockSession` and wrap a thin helper that delegates defaults to
the shared factory.

Scope
- Added: src/__tests__/helpers/mockSession.ts (canonical Session factory)
- Added: src/__tests__/helpers/index.ts (barrel export)
- Updated 60 test files to import from the shared helper
  - 48 files retained a thin local wrapper that delegates to
    baseCreateMockSession for domain-specific overrides
  - 12 files drop the local factory entirely and use the shared helper
    directly (e.g. tabStore, sessionStore, sessionValidation,
    terminalTabHelpers, tabHelpers, useFileTreeManagement,
    useGitStatusPolling, useGroupManagement, useModalHandlers,
    useTabCompletion, useTabHandlers, AgentSessionsModal,
    ThinkingStatusPill, contextExtractor)

Skipped (intentionally, different session type)
- src/__tests__/main/web-server/services/broadcastService.test.ts
  (uses SessionBroadcastData)
- src/__tests__/main/cue/cue-test-helpers.ts
- src/__tests__/main/cue/cue-executor.test.ts
  (both use SessionInfo from shared/types)
- src/__tests__/web/mobile/App.test.tsx
- src/__tests__/web/mobile/AllSessionsView.test.tsx
- src/__tests__/web/mobile/SessionPillBar.test.tsx
  (use Session type from web/hooks/useSessions)
- src/__tests__/renderer/components/RenameSessionModal.test.tsx
  (factory signature is createMockSessions returning Session[])

Verification
- npm run lint: clean
- Targeted vitest on all 62 modified files: 2991 passed
- Pre-existing flaky STACK_TRACE timeouts in useAgentExecution /
  useSessionRestoration reproduce on baseline and pass in isolation;
  unrelated to this change

Test-only refactor. No production code touched.
@jSydorowicz21 jSydorowicz21 force-pushed the dedup/phase-03a-mock-session-factory branch from 6f56900 to 5695349 Compare April 16, 2026 17:30
Copy link
Copy Markdown

@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 (5)
src/__tests__/renderer/hooks/useSummarizeHandler.test.ts (1)

90-99: Derive activeTabId from resolved tabs to avoid brittle defaults.

Line 97 hard-codes 'tab-1'. If a caller overrides aiTabs without also overriding activeTabId, the session can become internally inconsistent.

♻️ Optional hardening
 function createMockSession(overrides: Partial<Session> = {}): Session {
+	const aiTabs = overrides.aiTabs ?? [createMockTab()];
 	return baseCreateMockSession({
 		cwd: '/projects/test',
 		fullPath: '/projects/test',
 		projectRoot: '/projects/test',
 		contextUsage: 75,
-		aiTabs: [createMockTab()],
-		activeTabId: 'tab-1',
+		aiTabs,
+		activeTabId: overrides.activeTabId ?? aiTabs[0]?.id ?? '',
 		...overrides,
 	});
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/__tests__/renderer/hooks/useSummarizeHandler.test.ts` around lines 90 -
99, The helper createMockSession hard-codes activeTabId to 'tab-1', which can
conflict if callers override aiTabs; change createMockSession so activeTabId is
derived from the resolved aiTabs when overrides don't provide it (e.g., use
overrides.aiTabs?.[0]?.id or the id of createMockTab() used as default) before
calling baseCreateMockSession, ensuring the activeTabId always points to a tab
that actually exists in aiTabs.
src/__tests__/renderer/components/FileExplorerPanel.test.tsx (1)

241-251: Pin the test session ID locally to avoid hidden coupling.

This wrapper currently relies on the shared helper’s default id, but many assertions in this file expect "session-1". Setting it explicitly here makes the suite resilient to future helper-default changes.

Suggested patch
 const createMockSession = (overrides: Partial<Session> = {}): Session =>
 	baseCreateMockSession({
+		id: 'session-1',
 		cwd: '/Users/test/project',
 		fullPath: '/Users/test/project',
 		projectRoot: '/Users/test/project',
 		aiPid: 1234,
 		terminalPid: 5678,
 		isGitRepo: true,
 		fileTreeAutoRefreshInterval: 0,
 		...overrides,
 	});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/__tests__/renderer/components/FileExplorerPanel.test.tsx` around lines
241 - 251, The createMockSession helper relies on baseCreateMockSession's
default id which can change; explicitly set id: 'session-1' in the overrides
passed to baseCreateMockSession so tests that assert on "session-1" are
stable—update the createMockSession function to include id: 'session-1'
alongside cwd, fullPath, projectRoot, aiPid, terminalPid, isGitRepo, and
fileTreeAutoRefreshInterval when calling baseCreateMockSession.
src/__tests__/renderer/components/SessionList.test.tsx (1)

18-18: Prefer the test helpers barrel import for consistency.

Line 18 can import from the barrel (../../helpers) to match the Phase 03A consolidation pattern and reduce future path churn.

Suggested diff
-import { createMockSession as baseCreateMockSession } from '../../helpers/mockSession';
+import { createMockSession as baseCreateMockSession } from '../../helpers';
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/__tests__/renderer/components/SessionList.test.tsx` at line 18, The
import for createMockSession uses a deep path (createMockSession as
baseCreateMockSession) from '../../helpers/mockSession'; update this to import
from the helpers barrel (../../helpers) instead to match the Phase 03A
consolidation and keep imports consistent across tests—replace the existing
import statement so the symbol baseCreateMockSession is imported from the barrel
module.
src/__tests__/renderer/hooks/useAtMentionCompletion.test.ts (1)

22-22: The as any[] cast is acceptable for test code.

This is a single isolated usage, and the null fileTree case is intentionally tested (lines 142, 159 show test cases validating empty suggestion behavior). The proposed refactor is more verbose and still relies on unsafe casting—(session as Session & { fileTree: null }) is equally type-unsafe while adding object mutation and extra lines. For test helpers, the current concise approach is standard practice.

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

In `@src/__tests__/renderer/hooks/useAtMentionCompletion.test.ts` at line 22, The
reviewer approves the use of the concise `as any[]` cast in the test helper;
leave the line returning baseCreateMockSession unchanged (the `return
baseCreateMockSession({ fileTree: fileTree as any[] });` statement) instead of
introducing the proposed verbose mutation or `(session as Session & { fileTree:
null })` casting—no code change required beyond keeping the existing concise
cast in the test.
src/__tests__/renderer/hooks/useMergeTransferHandlers_stdin.test.ts (1)

134-134: Use proper typing for aiTabs instead of as any to catch structural errors at compile time.

The ] as any, cast on line 134 bypasses TypeScript's verification of the AITab structure. Extracting to a typed variable preserves compile-time safety and prevents regressions when the AITab interface changes. The proposed refactor is valid and recommended.

Proposed refactor
 function createMockSession(overrides: Partial<Session> = {}): Session {
+	const aiTabs: Session['aiTabs'] = [
+		{
+			id: 'tab-1',
+			name: 'Tab 1',
+			inputValue: '',
+			data: [],
+			logs: [
+				{ id: 'log-1', timestamp: Date.now(), source: 'user', text: 'Hello' },
+				{ id: 'log-2', timestamp: Date.now(), source: 'ai', text: 'Hi there' },
+			],
+			stagedImages: [],
+			agentSessionId: 'agent-1',
+			starred: false,
+			createdAt: Date.now(),
+		},
+	];
+
 	return baseCreateMockSession({
 		name: 'Test Agent',
 		cwd: '/test',
 		fullPath: '/test',
 		projectRoot: '/test/project',
-		aiTabs: [
-			{
-				id: 'tab-1',
-				name: 'Tab 1',
-				inputValue: '',
-				data: [],
-				logs: [
-					{ id: 'log-1', timestamp: Date.now(), source: 'user', text: 'Hello' },
-					{ id: 'log-2', timestamp: Date.now(), source: 'ai', text: 'Hi there' },
-				],
-				stagedImages: [],
-				agentSessionId: 'agent-1',
-				starred: false,
-				createdAt: Date.now(),
-			},
-		] as any,
+		aiTabs,
 		activeTabId: 'tab-1',
 		shellCwd: '/test',
 		...overrides,
 	});
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/__tests__/renderer/hooks/useMergeTransferHandlers_stdin.test.ts` at line
134, The test currently casts the aiTabs array with `] as any,` which bypasses
TypeScript checks; instead declare a properly typed variable (e.g. `const
aiTabs: AITab[] = [...]`) using the AITab interface and replace the inline `] as
any,` with that variable when calling the function under test in
useMergeTransferHandlers_stdin.test (referencing the aiTabs usage in the test).
Ensure each array element conforms to AITab (add missing required properties or
use a partial helper type if intentional) so the compiler enforces structure and
prevents future regressions.
🤖 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/__tests__/renderer/components/FileExplorerPanel.test.tsx`:
- Around line 241-251: The createMockSession helper relies on
baseCreateMockSession's default id which can change; explicitly set id:
'session-1' in the overrides passed to baseCreateMockSession so tests that
assert on "session-1" are stable—update the createMockSession function to
include id: 'session-1' alongside cwd, fullPath, projectRoot, aiPid,
terminalPid, isGitRepo, and fileTreeAutoRefreshInterval when calling
baseCreateMockSession.

In `@src/__tests__/renderer/components/SessionList.test.tsx`:
- Line 18: The import for createMockSession uses a deep path (createMockSession
as baseCreateMockSession) from '../../helpers/mockSession'; update this to
import from the helpers barrel (../../helpers) instead to match the Phase 03A
consolidation and keep imports consistent across tests—replace the existing
import statement so the symbol baseCreateMockSession is imported from the barrel
module.

In `@src/__tests__/renderer/hooks/useAtMentionCompletion.test.ts`:
- Line 22: The reviewer approves the use of the concise `as any[]` cast in the
test helper; leave the line returning baseCreateMockSession unchanged (the
`return baseCreateMockSession({ fileTree: fileTree as any[] });` statement)
instead of introducing the proposed verbose mutation or `(session as Session & {
fileTree: null })` casting—no code change required beyond keeping the existing
concise cast in the test.

In `@src/__tests__/renderer/hooks/useMergeTransferHandlers_stdin.test.ts`:
- Line 134: The test currently casts the aiTabs array with `] as any,` which
bypasses TypeScript checks; instead declare a properly typed variable (e.g.
`const aiTabs: AITab[] = [...]`) using the AITab interface and replace the
inline `] as any,` with that variable when calling the function under test in
useMergeTransferHandlers_stdin.test (referencing the aiTabs usage in the test).
Ensure each array element conforms to AITab (add missing required properties or
use a partial helper type if intentional) so the compiler enforces structure and
prevents future regressions.

In `@src/__tests__/renderer/hooks/useSummarizeHandler.test.ts`:
- Around line 90-99: The helper createMockSession hard-codes activeTabId to
'tab-1', which can conflict if callers override aiTabs; change createMockSession
so activeTabId is derived from the resolved aiTabs when overrides don't provide
it (e.g., use overrides.aiTabs?.[0]?.id or the id of createMockTab() used as
default) before calling baseCreateMockSession, ensuring the activeTabId always
points to a tab that actually exists in aiTabs.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 5397e8a6-1033-4385-ab3e-7f15d81f34ef

📥 Commits

Reviewing files that changed from the base of the PR and between 6f56900 and 5695349.

📒 Files selected for processing (63)
  • src/__tests__/helpers/index.ts
  • src/__tests__/helpers/mockSession.ts
  • src/__tests__/integration/AutoRunRightPanel.test.tsx
  • src/__tests__/integration/AutoRunSessionList.test.tsx
  • src/__tests__/renderer/components/AppAgentModals.test.tsx
  • src/__tests__/renderer/components/AppConfirmModals.test.tsx
  • src/__tests__/renderer/components/AppModals-selfSourced.test.tsx
  • src/__tests__/renderer/components/AppSessionModals.test.tsx
  • src/__tests__/renderer/components/AppWorktreeModals.test.tsx
  • src/__tests__/renderer/components/FileExplorerPanel.test.tsx
  • src/__tests__/renderer/components/GroupChatInput.test.tsx
  • src/__tests__/renderer/components/HistoryPanel.test.tsx
  • src/__tests__/renderer/components/InlineWizard/WizardInputPanel.test.tsx
  • src/__tests__/renderer/components/InputArea.test.tsx
  • src/__tests__/renderer/components/MergeSessionModal.test.tsx
  • src/__tests__/renderer/components/PromptComposerModal.test.tsx
  • src/__tests__/renderer/components/QuickActionsModal.test.tsx
  • src/__tests__/renderer/components/SendToAgentModal.test.tsx
  • src/__tests__/renderer/components/SessionItemCue.test.tsx
  • src/__tests__/renderer/components/SessionList.test.tsx
  • src/__tests__/renderer/components/ThinkingStatusPill.test.tsx
  • src/__tests__/renderer/components/WorktreeRunSection.test.tsx
  • src/__tests__/renderer/hooks/batch/useAutoRunHandlers.worktree.test.ts
  • src/__tests__/renderer/hooks/useActiveSession.test.ts
  • src/__tests__/renderer/hooks/useAgentExecution.test.ts
  • src/__tests__/renderer/hooks/useAgentListeners.test.ts
  • src/__tests__/renderer/hooks/useAgentSessionManagement.test.ts
  • src/__tests__/renderer/hooks/useAtMentionCompletion.test.ts
  • src/__tests__/renderer/hooks/useAutoRunAchievements.test.ts
  • src/__tests__/renderer/hooks/useAutoRunDocumentLoader.test.ts
  • src/__tests__/renderer/hooks/useAutoRunHandlers.test.ts
  • src/__tests__/renderer/hooks/useAvailableAgents.test.ts
  • src/__tests__/renderer/hooks/useBatchHandlers.test.ts
  • src/__tests__/renderer/hooks/useBatchProcessor.test.ts
  • src/__tests__/renderer/hooks/useFileExplorerEffects.test.ts
  • src/__tests__/renderer/hooks/useFileTreeManagement.test.ts
  • src/__tests__/renderer/hooks/useGitStatusPolling.test.ts
  • src/__tests__/renderer/hooks/useGroupManagement.test.ts
  • src/__tests__/renderer/hooks/useInputHandlers.test.ts
  • src/__tests__/renderer/hooks/useInputProcessing.test.ts
  • src/__tests__/renderer/hooks/useKeyboardNavigation.test.ts
  • src/__tests__/renderer/hooks/useMergeSession.test.ts
  • src/__tests__/renderer/hooks/useMergeTransferHandlers.test.ts
  • src/__tests__/renderer/hooks/useMergeTransferHandlers_stdin.test.ts
  • src/__tests__/renderer/hooks/useModalHandlers.test.ts
  • src/__tests__/renderer/hooks/useRemoteHandlers.test.ts
  • src/__tests__/renderer/hooks/useRemoteHandlers_stdin.test.ts
  • src/__tests__/renderer/hooks/useRemoteIntegration.test.ts
  • src/__tests__/renderer/hooks/useSendToAgent.test.ts
  • src/__tests__/renderer/hooks/useSessionLifecycle.test.ts
  • src/__tests__/renderer/hooks/useSessionRestoration.test.ts
  • src/__tests__/renderer/hooks/useSummarizeHandler.test.ts
  • src/__tests__/renderer/hooks/useTabCompletion.test.ts
  • src/__tests__/renderer/hooks/useTabExportHandlers.test.ts
  • src/__tests__/renderer/hooks/useTabHandlers.test.ts
  • src/__tests__/renderer/hooks/useWizardHandlers.test.ts
  • src/__tests__/renderer/stores/agentStore.test.ts
  • src/__tests__/renderer/stores/sessionStore.test.ts
  • src/__tests__/renderer/stores/tabStore.test.ts
  • src/__tests__/renderer/utils/contextExtractor.test.ts
  • src/__tests__/renderer/utils/sessionValidation.test.ts
  • src/__tests__/renderer/utils/tabHelpers.test.ts
  • src/__tests__/renderer/utils/terminalTabHelpers.test.ts
✅ Files skipped from review due to trivial changes (18)
  • src/tests/renderer/hooks/useModalHandlers.test.ts
  • src/tests/renderer/hooks/useGroupManagement.test.ts
  • src/tests/helpers/index.ts
  • src/tests/renderer/hooks/useTabHandlers.test.ts
  • src/tests/renderer/utils/tabHelpers.test.ts
  • src/tests/renderer/hooks/useMergeTransferHandlers.test.ts
  • src/tests/renderer/stores/sessionStore.test.ts
  • src/tests/renderer/hooks/useAutoRunHandlers.test.ts
  • src/tests/renderer/hooks/useBatchHandlers.test.ts
  • src/tests/renderer/hooks/useTabExportHandlers.test.ts
  • src/tests/renderer/components/SessionItemCue.test.tsx
  • src/tests/renderer/hooks/useRemoteHandlers.test.ts
  • src/tests/renderer/hooks/useInputHandlers.test.ts
  • src/tests/renderer/hooks/useInputProcessing.test.ts
  • src/tests/renderer/components/WorktreeRunSection.test.tsx
  • src/tests/renderer/hooks/useKeyboardNavigation.test.ts
  • src/tests/renderer/stores/agentStore.test.ts
  • src/tests/renderer/components/PromptComposerModal.test.tsx
🚧 Files skipped from review as they are similar to previous changes (29)
  • src/tests/renderer/hooks/useGitStatusPolling.test.ts
  • src/tests/renderer/hooks/useAutoRunAchievements.test.ts
  • src/tests/renderer/components/GroupChatInput.test.tsx
  • src/tests/renderer/components/AppSessionModals.test.tsx
  • src/tests/helpers/mockSession.ts
  • src/tests/renderer/hooks/useFileTreeManagement.test.ts
  • src/tests/renderer/hooks/useTabCompletion.test.ts
  • src/tests/renderer/hooks/useFileExplorerEffects.test.ts
  • src/tests/renderer/components/SendToAgentModal.test.tsx
  • src/tests/renderer/components/HistoryPanel.test.tsx
  • src/tests/renderer/components/AppModals-selfSourced.test.tsx
  • src/tests/renderer/hooks/useRemoteIntegration.test.ts
  • src/tests/renderer/components/MergeSessionModal.test.tsx
  • src/tests/renderer/components/AppAgentModals.test.tsx
  • src/tests/renderer/components/AppWorktreeModals.test.tsx
  • src/tests/renderer/hooks/useAgentListeners.test.ts
  • src/tests/renderer/components/ThinkingStatusPill.test.tsx
  • src/tests/renderer/components/InlineWizard/WizardInputPanel.test.tsx
  • src/tests/renderer/hooks/useBatchProcessor.test.ts
  • src/tests/renderer/utils/terminalTabHelpers.test.ts
  • src/tests/renderer/hooks/useSessionLifecycle.test.ts
  • src/tests/renderer/hooks/useWizardHandlers.test.ts
  • src/tests/renderer/hooks/useSendToAgent.test.ts
  • src/tests/renderer/hooks/useMergeSession.test.ts
  • src/tests/renderer/hooks/useActiveSession.test.ts
  • src/tests/renderer/hooks/useRemoteHandlers_stdin.test.ts
  • src/tests/renderer/hooks/useSessionRestoration.test.ts
  • src/tests/renderer/components/QuickActionsModal.test.tsx
  • src/tests/renderer/components/InputArea.test.tsx

- Apply prettier to useModalHandlers.test.ts
- Add prompts and history mocks that the transfer flow depends on
  via prepareMaestroSystemPrompt (new in rc since PR opened)
@reachrazamair reachrazamair merged commit 7209173 into RunMaestro:rc Apr 16, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready to merge This PR is ready to merge refactor Clean-up needs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants