Repository navigation
node pty processes - #117
Conversation
|
Warning Rate limit exceeded@Kitenite has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 8 minutes and 27 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (11)
WalkthroughRemove the BrowserWindow argument when composing the workspaces router; replace the mocked terminal router with a TerminalManager-backed implementation and wire terminal session props through the renderer; await DB init at startup and call terminalManager.cleanup() on quit; plus many import/order and small formatting edits. Changes
Sequence Diagram(s)sequenceDiagram
participant R as Renderer (Terminal.tsx)
participant TR as tRPC Terminal Router
participant TM as TerminalManager
participant PT as node-pty
rect rgb(220,235,255)
note over R,TR: create/attach session
R->>TR: createOrAttach({tabId, workspaceId, cols?, rows?})
TR->>TM: createOrAttach(...)
TM->>PT: spawn(...) or reuse pty
PT-->>TM: pty instance
TM-->>TR: { isNew, scrollback }
TR-->>R: { isNew, scrollback }
end
rect rgb(220,255,230)
note over R,TM: I/O and streaming
R->>TR: write({tabId, data})
TR->>TM: write(...)
TM->>PT: pty.write(data)
PT-->>TM: onData(data)
TM->>TR: emit stream events
TR-->>R: stream events (data/exit)
R->>R: xterm.write(data)
end
rect rgb(255,235,220)
note over R,TM: Resize / Detach / Cleanup
R->>TR: resize({tabId, cols, rows})
TR->>TM: resize(...)
TM->>PT: pty.resize(...)
R->>TR: detach({tabId})
TR->>TM: detach(...)
TM->>TM: session kept alive (detached) or killed on cleanup
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Potential focus areas:
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (2 warnings, 1 inconclusive)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (8)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/index.tsx (1)
33-35: Evaluate memoization necessity foractiveTabId.The
activeTabIdcalculation is straightforward, but if this component receives frequent re-renders and theactiveTabIdsobject is large, consider wrapping it inuseMemofor optimization. Currently, it's a simple object access, so memoization may not be needed—verify your performance profile.If profiling shows value, apply:
- const activeTabId = activeWorkspaceId - ? activeTabIds[activeWorkspaceId] - : null; + const activeTabId = useMemo( + () => (activeWorkspaceId ? activeTabIds[activeWorkspaceId] : null), + [activeWorkspaceId, activeTabIds], + );apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/GroupTabView/GroupTabPane.tsx (1)
40-42: Consider wiring or removing the unusedhandleFocuscallback
handleFocusis defined but never used. Either pass it toMosaicWindow(e.g., via an appropriate focus handler) or remove it to avoid dead code.apps/desktop/src/main/index.ts (1)
4-7: DB init before app setup and terminal cleanup hook look good; tighten thebefore-quithandlerInitializing the DB via
await initDb()beforemakeAppSetupis a solid sequencing choice and should prevent accidentaldbaccess before initialization. Thebefore-quithook to callterminalManager.cleanup()is also a good place for process teardown.One minor refinement: the handler is marked
asyncbut doesn’t await anything. To better express intent and, ifcleanupis async, allow awaiting it, you could either:
- Drop
asyncifcleanupis synchronous, or- Use
await terminalManager.cleanup();inside the handler.Either keeps behavior correct but makes the code’s intent clearer.
Also applies to: 34-45
apps/desktop/src/main/lib/terminal-manager.test.ts (1)
24-39: Simplify storing PTY callbacks to avoid self‑referential mocksThe current
onData/onExitmocks mutate their ownmockImplementationand later read backmock.results[0]?.valueto get the callback. This works but is harder to follow and slightly self‑referential:onData: mock((callback) => { mockPty.onData.mockImplementation(() => callback); return callback; }), // later const onDataCallback = mockPty.onData.mock.results[0]?.value;A simpler and clearer approach is to keep explicit variables for the callbacks:
+let onDataCallback: ((data: string) => void) | null = null; +let onExitCallback: ((event: { exitCode: number; signal?: number }) => void) | null = + null; mockPty = { write: mock(() => {}), resize: mock(() => {}), kill: mock(() => {}), - onData: mock((callback: (data: string) => void) => { - mockPty.onData.mockImplementation(() => callback); - return callback; - }), - onExit: mock( - (callback: (event: { exitCode: number; signal?: number }) => void) => { - mockPty.onExit.mockImplementation(() => callback); - return callback; - }, - ), + onData: mock((callback: (data: string) => void) => { + onDataCallback = callback; + }), + onExit: mock( + (callback: (event: { exitCode: number; signal?: number }) => void) => { + onExitCallback = callback; + }, + ), };Then in the tests you can invoke them directly:
onDataCallback?.("test output\n"); onExitCallback?.({ exitCode: 0, signal: undefined });This keeps the tests more straightforward and avoids nested
mockImplementationcalls.Also applies to: 273-311
apps/desktop/src/main/lib/terminal-manager.ts (2)
41-43: Clarify uniqueness assumptions aroundtabId
sessionsis keyed solely bytabId, andcreateOrAttachreuses an existing session for a giventabIdregardless ofworkspaceId:const existing = this.sessions.get(tabId); if (existing?.isAlive) { // ... return { isNew: false, scrollback: existing.scrollback }; }This is fine as long as
tabIdis guaranteed to be globally unique across all workspaces. IftabIdis only unique per‑workspace, you’ll end up reattaching to the wrong session.If there’s any chance of overlap, consider:
- Using a composite key like
${workspaceId}:${tabId}, or- Explicitly documenting that
tabIdmust be globally unique.Also applies to: 61-72, 88-98
75-80: Make shell selection respect the user’s default shellRight now the shell is hardcoded to
"powershell.exe"on Windows and"zsh"elsewhere:const shell = os.platform() === "win32" ? "powershell.exe" : "zsh";On many systems (especially Linux),
zshmay not be installed, or the user’s preferred shell might be something else (bash,fish, etc.). A more robust pattern is to derive this from the environment, e.g.:-const shell = os.platform() === "win32" ? "powershell.exe" : "zsh"; +const shell = + os.platform() === "win32" + ? process.env.COMSPEC || "powershell.exe" + : process.env.SHELL || "zsh";That keeps sensible defaults but falls back to whatever shell the user has configured.
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (1)
58-77: Consider simplifying subscription enablement for readabilityThe subscription uses a ref‑backed
enabledflag:trpc.terminal.stream.useSubscription(tabId, { enabled: isSubscribedRef.current, onData: (event) => { /* ... */ }, });
isSubscribedRef.currentis toggled insideuseEffect, and the component relies on other state changes (e.g., mutation state) to cause a re‑render so thatenabledtransitions fromfalsetotrue. This is a bit indirect and makes it harder to reason about when the subscription is actually live.For clarity, you could:
- Replace
isSubscribedRefwith a small piece of React state, e.g.const [enabled, setEnabled] = useState(false);, and- Set
enabledtotrue/falsein the mount/cleanup paths of the effect, passing that state directly touseSubscription.That keeps the lifecycle explicit and avoids subtle coupling to other hooks’ re‑renders.
apps/desktop/src/lib/trpc/routers/terminal/terminal.ts (1)
27-41: Make behavior explicit when workspace/worktree is missing
createOrAttachcomputescwdfromdb.data.workspacesanddb.data.worktrees, but if either lookup fails you just leavecwdundefined:const workspace = db.data.workspaces.find((w) => w.id === workspaceId); // ... if (worktree) { cwd = worktree.path; }Given
TerminalManagerthen defaultscwdtoos.homedir(), a bad or staleworkspaceIdwould silently drop the user into their home directory instead of the intended project directory.Depending on your UX goals, it might be preferable to:
- Throw a typed TRPC error (e.g. NOT_FOUND) when the workspace/worktree can’t be resolved, or
- At least log a clear warning including
workspaceId/tabIdso it’s obvious something went wrong.That will make debugging misconfigured workspaces noticeably easier.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (32)
apps/desktop/src/lib/trpc/routers/index.ts(1 hunks)apps/desktop/src/lib/trpc/routers/projects/index.ts(1 hunks)apps/desktop/src/lib/trpc/routers/projects/projects.ts(1 hunks)apps/desktop/src/lib/trpc/routers/terminal/terminal.ts(1 hunks)apps/desktop/src/lib/trpc/routers/workspaces/index.ts(1 hunks)apps/desktop/src/lib/trpc/routers/workspaces/utils/git.ts(1 hunks)apps/desktop/src/lib/trpc/routers/workspaces/workspaces.ts(4 hunks)apps/desktop/src/main/index.ts(2 hunks)apps/desktop/src/main/lib/db/index.ts(1 hunks)apps/desktop/src/main/lib/storage-manager.ts(1 hunks)apps/desktop/src/main/lib/terminal-manager.test.ts(1 hunks)apps/desktop/src/main/lib/terminal-manager.ts(1 hunks)apps/desktop/src/preload/index.ts(1 hunks)apps/desktop/src/renderer/react-query/workspaces/index.ts(1 hunks)apps/desktop/src/renderer/screens/main/components/TopBar/WorkspaceTabs/WorkspaceDropdown.tsx(1 hunks)apps/desktop/src/renderer/screens/main/components/TopBar/WorkspaceTabs/WorkspaceGroup.tsx(1 hunks)apps/desktop/src/renderer/screens/main/components/TopBar/WorkspaceTabs/WorkspaceItem.tsx(1 hunks)apps/desktop/src/renderer/screens/main/components/TopBar/WorkspaceTabs/index.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/mosaic-theme.css(1 hunks)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/SingleTabView.tsx(1 hunks)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx(2 hunks)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/index.tsx(1 hunks)apps/desktop/src/renderer/screens/main/components/WorkspaceView/Sidebar/TabsView/TabItem/index.tsx(1 hunks)apps/desktop/src/renderer/screens/main/components/WorkspaceView/Sidebar/TabsView/index.tsx(1 hunks)apps/desktop/src/renderer/screens/main/components/WorkspaceView/index.tsx(3 hunks)apps/desktop/src/renderer/screens/main/index.tsx(2 hunks)apps/desktop/src/renderer/stores/tabs/helpers/active-tab.ts(0 hunks)apps/desktop/src/renderer/stores/tabs/helpers/split-operations.ts(2 hunks)apps/desktop/src/renderer/stores/tabs/helpers/validation.ts(1 hunks)apps/desktop/src/renderer/stores/tabs/hooks.ts(0 hunks)apps/desktop/src/renderer/stores/tabs/store.ts(3 hunks)
💤 Files with no reviewable changes (2)
- apps/desktop/src/renderer/stores/tabs/helpers/active-tab.ts
- apps/desktop/src/renderer/stores/tabs/hooks.ts
🧰 Additional context used
🧬 Code graph analysis (8)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/GroupTabView/GroupTabPane.tsx (1)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (1)
Terminal(32-251)
apps/desktop/src/lib/trpc/routers/workspaces/workspaces.ts (1)
apps/desktop/src/main/lib/db/index.ts (1)
db(19-26)
apps/desktop/src/main/lib/terminal-manager.test.ts (1)
apps/desktop/src/main/lib/terminal-manager.ts (1)
TerminalManager(40-277)
apps/desktop/src/renderer/stores/tabs/helpers/split-operations.ts (1)
apps/desktop/src/shared/types.ts (1)
TabType(23-30)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/SingleTabView.tsx (1)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (1)
Terminal(32-251)
apps/desktop/src/main/index.ts (1)
apps/desktop/src/main/lib/terminal-manager.ts (1)
terminalManager(280-280)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (1)
apps/desktop/src/main/lib/terminal-manager.ts (4)
createOrAttach(48-128)write(133-143)resize(148-168)detach(212-223)
apps/desktop/src/lib/trpc/routers/terminal/terminal.ts (2)
apps/desktop/src/main/lib/db/index.ts (1)
db(19-26)apps/desktop/src/main/lib/terminal-manager.ts (2)
terminalManager(280-280)signal(173-187)
🔇 Additional comments (30)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/GroupTabView/mosaic-theme.css (1)
12-12: Minor whitespace normalization - LGTM.This is a cosmetic cleanup that removes unnecessary whitespace. No functional changes to the stylesheet.
apps/desktop/src/renderer/screens/main/components/TopBar/WorkspaceTabs/WorkspaceDropdown.tsx (1)
8-8: Import organization looks good.The reordering aligns imports with a logical grouping pattern (external UI libs → external non-UI libs → React → internal imports), which aids readability and consistency across the codebase.
Also applies to: 11-11
apps/desktop/src/renderer/screens/main/components/TopBar/WorkspaceTabs/index.tsx (1)
30-44: Workspace navigation hotkeys look solid.The
meta+alt+leftandmeta+alt+righthandlers correctly navigate between workspaces with proper boundary checks. Dependency arrays appropriately captureactiveWorkspaceId,allWorkspaces, andsetActiveWorkspaceto ensure closures have access to current values. The re-registration on group/workspace changes is expected and correct.apps/desktop/src/renderer/screens/main/components/WorkspaceView/index.tsx (2)
1-10: ✓ Import organization improved.Consolidating React imports at the top and grouping internal module imports together aligns with common conventions. All imports are utilized within the component.
38-78: ✓ Hotkey handlers well‑structured with complete dependency arrays.The multiline formatting improves readability, and all dependency arrays are complete:
meta+t: captures[activeWorkspaceId, addTab]meta+w: captures[activeTabId, removeTab]meta+alt+up/down: captures[activeWorkspaceId, activeTabId, tabs, setActiveTab]meta+1-9: captures[activeWorkspaceId, tabs, setActiveTab]No stale-closure risks or missing dependencies detected.
apps/desktop/src/renderer/stores/tabs/helpers/validation.ts (1)
1-1: LGTM! Clean import consolidation.Removing the duplicate import improves code clarity and follows best practices.
apps/desktop/src/main/lib/storage-manager.ts (1)
3-3: LGTM!Import reordering to group node built-in imports before third-party imports improves consistency.
apps/desktop/src/preload/index.ts (1)
77-78: LGTM!Formatting change improves readability without altering behavior.
apps/desktop/src/renderer/screens/main/components/WorkspaceView/Sidebar/TabsView/TabItem/index.tsx (1)
4-4: LGTM! Import consolidation improves code organization.The trpc import has been properly consolidated at the top of the import block, removing duplication and improving maintainability. This aligns with the broader import cleanup effort across the codebase.
apps/desktop/src/renderer/screens/main/index.tsx (2)
4-8: LGTM! Import organization improved.The multi-line import format enhances readability and follows common conventions for grouping related imports.
24-37: LGTM! Hotkey definitions are clean and consistent.The hotkey registrations maintain proper dependencies and conditional logic. String literal formatting is consistent throughout.
apps/desktop/src/renderer/stores/tabs/helpers/split-operations.ts (2)
16-16: LGTM: Formatting improvement for consistency.The selector predicate has been reformatted to a single-line arrow function in both split handlers, improving consistency between the vertical and horizontal split functions.
Also applies to: 38-38
23-23: LGTM: Consistent function call formatting.The
splitPaneInGroupcalls have been reformatted to single-line statements in both split handlers, maintaining the correct arguments and direction parameters.Also applies to: 45-45
apps/desktop/src/renderer/stores/tabs/store.ts (3)
3-3: LGTM!The
electronStorageimport is correctly added and properly used in the persistence configuration on line 133.
18-21: LGTM!The split operations imports are correctly organized and both functions are properly used in the store implementation (lines 121, 127).
32-32: Good practice: explicit type import.Adding the
typekeyword makes it clear this is a type-only import, which helps with tree-shaking and follows TypeScript best practices.apps/desktop/src/renderer/screens/main/components/TopBar/WorkspaceTabs/WorkspaceGroup.tsx (1)
1-2: Import reordering looks goodSeparating the React
useStateimport from the framer‑motion import is stylistic only and has no behavioral impact; the hook usage below remains correct.apps/desktop/src/lib/trpc/routers/workspaces/utils/git.ts (1)
2-3: Node path/simple-git import order change is safeMoving the
joinimport abovesimpleGitis purely cosmetic and does not affect any of the git utility behavior.apps/desktop/src/lib/trpc/routers/projects/projects.ts (1)
2-3: Type-only Electron import and router import order are appropriateSwitching to
import type { BrowserWindow }and separating it from thedialogvalue import, along with the minor router import reordering, is a clean TypeScript/ESM-friendly change with no impact on the projects router behavior.Also applies to: 8-8
apps/desktop/src/renderer/screens/main/components/TopBar/WorkspaceTabs/WorkspaceItem.tsx (1)
5-9: Hook import reordering is non-functionalReordering
useSetActiveWorkspacewithin the React Query workspaces import group is purely organizational and does not affect theWorkspaceItembehavior.apps/desktop/src/renderer/react-query/workspaces/index.ts (1)
4-5: Export list reordering preserves public APIReordering the React Query workspace hook exports (adding
useSetActiveWorkspaceanduseUpdateWorkspaceat the end) keeps the barrel file tidy without changing the exported API.apps/desktop/src/lib/trpc/routers/workspaces/workspaces.ts (1)
2-5: Workspace router changes are formatting-only and look safeImport reordering, the single-line
worktreePathjoin, and the clarifiedprojectshape ingetAllGroupedpreserve existing behavior while improving readability. No issues from these edits.Also applies to: 29-29, 96-96, 104-112
apps/desktop/src/main/lib/db/index.ts (1)
3-3: Import reordering onlyMoving the
JSONFilePresetimport has no behavioral effect; DB initialization and the guardeddbproxy remain unchanged and sound.apps/desktop/src/lib/trpc/routers/projects/index.ts (1)
1-2: Projects router re-exports look goodReordering the type and value exports keeps the API identical and is perfectly fine.
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/GroupTabView/GroupTabPane.tsx (1)
57-57: Terminal now correctly receives per-tab contextPassing
tabIdandworkspaceIdinto<Terminal />aligns this usage with the new terminal API and enables per-tab sessions; this looks correct.apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/index.tsx (1)
3-4: Import cleanup is correctConsolidating the store imports and keeping a single
DropOverlayimport at the top simplifies the module without changing behavior.apps/desktop/src/lib/trpc/routers/workspaces/index.ts (1)
1-2: Workspaces router re-exports are fineExporting
WorkspacesRouterandcreateWorkspacesRouterin this order keeps the public API unchanged; no issues here.apps/desktop/src/lib/trpc/routers/index.ts (1)
5-7: App router wiring matches the new workspaces router signatureImporting
createWorkspacesRouterand calling it without aBrowserWindowargument is consistent with the updated, parameterless factory.createAppRouterstill passeswindowonly to the routers that need it (window,projects), so the composition remains clean and correct.Also applies to: 12-18
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/SingleTabView.tsx (1)
45-45: Terminal props wiring looks correctPassing
tab.idandtab.workspaceIdintoTerminalaligns with the newTerminalPropscontract and the rest of the tab/workspace wiring.apps/desktop/src/main/lib/terminal-manager.test.ts (1)
5-8: No issues found — the mocking pattern is correct and safe.Per Bun's documentation,
mock.restore()resets only function mocks; it does not undo module overrides created bymock.module(). The module mock ofnode-pty(lines 5–7) persists across all tests, sopty.spawnremains a mock throughout. Each test's state is properly isolated:beforeEachcallsmockReturnValue()to refresh the mock behavior, andmock.restore()clears function-level state without affecting the module mock itself. The pattern safely avoids invoking real PTY code and maintains call history isolation between tests.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (1)
32-42: Fix staleisExitedstate so restart‑on‑key works after exit
isExitedis React state but thexterm.onDatahandler is created inside an effect that only depends on[tabId, workspaceId]. The handler therefore closes over the initialisExitedvalue (false) and will never see it change totrueafter an"exit"event from the subscription. As a result, pressing a key after[Press any key to restart]will not actually restart the session.A minimal fix is to mirror the exit state into a ref and read that inside the handler:
export const Terminal = ({ tabId, workspaceId }: TerminalProps) => { const terminalRef = useRef<HTMLDivElement>(null); const xtermRef = useRef<XTerm | null>(null); const fitAddonRef = useRef<FitAddon | null>(null); - const [isExited, setIsExited] = useState(false); + const [isExited, setIsExited] = useState(false); + const isExitedRef = useRef(false); @@ // Subscribe to terminal output trpc.terminal.stream.useSubscription(tabId, { onData: (event) => { if (event.type === "data") { xtermRef.current?.write(event.data); } else if (event.type === "exit") { - setIsExited(true); + isExitedRef.current = true; + setIsExited(true); xtermRef.current?.writeln( `\r\n\r\n[Process exited with code ${event.exitCode}]`, ); xtermRef.current?.writeln("[Press any key to restart]"); } }, }); @@ // Handle user input const disposable = xterm.onData((data) => { - if (isExited) { + if (isExitedRef.current) { // Restart terminal on any key press after exit - setIsExited(false); + isExitedRef.current = false; + setIsExited(false); xterm.clear(); createOrAttach.mutate({ tabId, workspaceId, cols: xterm.cols, rows: xterm.rows, }); } else { // Send input to terminal write.mutate({ tabId, data }); } }); @@ - // Note: Dependencies intentionally minimal to avoid recreating terminal on every state change + // Note: Dependencies intentionally minimal to avoid recreating terminal on every state changeThis keeps the effect deps minimal while making the restart behavior reliable.
Also applies to: 44-57, 136-152, 179-181
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
apps/desktop/src/main/lib/terminal-manager.test.ts(1 hunks)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/desktop/src/main/lib/terminal-manager.test.ts
🧰 Additional context used
🧬 Code graph analysis (1)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (1)
apps/desktop/src/main/lib/terminal-manager.ts (4)
createOrAttach(48-128)write(133-143)resize(148-168)detach(212-223)
🔇 Additional comments (2)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (2)
1-11: Imports, props, and debounce helper look goodThe xterm imports,
TerminalPropsshape, and the genericdebounceutility are all reasonable and self‑contained. No functional issues from this section.Also applies to: 13-30
59-65: Resize/debounce/cleanup wiring is solidUsing a shared debounced
resizemutation,ResizeObserveron the container, and cancelling the debounced call plus detaching the session in the cleanup gives you a clean lifecycle for terminal sizing and backend notifications. This section looks correct and robust.Also applies to: 154-158, 160-164, 169-176
| // Create or attach to terminal session | ||
| createOrAttach.mutate( | ||
| { | ||
| tabId, | ||
| workspaceId, | ||
| cols: xterm.cols, | ||
| rows: xterm.rows, | ||
| }, | ||
| { | ||
| onSuccess: (result) => { | ||
| // Replay scrollback if reattaching to existing session | ||
| if (!result.isNew && result.scrollback.length > 0) { | ||
| // Write history directly - it's already a raw string with ANSI codes | ||
| xterm.write(result.scrollback[0]); | ||
| } | ||
| }, | ||
| }, | ||
| ); |
There was a problem hiding this comment.
Replay the entire scrollback buffer when reattaching, not just the first entry
On successful createOrAttach, you currently do:
if (!result.isNew && result.scrollback.length > 0) {
xterm.write(result.scrollback[0]);
}Since scrollback is a string[] from TerminalManager, this will only restore the first chunk of history and drop the rest when reattaching to an existing session.
Consider writing all chunks, e.g.:
- if (!result.isNew && result.scrollback.length > 0) {
- // Write history directly - it's already a raw string with ANSI codes
- xterm.write(result.scrollback[0]);
- }
+ if (!result.isNew && result.scrollback.length > 0) {
+ // Replay full scrollback (already contains raw ANSI sequences)
+ for (const chunk of result.scrollback) {
+ xterm.write(chunk);
+ }
+ }(or xterm.write(result.scrollback.join(""));), so users get the complete prior terminal output when reconnecting.
🤖 Prompt for AI Agents
In
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
around lines 117 to 134, the reattach logic only writes the first element of
result.scrollback (result.scrollback[0]) so most of the saved history is lost;
update the handler to write the entire scrollback buffer to xterm (e.g., iterate
over result.scrollback and call xterm.write for each chunk or write the joined
string) so the full prior terminal output is restored when reattaching.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (1)
90-103: Replay full scrollback instead of only the first chunk when reattachingOn successful
createOrAttach, onlyresult.scrollback[0]is written, so most of the preserved history is dropped when reconnecting to an existing session:if (!result.isNew && result.scrollback.length > 0) { xterm.write(result.scrollback[0]); }You likely want to replay the entire buffer:
- if (!result.isNew && result.scrollback.length > 0) { - xterm.write(result.scrollback[0]); - } + if (!result.isNew && result.scrollback.length > 0) { + for (const chunk of result.scrollback) { + xterm.write(chunk); + } + }(or equivalently
xterm.write(result.scrollback.join(""));) so users see all previous output when reattaching.
🧹 Nitpick comments (1)
apps/desktop/package.json (1)
52-52: Consider a lighter alternative for debouncing.Adding the full lodash library to handle only debounce in Terminal.tsx may introduce unnecessary bloat. Evaluate whether a smaller, focused utility (e.g.,
just-debounce,tiny-debounce, or custom logic) would be more appropriate.Please verify that lodash is actually required and used across the codebase (not just for Terminal.tsx resize handling), or consider using a minimal debounce implementation instead.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
apps/desktop/package.json(2 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/config.ts(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (2)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/config.ts (2)
TERMINAL_OPTIONS(25-31)RESIZE_DEBOUNCE_MS(33-33)apps/desktop/src/main/lib/terminal-manager.ts (4)
createOrAttach(48-128)write(133-143)resize(148-168)detach(212-223)
🔇 Additional comments (3)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/config.ts (1)
1-33: Config module is cohesive and type‑safeCentralizing the XTerm theme and options in a typed config (using
ITerminalOptions["theme"]andTERMINAL_OPTIONS) plus a shared resize debounce constant keeps the Terminal setup consistent and easy to tweak later. No issues from my side here.apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (1)
31-131: Terminal lifecycle & restart handling look solid overallThe ref‑based
isExitedRefapproach, TRPC stream subscription, debounced resize withResizeObserver+ window listener, and cleanup (dispose, detach, cancel debounce, remove listeners) are all wired together cleanly. Aside from the scrollback issue above, the lifecycle looks robust.apps/desktop/package.json (1)
79-79: Security verification complete — both versions are safe.lodash 4.17.21 is the patched version addressing CVE-2020-28500 and prototype-pollution advisories and has no known vulnerabilities. @types/lodash 4.17.20 has no known security advisories. The versions in this change are appropriate for production use.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
apps/desktop/src/renderer/stores/tabs/store.ts (1)
3-3: Terminal cleanup integration on tab removal is sound; consider gating to terminal tabs onlyWiring
killTerminalForTabintoremoveTabandremoveChildTabFromGroupensures PTY sessions are cleaned up when tabs go away, and the newelectronStoragepersistence hook forTabsStorelooks fine.One thing to be aware of: as written,
killTerminalForTabruns for all tab IDs (including non‑terminal tab types), which will generate benign “session not found” warnings inTerminalManagerfor tabs that never spawned a terminal. If that noise becomes an issue, you could cheaply gate the cleanup by tab type, e.g. resolving the tab fromstate.tabsand only callingkillTerminalForTabwhen its type is the terminal variant (TabType.Terminalor equivalent).This is optional, since the current behavior is functionally correct.
Also applies to: 18-21, 32-33, 47-59, 91-96, 134-136
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
bun.lockis excluded by!**/*.lock
📒 Files selected for processing (5)
apps/desktop/src/main/lib/terminal-manager.ts(1 hunks)apps/desktop/src/renderer/lib/trpc-client.ts(1 hunks)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx(1 hunks)apps/desktop/src/renderer/stores/tabs/store.ts(5 hunks)apps/desktop/src/renderer/stores/tabs/utils/terminal-cleanup.ts(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
apps/desktop/src/renderer/stores/tabs/utils/terminal-cleanup.ts (1)
apps/desktop/src/renderer/lib/trpc-client.ts (1)
trpcClient(9-11)
apps/desktop/src/renderer/stores/tabs/store.ts (1)
apps/desktop/src/renderer/stores/tabs/utils/terminal-cleanup.ts (1)
killTerminalForTab(6-10)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (2)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/config.ts (2)
TERMINAL_OPTIONS(25-31)RESIZE_DEBOUNCE_MS(33-33)apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/index.ts (1)
Terminal(1-1)
🔇 Additional comments (3)
apps/desktop/src/renderer/stores/tabs/utils/terminal-cleanup.ts (1)
1-10:killTerminalForTabis a good, minimal fire‑and‑forget cleanup helperThe standalone client usage and error logging are appropriate for tab‑removal side effects; no further changes needed here.
apps/desktop/src/renderer/lib/trpc-client.ts (1)
1-11: RenderertrpcClientsetup looks correct for non‑React callersThe proxy client configuration with the IPC link and SuperJSON is clear and matches the intended use from stores/utilities.
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (1)
1-149: Terminal component lifecycle and TRPC/xterm wiring look solidThe ref-based wiring for xterm, restart-on-exit logic via
isExitedRef, stream subscription, debounced resize, and detach-on-unmount all fit together coherently; I don’t see functional issues in this component with the new node‑pty backend.
| ptyProcess.onData((data) => { | ||
| this.addToScrollback(session, data); | ||
| this.emit(`data:${tabId}`, data); | ||
| }); | ||
|
|
||
| ptyProcess.onExit(({ exitCode, signal }) => { | ||
| session.isAlive = false; | ||
| this.emit(`exit:${tabId}`, exitCode, signal); | ||
|
|
||
| // Allow reconnection window before cleanup | ||
| setTimeout(() => { | ||
| this.sessions.delete(tabId); | ||
| }, 5000); | ||
| }); |
There was a problem hiding this comment.
🧩 Analysis chain
Fix race where exit-time cleanup can delete a newly restarted session
In the onExit handler you schedule:
setTimeout(() => {
this.sessions.delete(tabId);
}, 5000);If the user restarts the terminal for the same tabId within those 5 seconds, createOrAttach will create a new session and overwrite the map entry—but the original timeout will still fire and unconditionally delete(tabId), wiping out the new live session. Subsequent write/resize calls will then start failing with “session not found or not alive”.
Guard the cleanup so it only deletes the original dead session, for example:
- ptyProcess.onExit(({ exitCode, signal }) => {
- session.isAlive = false;
- this.emit(`exit:${tabId}`, exitCode, signal);
-
- // Allow reconnection window before cleanup
- setTimeout(() => {
- this.sessions.delete(tabId);
- }, 5000);
- });
+ ptyProcess.onExit(({ exitCode, signal }) => {
+ session.isAlive = false;
+ this.emit(`exit:${tabId}`, exitCode, signal);
+
+ // Allow reconnection window before cleanup, but don't delete
+ // a new session that may have been created for the same tabId.
+ setTimeout(() => {
+ const current = this.sessions.get(tabId);
+ if (current === session && !current.isAlive) {
+ this.sessions.delete(tabId);
+ }
+ }, 5000);
+ });This preserves the reconnection window while avoiding accidental deletion of a restarted session.
---
🏁 Script executed:
```shell
#!/bin/bash
# Examine the terminal-manager.ts file structure and the specific code section
fd -e ts -p "terminal-manager.ts" | head -5
Length of output: 45
🏁 Script executed:
#!/bin/bash
# Look for the actual code in terminal-manager.ts
cat "apps/desktop/src/main/lib/terminal-manager.ts" | head -150Length of output: 3325
🏁 Script executed:
#!/bin/bash
# Search for createOrAttach and sessions.delete patterns
rg -n -A5 -B5 "createOrAttach|sessions\.delete|onExit" "apps/desktop/src/main/lib/terminal-manager.ts"Length of output: 1039
Fix race where exit-time cleanup can delete a newly restarted session
In the onExit handler (lines 89–97), you schedule:
setTimeout(() => {
this.sessions.delete(tabId);
}, 5000);If the user restarts the terminal for the same tabId within those 5 seconds, createOrAttach creates a new session and overwrites the map entry at line 99—but the original timeout still fires and unconditionally delete(tabId), wiping out the new live session. Subsequent write/resize calls will then fail with "session not found or not alive".
Guard the cleanup so it only deletes the original dead session:
- ptyProcess.onExit(({ exitCode, signal }) => {
- session.isAlive = false;
- this.emit(`exit:${tabId}`, exitCode, signal);
-
- // Allow reconnection window before cleanup
- setTimeout(() => {
- this.sessions.delete(tabId);
- }, 5000);
- });
+ ptyProcess.onExit(({ exitCode, signal }) => {
+ session.isAlive = false;
+ this.emit(`exit:${tabId}`, exitCode, signal);
+
+ // Allow reconnection window before cleanup, but don't delete
+ // a new session that may have been created for the same tabId.
+ setTimeout(() => {
+ const current = this.sessions.get(tabId);
+ if (current === session && !current.isAlive) {
+ this.sessions.delete(tabId);
+ }
+ }, 5000);
+ });🤖 Prompt for AI Agents
In apps/desktop/src/main/lib/terminal-manager.ts around lines 84 to 97, the
onExit handler schedules an unconditional delete(tabId) after 5s which can race
with a new session created for the same tabId; capture the original session
reference (or a unique token) into a local variable when scheduling the timeout
and, inside the timeout, only delete the tabId if this.sessions.get(tabId)
strictly equals that original session (or token), so a newly created session for
the same tabId is not removed; implement the strict equality check in the
timeout callback to guard the cleanup.
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (1)
147-149: Replay the entire scrollback buffer, not just the first entryThis issue was flagged in a previous review but remains unaddressed. You currently only write
result.scrollback[0], which discards the rest of the saved terminal history when reattaching to an existing session.Apply this diff to restore the complete scrollback:
- if (!result.isNew && result.scrollback.length > 0) { - xterm.write(result.scrollback[0]); - } + if (!result.isNew && result.scrollback.length > 0) { + for (const chunk of result.scrollback) { + xterm.write(chunk); + } + }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
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/config.ts (2)
TERMINAL_OPTIONS(25-31)RESIZE_DEBOUNCE_MS(33-33)
| const restartTerminal = () => { | ||
| isExitedRef.current = false; | ||
| setSubscriptionEnabled(false); | ||
| xterm.clear(); | ||
| createOrAttachRef.current( | ||
| { | ||
| tabId, | ||
| workspaceId, | ||
| cols: xterm.cols, | ||
| rows: xterm.rows, | ||
| }, | ||
| { | ||
| onSuccess: () => { | ||
| setSubscriptionEnabled(true); | ||
| }, | ||
| }, | ||
| ); | ||
| }; |
There was a problem hiding this comment.
Add error handling for terminal restart
If createOrAttach fails during restart (e.g., after the user presses a key following an exit), the terminal will remain cleared with subscription disabled and no recovery path. Consider adding an onError callback to display the error and restore the exit state so the user can retry.
Apply this diff to handle restart failures:
const restartTerminal = () => {
isExitedRef.current = false;
setSubscriptionEnabled(false);
xterm.clear();
createOrAttachRef.current(
{
tabId,
workspaceId,
cols: xterm.cols,
rows: xterm.rows,
},
{
onSuccess: () => {
setSubscriptionEnabled(true);
},
+ onError: (error) => {
+ isExitedRef.current = true;
+ xterm.writeln(`\x1b[31mFailed to restart terminal: ${error.message}\x1b[0m`);
+ xterm.writeln("[Press any key to retry]");
+ },
},
);
};📝 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.
| const restartTerminal = () => { | |
| isExitedRef.current = false; | |
| setSubscriptionEnabled(false); | |
| xterm.clear(); | |
| createOrAttachRef.current( | |
| { | |
| tabId, | |
| workspaceId, | |
| cols: xterm.cols, | |
| rows: xterm.rows, | |
| }, | |
| { | |
| onSuccess: () => { | |
| setSubscriptionEnabled(true); | |
| }, | |
| }, | |
| ); | |
| }; | |
| const restartTerminal = () => { | |
| isExitedRef.current = false; | |
| setSubscriptionEnabled(false); | |
| xterm.clear(); | |
| createOrAttachRef.current( | |
| { | |
| tabId, | |
| workspaceId, | |
| cols: xterm.cols, | |
| rows: xterm.rows, | |
| }, | |
| { | |
| onSuccess: () => { | |
| setSubscriptionEnabled(true); | |
| }, | |
| onError: (error) => { | |
| isExitedRef.current = true; | |
| xterm.writeln(`\x1b[31mFailed to restart terminal: ${error.message}\x1b[0m`); | |
| xterm.writeln("[Press any key to retry]"); | |
| }, | |
| }, | |
| ); | |
| }; |
🤖 Prompt for AI Agents
In
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
around lines 110 to 127, the restartTerminal function disables subscriptions and
clears the xterm but doesn't handle failures from createOrAttach; add an onError
handler to createOrAttachRef.current that logs/shows the error to the user
(e.g., show a toast or render an error), re-enable subscriptionEnabled or
restore isExitedRef.current as appropriate so the terminal isn't left in a
cleared/unrecoverable state, and ensure any cleanup/rollback (like re-enabling
subscriptions or resetting xterm) is performed on error to allow retry.
| createOrAttachRef.current( | ||
| { | ||
| tabId, | ||
| workspaceId, | ||
| cols: xterm.cols, | ||
| rows: xterm.rows, | ||
| }, | ||
| { | ||
| onSuccess: (result) => { | ||
| if (!result.isNew && result.scrollback.length > 0) { | ||
| xterm.write(result.scrollback[0]); | ||
| } | ||
| }, | ||
| }, | ||
| ); |
There was a problem hiding this comment.
Add error handling for the initial attach
If createOrAttach fails on mount, the terminal will remain blank with no feedback to the user and no way to recover. Consider handling onError to display a diagnostic message in the terminal.
Apply this diff to add error handling:
createOrAttachRef.current(
{
tabId,
workspaceId,
cols: xterm.cols,
rows: xterm.rows,
},
{
onSuccess: (result) => {
if (!result.isNew && result.scrollback.length > 0) {
xterm.write(result.scrollback[0]);
}
},
+ onError: (error) => {
+ xterm.writeln(`\r\n\x1b[31mFailed to attach terminal: ${error.message}\x1b[0m`);
+ },
},
);🤖 Prompt for AI Agents
In
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
around lines 138 to 152, the createOrAttachRef.current call does not handle
failure on mount so the terminal can stay blank; add an onError callback to that
second argument which writes a diagnostic message to the xterm (e.g.,
xterm.writeln or xterm.write with a newline), and also log the error to the
console or app logger; ensure the message gives brief recovery guidance (e.g.,
"Failed to attach terminal: <error message> — retry or reload") so the user sees
feedback and you can still surface the raw error for debugging.
Summary by CodeRabbit
New Features
Tests
Refactor
✏️ Tip: You can customize this high-level summary in your review settings.