Repository navigation
Conversation
WalkthroughAdds a new tRPC terminal router and wires it into the main app router; introduces a client-side Terminal (xterm.js) component and integrates it into SingleTabView and GroupTabView via a new GroupTabPane; accessibility and cursor tweaks for tab items; updates mosaic theme and drop-target styles. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant TabView as Tab View (Single/Group)
participant TerminalUI as Terminal (xterm)
participant tRPCClient as tRPC Client
participant TerminalRouter as Terminal Router
User->>TabView: open/focus tab
TabView->>TerminalUI: render + onFocus
TerminalUI->>tRPCClient: (optional) create terminal
tRPCClient->>TerminalRouter: create(input)
TerminalRouter-->>tRPCClient: { terminalId }
tRPCClient-->>TerminalUI: terminalId
User->>TerminalUI: type command
TerminalUI->>tRPCClient: executeCommand({terminalId, command})
tRPCClient->>TerminalRouter: executeCommand(input)
TerminalRouter-->>tRPCClient: mock response
tRPCClient-->>TerminalUI: response
TerminalUI->>User: display output
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (2 warnings, 1 inconclusive)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (3)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/GroupTabView/GroupTabPane.tsx (1)
28-63: GroupTabPane wiring looks good; consider passing a realcwdlaterThe composition of
MosaicWindow→TabContentContextMenu→Terminalis clean, and usingonFocusto triggersetActiveTab(workspaceId, tabId)is a good fit with the terminal’s focus handling (once the terminal lifecycle bug is fixed).Right now
cwd="~"is clearly a placeholder; when the terminal backend stops being mock, you’ll likely want to pass the actual workspace/project path here so sessions start in the expected directory.apps/desktop/src/lib/trpc/routers/terminal/terminal.ts (1)
86-90: Use enum or union type for signal parameter.The
signalparameter accepts any string. Consider using a union type or enum to restrict to valid signal values (e.g., "SIGINT", "SIGTERM", "SIGKILL") for better type safety.Apply this diff to add signal type constraints:
.input( z.object({ id: z.string(), - signal: z.string(), + signal: z.enum(["SIGINT", "SIGTERM", "SIGKILL", "SIGHUP", "SIGQUIT"]), }), )apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/SingleTabView.tsx (1)
44-49: Consider making cwd configurable.The
cwdprop is hardcoded to"~". Consider whether terminals should open in the workspace's actual directory or project root instead of the user's home directory. This could improve user experience by starting terminals in the relevant working directory.The
overflow-hiddenchange is correct for terminal rendering.If workspace-specific cwd is desired, you might want to pass a computed cwd value from the tab's workspace context:
cwd={tab.workspacePath || "~"}
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (10)
apps/desktop/src/lib/trpc/routers/index.ts(2 hunks)apps/desktop/src/lib/trpc/routers/terminal/index.ts(1 hunks)apps/desktop/src/lib/trpc/routers/terminal/terminal.ts(1 hunks)apps/desktop/src/renderer/screens/main/components/TopBar/WorkspaceTabs/WorkspaceItem.tsx(1 hunks)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/GroupTabView/GroupTabPane.tsx(1 hunks)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/GroupTabView/index.tsx(3 hunks)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/SingleTabView.tsx(3 hunks)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx(1 hunks)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/index.ts(1 hunks)apps/desktop/src/renderer/screens/main/components/WorkspaceView/Sidebar/TabsView/TabItem/index.tsx(2 hunks)
🧰 Additional context used
🧬 Code graph analysis (6)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/Sidebar/TabsView/TabItem/index.tsx (1)
apps/desktop/src/renderer/stores/tabs/helpers/tab-crud.ts (1)
handleRemoveTab(35-73)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/GroupTabView/GroupTabPane.tsx (2)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabContentContextMenu.tsx (1)
TabContentContextMenu(17-40)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (1)
Terminal(64-365)
apps/desktop/src/lib/trpc/routers/index.ts (1)
apps/desktop/src/lib/trpc/routers/terminal/terminal.ts (1)
createTerminalRouter(8-114)
apps/desktop/src/lib/trpc/routers/terminal/terminal.ts (2)
apps/desktop/src/lib/trpc/routers/terminal/index.ts (1)
createTerminalRouter(1-1)apps/desktop/src/lib/trpc/index.ts (1)
router(15-15)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/SingleTabView.tsx (3)
apps/desktop/src/renderer/stores/tabs/hooks.ts (1)
useSetActiveTab(10-11)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabContentContextMenu.tsx (1)
TabContentContextMenu(17-40)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (1)
Terminal(64-365)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/GroupTabView/index.tsx (2)
apps/desktop/src/renderer/stores/tabs/hooks.ts (1)
useSetActiveTab(10-11)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/GroupTabView/GroupTabPane.tsx (1)
GroupTabPane(28-67)
🔇 Additional comments (9)
apps/desktop/src/renderer/screens/main/components/TopBar/WorkspaceTabs/WorkspaceItem.tsx (1)
83-83: LGTM! Good UX improvement.The dynamic cursor styling correctly provides visual feedback during drag operations. Using "grabbing" while dragging and "pointer" in the idle state is appropriate and enhances user experience.
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/index.ts (1)
1-1: Terminal barrel export looks goodRe-exporting
Terminalfrom this index keeps imports clean (../Terminal) and matches howGroupTabPaneuses it. No issues here.apps/desktop/src/lib/trpc/routers/terminal/index.ts (1)
1-1: Terminal router barrel export is consistentRe-exporting
createTerminalRouterhere matches how the main router imports from"./terminal"and keeps the TRPC router structure coherent. No issues.apps/desktop/src/lib/trpc/routers/index.ts (1)
6-18: Terminal router integration intocreateAppRouterlooks correctWiring
terminal: createTerminalRouter()into the main router is straightforward and keeps theAppRoutertype source (ReturnType<typeof createAppRouter>) accurate. As long as the client typings regenerate against this updated router, thetrpc.terminal.*calls in the renderer will stay in sync.Please ensure your TRPC client types (or any codegen you use) have been refreshed so that the new
terminalnamespace is available on the client side.apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/SingleTabView.tsx (2)
4-4: LGTM! Clean integration of terminal hooks.The imports and hook initialization are well-structured and follow the established patterns in the codebase.
Also applies to: 9-9, 20-20
34-36: LGTM! Proper focus handling.The focus handler correctly updates the active tab state when the terminal gains focus, which is the expected behavior for terminal UI interactions.
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/GroupTabView/index.tsx (3)
16-16: LGTM! Consistent active tab management.The imports and hook initialization properly establish active tab tracking for group tab views, consistent with the SingleTabView implementation.
Also applies to: 22-22, 59-59
99-110: Excellent refactoring with proper separation of concerns.The extraction of pane rendering logic into
GroupTabPaneimproves code organization and maintainability. All necessary props are correctly passed, and the component properly handles Terminal rendering with focus management as shown in the relevant snippets.
113-122: LGTM! Complete dependency array.The dependency array correctly includes all values used within the
renderPanecallback, preventing stale closures and ensuring proper re-rendering when dependencies change.
| */ | ||
| export const createTerminalRouter = () => { | ||
| // Mock terminal sessions storage | ||
| const terminalSessions = new Map<string, string>(); |
There was a problem hiding this comment.
Add cleanup mechanism for terminal sessions.
The terminalSessions map grows unbounded with no cleanup mechanism. Consider implementing a proper disposal flow in the detach procedure or adding a separate cleanup/destroy procedure to prevent memory leaks.
Would you like me to generate an implementation for a cleanup mechanism?
| z.object({ | ||
| id: z.string().optional(), | ||
| cols: z.number().optional(), | ||
| rows: z.number().optional(), | ||
| cwd: z.string().optional(), | ||
| }), |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
Add validation constraints for terminal dimensions.
The cols and rows parameters lack validation constraints. Consider adding minimum/maximum bounds to prevent invalid dimensions in the real implementation.
Apply this diff to add validation:
z.object({
id: z.string().optional(),
- cols: z.number().optional(),
- rows: z.number().optional(),
+ cols: z.number().int().min(1).max(500).optional(),
+ rows: z.number().int().min(1).max(200).optional(),
cwd: z.string().optional(),
}),📝 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.
| z.object({ | |
| id: z.string().optional(), | |
| cols: z.number().optional(), | |
| rows: z.number().optional(), | |
| cwd: z.string().optional(), | |
| }), | |
| z.object({ | |
| id: z.string().optional(), | |
| cols: z.number().int().min(1).max(500).optional(), | |
| rows: z.number().int().min(1).max(200).optional(), | |
| cwd: z.string().optional(), | |
| }), |
🤖 Prompt for AI Agents
In apps/desktop/src/lib/trpc/routers/terminal/terminal.ts around lines 15–20,
the zod schema for terminal params allows any numeric value for cols and rows;
add validation to enforce integer, minimum and maximum bounds (e.g., cols:
z.number().int().min(10).max(1000).optional() and rows:
z.number().int().min(2).max(500).optional()) so invalid/huge dimensions are
rejected; update the schema accordingly and run type checks.
| }), | ||
| ) | ||
| .mutation(async ({ input }) => { | ||
| const terminalId = input.id || `terminal-${Date.now()}`; |
There was a problem hiding this comment.
Potential ID collision with Date.now().
Using Date.now() for ID generation can cause collisions if multiple terminals are created within the same millisecond. Consider using a more robust approach like crypto.randomUUID() or a counter with a prefix.
Apply this diff to use a more robust ID generation:
-const terminalId = input.id || `terminal-${Date.now()}`;
+const terminalId = input.id || `terminal-${crypto.randomUUID()}`;Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In apps/desktop/src/lib/trpc/routers/terminal/terminal.ts around line 23, the
terminal ID is generated with Date.now() which can collide; replace that with a
robust UUID generator such as crypto.randomUUID() (or
globalThis.crypto?.randomUUID() for browser-safe code) and provide a fallback
(e.g., an incrementing counter prefixed with "terminal-") if randomUUID is
unavailable; update the assignment to use input.id || `terminal-${uuid}` (or use
the counter) and ensure any needed imports or runtime checks for crypto are
added.
| // Initialize terminal once | ||
| useEffect(() => { | ||
| if (!containerRef.current || isInitializedRef.current) { | ||
| return; | ||
| } | ||
|
|
||
| isInitializedRef.current = true; | ||
|
|
||
| // Create terminal instance | ||
| const term = new XTerm({ | ||
| cursorBlink: true, | ||
| fontSize: 12, | ||
| fontFamily: 'Menlo, Monaco, "Courier New", monospace', | ||
| theme: theme === "light" ? TERMINAL_THEME.LIGHT : TERMINAL_THEME.DARK, | ||
| scrollback: 9999999, | ||
| macOptionClickForcesSelection: true, | ||
| rightClickSelectsWord: true, | ||
| }); | ||
|
|
||
| term.open(containerRef.current); | ||
|
|
||
| // Track disposal state | ||
| let isDisposed = false; | ||
|
|
||
| // Set up keyboard shortcuts | ||
| term.attachCustomKeyEventHandler((e: KeyboardEvent): boolean => { | ||
| // Cmd+K: Clear terminal | ||
| if ( | ||
| e.key === "k" && | ||
| e.metaKey && | ||
| !e.ctrlKey && | ||
| !e.altKey && | ||
| !e.shiftKey | ||
| ) { | ||
| e.preventDefault(); | ||
| term.clear(); | ||
| // TODO: Send clear command via tRPC | ||
| executeCommand.mutate({ | ||
| id: terminalId, | ||
| command: "\x0c", // Form feed (Ctrl+L) | ||
| }); | ||
| return false; | ||
| } | ||
|
|
||
| // Cmd+W: Prevent from being sent to shell | ||
| if ( | ||
| e.key === "w" && | ||
| e.metaKey && | ||
| !e.ctrlKey && | ||
| !e.altKey && | ||
| !e.shiftKey | ||
| ) { | ||
| e.preventDefault(); | ||
| return false; | ||
| } | ||
|
|
||
| return true; | ||
| }); | ||
|
|
||
| // Load addons | ||
| const webLinksAddon = new WebLinksAddon((event, uri) => { | ||
| event.preventDefault(); | ||
| // Open external links in default browser | ||
| window.open(uri, "_blank"); | ||
| }); | ||
| term.loadAddon(webLinksAddon); | ||
|
|
||
| const fitAddon = new FitAddon(); | ||
| term.loadAddon(fitAddon); | ||
| fitAddonRef.current = fitAddon; | ||
|
|
||
| const searchAddon = new SearchAddon(); | ||
| term.loadAddon(searchAddon); | ||
|
|
||
| // Custom fit function | ||
| const customFit = () => { | ||
| if (isDisposed || !containerRef.current) return; | ||
|
|
||
| try { | ||
| const rect = containerRef.current.getBoundingClientRect(); | ||
| if (rect.width <= 0 || rect.height <= 0) return; | ||
|
|
||
| const dimensions = fitAddon.proposeDimensions(); | ||
| if (dimensions) { | ||
| term.resize(dimensions.cols, dimensions.rows); | ||
| } | ||
| } catch (error) { | ||
| // Ignore dimension errors during terminal initialization | ||
| console.debug("Terminal fit error (expected during init):", error); | ||
| } | ||
| }; | ||
|
|
||
| // Perform initial fit after a small delay to ensure terminal is ready | ||
| setTimeout(() => { | ||
| if (!isDisposed) { | ||
| customFit(); | ||
| } | ||
| }, 0); | ||
|
|
||
| // Handle mouse wheel scrolling (disabled for now since we're using mock terminal) | ||
| // TODO: Re-enable when real terminal is implemented | ||
| term.attachCustomWheelEventHandler(() => { | ||
| // Allow default xterm scrolling behavior for now | ||
| return true; | ||
| }); | ||
|
|
||
| // Create terminal session | ||
| const dimensions = fitAddon.proposeDimensions(); | ||
| const cols = dimensions?.cols || 80; | ||
| const rows = dimensions?.rows || 30; | ||
|
|
||
| createTerminal.mutate({ | ||
| id: terminalId, | ||
| cwd, | ||
| cols, | ||
| rows, | ||
| }); | ||
|
|
||
| // Handle resize with debouncing | ||
| let resizeTimeout: ReturnType<typeof setTimeout> | null = null; | ||
| const handleResize = () => { | ||
| if (resizeTimeout) { | ||
| clearTimeout(resizeTimeout); | ||
| } | ||
|
|
||
| resizeTimeout = setTimeout(() => { | ||
| if (!isDisposed) { | ||
| customFit(); | ||
| } | ||
| resizeTimeout = null; | ||
| }, 150); | ||
| }; | ||
|
|
||
| const resizeObserver = new ResizeObserver(handleResize); | ||
| resizeObserver.observe(containerRef.current); | ||
| window.addEventListener("resize", handleResize); | ||
|
|
||
| // Write welcome message for mock terminal | ||
| const welcomeMessage = `\x1b[1;36mWelcome to Superset Terminal\x1b[0m\r\n\x1b[90mType any command and press Enter to test (mock mode)\x1b[0m\r\n\r\n$ `; | ||
| term.write(welcomeMessage); | ||
|
|
||
| // Simple mock input handler | ||
| let currentLine = ""; | ||
| term.onData((data) => { | ||
| // Handle Enter key | ||
| if (data === "\r") { | ||
| term.write("\r\n"); | ||
| if (currentLine.trim()) { | ||
| // Mock command execution | ||
| executeCommand.mutate({ | ||
| id: terminalId, | ||
| command: currentLine, | ||
| }); | ||
| term.write( | ||
| `\x1b[90m[Mock] Command "${currentLine}" received\x1b[0m\r\n`, | ||
| ); | ||
| } | ||
| currentLine = ""; | ||
| term.write("$ "); | ||
| } | ||
| // Handle Backspace | ||
| else if (data === "\x7f") { | ||
| if (currentLine.length > 0) { | ||
| currentLine = currentLine.slice(0, -1); | ||
| term.write("\b \b"); | ||
| } | ||
| } | ||
| // Handle Ctrl+C | ||
| else if (data === "\x03") { | ||
| term.write("^C\r\n$ "); | ||
| currentLine = ""; | ||
| } | ||
| // Regular character | ||
| else if (!data.startsWith("\x1b")) { | ||
| currentLine += data; | ||
| term.write(data); | ||
| } | ||
| }); | ||
|
|
||
| // Track current dimensions | ||
| let currentDimensions = { cols: 80, rows: 30 }; | ||
| let resizeSeq = 0; | ||
| let isInitialSetup = true; | ||
|
|
||
| // Delay marking initial setup as complete | ||
| setTimeout(() => { | ||
| isInitialSetup = false; | ||
| }, 100); | ||
|
|
||
| term.onResize(({ cols, rows }) => { | ||
| if (isInitialSetup) return; | ||
|
|
||
| if (currentDimensions.cols === cols && currentDimensions.rows === rows) { | ||
| return; | ||
| } | ||
|
|
||
| currentDimensions = { cols, rows }; | ||
| resizeSeq += 1; | ||
|
|
||
| resizeTerminal.mutate({ | ||
| id: terminalId, | ||
| cols, | ||
| rows, | ||
| seq: resizeSeq, | ||
| }); | ||
| }); | ||
|
|
||
| // Handle focus | ||
| const handleFocus = () => { | ||
| if (onFocus) { | ||
| onFocus(); | ||
| } | ||
| }; | ||
|
|
||
| if (term.textarea) { | ||
| term.textarea.addEventListener("focus", handleFocus); | ||
| } | ||
|
|
||
| setTerminal(term); | ||
|
|
||
| // Cleanup | ||
| return () => { | ||
| isDisposed = true; | ||
|
|
||
| if (resizeTimeout) { | ||
| clearTimeout(resizeTimeout); | ||
| } | ||
|
|
||
| resizeObserver.disconnect(); | ||
| window.removeEventListener("resize", handleResize); | ||
|
|
||
| if (term.textarea) { | ||
| term.textarea.removeEventListener("focus", handleFocus); | ||
| } | ||
|
|
||
| fitAddon.dispose(); | ||
| searchAddon.dispose(); | ||
| webLinksAddon.dispose(); | ||
| term.dispose(); | ||
| }; | ||
| }, [terminalId, cwd, theme, onFocus, createTerminal, resizeTerminal, executeCommand]); |
There was a problem hiding this comment.
🧩 Analysis chain
Effect cleanup disposes the terminal on prop changes and prevents re‑initialization
The main initialization useEffect depends on onFocus (and mutation objects). When onFocus changes identity (e.g., GroupTabPane creates a new handleFocus on each render), React runs the cleanup, which disposes the xterm instance and removes listeners, then re-runs the effect. Because isInitializedRef.current is already true, the body early‑returns and the terminal is never re‑initialized. After any such re-render, the terminal will be disposed and effectively dead.
To make the terminal lifecycle stable:
- Run the initialization effect only once on mount.
- Keep
onFocusin a ref so the textarea focus handler always calls the latest callback without re-running the heavy effect.
For example (outline only):
@@
- const isInitializedRef = useRef(false);
+ const isInitializedRef = useRef(false);
+ const onFocusRef = useRef<(() => void) | undefined>(onFocus);
+
+ useEffect(() => {
+ onFocusRef.current = onFocus;
+ }, [onFocus]);
@@
- // Handle focus
- const handleFocus = () => {
- if (onFocus) {
- onFocus();
- }
- };
+ // Handle focus
+ const handleFocus = () => {
+ onFocusRef.current?.();
+ };
@@
- }, [terminalId, cwd, theme, onFocus, createTerminal, resizeTerminal, executeCommand]);
+ // Intentionally run once on mount; terminal instance and handlers are managed manually.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);This keeps the xterm instance alive for the lifetime of the component while still respecting updated onFocus handlers.
Please verify with a quick interaction test (e.g., toggling active group tabs) that the terminal continues to accept input after parent re-renders once this change is applied.
I'll verify the review comment by examining the codebase to confirm whether onFocus is indeed unstable and causing the described terminal disposal issue.
🏁 Script executed:
#!/bin/bash
# Find where Terminal component is imported and used
rg -n "Terminal" --type=tsx --type=ts | grep -E "(import|from|<Terminal)" | head -20Length of output: 27
🏁 Script executed:
#!/bin/bash
# Look for GroupTabPane to see how it passes onFocus
rg -n "GroupTabPane" --type=tsx --type=ts -A 5 -B 5 | head -50Length of output: 27
🏁 Script executed:
#!/bin/bash
# Find the actual file and parent component that uses Terminal
fd "GroupTabPane" --type f --type=tsx --type=tsLength of output: 170
🏁 Script executed:
#!/bin/bash
# Search for the Terminal component file to confirm location
fd "Terminal.tsx" --type fLength of output: 188
🏁 Script executed:
#!/bin/bash
# Look for handleFocus or onFocus in parent components
rg -n "handleFocus\|onFocus" --type=tsx --type=ts | grep -v "node_modules" | head -30Length of output: 27
---
🏁 Script executed:
```shell
#!/bin/bash
# Find files that import the Terminal component
rg "import.*Terminal" -g "*.ts" -g "*.tsx" -g "*.js" -g "*.jsx" | head -20
Length of output: 2291
🏁 Script executed:
#!/bin/bash
# Look at the parent directory structure to find TabsContent or other parents
find apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent -type f -name "*.tsx" -o -name "*.ts" | head -20Length of output: 1300
🏁 Script executed:
#!/bin/bash
# Check what files exist in the TabsContent directory
ls -la apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Length of output: 691
🏁 Script executed:
#!/bin/bash
# Look for where Terminal is instantiated with onFocus prop
rg "onFocus" -g "*.tsx" -g "*.ts" -A 2 -B 2 | head -50Length of output: 4639
🏁 Script executed:
#!/bin/bash
# Look for GroupTabPane specifically
find apps -type f -name "*GroupTab*" -o -name "*group-tab*" | head -10Length of output: 240
---
🏁 Script executed:
```shell
#!/bin/bash
# Read GroupTabPane.tsx to see how it passes onFocus to Terminal
cat apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/GroupTabView/GroupTabPane.tsx
Length of output: 1655
🏁 Script executed:
#!/bin/bash
# Read SingleTabView.tsx to see how it passes onFocus to Terminal
cat apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/SingleTabView.tsxLength of output: 1212
🏁 Script executed:
#!/bin/bash
# Read the Terminal component signature to see the onFocus prop
cat apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx | head -50Length of output: 1242
---
🏁 Script executed:
```shell
#!/bin/bash
# Read Terminal.tsx focusing on the useEffect dependency array around line 115-355
sed -n '100,365p' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx | tail -20
Length of output: 486
🏁 Script executed:
#!/bin/bash
# Find the exact dependency array of the useEffect at line 115
grep -n "}, \[" apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsxLength of output: 147
Effect cleanup disposes the terminal on prop changes and prevents re‑initialization
The main initialization useEffect (line 355) depends on onFocus and mutation objects. When onFocus changes identity—which happens on every parent render since GroupTabPane and SingleTabView create new handleFocus functions inline—React runs the cleanup, which disposes the xterm instance and removes listeners, then re-runs the effect. Because isInitializedRef.current is already true, the body early‑returns and the terminal is never re‑initialized. After any parent re-render, the terminal will be disposed and effectively dead.
To make the terminal lifecycle stable:
- Run the initialization effect only once on mount.
- Keep
onFocusin a ref so the textarea focus handler always calls the latest callback without re-running the effect.
For example:
- const isInitializedRef = useRef(false);
+ const isInitializedRef = useRef(false);
+ const onFocusRef = useRef<(() => void) | undefined>(onFocus);
+
+ useEffect(() => {
+ onFocusRef.current = onFocus;
+ }, [onFocus]);And update the focus handler:
- const handleFocus = () => {
- if (onFocus) {
- onFocus();
- }
- };
+ const handleFocus = () => {
+ onFocusRef.current?.();
+ };And change the effect to run once:
- }, [terminalId, cwd, theme, onFocus, createTerminal, resizeTerminal, executeCommand]);
+ // Intentionally run once on mount; terminal instance and handlers are managed manually.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);This keeps the xterm instance alive for the lifetime of the component while still respecting updated onFocus handlers.
Committable suggestion skipped: line range outside the PR's diff.
| const webLinksAddon = new WebLinksAddon((event, uri) => { | ||
| event.preventDefault(); | ||
| // Open external links in default browser | ||
| window.open(uri, "_blank"); | ||
| }); | ||
| term.loadAddon(webLinksAddon); |
There was a problem hiding this comment.
🧩 Analysis chain
Opening links with window.open in Electron can be unsafe
Using window.open(uri, "_blank") in the renderer can open untrusted URLs in a new Electron BrowserWindow instead of the system browser, which is a security risk (remote content with app privileges).
Consider routing URLs to the main process and using shell.openExternal (or your existing preload/IPC helper) instead of window.open, e.g.:
- const webLinksAddon = new WebLinksAddon((event, uri) => {
- event.preventDefault();
- // Open external links in default browser
- window.open(uri, "_blank");
- });
+ const webLinksAddon = new WebLinksAddon((event, uri) => {
+ event.preventDefault();
+ // Delegate to main process / preload API to open in the system browser
+ window.electron?.openExternal?.(uri);
+ });(adapt the call to whatever secure bridge you already expose to the renderer).
Please confirm against your Electron security model/documentation that links opened from the terminal are always routed to the system browser and never load arbitrary remote content in a privileged window.
I'll verify this critical security concern by examining the codebase for existing Electron security patterns and consulting Electron documentation.
</web_search>
🏁 Script executed:
#!/bin/bash
# Search for preload scripts and IPC setup
fd -t f -e ts -e js -e tsx -e jsx | head -20
fd -name "*preload*" -o -name "*ipc*"Length of output: 917
🏁 Script executed:
#!/bin/bash
# Search for existing openExternal usage
rg -n "openExternal\|shell\.open" --type=ts --type=tsx -C3Length of output: 27
🏁 Script executed:
#!/bin/bash
# Search for window.electron pattern or similar bridge
rg -n "window\.electron\|contextBridge" --type=ts --type=tsx --type=js -C2Length of output: 27
🏁 Script executed:
#!/bin/bash
# Check the main Electron entry point and IPC handlers
fd -name "main.ts" -o -name "main.js" | head -5Length of output: 230
🏁 Script executed:
#!/bin/bash
# Search for other window.open usage in the codebase
rg -n "window\.open" --type=ts --type=tsx -C2Length of output: 27
🏁 Script executed:
#!/bin/bash
# Look for BrowserWindow configuration
rg -n "new BrowserWindow" --type=ts --type=tsx --type=js -C3Length of output: 27
🏁 Script executed:
#!/bin/bash
# Check package.json or similar for Electron version
fd -name "package.json" | xargs grep -l "electron" | head -3Length of output: 230
🏁 Script executed:
#!/bin/bash
# Find preload file and check its exports
find . -type f \( -name "*preload*" \) -exec cat {} \; 2>/dev/null | head -100Length of output: 0
🏁 Script executed:
#!/bin/bash
# Look for IPC event handlers related to opening links
rg -n "ipcMain\|ipcRenderer" --type=ts --type=tsx --type=js -C3 | head -50Length of output: 27
🏁 Script executed:
#!/bin/bash
# Check if there's an existing openExternal handler or similar
rg -n "openExternal\|open.*external\|shell\." --type=ts --type=tsx --type=js | head -30Length of output: 27
🏁 Script executed:
#!/bin/bash
# Locate the main process entry point
find . -type f -name "*.ts" -o -name "*.js" | xargs grep -l "app.on.*ready\|createWindow" | grep -i main | head -5Length of output: 213
🏁 Script executed:
#!/bin/bash
# Check Electron version in package.json
cat package.json 2>/dev/null | grep -A2 '"electron'Length of output: 0
🏁 Script executed:
#!/bin/bash
# Search for WebLinksAddon usage context and surrounding code
rg -n "WebLinksAddon" --type=ts --type=tsx -B5 -A10Length of output: 27
🏁 Script executed:
#!/bin/bash
# Look for Terminal.tsx and understand the component context
cat apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx 2>/dev/null | head -200Length of output: 5003
🏁 Script executed:
#!/bin/bash
# Check for any security-related comments or configurations
rg -n "security\|CSP\|sandbox" --type=ts --type=tsx --type=js -i | head -20Length of output: 27
🏁 Script executed:
#!/bin/bash
# Look for window configuration and security settings
rg -n "preload\|nodeIntegration\|contextIsolation\|sandboxMode" --type=ts --type=tsx --type=js -C2Length of output: 27
🏁 Script executed:
#!/bin/bash
# Check if electron is imported anywhere for shell usage
rg -n "require.*electron\|import.*electron" --type=ts --type=tsx --type=js | head -20Length of output: 27
🏁 Script executed:
#!/bin/bash
# Search for any existing link opening handlers
rg -n "href.*open\|link.*open\|openUrl\|navigate.*http" --type=ts --type=tsx -i -C2Length of output: 27
🏁 Script executed:
#!/bin/bash
# Look in the main process directory
find . -path "*/main/*" -o -path "*/electron/*" | grep -E "\.(ts|js)$" | head -20Length of output: 1595
🏁 Script executed:
#!/bin/bash
# Search for all IPC calls related to opening things
rg -n "send\(.*open\|invoke\(.*open" --type=ts --type=tsx -iLength of output: 27
🏁 Script executed:
#!/bin/bash
# Check for build or src structure
ls -la apps/desktop/src/ 2>/dev/nullLength of output: 439
🏁 Script executed:
#!/bin/bash
# Look for main process files
find apps/desktop -name "*main*" -type f 2>/dev/nullLength of output: 37
🏁 Script executed:
#!/bin/bash
# Get full Terminal.tsx file to understand context
wc -l apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx 2>/dev/nullLength of output: 113
🏁 Script executed:
#!/bin/bash
# Check the Terminal component more carefully around the WebLinksAddon
sed -n '160,195p' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx 2>/dev/nullLength of output: 796
🏁 Script executed:
#!/bin/bash
# Look for any preload or main process setup in src directory
find apps/desktop/src -type f \( -name "*main*" -o -name "*preload*" \) 2>/dev/nullLength of output: 37
🏁 Script executed:
#!/bin/bash
# Check for any electron related files in the project
find apps/desktop -type f -name "*.ts" -o -name "*.js" | xargs grep -l "ipcMain\|BrowserWindow" 2>/dev/null | head -10Length of output: 369
🏁 Script executed:
#!/bin/bash
# Look at the app structure
ls -la apps/desktop/ 2>/dev/nullLength of output: 1052
🏁 Script executed:
#!/bin/bash
# Find potential main/preload entry points
find . -type f \( -name "main.ts" -o -name "preload.ts" -o -name "index.ts" \) | grep -E "(main|preload)" | head -10Length of output: 511
🏁 Script executed:
#!/bin/bash
# Check root directory structure
ls -la | head -20Length of output: 1192
🏁 Script executed:
#!/bin/bash
# Search across entire repo for BrowserWindow setup
rg -n "new BrowserWindow" -t ts -t jsLength of output: 221
🏁 Script executed:
#!/bin/bash
# Look for any electron setup or entry points
rg -n "app\.on\(" -t ts -t jsLength of output: 1157
🏁 Script executed:
#!/bin/bash
# Find where electron is actually used
rg -n "from.*electron\|require.*electron" -t ts -t js | head -20Length of output: 0
🏁 Script executed:
#!/bin/bash
# Check the actual imports in Terminal.tsx
head -50 apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx 2>/dev/nullLength of output: 1242
🏁 Script executed:
#!/bin/bash
# Look for IPC setup anywhere
find . -type f \( -name "*.ts" -o -name "*.js" \) -exec grep -l "ipcMain\|ipcRenderer" {} \; 2>/dev/null | head -10Length of output: 452
🏁 Script executed:
#!/bin/bash
# Get a tree of the apps structure
find apps -maxdepth 3 -type d | head -30Length of output: 560
🏁 Script executed:
#!/bin/bash
# Check if there's a src/main or src/preload
ls -la apps/desktop/src/main 2>/dev/null || echo "No main directory"
ls -la apps/desktop/src/preload 2>/dev/null || echo "No preload directory"Length of output: 447
🏁 Script executed:
#!/bin/bash
# Search for shell.openExternal in entire repo
rg -n "shell\.openExternal" -t ts -t jsLength of output: 324
🏁 Script executed:
#!/bin/bash
# Look for file with webPreferences, nodeIntegration, etc
rg -n "webPreferences\|nodeIntegration\|preload:" -t ts -t js -C3Length of output: 0
🏁 Script executed:
#!/bin/bash
# Check package.json content for structure and dependencies
cat package.json 2>/dev/null | head -50Length of output: 1374
🏁 Script executed:
#!/bin/bash
# Look for all .ts/.tsx/.js files in apps/desktop
find apps/desktop -type f \( -name "*.ts" -o -name "*.tsx" -o -name "*.js" \) | sort | head -50Length of output: 2570
🏁 Script executed:
#!/bin/bash
# Search for where the app is initialized or the main process
find . -type f -name "*.ts" -o -name "*.js" | xargs grep -l "createBrowserWindow\|app\.whenReady\|app\.on('ready'" 2>/dev/null | head -10Length of output: 69
🏁 Script executed:
#!/bin/bash
# Look for all instances of window in Terminal.tsx
rg -n "window\." apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx 2>/dev/nullLength of output: 148
🏁 Script executed:
#!/bin/bash
# Try to find the main entry point by looking at package.json main field
cat package.json 2>/dev/null | grep -E '"main"|"preload"' -A1 -B1Length of output: 0
🏁 Script executed:
#!/bin/bash
# Check if there are multiple package.json files (monorepo structure)
find . -name "package.json" -type f | head -10Length of output: 265
🏁 Script executed:
#!/bin/bash
# Look at the root and apps/desktop package.json
cat apps/desktop/package.json 2>/dev/null | grep -E '"main"|"electron"' -A2 -B2Length of output: 326
🏁 Script executed:
#!/bin/bash
# Search for window.open in entire codebase to see the pattern
rg -n "window\.open" -t ts -t tsx -t jsLength of output: 27
🏁 Script executed:
#!/bin/bash
# Check for electron contextBridge or preload patterns in all files
rg -n "contextBridge\|preload" -t ts -t js --type=tsxLength of output: 27
🏁 Script executed:
#!/bin/bash
# Look for IPC channel names that might handle external links
rg -n '"open\|channel.*link\|link.*channel' -t ts -t tsx -t js -iLength of output: 27
🏁 Script executed:
#!/bin/bash
# Check if window.electron is referenced anywhere
rg -n "window\.electron\|windowAPI" -t ts -t tsx -t jsLength of output: 27
🏁 Script executed:
#!/bin/bash
# Search for all files that use shell module
rg -n "from.*shell.*|require.*shell" -t ts -t tsx -t jsLength of output: 27
🏁 Script executed:
#!/bin/bash
# Look at what version of electron is used
grep -r "electron" package*.json 2>/dev/null | grep versionLength of output: 0
🏁 Script executed:
#!/bin/bash
# Final check: look for .electron or electron directory
find . -type d -name "*electron*" 2>/dev/nullLength of output: 75
🏁 Script executed:
#!/bin/bash
# Check if there's a taurirc or similar config suggesting it might not be electron
find . -name "*.config.*" -o -name "*rc*" -o -name "tauri.conf.json" 2>/dev/null | head -10Length of output: 395
🏁 Script executed:
#!/bin/bash
# Let me check the imports at the top of Terminal.tsx more carefully
head -100 apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx 2>/dev/null | grep -E "^import|^from"Length of output: 337
🏁 Script executed:
#!/bin/bash
# Check if this is actually a web app or Electron
rg -n "electron\|tauri\|cordova" -t json | head -20Length of output: 0
🏁 Script executed:
#!/bin/bash
# Look at tsconfig or similar to understand the project type
find . -name "tsconfig*.json" | xargs cat 2>/dev/null | head -100Length of output: 2117
🏁 Script executed:
#!/bin/bash
# Check index.html or main entry
find apps/desktop -name "index.html" -o -name "index.tsx" -o -name "main.tsx" 2>/dev/null | head -5Length of output: 331
🏁 Script executed:
#!/bin/bash
# Check the actual content type - is window defined at all?
rg -n "typeof window\|window\s*===" -t ts -t tsx | head -10Length of output: 27
🏁 Script executed:
#!/bin/bash
# Look at the WebLinksAddon usage more carefully - any event.preventDefault() context?
rg -n "WebLinksAddon\|new WebLinksAddon" -t ts -t tsx -B10 -A10Length of output: 27
🏁 Script executed:
#!/bin/bash
# Final: check package.json for the real app type
python3 << 'EOF'
import json
try:
with open('package.json', 'r') as f:
data = json.load(f)
print("Dependencies with 'electron':")
for key in ['dependencies', 'devDependencies']:
if key in data:
for dep, ver in data[key].items():
if 'electron' in dep.lower():
print(f" {dep}: {ver}")
print(f"\nMain field: {data.get('main', 'Not set')}")
except Exception as e:
print(f"Error: {e}")
EOFLength of output: 50
🏁 Script executed:
#!/bin/bash
# Check for any build targets or platform targets
grep -r "electron\|browser\|web" package.json 2>/dev/null | grep -i "build\|target\|platform"Length of output: 0
🏁 Script executed:
#!/bin/bash
# Look for vite or webpack config that might indicate Electron setup
find . -name "vite.config.*" -o -name "webpack.config.*" | xargs cat 2>/dev/null | head -50Length of output: 0
🏁 Script executed:
#!/bin/bash
# Verify this is Electron app - check build or dist structure
ls -la apps/desktop/dist 2>/dev/null || echo "No dist directory found"
ls -la apps/desktop/src 2>/dev/nullLength of output: 463
🏁 Script executed:
#!/bin/bash
# Final comprehensive check for the app framework
rg -n "createRoot\|ReactDOM\|import React" apps/desktop/src/renderer -t ts -t tsx | head -5Length of output: 27
🏁 Script executed:
#!/bin/bash
# Look for the actual app entry
find apps/desktop/src -name "*.tsx" -o -name "*.ts" | xargs grep -l "export.*App\|default export" | head -5Length of output: 228
🏁 Script executed:
#!/bin/bash
# Check if Electron apis are available at all in the renderer
rg -n "require.*electron\|from.*electron" apps/desktop/src/renderer -t ts -t tsxLength of output: 27
🏁 Script executed:
#!/bin/bash
# Look at the actual Terminal file - just show the full thing
cat apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx 2>/dev/nullLength of output: 8829
🏁 Script executed:
#!/bin/bash
# Check the first 50 lines at minimum
head -50 apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx 2>/dev/nullLength of output: 1242
🏁 Script executed:
#!/bin/bash
# Look for all .tsx files in the target directory
ls -la apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/ 2>/dev/nullLength of output: 231
🏁 Script executed:
#!/bin/bash
# Try absolute path checks
stat apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx 2>/dev/null || find . -name "Terminal.tsx" 2>/dev/nullLength of output: 192
🏁 Script executed:
#!/bin/bash
# Check what files actually exist in that directory structure
find apps/desktop/src/renderer/screens -type d | head -20Length of output: 1236
🏁 Script executed:
#!/bin/bash
# List all tsx files to find Terminal
find apps/desktop -name "Terminal.tsx" -o -name "Terminal.ts"Length of output: 109
🏁 Script executed:
#!/bin/bash
# Look for any terminal-related files
find . -iname "*terminal*" -type f 2>/dev/null | head -20Length of output: 649
🏁 Script executed:
#!/bin/bash
# Just list the repo structure to understand it
find . -maxdepth 5 -type f -name "*.tsx" 2>/dev/null | head -30Length of output: 1057
🏁 Script executed:
#!/bin/bash
# Look for the actual project structure
ls -R apps/desktop/src 2>/dev/null | head -100Length of output: 1353
🏁 Script executed:
#!/bin/bash
# Check if there are any files at all that match the pattern
find . -path "*/renderer/screens*" -type d 2>/dev/nullLength of output: 5168
🏁 Script executed:
#!/bin/bash
# List everything in apps/desktop
find apps/desktop -type f -name "*.tsx" 2>/dev/null | head -50Length of output: 3162
🏁 Script executed:
#!/bin/bash
# Even simpler - just list everything
find apps/desktop -type f 2>/dev/null | head -100Length of output: 6825
🏁 Script executed:
#!/bin/bash
# Check monorepo structure
ls -la apps/Length of output: 438
🏁 Script executed:
#!/bin/bash
# Is there actually an apps directory?
ls -la 2>/dev/null | grep -E "^d"Length of output: 465
🏁 Script executed:
#!/bin/bash
# Full directory listing
pwd && find . -maxdepth 2 -type dLength of output: 411
🏁 Script executed:
#!/bin/bash
# What do we actually have
ls -laLength of output: 1384
🏁 Script executed:
#!/bin/bash
# Find all tsx files anywhere
find . -name "*.tsx" 2>/dev/null | head -20Length of output: 763
🏁 Script executed:
#!/bin/bash
# Look for electron mentions
grep -r "window\.open" . --include="*.tsx" --include="*.ts" 2>/dev/nullLength of output: 142
🏁 Script executed:
#!/bin/bash
# Verify repo was cloned
git log --oneline 2>/dev/null | head -3 || echo "No git repo"Length of output: 153
🏁 Script executed:
#!/bin/bash
# Check branches
git branch -a 2>/dev/null | head -5Length of output: 82
🏁 Script executed:
#!/bin/bash
# Check current branch and status
git status 2>/dev/nullLength of output: 62
🏁 Script executed:
#!/bin/bash
# List all files git knows about that match pattern
git ls-files | grep -i terminalLength of output: 789
🏁 Script executed:
#!/bin/bash
# Find the actual file
git ls-files | grep "Terminal"Length of output: 491
🏁 Script executed:
#!/bin/bash
# Search for WebLinksAddon usage
git grep -n "WebLinksAddon" 2>/dev/nullLength of output: 759
🏁 Script executed:
#!/bin/bash
# Get everything from the working directory
git ls-files 2>/dev/null | head -100Length of output: 3309
🏁 Script executed:
#!/bin/bash
# Check if we're in the right place
git log --name-only --oneline 2>/dev/null | grep -i "terminal\|window" | head -10Length of output: 616
🏁 Script executed:
#!/bin/bash
# Try to find where the change actually is
git diff HEAD^ HEAD --name-only 2>/dev/nullLength of output: 888
🏁 Script executed:
#!/bin/bash
# Show the diff for the mentioned file
git diff HEAD -- "*Terminal.tsx" 2>/dev/null | head -100Length of output: 0
🏁 Script executed:
#!/bin/bash
# Look at recent changes
git log -5 --name-only 2>/dev/nullLength of output: 7958
🏁 Script executed:
#!/bin/bash
# Show all changed files in the current branch
git diff main... --name-only 2>/dev/nullLength of output: 888
🏁 Script executed:
#!/bin/bash
# Check what files are in the PR
git status --porcelain 2>/dev/nullLength of output: 0
🏁 Script executed:
#!/bin/bash
# List everything that's different from main
git diff main --name-only 2>/dev/nullLength of output: 888
🏁 Script executed:
#!/bin/bash
# Show all files in repo
git ls-tree -r HEAD --name-only 2>/dev/null | head -100Length of output: 3309
🏁 Script executed:
#!/bin/bash
# Just look for ANY WebLinksAddon
git grep "WebLinksAddon" 2>/dev/null || grep -r "WebLinksAddon" . 2>/dev/nullLength of output: 743
🏁 Script executed:
#!/bin/bash
# Maybe it's a different terminal - find all components
find . -type f -name "*.tsx" | xargs grep -l "WebLinksAddon" 2>/dev/nullLength of output: 192
🏁 Script executed:
#!/bin/bash
# Check if xterm.js-related files exist
find . -type f | xargs grep -l "xterm\|terminal" 2>/dev/null | head -20Length of output: 974
🏁 Script executed:
#!/bin/bash
# Simple test - does the file exist?
test -f "apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx" && echo "File exists" || echo "File does not exist"
find . -type f | xargs grep -l "window\.open.*_blank" 2>/dev/null | head -10Length of output: 123
🏁 Script executed:
#!/bin/bash
# Last resort - search for the exact code pattern
git grep -n "WebLinksAddon" 2>/dev/nullLength of output: 759
🏁 Script executed:
#!/bin/bash
# Look at what changed if this is a PR branch
git diff --unified=1 2>/dev/null | head -200Length of output: 0
🏁 Script executed:
#!/bin/bash
# Show all changes
git show --stat 2>/dev/nullLength of output: 833
🏁 Script executed:
#!/bin/bash
# Try getting a diff from a specific commit range
git log --oneline -10 2>/dev/nullLength of output: 430
🏁 Script executed:
#!/bin/bash
# Just search everywhere for the code snippet
grep -r "WebLinksAddon" . 2>/dev/null || echo "Not found in repo"Length of output: 753
🏁 Script executed:
#!/bin/bash
# If not in repo, the code is from the diff - search for patterns that would indicate Electron
grep -r "window\.open\|shell\.openExternal\|ipcMain\|ipcRenderer" . --include="*.ts" --include="*.tsx" 2>/dev/null | head -20Length of output: 1965
🏁 Script executed:
#!/bin/bash
# At minimum check what kind of app this is
find . -name "package.json" -exec grep -l "electron\|vite\|react" {} \; | head -5Length of output: 244
🏁 Script executed:
#!/bin/bash
# Check the content
cat package.json 2>/dev/null | grep "electron\|name\|type" | head -10Length of output: 95
🏁 Script executed:
#!/bin/bash
# Check specific package.json files
find . -name "package.json" | head -5 | xargs cat 2>/dev/null | grep -E "electron|main|preload|scripts" -A1 | head -40Length of output: 1142
🏁 Script executed:
#!/bin/bash
# Get package.json content
python3 -c "import json; data=json.load(open('package.json')); print('Has electron:', 'electron' in str(data)); [print(f'{k}: {v}') for k,v in list(data.get('devDependencies', {}).items())[:10]]" 2>/dev/nullLength of output: 71
🏁 Script executed:
#!/bin/bash
# Verify Electron is in the project
cat package.json 2>/dev/null | python3 -m json.tool | grep -i electron -A2 -B2Length of output: 0
🌐 Web query:
Electron window.open security risks renderer process BrowserWindow
💡 Result:
Short summary — risks when renderer calls window.open (creates BrowserWindow) and how to mitigate:
Risks
- Child window accidentally gets Node APIs / full renderer privileges (can execute local code). This has been a real vulnerability in older Electron versions. [1][2]
- window.opener / cross-window access lets an attacker-controlled page manipulate the opener (navigation, DOM, JS) or exfiltrate data. [1]
- Unrestricted popups can open malicious protocols or files, leading to phishing/OS-level actions. [1][4]
- Preload/webview misuse or enabling webviewTag/allowpopups can expose privileged APIs to untrusted content. [2]
- Incorrect defaults or relying on legacy shims (nativeWindowOpen, nodeIntegration flags) can produce surprising privilege differences across Electron versions. [1][3]
Mitigations (recommended)
- Never enable nodeIntegration in windows that load untrusted content; explicitly set nodeIntegration: false. Use contextIsolation: true. [2]
- Run untrusted renderers in the Chromium sandbox (webPreferences.sandbox / --enable-sandbox) or create them as separate, hardened BrowserWindows. [2]
- Use webContents.setWindowOpenHandler (or app.on('web-contents-created')) to intercept window.open/_blank and:
- validate URLs and protocols,
- deny or open externally (shell.openExternal) for untrusted targets,
- explicitly override BrowserWindow options for child windows (ensure node disabled, contextIsolation enabled, minimal preload API). [4]
- Prefer creating child BrowserWindow from the main process with tightly controlled webPreferences rather than relying on default window.open behavior. [1][4]
- Disable webview tag (webviewTag: false) unless strictly necessary; if used, strip preload and handle allowpopups carefully. [2]
- Limit the preload script surface with contextBridge.exposeInMainWorld; export only the minimal, checked APIs. [2]
- Keep Electron up to date and follow security advisories; search releases/changelogs for window.open/nativeWindowOpen fixes. [3]
References
[1] Electron — window.open / BrowserWindow docs. (zeke.github.io)
[2] Electron — sandbox, webPreferences and security best-practices. (freesoftwaredevlopment.github.io)
[3] Electron blog / release notes — historical vulnerability and nativeWindowOpen behavior changes. (electronjs.org)
[4] Electron — setWindowOpenHandler / new-window handling and overrideBrowserWindowOptions guidance. (electronjs.p2hp.com)
If you want, tell me your Electron version and I’ll give concrete code snippets (setWindowOpenHandler + safe BrowserWindow options).
Citations:
- 1: https://zeke.github.io/electron.atom.io/docs/all/?utm_source=openai
- 2: https://freesoftwaredevlopment.github.io/electron/docs/api/sandbox-option.html?utm_source=openai
- 3: https://www.electronjs.org/blog/page/7/?utm_source=openai
- 4: https://electronjs.p2hp.com/docs/latest/breaking-changes?utm_source=openai
🌐 Web query:
Electron shell.openExternal best practices external links
💡 Result:
Short checklist — best practices when using shell.openExternal for external links in Electron:
- Never call openExternal with untrusted/user-controlled input — validate/whitelist URLs and block dangerous protocols (file:, smb:, javascript:, data:, custom app schemes). [1][2][3]
- Centralize handling in main (webContents.setWindowOpenHandler or web-contents-created) and deny default navigation; call shell.openExternal from that trusted handler. [1][4]
- Canonicalize and parse URLs before opening (URL constructor) and enforce HTTPS where appropriate; reject or prompt for non-HTTP(S) schemes. [1][2]
- Rate-limit or require user gesture for protocol launches that may invoke external apps; consider a confirmation dialog for uncommon schemes. [1][3]
- Prefer opening links in the OS browser (shell.openExternal) instead of navigating renderer windows; avoid exposing window or app internals via external sites. [2][4]
- Log and audit external-open events; surface user-facing warnings when opening potentially risky destinations. [1]
- Keep Electron up-to-date and follow the official Security Checklist for new guidance. [1]
Sources: Electron security guidance and shell API docs; research on protocol-handler abuse. [1][2][3][4]
🌐 Web query:
Electron window.open vs shell.openExternal differences
💡 Result:
Short summary — when to use which:
-
window.open (renderer)
- Creates an in‑app window (Electron pairs a native Window with a BrowserWindow under the hood) and returns a Window / BrowserWindowProxy you can script. Use when you want the page to open content inside your Electron app and possibly communicate with the opener. You control behavior via webContents.setWindowOpenHandler() and the features string / BrowserWindow options. [1]
-
shell.openExternal (main or non‑sandboxed renderer)
- Opens the URL with the OS’s default handler (usually the user’s external browser) — outside your app. Returns a Promise and has platform options (e.g., macOS activate). Use when you want links to open in the user’s browser or another native app. [2]
Key differences and security notes
- In‑app vs external: window.open = new in‑app BrowserWindow; shell.openExternal = launches external app. [1][2]
- Control & scripting: window.open returns a proxied window you can script (subject to same‑origin and nativeWindowOpen behavior); shell.openExternal gives no in‑app window to script. [1][2]
- Where to call: window.open is a renderer API (creates web content); shell.openExternal can be called from main or non‑sandboxed renderer. [1][2]
- Security: shell.openExternal can execute OS handlers and is risky with untrusted input (validate/deny untrusted URLs); prefer intercepting window opens and using shell.openExternal from main with checks. [3]
Sources: Electron docs — window.open, shell.openExternal, and Security guide. [1][2][3]
🌐 Web query:
Electron preload script IPC external link handling
💡 Result:
Short recipe + code + security notes.
- Preload — expose a single, validated API (use contextBridge + ipcRenderer.invoke):
-
Example preload.js
const { contextBridge, ipcRenderer } = require('electron')contextBridge.exposeInMainWorld('electronAPI', {
openExternal: (url) => ipcRenderer.invoke('open-external', url)
})
- Main — validate the URL, check sender/origin if needed, then call shell.openExternal:
-
Example main.js
const { app, BrowserWindow, ipcMain, shell } = require('electron')
const { URL } = require('url')ipcMain.handle('open-external', async (event, urlString) => {
try {
const url = new URL(urlString) // throws on invalid URL
if (!['http:', 'https:'].includes(url.protocol)) throw new Error('Invalid protocol')
// Optional: validate event.senderFrame or event.sender.id / webContents.id to ensure request from a trusted window
await shell.openExternal(url.toString())
return { ok: true }
} catch (err) {
return { ok: false, error: String(err) }
}
})
- Renderer usage:
// in page JS
window.electronAPI.openExternal('https://example.com')
Security notes (must-dos)
- Enable contextIsolation and do NOT expose ipcRenderer directly to the page. Use one method per action. (electronjs.org) [1]
- Validate and sanitize the URL (scheme, hostname or allowlist) in the main process before calling shell.openExternal. Don’t call openExternal on arbitrary input from untrusted pages. (electronjs.org) [2]
- Prefer ipcRenderer.invoke + ipcMain.handle (request/response) over exposing send/on directly. Limit the API surface. (electronjs.org) [3][4]
- Optionally verify event.sender / senderFrame to ensure the call originates from a trusted webContents/frame.
References
[1] Electron: Context Isolation (contextBridge best practices). (electronjs.org)
[2] Electron Security checklist (do not use shell.openExternal with untrusted content; validate IPC sender). (electronjs.org)
[3] contextBridge API docs. (electronjs.org)
[4] Preload/tutorial docs (preload sandboxing and examples). (electronjs.org)
If you want, I can produce a complete minimal repo structure or add an allowlist example (hostnames/regex) for stricter validation.
Citations:
- 1: https://www.electronjs.org/docs/latest/tutorial/context-isolation?utm_source=openai
- 2: https://www.electronjs.org/docs/latest/tutorial/security?utm_source=openai
- 3: https://www.electronjs.org/docs/latest/api/context-bridge?utm_source=openai
- 4: https://www.electronjs.org/docs/latest/tutorial/context-isolation?utm_source=openai
- 5: https://www.electronjs.org/docs/latest/tutorial/security?utm_source=openai
- 6: https://www.electronjs.org/docs/latest/api/context-bridge?utm_source=openai
- 7: https://www.electronjs.org/de/docs/latest/tutorial/tutorial-preload?utm_source=openai
🌐 Web query:
Electron security sandbox context isolation window.open
💡 Result:
Short summary and secure recommendations:
-
What happens: window.open in Electron creates a BrowserWindow (or a BrowserWindowProxy) that inherits many webPreferences from the opener (contextIsolation, nodeIntegration, javascript). You can let the main process control/allow/deny and override options via webContents.setWindowOpenHandler(). [1]
-
Context isolation: enabled by default since Electron 12; it runs preload/Electron internals in a separate JS context to prevent page scripts from reaching privileged objects. Do not disable it for untrusted content. [2]
-
Sandbox vs contextIsolation: sandboxed renderer (webPreferences.sandbox) further restricts renderer OS-level privileges; contextIsolation is orthogonal (JS-context separation) and should remain enabled. Both improve security. [2]
-
Native window.open: setting webPreferences.nativeWindowOpen = true uses Chromium’s native semantics (synchronous access to opened Window) but changes semantics/security surface — only enable if you need it and understand opener access. [1]
-
Main risks when opening windows:
- A child window can access window.opener (same-origin) and message the opener (postMessage), giving potential cross-window abuse.
- Inherited prefs (if opener had risky settings) can leak Node or privileged APIs.
- Historical context-isolation bugs have existed — keep Electron up-to-date. (see CVE examples). [3][4]
-
Secure defaults and checklist (apply these together):
- Keep Electron up to date. Patch known contextIsolation vulnerabilities. [4]
- Always: contextIsolation: true, nodeIntegration: false, webPreferences.sandbox where feasible, webSecurity: true. [2][5]
- Use webContents.setWindowOpenHandler() in main to validate/whitelist URLs, return { action: 'deny' } for untrusted targets, or { action: 'allow', overrideBrowserWindowOptions: {...} } to force safe options (disable node, add a preload sandbox API, disable devtools, set outlivesOpener appropriately). [1]
- Avoid nativeWindowOpen unless needed; if used, review opener/child interaction. [1]
- Use a narrow, audited preload exposing only safe APIs via contextBridge (no exposing Node/fs unless necessary). [2]
- Enforce strict Content-Security-Policy and disable allowpopups for . [5]
- Limit navigation and external-opening: intercept links and use shell.openExternal() only for vetted URLs. [5]
-
Minimal example (concept):
- In main:
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
if (!isAllowedUrl(url)) return { action: 'deny' }
return {
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: pathToSafePreload,
sandbox: true
},
devTools: false
}
}
}) - In preload: expose limited API via contextBridge.
- In main:
Sources:
[1] Electron docs — Opening windows from the renderer / window.open.
[2] Electron docs — Context Isolation tutorial.
[3] Electron docs — Security recommendations.
[4] Public CVEs / advisories for contextIsolation bypasses (illustrates need to update Electron).
If you want, I can: (A) give a copy-paste-ready main/preload example tailored to your Electron version, or (B) review a snippet of your current window-open handling for insecure patterns.
🌐 Web query:
xterm.js WebLinksAddon Electron security handling
💡 Result:
Short guidance and a safe pattern.
Key points
- xterm.js WebLinksAddon emits link clicks via an activate handler you control — use that to avoid letting the addon open links directly. [1]
- In Electron, never open unvalidated user-controlled URIs from the renderer. Validate/parse and open only from the main process (shell.openExternal) and block in-app navigation/new windows in the main process. [2]
Recommended minimal flow
- Renderer: load WebLinksAddon with a handler that sends the clicked URL to the preload via postMessage/IPC (do not call window APIs that open windows from the renderer). Use a modifier-key check if desired (the addon supports that pattern). [1]
- Preload: forward the URL to the main process via a safe, limited IPC channel (contextIsolation = true, expose only a tiny API).
- Main: parse & validate the URL (use the WHATWG URL parser):
- allow only safe schemes (https:, http:) unless you explicitly whitelist others
- explicitly block dangerous schemes (file:, data:, javascript:, smb:, magnet:, etc.)
- optionally match hostname whitelist / regex and/or prompt the user
- Main: if validated, call shell.openExternal(url) from the main process (do not call openExternal on raw/unvalidated input). [2]
Hardening (must-dos)
- Disable nodeIntegration in renderer; enable contextIsolation; use a preload script for IPC. [2]
- Register app.webContents handlers in main to deny unexpected navigations/new windows:
- webContents.setWindowOpenHandler(...) — deny and route safe URLs to shell.openExternal. [2]
- listen for webContents.on('will-navigate', ...) and prevent navigation to untrusted URLs.
- Apply a strict Content-Security-Policy for your renderer.
- Log/ratelimit link open requests if relevant.
Minimal code sketches
- xterm WebLinksAddon (renderer/preload): create WebLinksAddon(activateLink) where activateLink posts the URL to preload IPC. [1]
- Main (simplified):
- parse URL: const u = new URL(candidate);
- if (['http:','https:'].includes(u.protocol) && isAllowedHost(u)) shell.openExternal(u.href);
References
- xterm.js link handling / WebLinksAddon docs. [1]
- Electron security recommendations (shell.openExternal cautions, setWindowOpenHandler, prevent navigation, contextIsolation/nodeIntegration guidance). [2]
If you want, I can paste a short secure example (renderer + preload + main) tailored to your Electron version.
🌐 Web query:
Electron trusted URLs sandbox untrusted content
💡 Result:
Short guidance — treat any external URL as untrusted and isolate it. Key controls and best practices:
- Never run remote/untrusted pages with Node.js integration; disable nodeIntegration. [1]
- Enable contextIsolation and enable Chromium process sandboxing for renderers (sandbox: true / app-wide). [1][2]
- Load remote content only over HTTPS and apply a strict Content-Security-Policy. [1]
- Render untrusted sites in isolated containers: use or BrowserView/WebContents with a separate session/partition (not the UI renderer) and no exposed Electron APIs. [1]
- Use ses.setPermissionRequestHandler(...) to deny/allow permissions by origin. [1]
- Disable allowpopups on , prevent or tightly control navigation/new-window events, and avoid shell.openExternal for untrusted links. Validate and allowlist hostnames/URL schemes. [1]
- Prefer custom protocols or a sanitized intermediary that fetches and purifies remote data (serve sanitized HTML/plain text rather than executing remote HTML/JS). Sanitize/escape any content before injecting into your UI. [1][3]
- Keep Electron up-to-date and follow the official security checklist; consider additional sandboxing/OS-level isolation for high-risk content. [1][3]
Relevant references: Electron security checklist and sandbox docs; security writeups on hosting untrusted web content. [1] Electron Security Guide. [2] Electron Process Sandboxing. [3] NCC Group “Avoiding Pitfalls Developing with Electron.”
🌐 Web query:
Electron BrowserWindow privileges renderer links
💡 Result:
Short answer: renderer code runs with limited (but configurable) privileges — the BrowserWindow/main process holds higher privileges. Treat any links or external content in the renderer as untrusted and prevent privilege escalation by disabling Node in the renderer, using a secure preload for controlled IPC, and handling link-opening from the main process (or via safe APIs). Key measures:
- BrowserWindow / webPreferences
- Disable Node and remote in renderers: nodeIntegration: false, enableRemoteModule: false. Use contextIsolation: true and sandbox when appropriate. [1][2][3]
- Use a preload script + IPC
- Expose a minimal, vetted API from preload (contextBridge) and keep all privileged APIs in the main process. Validate/whitelist URLs in the main before acting. [1]
- Handle links safely
- Don’t let renderer directly open privileged APIs. For external links, either:
- Call main to open with shell.openExternal after validating the URL; or
- Intercept window.open/new-window via BrowserWindow.setWindowOpenHandler (or nativeWindowOpen behavior) and open trusted URLs externally. Validate and normalize URLs to avoid javascript: or data: schemes. [2]
- Prevent tabnabbing / opener attacks
- For anchor tags opened in new windows, add rel="noopener noreferrer" (or ensure target=_blank is handled so window.opener is not exposed). Don’t rely solely on client-side removal. [4][5]
- Content security & other hardening
- Enforce a strict Content-Security-Policy for renderers, disable devtools in production, keep Electron up-to-date, and avoid loading remote/untrusted content into non-sandboxed renderers. [1]
If you want, I can show minimal example code (BrowserWindow webPreferences + preload + setWindowOpenHandler and main-side shell.openExternal) for your Electron version — tell me which Electron version you’re using.
Delegate external link opening to main process via existing IPC pattern
The concern is valid. xterm.js WebLinksAddon in Electron can detect URLs from terminal output (which may be untrusted content from git, shells, or remote sources), and window.open(uri, "_blank") in the renderer poses security risks. The recommended approach is to validate URLs and use shell.openExternal() from the main process rather than allowing the renderer to open windows directly.
Your codebase already has a secure IPC foundation: apps/desktop/src/preload/index.ts exposes ipcRenderer via contextBridge, and apps/desktop/src/main/lib/storage-ipcs.ts demonstrates the existing pattern (ipcMain.handle()). Route the link through this infrastructure instead of window.open:
- Add an
ipcMain.handle('open-external', ...)handler in the main process that validates the URL (scheme, protocol, optional allowlist) and callsshell.openExternal(). - Expose an
openExternalmethod in the preload viacontextBridge. - In Terminal.tsx line 175–180, replace
window.open(uri, "_blank")withwindow.ipcRenderer.invoke('open-external', uri).
🤖 Prompt for AI Agents
In
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
around lines 175–180, the renderer currently calls window.open(uri, "_blank")
which is unsafe for untrusted terminal output; instead, add an
ipcMain.handle('open-external', handler) in the main process that validates the
URI (check scheme/protocol, optional allowlist) and calls shell.openExternal(),
expose a safe openExternal/invoke wrapper in the preload via contextBridge
(e.g., window.ipcRenderer.invoke or a dedicated method), and replace the
window.open call in Terminal.tsx with a call to the exposed IPC method (invoke
'open-external' with the uri) so link opening is validated and performed in the
main process.
| <div | ||
| role="button" | ||
| tabIndex={-1} | ||
| onClick={handleToggleExpand} | ||
| onDoubleClick={(e) => { | ||
| e.stopPropagation(); | ||
| e.preventDefault(); | ||
| }} | ||
| onKeyDown={(e) => { | ||
| if (e.key === "Enter" || e.key === " ") { | ||
| e.preventDefault(); | ||
| handleToggleExpand(e as unknown as React.MouseEvent); | ||
| } | ||
| }} | ||
| className="shrink-0 cursor-pointer hover:opacity-80" | ||
| > | ||
| <HiChevronRight | ||
| className={`size-4 transition-transform ${isExpanded ? "rotate-90" : ""}`} | ||
| /> | ||
| </button> | ||
| </div> |
There was a problem hiding this comment.
Accessibility regression: div role="button" with tabIndex={-1} breaks keyboard navigation.
Replacing native <button> elements with <div role="button" tabIndex={-1}> introduces several critical accessibility issues:
- tabIndex={-1} removes keyboard focusability—users cannot Tab to these controls
- The onKeyDown handlers will never fire because the elements cannot receive focus
- Native button semantics (screen reader announcements, built-in keyboard support) are lost
- Line 130 contains an unsafe type cast:
handleToggleExpand(e as unknown as React.MouseEvent)
If nested interactive elements were causing issues (buttons inside the parent <Button>), the correct solution is to restructure the component—not to replace semantic HTML with divs. Consider:
- Moving interactive controls outside the parent Button
- Using click handlers on non-button elements without role="button"
- Keeping native
<button>elements and preventing event propagation properly
Apply this diff to restore native buttons with proper keyboard accessibility:
{isGroupTab && hasChildren && (
- <div
- role="button"
- tabIndex={-1}
+ <button
+ type="button"
onClick={handleToggleExpand}
onDoubleClick={(e) => {
e.stopPropagation();
e.preventDefault();
}}
- onKeyDown={(e) => {
- if (e.key === "Enter" || e.key === " ") {
- e.preventDefault();
- handleToggleExpand(e as unknown as React.MouseEvent);
- }
- }}
className="shrink-0 cursor-pointer hover:opacity-80"
>
<HiChevronRight
className={`size-4 transition-transform ${isExpanded ? "rotate-90" : ""}`}
/>
- </div>
+ </button>
)} {!isGroupTab && (
- <div
- role="button"
- tabIndex={-1}
+ <button
+ type="button"
onClick={handleRemoveTab}
- onKeyDown={(e) => {
- if (e.key === "Enter" || e.key === " ") {
- e.preventDefault();
- handleRemoveTab();
- }
- }}
className="cursor-pointer opacity-0 group-hover:opacity-100 ml-2 text-xs shrink-0"
>
<HiMiniXMark className="size-4" />
- </div>
+ </button>
)}Note: If nested buttons are invalid HTML in your setup, restructure the component so interactive controls are not children of the parent Button element.
Also applies to: 156-169
🤖 Prompt for AI Agents
In
apps/desktop/src/renderer/screens/main/components/WorkspaceView/Sidebar/TabsView/TabItem/index.tsx
around lines 119-138 (and similarly 156-169), the code uses a div with
role="button" and tabIndex={-1} which breaks keyboard accessibility and includes
an unsafe cast for the event; replace the div with a native <button> element (or
move the interactive control out of any parent <button> to avoid nested
buttons), remove tabIndex={-1} so the control is focusable, keep
event.stopPropagation()/preventDefault() on doubleClick and click as needed,
wire handleToggleExpand to the button's onClick without casting the event
(accept a MouseEvent), and remove the onKeyDown hack since native buttons
provide proper keyboard handling; if restructuring is required due to nested
interactive elements, reposition the expand control outside the parent Button to
preserve valid HTML semantics and accessibility.
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/SingleTabView.tsx(3 hunks)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
🧰 Additional context used
🧬 Code graph analysis (1)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/SingleTabView.tsx (3)
apps/desktop/src/renderer/stores/tabs/hooks.ts (1)
useSetActiveTab(10-11)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabContentContextMenu.tsx (1)
TabContentContextMenu(17-40)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (1)
Terminal(1-3)
🔇 Additional comments (1)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/SingleTabView.tsx (1)
4-4: Active-tab focus wiring looks correct and cohesive with the tabs store
useSetActiveTabplushandleFocuscallingsetActiveTab(tab.workspaceId, tab.id)is a clean way to keep the store in sync with whichever pane’s terminal currently has focus. This should play nicely with split panes as long as eachtab.idis unique within a workspace.No changes needed here from my side.
Also applies to: 20-20, 34-36
| <div className="w-full h-full overflow-hidden bg-background"> | ||
| <Terminal | ||
| terminalId={tab.id} | ||
| cwd="~" | ||
| onFocus={handleFocus} | ||
| /> |
There was a problem hiding this comment.
Terminal props contract currently mismatches implementation and focus may be ignored
In SingleTabView the Terminal is used as:
<Terminal
terminalId={tab.id}
cwd="~"
onFocus={handleFocus}
/>But the provided Terminal.tsx implementation is:
export const Terminal = () => {
return <div>Terminal</div>;
};So currently:
- TypeScript will see
Terminalas taking no props (or{}), makingterminalId,cwd, andonFocusinvalid props. - Even at runtime,
onFocus={handleFocus}is never wired to any DOM node, so focusing the terminal won’t activate the tab as intended. cwd="~"is a hard-coded placeholder and doesn’t yet reflect the tab/workspace context.
I’d recommend updating Terminal.tsx to accept and forward these props, e.g.:
type TerminalProps = {
terminalId: string;
cwd: string;
onFocus?: () => void;
};
export const Terminal: React.FC<TerminalProps> = ({ terminalId, cwd, onFocus }) => {
return (
<div
data-terminal-id={terminalId}
data-cwd={cwd}
tabIndex={0}
onFocus={onFocus}
>
Terminal
</div>
);
};…and later replace the placeholder cwd="~" here with the actual workspace/tab path when that data is available.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (1)
46-46: WebLinksAddon requires secure link handling via IPC.The default WebLinksAddon behavior may open links directly in the renderer, which is unsafe in Electron—terminal output is untrusted and could contain malicious URLs. Past review provided comprehensive guidance: validate URLs in the main process and use
shell.openExternal()instead of allowing renderer-side window creation.Provide a custom handler that routes links through your existing IPC infrastructure:
- const webLinksAddon = new WebLinksAddon(); + const webLinksAddon = new WebLinksAddon((event, uri) => { + event.preventDefault(); + // Route to main process via IPC for validation and safe opening + window.ipcRenderer?.invoke('open-external', uri); + });Then add an
ipcMain.handle('open-external', ...)handler in the main process that:
- Parses and validates the URL (check scheme, optional allowlist)
- Calls
shell.openExternal(url)only for safe URLsBased on learnings: This matches the security pattern recommended in the past review with detailed Electron documentation references.
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/SingleTabView.tsx (1)
34-36:handleFocusis defined but not wired to Terminal.The function prepares tab activation logic but is currently unused. Once the
Terminalcomponent accepts anonFocusprop (see Terminal.tsx review), passhandleFocushere to enable focus-driven tab activation.Update line 45 when Terminal props are added:
- <Terminal /> + <Terminal + terminalId={tab.id} + cwd={tab.cwd ?? "~"} + onFocus={handleFocus} + />(Adjust
cwdto use the actual workspace/tab path once available in the tab model.)
🧹 Nitpick comments (1)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/GroupTabView/mosaic-theme.css (1)
51-58: Drop target hover styling is visually clear, but consider specificity over !important flags.The new drop target styling provides good visual feedback with the glow effect and border. However, multiple
!importantflags can reduce maintainability. If these are necessary to override mosaic library styles, document why. Otherwise, consider increasing selector specificity instead.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/GroupTabView/GroupTabPane.tsx(1 hunks)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/GroupTabView/mosaic-theme.css(2 hunks)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/SingleTabView.tsx(3 hunks)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/GroupTabView/GroupTabPane.tsx
🧰 Additional context used
🧬 Code graph analysis (2)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (1)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/index.ts (1)
Terminal(1-1)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/SingleTabView.tsx (3)
apps/desktop/src/renderer/stores/tabs/hooks.ts (1)
useSetActiveTab(10-11)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/TabContentContextMenu.tsx (1)
TabContentContextMenu(17-40)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (1)
Terminal(7-107)
🔇 Additional comments (4)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/GroupTabView/mosaic-theme.css (2)
44-47: Verify the CSS selector for the dragging split hover state.The selector
.mosaic-theme-dark .mosaic-split.mosaic-split-dragging .mosaic-split:hoverappears to select a nested.mosaic-splitelement inside another split with the dragging class. This may not be the intended behavior—typically you'd want to style the dragging split itself on hover.Verify this is correct, or consider updating to:
.mosaic-theme-dark .mosaic-split.mosaic-split-dragging:hover { opacity: 1; background: var(--color-border); }
11-21: Verify color variables are defined in the design system.The changes introduce
var(--color-sidebar)andvar(--color-border)for toolbar styling. Ensure these CSS variables are properly defined and align with your design system across the codebase.apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (1)
12-100: Terminal initialization and demo behavior look good for prototype stage.The xterm instance setup is well-structured with proper addon loading, container fitting, and cleanup. The empty dependency array correctly ensures the terminal is created once on mount, and the echo-based input handling effectively demonstrates terminal functionality.
When integrating the tRPC terminal router (referenced in PR objectives), you'll replace the demo input handler (lines 69-86) with bidirectional communication—send input to the backend process and write output/stderr back to the xterm instance.
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/SingleTabView.tsx (1)
44-44: LGTM: overflow-hidden is correct for terminal containers.This change prevents outer scrollbars that would conflict with xterm's internal scrolling buffer, ensuring proper terminal UX.
| import { WebLinksAddon } from "@xterm/addon-web-links"; | ||
| import "@xterm/xterm/css/xterm.css"; | ||
|
|
||
| export const Terminal = () => { |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
Define props interface for Terminal component integration.
The component currently accepts no props, but integration with the tab system requires terminalId, cwd, and onFocus parameters. Without these, the terminal cannot be properly identified, configured with workspace context, or participate in focus/activation flows.
Add a props interface and update the signature:
+interface TerminalProps {
+ terminalId: string;
+ cwd: string;
+ onFocus?: () => void;
+}
+
-export const Terminal = () => {
+export const Terminal = ({ terminalId, cwd, onFocus }: TerminalProps) => {
const terminalRef = useRef<HTMLDivElement>(null);
const xtermRef = useRef<XTerm | null>(null);
const fitAddonRef = useRef<FitAddon | null>(null);Then wire onFocus to the terminal container's focus event and use terminalId/cwd for backend integration when connecting the tRPC terminal router.
🤖 Prompt for AI Agents
In
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
around line 7, the Terminal component currently has no props; add a props
interface (e.g. TerminalProps) exposing terminalId: string, cwd?: string, and
onFocus?: () => void, change the component signature to accept these props, and
pass them through where the component is used. Wire onFocus to the terminal
container’s focus/activation handler (call props.onFocus() when the container
gains focus or is clicked) and use terminalId and cwd when initializing or
connecting the tRPC terminal router/backend so the backend session is
created/selected with the correct terminal identifier and working directory.
Summary by CodeRabbit
New Features
UI/UX Improvements
Accessibility
✏️ Tip: You can customize this high-level summary in your review settings.