Skip to content

forward hotkeys - #186

Closed
Kitenite wants to merge 1 commit into
mainfrom
jade-cloud-49
Closed

Kitenite wants to merge 1 commit into
mainfrom
jade-cloud-49

Conversation

@Kitenite

@Kitenite Kitenite commented Nov 29, 2025 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

Release Notes

  • New Features

    • Added keyboard shortcuts for terminal: Meta+K to clear and restart, Meta+W to close tab.
  • Improvements

    • Enhanced terminal exit handling and recovery flow.
    • Improved tab closing behavior and lifecycle management.

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

@vercel

vercel Bot commented Nov 29, 2025 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
website Error Error Nov 29, 2025 8:26pm

@coderabbitai

coderabbitai Bot commented Nov 29, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This PR refactors terminal tab management and lifecycle handling in the desktop renderer's Terminal component. It centralizes exit handling, adds keyboard shortcuts (Meta+K and Meta+W), coordinates tab closure with the tabs store, implements a deferred event-processing mechanism, and ensures the PTY remains available for reattachment after detach.

Changes

Cohort / File(s) Summary
Terminal component lifecycle and exit handling
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
Added tab lifecycle hooks (useTabsStore, removeTab, removeChildTabFromGroup); centralized terminal exit behavior via handleTerminalExit; implemented closeTabRef guard with hasClosedRef to prevent multiple closures; added keyboard shortcuts (Meta+K for clear/restart, Meta+W for close); introduced deferred event-processing with flush mechanism; coordinated restart flow with createOrAttach; ensured PTY persistence on detach for reattachment; expanded effect initialization for state reset and close behavior.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

  • Multiple interacting logic paths (tab lifecycle, exit handling, keyboard shortcuts, restart coordination) require careful review
  • Tab closure behavior must correctly handle both direct and parent-group removal scenarios
  • Restart and event-deferral mechanisms need verification to ensure consistent behavior across terminal recovery paths
  • Keyboard shortcut handlers and their integration with existing event flows warrant close scrutiny

Possibly related PRs

  • persist process history #120: Modifies terminal-history and terminal-manager components with createOrAttach return value changes, wasRecovered flag, and initial scrollback handling—directly paired with this PR's restart/recover flow coordination.
  • add close pane control #123: Implements tab-closing behavior and uses the same removeChildTabFromGroup store function, creating a direct dependency on tab management logic.
  • CMD+W to close tab #92: Implements Meta/Cmd+W "close terminal" shortcut handling, directly related to this PR's keyboard shortcut feature addition.

Poem

