Repository navigation
feat(desktop): terminal session persistence (CWD restore + optional tmux backend) - #518
andreasasprou wants to merge 36 commits into
Conversation
|
Important Review skippedDraft detected. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the 📝 WalkthroughWalkthroughAdds tmux-backed terminal persistence with session lifecycles, scrollback sanitization and metadata, renderer integration for sanitized output, and a coordinated shutdown that detaches/persists sessions before quitting. Changes
Sequence Diagram(s)sequenceDiagram
participant App
participant ProcessPersistence as Process Persistence
participant TerminalMgr as Terminal Manager
participant Lifecycle as SessionLifecycle
participant Tmux as TmuxBackend
participant History as HistoryWriter/Reader
App->>ProcessPersistence: initialize()
App->>TerminalMgr: createOrAttach(workspace,pane)
TerminalMgr->>History: readMetadata(workspace,pane)
History-->>TerminalMgr: {scrollback, savedCwd}
alt persistent session exists
TerminalMgr->>Lifecycle: getOrCreateLifecycle(pane,session)
TerminalMgr->>Lifecycle: ensureAttached(cols,rows)
Lifecycle->>Tmux: attachSession(sessionName)
Tmux-->>Lifecycle: IPty (attached)
Lifecycle-->>TerminalMgr: attached (buffered data)
else create new persistent session
TerminalMgr->>ProcessPersistence: createSession({name,cwd,shell,env})
ProcessPersistence->>Tmux: createSession(...)
ProcessPersistence-->>TerminalMgr: created
TerminalMgr->>Lifecycle: setupPersistentSessionWithLifecycle(...)
Lifecycle->>History: initialize with recovered scrollback
end
TerminalMgr-->>App: TerminalSession ready
sequenceDiagram
participant User
participant App
participant ProcessPersistence as Process Persistence
participant TerminalMgr as Terminal Manager
participant Lifecycle as SessionLifecycle
participant History as HistoryWriter
User->>App: Quit
App->>App: before-quit -> set quitState="cleaning"
App->>ProcessPersistence: isPersistenceEnabled()
alt persistence enabled
App->>TerminalMgr: detachAll()
TerminalMgr->>Lifecycle: detach() for each lifecycle
Lifecycle->>ProcessPersistence: detachSession(name)
TerminalMgr->>History: closeForDetach() (flush metadata)
History-->>TerminalMgr: metadata persisted
else persistence disabled
TerminalMgr->>History: close() (finalize)
end
App->>App: set quitState="ready-to-quit"
App->>App: app.quit()
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (6)
turbo.jsonc (1)
5-164: Excellent refactoring of environment variable scoping!The restructuring from global to package-specific environment variables improves cache granularity—changes to API secrets no longer invalidate web/admin/marketing/docs builds. The extensive comments and logical grouping enhance maintainability.
Verified that previously global variables (CLERK_WEBHOOK_SECRET, BLOB_READ_WRITE_TOKEN, POSTHOG_API_KEY, KV tokens, etc.) are now correctly scoped to the packages that consume them.
Minor observation: This refactoring appears unrelated to the PR's stated objective (terminal session persistence). While the changes are valuable, consider whether such infrastructure improvements might be clearer as separate PRs to simplify review and git history.
apps/desktop/src/main/lib/terminal-history.ts (1)
169-177: Consider adding minimal validation for metadata parsing.The
JSON.parseresult is returned directly asSessionMetadatawithout validation. If the file is corrupted or has an incompatible schema from a different version, this could cause subtle runtime issues downstream.🔎 Optional: Add basic type guard
async readMetadata(): Promise<SessionMetadata | null> { try { const metaPath = getMetadataPath(this.workspaceId, this.paneId); const metaContent = await fs.readFile(metaPath, "utf-8"); - return JSON.parse(metaContent); + const parsed = JSON.parse(metaContent); + // Basic validation - ensure required fields exist + if (typeof parsed?.cwd === "string" && typeof parsed?.startedAt === "string") { + return parsed as SessionMetadata; + } + return null; } catch { return null; } }apps/desktop/src/main/index.ts (1)
95-122: Well-structured quit state machine, with a minor consideration.The three-state machine (
idle→cleaning→ready-to-quit) correctly prevents re-entrant quit handling. Thefinallyblock ensures the app quits even if cleanup fails, which is reasonable for shutdown.However, errors from
detachAll()orcleanup()are silently swallowed. Consider logging them for debugging:🔎 Optional: Log cleanup errors
try { if (processPersistence.enabled) { await terminalManager.detachAll(); } else { await terminalManager.cleanup(); } await posthog?.shutdown(); +} catch (error) { + console.error("[main] Cleanup error during quit:", error); } finally { quitState = "ready-to-quit"; app.quit(); }apps/desktop/src/main/lib/terminal/persistence/types.ts (1)
3-33: Clean interface design with minor duplication opportunity.The
PersistenceBackendinterface is well-structured with clear method signatures. The optional methods (getSessionLastActivity,cleanupOrphanedScripts) allow for capability detection.Consider using
CreatePersistentSessionParamsin thecreateSessionsignature to reduce duplication:🔎 Optional: Reuse CreatePersistentSessionParams
- createSession(opts: { - name: string; - cwd: string; - shell: string; - env: Record<string, string>; - }): Promise<void>; + createSession(opts: CreatePersistentSessionParams): Promise<void>;apps/desktop/docs/TERMINAL_SESSION_PERSISTENCE.md (1)
317-347: Consider adding a language specifier to the fenced code block.The static analysis tool flagged this ASCII diagram block as missing a language specifier. While ASCII diagrams don't have a specific language, you can use
textorplaintextto silence the warning:-``` +```text ┌─────────────────────────────────────────────────────────┐apps/desktop/src/main/lib/terminal/persistence/tmux-backend.ts (1)
166-180: Consider using actual terminal dimensions instead of hardcoded values.The
attachSessionmethod hardcodescols: 80androws: 24. If the caller has access to the actual terminal dimensions, consider accepting them as parameters to avoid a resize operation immediately after attach.🔎 Suggested improvement
- async attachSession(name: string): Promise<pty.IPty> { + async attachSession(name: string, cols?: number, rows?: number): Promise<pty.IPty> { const env = { ...process.env }; delete env.TMUX; return pty.spawn( "tmux", ["-S", TMUX_SOCKET, "attach-session", "-t", name], { name: "xterm-256color", - cols: 80, - rows: 24, + cols: cols ?? 80, + rows: rows ?? 24, env: env as Record<string, string>, }, ); }
📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (14)
apps/desktop/docs/TERMINAL_SESSION_PERSISTENCE.mdapps/desktop/src/lib/electron-app/factories/app/setup.tsapps/desktop/src/lib/trpc/routers/terminal/terminal.tsapps/desktop/src/main/index.tsapps/desktop/src/main/lib/terminal-history.tsapps/desktop/src/main/lib/terminal/manager.tsapps/desktop/src/main/lib/terminal/persistence/manager.tsapps/desktop/src/main/lib/terminal/persistence/tmux-backend.tsapps/desktop/src/main/lib/terminal/persistence/types.tsapps/desktop/src/main/lib/terminal/session.tsapps/desktop/src/main/lib/terminal/types.tsapps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsxapps/desktop/src/shared/parse-cwd.tsturbo.jsonc
💤 Files with no reviewable changes (1)
- apps/desktop/src/lib/electron-app/factories/app/setup.ts
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Avoid using any type in TypeScript - maintain type safety unless absolutely necessary
Files:
apps/desktop/src/shared/parse-cwd.tsapps/desktop/src/lib/trpc/routers/terminal/terminal.tsapps/desktop/src/main/lib/terminal/types.tsapps/desktop/src/main/lib/terminal/persistence/tmux-backend.tsapps/desktop/src/main/lib/terminal-history.tsapps/desktop/src/main/lib/terminal/session.tsapps/desktop/src/main/lib/terminal/manager.tsapps/desktop/src/main/lib/terminal/persistence/types.tsapps/desktop/src/main/index.tsapps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsxapps/desktop/src/main/lib/terminal/persistence/manager.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (AGENTS.md)
Run Biome for formatting, linting, import organization, and safe fixes at the root level using bun run lint:fix
Files:
apps/desktop/src/shared/parse-cwd.tsapps/desktop/src/lib/trpc/routers/terminal/terminal.tsapps/desktop/src/main/lib/terminal/types.tsapps/desktop/src/main/lib/terminal/persistence/tmux-backend.tsapps/desktop/src/main/lib/terminal-history.tsapps/desktop/src/main/lib/terminal/session.tsapps/desktop/src/main/lib/terminal/manager.tsapps/desktop/src/main/lib/terminal/persistence/types.tsapps/desktop/src/main/index.tsapps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsxapps/desktop/src/main/lib/terminal/persistence/manager.ts
apps/desktop/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/desktop/AGENTS.md)
apps/desktop/**/*.{ts,tsx}: For Electron interprocess communication, ALWAYS use tRPC as defined insrc/lib/trpc
Use alias as defined intsconfig.jsonwhen possible
Prefer zustand for state management if it makes sense. Do not use effect unless absolutely necessary.
For tRPC subscriptions with trpc-electron, ALWAYS use the observable pattern from@trpc/server/observableinstead of async generators, as the library explicitly checksisObservable(result)and throws an error otherwise
Files:
apps/desktop/src/shared/parse-cwd.tsapps/desktop/src/lib/trpc/routers/terminal/terminal.tsapps/desktop/src/main/lib/terminal/types.tsapps/desktop/src/main/lib/terminal/persistence/tmux-backend.tsapps/desktop/src/main/lib/terminal-history.tsapps/desktop/src/main/lib/terminal/session.tsapps/desktop/src/main/lib/terminal/manager.tsapps/desktop/src/main/lib/terminal/persistence/types.tsapps/desktop/src/main/index.tsapps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsxapps/desktop/src/main/lib/terminal/persistence/manager.ts
apps/desktop/src/{main,renderer,preload}/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use type-safe IPC communication - define channel types in apps/desktop/src/shared/ipc-channels.ts before implementing handlers
Files:
apps/desktop/src/main/lib/terminal/types.tsapps/desktop/src/main/lib/terminal/persistence/tmux-backend.tsapps/desktop/src/main/lib/terminal-history.tsapps/desktop/src/main/lib/terminal/session.tsapps/desktop/src/main/lib/terminal/manager.tsapps/desktop/src/main/lib/terminal/persistence/types.tsapps/desktop/src/main/index.tsapps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsxapps/desktop/src/main/lib/terminal/persistence/manager.ts
apps/desktop/src/main/**/*.ts
📄 CodeRabbit inference engine (AGENTS.md)
Accept object parameters in IPC handlers - do not use positional parameters in ipcMain.handle()
Files:
apps/desktop/src/main/lib/terminal/types.tsapps/desktop/src/main/lib/terminal/persistence/tmux-backend.tsapps/desktop/src/main/lib/terminal-history.tsapps/desktop/src/main/lib/terminal/session.tsapps/desktop/src/main/lib/terminal/manager.tsapps/desktop/src/main/lib/terminal/persistence/types.tsapps/desktop/src/main/index.tsapps/desktop/src/main/lib/terminal/persistence/manager.ts
apps/desktop/src/main/index.ts
📄 CodeRabbit inference engine (AGENTS.md)
Load environment variables in src/main/index.ts and electron.vite.config.ts with override: true before other imports
Files:
apps/desktop/src/main/index.ts
**/{components,features}/**/[!.]*.tsx
📄 CodeRabbit inference engine (AGENTS.md)
Organize project structure with one folder per component: ComponentName/ComponentName.tsx with index.ts barrel export
Files:
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
**/{components,features}/**/*.{ts,tsx,test.ts,test.tsx,stories.tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Co-locate component dependencies (utils, hooks, constants, config, tests, stories) next to the file using them
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 in renderer process or shared code - use only in main process (src/main/)
Files:
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
**/*.{tsx,css}
📄 CodeRabbit inference engine (AGENTS.md)
Use React + TailwindCSS v4 + shadcn/ui for UI development
Files:
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
**/{components,features}/**/*.tsx
📄 CodeRabbit inference engine (AGENTS.md)
**/{components,features}/**/*.tsx: Nest components in parent's components/ folder if used only once, promote to highest shared parent's components/ if used 2+ times
Use one component per file - do not combine multiple components in a single file
Files:
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
🧠 Learnings (6)
📚 Learning: 2025-12-18T23:19:10.415Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-18T23:19:10.415Z
Learning: Applies to apps/desktop/src/renderer/**/*.{ts,tsx} : Never import Node.js modules in renderer process or shared code - use only in main process (src/main/)
Applied to files:
apps/desktop/src/shared/parse-cwd.tsapps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
📚 Learning: 2025-12-18T23:19:10.415Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-18T23:19:10.415Z
Learning: Applies to apps/desktop/src/{main,renderer,preload}/**/*.{ts,tsx} : Use type-safe IPC communication - define channel types in apps/desktop/src/shared/ipc-channels.ts before implementing handlers
Applied to files:
apps/desktop/src/shared/parse-cwd.tsapps/desktop/src/main/lib/terminal/persistence/types.tsapps/desktop/src/main/index.ts
📚 Learning: 2025-12-21T04:39:28.543Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: apps/desktop/AGENTS.md:0-0
Timestamp: 2025-12-21T04:39:28.543Z
Learning: Applies to apps/desktop/**/*.{ts,tsx} : Prefer zustand for state management if it makes sense. Do not use effect unless absolutely necessary.
Applied to files:
apps/desktop/src/main/index.ts
📚 Learning: 2025-12-21T04:39:28.543Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: apps/desktop/AGENTS.md:0-0
Timestamp: 2025-12-21T04:39:28.543Z
Learning: Applies to apps/desktop/**/*.{ts,tsx} : Use alias as defined in `tsconfig.json` when possible
Applied to files:
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
📚 Learning: 2025-12-18T23:19:10.415Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-18T23:19:10.415Z
Learning: Applies to src/components/{ui,ai-elements,react-flow}/**/*.tsx : Use kebab-case single files for shadcn/ui components in src/components/ui/, src/components/ai-elements, and src/components/react-flow/ directories
Applied to files:
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
📚 Learning: 2025-12-18T23:19:10.415Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-18T23:19:10.415Z
Learning: Applies to apps/desktop/src/main/index.ts : Load environment variables in src/main/index.ts and electron.vite.config.ts with override: true before other imports
Applied to files:
turbo.jsonc
🧬 Code graph analysis (4)
apps/desktop/src/lib/trpc/routers/terminal/terminal.ts (2)
apps/desktop/src/main/lib/terminal/manager.ts (1)
terminalManager(618-618)apps/desktop/src/main/lib/terminal/index.ts (1)
terminalManager(1-1)
apps/desktop/src/main/lib/terminal/session.ts (3)
apps/desktop/src/main/lib/terminal-history.ts (1)
HistoryReader(163-207)apps/desktop/src/shared/parse-cwd.ts (1)
parseCwd(24-39)apps/desktop/src/main/lib/terminal/types.ts (1)
TerminalSession(5-25)
apps/desktop/src/main/lib/terminal/manager.ts (4)
apps/desktop/src/main/lib/terminal/types.ts (2)
TerminalSession(5-25)SessionResult(40-44)apps/desktop/src/main/lib/terminal/persistence/tmux-backend.ts (1)
getSessionName(49-61)apps/desktop/src/main/lib/terminal/env.ts (2)
getDefaultShell(10-26)buildTerminalEnv(66-108)apps/desktop/src/main/lib/terminal/session.ts (4)
setupDataHandler(172-216)reinitializeHistory(250-264)closeSessionHistory(218-239)closeSessionHistoryForDetach(241-248)
apps/desktop/src/main/index.ts (3)
apps/desktop/src/main/lib/terminal/persistence/manager.ts (1)
processPersistence(151-151)apps/desktop/src/main/lib/terminal/manager.ts (1)
terminalManager(618-618)apps/desktop/src/main/lib/analytics/index.ts (1)
posthog(4-4)
🪛 LanguageTool
apps/desktop/docs/TERMINAL_SESSION_PERSISTENCE.md
[grammar] ~1134-~1134: Ensure spelling is correct
Context: ...ned while away Recommendation: Add shpool support in a future iteration if users ...
(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)
🪛 markdownlint-cli2 (0.18.1)
apps/desktop/docs/TERMINAL_SESSION_PERSISTENCE.md
317-317: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
🔇 Additional comments (32)
apps/desktop/src/main/lib/terminal-history.ts (2)
87-110: Debounced metadata write implementation looks solid.The use of
unref()on line 109 is appropriate to prevent this timer from keeping the process alive during shutdown. The debounce pattern correctly cancels pending writes before scheduling new ones.One minor observation: the async callback in
setTimeout(line 97) means any rejection will be unhandled at the process level, but the try-catch adequately handles the expectedfs.writeFileerrors.
112-134: LGTM - closeForDetach properly handles detach lifecycle.The method correctly:
- Cancels pending debounced writes
- Flushes the stream with proper promise wrapping
- Persists current metadata without setting
endedAt(preserving session state for reattachment)apps/desktop/src/shared/parse-cwd.ts (1)
1-39: LGTM - Clean shared module implementation.The module correctly avoids Node.js dependencies as documented (lines 6-8), making it safe for use in both main and renderer processes. The OSC-7 parsing logic is well-implemented with proper URL decoding and fallback handling. Based on learnings, this aligns with the guideline to never import Node.js modules in renderer process or shared code.
apps/desktop/src/lib/trpc/routers/terminal/terminal.ts (1)
139-147: LGTM - Correctly awaiting async detach operation.The
awaiton line 146 ensures the detach operation completes before the mutation returns, which is essential for the new persistence-enabled flow where detach involves cleanup of history writers and potential tmux session handling.apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (1)
23-23: LGTM - Import updated to use shared module.The import path correctly uses the
shared/alias as defined in tsconfig.json, and the shared module is appropriately free of Node.js dependencies for renderer process usage. Based on learnings, this aligns with the guideline to use aliases as defined intsconfig.jsonwhen possible.apps/desktop/src/main/lib/terminal/types.ts (1)
22-24: LGTM - Type extensions for persistence support.The new optional properties are well-typed and maintain backward compatibility with existing session handling code. Using
ReturnType<typeof setTimeout>forcleanupTimeoutis the correct portable type for Node.js timer handles.apps/desktop/src/main/index.ts (1)
163-164: LGTM - Persistence initialization correctly placed in startup sequence.Initializing
processPersistenceafter auth but beforemakeAppSetupensures the tmux backend is detected and ready before any terminal sessions could be created through the UI.apps/desktop/src/main/lib/terminal/persistence/manager.ts (4)
26-46: Initialization guard is correctly implemented.Setting
initialized = trueat line 28 before async operations prevents re-entrant calls, which is the correct pattern. The early returns for missing env var and Windows platform are clean.
48-65: LGTM - Sensible default tmux configuration.The default config appropriately disables tmux's prefix key and status bar since the terminal is embedded in the app. The
history-limit 50000andescape-time 0settings are good defaults for a responsive terminal experience.
111-148: Robust orphan cleanup with conservative defaults.The cleanup logic correctly:
- Only cleans sessions older than 72 hours (
MAX_ORPHAN_AGE_MS)- Keeps sessions with unknown age (line 130-134) - safe default
- Logs cleanup actions for debugging
The sequential iteration is appropriate for cleanup operations where parallel kills could cause race conditions.
67-100: Intentional asymmetry in error handling is appropriate.The design correctly distinguishes between:
- Query operations (
sessionExists,listSessions,captureScrollback): Return safe defaults when no backend- Mutating operations (
createSession,attachSession): Throw to signal caller that the operation cannot proceedThis prevents silent failures for critical operations while allowing graceful degradation for queries.
apps/desktop/src/main/lib/terminal/session.ts (5)
1-4: LGTM!The imports are correctly structured -
fsfromnode:fs/promisesfor async file operations andparseCwdfrom the shared module for cross-process OSC-7 parsing.
19-51: LGTM - Well-designed fix for the CWD recovery bug.The function now correctly:
- Reads metadata first (line 25) to always have access to
savedCwd- Returns
savedCwdin all three code paths (existing scrollback, history-based recovery, and empty scrollback)- Handles the edge case where metadata exists but scrollback is empty (line 50)
This addresses the documented bug where the early return skipped reading
meta.json.
104-123: LGTM - Robust directory validation with appropriate fallback.The implementation correctly:
- Uses
savedCwdfrom recovery in the fallback chain (line 110)- Validates directory accessibility using
stat()+readdir()(better thanaccess(X_OK)on macOS)- Falls back gracefully to
homedir()if the directory is inaccessibleThe documentation correctly notes that
readdir()is more reliable thanX_OKfor handling SIP/sandboxing on macOS.
170-200: LGTM - Correct OSC-7 rolling buffer implementation.The rolling buffer approach (line 195) correctly handles split OSC-7 sequences across PTY chunks. Using raw
datainstead ofdataToStoreensures OSC-7 sequences aren't missed after clear operations. The 4KB buffer size is appropriate for capturing complete sequences.
241-248: LGTM - Clean detach-specific cleanup.This function provides the proper separation between normal session close (with
endedAt/exitCode) and detach (preserving session metadata without termination markers). This is essential for the persistent backend workflow.apps/desktop/docs/TERMINAL_SESSION_PERSISTENCE.md (1)
1-1245: Excellent documentation - comprehensive and well-structured.The documentation thoroughly covers:
- Phase 1 (CWD persistence) and Phase 2 (process persistence) implementation details
- Security considerations (safe env vars, isolated tmux socket)
- Edge cases and error handling
- Manual acceptance checklists with specific test cases
- "Don't ship without" critical checks
This serves as both a design doc and operational guide.
apps/desktop/src/main/lib/terminal/persistence/tmux-backend.ts (7)
16-18: LGTM - Correct isolation paths.Using
SUPERSET_HOME_DIRfrom the app environment ensures correct paths for both production (~/.superset) and development (~/.superset-dev) environments.
20-35: LGTM - Security-conscious environment whitelist.The
SAFE_ENV_KEYSwhitelist correctly excludes sensitive variables (AWS_*, GITHUB_TOKEN, API keys) while including only necessary shell configuration and Superset-specific identifiers. This prevents credential leakage in wrapper scripts.
37-39: LGTM - Correct shell quoting implementation.The
shellQuotefunction properly handles embedded single quotes by breaking out of the quoted string, adding an escaped quote, and continuing. This prevents shell injection attacks.
49-70: MD5 usage is acceptable here for non-cryptographic hashing.MD5 is used only for generating short, deterministic identifiers from workspace/pane IDs - not for security purposes. The collision risk for session naming is negligible given the use case.
143-164: LGTM - Secure session creation with wrapper script.The implementation correctly:
- Creates the sessions directory with
recursive: true- Uses
buildSafeEnvForScriptto filter environment variables- Sets appropriate permissions (
0o755) on the wrapper script- Uses
shellQuotefor all command arguments to prevent injection
192-208: LGTM - Robust session cleanup with proper error handling.The
killSessionmethod correctly:
- Kills the tmux session first
- Cleans up the wrapper script
- Ignores
ENOENTerrors (script may not exist)- Logs unexpected errors without throwing
233-246: LGTM - Safe orphan script cleanup.The implementation correctly compares existing scripts against active sessions and only removes orphans. The
.catch(() => {})on individual removals prevents one failure from blocking others.apps/desktop/src/main/lib/terminal/manager.ts (8)
2-10: LGTM - Correct imports for persistence integration.The imports properly bring in the necessary utilities from the persistence module and environment configuration.
62-130: Well-structured persistence flow with proper fallback.The method correctly:
- Generates the session name using the hash-based naming convention
- Attempts to attach to existing persistent sessions first
- Kills orphaned sessions that fail to attach (preventing duplicates)
- Falls back to creating new persistent sessions
- Falls back to non-persistent sessions if persistence fails entirely
The error handling is appropriately defensive.
132-147: LGTM - Bounded scrollback capture with timeout.The 2-second timeout and 500KB limit prevent blocking the UI during scrollback capture. The
Promise.racepattern is correctly used for the timeout.
240-249: LGTM - Correct exit handler behavior for persistent backends.The exit handler correctly:
- Returns early for expected detaches (line 240-242)
- Cleans up history and emits exit for unexpected persistent exits (line 244-249)
- Skips the fallback shell logic for persistent backends
284-288: LGTM - Cleanup timeout with unref for graceful shutdown.Using
.unref()on the timeout ensures it won't keep the Node.js event loop alive during shutdown. The timeout is correctly stored on the session for potential cancellation on reattach.
385-407: LGTM - Async detach with proper cleanup sequence.The detach method correctly:
- Cancels any pending cleanup timeout (preventing race conditions)
- Sets
isExpectedDetachbefore killing PTY- Closes history for detach (preserving metadata)
- Removes from session map immediately
- Falls back to updating
lastActivefor non-persistent sessions
568-579: LGTM - detachAll correctly handles both session types.The method properly distinguishes between persistent and non-persistent sessions, detaching the former and killing the latter. Clearing the sessions map at the end is appropriate.
149-198: Replace dynamic import with static import for consistency.
manager.tsuses a dynamic import forDataBatcher(line 171), whilesession.tsin the same module uses a static import (line 6). Both files instantiate the same class without any apparent code-splitting or dependency-management benefit. Use a static import to match the pattern elsewhere in the terminal module.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (2)
apps/desktop/src/main/lib/terminal/manager.ts (2)
102-104: Avoid redundantgetDefaultShell()calls.
getDefaultShell()is invoked twice within the same object. While it caches the result internally, extracting to a local variable improves clarity.🔎 Suggested fix
+ const shell = getDefaultShell(); await processPersistence.createSession({ name: sessionName, cwd: params.cwd ?? os.homedir(), - shell: getDefaultShell(), + shell, env: buildTerminalEnv({ - shell: getDefaultShell(), + shell, paneId: params.paneId,
588-599: Consider awaiting PTY exits for persistent sessions.For persistent backend sessions,
session.pty.kill()is called but not awaited. The exit handler setsisExpectedDetachand returns early, but there's no guarantee the exit event fires beforesessions.clear(). This is likely harmless but could leave cleanup incomplete.For consistency with the non-persistent path (which calls the async
kill()method), consider adding a brief wait or tracking exit events:async detachAll(): Promise<void> { + const exitPromises: Promise<void>[] = []; for (const [paneId, session] of this.sessions.entries()) { if (session.isPersistentBackend && session.isAlive) { session.isExpectedDetach = true; await closeSessionHistoryForDetach(session); + exitPromises.push( + new Promise<void>((resolve) => { + this.once(`exit:${paneId}`, () => resolve()); + setTimeout(resolve, 100); // Brief timeout fallback + }), + ); session.pty.kill(); } else { await this.kill({ paneId }); } } + await Promise.all(exitPromises); this.sessions.clear(); }
📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
apps/desktop/src/main/lib/terminal/manager.ts
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Avoid using any type in TypeScript - maintain type safety unless absolutely necessary
Files:
apps/desktop/src/main/lib/terminal/manager.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (AGENTS.md)
Run Biome for formatting, linting, import organization, and safe fixes at the root level using bun run lint:fix
Files:
apps/desktop/src/main/lib/terminal/manager.ts
apps/desktop/src/{main,renderer,preload}/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use type-safe IPC communication - define channel types in apps/desktop/src/shared/ipc-channels.ts before implementing handlers
Files:
apps/desktop/src/main/lib/terminal/manager.ts
apps/desktop/src/main/**/*.ts
📄 CodeRabbit inference engine (AGENTS.md)
Accept object parameters in IPC handlers - do not use positional parameters in ipcMain.handle()
Files:
apps/desktop/src/main/lib/terminal/manager.ts
apps/desktop/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/desktop/AGENTS.md)
apps/desktop/**/*.{ts,tsx}: For Electron interprocess communication, ALWAYS use tRPC as defined insrc/lib/trpc
Use alias as defined intsconfig.jsonwhen possible
Prefer zustand for state management if it makes sense. Do not use effect unless absolutely necessary.
For tRPC subscriptions with trpc-electron, ALWAYS use the observable pattern from@trpc/server/observableinstead of async generators, as the library explicitly checksisObservable(result)and throws an error otherwise
Files:
apps/desktop/src/main/lib/terminal/manager.ts
🧬 Code graph analysis (1)
apps/desktop/src/main/lib/terminal/manager.ts (7)
apps/desktop/src/main/lib/terminal/types.ts (3)
CreateSessionParams(46-57)TerminalSession(5-25)SessionResult(40-44)apps/desktop/src/main/lib/terminal/index.ts (2)
CreateSessionParams(3-3)SessionResult(4-4)apps/desktop/src/main/lib/terminal/persistence/manager.ts (2)
getSessionName(152-152)processPersistence(151-151)apps/desktop/src/main/lib/terminal/persistence/tmux-backend.ts (1)
getSessionName(49-61)apps/desktop/src/main/lib/terminal/env.ts (2)
getDefaultShell(10-26)buildTerminalEnv(66-108)apps/desktop/src/main/lib/terminal-history.ts (1)
HistoryWriter(32-161)apps/desktop/src/main/lib/terminal/session.ts (1)
setupDataHandler(172-216)
🔇 Additional comments (9)
apps/desktop/src/main/lib/terminal/manager.ts (9)
1-26: LGTM!Imports are well-organized and all added dependencies (
os,HistoryReader,HistoryWriter,buildTerminalEnv,getDefaultShell,getSessionName,processPersistence,closeSessionHistoryForDetach) are properly typed and used throughout the file.
133-148: LGTM!The bounded scrollback capture with timeout protection is well-implemented. The 2-second timeout prevents hanging, and the fallback to empty string on failure is appropriate for resilience.
170-198: HistoryWriter initialization properly addressed.The
historyWriteris now correctly instantiated and assigned to the session object, enabling CWD persistence and backup scrollback for persistent backend sessions. This addresses the concern raised in the past review.
260-269: LGTM!The exit handler correctly distinguishes between expected detaches (which should short-circuit) and unexpected exits for persistent backend sessions. The cleanup sequence (close history, remove ports, emit exit) is appropriate.
405-427: LGTM!The async detach flow properly coordinates the cleanup sequence for persistent sessions: clearing timeouts, marking expected detach, closing history for detach, killing the PTY, and removing from the session map. The
isExpectedDetachflag ensures the exit handler short-circuits correctly.
392-395: LGTM!The kill method correctly delegates to
processPersistence.killSessionfor persistent backends before proceeding with local PTY cleanup. Silently catching errors is appropriate since the session may already be terminated.
460-482: LGTM with minor note.The method correctly calls
processPersistence.killByWorkspaceto ensure orphaned tmux sessions are cleaned. The call at line 478 after killing individual sessions is defensive and ensures complete cleanup even if some sessions weren't tracked locally.
327-337: LGTM!The strict validation for resize geometry (positive integers only) is a good defensive measure that prevents potential crashes or undefined behavior in the PTY layer.
28-61: LGTM!The
createOrAttachmethod cleanly delegates todoCreateOrAttachPersistent, properly handles pending sessions to prevent duplicate creation, and correctly extractsworkspaceIdfrom params. The pending session pattern prevents race conditions from concurrent attach requests.
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (5)
apps/desktop/src/main/lib/terminal/persistence/manager.ts (2)
30-50: Initialization race condition potential.Setting
this.initialized = truebefore async operations complete means concurrent calls toinitialize()will exit early while the first call is still in progress. If callers awaitinitialize()before using the manager, they may get an uninitialized backend.Consider using a promise-based guard:
🔎 Proposed fix
class ProcessPersistence { private backend: PersistenceBackend | null = null; private _enabled = false; - private initialized = false; + private initPromise: Promise<void> | null = null; get enabled(): boolean { return this._enabled; } async initialize(): Promise<void> { - if (this.initialized) return; - this.initialized = true; + if (this.initPromise) return this.initPromise; + this.initPromise = this.doInitialize(); + return this.initPromise; + } + private async doInitialize(): Promise<void> { if (!process.env.SUPERSET_TERMINAL_PERSISTENCE) { return; } // ... rest of initialization }
110-117: Consider parallel session kills for better performance.Sequential kills work correctly but may be slow with many sessions.
Promise.allSettledwould be faster while preserving error handling.🔎 Optional optimization
async killByWorkspace(workspaceId: string): Promise<void> { if (!this.backend) return; const prefix = getWorkspacePrefix(workspaceId); const sessions = await this.backend.listSessions(prefix); - for (const session of sessions) { - await this.backend.killSession(session).catch(() => {}); - } + await Promise.allSettled( + sessions.map((session) => this.backend!.killSession(session)), + ); }apps/desktop/src/main/lib/terminal/persistence/session-lifecycle.ts (1)
221-236: Transition toclosedbefore killing PTY may cause race.In
close(), the state transitions toclosed(line 228) before killing the PTY (line 232). If the PTY'sonExithandler fires synchronously, it will seestate === "closed"and exit early (line 134), which is correct. However, if there's any async gap, the order matters. The current order is safe but slightly fragile.Consider adding a comment clarifying why the transition happens before the kill, or moving
transition("closed")after the PTY cleanup for clarity.apps/desktop/src/main/lib/terminal/manager.ts (2)
566-585: Consider handlingdisconnectedstate more gracefully.When the lifecycle is in
disconnectedstate (e.g., after detach), throwing an error may be too aggressive. Returning early with a warning (likeconnecting/reconnecting) might be more appropriate to avoid breaking callers.🔎 Proposed fix
if (lifecycle.canWrite()) { lifecycle.write(data); } else { const state = lifecycle.getState(); - if (state === "reconnecting" || state === "connecting") { + if (state === "reconnecting" || state === "connecting" || state === "disconnected") { console.warn( `[TerminalManager] Write dropped for ${paneId}: lifecycle in ${state} state`, ); return; } throw new Error( `Cannot write to ${paneId}: lifecycle in ${state} state`, ); }
789-796: Consider parallelizing lifecycle detach operations.The sequential detach loop could slow down workspace cleanup with many sessions. Since detaches are independent, they can be parallelized.
🔎 Proposed fix
// 1. Detach all persistent lifecycles (stops reconnect, no "closed" events) -for (const [paneId] of persistentSessions) { - const lifecycle = this.lifecycles.get(paneId); - if (lifecycle) { - await lifecycle.detach(); - this.lifecycles.delete(paneId); // Delete immediately - } -} +await Promise.all( + persistentSessions.map(async ([paneId]) => { + const lifecycle = this.lifecycles.get(paneId); + if (lifecycle) { + await lifecycle.detach(); + this.lifecycles.delete(paneId); + } + }), +);
📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
apps/desktop/src/main/lib/terminal/manager.tsapps/desktop/src/main/lib/terminal/persistence/manager.tsapps/desktop/src/main/lib/terminal/persistence/session-lifecycle.tsapps/desktop/src/main/lib/terminal/persistence/tmux-backend.tsapps/desktop/src/main/lib/terminal/persistence/types.tsapps/desktop/src/main/lib/terminal/session.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- apps/desktop/src/main/lib/terminal/persistence/tmux-backend.ts
- apps/desktop/src/main/lib/terminal/persistence/types.ts
🧰 Additional context used
📓 Path-based instructions (3)
apps/desktop/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/desktop/AGENTS.md)
apps/desktop/**/*.{ts,tsx}: For Electron interprocess communication, ALWAYS use tRPC as defined insrc/lib/trpc
Use alias as defined intsconfig.jsonwhen possible
Prefer zustand for state management if it makes sense. Do not use effect unless absolutely necessary.
For tRPC subscriptions with trpc-electron, ALWAYS use the observable pattern from@trpc/server/observableinstead of async generators, as the library explicitly checksisObservable(result)and throws an error otherwise
Files:
apps/desktop/src/main/lib/terminal/persistence/session-lifecycle.tsapps/desktop/src/main/lib/terminal/persistence/manager.tsapps/desktop/src/main/lib/terminal/session.tsapps/desktop/src/main/lib/terminal/manager.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use type safety and avoid
anytypes unless absolutely necessary in TypeScript files
Files:
apps/desktop/src/main/lib/terminal/persistence/session-lifecycle.tsapps/desktop/src/main/lib/terminal/persistence/manager.tsapps/desktop/src/main/lib/terminal/session.tsapps/desktop/src/main/lib/terminal/manager.ts
apps/desktop/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Move Node.js functionality needed in Electron renderer to
src/main/lib/and communicate via IPC
Files:
apps/desktop/src/main/lib/terminal/persistence/session-lifecycle.tsapps/desktop/src/main/lib/terminal/persistence/manager.tsapps/desktop/src/main/lib/terminal/session.tsapps/desktop/src/main/lib/terminal/manager.ts
🧠 Learnings (1)
📚 Learning: 2025-12-28T01:56:39.021Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-28T01:56:39.021Z
Learning: Applies to apps/desktop/src/**/*.{ts,tsx} : Move Node.js functionality needed in Electron renderer to `src/main/lib/` and communicate via IPC
Applied to files:
apps/desktop/src/main/lib/terminal/session.ts
🧬 Code graph analysis (2)
apps/desktop/src/main/lib/terminal/persistence/session-lifecycle.ts (3)
apps/desktop/src/main/lib/terminal/persistence/types.ts (3)
SessionState(12-18)PersistenceErrorCode(4-9)PersistenceBackend(20-45)apps/desktop/src/main/lib/terminal/persistence/manager.ts (1)
sessionExists(71-74)apps/desktop/src/main/lib/terminal/persistence/tmux-backend.ts (1)
sessionExists(130-140)
apps/desktop/src/main/lib/terminal/session.ts (4)
apps/desktop/src/main/lib/terminal-history.ts (1)
HistoryReader(163-207)apps/desktop/src/main/lib/terminal/types.ts (1)
TerminalSession(5-25)apps/desktop/src/main/lib/terminal-escape-filter.ts (2)
containsClearScrollbackSequence(29-31)extractContentAfterClear(38-46)apps/desktop/src/shared/parse-cwd.ts (1)
parseCwd(24-39)
🔇 Additional comments (15)
apps/desktop/src/main/lib/terminal/persistence/manager.ts (2)
119-156: LGTM!The orphan cleanup logic is well-structured with proper error handling, age threshold checks, and graceful handling of unknown activity timestamps.
162-170: LGTM!The
createLifecyclemethod correctly enforces that a backend is available before creating a lifecycle, maintaining consistency with other backend-dependent methods.apps/desktop/src/main/lib/terminal/persistence/session-lifecycle.ts (3)
203-219:isDetachingflag is never reset, preventing reattachment.Once
detach()is called,isDetachingremainstrueforever. This prevents the reconnection logic from working (lines 134, 152) if the lifecycle is reused. If reuse after detach is intended, reset the flag inensureAttached.If the lifecycle is expected to be discarded after detach, this is fine. Please confirm whether
SessionLifecycleinstances are reused after detach or always replaced.
112-129: LGTM!The data buffering implementation is sound: it uses a byte-limited buffer (1MB) to prevent unbounded memory growth, handles the handler-not-yet-set case gracefully, and drops excess data rather than crashing.
180-192: LGTM!The
setDataHandlermethod correctly flushes buffered data synchronously and clears the buffer state to release memory.apps/desktop/src/main/lib/terminal/session.ts (4)
110-123: LGTM!Good defensive validation of the working directory. The fallback to homedir with a warning log is appropriate for handling inaccessible directories (deleted, permission denied, etc.).
176-204: LGTM!The
processTerminalChunkhelper cleanly centralizes scrollback, history, CWD tracking, and port scanning. The rolling OSC7 buffer approach correctly preserves only the last 4KB for pattern matching.
264-271: LGTM!The
closeSessionHistoryForDetachhelper provides a clean interface for the detach workflow, correctly clearing thehistoryWriterreference after closing.
212-238: LGTM!The
shouldRunCommandscondition is appropriately strict (not recovered AND initialCommands defined AND non-empty). The refactoredsetupDataHandlerproperly delegates toprocessTerminalChunkand maintains the existing initial command behavior.apps/desktop/src/main/lib/terminal/manager.ts (6)
85-174: LGTM!The
doCreateOrAttachPersistentmethod has well-structured fallback logic: attempt attach → fallback to create → fallback to non-persistent. Error handling appropriately cleans up orphaned sessions and lifecycles before retrying.
214-252: LGTM!The
cleanupSessionmethod is well-designed with identity guards to prevent race conditions. The snapshot oflifecyclebefore await (line 226) ensures the correct lifecycle is checked after async operations. The delayed session deletion with.unref()prevents blocking app shutdown.
312-388: LGTM!The session setup sequence is carefully ordered: create session → store in map → init historyWriter → wire data handler. This ensures data buffered during async initialization is flushed correctly. The previous review concern about missing
historyWriterhas been addressed.
631-655: LGTM!The signal handling correctly differentiates between persistent and non-persistent backends. Mapping SIGINT to
\x03(Ctrl+C) for tmux sessions is appropriate, and escalating other signals to session termination is a sensible fallback.
254-284: LGTM!The lifecycle state change handler correctly propagates state changes to the session and emits appropriate events. The reconnection logic properly updates the PTY reference, and the cleanup on
closedstate is intentionally fire-and-forget to avoid blocking.
929-950: Inconsistentawaitusage indetachAll().Several async operations are not awaited:
- Line 933:
lifecycle.detach()is not awaited- Line 944:
this.kill({ paneId })is not awaited (fire-and-forget withvoid)This could cause issues if the caller expects all sessions to be fully detached when the method returns.
🔎 Proposed fix
async detachAll(): Promise<void> { - for (const [paneId, session] of this.sessions.entries()) { + const detachPromises: Promise<void>[] = []; + + for (const [paneId, session] of this.sessions.entries()) { const lifecycle = this.lifecycles.get(paneId); if (lifecycle) { - lifecycle.detach(); + detachPromises.push(lifecycle.detach()); } if (session.isPersistentBackend && session.isAlive) { session.isExpectedDetach = true; session.isAlive = false; - await closeSessionHistoryForDetach(session); + detachPromises.push(closeSessionHistoryForDetach(session)); try { session.pty.kill(); } catch {} } else { - await this.kill({ paneId }); + detachPromises.push(this.kill({ paneId })); } } + await Promise.all(detachPromises); this.lifecycles.clear(); this.osc7Buffers.clear(); this.sessions.clear(); }Likely an incorrect or invalid review comment.
| this.ptyProcess.onExit(async () => { | ||
| this.ptyProcess = null; | ||
|
|
||
| if (this.disposed || this.state === "closed" || this.isDetaching) return; | ||
|
|
||
| const sessionExists = await this.backend | ||
| .sessionExists(this.sessionName) | ||
| .catch(() => false); | ||
|
|
||
| if (!sessionExists) { | ||
| this.transition("closed"); | ||
| return; | ||
| } | ||
|
|
||
| if (this.retryCount < MAX_RETRIES) { | ||
| this.retryCount++; | ||
| this.transition("reconnecting"); | ||
|
|
||
| const delay = RETRY_DELAYS_MS[this.retryCount - 1] ?? 1000; | ||
| await new Promise((r) => setTimeout(r, delay)); | ||
|
|
||
| if (!this.disposed && !this.isDetaching) { | ||
| await this.doAttach( | ||
| this.lastDimensions.cols, | ||
| this.lastDimensions.rows, | ||
| ); | ||
| } | ||
| } else { | ||
| this.events.onError( | ||
| "ATTACH_FAILED", | ||
| `Max retries (${MAX_RETRIES}) exhausted`, | ||
| ); | ||
| this.transition("failed"); | ||
| } | ||
| }); |
There was a problem hiding this comment.
Missing error handling in onExit retry path.
If doAttach throws during reconnection (line 153-156), the error is unhandled and may cause an unhandled promise rejection. The error should be caught to prevent crashes.
🔎 Proposed fix
if (!this.disposed && !this.isDetaching) {
- await this.doAttach(
- this.lastDimensions.cols,
- this.lastDimensions.rows,
- );
+ try {
+ await this.doAttach(
+ this.lastDimensions.cols,
+ this.lastDimensions.rows,
+ );
+ } catch (error) {
+ // doAttach handles its own state transitions and error reporting
+ console.warn("[SessionLifecycle] Reconnect attempt failed:", error);
+ }
}📝 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.
| this.ptyProcess.onExit(async () => { | |
| this.ptyProcess = null; | |
| if (this.disposed || this.state === "closed" || this.isDetaching) return; | |
| const sessionExists = await this.backend | |
| .sessionExists(this.sessionName) | |
| .catch(() => false); | |
| if (!sessionExists) { | |
| this.transition("closed"); | |
| return; | |
| } | |
| if (this.retryCount < MAX_RETRIES) { | |
| this.retryCount++; | |
| this.transition("reconnecting"); | |
| const delay = RETRY_DELAYS_MS[this.retryCount - 1] ?? 1000; | |
| await new Promise((r) => setTimeout(r, delay)); | |
| if (!this.disposed && !this.isDetaching) { | |
| await this.doAttach( | |
| this.lastDimensions.cols, | |
| this.lastDimensions.rows, | |
| ); | |
| } | |
| } else { | |
| this.events.onError( | |
| "ATTACH_FAILED", | |
| `Max retries (${MAX_RETRIES}) exhausted`, | |
| ); | |
| this.transition("failed"); | |
| } | |
| }); | |
| this.ptyProcess.onExit(async () => { | |
| this.ptyProcess = null; | |
| if (this.disposed || this.state === "closed" || this.isDetaching) return; | |
| const sessionExists = await this.backend | |
| .sessionExists(this.sessionName) | |
| .catch(() => false); | |
| if (!sessionExists) { | |
| this.transition("closed"); | |
| return; | |
| } | |
| if (this.retryCount < MAX_RETRIES) { | |
| this.retryCount++; | |
| this.transition("reconnecting"); | |
| const delay = RETRY_DELAYS_MS[this.retryCount - 1] ?? 1000; | |
| await new Promise((r) => setTimeout(r, delay)); | |
| if (!this.disposed && !this.isDetaching) { | |
| try { | |
| await this.doAttach( | |
| this.lastDimensions.cols, | |
| this.lastDimensions.rows, | |
| ); | |
| } catch (error) { | |
| // doAttach handles its own state transitions and error reporting | |
| console.warn("[SessionLifecycle] Reconnect attempt failed:", error); | |
| } | |
| } | |
| } else { | |
| this.events.onError( | |
| "ATTACH_FAILED", | |
| `Max retries (${MAX_RETRIES}) exhausted`, | |
| ); | |
| this.transition("failed"); | |
| } | |
| }); |
🤖 Prompt for AI Agents
In apps/desktop/src/main/lib/terminal/persistence/session-lifecycle.ts around
lines 131 to 165, the awaited call to this.doAttach(...) in the onExit retry
path is not wrapped in error handling; wrap the await this.doAttach(...) call in
a try/catch, and in the catch block call this.events.onError("ATTACH_FAILED",
String(err)) (include useful error text), then transition to "failed"
(this.transition("failed")) or otherwise stop retrying to avoid unhandled
promise rejections.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
apps/desktop/src/main/lib/terminal/manager.ts (2)
729-733: Missing promise rejection handler onlifecycle.detach().
lifecycle.detach()is an async method but is called withoutawaitor.catch(). While the commit message mentions fixing fire-and-forget async calls forcleanupSessionandkill, this call was not addressed and could still lead to unhandled promise rejections.🔎 Proposed fix
const lifecycle = this.lifecycles.get(paneId); if (lifecycle) { - lifecycle.detach(); + lifecycle.detach().catch((err) => + console.error(`[TerminalManager] detach failed for ${paneId}:`, err), + ); this.lifecycles.delete(paneId); }
965-968: Missing promise rejection handlers onlifecycle.close()calls.The
lifecycle.close()calls are not awaited and lack.catch()handlers, which could lead to unhandled promise rejections. Consistent with the approach for other async calls, these should either be awaited or have rejection handlers.🔎 Proposed fix
async cleanup(): Promise<void> { - for (const lifecycle of this.lifecycles.values()) { - lifecycle.close(); - } + for (const lifecycle of this.lifecycles.values()) { + lifecycle.close().catch((err) => + console.error('[TerminalManager] lifecycle.close failed:', err), + ); + } this.lifecycles.clear();Or, to ensure all closes complete before proceeding:
async cleanup(): Promise<void> { - for (const lifecycle of this.lifecycles.values()) { - lifecycle.close(); - } + await Promise.allSettled( + Array.from(this.lifecycles.values()).map((lifecycle) => + lifecycle.close().catch((err) => + console.error('[TerminalManager] lifecycle.close failed:', err), + ), + ), + ); this.lifecycles.clear();
📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
apps/desktop/src/main/lib/terminal/manager.ts
🧰 Additional context used
📓 Path-based instructions (3)
apps/desktop/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/desktop/AGENTS.md)
apps/desktop/**/*.{ts,tsx}: For Electron interprocess communication, ALWAYS use tRPC as defined insrc/lib/trpc
Use alias as defined intsconfig.jsonwhen possible
Prefer zustand for state management if it makes sense. Do not use effect unless absolutely necessary.
For tRPC subscriptions with trpc-electron, ALWAYS use the observable pattern from@trpc/server/observableinstead of async generators, as the library explicitly checksisObservable(result)and throws an error otherwise
Files:
apps/desktop/src/main/lib/terminal/manager.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use type safety and avoid
anytypes unless absolutely necessary in TypeScript files
Files:
apps/desktop/src/main/lib/terminal/manager.ts
apps/desktop/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Move Node.js functionality needed in Electron renderer to
src/main/lib/and communicate via IPC
Files:
apps/desktop/src/main/lib/terminal/manager.ts
🔇 Additional comments (7)
apps/desktop/src/main/lib/terminal/manager.ts (7)
50-59: Good error recovery for failed persistent sessions.The retry logic for failed lifecycle states is well-designed. When a session exists but its lifecycle is in a failed state, the code attempts to reattach and updates the PTY reference if successful.
86-175: Well-structured persistence flow with proper fallback handling.The method correctly separates attach/create/fallback paths with comprehensive error handling. The orphaned session cleanup (lines 121-128) and fallback to non-persistent sessions (lines 171-175) provide good resilience.
217-255: Excellent use of identity guards to prevent race conditions.The unified cleanup method properly handles concurrent session replacements by checking
this.sessions.get(paneId) !== sessionafter async operations. The delayed cleanup withunref()is also well-designed to prevent blocking process exit.
284-289: Good addition of.catch()handler for fire-and-forget async call.This properly handles potential promise rejections from the async
cleanupSessioncall, as mentioned in the commit message.
320-396: Well-designed session initialization sequence.The numbered comments (lines 338, 359, 362, 373) clearly explain why the session must be stored before async history initialization. This ensures the data handler can find the session when processing buffered data.
662-664: Good addition of.catch()handler for async kill call.This properly handles potential promise rejections from the async
killmethod.
685-701: Well-structured persistent session termination.The kill path for persistent sessions correctly sequences: detach → delete lifecycle → kill backend → cleanup. Deleting the lifecycle immediately (line 691) prevents race conditions with writes/resizes.
| const lifecycle = this.lifecycles.get(paneId); | ||
| if (lifecycle) { | ||
| lifecycle.detach(); | ||
| } |
There was a problem hiding this comment.
Missing promise rejection handler on lifecycle.detach().
Similar to line 731, lifecycle.detach() is called without await or .catch(), which could lead to unhandled promise rejections. For consistency with the fixes mentioned in the commit message, this should also have a rejection handler.
🔎 Proposed fix
for (const [paneId, session] of this.sessions.entries()) {
const lifecycle = this.lifecycles.get(paneId);
if (lifecycle) {
- lifecycle.detach();
+ lifecycle.detach().catch((err) =>
+ console.error(`[TerminalManager] detach failed for ${paneId}:`, err),
+ );
}🤖 Prompt for AI Agents
In apps/desktop/src/main/lib/terminal/manager.ts around lines 943 to 946,
lifecycle.detach() is invoked without handling its returned Promise, which can
produce unhandled rejections; update the call to either await lifecycle.detach()
if the surrounding function is async, or append a rejection handler like
lifecycle.detach().catch(err => { /* log or handle error */ }) (or use void
lifecycle.detach().catch(...)) so any errors are caught and handled consistently
with the fix at line 731.
935eaf6 to
3fa5192
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (4)
apps/desktop/src/main/lib/terminal/persistence/session-lifecycle.ts (1)
131-165: Missing error handling in onExit retry path.The
doAttachcall at lines 153-156 is not wrapped in try/catch. If it throws, the error will be unhandled. This was flagged in a previous review.🔎 Proposed fix
if (!this.disposed && !this.isDetaching) { - await this.doAttach( - this.lastDimensions.cols, - this.lastDimensions.rows, - ); + try { + await this.doAttach( + this.lastDimensions.cols, + this.lastDimensions.rows, + ); + } catch (error) { + // doAttach handles its own state transitions + console.warn("[SessionLifecycle] Reconnect attempt failed:", error); + } }apps/desktop/src/main/lib/terminal/manager.ts (3)
729-733: Missing promise rejection handler onlifecycle.detach().Line 731 calls
lifecycle.detach()withoutawaitor.catch(), which can lead to unhandled promise rejections. This is inconsistent with the fixes applied at lines 284 and 662-664 where fire-and-forget async calls properly handle rejections.🔎 Recommended fix
const lifecycle = this.lifecycles.get(paneId); if (lifecycle) { - lifecycle.detach(); + lifecycle.detach().catch((err) => + console.error(`[TerminalManager] detach failed for ${paneId}:`, err), + ); this.lifecycles.delete(paneId); }
943-946: Missing promise rejection handler onlifecycle.detach()in detachAll.Line 945 calls
lifecycle.detach()without.catch(), inconsistent with the fixes applied elsewhere (lines 284, 662-664, and 731 above). Fire-and-forget async calls must handle rejections to prevent unhandled promise rejection warnings.🔎 Recommended fix
for (const [paneId, session] of this.sessions.entries()) { const lifecycle = this.lifecycles.get(paneId); if (lifecycle) { - lifecycle.detach(); + lifecycle.detach().catch((err) => + console.error(`[TerminalManager] detach failed for ${paneId}:`, err), + ); }
964-968: Missingawaitonlifecycle.close()calls.Lines 965-967 call
lifecycle.close()without awaiting, so lifecycles may not finish closing before the map is cleared. A past review comment claimed this was addressed in commit c4060fe, but the fire-and-forget pattern remains. For consistency with other async cleanup patterns in this file, these should be awaited.🔎 Recommended fix
async cleanup(): Promise<void> { - for (const lifecycle of this.lifecycles.values()) { - lifecycle.close(); - } + await Promise.all( + Array.from(this.lifecycles.values()).map((lifecycle) => + lifecycle.close().catch((err) => + console.error('[TerminalManager] lifecycle.close() failed:', err), + ), + ), + ); this.lifecycles.clear();
🧹 Nitpick comments (2)
apps/desktop/src/main/lib/terminal-history.ts (1)
169-177: Consider adding type validation for parsed metadata.The
JSON.parseresult is cast directly toSessionMetadatawithout validation. If the file is corrupted or has an unexpected schema, this could cause runtime issues downstream.🔎 Proposed fix with basic validation
async readMetadata(): Promise<SessionMetadata | null> { try { const metaPath = getMetadataPath(this.workspaceId, this.paneId); const metaContent = await fs.readFile(metaPath, "utf-8"); - return JSON.parse(metaContent); + const parsed = JSON.parse(metaContent); + // Basic validation - ensure required fields exist + if (typeof parsed?.cwd === "string") { + return parsed as SessionMetadata; + } + return null; } catch { return null; } }apps/desktop/src/main/lib/terminal/persistence/manager.ts (1)
119-156: Consider logging when orphan sessions are preserved due to recent activity.The cleanup logic correctly:
- Compares backend sessions against known panes
- Uses age-based eviction (72-hour threshold)
- Preserves sessions with unknown age
However, it only logs when cleaning stale orphans (line 146-148) but not when preserving young orphans. Adding a log at the skip path would help with debugging.
🔎 Proposed logging addition
if (age > MAX_ORPHAN_AGE_MS) { console.log( `[ProcessPersistence] Cleaning stale orphan: ${session}`, ); await this.backend.killSession(session).catch(() => {}); + } else { + console.log( + `[ProcessPersistence] Keeping recent orphan (age: ${Math.round(age / 1000 / 60)}min): ${session}`, + ); }
📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (16)
apps/desktop/src/lib/electron-app/factories/app/setup.tsapps/desktop/src/lib/trpc/routers/terminal/terminal.tsapps/desktop/src/main/index.tsapps/desktop/src/main/lib/terminal-history.tsapps/desktop/src/main/lib/terminal/manager.tsapps/desktop/src/main/lib/terminal/persistence/manager.tsapps/desktop/src/main/lib/terminal/persistence/session-lifecycle.tsapps/desktop/src/main/lib/terminal/persistence/tmux-backend.tsapps/desktop/src/main/lib/terminal/persistence/types.tsapps/desktop/src/main/lib/terminal/session.tsapps/desktop/src/main/lib/terminal/types.tsapps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsxapps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/suppressQueryResponses.tsapps/desktop/src/shared/parse-cwd.tsapps/desktop/src/shared/terminal-scrollback-sanitizer.test.tsapps/desktop/src/shared/terminal-scrollback-sanitizer.ts
💤 Files with no reviewable changes (1)
- apps/desktop/src/lib/electron-app/factories/app/setup.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- apps/desktop/src/lib/trpc/routers/terminal/terminal.ts
- apps/desktop/src/main/index.ts
- apps/desktop/src/main/lib/terminal/types.ts
🧰 Additional context used
📓 Path-based instructions (6)
apps/desktop/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/desktop/AGENTS.md)
apps/desktop/**/*.{ts,tsx}: For Electron interprocess communication, ALWAYS use tRPC as defined insrc/lib/trpc
Use alias as defined intsconfig.jsonwhen possible
Prefer zustand for state management if it makes sense. Do not use effect unless absolutely necessary.
For tRPC subscriptions with trpc-electron, ALWAYS use the observable pattern from@trpc/server/observableinstead of async generators, as the library explicitly checksisObservable(result)and throws an error otherwise
Files:
apps/desktop/src/shared/terminal-scrollback-sanitizer.tsapps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/suppressQueryResponses.tsapps/desktop/src/main/lib/terminal/persistence/session-lifecycle.tsapps/desktop/src/main/lib/terminal/persistence/manager.tsapps/desktop/src/shared/parse-cwd.tsapps/desktop/src/main/lib/terminal-history.tsapps/desktop/src/shared/terminal-scrollback-sanitizer.test.tsapps/desktop/src/main/lib/terminal/session.tsapps/desktop/src/main/lib/terminal/manager.tsapps/desktop/src/main/lib/terminal/persistence/tmux-backend.tsapps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsxapps/desktop/src/main/lib/terminal/persistence/types.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use type safety and avoid
anytypes unless absolutely necessary in TypeScript files
Files:
apps/desktop/src/shared/terminal-scrollback-sanitizer.tsapps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/suppressQueryResponses.tsapps/desktop/src/main/lib/terminal/persistence/session-lifecycle.tsapps/desktop/src/main/lib/terminal/persistence/manager.tsapps/desktop/src/shared/parse-cwd.tsapps/desktop/src/main/lib/terminal-history.tsapps/desktop/src/shared/terminal-scrollback-sanitizer.test.tsapps/desktop/src/main/lib/terminal/session.tsapps/desktop/src/main/lib/terminal/manager.tsapps/desktop/src/main/lib/terminal/persistence/tmux-backend.tsapps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsxapps/desktop/src/main/lib/terminal/persistence/types.ts
apps/desktop/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Move Node.js functionality needed in Electron renderer to
src/main/lib/and communicate via IPC
Files:
apps/desktop/src/shared/terminal-scrollback-sanitizer.tsapps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/suppressQueryResponses.tsapps/desktop/src/main/lib/terminal/persistence/session-lifecycle.tsapps/desktop/src/main/lib/terminal/persistence/manager.tsapps/desktop/src/shared/parse-cwd.tsapps/desktop/src/main/lib/terminal-history.tsapps/desktop/src/shared/terminal-scrollback-sanitizer.test.tsapps/desktop/src/main/lib/terminal/session.tsapps/desktop/src/main/lib/terminal/manager.tsapps/desktop/src/main/lib/terminal/persistence/tmux-backend.tsapps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsxapps/desktop/src/main/lib/terminal/persistence/types.ts
**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Co-locate tests with their source files using the same folder structure (e.g.,
ComponentName.test.tsxnext toComponentName.tsx)
Files:
apps/desktop/src/shared/terminal-scrollback-sanitizer.test.ts
apps/**/src/**/**/[A-Z]*.tsx
📄 CodeRabbit inference engine (AGENTS.md)
Structure component folders with one component per file using format
ComponentName/ComponentName.tsxwithindex.tsbarrel export
Files:
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
apps/desktop/src/{shared/ipc-channels.ts,main/**/*ipcs.ts,renderer/**/*.tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Define all Electron IPC channel types in
apps/desktop/src/shared/ipc-channels.tsbefore implementing handlers
Files:
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
🧠 Learnings (3)
📚 Learning: 2025-12-28T01:56:39.021Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-28T01:56:39.021Z
Learning: Applies to apps/desktop/src/**/*.{ts,tsx} : Move Node.js functionality needed in Electron renderer to `src/main/lib/` and communicate via IPC
Applied to files:
apps/desktop/src/main/lib/terminal/persistence/manager.tsapps/desktop/src/shared/parse-cwd.tsapps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx
📚 Learning: 2025-12-28T01:56:39.021Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-28T01:56:39.021Z
Learning: Applies to apps/desktop/src/{renderer,lib/electron-router-dom.ts} : Never import Node.js modules in Electron renderer or shared code (`src/renderer/` and `src/lib/electron-router-dom.ts`)
Applied to files:
apps/desktop/src/shared/parse-cwd.ts
📚 Learning: 2025-12-28T01:56:39.021Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-28T01:56:39.021Z
Learning: Applies to apps/desktop/src/{shared/ipc-channels.ts,main/**/*ipcs.ts,renderer/**/*.tsx} : Define all Electron IPC channel types in `apps/desktop/src/shared/ipc-channels.ts` before implementing handlers
Applied to files:
apps/desktop/src/shared/parse-cwd.tsapps/desktop/src/main/lib/terminal/persistence/types.ts
🧬 Code graph analysis (4)
apps/desktop/src/main/lib/terminal/persistence/session-lifecycle.ts (3)
apps/desktop/src/main/lib/terminal/persistence/types.ts (3)
SessionState(12-18)PersistenceErrorCode(4-9)PersistenceBackend(20-45)apps/desktop/src/main/lib/terminal/persistence/manager.ts (1)
sessionExists(71-74)apps/desktop/src/main/lib/terminal/persistence/tmux-backend.ts (1)
sessionExists(130-140)
apps/desktop/src/shared/terminal-scrollback-sanitizer.test.ts (1)
apps/desktop/src/shared/terminal-scrollback-sanitizer.ts (1)
sanitizeTerminalScrollback(47-65)
apps/desktop/src/main/lib/terminal/persistence/tmux-backend.ts (2)
apps/desktop/src/main/lib/app-environment.ts (1)
SUPERSET_HOME_DIR(5-5)apps/desktop/src/main/lib/terminal/persistence/types.ts (2)
CreatePersistentSessionParams(47-52)PersistenceErrorCode(4-9)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (1)
apps/desktop/src/shared/terminal-scrollback-sanitizer.ts (1)
sanitizeTerminalScrollback(47-65)
🪛 ast-grep (0.40.3)
apps/desktop/src/shared/terminal-scrollback-sanitizer.ts
[warning] 16-16: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(${ESC}\\[[?>]?[0-9;]*c, "g")
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html
(regexp-from-variable)
[warning] 17-17: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(${ESC}\\[[?>]?[0-9;]*R, "g")
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html
(regexp-from-variable)
[warning] 18-18: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(${ESC}\\[[?>]?[0-9;]*\\$y, "g")
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html
(regexp-from-variable)
[warning] 19-19: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(${ESC}\\[<\\d+(?:;\\d+){2}[Mm], "g")
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html
(regexp-from-variable)
🔇 Additional comments (34)
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/suppressQueryResponses.ts (1)
37-44: LGTM! Defensive suppression for SGR mouse tracking.The implementation correctly suppresses SGR mouse tracking reports (CSI
<...M/m) that can leak into the PTY output stream during session restore or reconnection. The handlers follow the established pattern, properly returntrueto suppress display, and are integrated into the disposables collection for cleanup.Note: While these sequences are technically input reports rather than query responses, suppressing them here is appropriate defensive programming to prevent them from appearing as visible text when buffered data is replayed.
apps/desktop/src/shared/parse-cwd.ts (1)
6-8: LGTM!The added documentation clearly communicates the cross-process usage constraint. This aligns with the coding guidelines that prohibit Node.js modules in shared code between main and renderer processes.
apps/desktop/src/main/lib/terminal-history.ts (2)
87-110: LGTM!The debounced metadata write implementation is well-structured:
- Properly clears existing timeout before scheduling new one
- Uses
unref()to prevent blocking process exit- Handles write errors gracefully with a warning log
- 1-second debounce is reasonable for CWD updates
112-134: LGTM!The
closeForDetachmethod correctly handles the graceful detach flow: clearing pending writes, awaiting stream close, and persisting metadata. Silent error handling is appropriate here since this is a best-effort operation during detach.apps/desktop/src/main/lib/terminal/session.ts (5)
24-53: LGTM!The updated
recoverScrollbackfunction properly:
- Reads metadata to extract
savedCwd- Sanitizes scrollback data using the shared sanitizer
- Returns the
savedCwdin all code paths for CWD restoration
112-125: LGTM!Robust CWD validation that gracefully falls back to
homedir()when the target directory is inaccessible. Thereaddircheck ensures the directory is actually listable, not just that it exists.
178-212: LGTM!Well-designed centralized data processing:
- Rolling OSC-7 buffer (4KB) efficiently tracks CWD changes
- Fire-and-forget
onClearScrollbackproperly has.catch()to avoid unhandled rejections- Sanitization applied before storing in scrollback and history
- Clean separation of concerns
220-246: LGTM!The refactored
setupDataHandlercleanly delegates toprocessTerminalChunkand has stricter command execution logic. The guard at line 240 (initialCommands) is redundant given theshouldRunCommandscheck, but harmless and adds clarity.
272-279: LGTM!Clean addition of
closeSessionHistoryForDetachto support graceful detach without marking the session as ended.apps/desktop/src/shared/terminal-scrollback-sanitizer.test.ts (1)
1-39: LGTM!Comprehensive test coverage for the sanitizer including:
- Both raw and caret-escaped escape sequences
- Heuristic payload detection
- Critical preservation test for SGR styling (line 35-38)
Consider adding edge case tests for empty string and data without any escape sequences to verify the fast-path behavior, but current coverage is solid.
apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx (3)
13-14: LGTM!Good migration to shared modules - both
parseCwdandsanitizeTerminalScrollbackare now imported from the shared directory, ensuring cross-process compatibility without Node.js dependencies.
145-147: Verify CWD parsing uses raw data.Sanitization is correctly applied before
xterm.write(), but note thatupdateCwdFromData(event.data)at line 147 correctly receives the raw (unsanitized) data - this is important since OSC-7 sequences would be stripped by sanitization.
228-248: LGTM!Consistent sanitization pattern applied to both pending event flushes and initial state application. The CWD update at lines 231 and 247 correctly uses the raw data to preserve OSC-7 sequences for parsing.
apps/desktop/src/shared/terminal-scrollback-sanitizer.ts (3)
1-12: LGTM!Excellent documentation explaining:
- The shared nature of the module (no Node.js deps)
- Why sanitization is needed (terminal responses leaking into scrollback)
- What is preserved vs. stripped
14-45: Static analysis warnings are false positives - ESC is a compile-time constant.The ast-grep warnings about "regex from variable input" are incorrect here.
ESCis defined as a constant string"\x1b"at compile time, not user input. There is no ReDoS risk since:
- The patterns are fixed at module load
- Input data is terminal output, not attacker-controlled regex
The regex patterns themselves use bounded quantifiers (
{1,4},{2,}) and character classes that prevent catastrophic backtracking.
47-65: LGTM!The function implementation is efficient:
- Fast-path short-circuits when no escape markers are present
- Sequential pattern replacement is clear and maintainable
- DA_PAYLOAD replacement preserves leading whitespace via capture group
apps/desktop/src/main/lib/terminal/persistence/manager.ts (3)
30-50: LGTM!Initialization is properly gated:
- Environment variable check (
SUPERSET_TERMINAL_PERSISTENCE)- Platform check (Windows excluded)
- Backend availability verification
- Idempotent via
initializedflag
52-69: LGTM!Minimal tmux configuration that:
- Disables prefix key to avoid conflicts
- Disables mouse and status bar
- Sets reasonable history limit (50,000 lines)
- Configures terminal for 256-color support
110-117: LGTM!
killByWorkspacecorrectly iterates through sessions and uses.catch(() => {})on each kill to prevent unhandled rejections, per the PR objectives for fire-and-forget async calls.apps/desktop/src/main/lib/terminal/persistence/session-lifecycle.ts (5)
17-35: LGTM!Clean class structure with well-chosen defaults:
- 1MB buffer limit prevents memory exhaustion
isDetachingflag distinguishes intentional disconnects from failuresdisposedflag prevents operations after close
52-75: LGTM!Good attach promise deduplication pattern - prevents multiple concurrent attach attempts while allowing callers to await the result.
112-129: LGTM!Data buffering implementation is well-designed:
- Calculates byte length properly for UTF-8
- Silently drops data when buffer is full (bounded memory)
- Flushes buffer when handler is set
203-219: LGTM!The
detach()method properly:
- Sets
isDetachingflag first to prevent reconnect attempts inonExit- Clears buffer to release memory
- Kills PTY and transitions to disconnected state
221-247: LGTM!The
close()andretry()methods are well-implemented:
close()setsdisposedflag first to prevent any further operationsretry()resets retry count and delegates toensureAttached- Both clear buffers appropriately
apps/desktop/src/main/lib/terminal/persistence/types.ts (1)
1-52: LGTM! Well-designed type definitions.The persistence type definitions are clean and well-structured:
PersistenceErrorCodeprovides clear error classificationSessionStatedocuments lifecycle transitions with inline commentsPersistenceBackendinterface uses a literal type forname(line 21), ensuring type safety- Optional methods are appropriately marked
apps/desktop/src/main/lib/terminal/persistence/tmux-backend.ts (4)
31-58: Excellent security practices with environment filtering and shell quoting.The implementation properly restricts environment variables to a whitelist (lines 31-46) and uses robust shell quoting (lines 48-50) to prevent injection attacks. The
buildSafeEnvForScriptfunction ensures only approved variables are passed to wrapper scripts.
60-81: MD5 usage is appropriate for session naming.Using MD5 for hashing workspace and pane IDs into session names is acceptable here since this is not a cryptographic use case—just deterministic name generation to avoid collisions.
157-179: Well-implemented session creation with proper script handling.The wrapper script approach is clean:
- Exports filtered environment variables (lines 166-168)
- Uses
execto replace the wrapper process (line 169), avoiding an extra process layer- Sets appropriate file mode
0o755(line 173)- Properly quotes all shell arguments
181-200: Attachment logic correctly prevents nested tmux.Setting
TMUX: undefined(line 185) prevents nested tmux sessions, and detaching existing clients first (line 188) ensures clean attachment. The-dflag on line 192 properly detaches other clients during attach.apps/desktop/src/main/lib/terminal/manager.ts (5)
217-255: Excellent unified cleanup with identity guards.The
cleanupSessionmethod is well-designed:
- Idempotent cleanup timeout clearing (lines 223-226)
- Snapshots lifecycle before async operations (line 229)
- Identity guards after await to prevent use-after-free bugs (lines 237-239, 244, 250)
- Delayed session cleanup with unref (lines 249-254)
This is a robust pattern for managing lifecycle state across async boundaries.
320-396: Proper sequencing prevents race conditions in lifecycle setup.The ordering is critical and correctly implemented:
- Create session object without historyWriter (lines 339-357)
- Store session in map BEFORE async init (line 360)—ensures data handler can find it
- Initialize historyWriter asynchronously (lines 363-371)
- Attach historyWriter to session (line 371)
- Wire data handler last to flush any buffered data (line 374)
This avoids race conditions where data arrives before the session is ready.
50-59: Good recovery mechanism for failed lifecycle state.The auto-retry logic for failed sessions (lines 54-58) properly updates the PTY after successful reconnection, ensuring the session continues working. This provides a smooth user experience when transient failures occur.
687-701: Well-separated persistent vs non-persistent kill paths.The kill logic correctly differentiates between persistent and non-persistent sessions:
- Persistent: detach → delete lifecycle immediately → kill tmux → manual cleanup + emit (lines 689-701)
- Non-persistent: close lifecycle → kill PTY → let setupExitHandler handle cleanup (lines 703-711)
The immediate lifecycle deletion (line 691) prevents further writes/resizes, which is the right behavior.
789-823: Coordinated workspace-level cleanup with proper sequencing.The persistent session cleanup for
killByWorkspaceIdfollows the correct order:
- Detach all lifecycles to stop reconnects (lines 802-808)—properly awaited at line 805 ✓
- Kill all tmux sessions in batch (line 811)
- Manual cleanup and emit for each session (lines 814-823)
This prevents race conditions and ensures consistent state.
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (3)
apps/desktop/src/main/lib/terminal/manager.ts (3)
963-963: Missing promise rejection handler onlifecycle.detach().Similar to line 749,
lifecycle.detach()is called withoutawaitor.catch(), which can lead to unhandled promise rejections. This matches the unresolved past review comment for lines 961-964.🔎 Proposed fix
for (const [paneId, session] of this.sessions.entries()) { const lifecycle = this.lifecycles.get(paneId); if (lifecycle) { - lifecycle.detach(); + lifecycle.detach().catch((err) => + console.error(`[TerminalManager] detach failed for ${paneId}:`, err), + ); }
983-986: Missingawaitonlifecycle.close()calls.The
lifecycle.close()method is async but these calls are fire-and-forget. Lifecycles may not be fully closed before the map is cleared.Note: A past review comment flagged this issue as addressed in commit c4060fe, but the code still shows the fire-and-forget pattern.
🔎 Proposed fix
async cleanup(): Promise<void> { - for (const lifecycle of this.lifecycles.values()) { - lifecycle.close(); - } + await Promise.all( + Array.from(this.lifecycles.values()).map((lifecycle) => lifecycle.close()), + ); this.lifecycles.clear();
749-749: Missing promise handling onlifecycle.detach().The
lifecycle.detach()method returns a Promise but is called here withoutawaitor.catch(). This can cause unhandled promise rejections and the lifecycle may not be fully detached before the PTY is killed.Note: A past review comment flagged this issue as addressed, but the code still shows the fire-and-forget call.
🔎 Proposed fix
Since
detach()is synchronous in its critical path (stops reconnection), you can use fire-and-forget with error handling:const lifecycle = this.lifecycles.get(paneId); if (lifecycle) { - lifecycle.detach(); + lifecycle.detach().catch((err) => + console.error(`[TerminalManager] detach failed for ${paneId}:`, err), + ); this.lifecycles.delete(paneId); }
🧹 Nitpick comments (3)
apps/desktop/src/shared/terminal-scrollback-sanitizer.ts (1)
14-20: Static analysis warnings are false positives; consider literal regex for cleaner code.The ast-grep warnings flag these as ReDoS risks because regex is "constructed from variable input." However,
ESCis a compile-time constant (\x1b), not user input, making these false positives. Additionally, the regex patterns themselves are linear with no nested quantifiers that could cause catastrophic backtracking.That said, using literal regex patterns would silence the warnings and slightly improve readability.
🔎 Optional: Use literal regex patterns
const ESC = "\x1b"; // Raw control sequence variants -const DA_RESPONSE_RAW = new RegExp(`${ESC}\\[[?>]?[0-9;]*c`, "g"); -const CPR_RESPONSE_RAW = new RegExp(`${ESC}\\[[?>]?[0-9;]*R`, "g"); -const MODE_REPORT_RAW = new RegExp(`${ESC}\\[[?>]?[0-9;]*\\$y`, "g"); -const MOUSE_SGR_RAW = new RegExp(`${ESC}\\[<\\d+(?:;\\d+){2}[Mm]`, "g"); +const DA_RESPONSE_RAW = /\x1b\[[?>]?[0-9;]*c/g; +const CPR_RESPONSE_RAW = /\x1b\[[?>]?[0-9;]*R/g; +const MODE_REPORT_RAW = /\x1b\[[?>]?[0-9;]*\$y/g; +const MOUSE_SGR_RAW = /\x1b\[<\d+(?:;\d+){2}[Mm]/g;apps/desktop/src/main/lib/terminal/persistence/manager.ts (1)
111-118: Consider logging errors during workspace session cleanup.Line 116 silently ignores all errors when killing sessions. While this allows cleanup to continue despite failures, it could make debugging difficult if kills consistently fail. Consider logging errors to aid troubleshooting.
🔎 Suggested improvement
for (const session of sessions) { - await this.backend.killSession(session).catch(() => {}); + await this.backend.killSession(session).catch((error) => { + console.warn(`[ProcessPersistence] Failed to kill session ${session}:`, error); + }); }apps/desktop/src/main/lib/terminal/manager.ts (1)
32-32: OSC7_BUFFER_SIZE constant declared but never used.The constant
OSC7_BUFFER_SIZE = 4096is defined but theosc7BuffersMap entries are never bounded to this size. This could lead to memory growth if terminal output accumulates large OSC-7 sequences.🔎 Suggested fix
Either remove the unused constant if no size limit is intended, or apply the limit when storing OSC-7 buffers. For example, in
handleLifecycleData:private handleLifecycleData(paneId: string, data: string): void { const session = this.sessions.get(paneId); if (!session) return; const osc7Buffer = this.osc7Buffers.get(paneId) ?? ""; const { newOsc7Buffer } = processTerminalChunk( session, data, osc7Buffer, () => reinitializeHistory(session), ); - this.osc7Buffers.set(paneId, newOsc7Buffer); + const bounded = newOsc7Buffer.length > OSC7_BUFFER_SIZE + ? newOsc7Buffer.slice(-OSC7_BUFFER_SIZE) + : newOsc7Buffer; + this.osc7Buffers.set(paneId, bounded); }
📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
apps/desktop/electron-builder.tsapps/desktop/src/main/lib/terminal/manager.tsapps/desktop/src/main/lib/terminal/persistence/manager.tsapps/desktop/src/shared/terminal-scrollback-sanitizer.tsturbo.jsonc
🧰 Additional context used
📓 Path-based instructions (3)
apps/desktop/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/desktop/AGENTS.md)
apps/desktop/**/*.{ts,tsx}: For Electron interprocess communication, ALWAYS use tRPC as defined insrc/lib/trpc
Use alias as defined intsconfig.jsonwhen possible
Prefer zustand for state management if it makes sense. Do not use effect unless absolutely necessary.
For tRPC subscriptions with trpc-electron, ALWAYS use the observable pattern from@trpc/server/observableinstead of async generators, as the library explicitly checksisObservable(result)and throws an error otherwise
Files:
apps/desktop/electron-builder.tsapps/desktop/src/shared/terminal-scrollback-sanitizer.tsapps/desktop/src/main/lib/terminal/persistence/manager.tsapps/desktop/src/main/lib/terminal/manager.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use type safety and avoid
anytypes unless absolutely necessary in TypeScript files
Files:
apps/desktop/electron-builder.tsapps/desktop/src/shared/terminal-scrollback-sanitizer.tsapps/desktop/src/main/lib/terminal/persistence/manager.tsapps/desktop/src/main/lib/terminal/manager.ts
apps/desktop/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Move Node.js functionality needed in Electron renderer to
src/main/lib/and communicate via IPC
Files:
apps/desktop/src/shared/terminal-scrollback-sanitizer.tsapps/desktop/src/main/lib/terminal/persistence/manager.tsapps/desktop/src/main/lib/terminal/manager.ts
🧠 Learnings (3)
📚 Learning: 2025-12-28T01:56:39.021Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-28T01:56:39.021Z
Learning: Applies to apps/desktop/src/**/*.{ts,tsx} : Move Node.js functionality needed in Electron renderer to `src/main/lib/` and communicate via IPC
Applied to files:
apps/desktop/src/main/lib/terminal/persistence/manager.ts
📚 Learning: 2025-12-28T01:56:39.021Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-28T01:56:39.021Z
Learning: Applies to apps/desktop/src/main/index.ts : Load environment variables in `src/main/index.ts` with `override: true` before any other imports in the desktop app
Applied to files:
turbo.jsonc
📚 Learning: 2025-12-28T01:56:39.021Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-28T01:56:39.021Z
Learning: Use Turborepo as the build system for managing workspaces and running scripts across the monorepo
Applied to files:
turbo.jsonc
🧬 Code graph analysis (1)
apps/desktop/src/main/lib/terminal/persistence/manager.ts (4)
apps/desktop/src/main/lib/terminal/persistence/types.ts (2)
PersistenceBackend(20-45)CreatePersistentSessionParams(47-52)apps/desktop/src/main/lib/terminal/persistence/tmux-backend.ts (3)
TmuxBackend(83-297)getWorkspacePrefix(74-81)getSessionName(60-72)apps/desktop/src/main/lib/app-environment.ts (1)
SUPERSET_HOME_DIR(5-5)apps/desktop/src/main/lib/terminal/persistence/session-lifecycle.ts (2)
SessionLifecycleEvents(12-15)SessionLifecycle(17-248)
🪛 ast-grep (0.40.3)
apps/desktop/src/shared/terminal-scrollback-sanitizer.ts
[warning] 16-16: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(${ESC}\\[[?>]?[0-9;]*c, "g")
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html
(regexp-from-variable)
[warning] 17-17: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(${ESC}\\[[?>]?[0-9;]*R, "g")
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html
(regexp-from-variable)
[warning] 18-18: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(${ESC}\\[[?>]?[0-9;]*\\$y, "g")
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html
(regexp-from-variable)
[warning] 19-19: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(${ESC}\\[<\\d+(?:;\\d+){2}[Mm], "g")
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html
(regexp-from-variable)
🔇 Additional comments (18)
apps/desktop/electron-builder.ts (1)
107-112: LGTM! Good build flexibility improvement.The conditional notarization logic is correct and makes the build configuration more flexible by gracefully handling environments without Apple credentials (e.g., local development, CI without secrets, forks).
apps/desktop/src/shared/terminal-scrollback-sanitizer.ts (4)
1-12: Well-documented module header.Clear explanation of the module's purpose, cross-process constraints, and the specific problem it solves with terminal protocol artifacts.
22-33: LGTM on caret-escaped and heuristic patterns.The caret-escaped variants correctly handle the
^[representation, and the heuristic patterns use bounded quantifiers ({1,3},{1,4}) to prevent performance issues while targeting legitimate payload leakage scenarios.
35-48: Good separation of patterns.Keeping
DA_PAYLOADout ofPATTERNSis correct since it requires capture-group substitution ($1) rather than simple removal. ThePAYLOAD_TERMINATOR_CHECKefficiently gates the fast path by checking for both DA (c) and mouse (M) terminators.
50-80: Solid implementation with appropriate fast-path optimization.The function correctly:
- Short-circuits on falsy/empty input
- Uses fast-path when no escape markers are present, only running payload cleanup if needed
- Applies all patterns sequentially in the full path, then handles
DA_PAYLOADseparately to preserve leading whitespaceThe logic flow is clear and the optimization avoids unnecessary regex work for clean input.
apps/desktop/src/main/lib/terminal/persistence/manager.ts (4)
1-19: LGTM!Imports are well-organized and the 72-hour orphan cleanup threshold is reasonable for avoiding accidental deletion of long-running sessions.
72-109: LGTM!Session operation methods have consistent error handling: read operations return safe defaults when no backend is available, while write operations appropriately throw. The delegation pattern to the backend is clean and well-structured.
120-157: LGTM!The orphaned session cleanup logic is well-structured with appropriate safety measures: it conservatively keeps sessions with unknown activity timestamps (line 138-142) and uses age-based eviction with a 72-hour threshold. The error handling with try-catch and logging is appropriate for a cleanup operation.
159-175: LGTM!The
createLifecyclemethod correctly enforces backend availability and provides a clean abstraction for TerminalManager. The singleton export pattern and helper function re-exports are appropriate for this module's role as the primary persistence orchestrator.turbo.jsonc (5)
34-45: Pass-through environment variables correctly configured.The
globalPassThroughEnvsection properly declares platform and CI variables that should be available but don't affect caching. This is the correct approach for these types of variables.
70-113: API build task environment variables are well-organized.The comprehensive environment variable list for the API package is properly scoped and well-documented. The grouping by purpose (OAuth, integrations, background jobs, storage, etc.) significantly improves maintainability.
118-131: Web build task correctly includes necessary environment variables.The inclusion of
DESKTOP_AUTH_SECRETin both the API and Web build tasks is appropriate, as the Web app needs it for OAuth callback handling while the API needs it for authentication. The comment clarifies this intent.
136-220: Remaining build tasks and overall structure are well-configured.The simpler applications (admin, marketing, docs) correctly have minimal environment variable requirements, needing only their respective Sentry DSNs. The addition of section comments throughout the file significantly improves readability and maintainability.
This reorganization represents a substantial improvement in environment variable scoping and follows Turborepo best practices for monorepo management.
5-32: No action required—the turbo.jsonc configuration is correct.The environment variable scoping is properly implemented. Apps that import from
@superset/trpc(web, admin) only use exported types and procedures—they do not import theenvvalidation module. Server-side secrets likeBLOB_READ_WRITE_TOKEN,POSTHOG_API_KEY, andKV_REST_API_URLare defined inpackages/trpc/src/env.tsbut are not re-exported, and are only actually used by code in the API package. These variables are correctly declared in the@superset/api#buildtask and do not need to be added to other app configurations.Likely an incorrect or invalid review comment.
apps/desktop/src/main/lib/terminal/manager.ts (4)
50-59: LGTM: Auto-retry on failed lifecycle state.The retry logic properly handles failed persistent sessions by calling
lifecycle.retry()and updating the PTY reference when successful. This provides resilience for temporary connection failures.
177-194: LGTM: Scrollback capture with proper bounds and timeout.The method correctly applies a 2-second timeout, bounds the result to 500K characters, and sanitizes the output. Error handling returns an empty string, which is appropriate for graceful degradation.
217-255: LGTM: Robust unified cleanup with identity guards.The cleanup method correctly:
- Makes idempotent by clearing existing timeouts
- Snapshots lifecycle before async operations
- Uses identity guards after awaits to prevent stale cleanup
- Delays session deletion by 5 seconds to allow event handlers to access data
This prevents race conditions where a session might be recreated during cleanup.
340-354: LGTM: Disk scrollback fallback when tmux capture fails.The fallback logic correctly uses disk history when
wasRecoveredis true but backend scrollback is empty. This provides resilience when tmux capture times out or fails, ensuring users don't lose their scrollback history.
| console.warn( | ||
| "[TerminalManager] Lifecycle attach failed, killing session", | ||
| ); | ||
| await processPersistence.killSession(sessionName).catch(() => {}); | ||
| this.lifecycles.delete(paneId); |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
Missing lifecycle cleanup before deletion.
When attachment fails, the lifecycle is deleted from the map without calling lifecycle.close() or lifecycle.detach(). This may leave internal resources (timers, buffers, event listeners) active.
🔎 Proposed fix
console.warn(
"[TerminalManager] Lifecycle attach failed, killing session",
);
await processPersistence.killSession(sessionName).catch(() => {});
+ const lifecycle = this.lifecycles.get(paneId);
+ if (lifecycle) {
+ await lifecycle.close();
+ }
this.lifecycles.delete(paneId);Apply the same pattern at lines 128, 161, and 167 where lifecycles are deleted.
🤖 Prompt for AI Agents
In apps/desktop/src/main/lib/terminal/manager.ts around lines 112-116, the code
deletes the lifecycle from this.lifecycles when attach fails but never calls
lifecycle.detach() or lifecycle.close(), risking leaked resources; before
deleting, look up the lifecycle by paneId, call await lifecycle.close() if
available (or lifecycle.detach() if close() doesn't exist), wrap the call in a
try/catch to swallow errors, then remove from the map and kill the session;
apply the same change to the other delete sites at lines ~128, ~161, and ~167 so
every lifecycle is properly closed/detached before deletion.
| async initialize(): Promise<void> { | ||
| if (this.initialized) return; | ||
| this.initialized = true; | ||
|
|
||
| // Strict check: only enable when explicitly set to "1" | ||
| if (process.env.SUPERSET_TERMINAL_PERSISTENCE !== "1") { | ||
| return; | ||
| } | ||
|
|
||
| if (process.platform === "win32") { | ||
| return; | ||
| } | ||
|
|
||
| const tmux = new TmuxBackend(); | ||
| if (await tmux.isAvailable()) { | ||
| this.backend = tmux; | ||
| await this.copyTmuxConfig(); | ||
| await tmux.ensureServerConfig(); | ||
| await tmux.cleanupOrphanedScripts?.(); | ||
| this._enabled = true; | ||
| } | ||
| } |
There was a problem hiding this comment.
Add error handling for initialization robustness.
The initialization sequence (lines 46-48) lacks error handling. If copyTmuxConfig(), ensureServerConfig(), or cleanupOrphanedScripts() fail, the error propagates unhandled and _enabled remains false, but partial initialization may have occurred. Consider wrapping these operations in a try-catch to log errors and ensure graceful degradation.
🔎 Suggested error handling approach
const tmux = new TmuxBackend();
if (await tmux.isAvailable()) {
- this.backend = tmux;
- await this.copyTmuxConfig();
- await tmux.ensureServerConfig();
- await tmux.cleanupOrphanedScripts?.();
- this._enabled = true;
+ try {
+ this.backend = tmux;
+ await this.copyTmuxConfig();
+ await tmux.ensureServerConfig();
+ await tmux.cleanupOrphanedScripts?.();
+ this._enabled = true;
+ } catch (error) {
+ console.error("[ProcessPersistence] Initialization failed:", error);
+ this.backend = null;
+ this._enabled = false;
+ }
}📝 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.
| async initialize(): Promise<void> { | |
| if (this.initialized) return; | |
| this.initialized = true; | |
| // Strict check: only enable when explicitly set to "1" | |
| if (process.env.SUPERSET_TERMINAL_PERSISTENCE !== "1") { | |
| return; | |
| } | |
| if (process.platform === "win32") { | |
| return; | |
| } | |
| const tmux = new TmuxBackend(); | |
| if (await tmux.isAvailable()) { | |
| this.backend = tmux; | |
| await this.copyTmuxConfig(); | |
| await tmux.ensureServerConfig(); | |
| await tmux.cleanupOrphanedScripts?.(); | |
| this._enabled = true; | |
| } | |
| } | |
| async initialize(): Promise<void> { | |
| if (this.initialized) return; | |
| this.initialized = true; | |
| // Strict check: only enable when explicitly set to "1" | |
| if (process.env.SUPERSET_TERMINAL_PERSISTENCE !== "1") { | |
| return; | |
| } | |
| if (process.platform === "win32") { | |
| return; | |
| } | |
| const tmux = new TmuxBackend(); | |
| if (await tmux.isAvailable()) { | |
| try { | |
| this.backend = tmux; | |
| await this.copyTmuxConfig(); | |
| await tmux.ensureServerConfig(); | |
| await tmux.cleanupOrphanedScripts?.(); | |
| this._enabled = true; | |
| } catch (error) { | |
| console.error("[ProcessPersistence] Initialization failed:", error); | |
| this.backend = null; | |
| this._enabled = false; | |
| } | |
| } | |
| } |
🤖 Prompt for AI Agents
In apps/desktop/src/main/lib/terminal/persistence/manager.ts around lines 30 to
51, wrap the tmux setup sequence (copyTmuxConfig, ensureServerConfig,
cleanupOrphanedScripts) in a try-catch so initialization failures don’t
propagate and leave the manager in a partial state; on catch log the error (with
context), set this.backend = undefined and this._enabled = false (or leave
false), and avoid rethrowing so the app can continue gracefully; ensure any
resources created by a partially-initialized tmux are cleaned up or rolled back
in the catch block.
| private async copyTmuxConfig(): Promise<void> { | ||
| const configPath = join(SUPERSET_HOME_DIR, "tmux.conf"); | ||
| try { | ||
| await fs.access(configPath); | ||
| } catch { | ||
| const defaultConfig = `# Superset tmux config - minimal, non-conflicting | ||
| set -g prefix None | ||
| unbind C-b | ||
| set -g mouse off | ||
| set -g status off | ||
| set -g history-limit 50000 | ||
| set -g escape-time 0 | ||
| set -g default-terminal "xterm-256color" | ||
| set -ga terminal-overrides ",xterm-256color:Tc" | ||
| `; | ||
| await fs.writeFile(configPath, defaultConfig); | ||
| } | ||
| } |
There was a problem hiding this comment.
Add error handling for config file write.
Line 68's writeFile call is not wrapped in error handling. If the write fails (e.g., permissions, disk full), the error propagates and could prevent persistence initialization. Consider adding a try-catch to log the error and allow graceful degradation.
🔎 Suggested error handling
private async copyTmuxConfig(): Promise<void> {
const configPath = join(SUPERSET_HOME_DIR, "tmux.conf");
try {
await fs.access(configPath);
} catch {
- const defaultConfig = `# Superset tmux config - minimal, non-conflicting
+ try {
+ const defaultConfig = `# Superset tmux config - minimal, non-conflicting
set -g prefix None
unbind C-b
set -g mouse off
set -g status off
set -g history-limit 50000
set -g escape-time 0
set -g default-terminal "xterm-256color"
set -ga terminal-overrides ",xterm-256color:Tc"
`;
- await fs.writeFile(configPath, defaultConfig);
+ await fs.writeFile(configPath, defaultConfig);
+ } catch (writeError) {
+ console.error("[ProcessPersistence] Failed to write tmux config:", writeError);
+ throw writeError;
+ }
}
}📝 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.
| private async copyTmuxConfig(): Promise<void> { | |
| const configPath = join(SUPERSET_HOME_DIR, "tmux.conf"); | |
| try { | |
| await fs.access(configPath); | |
| } catch { | |
| const defaultConfig = `# Superset tmux config - minimal, non-conflicting | |
| set -g prefix None | |
| unbind C-b | |
| set -g mouse off | |
| set -g status off | |
| set -g history-limit 50000 | |
| set -g escape-time 0 | |
| set -g default-terminal "xterm-256color" | |
| set -ga terminal-overrides ",xterm-256color:Tc" | |
| `; | |
| await fs.writeFile(configPath, defaultConfig); | |
| } | |
| } | |
| private async copyTmuxConfig(): Promise<void> { | |
| const configPath = join(SUPERSET_HOME_DIR, "tmux.conf"); | |
| try { | |
| await fs.access(configPath); | |
| } catch { | |
| try { | |
| const defaultConfig = `# Superset tmux config - minimal, non-conflicting | |
| set -g prefix None | |
| unbind C-b | |
| set -g mouse off | |
| set -g status off | |
| set -g history-limit 50000 | |
| set -g escape-time 0 | |
| set -g default-terminal "xterm-256color" | |
| set -ga terminal-overrides ",xterm-256color:Tc" | |
| `; | |
| await fs.writeFile(configPath, defaultConfig); | |
| } catch (writeError) { | |
| console.error("[ProcessPersistence] Failed to write tmux config:", writeError); | |
| throw writeError; | |
| } | |
| } | |
| } |
🤖 Prompt for AI Agents
In apps/desktop/src/main/lib/terminal/persistence/manager.ts around lines 53 to
70, the await fs.writeFile(configPath, defaultConfig) is not protected so a
filesystem error (permissions, disk full, etc.) will propagate and abort
initialization; wrap the writeFile call in a try-catch, log the caught error
(include error.message and configPath) using the module’s logger or
console.error, and swallow the error so the method continues gracefully (do not
rethrow), ensuring persistence initialization proceeds even if writing the
default tmux config fails.
- Add confirmOnQuit boolean column to settings table with migration - Add getConfirmOnQuit/setConfirmOnQuit tRPC procedures - Create new "Behavior" section in settings sidebar - Add BehaviorSettings component with toggle switch - Implement native quit confirmation dialog in main process - Default to enabled (confirm before quitting) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- P0: Use app.exit(0) for !gotTheLock to avoid confirmation dialog on second instance (prevents headless zombie process) - P1: Wrap dialog.showMessageBox in try/catch to prevent stuck "confirming" state if dialog fails - P1: Add optimistic update with rollback for Switch toggle so UI updates immediately - Add setSkipQuitConfirmation() for auto-updater to bypass confirmation during quitAndInstall 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
…tion - Add DEFAULT_CONFIRM_ON_QUIT to shared/constants.ts - Update main/index.ts to use shared constant instead of hardcoded true - Update trpc settings router to use shared constant - Prevents maintenance issues when default value needs to change - Addresses PR review comment about duplicate defaults
- Fix import order in apps/desktop/src/main/index.ts - Fix import order in apps/desktop/src/main/lib/auto-updater.ts - Run biome check --write to automatically organize imports
… tmux backend Implement two-phase terminal session persistence: **Phase 1: CWD Persistence** - Move OSC-7 parser to shared module for main/renderer use - Fix recoverScrollback() to always return savedCwd from metadata - Add rolling buffer for split OSC-7 sequences in data handler - Add updateCwd() with debounced crash-safe writes to HistoryWriter - Validate and use recovered CWD on session recreation **Phase 2: Process Persistence (tmux)** - Add PersistenceBackend interface for pluggable backends - Implement TmuxBackend with isolated socket and config - Add ProcessPersistence manager with feature flag gate - Integrate persistence into TerminalManager (attach/detach/create flow) - Add detachAll() for graceful app quit with session survival - Consolidate quit handlers with state machine pattern - Clean up workspace sessions on deletion **Security** - Only safe env vars persisted to tmux wrapper scripts - No secrets (AWS_*, GITHUB_TOKEN, etc.) written to disk **Feature Flag** - Gated by SUPERSET_TERMINAL_PERSISTENCE=1 env var - macOS/Linux only (not Windows) Closes the gap where terminal sessions lose state on app restart.
Addresses CodeRabbit review feedback. Previously, tmux-backed sessions didn't have historyWriter initialized, which meant: - CWD changes weren't persisted to metadata files - closeSessionHistoryForDetach was a no-op - No fallback if tmux crashed Now persistent sessions also use historyWriter to: - Read saved CWD from metadata as fallback on re-attach - Track CWD changes via OSC-7 and persist to disk - Provide backup scrollback storage for resilience
The PR description contains all necessary documentation. Implementation plan is no longer needed post-implementation.
macOS GUI apps don't inherit shell PATH, so Homebrew binaries at /opt/homebrew/bin (Apple Silicon) or /usr/local/bin (Intel) aren't found. Add EXTENDED_PATH constant and apply to all exec() calls and pty.spawn() for tmux operations.
…persistence Fixes 3 bugs in terminal session restoration: - Bug #1: Terminal blank after attach failure - auto-reconnect with retry backoff - Bug #2: Wrong dimensions after restore - pass actual cols/rows to attachSession - Bug #3: Cannot type after restore - lifecycle routes writes through connected PTY Changes: - Add SessionLifecycle class with states: disconnected→connecting→connected→reconnecting→failed→closed - Add TmuxError classification for intelligent retry decisions - Add -d flag to detach other clients before attaching - Integrate lifecycle into TerminalManager (write, resize, kill, detach, cleanup)
Fixes 6 issues identified in review: 1. Prevent reconnect flapping after detach() - Add isDetaching flag to SessionLifecycle - Check flag in onExit handler before attempting reconnect 2. Use fresh dimensions on reconnect - wireHandlers() now uses this.lastDimensions instead of captured values - resize() already updates lastDimensions correctly 3. Handle writes/resizes when lifecycle not connected - Add canWrite() method to SessionLifecycle - Drop writes during reconnecting state with warning - Throw explicit error for other non-connected states - Retry failed lifecycle on createOrAttach 4. Add ED3 clear + OSC7 parsing to persistent data path - handleLifecycleData now checks containsClearScrollbackSequence - Parse OSC7 for CWD updates with per-session buffer - Update historyWriter.updateCwd when CWD changes 5. Port scan restored scrollback - Scan scrollback for ports in setupPersistentSessionWithLifecycle 6. Don't delete session in detach() prematurely - Keep session record after detach (set isAlive=false) - Allows subsequent kill() to find and cleanup tmux session - Clean up detached sessions on next createOrAttach
Address 3 additional code review issues: 1. Fix kill() vs detach() race - Check isExpectedDetach in kill() to avoid relying on exit handler - If session was already detached, do cleanup directly in kill() 2. Fix killing detached session missing cleanup - Add portManager.removePortsForPane() for !isAlive path - Add osc7Buffers.delete() for !isAlive path 3. Fix osc7Buffers memory leak - Clean osc7Buffer on every PTY exit in setupExitHandler - Prevents memory leak and stale CWD data on restart
- Add unified cleanupSession() with identity guards to prevent race conditions - Extract processTerminalChunk() for shared data handling between persistent/non-persistent sessions - Add byte-limited buffering (1MB) in SessionLifecycle with setDataHandler() to fix data race - Rename TmuxError to PersistenceErrorCode and use discriminated union for backend name - Add processPersistence.createLifecycle() as single entry point, remove TmuxBackend from TerminalManager - Fix kill/signal semantics: detach first to prevent auto-reconnect, then kill tmux - Separate persistent vs non-persistent in killByWorkspaceId() Addresses code review feedback on tmux leakage, cleanup gaps, and data plane duplication.
- P1: Add .catch() to fire-and-forget async calls (cleanupSession, kill)
to prevent unhandled rejections on FS/cleanup errors
- P1: Fix signal semantics - SIGINT now uses write('\x03') for both
persistent AND non-persistent sessions (interrupt foreground process,
not pty.kill which signals shell PID)
- P2: Pass exitCode=0 to cleanupSession in kill() and killByWorkspaceId()
for consistent history metadata
Turborepo was filtering out env vars not listed in globalEnv, causing Vercel deployments to fail with "Invalid environment variables" errors. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Move truly shared vars (DATABASE_*, CLERK_*, URLs) to globalEnv - Scope app-specific secrets to per-package build tasks: - API: OAuth, Linear, QStash, Blob storage secrets - Web: Desktop auth, marketing/docs URLs - Admin/Marketing/Docs: Only Sentry DSNs - Add comments for better maintainability Benefits: - Changing QSTASH_TOKEN only invalidates API cache, not all apps - Clearer ownership of which app needs which secrets - Better cache efficiency in CI 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
The @superset/trpc package requires POSTHOG_API_KEY and POSTHOG_PROJECT_ID for server-side analytics. These were missing from the API build task. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Skip notarization when APPLE_ID, APPLE_ID_PASSWORD, or APPLE_TEAM_ID are not set. This allows building unsigned DMGs for testing/development without requiring Apple Developer credentials. Users can still distribute unsigned builds - recipients just need to right-click → Open to bypass Gatekeeper. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
…istence P0: Fix scrollback truncation when tmux capture fails - When captureScrollbackBounded() times out or errors, fall back to disk backup instead of truncating scrollback.bin - Prevents data loss when tmux has transient issues but session is recoverable P1: Fix feature flag strict parsing - Change from truthy check to strict === "1" comparison - Prevents accidental enablement with "0" or "false" values P2: Improve sanitization performance with better fast path - Replace broad semicolon check with targeted payload terminator check - When no escape sequences present, only run 2 payload patterns vs 9 - Fast path now correctly exits early for plain text output 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Without this, Vite doesn't replace process.env.SUPERSET_TERMINAL_PERSISTENCE at build time, so it's always undefined in production builds, causing the terminal persistence feature to be permanently disabled. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
When scrollback from a previous session contains escape sequences that enabled alternate screen buffer or mouse tracking modes (from TUI apps like vim, less, htop), the terminal would remain in that state after restore. This caused mouse wheel scroll to be converted to arrow keys, which cycled through shell history instead of scrolling the viewport. Fix by sending mode-disabling sequences after writing restored scrollback: - ?1049l: disable alternate screen buffer - ?1l: disable application cursor keys - ?1000l/?1002l/?1003l/?1006l: disable mouse tracking modes 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
…scroll Multiple fixes to prevent scroll wheel from being interpreted as shell history navigation (up/down arrows) when terminal persistence is enabled: 1. ensureServerConfig() now sets 'mouse off' globally on tmux server 2. tmux.conf is always overwritten to ensure correct settings 3. Per-session 'mouse off' is set when creating new sessions 4. terminal-overrides includes 'kmous@' to disable mouse at terminfo level The issue was that with mouse mode enabled, xterm.js sends scroll wheel events to the PTY, which then get interpreted as arrow keys by the shell. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Fixes additional potential bugs with similar root causes to the scroll issue: Terminal mode resets (prevent state leakage from restored sessions): - Bracketed paste mode (?2004l) - prevents paste issues - Focus reporting (?1004l) - prevents spurious focus events - Auto-wrap mode (?7h) - ensures line wrapping works - Scroll region (r) - resets to full screen - Character set ((B) - resets to ASCII Environment variables (fixes SSH/GPG issues in persistent sessions): - Added HOME, USER, LOGNAME for identity - Added SSH_AUTH_SOCK, SSH_AGENT_PID for SSH agent forwarding - Added GPG_TTY, GPG_AGENT_INFO for git commit signing - Added XDG_* for modern config directories Also ensures escape-time 0 is applied to running tmux servers. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
When deleting a workspace with terminal persistence enabled, users were seeing ugly terminal teardown messages ([lost tty], [Process exited], [Press any key to restart]). This fix navigates to the next workspace (or shows StartView for the last workspace) BEFORE deletion starts. Changes: - Pass allWorkspaces and activeWorkspaceId props through component tree - Add navigation-before-delete logic to DeleteWorkspaceDialog - Use optimistic cache clear for last-workspace case - Restore previous active workspace if deletion fails - Add loading states to buttons during async operations 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
f80c86a to
c0df17c
Compare
- Capture tmux scrollback via spawn with bounded output + timeout - Allow attach/cleanup of existing tmux sessions even when persistence is disabled - Move quit-confirmation helpers to main/lib to avoid main entrypoint coupling
- P0: Don't kill tmux sessions on attach failure - only clear state for safe-to-proceed errors (NO_SERVER, NO_SESSION, SOCKET_MISSING) - Add retry/backoff to initial ensureAttached() (3 retries, 1s delay) - P2: Fix unreachable 'reconnected' branch by tracking wasRetrying state - Add retryAttach and killPersistentSession tRPC mutations - Add inline recovery banner with Retry and Kill & Restart actions
- Fix tmux config indentation bug causing default-terminal and terminal-overrides to be ignored - Enable mouse support in tmux (mouse on) for TUI apps like opencode, claude code - Remove kmous@ from terminal-overrides that was disabling mouse at terminfo level - Fix xterm.js wheel handler semantics: return true = let xterm handle, return false = we handled it - Add resizeWindow to resize tmux window before attach to prevent size mismatch - Add refreshClient to force tmux redraw after attach - Skip old scrollback for recovered sessions to prevent garbled display from size mismatch These fixes address: - Unicode block characters rendering as dashes/underscores in tmux - Mouse scroll not working in TUI apps (opencode, vim, less, etc.) - Garbled terminal display when restoring tmux sessions after app restart
Resolved conflicts by keeping HEAD's terminal session persistence feature: - settings/index.ts: terminal persistence procedures - main/index.ts: quit-confirmation module + persistence logic - auto-updater.ts: import from quit-confirmation module - BehaviorSettings.tsx: terminal persistence UI toggle - suppressQueryResponses.ts: comprehensive query suppression - constants.ts: DEFAULT_TERMINAL_SESSION_PERSISTENCE - _journal.json: migration entry for persistence setting - schema.ts: terminalSessionPersistence column
Summary
This PR adds terminal session persistence in two layers:
Details
Always on (no toggle)
meta.jsonOptional tmux backend (Behavior toggle)
SessionLifecyclestate machine with bounded buffering + retry/backoff for attach failuresWhy tmux (and not Electron utility process)
utilityProcessis still part of the app lifecycle; it does not survive a full app quit/relaunch, so it can't provide "keep terminals alive across restarts" on its own.Edge Cases Fixed
Terminal rendering issues
default-terminalandterminal-overridesto be ignored, resulting in Unicode block characters (█▀▄) rendering as dashes/underscorestmux config fixes
kmous@from terminal-overrides that was disabling mouse capability at terminfo levelmouse offtomouse onto enable mouse event passthrough to TUI applicationsresizeWindowto resize tmux window before attach to prevent size mismatchrefreshClientto force tmux redraw after attachSecurity / safety
0700best-effort), tmux config (0600), and wrapper scripts (0700)TMUXremoved from env to avoid nested tmux issuesTest plan
cdinto a nested directory, quit and reopen → terminal restores in same CWD