Skip to content

node pty processes - #117

Merged
Kitenite merged 13 commits into
mainfrom
node-pty-processes
Nov 21, 2025
Merged

Kitenite merged 13 commits into
mainfrom
node-pty-processes

Conversation

@Kitenite

@Kitenite Kitenite commented Nov 21, 2025 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • Full terminal integration: per-tab/workspace terminal sessions with create/attach, live streaming output, input, resize, signals, detach/kill, and preserved scrollback.
    • Renderer adds an IPC-backed client for calling backend procedures; terminal UI theme/options exposed.
  • Tests

    • Comprehensive terminal test suite covering lifecycle, IO, resize, signals, detach/kill, events, and cleanup.
  • Refactor

    • App startup now initializes storage/db before UI and performs terminal cleanup on quit; tab removal triggers terminal cleanup.

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

@coderabbitai

coderabbitai Bot commented Nov 21, 2025 •

Copy link
Copy Markdown
Contributor

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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.

📥 Commits

Reviewing files that changed from the base of the PR and between 758834a and df859f8.

📒 Files selected for processing (11)
  • 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/workspaces.ts (4 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/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)
  • apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/helpers.ts (1 hunks)
  • apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/types.ts (1 hunks)
  • apps/desktop/src/renderer/stores/tabs/store.test.ts (1 hunks)
  • apps/desktop/test-setup.ts (1 hunks)

Walkthrough

Remove 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

