Skip to content

Refactor terminal component - #839

Closed
Kitenite wants to merge 1 commit into
mainfrom
refactor-terminal-1
Closed

Kitenite wants to merge 1 commit into
mainfrom
refactor-terminal-1

Conversation

@Kitenite

@Kitenite Kitenite commented Jan 19, 2026 •

Copy link
Copy Markdown
Member

Description

Related Issues

Type of Change

  • Bug fix
  • New feature
  • Documentation
  • Refactor
  • Other (please describe):

Testing

Screenshots (if applicable)

Additional Notes

Summary by CodeRabbit

Release Notes

  • New Features

    • Added visual overlays for terminal connection errors, killed sessions, and restored sessions to provide clearer user feedback.
  • Refactor

    • Restructured terminal session management architecture for improved reliability and restoration behavior.
    • Enhanced file link and current working directory handling in terminal.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Jan 19, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Large-scale refactoring of Terminal component state management from module-scoped maps to granular React hooks. Introduces five new hooks for distinct terminal concerns (connection, CWD, file links, input, session lifecycle), adds TerminalOverlays UI component, and provides utility modules for path normalization and mode parsing. Public Terminal API unchanged.

Changes

Cohort / File(s) Summary
Main Terminal Component
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
Replaced module-level state maps with hook-driven architecture; integrated new hooks for session, CWD, input, and file links; delegated overlay rendering to TerminalOverlays component; added first-render and render gating for restoration flow; refactored lifecycle logic into composable hooks.
Terminal Overlays UI
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/TerminalOverlays/TerminalOverlays.tsx, TerminalOverlays/index.ts
Created new overlay components (KilledOverlay, ConnectionErrorOverlay, RestoredOverlay) with state-specific UI and callbacks; extracted inline error/kill/restore blocks from Terminal into reusable overlay exports.
Hook System
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalSession.ts, hooks/useTerminalCwd.ts, hooks/useTerminalFileLinks.ts, hooks/useTerminalInput.ts, hooks/index.ts
Introduced five hooks managing terminal session lifecycle (creation, attachment, restoration, event streaming), CWD tracking with OSC-7 parsing, file link click handling, input buffering and keyboard events; exposed module-level pendingDetaches and coldRestoreState maps for cross-component state persistence.
Path & Mode Utilities
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/normalizeFilePath.ts, terminalModes.ts
Added utilities for path categorization (relative, workspace-root, absolute-outside-workspace) and terminal mode detection (alternate screen, bracketed paste) with carry-buffer chunking support.
Test Coverage
normalizeFilePath.test.ts, parseCwd.test.ts, terminalModes.test.ts
Added comprehensive test suites for path normalization, OSC-7 CWD extraction, and terminal mode parsing; covers edge cases, encoding, sequence handling, and chunked input scenarios.

Sequence Diagram(s)

sequenceDiagram
    participant TC as Terminal Component
    participant USH as useTerminalSession Hook
    participant TM as TerminalManager (TRPC)
    participant ES as Event Stream
    participant Store as Tabs Store

    TC->>USH: init with options & refs
    Note over USH: Create/attach pending

    alt Cold Restore Available
        USH->>Store: retrieve coldRestoreState
        Note over USH: Apply initial scrollback
    end

    USH->>TM: createOrAttach(sessionId)
    TM-->>USH: CreateOrAttachResult (scrollback, snapshot)
    
    USH->>USH: setupFirstRenderGating()<br/>- Await didFirstRender or fallback timer<br/>- Gate restoration until ready
    
    TC->>TC: First render completes
    USH->>USH: didFirstRender = true
    
    USH->>USH: maybeApplyInitialState()<br/>- Apply snapshot to xterm<br/>- Set restoration modes
    
    USH->>TM: stream(sessionId)
    TM-->>ES: TerminalStreamEvent[]
    
    loop Stream Event Processing
        ES->>USH: handleStreamData(event)
        alt Stream Ready
            USH->>USH: Apply event immediately<br/>- Update modes, parse CWD<br/>- Write to xterm
        else Not Ready Yet
            USH->>USH: Queue event to pending buffer
        end
    end
    
    alt Exit or Disconnect
        ES->>USH: exit/disconnect event
        USH->>Store: update pane status
        USH->>TC: render overlay (Killed/Error)
    end
    
    TC->>USH: handleRetryConnection()
    USH->>USH: Clear refs, reset state
    USH->>TM: createOrAttach (retry)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~70 minutes