🐰 With whiskers twitching, I bound through the code,
Where terminals restart on a well-trodden road,
Tabs close gently, no double-closure fright,
Shortcuts dance nimbly—Meta+K, Meta+W so bright,
Events queue patiently, PTY stays alive,
A rabbit's delight to see systems survive! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Description check ⚠️ Warning The description lists many related issue references but lacks the structured template sections like 'Description', 'Type of Change', and 'Testing' that are required by the repository template. Restructure the description to follow the template: provide a clear summary of changes under 'Description', categorize the change type, detail testing performed, and explain the purpose of these related issues.
Title check ❓ Inconclusive The PR title 'forward hotkeys' is vague and does not clearly relate to the main changes, which involve comprehensive terminal lifecycle management, exit handling abstraction, and keyboard shortcuts implementation. Consider a more descriptive title such as 'Refactor terminal lifecycle and add keyboard shortcuts' to better reflect the significant changes in tab management, exit handling, and keyboard event processing.
✅ Passed checks (1 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch jade-cloud-49

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

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

202-224: Cross-platform keyboard shortcut support may be missing.

The shortcut handler only responds to the metaKey (Cmd on macOS). On Windows and Linux, users typically expect Ctrl+K and Ctrl+W for these operations. If this is a cross-platform Electron app, consider supporting both modifier keys.

 const shortcutHandler = (event: KeyboardEvent) => {
-	const isMetaOnly = event.metaKey && !event.ctrlKey && !event.altKey;
-	if (!isMetaOnly || event.shiftKey) return true;
+	const isMeta = event.metaKey && !event.ctrlKey && !event.altKey;
+	const isCtrl = event.ctrlKey && !event.metaKey && !event.altKey;
+	const isShortcutModifier = isMeta || isCtrl;
+	if (!isShortcutModifier || event.shiftKey) return true;

 	if (event.code === "KeyK") {

85-103: Memoize handleStreamData with useCallback to prevent unnecessary subscription rebinds and potential stale closure issues.

The handleStreamData function references the subscriptionEnabled state directly and is passed as the onData callback to trpc.useSubscription. Without memoization, the function is recreated on every render, which can cause:

  1. Unnecessary resubscribe/unsubscribe cycles in the tRPC subscription
  2. Potential stale closure if the subscription handler is not rebound on each render

Wrap it with useCallback and include subscriptionEnabled as a dependency (already done for handleTerminalExit):

const handleStreamData = useCallback((event: TerminalStreamEvent) => {
	if (!xtermRef.current) {
		pendingEventsRef.current.push(event);
		return;
	}

	if (!subscriptionEnabled) {
		pendingEventsRef.current.push(event);
		return;
	}

	if (event.type === "data") {
		xtermRef.current.write(event.data);
	} else if (event.type === "exit") {
		handleTerminalExit(event.exitCode);
	}
}, [subscriptionEnabled, handleTerminalExit]);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4b4935d and eec0d57.

📒 Files selected for processing (1)
  • apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (7 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
apps/desktop/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (apps/desktop/AGENTS.md)

For Electron interprocess communication, ALWAYS use tRPC as defined in src/lib/trpc

Files:

  • apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
apps/desktop/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/desktop/AGENTS.md)

apps/desktop/**/*.{ts,tsx}: Please use alias as defined in tsconfig.json when possible
Prefer zustand for state management if it makes sense. Do not use effect unless absolutely necessary

Files:

  • apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Avoid using any type - use explicit types instead for type safety
Use camelCase for variable and function names following existing codebase patterns
Keep diffs minimal with targeted edits only - avoid unnecessary changes when making modifications
Follow existing patterns and match the codebase style when writing new code

Files:

  • apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
**/components/**/*.tsx

📄 CodeRabbit inference engine (AGENTS.md)

**/components/**/*.tsx: Create one folder per component with structure: ComponentName/ComponentName.tsx + index.ts for barrel export
Co-locate tests next to the component file they test (e.g., ComponentName.test.tsx)
Co-locate dependencies (utils, hooks, constants, config, stories) next to the file using them
Use nested components/ subdirectory within a parent component only if a sub-component is used 2+ times within that parent; otherwise keep it in the parent's components/ folder
One component per file - avoid multi-component files

Files:

  • apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
apps/desktop/src/renderer/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Never import Node.js modules (fs, path, os, net, etc.) in renderer process code - browser environment only

Files:

  • apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
apps/desktop/src/renderer/**/*.tsx

📄 CodeRabbit inference engine (AGENTS.md)

Call IPC methods using window.ipcRenderer.invoke() with object parameters - TypeScript will infer the exact response type automatically

Files:

  • apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
🧠 Learnings (1)
📚 Learning: 2025-11-28T01:03:47.951Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-11-28T01:03:47.951Z
Learning: Applies to **/*.{ts,tsx} : Keep diffs minimal with targeted edits only - avoid unnecessary changes when making modifications

Applied to files:

  • apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
🧬 Code graph analysis (1)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (3)
apps/desktop/src/renderer/stores/tabs/hooks.ts (1)
  • useSetActiveTab (10-11)
apps/desktop/src/renderer/stores/theme/store.ts (1)
  • useTerminalTheme (184-185)
apps/desktop/src/renderer/stores/tabs/store.ts (1)
  • useTabsStore (36-167)
🔇 Additional comments (10)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (10)

4-11: LGTM!

Imports are well-organized, use alias paths as defined in tsconfig.json, and correctly add the necessary hooks for the new tab lifecycle management functionality. No Node.js modules are imported in this renderer process code.


29-37: LGTM!

Good use of refs for mutable closure state (closeTabRef, hasClosedRef) to prevent stale closure issues and double-close race conditions. The zustand selectors for removeTab and removeChildTabFromGroup follow the recommended pattern.


59-61: LGTM!

Correctly resets the close guard when the tabId changes, ensuring the new tab instance can be closed. This handles the edge case of prop changes without component remount.


63-74: LGTM!

The close tab logic correctly distinguishes between grouped child tabs and standalone tabs. The hasClosedRef guard prevents multiple close attempts, which is important since closeTabRef.current() is called from multiple code paths (exit handler, keyboard shortcut).


76-83: LGTM!

Good centralization of exit handling logic. The underscore prefix on _exitCode correctly indicates an intentionally unused parameter. Note that setSubscriptionEnabled is a stable React setState function, so it doesn't strictly need to be in the dependency array, but including it is harmless and explicit.


252-259: Verify terminalTheme is intentionally excluded from dependencies.

The terminalTheme is used in createTerminalInstance (line 117) but is not in the dependency array. A separate effect handles theme updates (lines 262-269), which suggests this is intentional to avoid recreating the terminal on theme changes.

However, if terminalTheme is undefined initially and loads asynchronously, the terminal may start with the default theme even if a custom theme is available shortly after. The separate theme effect should correct this, so this is likely acceptable behavior.


242-251: LGTM!

Cleanup sequence is correct: dispose input listener, cleanup event handlers, detach PTY (keeping it alive for reattachment), disable subscription, then dispose xterm. The comment at line 246 clarifies the intentional PTY preservation.


261-269: LGTM!

Clean separation of theme update logic from terminal initialization. Using the options setter is the correct approach for xterm.js v5 to trigger a repaint without recreating the instance.


274-281: LGTM!

Simple and clean JSX structure with proper background color fallback handling.


214-219: Review comment is incorrect—no PTY lifecycle error exists.

When Meta+W triggers closeTabRef.current(), the actual flow is:

  1. removeTab → killTerminalForTab(id) calls trpcClient.terminal.kill({ tabId, deleteHistory: true }) (async, fire-and-forget)
  2. Component unmounts
  3. Cleanup runs: detachRef.current({ tabId })

Both kill and detach in apps/desktop/src/main/lib/terminal-manager.ts gracefully handle race conditions:

  • kill() (lines 230-252): If session not found, logs warning and returns safely
  • detach() (lines 254-264): If session not found, logs warning and returns safely; otherwise updates lastActive

There is no error condition. detach does not require the PTY to exist—it checks for the session and warns if missing. The operations are idempotent and safe regardless of execution order.

@Kitenite Kitenite changed the title jade cloud 49 forward hotkeys Nov 29, 2025
@Kitenite Kitenite closed this Dec 1, 2025
@Kitenite
Kitenite deleted the jade-cloud-49 branch December 1, 2025 19:27

This branch had an error being deployed

1 failed deployment
Preview — eec0d570 Deployed Nov 29, 2025 by vercel[bot]
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