Cohort / File(s) Summary
Terminal manager & tests
apps/desktop/src/main/lib/terminal-manager.ts, apps/desktop/src/main/lib/terminal-manager.test.ts
Adds a TerminalManager singleton managing pty sessions (createOrAttach, write, resize, signal, kill, detach, getSession, cleanup), scrollback buffering, event callbacks, and unit tests with a mocked pty.
tRPC terminal router
apps/desktop/src/lib/trpc/routers/terminal/terminal.ts
Replaces mocked terminal router with procedures backed by terminalManager and db: createOrAttach, write, resize, signal, kill, detach, getSession, and stream (observable).
Terminal UI & config
apps/desktop/src/renderer/.../Terminal/Terminal.tsx, apps/desktop/src/renderer/.../Terminal/config.ts
Makes Terminal prop-driven (tabId, workspaceId), integrates createOrAttach, stream subscription, debounced resize, write/detach flows, lifecycle cleanup, and adds terminal config constants.
Terminal usage wiring
apps/desktop/src/renderer/.../SingleTabView.tsx, apps/desktop/src/renderer/.../GroupTabPane.tsx
Passes tabId and workspaceId props into Terminal where rendered.
App startup & DB
apps/desktop/src/main/index.ts, apps/desktop/src/main/lib/db/index.ts, apps/desktop/src/main/lib/storage-manager.ts
Import terminalManager and initDb; await initDb() during startup and call terminalManager.cleanup() on app quit; minor import reorderings.
Workspaces router composition
apps/desktop/src/lib/trpc/routers/index.ts, apps/desktop/src/lib/trpc/routers/workspaces/index.ts, apps/desktop/src/lib/trpc/routers/workspaces/workspaces.ts, apps/desktop/src/lib/trpc/routers/workspaces/utils/git.ts
Stop passing BrowserWindow into workspaces router (createWorkspacesRouter() is now parameterless); small import/format changes.
Projects router & misc routers
apps/desktop/src/lib/trpc/routers/projects/*
Import/export reordering only; no behavior change.
Renderer stores & tabs helpers
apps/desktop/src/renderer/stores/tabs/store.ts, apps/desktop/src/renderer/stores/tabs/helpers/*, apps/desktop/src/renderer/stores/tabs/hooks.ts
Consolidates imports, wires split handlers, invokes killTerminalForTab on tab removal, and applies minor formatting changes.
Renderer tRPC client & terminal-cleanup util
apps/desktop/src/renderer/lib/trpc-client.ts, apps/desktop/src/renderer/stores/tabs/utils/terminal-cleanup.ts
Adds renderer-side tRPC proxy trpcClient and killTerminalForTab helper that calls trpcClient.terminal.kill.mutate.
Views, hotkeys & import cleanup
apps/desktop/src/renderer/screens/main/**, apps/desktop/src/preload/index.ts, apps/desktop/src/renderer/react-query/workspaces/index.ts
Widespread import/order and formatting edits, consolidated useHotkeys calls, quote-style tweaks, duplicate import removals; no functional changes except Terminal prop wiring.
Package & miscellaneous
apps/desktop/package.json, various CSS and small files
Adds lodash and @types/lodash; many whitespace/import-order edits across files.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Potential focus areas:

  • apps/desktop/src/main/lib/terminal-manager.ts — session lifecycle, scrollback bounds, event listener cleanup, env/platform handling.
  • apps/desktop/src/lib/trpc/routers/terminal/terminal.ts — observable lifecycle, subscription cleanup, db interactions and error propagation.
  • apps/desktop/src/renderer/.../Terminal/Terminal.tsx — mount/attach sequencing, resize debounce, FitAddon usage, teardown on unmount.
  • apps/desktop/src/main/index.ts — ensure initDb() await and terminalManager.cleanup() ordering.

Possibly related PRs

  • xterm ui #115 — prior terminal router and renderer scaffolding; directly relates to replacing the mocked terminal router with a TerminalManager-backed implementation.
  • Manage workspaces using trpc/lowdb, implement recent projects #112 — changes to workspaces router composition and createWorkspacesRouter signature; directly related to removal of BrowserWindow argument.
  • mosaic fix #66 — earlier Terminal component prop/API changes; related to Terminal prop additions and renderer wiring.

Poem

🐇 I nibbled keys and watched ptys wake,

tabs find burrows, scrollbacks in a flake,
events hop in tidy rows,
cleanup tucks the sleepers close,
now terminals hum while moonlight bakes.

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings, 1 inconclusive)
Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is a list of commit messages from many prior PRs rather than a cohesive description of this PR's specific changes; it doesn't follow the provided template structure. Replace the commit list with a clear description following the template: explain the terminal manager implementation, mention related issues, specify the change type, and add testing/verification details.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title check ❓ Inconclusive The title 'node pty processes' is too vague and generic; it lacks specificity about the actual changes being made. Consider a more descriptive title that clarifies what was implemented, such as 'Implement TerminalManager with node-pty integration' or 'Add terminal session management with TerminalManager.'

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (8)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/index.tsx (1)

33-35: Evaluate memoization necessity for activeTabId.

The activeTabId calculation is straightforward, but if this component receives frequent re-renders and the activeTabIds object is large, consider wrapping it in useMemo for 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 unused handleFocus callback

handleFocus is defined but never used. Either pass it to MosaicWindow (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 the before-quit handler

Initializing the DB via await initDb() before makeAppSetup is a solid sequencing choice and should prevent accidental db access before initialization. The before-quit hook to call terminalManager.cleanup() is also a good place for process teardown.

One minor refinement: the handler is marked async but doesn’t await anything. To better express intent and, if cleanup is async, allow awaiting it, you could either:

  • Drop async if cleanup is 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 mocks

The current onData / onExit mocks mutate their own mockImplementation and later read back mock.results[0]?.value to 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 mockImplementation calls.

Also applies to: 273-311

apps/desktop/src/main/lib/terminal-manager.ts (2)

41-43: Clarify uniqueness assumptions around tabId

sessions is keyed solely by tabId, and createOrAttach reuses an existing session for a given tabId regardless of workspaceId:

const existing = this.sessions.get(tabId);
if (existing?.isAlive) {
  // ...
  return { isNew: false, scrollback: existing.scrollback };
}

This is fine as long as tabId is guaranteed to be globally unique across all workspaces. If tabId is 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 tabId must be globally unique.

Also applies to: 61-72, 88-98


75-80: Make shell selection respect the user’s default shell

Right 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), zsh may 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 readability

The subscription uses a ref‑backed enabled flag:

trpc.terminal.stream.useSubscription(tabId, {
  enabled: isSubscribedRef.current,
  onData: (event) => { /* ... */ },
});

isSubscribedRef.current is toggled inside useEffect, and the component relies on other state changes (e.g., mutation state) to cause a re‑render so that enabled transitions from false to true. This is a bit indirect and makes it harder to reason about when the subscription is actually live.

For clarity, you could:

  • Replace isSubscribedRef with a small piece of React state, e.g. const [enabled, setEnabled] = useState(false);, and
  • Set enabled to true/false in the mount/cleanup paths of the effect, passing that state directly to useSubscription.

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

createOrAttach computes cwd from db.data.workspaces and db.data.worktrees, but if either lookup fails you just leave cwd undefined:

const workspace = db.data.workspaces.find((w) => w.id === workspaceId);
// ...
if (worktree) {
  cwd = worktree.path;
}

Given TerminalManager then defaults cwd to os.homedir(), a bad or stale workspaceId would 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/tabId so 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

📥 Commits

Reviewing files that changed from the base of the PR and between b0c6de7 and e7839ff.

📒 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+left and meta+alt+right handlers correctly navigate between workspaces with proper boundary checks. Dependency arrays appropriately capture activeWorkspaceId, allWorkspaces, and setActiveWorkspace to 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 splitPaneInGroup calls 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 electronStorage import 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 type keyword 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 good

