Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,6 @@ export async function initializeWorkspaceWorktree({
reason: string,
checkOriginRefs: boolean,
): Promise<LocalStartPointResult> => {
// Try origin tracking ref first (only if remote exists)
if (checkOriginRefs) {
const originRef = `origin/${effectiveBaseBranch}`;
if (await refExistsLocally(mainRepoPath, originRef)) {
Expand All @@ -204,27 +203,23 @@ export async function initializeWorkspaceWorktree({
}
}

// Try local branch
if (await refExistsLocally(mainRepoPath, effectiveBaseBranch)) {
console.log(
`[workspace-init] ${reason}. Using local branch: ${effectiveBaseBranch}`,
);
return { ref: effectiveBaseBranch };
}

// Only try fallback branches if the base branch was auto-derived
if (baseBranchWasExplicit) {
console.log(
`[workspace-init] ${reason}. Base branch "${effectiveBaseBranch}" was explicitly set, not using fallback.`,
);
return null;
}

// Fallback: try common default branch names
const commonBranches = ["main", "master", "develop", "trunk"];
for (const branch of commonBranches) {
if (branch === effectiveBaseBranch) continue; // Already tried
// Only check origin refs if remote exists
if (branch === effectiveBaseBranch) continue;
if (checkOriginRefs) {
const fallbackOriginRef = `origin/${branch}`;
if (await refExistsLocally(mainRepoPath, fallbackOriginRef)) {
Expand All @@ -245,7 +240,6 @@ export async function initializeWorkspaceWorktree({
return null;
};

// Helper to update baseBranch when fallback is used
const applyFallbackBranch = (fallbackBranch: string) => {
console.log(
`[workspace-init] Updating baseBranch from "${effectiveBaseBranch}" to "${fallbackBranch}" for workspace ${workspaceId}`,
Expand Down Expand Up @@ -355,7 +349,6 @@ export async function initializeWorkspaceWorktree({
try {
await fetchDefaultBranch(mainRepoPath, effectiveBaseBranch);
} catch (fetchError) {
// Fetch failed - verify local tracking ref exists before proceeding
const originRef = `origin/${effectiveBaseBranch}`;
if (!(await refExistsLocally(mainRepoPath, originRef))) {
console.warn(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,7 @@ import { useTerminalCallbacksStore } from "renderer/stores/tabs/terminal-callbac
import { useTerminalTheme } from "renderer/stores/theme";
import { scheduleTerminalAttach } from "./attach-scheduler";
import { sanitizeForTitle } from "./commandBuffer";
import {
ConnectionErrorOverlay,
RestoredModeOverlay,
SessionKilledOverlay,
} from "./components";
import { ConnectionErrorOverlay, SessionKilledOverlay } from "./components";
import { DEBUG_TERMINAL, FIRST_RENDER_RESTORE_FALLBACK_MS } from "./config";
import {
createTerminalInstance,
Expand Down Expand Up @@ -75,7 +71,6 @@ export const Terminal = ({ tabId, workspaceId }: TerminalProps) => {
const terminalTheme = useTerminalTheme();
const restartTerminalRef = useRef<() => void>(() => {});

// Terminal connection state and mutations
const {
connectionError,
setConnectionError,
Expand All @@ -89,14 +84,12 @@ export const Terminal = ({ tabId, workspaceId }: TerminalProps) => {
},
} = useTerminalConnection({ workspaceId });

// Terminal CWD management
const { updateCwdFromData } = useTerminalCwd({
paneId,
initialCwd: paneInitialCwd,
workspaceCwd,
});

// Terminal modes tracking
const {
isAlternateScreenRef,
isBracketedPasteRef,
Expand All @@ -105,13 +98,11 @@ export const Terminal = ({ tabId, workspaceId }: TerminalProps) => {
resetModes,
} = useTerminalModes();

// File link click handler
const { handleFileLinkClick } = useFileLinkClick({
workspaceId,
workspaceCwd,
});

// Refs for stable identity
const initialThemeRef = useRef(terminalTheme);
const isFocused = focusedPaneId === paneId;
const isFocusedRef = useRef(isFocused);
Expand All @@ -130,8 +121,6 @@ export const Terminal = ({ tabId, workspaceId }: TerminalProps) => {
const handleFileLinkClickRef = useRef(handleFileLinkClick);
handleFileLinkClickRef.current = handleFileLinkClick;

// Refs for stream event handlers (populated after useTerminalStream)
// These allow flushPendingEvents to call the handlers via refs
const handleTerminalExitRef = useRef<
(exitCode: number, xterm: XTerm) => void
>(() => {});
Expand Down Expand Up @@ -167,7 +156,6 @@ export const Terminal = ({ tabId, workspaceId }: TerminalProps) => {
useTerminalCallbacksStore.getState().unregisterScrollToBottomCallback,
);

// Terminal restore logic
const {
isStreamReadyRef,
didFirstRenderRef,
Expand All @@ -191,7 +179,6 @@ export const Terminal = ({ tabId, workspaceId }: TerminalProps) => {
setConnectionError(reason || "Connection to terminal daemon lost"),
});

// Cold restore handling
const {
isRestoredMode,
setIsRestoredMode,
Expand Down Expand Up @@ -219,13 +206,11 @@ export const Terminal = ({ tabId, workspaceId }: TerminalProps) => {
resetModes,
});

// Avoid effect re-runs: track overlay states via refs for input gating
const isRestoredModeRef = useRef(isRestoredMode);
isRestoredModeRef.current = isRestoredMode;
const connectionErrorRef = useRef(connectionError);
connectionErrorRef.current = connectionError;

// Stream handling
const { handleTerminalExit, handleStreamError, handleStreamData } =
useTerminalStream({
paneId,
Expand All @@ -240,17 +225,14 @@ export const Terminal = ({ tabId, workspaceId }: TerminalProps) => {
updateCwdFromData,
});

// Populate handler refs for flushPendingEvents to use
handleTerminalExitRef.current = handleTerminalExit;
handleStreamErrorRef.current = handleStreamError;

// Stream subscription
electronTrpc.terminal.stream.useSubscription(paneId, {
onData: handleStreamData,
enabled: true,
});

// Focus handler ref
const handleTerminalFocusRef = useRef(() => {});
handleTerminalFocusRef.current = () => {
if (pane?.tabId) {
Expand Down Expand Up @@ -299,7 +281,6 @@ export const Terminal = ({ tabId, workspaceId }: TerminalProps) => {
console.log(`[Terminal] Mount: ${paneId}`);
}

// Cancel pending detach from previous unmount
const pendingDetach = pendingDetaches.get(paneId);
if (pendingDetach) {
clearTimeout(pendingDetach);
Expand Down Expand Up @@ -346,7 +327,6 @@ export const Terminal = ({ tabId, workspaceId }: TerminalProps) => {
searchAddonRef.current = searchAddon;
});

// Wait for first render before applying restoration
let renderDisposable: IDisposable | null = null;
let firstRenderFallback: ReturnType<typeof setTimeout> | null = null;

Expand Down Expand Up @@ -489,15 +469,14 @@ export const Terminal = ({ tabId, workspaceId }: TerminalProps) => {

const storedColdRestore = coldRestoreState.get(paneId);
if (storedColdRestore?.isRestored) {
setIsRestoredMode(true);
setRestoredCwd(storedColdRestore.cwd);
if (storedColdRestore.scrollback && xterm) {
xterm.write(
storedColdRestore.scrollback,
scheduleScrollToBottom,
);
}
didFirstRenderRef.current = true;
handleStartShell(storedColdRestore.cwd);
return;
Comment on lines 470 to 480

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect write buffering / readiness handling around terminal writes
rg -n --type=ts -C3 'useTerminalConnection' apps/desktop/src/renderer
rg -n --type=ts -C3 'writeRef\.current|write\(' apps/desktop/src/renderer
rg -n --type=ts -C3 'isStreamReadyRef' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal

Repository: superset-sh/superset

Length of output: 50376


🏁 Script executed:

#!/bin/bash
# Get the exact lines in question
sed -n '480,515p' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx

# Look for the writeRef usage context - check if it's subject to readiness gating
rg -n 'writeRef\.current\(' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx -A 2 -B 2

# Check how events are flushed and understand the queuing mechanism
rg -n 'flushPendingEvents|pendingEventsRef' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalStream.ts -A 2 -B 2

Repository: superset-sh/superset

Length of output: 2416


🏁 Script executed:

#!/bin/bash
# Find the writeMutation definition and see if it has any buffering/gating
rg -n 'writeMutation|useMutation' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalConnection.ts -A 5 -B 2

# Check if there's any check for session readiness before accepting writes
rg -n 'isStreamReady|session.*ready|attach' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx -B 2 -A 2 | head -100

# Look for any input buffering or queueing in the component
rg -n 'buffer|queue.*input|input.*queue' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal -i

Repository: superset-sh/superset

Length of output: 16215


🏁 Script executed:

#!/bin/bash
# Check attach-scheduler to see if it manages session readiness
cat apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/attach-scheduler.ts

# Check handleStartShell to see when it subscribes to the stream
rg -n 'handleStartShell' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx -A 15 | head -50

# Look for any input validation/buffering in handleWrite or before writeRef is called
rg -n 'const handleWrite|handleKeyPress|onData' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx -A 10 | head -80

Repository: superset-sh/superset

Length of output: 9287


🏁 Script executed:

#!/bin/bash
# Check if there's any gating of writeRef calls based on session readiness
rg -n 'handleTerminalInput|onData' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx -B 5 -A 10 | head -80

# Look at the actual terminal input handler
rg -n 'const handleTerminalInput' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx -A 8

Repository: superset-sh/superset

Length of output: 1846


🏁 Script executed:

#!/bin/bash
# Check if there's any buffering on the tRPC write mutation or backend
# First, let's see if tRPC mutation implementation has any built-in buffering
rg -n 'terminal.write' apps/desktop/src -l

# Check the backend implementation if available
fd -t f -e ts 'router' apps/main/src | head -5

Repository: superset-sh/superset

Length of output: 564


🏁 Script executed:

#!/bin/bash
# Check the backend write implementation
cat apps/desktop/src/lib/trpc/routers/terminal/terminal.ts | head -200

# Look for session.write or input handling
rg -n 'write.*session|session.*write|input.*buffer|buffer.*input' apps/desktop/src/lib/trpc/routers/terminal/terminal.ts -B 2 -A 5

Repository: superset-sh/superset

Length of output: 5902


🏁 Script executed:

#!/bin/bash
# Get more of the write implementation
sed -n '185,230p' apps/desktop/src/lib/trpc/routers/terminal/terminal.ts

# Check the stream subscription to understand when isStreamReadyRef gets set to true
rg -n 'stream.*subscription|stream.*mutate' apps/desktop/src/lib/trpc/routers/terminal/terminal.ts -B 3 -A 15 | head -100

# Check the underlying terminal.write implementation
rg -n 'terminal\.write' apps/desktop/src/main/lib/terminal -l

Repository: superset-sh/superset

Length of output: 1084


🏁 Script executed:

#!/bin/bash
# Check handleStartShell to see if/when stream subscription starts
rg -n 'const handleStartShell' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalColdRestore.ts -A 30

# Check when stream subscription is enabled/started
rg -n 'useSubscription\|enabled.*true' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx -B 3 -A 3

Repository: superset-sh/superset

Length of output: 2094


🏁 Script executed:

#!/bin/bash
# Get the complete handleStartShell function
sed -n '172,240p' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalColdRestore.ts

# Check when useSubscription actually subscribes (before or after createOrAttach)
sed -n '240,250p' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx

# Look for how the terminal.write backend handles session initialization
cat apps/desktop/src/main/lib/terminal.ts | head -100

Repository: superset-sh/superset

Length of output: 2414


🏁 Script executed:

#!/bin/bash
# Find the terminal implementation
find apps/desktop/src/main -name "*terminal*" -type f | head -10

# Check if there's buffering in the pty implementation
rg -n 'write.*pty|pty.*write|input.*buffer' apps/desktop/src/main/lib -i

Repository: superset-sh/superset

Length of output: 2407


🏁 Script executed:

#!/bin/bash
# Examine the PtyWriteQueue implementation
cat apps/desktop/src/main/lib/terminal/pty-write-queue.ts

# Check how manager.write() handles non-existent sessions
rg -n 'write.*session|write\(' apps/desktop/src/main/lib/terminal/manager.ts -B 2 -A 8 | head -100

Repository: superset-sh/superset

Length of output: 4942


🏁 Script executed:

#!/bin/bash
# Check if isRestoredModeRef is properly set during cold restore
rg -n 'isRestoredModeRef' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx -B 1 -A 1

# Check when isRestoredModeRef is set/cleared
rg -n 'isRestoredModeRef.*true|isRestoredModeRef.*false' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalColdRestore.ts -B 1 -A 1

# Check the handleTerminalInput gate more carefully
sed -n '399,407p' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx

Repository: superset-sh/superset

Length of output: 901


🏁 Script executed:

#!/bin/bash
# Check when isRestoredMode is set/used during cold restore
rg -n 'isRestoredMode\|setIsRestoredMode' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal -B 2 -A 2 | head -150

# Check if there's any readiness gate between scrollback write and session creation
sed -n '486,520p' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx

Repository: superset-sh/superset

Length of output: 1173


🏁 Script executed:

#!/bin/bash
# Find where isRestoredMode state is defined and initialized
rg -n 'useState.*isRestoredMode\|const.*isRestoredMode.*useState' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal

# Check the full useTerminalColdRestore return to see if it manages isRestoredMode state
rg -n 'setIsRestoredMode' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalColdRestore.ts -B 3 -A 1

# See the complete picture - check if isRestoredMode is a return value from the hook
sed -n '50,70p' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalColdRestore.ts

Repository: superset-sh/superset

Length of output: 1481


🏁 Script executed:

#!/bin/bash
# Check if isRestoredMode is ever set to true before cold restore processing
rg -n 'setIsRestoredMode.*true' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal

# Check the complete flow - when/where does cold restore mode get activated?
rg -n 'coldRestoreState\|isColdRestore' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx -B 1 -A 1 | head -100

# Verify: is isRestoredMode supposed to be set to true somewhere?
rg -n 'setIsRestoredMode.*true' apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks -B 3 -A 1

Repository: superset-sh/superset

Length of output: 46


Input loss window during cold restore session transition.

While PtyWriteQueue does buffer outgoing writes, user keystrokes between xterm.write(scrollback) and new session creation can be lost. The gate isRestoredModeRef.current in handleTerminalInput (line 400) never evaluates to true—isRestoredMode is initialized to false and only reset to false; it's never set to true. This leaves input unguarded during the createOrAttachRef() async transition, causing writes to fail when manager.write() cannot find the old session (throwing "Terminal session not found or not alive"). The error is caught and emitted, but the keystroke is dropped. Consider actually enabling isRestoredMode during cold restore or adding explicit isStreamReadyRef gating to prevent writes until the new session is fully attached.

🤖 Prompt for AI Agents
In
`@apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx`
around lines 486 - 496, During cold-restore, input can be dropped because
isRestoredModeRef is never set and writes occur while the old session is gone;
fix by enabling a gating flag during the restore-and-attach window and flushing
buffered writes only after the new session is attached: set
isRestoredModeRef.current = true (or set isStreamReadyRef.current = false)
before calling xterm.write(...) in the cold-restore branch (the block that reads
coldRestoreState and calls handleStartShell/createOrAttachRef), keep the flag
set until createOrAttachRef() (or the promise returned by handleStartShell)
completes successfully, then clear the flag and flush the PtyWriteQueue so
manager.write() is only attempted when the new session is live; update
handleTerminalInput to check isRestoredModeRef (or isStreamReadyRef) and queue
inputs instead of calling manager.write when the gate is active.

}

Expand All @@ -509,12 +488,11 @@ export const Terminal = ({ tabId, workspaceId }: TerminalProps) => {
cwd: result.previousCwd || null,
scrollback,
});
setIsRestoredMode(true);
setRestoredCwd(result.previousCwd || null);
if (scrollback && xterm) {
xterm.write(scrollback, scheduleScrollToBottom);
}
didFirstRenderRef.current = true;
handleStartShell(result.previousCwd || null);
return;
}

Expand Down Expand Up @@ -711,9 +689,6 @@ export const Terminal = ({ tabId, workspaceId }: TerminalProps) => {
{connectionError && (
<ConnectionErrorOverlay onRetry={handleRetryConnection} />
)}
{isRestoredMode && (
<RestoredModeOverlay onStartShell={handleStartShell} />
)}
<div ref={terminalRef} className="h-full w-full" />
</div>
);
Expand Down
Loading