Possibly related PRs

Suggested reviewers

  • AviPeltz

🐰 Hooks and stores in harmony,
State flows like a gentle stream,
Terminals are tamed at last! ✨
No more module-level seams,
Just composable dreams. 💭

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is entirely empty, containing only the template structure with no actual content, implementation details, or justification for the extensive changes made. Fill out all required sections: provide a clear summary of changes, link related issues, confirm the Refactor checkbox, describe testing performed, and add any additional context for reviewers.
Title check ❓ Inconclusive The title 'Refactor terminal component' is generic and does not clearly convey the specific nature or scope of the refactoring; it lacks concrete details about the primary architectural change. Consider a more specific title that highlights the key refactoring: e.g., 'Refactor terminal component to hook-driven architecture' or 'Migrate terminal state management to custom hooks'.
✅ Passed checks (1 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing touches
  • 📝 Generate docstrings

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.

@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: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (1)

620-631: Remove sessionRefs from the dependency array or memoize the refs object.

The refs object returned by useTerminalSession is created fresh on every render (lines 711-727 in useTerminalSession.ts) without memoization, causing the effect to re-run unnecessarily. Since the effect only reads/writes to the individual ref properties via .current, it doesn't depend on the wrapper object's reference being stable. Either remove sessionRefs from the dependency array at line 626, or wrap the returned object in useMemo within useTerminalSession.

🤖 Fix all issues with AI agents
In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalFileLinks.ts`:
- Around line 57-75: Update the console log prefixes to follow the
"[domain/operation]" convention: replace console.error("[Terminal] Failed to
open file in editor:", ...) with something like
console.error("[terminal/open-file] Failed to open file in editor:", ...) and
replace console.warn("[Terminal] workspaceCwd not loaded, falling back to
external editor", ...) with console.warn("[terminal/workspace-cwd] workspaceCwd
not loaded, falling back to external editor", ...). Search within
useTerminalFileLinks (and the surrounding functions open-file handling) for
other "[Terminal]" logs and rename them to the domain/operation format
(lowercase domain, concise operation name) so all logs in this file follow the
same convention.
- Around line 14-20: Change the positional params on the terminal file-link
handler to a single params object: update the UseTerminalFileLinksResult
interface to have handleFileLinkClick: (args: { path: string; line?: number;
column?: number }) => void and update handleFileLinkClickRef to
React.RefObject<(args: { path: string; line?: number; column?: number }) =>
void>; then refactor the implementation in useTerminalFileLinks (replace usages
of (path, line, column) with a single args object destructured as { path, line,
column }) and update the call site in Terminal.tsx to call handleFileLinkClick({
path, line, column }) instead of positional arguments. Ensure all references and
types are adjusted to the new named-params shape.

In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/normalizeFilePath.ts`:
- Around line 18-21: Refactor normalizeFilePath to accept a single params object
instead of two positional args: change its signature to normalizeFilePath({
path, workspaceCwd }: { path: string; workspaceCwd: string }): NormalizedPath
and update its implementation accordingly; then update all call sites (the
import/use in useTerminalFileLinks.ts and the nine test usages) to pass an
object { path: ..., workspaceCwd: ... } instead of two arguments, ensuring named
properties match exactly and keeping return type NormalizedPath unchanged.

In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/TerminalOverlays/TerminalOverlays.tsx`:
- Around line 6-112: This file bundles three exported components in one module;
split KilledOverlay, ConnectionErrorOverlay, and RestoredOverlay into their own
files (KilledOverlay.tsx, ConnectionErrorOverlay.tsx, RestoredOverlay.tsx) and
move the shared OverlayContainer into OverlayContainer.tsx (or colocate with one
overlay) then create an index.ts that re-exports the three overlays; update each
new file to import OverlayContainer and ensure the exported component names
(KilledOverlay, ConnectionErrorOverlay, RestoredOverlay) and prop interfaces
(KilledOverlayProps, ConnectionErrorOverlayProps, RestoredOverlayProps) match
the originals so existing consumers keep working.
🧹 Nitpick comments (6)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalCwd.ts (1)

46-50: Extract debounce interval to a named constant.

Keeps the 150ms value discoverable and consistent if reused. As per coding guidelines, extract magic numbers to module-level constants.

♻️ Proposed refactor
+const PANE_CWD_DEBOUNCE_MS = 150;
+
 // Debounced CWD update to reduce store updates during rapid directory changes
 const debouncedUpdatePaneCwdRef = useRef(
 	debounce((id: string, cwd: string | null, confirmed: boolean) => {
 		updatePaneCwd(id, cwd, confirmed);
-	}, 150),
+	}, PANE_CWD_DEBOUNCE_MS),
 );
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/terminalModes.ts (1)

37-94: Prefer params objects + named carry-buffer length.

These exported helpers take 2+ positional args and use a hardcoded tail length. Using params objects and a named constant improves call-site clarity and aligns with the object-param/magic-number conventions. Please update call sites in terminalModes.test.ts and useTerminalSession.ts accordingly. As per coding guidelines, use params objects for 2+ args and extract magic numbers.

♻️ Proposed refactor
+const MODE_CARRY_BUFFER_TAIL_LENGTH = 32;
+
+type ParseModesFromDataParams = {
+	data: string;
+	previousModes?: TerminalModes;
+};
+
+type ParseModesWithCarryBufferParams = {
+	data: string;
+	carryBuffer: string;
+	previousModes: TerminalModes;
+};
+
 export function parseModesFromData(
-	data: string,
-	previousModes: TerminalModes = {
+	{
+		data,
+		previousModes = {
 			alternateScreen: false,
 			bracketedPaste: false,
-	},
-): TerminalModes {
+		},
+	}: ParseModesFromDataParams,
+): TerminalModes {
 	const modes = { ...previousModes };
 	...
 }
 
 export function parseModesWithCarryBuffer(
-	data: string,
-	carryBuffer: string,
-	previousModes: TerminalModes,
+	{ data, carryBuffer, previousModes }: ParseModesWithCarryBufferParams,
 ): { modes: TerminalModes; newCarryBuffer: string } {
 	const combined = carryBuffer + data;
 
-	const modes = parseModesFromData(combined, previousModes);
+	const modes = parseModesFromData({ data: combined, previousModes });
 
-	const newCarryBuffer = combined.slice(-32);
+	const newCarryBuffer = combined.slice(-MODE_CARRY_BUFFER_TAIL_LENGTH);
 
 	return { modes, newCarryBuffer };
 }
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalSession.ts (2)

205-221: Use a params object for the multi-arg exit helper.

This aligns with the object-params convention and makes call sites clearer. Please update the two call sites in flushPendingEvents and handleStreamData accordingly. As per coding guidelines, prefer params objects for functions with 2+ arguments.

♻️ Proposed refactor
-const handleTerminalExit = useCallback(
-	(exitCode: number, xterm: XTerm, wasKilledByUser: boolean) => {
+const handleTerminalExit = useCallback(
+	({
+		exitCode,
+		xterm,
+		wasKilledByUser,
+	}: { exitCode: number; xterm: XTerm; wasKilledByUser: boolean }) => {
 		isExitedRef.current = true;
 		isStreamReadyRef.current = false;
 		wasKilledByUserRef.current = wasKilledByUser;
 		onExitStatusChange(wasKilledByUser ? "killed" : "exited");
 		...
 	},
 	[onExitStatusChange],
 );

223-283: Consider a shared event dispatcher to avoid drift.

flushPendingEvents and handleStreamData duplicate event-type branching and error handling. A shared handler or lookup map reduces duplication and aligns with the lookup-map guideline. As per coding guidelines, prefer lookup objects/maps over repeated type conditionals.

♻️ Example refactor sketch
+const handleStreamEvent = useCallback(
+	({ event, xterm }: { event: TerminalStreamEvent; xterm: XTerm }) => {
+		if (event.type === "data") {
+			updateModesFromData(event.data);
+			xterm.write(event.data);
+			onCwdUpdate(event.data);
+			return;
+		}
+		if (event.type === "exit") {
+			handleTerminalExit({
+				exitCode: event.exitCode,
+				xterm,
+				wasKilledByUser: wasKilledByUserRef.current,
+			});
+			return;
+		}
+		if (event.type === "disconnect") {
+			onConnectionError(event.reason || "Connection to terminal daemon lost");
+			return;
+		}
+		// error handling block...
+	},
+	[updateModesFromData, onCwdUpdate, handleTerminalExit, onConnectionError],
+);
+
 // flushPendingEvents
-for (const event of events) { ... }
+for (const event of events) {
+	handleStreamEvent({ event, xterm });
+}
 
 // handleStreamData
-// repeated event.type chain...
+const xterm = xtermRef.current;
+if (xterm) {
+	handleStreamEvent({ event, xterm });
+}

Also applies to: 639-699

apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (2)

182-189: Minor: Inline function created on every render.

The debouncedSetTabAutoTitle prop creates a new function on each render. If useTerminalInput doesn't store this in a ref internally, it could cause unnecessary work or stale closures.

Consider memoizing or using a ref-based pattern consistent with other callbacks in this file:

♻️ Suggested improvement
+	const debouncedSetTabAutoTitleCallback = useCallback(
+		(tabIdArg: string, title: string) =>
+			debouncedSetTabAutoTitleRef.current(tabIdArg, title),
+		[],
+	);
+
 	const { handleKeyPress, handlePaste } = useTerminalInput({
 		paneId,
 		isAlternateScreenRef: sessionRefs.isAlternateScreen,
 		parentTabIdRef,
-		debouncedSetTabAutoTitle: (tabIdArg, title) =>
-			debouncedSetTabAutoTitleRef.current(tabIdArg, title),
+		debouncedSetTabAutoTitle: debouncedSetTabAutoTitleCallback,
 	});

319-325: Add error handling for dynamic import.

The dynamic import for SearchAddon silently fails if the import errors. While unlikely, this could leave users without search functionality without any indication.

♻️ Suggested fix
 		// Load search addon asynchronously
-		import("@xterm/addon-search").then(({ SearchAddon }) => {
-			if (isUnmounted) return;
-			const searchAddon = new SearchAddon();
-			xterm.loadAddon(searchAddon);
-			searchAddonRef.current = searchAddon;
-		});
+		import("@xterm/addon-search")
+			.then(({ SearchAddon }) => {
+				if (isUnmounted) return;
+				const searchAddon = new SearchAddon();
+				xterm.loadAddon(searchAddon);
+				searchAddonRef.current = searchAddon;
+			})
+			.catch((error) => {
+				console.error("[Terminal] Failed to load search addon:", error);
+			});

Comment on lines +14 to +20
export interface UseTerminalFileLinksResult {
/** Handler for file link clicks in terminal */
handleFileLinkClick: (path: string, line?: number, column?: number) => void;
/** Ref to handleFileLinkClick for use in terminal instance creation */
handleFileLinkClickRef: React.RefObject<
(path: string, line?: number, column?: number) => void
>;

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.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# First, let's read the file to understand the current implementation
cat -n apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalFileLinks.ts

Repository: superset-sh/superset

Length of output: 184


🏁 Script executed:

# Search for all usages of handleFileLinkClick in the codebase
rg "handleFileLinkClick" --type ts --type tsx -A 2 -B 2

Repository: superset-sh/superset

Length of output: 91


🏁 Script executed:

# Also search for any console logging in this file to check the logging prefix
rg "console\.(error|warn|log)" apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalFileLinks.ts -A 1 -B 1

Repository: superset-sh/superset

Length of output: 285


🏁 Script executed:

# Read the file directly with cat
cat -n "apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalFileLinks.ts"

Repository: superset-sh/superset

Length of output: 4203


🏁 Script executed:

# Search for handleFileLinkClick usage more broadly (all file types)
rg "handleFileLinkClick" -A 3 -B 1

Repository: superset-sh/superset

Length of output: 4853


🏁 Script executed:

# Find all files in the Terminal hooks directory
fd . "apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal"

Repository: superset-sh/superset

Length of output: 5265


Switch file-link handlers to a params object.

The callback currently takes positional parameters (path, line, column). Per coding guidelines, functions with 2+ parameters should accept a single params object with named properties. Refactor the interface definitions and implementation, then update the call site in Terminal.tsx.

♻️ Proposed refactor
+export interface TerminalFileLinkClickParams {
+	path: string;
+	line?: number;
+	column?: number;
+}
+
 export interface UseTerminalFileLinksResult {
 	/** Handler for file link clicks in terminal */
-	handleFileLinkClick: (path: string, line?: number, column?: number) => void;
+	handleFileLinkClick: (params: TerminalFileLinkClickParams) => void;
 	/** Ref to handleFileLinkClick for use in terminal instance creation */
 	handleFileLinkClickRef: React.RefObject<
-		(path: string, line?: number, column?: number) => void
+		(params: TerminalFileLinkClickParams) => void
 	>;
 }

 const handleFileLinkClick = useCallback(
-	(path: string, line?: number, column?: number) => {
+	({ path, line, column }: TerminalFileLinkClickParams) => {

Then in Terminal.tsx, update the call site from:

-onFileLinkClick: (path, line, column) =>
-	handleFileLinkClickRef.current(path, line, column),
+onFileLinkClick: (path, line, column) =>
+	handleFileLinkClickRef.current({ path, line, column }),
🤖 Prompt for AI Agents
In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalFileLinks.ts`
around lines 14 - 20, Change the positional params on the terminal file-link
handler to a single params object: update the UseTerminalFileLinksResult
interface to have handleFileLinkClick: (args: { path: string; line?: number;
column?: number }) => void and update handleFileLinkClickRef to
React.RefObject<(args: { path: string; line?: number; column?: number }) =>
void>; then refactor the implementation in useTerminalFileLinks (replace usages
of (path, line, column) with a single args object destructured as { path, line,
column }) and update the call site in Terminal.tsx to call handleFileLinkClick({
path, line, column }) instead of positional arguments. Ensure all references and
types are adjusted to the new named-params shape.

Comment on lines +57 to +75
console.error(
"[Terminal] Failed to open file in editor:",
path,
error,
);
const errorMessage =
error instanceof Error ? error.message : String(error);
toast.error("Failed to open file in editor", {
description: errorMessage,
});
});
};