Separating the React useState import 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 safe

Moving the join import above simpleGit is 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 appropriate

Switching to import type { BrowserWindow } and separating it from the dialog value 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-functional

Reordering useSetActiveWorkspace within the React Query workspaces import group is purely organizational and does not affect the WorkspaceItem behavior.

apps/desktop/src/renderer/react-query/workspaces/index.ts (1)

4-5: Export list reordering preserves public API

Reordering the React Query workspace hook exports (adding useSetActiveWorkspace and useUpdateWorkspace at 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 safe

Import reordering, the single-line worktreePath join, and the clarified project shape in getAllGrouped preserve 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 only

Moving the JSONFilePreset import has no behavioral effect; DB initialization and the guarded db proxy remain unchanged and sound.

apps/desktop/src/lib/trpc/routers/projects/index.ts (1)

1-2: Projects router re-exports look good

Reordering 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 context

Passing tabId and workspaceId into <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 correct

Consolidating the store imports and keeping a single DropOverlay import 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 fine

Exporting WorkspacesRouter and createWorkspacesRouter in 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 signature

Importing createWorkspacesRouter and calling it without a BrowserWindow argument is consistent with the updated, parameterless factory. createAppRouter still passes window only 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 correct

Passing tab.id and tab.workspaceId into Terminal aligns with the new TerminalProps contract 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 by mock.module(). The module mock of node-pty (lines 5–7) persists across all tests, so pty.spawn remains a mock throughout. Each test's state is properly isolated: beforeEach calls mockReturnValue() to refresh the mock behavior, and mock.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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (1)

32-42: Fix stale isExited state so restart‑on‑key works after exit

isExited is React state but the xterm.onData handler is created inside an effect that only depends on [tabId, workspaceId]. The handler therefore closes over the initial isExited value (false) and will never see it change to true after 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 change

This 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

📥 Commits

Reviewing files that changed from the base of the PR and between e7839ff and 8e72be6.

📒 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 good

The xterm imports, TerminalProps shape, and the generic debounce utility are all reasonable and self‑contained. No functional issues from this section.

Also applies to: 13-30


59-65: Resize/debounce/cleanup wiring is solid

Using a shared debounced resize mutation, ResizeObserver on 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

Comment on lines +117 to +134
// 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]);
}
},
},
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 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 reattaching

On successful createOrAttach, only result.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

📥 Commits

Reviewing files that changed from the base of the PR and between 8e72be6 and d0e468e.

📒 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‑safe

Centralizing the XTerm theme and options in a typed config (using ITerminalOptions["theme"] and TERMINAL_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 overall

The ref‑based isExitedRef approach, TRPC stream subscription, debounced resize with ResizeObserver + 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 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 only

Wiring killTerminalForTab into removeTab and removeChildTabFromGroup ensures PTY sessions are cleaned up when tabs go away, and the new electronStorage persistence hook for TabsStore looks fine.

One thing to be aware of: as written, killTerminalForTab runs for all tab IDs (including non‑terminal tab types), which will generate benign “session not found” warnings in TerminalManager for 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 from state.tabs and only calling killTerminalForTab when its type is the terminal variant (TabType.Terminal or 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

📥 Commits

Reviewing files that changed from the base of the PR and between d0e468e and 09aee22.

⛔ Files ignored due to path filters (1)
  • bun.lock is 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: killTerminalForTab is a good, minimal fire‑and‑forget cleanup helper

The 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: Renderer trpcClient setup looks correct for non‑React callers

The 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 solid

The 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.

Comment on lines +84 to +97
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);
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 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 -150

Length 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 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 entry

This 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

📥 Commits

Reviewing files that changed from the base of the PR and between 09aee22 and 758834a.

📒 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)

Comment on lines +110 to +127
const restartTerminal = () => {
isExitedRef.current = false;
setSubscriptionEnabled(false);
xterm.clear();
createOrAttachRef.current(
{
tabId,
workspaceId,
cols: xterm.cols,
rows: xterm.rows,
},
{
onSuccess: () => {
setSubscriptionEnabled(true);
},
},
);
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

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.

Suggested change
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.

Comment on lines +138 to +152
createOrAttachRef.current(
{
tabId,
workspaceId,
cols: xterm.cols,
rows: xterm.rows,
},
{
onSuccess: (result) => {
if (!result.isNew && result.scrollback.length > 0) {
xterm.write(result.scrollback[0]);
}
},
},
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

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.

@Kitenite
Kitenite merged commit 30ffd5b into main Nov 21, 2025
1 check passed
@Kitenite
Kitenite deleted the node-pty-processes branch November 21, 2025 04:55
This was referenced Nov 21, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Nov 21, 2025
5 tasks
This was referenced Nov 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant