diff --git a/src/main/ipc/filesystem-mutations.ts b/src/main/ipc/filesystem-mutations.ts index 528baa173..cecb1568d 100644 --- a/src/main/ipc/filesystem-mutations.ts +++ b/src/main/ipc/filesystem-mutations.ts @@ -18,7 +18,7 @@ import { basename, dirname, isAbsolute, join, relative, resolve } from 'path' import { pipeline } from 'stream/promises' import type { Store } from '../persistence' import { authorizeExternalPath, resolveAuthorizedPath, isENOENT } from './filesystem-auth' -import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch' +import { requireSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch' import { importExternalPathsSsh } from './filesystem-import-ssh' /** @@ -70,10 +70,7 @@ export function registerFilesystemMutationHandlers(store: Store): void { 'fs:createFile', async (_event, args: { filePath: string; connectionId?: string }): Promise => { if (args.connectionId) { - const provider = getSshFilesystemProvider(args.connectionId) - if (!provider) { - throw new Error(`No filesystem provider for connection "${args.connectionId}"`) - } + const provider = requireSshFilesystemProvider(args.connectionId) return provider.createFile(args.filePath) } const filePath = await resolveAuthorizedPath(args.filePath, store) @@ -91,10 +88,7 @@ export function registerFilesystemMutationHandlers(store: Store): void { 'fs:createDir', async (_event, args: { dirPath: string; connectionId?: string }): Promise => { if (args.connectionId) { - const provider = getSshFilesystemProvider(args.connectionId) - if (!provider) { - throw new Error(`No filesystem provider for connection "${args.connectionId}"`) - } + const provider = requireSshFilesystemProvider(args.connectionId) return provider.createDir(args.dirPath) } const dirPath = await resolveAuthorizedPath(args.dirPath, store) @@ -113,10 +107,7 @@ export function registerFilesystemMutationHandlers(store: Store): void { args: { oldPath: string; newPath: string; connectionId?: string } ): Promise => { if (args.connectionId) { - const provider = getSshFilesystemProvider(args.connectionId) - if (!provider) { - throw new Error(`No filesystem provider for connection "${args.connectionId}"`) - } + const provider = requireSshFilesystemProvider(args.connectionId) return provider.rename(args.oldPath, args.newPath) } // Why: rename() operates on directory entries, not file contents. If @@ -139,10 +130,7 @@ export function registerFilesystemMutationHandlers(store: Store): void { args: { sourcePath: string; destinationPath: string; connectionId?: string } ): Promise => { if (args.connectionId) { - const provider = getSshFilesystemProvider(args.connectionId) - if (!provider) { - throw new Error(`No filesystem provider for connection "${args.connectionId}"`) - } + const provider = requireSshFilesystemProvider(args.connectionId) return provider.copy(args.sourcePath, args.destinationPath) } const sourcePath = await resolveAuthorizedPath(args.sourcePath, store, { diff --git a/src/main/ipc/filesystem.test.ts b/src/main/ipc/filesystem.test.ts index b9c12aea6..adfca251b 100644 --- a/src/main/ipc/filesystem.test.ts +++ b/src/main/ipc/filesystem.test.ts @@ -106,11 +106,24 @@ vi.mock('../git/worktree', () => ({ })) vi.mock('../providers/ssh-filesystem-dispatch', () => ({ - getSshFilesystemProvider: getSshFilesystemProviderMock + getSshFilesystemProvider: getSshFilesystemProviderMock, + SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE: + 'Remote connection dropped. Click Reconnect on the SSH target before retrying.', + requireSshFilesystemProvider: (connectionId: string) => { + const provider = getSshFilesystemProviderMock(connectionId) + if (!provider) { + throw new Error( + 'Remote connection dropped. Click Reconnect on the SSH target before retrying.' + ) + } + return provider + } })) vi.mock('../providers/ssh-git-dispatch', () => ({ - getSshGitProvider: getSshGitProviderMock + getSshGitProvider: getSshGitProviderMock, + SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE: + 'Remote connection dropped. Click Reconnect on the SSH target before retrying.' })) vi.mock('../text-generation/commit-message-text-generation', () => ({ @@ -230,6 +243,16 @@ describe('registerFilesystemHandlers', () => { lstatMock.mockRejectedValue(Object.assign(new Error('missing'), { code: 'ENOENT' })) }) + it('returns an actionable reconnect error when the SSH filesystem provider is unavailable', async () => { + registerFilesystemHandlers(store as never) + + await expect( + handlers.get('fs:readDir')!(null, { dirPath: '/remote/repo', connectionId: 'ssh-1' }) + ).rejects.toThrow( + 'Remote connection dropped. Click Reconnect on the SSH target before retrying.' + ) + }) + it('rejects readFile when the real path escapes allowed roots', async () => { const linkPath = path.resolve('/workspace/repo/link.txt') realpathMock.mockImplementation(async (targetPath: string) => { diff --git a/src/main/ipc/filesystem.ts b/src/main/ipc/filesystem.ts index 6dafcd3fc..cd818cb9e 100644 --- a/src/main/ipc/filesystem.ts +++ b/src/main/ipc/filesystem.ts @@ -74,8 +74,14 @@ import { registerFilesystemMutationHandlers } from './filesystem-mutations' import { searchWithGitGrep } from './filesystem-search-git' import { listMarkdownDocuments, markdownDocumentsFromRelativePaths } from './markdown-documents' import { checkRgAvailable } from './rg-availability' -import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch' -import { getSshGitProvider } from '../providers/ssh-git-dispatch' +import { + getSshFilesystemProvider, + requireSshFilesystemProvider +} from '../providers/ssh-filesystem-dispatch' +import { + getSshGitProvider, + SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE +} from '../providers/ssh-git-dispatch' import { prepareLocalCommitMessageAgentEnv, type CommitMessageAgentEnvironmentResolvers @@ -169,10 +175,7 @@ export function registerFilesystemHandlers( 'fs:readDir', async (_event, args: { dirPath: string; connectionId?: string }): Promise => { if (args.connectionId) { - const provider = getSshFilesystemProvider(args.connectionId) - if (!provider) { - throw new Error(`No filesystem provider for connection "${args.connectionId}"`) - } + const provider = requireSshFilesystemProvider(args.connectionId) return provider.readDir(args.dirPath) } const dirPath = await resolveAuthorizedPath(args.dirPath, store) @@ -202,10 +205,7 @@ export function registerFilesystemHandlers( args: { filePath: string; connectionId?: string } ): Promise<{ content: string; isBinary: boolean; isImage?: boolean; mimeType?: string }> => { if (args.connectionId) { - const provider = getSshFilesystemProvider(args.connectionId) - if (!provider) { - throw new Error(`No filesystem provider for connection "${args.connectionId}"`) - } + const provider = requireSshFilesystemProvider(args.connectionId) return provider.readFile(args.filePath) } const filePath = await resolveAuthorizedPath(args.filePath, store) @@ -254,10 +254,7 @@ export function registerFilesystemHandlers( args: { rootPath: string; connectionId?: string } ): Promise => { if (args.connectionId) { - const provider = getSshFilesystemProvider(args.connectionId) - if (!provider) { - throw new Error(`No filesystem provider for connection "${args.connectionId}"`) - } + const provider = requireSshFilesystemProvider(args.connectionId) const relativePaths = await provider.listFiles(args.rootPath) return markdownDocumentsFromRelativePaths(args.rootPath, relativePaths) } @@ -274,10 +271,7 @@ export function registerFilesystemHandlers( args: { filePath: string; content: string; connectionId?: string } ): Promise => { if (args.connectionId) { - const provider = getSshFilesystemProvider(args.connectionId) - if (!provider) { - throw new Error(`No filesystem provider for connection "${args.connectionId}"`) - } + const provider = requireSshFilesystemProvider(args.connectionId) return provider.writeFile(args.filePath, args.content) } const filePath = await resolveAuthorizedPath(args.filePath, store) @@ -304,10 +298,7 @@ export function registerFilesystemHandlers( args: { targetPath: string; connectionId?: string; recursive?: boolean } ): Promise => { if (args.connectionId) { - const provider = getSshFilesystemProvider(args.connectionId) - if (!provider) { - throw new Error(`No filesystem provider for connection "${args.connectionId}"`) - } + const provider = requireSshFilesystemProvider(args.connectionId) return provider.deletePath(args.targetPath, args.recursive) } // Why: deleting must operate on the symlink itself, not its target. @@ -345,10 +336,7 @@ export function registerFilesystemHandlers( args: { filePath: string; connectionId?: string } ): Promise<{ size: number; isDirectory: boolean; mtime: number }> => { if (args.connectionId) { - const provider = getSshFilesystemProvider(args.connectionId) - if (!provider) { - throw new Error(`No filesystem provider for connection "${args.connectionId}"`) - } + const provider = requireSshFilesystemProvider(args.connectionId) const s = await provider.stat(args.filePath) return { size: s.size, isDirectory: s.type === 'directory', mtime: s.mtime } } @@ -367,10 +355,7 @@ export function registerFilesystemHandlers( 'fs:search', async (event, args: SearchOptions & { connectionId?: string }): Promise => { if (args.connectionId) { - const provider = getSshFilesystemProvider(args.connectionId) - if (!provider) { - throw new Error(`No filesystem provider for connection "${args.connectionId}"`) - } + const provider = requireSshFilesystemProvider(args.connectionId) return provider.search(args) } const rootPath = await resolveAuthorizedPath(args.rootPath, store) @@ -508,7 +493,7 @@ export function registerFilesystemHandlers( if (args.connectionId) { const provider = getSshGitProvider(args.connectionId) if (!provider) { - throw new Error(`No git provider for connection "${args.connectionId}"`) + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.getStatus(args.worktreePath, options) } @@ -527,7 +512,7 @@ export function registerFilesystemHandlers( const paths = args.paths.map((p) => validateGitRelativeFilePath(args.worktreePath, p)) const provider = getSshGitProvider(args.connectionId) if (!provider) { - throw new Error(`No git provider for connection "${args.connectionId}"`) + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.checkIgnoredPaths(args.worktreePath, paths) } @@ -547,7 +532,7 @@ export function registerFilesystemHandlers( if (args.connectionId) { const provider = getSshGitProvider(args.connectionId) if (!provider) { - throw new Error(`No git provider for connection "${args.connectionId}"`) + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.getHistory(args.worktreePath, options) } @@ -568,7 +553,7 @@ export function registerFilesystemHandlers( if (args.connectionId) { const provider = getSshGitProvider(args.connectionId) if (!provider) { - throw new Error(`No git provider for connection "${args.connectionId}"`) + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.detectConflictOperation(args.worktreePath) } @@ -592,7 +577,7 @@ export function registerFilesystemHandlers( if (args.connectionId) { const provider = getSshGitProvider(args.connectionId) if (!provider) { - throw new Error(`No git provider for connection "${args.connectionId}"`) + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.getDiff( args.worktreePath, @@ -620,7 +605,7 @@ export function registerFilesystemHandlers( if (args.connectionId) { const provider = getSshGitProvider(args.connectionId) if (!provider) { - throw new Error(`No git provider for connection "${args.connectionId}"`) + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.commit(args.worktreePath, args.message) } @@ -647,7 +632,7 @@ export function registerFilesystemHandlers( if (!provider) { return { success: false, - error: `No git provider for connection "${args.connectionId}"` + error: SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE } } let context @@ -738,7 +723,7 @@ export function registerFilesystemHandlers( if (!provider) { return { success: false, - error: `No git provider for connection "${args.connectionId}"` + error: SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE } } const context = await getPullRequestDraftContext( @@ -815,7 +800,7 @@ export function registerFilesystemHandlers( if (args.connectionId) { const provider = getSshGitProvider(args.connectionId) if (!provider) { - throw new Error(`No git provider for connection "${args.connectionId}"`) + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.getBranchCompare(args.worktreePath, args.baseRef) } @@ -834,7 +819,7 @@ export function registerFilesystemHandlers( if (args.connectionId) { const provider = getSshGitProvider(args.connectionId) if (!provider) { - throw new Error(`No git provider for connection "${args.connectionId}"`) + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.getCommitCompare(args.worktreePath, commitId) } @@ -852,7 +837,7 @@ export function registerFilesystemHandlers( if (args.connectionId) { const provider = getSshGitProvider(args.connectionId) if (!provider) { - throw new Error(`No git provider for connection "${args.connectionId}"`) + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.getUpstreamStatus(args.worktreePath) } @@ -867,7 +852,7 @@ export function registerFilesystemHandlers( if (args.connectionId) { const provider = getSshGitProvider(args.connectionId) if (!provider) { - throw new Error(`No git provider for connection "${args.connectionId}"`) + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.fetchRemote(args.worktreePath) } @@ -897,7 +882,7 @@ export function registerFilesystemHandlers( } const provider = getSshGitProvider(args.connectionId) if (!provider) { - throw new Error(`No git provider for connection "${args.connectionId}"`) + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.pushBranch(args.worktreePath, publish, args.pushTarget) } @@ -915,7 +900,7 @@ export function registerFilesystemHandlers( if (args.connectionId) { const provider = getSshGitProvider(args.connectionId) if (!provider) { - throw new Error(`No git provider for connection "${args.connectionId}"`) + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.pullBranch(args.worktreePath) } @@ -944,7 +929,7 @@ export function registerFilesystemHandlers( if (args.connectionId) { const provider = getSshGitProvider(args.connectionId) if (!provider) { - throw new Error(`No git provider for connection "${args.connectionId}"`) + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } const results = await provider.getBranchDiff(args.worktreePath, args.compare.mergeBase, { includePatch: true, @@ -993,7 +978,7 @@ export function registerFilesystemHandlers( if (args.connectionId) { const provider = getSshGitProvider(args.connectionId) if (!provider) { - throw new Error(`No git provider for connection "${args.connectionId}"`) + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.getCommitDiff(args.worktreePath, { commitOid, @@ -1025,7 +1010,7 @@ export function registerFilesystemHandlers( if (args.connectionId) { const provider = getSshGitProvider(args.connectionId) if (!provider) { - throw new Error(`No git provider for connection "${args.connectionId}"`) + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.stageFile(args.worktreePath, args.filePath) } @@ -1044,7 +1029,7 @@ export function registerFilesystemHandlers( if (args.connectionId) { const provider = getSshGitProvider(args.connectionId) if (!provider) { - throw new Error(`No git provider for connection "${args.connectionId}"`) + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.unstageFile(args.worktreePath, args.filePath) } @@ -1063,7 +1048,7 @@ export function registerFilesystemHandlers( if (args.connectionId) { const provider = getSshGitProvider(args.connectionId) if (!provider) { - throw new Error(`No git provider for connection "${args.connectionId}"`) + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.discardChanges(args.worktreePath, args.filePath) } @@ -1082,7 +1067,7 @@ export function registerFilesystemHandlers( if (args.connectionId) { const provider = getSshGitProvider(args.connectionId) if (!provider) { - throw new Error(`No git provider for connection "${args.connectionId}"`) + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.bulkDiscardChanges(args.worktreePath, args.filePaths) } @@ -1101,7 +1086,7 @@ export function registerFilesystemHandlers( if (args.connectionId) { const provider = getSshGitProvider(args.connectionId) if (!provider) { - throw new Error(`No git provider for connection "${args.connectionId}"`) + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.bulkStageFiles(args.worktreePath, args.filePaths) } @@ -1120,7 +1105,7 @@ export function registerFilesystemHandlers( if (args.connectionId) { const provider = getSshGitProvider(args.connectionId) if (!provider) { - throw new Error(`No git provider for connection "${args.connectionId}"`) + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.bulkUnstageFiles(args.worktreePath, args.filePaths) } @@ -1142,7 +1127,7 @@ export function registerFilesystemHandlers( if (args.connectionId) { const provider = getSshGitProvider(args.connectionId) if (!provider) { - throw new Error(`No git provider for connection "${args.connectionId}"`) + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.getRemoteFileUrl(args.worktreePath, args.relativePath, args.line) } diff --git a/src/main/ipc/ssh.test.ts b/src/main/ipc/ssh.test.ts index f5efc8f9b..ad2c243fc 100644 --- a/src/main/ipc/ssh.test.ts +++ b/src/main/ipc/ssh.test.ts @@ -26,6 +26,7 @@ const { mockConnectionManager: { connect: vi.fn(), disconnect: vi.fn(), + getConnection: vi.fn(), getState: vi.fn(), disconnectAll: vi.fn() }, @@ -188,6 +189,7 @@ describe('SSH IPC handlers', () => { mockConnectionManager.connect.mockReset() mockConnectionManager.disconnect.mockReset() + mockConnectionManager.getConnection.mockReset() mockConnectionManager.getState.mockReset() mockConnectionManager.disconnectAll.mockReset() @@ -323,6 +325,72 @@ describe('SSH IPC handlers', () => { expect(mockConnectionManager.connect).toHaveBeenCalledWith(target) }) + it('surfaces relay channel loss while the SSH connection remains alive', async () => { + vi.useFakeTimers() + const target: SshTarget = { + id: 'ssh-1', + label: 'Server', + host: 'example.com', + port: 22, + username: 'deploy' + } + const conn = {} + mockSshStore.getTarget.mockReturnValue(target) + mockConnectionManager.connect.mockResolvedValue(conn) + mockConnectionManager.getConnection.mockReturnValue(conn) + mockConnectionManager.getState.mockReturnValue({ + targetId: 'ssh-1', + status: 'connected', + error: null, + reconnectAttempt: 0 + }) + + try { + await handlers.get('ssh:connect')!(null, { targetId: 'ssh-1' }) + const onDispose = mockMux.onDispose.mock.calls[0]?.[0] as + | ((reason: 'shutdown' | 'connection_lost') => void) + | undefined + + onDispose?.('connection_lost') + + expect(mockWindow.webContents.send).toHaveBeenCalledWith('ssh:state-changed', { + targetId: 'ssh-1', + state: { + targetId: 'ssh-1', + status: 'reconnecting', + error: 'Relay channel lost. Reconnecting...', + reconnectAttempt: 1 + } + }) + expect(handlers.get('ssh:getState')!(null, { targetId: 'ssh-1' })).toEqual({ + targetId: 'ssh-1', + status: 'reconnecting', + error: 'Relay channel lost. Reconnecting...', + reconnectAttempt: 1 + }) + + await vi.advanceTimersByTimeAsync(500) + + expect(mockWindow.webContents.send).toHaveBeenCalledWith('ssh:state-changed', { + targetId: 'ssh-1', + state: { + targetId: 'ssh-1', + status: 'connected', + error: null, + reconnectAttempt: 0 + } + }) + expect(handlers.get('ssh:getState')!(null, { targetId: 'ssh-1' })).toEqual({ + targetId: 'ssh-1', + status: 'connected', + error: null, + reconnectAttempt: 0 + }) + } finally { + vi.useRealTimers() + } + }) + it('forwards remote PTY events into the runtime', async () => { const runtime = { onPtyData: vi.fn(), diff --git a/src/main/ipc/ssh.ts b/src/main/ipc/ssh.ts index 3f7f1ddda..d0b6ad845 100644 --- a/src/main/ipc/ssh.ts +++ b/src/main/ipc/ssh.ts @@ -72,6 +72,7 @@ type RelayLostBackoffState = { pendingTimer: ReturnType | null } const relayLostBackoff = new Map() +const relayStateOverrides = new Map() const RELAY_LOST_MAX_ATTEMPTS = 6 const RELAY_LOST_BASE_DELAY_MS = 500 const RELAY_LOST_MAX_DELAY_MS = 15_000 @@ -91,6 +92,37 @@ function clearRelayLostBackoff(targetId: string): void { relayLostBackoff.delete(targetId) } +function broadcastSshState( + getMainWindow: () => BrowserWindow | null, + targetId: string, + state: SshConnectionState +): void { + const win = getMainWindow() + if (win && !win.isDestroyed()) { + win.webContents.send('ssh:state-changed', { targetId, state }) + } +} + +function publishRelayOverride( + getMainWindow: () => BrowserWindow | null, + targetId: string, + status: SshConnectionStatus, + error: string | null, + reconnectAttempt: number +): void { + const state: SshConnectionState = { targetId, status, error, reconnectAttempt } + relayStateOverrides.set(targetId, state) + broadcastSshState(getMainWindow, targetId, state) +} + +function clearRelayStateOverride(targetId: string): void { + relayStateOverrides.delete(targetId) +} + +function getPublicSshState(targetId: string): SshConnectionState | undefined { + return relayStateOverrides.get(targetId) ?? connectionManager!.getState(targetId) ?? undefined +} + function broadcastPortForwards(getMainWindow: () => BrowserWindow | null, targetId: string): void { const win = getMainWindow() if (!win || win.isDestroyed()) { @@ -243,16 +275,33 @@ export function registerSshHandlers( return } - const win = getMainWindow() - if (win && !win.isDestroyed()) { - win.webContents.send('ssh:state-changed', { targetId, state }) - } - // Why: when SSH reconnects after a network blip, we must re-deploy the // relay and rebuild the full provider stack. The session's state machine // ensures this only triggers when appropriate — 'deploying' state from // an explicit ssh:connect is not 'ready', so this branch won't fire. const session = activeSessions.get(targetId) + const sessionState = session?.getState() + const shouldReconnectRelay = + session !== undefined && + state.status === 'connected' && + state.reconnectAttempt === 0 && + (sessionState === 'ready' || sessionState === 'reconnecting') + + if (shouldReconnectRelay) { + // Why: SSH is connected before the relay providers are rebuilt. Keep + // renderer actions gated until SshRelaySession reaches ready again. + publishRelayOverride( + getMainWindow, + targetId, + 'reconnecting', + 'Relay channel reconnecting...', + state.reconnectAttempt + ) + } else { + clearRelayStateOverride(targetId) + broadcastSshState(getMainWindow, targetId, state) + } + if (!session) { return } @@ -260,12 +309,7 @@ export function registerSshHandlers( // 'reconnecting' (previous reconnect attempt failed, e.g. relay deploy // error on a working SSH connection). Without the 'reconnecting' check, // a failed relay deploy would permanently brick the session. - const sessionState = session.getState() - if ( - state.status === 'connected' && - state.reconnectAttempt === 0 && - (sessionState === 'ready' || sessionState === 'reconnecting') - ) { + if (shouldReconnectRelay) { const target = sshStore?.getTarget(targetId) const conn = connectionManager?.getConnection(targetId) if (conn) { @@ -305,6 +349,7 @@ export function registerSshHandlers( session.dispose() activeSessions.delete(args.id) clearRelayLostBackoff(args.id) + clearRelayStateOverride(args.id) } try { await connectionManager!.disconnect(args.id) @@ -342,6 +387,7 @@ export function registerSshHandlers( }) async function doConnect(targetId: string): Promise { + clearRelayStateOverride(targetId) const target = sshStore!.getTarget(targetId) if (!target) { throw new Error(`SSH target "${targetId}" not found`) @@ -360,6 +406,7 @@ export function registerSshHandlers( existingSession.detach() activeSessions.delete(targetId) clearRelayLostBackoff(targetId) + clearRelayStateOverride(targetId) } // Why: create the session early so onStateChange sees it in 'deploying' @@ -392,18 +439,13 @@ export function registerSshHandlers( credentialRequestedForTarget.delete(targetId) activeSessions.delete(targetId) clearRelayLostBackoff(targetId) - const win = getMainWindow() - if (win && !win.isDestroyed()) { - win.webContents.send('ssh:state-changed', { - targetId, - state: { - targetId, - status, - error: errObj.message, - reconnectAttempt: 0 - } - }) - } + clearRelayStateOverride(targetId) + broadcastSshState(getMainWindow, targetId, { + targetId, + status, + error: errObj.message, + reconnectAttempt: 0 + }) throw err } @@ -432,18 +474,7 @@ export function registerSshHandlers( console.warn( `[ssh] Terminal relay error for ${tid}: ${err.message}; skipping reconnect backoff.` ) - const win = getMainWindow() - if (win && !win.isDestroyed()) { - win.webContents.send('ssh:state-changed', { - targetId: tid, - state: { - targetId: tid, - status: 'error', - error: err.message, - reconnectAttempt: 0 - } - }) - } + publishRelayOverride(getMainWindow, tid, 'error', err.message, 0) }) session.setOnRelayLost((tid) => { @@ -477,18 +508,13 @@ export function registerSshHandlers( // Why: surface the failure so the renderer can prompt the user. // A still-live SSH connection with a dead relay is otherwise an // invisible failure — typing in remote terminals just stops working. - const win = getMainWindow() - if (win && !win.isDestroyed()) { - win.webContents.send('ssh:state-changed', { - targetId: tid, - state: { - targetId: tid, - status: 'error', - error: 'Relay channel kept dropping. Please reconnect.', - reconnectAttempt: 0 - } - }) - } + publishRelayOverride( + getMainWindow, + tid, + 'error', + 'Relay channel kept dropping. Click Reconnect on the SSH target before retrying.', + 0 + ) return } const delay = Math.min( @@ -496,6 +522,13 @@ export function registerSshHandlers( RELAY_LOST_MAX_DELAY_MS ) state.attempts += 1 + publishRelayOverride( + getMainWindow, + tid, + 'reconnecting', + 'Relay channel lost. Reconnecting...', + state.attempts + ) state.pendingTimer = setTimeout(() => { state.pendingTimer = null state.lastAttemptStartedAt = Date.now() @@ -529,6 +562,15 @@ export function registerSshHandlers( relayLostBackoff.delete(tid) } } + clearRelayStateOverride(tid) + if (!testingTargets.has(tid)) { + broadcastSshState(getMainWindow, tid, { + targetId: tid, + status: 'connected', + error: null, + reconnectAttempt: 0 + }) + } void restorePortForwards(tid, getMainWindow) }) @@ -540,6 +582,7 @@ export function registerSshHandlers( // trigger the reconnection logic. const win = getMainWindow() if (win && !win.isDestroyed()) { + clearRelayStateOverride(targetId) win.webContents.send('ssh:state-changed', { targetId, state: { @@ -566,7 +609,7 @@ export function registerSshHandlers( credentialRequestedForTarget.delete(targetId) sshStore!.updateTarget(targetId, { lastRequiredPassphrase: requiredPassphrase }) - return connectionManager!.getState(targetId)! + return getPublicSshState(targetId)! } ipcMain.handle('ssh:disconnect', async (_event, args: { targetId: string }) => { @@ -579,6 +622,7 @@ export function registerSshHandlers( session.detach() activeSessions.delete(args.targetId) clearRelayLostBackoff(args.targetId) + clearRelayStateOverride(args.targetId) } await connectionManager!.disconnect(args.targetId) }) @@ -625,12 +669,13 @@ export function registerSshHandlers( session.dispose() activeSessions.delete(args.targetId) clearRelayLostBackoff(args.targetId) + clearRelayStateOverride(args.targetId) } await connectionManager!.disconnect(args.targetId) }) ipcMain.handle('ssh:getState', (_event, args: { targetId: string }) => { - return connectionManager!.getState(args.targetId) + return getPublicSshState(args.targetId) }) // Why: callers that want to auto-connect (Cmd+J jump, terminal reattach) need diff --git a/src/main/ipc/worktree-remote.ts b/src/main/ipc/worktree-remote.ts index a1a35665a..f97b0af42 100644 --- a/src/main/ipc/worktree-remote.ts +++ b/src/main/ipc/worktree-remote.ts @@ -30,7 +30,7 @@ import type { OrcaRuntimeService } from '../runtime/orca-runtime' import type { RemoteFetchResult, RemoteTrackingBase } from '../runtime/orca-runtime' import { isWslPath, parseWslPath, getWslHome } from '../wsl' import { createSetupRunnerScript, getEffectiveHooks, shouldRunSetupForCreate } from '../hooks' -import { getSshGitProvider } from '../providers/ssh-git-dispatch' +import { requireSshGitProvider } from '../providers/ssh-git-dispatch' import { getActiveMultiplexer } from './ssh' import type { SshGitProvider } from '../providers/ssh-git-provider' import { isTuiAgent } from '../../shared/tui-agent-config' @@ -319,10 +319,7 @@ export async function createRemoteWorktree( throw new Error('Sparse checkout is not supported for remote SSH repos yet.') } - const provider = getSshGitProvider(repo.connectionId!) as SshGitProvider | undefined - if (!provider) { - throw new Error(`No git provider for connection "${repo.connectionId}"`) - } + const provider = requireSshGitProvider(repo.connectionId!) const settings = store.getSettings() const requestedName = args.name diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts index afeb41f55..5e53b672d 100644 --- a/src/main/ipc/worktrees.test.ts +++ b/src/main/ipc/worktrees.test.ts @@ -91,7 +91,18 @@ vi.mock('../github/client', () => ({ })) vi.mock('../providers/ssh-git-dispatch', () => ({ - getSshGitProvider: getSshGitProviderMock + getSshGitProvider: getSshGitProviderMock, + SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE: + 'Remote connection dropped. Click Reconnect on the SSH target before retrying.', + requireSshGitProvider: (connectionId: string) => { + const provider = getSshGitProviderMock(connectionId) + if (!provider) { + throw new Error( + 'Remote connection dropped. Click Reconnect on the SSH target before retrying.' + ) + } + return provider + } })) vi.mock('./ssh', () => ({ diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index 5148956f7..17b84923c 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -25,7 +25,7 @@ import { resolveGitHubPrStartPoint } from '../github/pr-start-point' import { getProjectRef as getGlabProjectRef, getGlabKnownHosts } from '../gitlab/gl-utils' import { getWorkItemByProjectRef as getGitLabWorkItemByProjectRef } from '../gitlab/client' import { listRepoWorktrees, createFolderWorktree } from '../repo-worktrees' -import { getSshGitProvider } from '../providers/ssh-git-dispatch' +import { getSshGitProvider, requireSshGitProvider } from '../providers/ssh-git-dispatch' import { createIssueCommandRunnerScript, getEffectiveHooks, @@ -585,10 +585,7 @@ export function registerWorktreeHandlers( // Why: the renderer-supplied worktreeId contains a filesystem path. // Re-derive the canonical path from git before any destructive action. - const provider = repo.connectionId ? getSshGitProvider(repo.connectionId) : null - if (repo.connectionId && !provider) { - throw new Error(`No git provider for connection "${repo.connectionId}"`) - } + const provider = repo.connectionId ? requireSshGitProvider(repo.connectionId) : null const registeredWorktrees = repo.connectionId ? await provider!.listWorktrees(repo.path) : await listGitWorktrees(repo.path) diff --git a/src/main/providers/ssh-filesystem-dispatch.ts b/src/main/providers/ssh-filesystem-dispatch.ts index aa70df41f..6cadd3b7e 100644 --- a/src/main/providers/ssh-filesystem-dispatch.ts +++ b/src/main/providers/ssh-filesystem-dispatch.ts @@ -2,6 +2,9 @@ import type { IFilesystemProvider } from './types' const sshProviders = new Map() +export const SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE = + 'Remote connection dropped. Click Reconnect on the SSH target before retrying.' + export function registerSshFilesystemProvider( connectionId: string, provider: IFilesystemProvider @@ -16,3 +19,11 @@ export function unregisterSshFilesystemProvider(connectionId: string): void { export function getSshFilesystemProvider(connectionId: string): IFilesystemProvider | undefined { return sshProviders.get(connectionId) } + +export function requireSshFilesystemProvider(connectionId: string): IFilesystemProvider { + const provider = getSshFilesystemProvider(connectionId) + if (!provider) { + throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE) + } + return provider +} diff --git a/src/main/providers/ssh-git-dispatch.ts b/src/main/providers/ssh-git-dispatch.ts index 74afe7700..a1032331f 100644 --- a/src/main/providers/ssh-git-dispatch.ts +++ b/src/main/providers/ssh-git-dispatch.ts @@ -2,6 +2,9 @@ import type { SshGitProvider } from './ssh-git-provider' const sshProviders = new Map() +export const SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE = + 'Remote connection dropped. Click Reconnect on the SSH target before retrying.' + export function registerSshGitProvider(connectionId: string, provider: SshGitProvider): void { sshProviders.set(connectionId, provider) } @@ -13,3 +16,11 @@ export function unregisterSshGitProvider(connectionId: string): void { export function getSshGitProvider(connectionId: string): SshGitProvider | undefined { return sshProviders.get(connectionId) } + +export function requireSshGitProvider(connectionId: string): SshGitProvider { + const provider = getSshGitProvider(connectionId) + if (!provider) { + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) + } + return provider +} diff --git a/src/main/runtime/orca-runtime-files.test.ts b/src/main/runtime/orca-runtime-files.test.ts index 66dc75086..d0fc2c78f 100644 --- a/src/main/runtime/orca-runtime-files.test.ts +++ b/src/main/runtime/orca-runtime-files.test.ts @@ -41,7 +41,9 @@ vi.mock('../ipc/filesystem-auth', async () => { }) vi.mock('../providers/ssh-filesystem-dispatch', () => ({ - getSshFilesystemProvider: vi.fn() + getSshFilesystemProvider: vi.fn(), + SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE: + 'Remote connection dropped. Click Reconnect on the SSH target before retrying.' })) import { awaitRuntimeFileWatcherUnsubscribes, RuntimeFileCommands } from './orca-runtime-files' diff --git a/src/main/runtime/orca-runtime-files.ts b/src/main/runtime/orca-runtime-files.ts index de05bf41e..f5c5c90b6 100644 --- a/src/main/runtime/orca-runtime-files.ts +++ b/src/main/runtime/orca-runtime-files.ts @@ -49,7 +49,10 @@ import { SEARCH_TIMEOUT_MS } from '../../shared/text-search' import type { Store } from '../persistence' -import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch' +import { + getSshFilesystemProvider, + SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE +} from '../providers/ssh-filesystem-dispatch' import { joinWorktreeRelativePath, normalizeRuntimeRelativePath } from './runtime-relative-paths' const MOBILE_FILE_LIST_LIMIT = 5000 @@ -225,7 +228,7 @@ export class RuntimeFileCommands { const provider = target.connectionId ? getSshFilesystemProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_filesystem_unavailable') + throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.readDir(target.path) } @@ -258,7 +261,7 @@ export class RuntimeFileCommands { const provider = target.connectionId ? getSshFilesystemProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_filesystem_unavailable') + throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.watch(target.path, callback) } @@ -323,7 +326,7 @@ export class RuntimeFileCommands { const provider = target.connectionId ? getSshFilesystemProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_filesystem_unavailable') + throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE) } const fileStats = await provider.stat(target.path) if (fileStats.size > RUNTIME_PREVIEWABLE_BINARY_MAX_BYTES) { @@ -368,7 +371,7 @@ export class RuntimeFileCommands { const provider = target.connectionId ? getSshFilesystemProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_filesystem_unavailable') + throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE) } await provider.writeFile(target.path, content) return { ok: true } @@ -399,7 +402,7 @@ export class RuntimeFileCommands { const content = Buffer.from(contentBase64, 'base64') if (target.connectionId) { if (!provider) { - throw new Error('remote_filesystem_unavailable') + throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE) } await provider.writeFileBase64(target.path, contentBase64) return { ok: true } @@ -422,7 +425,7 @@ export class RuntimeFileCommands { const content = Buffer.from(contentBase64, 'base64') if (target.connectionId) { if (!provider) { - throw new Error('remote_filesystem_unavailable') + throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE) } await provider.writeFileBase64Chunk(target.path, contentBase64, append) return { ok: true } @@ -442,7 +445,7 @@ export class RuntimeFileCommands { const provider = target.connectionId ? getSshFilesystemProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_filesystem_unavailable') + throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE) } await provider.createFile(target.path) return { ok: true } @@ -466,7 +469,7 @@ export class RuntimeFileCommands { const provider = target.connectionId ? getSshFilesystemProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_filesystem_unavailable') + throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE) } await provider.createDir(target.path) return { ok: true } @@ -486,7 +489,7 @@ export class RuntimeFileCommands { const provider = target.connectionId ? getSshFilesystemProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_filesystem_unavailable') + throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE) } await provider.createDirNoClobber(target.path) return { ok: true } @@ -509,7 +512,7 @@ export class RuntimeFileCommands { : null if (tempTarget.connectionId) { if (!provider) { - throw new Error('remote_filesystem_unavailable') + throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE) } await provider.copy(tempTarget.path, finalTarget.path) await provider.deletePath(tempTarget.path, false).catch(() => {}) @@ -537,7 +540,7 @@ export class RuntimeFileCommands { : null if (oldTarget.connectionId) { if (!provider) { - throw new Error('remote_filesystem_unavailable') + throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE) } await provider.rename(oldTarget.path, newTarget.path) return { ok: true } @@ -566,7 +569,7 @@ export class RuntimeFileCommands { : null if (sourceTarget.connectionId) { if (!provider) { - throw new Error('remote_filesystem_unavailable') + throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE) } await provider.copy(sourceTarget.path, destinationTarget.path) return { ok: true } @@ -595,7 +598,7 @@ export class RuntimeFileCommands { const provider = target.connectionId ? getSshFilesystemProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_filesystem_unavailable') + throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE) } await provider.deletePath(target.path, recursive) return { ok: true } @@ -620,7 +623,7 @@ export class RuntimeFileCommands { const searchOptions = { ...options, rootPath } if (target.connectionId) { if (!provider) { - throw new Error('remote_filesystem_unavailable') + throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.search(searchOptions) } @@ -647,7 +650,7 @@ export class RuntimeFileCommands { const provider = target.connectionId ? getSshFilesystemProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_filesystem_unavailable') + throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE) } const relativePaths = await provider.listFiles(target.worktree.path) return markdownDocumentsFromRelativePaths(target.worktree.path, relativePaths) @@ -663,7 +666,7 @@ export class RuntimeFileCommands { const provider = target.connectionId ? getSshFilesystemProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_filesystem_unavailable') + throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE) } const fileStat = await provider.stat(target.path) return { @@ -790,7 +793,7 @@ export class RuntimeFileCommands { private async readRemoteMobileFile(filePath: string, connectionId: string): Promise { const provider = getSshFilesystemProvider(connectionId) if (!provider) { - throw new Error('remote_filesystem_unavailable') + throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE) } const fileStat = await provider.stat(filePath) // Why: the SSH filesystem API does not expose ranged reads here, so reject diff --git a/src/main/runtime/orca-runtime-git.ts b/src/main/runtime/orca-runtime-git.ts index 7aaad5bc7..a82a2edc8 100644 --- a/src/main/runtime/orca-runtime-git.ts +++ b/src/main/runtime/orca-runtime-git.ts @@ -34,7 +34,10 @@ import { import { getHistory as getGitHistory } from '../git/history' import { getUpstreamStatus } from '../git/upstream' import { gitFetch, gitPull, gitPush } from '../git/remote' -import { getSshGitProvider } from '../providers/ssh-git-dispatch' +import { + getSshGitProvider, + SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE +} from '../providers/ssh-git-dispatch' import { checkIgnoredPaths } from '../git/check-ignored-paths' import { cancelGenerateCommitMessageLocal, @@ -85,7 +88,7 @@ export class RuntimeGitCommands { const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_git_unavailable') + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return options ? provider.getStatus(target.worktree.path, options) @@ -104,7 +107,7 @@ export class RuntimeGitCommands { const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_git_unavailable') + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.checkIgnoredPaths(target.worktree.path, relativePaths) } @@ -119,7 +122,7 @@ export class RuntimeGitCommands { const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_git_unavailable') + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.getHistory(target.worktree.path, options) } @@ -131,7 +134,7 @@ export class RuntimeGitCommands { const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_git_unavailable') + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.detectConflictOperation(target.worktree.path) } @@ -149,7 +152,7 @@ export class RuntimeGitCommands { const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_git_unavailable') + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.getDiff(target.worktree.path, relativePath, staged, compareAgainstHead) } @@ -164,7 +167,7 @@ export class RuntimeGitCommands { const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_git_unavailable') + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.getBranchCompare(target.worktree.path, baseRef) } @@ -179,7 +182,7 @@ export class RuntimeGitCommands { const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_git_unavailable') + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.getCommitCompare(target.worktree.path, commitId) } @@ -191,7 +194,7 @@ export class RuntimeGitCommands { const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_git_unavailable') + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.getUpstreamStatus(target.worktree.path) } @@ -203,7 +206,7 @@ export class RuntimeGitCommands { const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_git_unavailable') + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } await provider.fetchRemote(target.worktree.path) return { ok: true } @@ -217,7 +220,7 @@ export class RuntimeGitCommands { const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_git_unavailable') + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } await provider.pullBranch(target.worktree.path) return { ok: true } @@ -235,7 +238,7 @@ export class RuntimeGitCommands { const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_git_unavailable') + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } await provider.pushBranch(target.worktree.path, publish === true, pushTarget) return { ok: true } @@ -256,7 +259,7 @@ export class RuntimeGitCommands { const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_git_unavailable') + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } const results = await provider.getBranchDiff(target.worktree.path, compare.mergeBase, { includePatch: true, @@ -291,7 +294,7 @@ export class RuntimeGitCommands { const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_git_unavailable') + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.getCommitDiff(target.worktree.path, { commitOid: args.commitOid, @@ -319,7 +322,7 @@ export class RuntimeGitCommands { const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_git_unavailable') + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.commit(target.worktree.path, message) } @@ -344,7 +347,7 @@ export class RuntimeGitCommands { if (!provider) { return { success: false, - error: `No git provider for connection "${target.connectionId}"` + error: SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE } } let context: CommitMessageDraftContext | null @@ -418,7 +421,7 @@ export class RuntimeGitCommands { if (target.connectionId && !provider) { return { success: false, - error: `No git provider for connection "${target.connectionId}"` + error: SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE } } const context = target.connectionId @@ -481,7 +484,7 @@ export class RuntimeGitCommands { const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_git_unavailable') + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } await provider.stageFile(target.worktree.path, relativePath) return { ok: true } @@ -496,7 +499,7 @@ export class RuntimeGitCommands { const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_git_unavailable') + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } await provider.unstageFile(target.worktree.path, relativePath) return { ok: true } @@ -514,7 +517,7 @@ export class RuntimeGitCommands { const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_git_unavailable') + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } await provider.bulkStageFiles(target.worktree.path, relativePaths) return { ok: true } @@ -532,7 +535,7 @@ export class RuntimeGitCommands { const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_git_unavailable') + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } await provider.bulkUnstageFiles(target.worktree.path, relativePaths) return { ok: true } @@ -550,7 +553,7 @@ export class RuntimeGitCommands { const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_git_unavailable') + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } await provider.bulkDiscardChanges(target.worktree.path, relativePaths) return { ok: true } @@ -565,7 +568,7 @@ export class RuntimeGitCommands { const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_git_unavailable') + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } await provider.discardChanges(target.worktree.path, relativePath) return { ok: true } @@ -584,7 +587,7 @@ export class RuntimeGitCommands { const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null if (target.connectionId) { if (!provider) { - throw new Error('remote_git_unavailable') + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) } return provider.getRemoteFileUrl(target.worktree.path, normalizedRelativePath, line) } diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 38955ce6b..8a840e10d 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -87,6 +87,17 @@ vi.mock('../git/worktree', () => ({ vi.mock('../providers/ssh-git-dispatch', () => ({ getSshGitProvider: getSshGitProviderMock, + SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE: + 'Remote connection dropped. Click Reconnect on the SSH target before retrying.', + requireSshGitProvider: (connectionId: string) => { + const provider = getSshGitProviderMock(connectionId) + if (!provider) { + throw new Error( + 'Remote connection dropped. Click Reconnect on the SSH target before retrying.' + ) + } + return provider + }, registerSshGitProvider: registerSshGitProviderMock, unregisterSshGitProvider: unregisterSshGitProviderMock })) diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index cb6620cdb..974f29601 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -273,7 +273,7 @@ import { killAllProcessesForWorktree } from './worktree-teardown' import { MOBILE_SUBSCRIBE_SCROLLBACK_ROWS } from './scrollback-limits' import type { IFilesystemProvider, IPtyProvider } from '../providers/types' import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch' -import { getSshGitProvider } from '../providers/ssh-git-dispatch' +import { getSshGitProvider, requireSshGitProvider } from '../providers/ssh-git-dispatch' import type { ClaudeAccountService } from '../claude-accounts/service' import type { CodexAccountService } from '../codex-accounts/service' import type { RateLimitService } from '../rate-limits/service' @@ -6371,10 +6371,7 @@ export class OrcaRuntimeService { throw new Error('Folder mode does not support deleting worktrees.') } if (repo.connectionId) { - const provider = getSshGitProvider(repo.connectionId) - if (!provider) { - throw new Error(`No git provider for connection "${repo.connectionId}"`) - } + const provider = requireSshGitProvider(repo.connectionId) await provider.removeWorktree(worktree.path, force) this.clearOptimisticReconcileToken(worktree.id) this.store.removeWorktreeMeta(worktree.id) diff --git a/src/main/window/clipboard-ipc-handlers.test.ts b/src/main/window/clipboard-ipc-handlers.test.ts index 2996e3f0c..2eb99778f 100644 --- a/src/main/window/clipboard-ipc-handlers.test.ts +++ b/src/main/window/clipboard-ipc-handlers.test.ts @@ -54,7 +54,16 @@ vi.mock('electron', () => ({ })) vi.mock('../providers/ssh-filesystem-dispatch', () => ({ - getSshFilesystemProvider: getSshFilesystemProviderMock + getSshFilesystemProvider: getSshFilesystemProviderMock, + requireSshFilesystemProvider: (connectionId: string) => { + const provider = getSshFilesystemProviderMock(connectionId) + if (!provider) { + throw new Error( + 'Remote connection dropped. Click Reconnect on the SSH target before retrying.' + ) + } + return provider + } })) import { registerClipboardHandlers } from './clipboard-ipc-handlers' diff --git a/src/main/window/clipboard-ipc-handlers.ts b/src/main/window/clipboard-ipc-handlers.ts index b4586d9cc..fb82a4ac8 100644 --- a/src/main/window/clipboard-ipc-handlers.ts +++ b/src/main/window/clipboard-ipc-handlers.ts @@ -3,7 +3,7 @@ import path from 'node:path' import { randomUUID } from 'node:crypto' import { app, clipboard, ipcMain, nativeImage } from 'electron' -import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch' +import { requireSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch' import { isWindowsAbsolutePathLike } from '../../shared/cross-platform-path' type SaveClipboardImageAsTempFileArgs = { @@ -26,10 +26,7 @@ async function saveClipboardImageBufferAsTempFile( const fileName = `orca-paste-${Date.now()}-${randomUUID()}.png` if (args?.connectionId) { - const provider = getSshFilesystemProvider(args.connectionId) - if (!provider) { - throw new Error(`No filesystem provider for connection "${args.connectionId}"`) - } + const provider = requireSshFilesystemProvider(args.connectionId) const remoteTempDir = (await provider.getTempDir?.()) ?? REMOTE_CLIPBOARD_IMAGE_TEMP_DIR const remotePath = joinRemotePath(remoteTempDir, fileName) // Why: SSH terminal agents run on the remote host, so the pasted path must diff --git a/src/renderer/src/components/sidebar/WorktreeList.tsx b/src/renderer/src/components/sidebar/WorktreeList.tsx index 2988f5018..0703dddbb 100644 --- a/src/renderer/src/components/sidebar/WorktreeList.tsx +++ b/src/renderer/src/components/sidebar/WorktreeList.tsx @@ -32,7 +32,6 @@ import type { WorkspaceStatus, WorkspaceStatusDefinition } from '../../../../shared/types' -import { isGitRepoKind } from '../../../../shared/repo-kind' import { buildWorktreeComparator } from './smart-sort' import { buildAttentionByWorktree, @@ -81,6 +80,7 @@ import { } from './worktree-multi-selection' import { branchDisplayName } from './WorktreeCardHelpers' import { callRuntimeRpc, getActiveRuntimeTarget } from '@/runtime/runtime-rpc-client' +import { getRepoHeaderCreateState } from './repo-header-create-state' // How long to wait after a sortEpoch bump before actually re-sorting. // Prevents jarring position shifts when background events (AI starting work, @@ -341,6 +341,7 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp const activeLineageChildTargetLabel = useAppStore((s) => activeLineageChildConnectionId ? s.sshTargetLabels.get(activeLineageChildConnectionId) : null ) + const sshConnectionStates = useAppStore((s) => s.sshConnectionStates) const activeLineageChildSshDisconnected = activeLineageChildSshStatus !== null && activeLineageChildSshStatus !== 'connected' const renderRowsRef = useRef(renderRows) @@ -854,6 +855,15 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp ? getWorkspaceStatusFromGroupKey(row.key, workspaceStatuses) : null const isPinnedHeader = row.key === PINNED_GROUP_KEY + const createState = row.repo + ? getRepoHeaderCreateState({ + repo: row.repo, + label: row.label, + sshStatus: row.repo.connectionId + ? (sshConnectionStates.get(row.repo.connectionId)?.status ?? null) + : null + }) + : null return (
- + + ) : ( + + onKeyDown={stopRepoHeaderKeyboardToggle} + onClick={(event) => { + event.preventDefault() + event.stopPropagation() + if (row.repo) { + handleCreateForRepo(row.repo.id) + } + }} + > + + + )} - {row.repo && !isGitRepoKind(row.repo) - ? `${row.label} is opened as a folder` - : `Create worktree for ${row.label}`} + {createState?.tooltip ?? `Create worktree for ${row.label}`} ) : null} diff --git a/src/renderer/src/components/sidebar/repo-header-create-state.test.ts b/src/renderer/src/components/sidebar/repo-header-create-state.test.ts new file mode 100644 index 000000000..d25ba41cf --- /dev/null +++ b/src/renderer/src/components/sidebar/repo-header-create-state.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it } from 'vitest' +import type { SshConnectionStatus } from '../../../../shared/ssh-types' +import type { Repo } from '../../../../shared/types' +import { getRepoHeaderCreateState } from './repo-header-create-state' + +function makeRepo(overrides: Partial = {}): Repo { + return { + id: 'repo-1', + path: '/repo', + displayName: 'orca', + badgeColor: '#999999', + addedAt: 1, + ...overrides + } +} + +describe('repo header create state', () => { + it('allows local git repos', () => { + expect( + getRepoHeaderCreateState({ + repo: makeRepo(), + label: 'orca', + sshStatus: null + }) + ).toEqual({ + disabled: false, + tooltip: 'Create worktree for orca', + ariaLabel: 'Create worktree for orca', + requiresSshReconnect: false + }) + }) + + it('disables folder repos', () => { + expect( + getRepoHeaderCreateState({ + repo: makeRepo({ kind: 'folder' }), + label: 'docs', + sshStatus: null + }) + ).toMatchObject({ + disabled: true, + tooltip: 'docs is opened as a folder', + requiresSshReconnect: false + }) + }) + + it('allows connected SSH repos', () => { + expect( + getRepoHeaderCreateState({ + repo: makeRepo({ connectionId: 'ssh-1' }), + label: 'remote', + sshStatus: 'connected' + }) + ).toMatchObject({ + disabled: false, + tooltip: 'Create worktree for remote', + requiresSshReconnect: false + }) + }) + + it('disables SSH repos while relay providers are unavailable', () => { + const blockedStatuses: (SshConnectionStatus | null)[] = [ + null, + 'disconnected', + 'reconnecting', + 'error' + ] + + for (const sshStatus of blockedStatuses) { + expect( + getRepoHeaderCreateState({ + repo: makeRepo({ connectionId: 'ssh-1' }), + label: 'remote', + sshStatus + }) + ).toEqual({ + disabled: true, + tooltip: 'Reconnect SSH target before creating workspaces', + ariaLabel: 'Reconnect SSH target before creating workspaces for remote', + requiresSshReconnect: true + }) + } + }) +}) diff --git a/src/renderer/src/components/sidebar/repo-header-create-state.ts b/src/renderer/src/components/sidebar/repo-header-create-state.ts new file mode 100644 index 000000000..630f2c9d9 --- /dev/null +++ b/src/renderer/src/components/sidebar/repo-header-create-state.ts @@ -0,0 +1,46 @@ +import type { SshConnectionStatus } from '../../../../shared/ssh-types' +import type { Repo } from '../../../../shared/types' +import { isGitRepoKind } from '../../../../shared/repo-kind' +import { getSelectedRepoSshGate } from '../../lib/new-workspace-ssh-gate' + +export type RepoHeaderCreateState = { + disabled: boolean + tooltip: string + ariaLabel: string + requiresSshReconnect: boolean +} + +export function getRepoHeaderCreateState(input: { + repo: Repo + label: string + sshStatus: SshConnectionStatus | null +}): RepoHeaderCreateState { + if (!isGitRepoKind(input.repo)) { + return { + disabled: true, + tooltip: `${input.label} is opened as a folder`, + ariaLabel: `${input.label} is opened as a folder`, + requiresSshReconnect: false + } + } + + const sshGate = getSelectedRepoSshGate({ + connectionId: input.repo.connectionId, + status: input.repo.connectionId ? input.sshStatus : null + }) + if (sshGate.selectedRepoRequiresConnection) { + return { + disabled: true, + tooltip: 'Reconnect SSH target before creating workspaces', + ariaLabel: `Reconnect SSH target before creating workspaces for ${input.label}`, + requiresSshReconnect: true + } + } + + return { + disabled: false, + tooltip: `Create worktree for ${input.label}`, + ariaLabel: `Create worktree for ${input.label}`, + requiresSshReconnect: false + } +}