if (behavior === "file-viewer") {
// If workspaceCwd is not loaded yet, fall back to external editor
if (!workspaceCwd) {
console.warn(
"[Terminal] workspaceCwd not loaded, falling back to external editor",
);

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.

⚠️ Potential issue | 🟡 Minor

Align console prefixes with [domain/operation] convention.

The current log prefixes don’t include an operation identifier. Please adjust to the required format. As per coding guidelines, ...

💡 Suggested tweak
-						console.error(
-							"[Terminal] Failed to open file in editor:",
+						console.error(
+							"[terminal/open-file] Failed to open file in editor:",
 							path,
 							error,
 						);
@@
-					console.warn(
-						"[Terminal] workspaceCwd not loaded, falling back to external editor",
-					);
+					console.warn(
+						"[terminal/file-link] workspaceCwd not loaded, falling back to external editor",
+					);
📝 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
console.error(
"[Terminal] Failed to open file in editor:",
path,
error,
);
const errorMessage =
error instanceof Error ? error.message : String(error);
toast.error("Failed to open file in editor", {
description: errorMessage,
});
});
};
if (behavior === "file-viewer") {
// If workspaceCwd is not loaded yet, fall back to external editor
if (!workspaceCwd) {
console.warn(
"[Terminal] workspaceCwd not loaded, falling back to external editor",
);
console.error(
"[terminal/open-file] Failed to open file in editor:",
path,
error,
);
const errorMessage =
error instanceof Error ? error.message : String(error);
toast.error("Failed to open file in editor", {
description: errorMessage,
});
});
};
if (behavior === "file-viewer") {
// If workspaceCwd is not loaded yet, fall back to external editor
if (!workspaceCwd) {
console.warn(
"[terminal/file-link] workspaceCwd not loaded, falling back to external editor",
);
🤖 Prompt for AI Agents
In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalFileLinks.ts`
around lines 57 - 75, Update the console log prefixes to follow the
"[domain/operation]" convention: replace console.error("[Terminal] Failed to
open file in editor:", ...) with something like
console.error("[terminal/open-file] Failed to open file in editor:", ...) and
replace console.warn("[Terminal] workspaceCwd not loaded, falling back to
external editor", ...) with console.warn("[terminal/workspace-cwd] workspaceCwd
not loaded, falling back to external editor", ...). Search within
useTerminalFileLinks (and the surrounding functions open-file handling) for
other "[Terminal]" logs and rename them to the domain/operation format
(lowercase domain, concise operation name) so all logs in this file follow the
same convention.

Comment on lines +18 to +21
export function normalizeFilePath(
path: string,
workspaceCwd: string,
): NormalizedPath {

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.

🛠️ Refactor suggestion | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

cat -n apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/normalizeFilePath.ts

Repository: superset-sh/superset

Length of output: 1530


🏁 Script executed:

rg "normalizeFilePath" --type ts --type tsx -n

Repository: superset-sh/superset

Length of output: 91


🏁 Script executed:

# Search for test files that might call normalizeFilePath
fd "\.test\.(ts|tsx)" | xargs rg "normalizeFilePath" -l

Repository: superset-sh/superset

Length of output: 186


🏁 Script executed:

rg "normalizeFilePath" -n

Repository: superset-sh/superset

Length of output: 2970


🏁 Script executed:

cat -n apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/normalizeFilePath.test.ts

Repository: superset-sh/superset

Length of output: 3954


🏁 Script executed:

cat -n apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalFileLinks.ts | sed -n '75,90p'

Repository: superset-sh/superset

Length of output: 563


🏁 Script executed:

cat -n apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalFileLinks.ts | head -100

Repository: superset-sh/superset

Length of output: 3899


Refactor normalizeFilePath to use a params object.

This function has 2 parameters and violates the coding guideline requiring object parameters for functions with 2+ arguments. Update the function signature and all 10 call sites (9 in tests, 1 in useTerminalFileLinks.ts).

♻️ Proposed refactor
+export interface NormalizeFilePathParams {
+	path: string;
+	workspaceCwd: string;
+}
+
 export function normalizeFilePath(
-	path: string,
-	workspaceCwd: string,
+	{ path, workspaceCwd }: NormalizeFilePathParams,
 ): NormalizedPath {
🤖 Prompt for AI Agents
In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/normalizeFilePath.ts`
around lines 18 - 21, Refactor normalizeFilePath to accept a single params
object instead of two positional args: change its signature to
normalizeFilePath({ path, workspaceCwd }: { path: string; workspaceCwd: string
}): NormalizedPath and update its implementation accordingly; then update all
call sites (the import/use in useTerminalFileLinks.ts and the nine test usages)
to pass an object { path: ..., workspaceCwd: ... } instead of two arguments,
ensuring named properties match exactly and keeping return type NormalizedPath
unchanged.

Comment on lines +6 to +112
interface OverlayContainerProps {
children: React.ReactNode;
}

/**
* Common overlay container with centered positioning and backdrop.
*/
function OverlayContainer({ children }: OverlayContainerProps) {
return (
<div className="absolute inset-0 z-10 flex items-center justify-center bg-black/50">
{children}
</div>
);
}

interface KilledOverlayProps {
onRestart: () => void;
}

/**
* Overlay shown when terminal session was killed by user.
*/
export function KilledOverlay({ onRestart }: KilledOverlayProps) {
return (
<OverlayContainer>
<Card className="gap-3 py-4 px-2">
<div className="flex flex-col items-center text-center gap-1.5 px-4">
<LuPower className="size-5 text-muted-foreground" />
<div className="space-y-0.5">
<p className="text-sm font-medium">Session killed</p>
<p className="text-xs text-muted-foreground">
You terminated this shell session
</p>
</div>
</div>
<div className="px-4">
<Button size="sm" className="w-full" onClick={onRestart}>
Restart
</Button>
</div>
</Card>
</OverlayContainer>
);
}

interface ConnectionErrorOverlayProps {
onRetry: () => void;
}

/**
* Overlay shown when connection to terminal daemon is lost.
*/
export function ConnectionErrorOverlay({
onRetry,
}: ConnectionErrorOverlayProps) {
return (
<OverlayContainer>
<Card className="gap-3 py-4 px-2 max-w-xs">
<div className="flex flex-col items-center text-center gap-1.5 px-4">
<HiExclamationTriangle className="size-5 text-destructive" />
<div className="space-y-0.5">
<p className="text-sm font-medium">Connection error</p>
<p className="text-xs text-muted-foreground">
Lost connection to terminal daemon
</p>
</div>
</div>
<div className="px-4">
<Button size="sm" className="w-full" onClick={onRetry}>
Retry
</Button>
</div>
</Card>
</OverlayContainer>
);
}

interface RestoredOverlayProps {
onStartShell: () => void;
}

/**
* Overlay shown after cold restore (reboot recovery).
* Previous scrollback is preserved and displayed read-only until user starts new shell.
*/
export function RestoredOverlay({ onStartShell }: RestoredOverlayProps) {
return (
<OverlayContainer>
<Card className="gap-3 py-4 px-2">
<div className="flex flex-col items-center text-center gap-1.5 px-4">
<LuTerminal className="size-5 text-primary" />
<div className="space-y-0.5">
<p className="text-sm font-medium">Session restored</p>
<p className="text-xs text-muted-foreground">
Previous scrollback preserved after restart
</p>
</div>
</div>
<div className="px-4">
<Button size="sm" className="w-full" onClick={onStartShell}>
Start Shell
</Button>
</div>
</Card>
</OverlayContainer>
);
}

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.

🛠️ Refactor suggestion | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# Check if OverlayContainer or individual overlays are imported elsewhere
rg "from.*TerminalOverlays|import.*TerminalOverlays" --type ts --type tsx

Repository: superset-sh/superset

Length of output: 91


🏁 Script executed:

# Check if there are re-exports or if these are used individually
rg "KilledOverlay|ConnectionErrorOverlay|RestoredOverlay|OverlayContainer" --type ts --type tsx -l

Repository: superset-sh/superset

Length of output: 91


🏁 Script executed:

# Check similar component structures in the codebase for patterns
fd "components" -t d apps/desktop/src/renderer --max-depth 5 | head -20

Repository: superset-sh/superset

Length of output: 1030


🏁 Script executed:

# Search for imports of components from this file
rg "TerminalOverlays|KilledOverlay|ConnectionErrorOverlay|RestoredOverlay" --glob "*.{ts,tsx}" -B2 -A2 | head -100

Repository: superset-sh/superset

Length of output: 8507


🏁 Script executed:

# Check the directory structure to understand the file organization
cat apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/TerminalOverlays/TerminalOverlays.tsx | head -20

Repository: superset-sh/superset

Length of output: 596


🏁 Script executed:

# Look for files importing from the TerminalOverlays directory/file
fd . apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/ -type f | head -20

Repository: superset-sh/superset

Length of output: 234


🏁 Script executed:

# Check the index.ts file to see how components are exported
cat apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/TerminalOverlays/index.ts

Repository: superset-sh/superset

Length of output: 160


Split into one component per file.

This file defines three exported components (KilledOverlay, ConnectionErrorOverlay, RestoredOverlay) in a single .tsx file, violating the one-component-per-file rule. Each overlay should be in its own file. The internal OverlayContainer helper can be extracted to a shared utility file or colocated with one of the overlays if used by only that component.

Example structure:
TerminalOverlays/
├── KilledOverlay.tsx
├── ConnectionErrorOverlay.tsx
├── RestoredOverlay.tsx
├── OverlayContainer.tsx (or merge into a shared utility)
└── index.ts
🤖 Prompt for AI Agents
In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/TerminalOverlays/TerminalOverlays.tsx`
around lines 6 - 112, This file bundles three exported components in one module;
split KilledOverlay, ConnectionErrorOverlay, and RestoredOverlay into their own
files (KilledOverlay.tsx, ConnectionErrorOverlay.tsx, RestoredOverlay.tsx) and
move the shared OverlayContainer into OverlayContainer.tsx (or colocate with one
overlay) then create an index.ts that re-exports the three overlays; update each
new file to import OverlayContainer and ensure the exported component names
(KilledOverlay, ConnectionErrorOverlay, RestoredOverlay) and prop interfaces
(KilledOverlayProps, ConnectionErrorOverlayProps, RestoredOverlayProps) match
the originals so existing consumers keep working.

@Kitenite Kitenite closed this Jan 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🧹 Preview Cleanup Complete

The following preview resources have been cleaned up:

  • ⚠️ Neon database branch
  • ⚠️ Electric Fly.io app

Thank you for your contribution! 🎉

@Kitenite
Kitenite deleted the refactor-terminal-1 branch January 20, 2026 01:10
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