diff --git a/apps/desktop/src/lib/trpc/routers/workspaces/utils/workspace-init.ts b/apps/desktop/src/lib/trpc/routers/workspaces/utils/workspace-init.ts index e819e7844bc..353c300c199 100644 --- a/apps/desktop/src/lib/trpc/routers/workspaces/utils/workspace-init.ts +++ b/apps/desktop/src/lib/trpc/routers/workspaces/utils/workspace-init.ts @@ -193,7 +193,6 @@ export async function initializeWorkspaceWorktree({ reason: string, checkOriginRefs: boolean, ): Promise => { - // Try origin tracking ref first (only if remote exists) if (checkOriginRefs) { const originRef = `origin/${effectiveBaseBranch}`; if (await refExistsLocally(mainRepoPath, originRef)) { @@ -204,7 +203,6 @@ export async function initializeWorkspaceWorktree({ } } - // Try local branch if (await refExistsLocally(mainRepoPath, effectiveBaseBranch)) { console.log( `[workspace-init] ${reason}. Using local branch: ${effectiveBaseBranch}`, @@ -212,7 +210,6 @@ export async function initializeWorkspaceWorktree({ 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.`, @@ -220,11 +217,9 @@ export async function initializeWorkspaceWorktree({ 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)) { @@ -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}`, @@ -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( diff --git a/apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx b/apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx index cdc27f69ad1..c8f832f0069 100644 --- a/apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx +++ b/apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/Terminal.tsx @@ -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, @@ -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, @@ -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, @@ -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); @@ -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 >(() => {}); @@ -167,7 +156,6 @@ export const Terminal = ({ tabId, workspaceId }: TerminalProps) => { useTerminalCallbacksStore.getState().unregisterScrollToBottomCallback, ); - // Terminal restore logic const { isStreamReadyRef, didFirstRenderRef, @@ -191,7 +179,6 @@ export const Terminal = ({ tabId, workspaceId }: TerminalProps) => { setConnectionError(reason || "Connection to terminal daemon lost"), }); - // Cold restore handling const { isRestoredMode, setIsRestoredMode, @@ -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, @@ -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) { @@ -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); @@ -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 | null = null; @@ -489,8 +469,6 @@ 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, @@ -498,6 +476,7 @@ export const Terminal = ({ tabId, workspaceId }: TerminalProps) => { ); } didFirstRenderRef.current = true; + handleStartShell(storedColdRestore.cwd); return; } @@ -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; } @@ -711,9 +689,6 @@ export const Terminal = ({ tabId, workspaceId }: TerminalProps) => { {connectionError && ( )} - {isRestoredMode && ( - - )}
); diff --git a/apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalColdRestore.ts b/apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalColdRestore.ts index 0c61d87e2f5..e16fe0fd566 100644 --- a/apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalColdRestore.ts +++ b/apps/desktop/src/renderer/screens/main/components/WorkspaceView/ContentView/TabsContent/Terminal/hooks/useTerminalColdRestore.ts @@ -38,7 +38,7 @@ export interface UseTerminalColdRestoreReturn { setIsRestoredMode: (value: boolean) => void; setRestoredCwd: (value: string | null) => void; handleRetryConnection: () => void; - handleStartShell: () => void; + handleStartShell: (cwd?: string | null) => void; } /** @@ -72,10 +72,11 @@ export function useTerminalColdRestore({ const [isRestoredMode, setIsRestoredMode] = useState(false); const [restoredCwd, setRestoredCwd] = useState(null); - // Ref for restoredCwd to use in callbacks const restoredCwdRef = useRef(restoredCwd); restoredCwdRef.current = restoredCwd; + const handleStartShellRef = useRef<(cwd?: string | null) => void>(() => {}); + const handleRetryConnection = useCallback(() => { setConnectionError(null); const xterm = xtermRef.current; @@ -110,8 +111,6 @@ export function useTerminalColdRestore({ cwd: result.previousCwd || null, scrollback, }); - setIsRestoredMode(true); - setRestoredCwd(result.previousCwd || null); currentXterm.clear(); if (scrollback) { @@ -124,6 +123,7 @@ export function useTerminalColdRestore({ } didFirstRenderRef.current = true; + handleStartShellRef.current(result.previousCwd || null); return; } @@ -167,89 +167,87 @@ export function useTerminalColdRestore({ flushPendingEvents, ]); - const handleStartShell = useCallback(() => { - const xterm = xtermRef.current; - const fitAddon = fitAddonRef.current; - if (!xterm || !fitAddon) return; + const handleStartShell = useCallback( + (cwd?: string | null) => { + const xterm = xtermRef.current; + const fitAddon = fitAddonRef.current; + if (!xterm || !fitAddon) return; - // Drop any queued events from the pre-restore session - pendingEventsRef.current = []; + pendingEventsRef.current = []; - // Acknowledge cold restore to main process - trpcClient.terminal.ackColdRestore.mutate({ paneId }).catch((error) => { - console.warn("[Terminal] Failed to acknowledge cold restore:", { - paneId, - error: error instanceof Error ? error.message : String(error), + trpcClient.terminal.ackColdRestore.mutate({ paneId }).catch((error) => { + console.warn("[Terminal] Failed to acknowledge cold restore:", { + paneId, + error: error instanceof Error ? error.message : String(error), + }); }); - }); - // Add visual separator - xterm.write("\r\n\x1b[90m─── New session ───\x1b[0m\r\n\r\n"); - - // Reset state for new session - isStreamReadyRef.current = false; - isExitedRef.current = false; - wasKilledByUserRef.current = false; - setExitStatus(null); - clearTerminalKilledByUser(paneId); - pendingInitialStateRef.current = null; - resetModes(); + isStreamReadyRef.current = false; + isExitedRef.current = false; + wasKilledByUserRef.current = false; + setExitStatus(null); + clearTerminalKilledByUser(paneId); + pendingInitialStateRef.current = null; + resetModes(); - // Create new session with previous cwd - createOrAttachRef.current( - { - paneId, - tabId: parentTabIdRef.current || paneId, - workspaceId, - cols: xterm.cols, - rows: xterm.rows, - cwd: restoredCwdRef.current || undefined, - skipColdRestore: true, - allowKilled: true, - }, - { - onSuccess: (result: CreateOrAttachResult) => { - pendingInitialStateRef.current = result; - maybeApplyInitialState(); + createOrAttachRef.current( + { + paneId, + tabId: parentTabIdRef.current || paneId, + workspaceId, + cols: xterm.cols, + rows: xterm.rows, + cwd: cwd ?? restoredCwdRef.current ?? undefined, + skipColdRestore: true, + allowKilled: true, + }, + { + onSuccess: (result: CreateOrAttachResult) => { + pendingInitialStateRef.current = result; + maybeApplyInitialState(); - setIsRestoredMode(false); - coldRestoreState.delete(paneId); + setIsRestoredMode(false); + coldRestoreState.delete(paneId); - setTimeout(() => { - const currentXterm = xtermRef.current; - if (currentXterm) { - currentXterm.focus(); - } - }, 0); - }, - onError: (error: { message?: string }) => { - console.error("[Terminal] Failed to start shell:", error); - setConnectionError(error.message || "Failed to start shell"); - setIsRestoredMode(false); - coldRestoreState.delete(paneId); - isStreamReadyRef.current = true; - flushPendingEvents(); + setTimeout(() => { + const currentXterm = xtermRef.current; + if (currentXterm) { + currentXterm.focus(); + } + }, 0); + }, + onError: (error: { message?: string }) => { + console.error("[Terminal] Failed to start shell:", error); + setConnectionError(error.message || "Failed to start shell"); + setIsRestoredMode(false); + coldRestoreState.delete(paneId); + isStreamReadyRef.current = true; + flushPendingEvents(); + }, }, - }, - ); - }, [ - paneId, - workspaceId, - parentTabIdRef, - xtermRef, - fitAddonRef, - isStreamReadyRef, - isExitedRef, - wasKilledByUserRef, - pendingInitialStateRef, - pendingEventsRef, - createOrAttachRef, - setConnectionError, - setExitStatus, - maybeApplyInitialState, - flushPendingEvents, - resetModes, - ]); + ); + }, + [ + paneId, + workspaceId, + parentTabIdRef, + xtermRef, + fitAddonRef, + isStreamReadyRef, + isExitedRef, + wasKilledByUserRef, + pendingInitialStateRef, + pendingEventsRef, + createOrAttachRef, + setConnectionError, + setExitStatus, + maybeApplyInitialState, + flushPendingEvents, + resetModes, + ], + ); + + handleStartShellRef.current = handleStartShell; return { isRestoredMode, diff --git a/apps/desktop/src/renderer/screens/main/components/WorkspaceView/WorkspaceInitializingView/WorkspaceInitializingView.tsx b/apps/desktop/src/renderer/screens/main/components/WorkspaceView/WorkspaceInitializingView/WorkspaceInitializingView.tsx index 180deff65fb..0df451d125e 100644 --- a/apps/desktop/src/renderer/screens/main/components/WorkspaceView/WorkspaceInitializingView/WorkspaceInitializingView.tsx +++ b/apps/desktop/src/renderer/screens/main/components/WorkspaceView/WorkspaceInitializingView/WorkspaceInitializingView.tsx @@ -30,7 +30,6 @@ interface WorkspaceInitializingViewProps { isInterrupted?: boolean; } -// Steps to display in the progress view (skip pending and ready) const DISPLAY_STEPS: WorkspaceInitStep[] = INIT_STEP_ORDER.filter( (step) => step !== "pending" && step !== "ready", ); @@ -84,8 +83,6 @@ export function WorkspaceInitializingView({ const currentStep = progress?.step ?? "pending"; - // Interrupted state (app restart during init - no in-memory progress) - // Only show after delay to avoid flash during normal creation if (isInterrupted && !progress && showInterruptedUI) { return ( <> @@ -176,7 +173,6 @@ export function WorkspaceInitializingView({ ); } - // Failed state if (hasFailed) { return ( <> @@ -269,7 +265,6 @@ export function WorkspaceInitializingView({ ); } - // Initializing state return (