From 70db0041c331debaf3f92e0459a0d06fcaa83c01 Mon Sep 17 00:00:00 2001 From: wsp Date: Tue, 17 Nov 2026 16:57:43 +0800 Subject: [PATCH] fix(review): Align GitHub CLI login with PR host - Open the login terminal on the OpenBitFun host so GitHub CLI login shares credentials with the PR backend for SSH workspaces. - Validate the captured workspace root and SSH connection before creating the terminal. Keep older Desktop peers on the explicit host terminal path. Refs: #3958 --- src/apps/desktop/src/api/terminal_api.rs | 108 ++++++++++++++++-- .../generated/remote-surface-registry.json | 4 +- .../src/remote_surface/capabilities.rs | 10 ++ .../ReviewPlatformPanel.test.tsx | 25 ++-- .../review-platform/ReviewPlatformPanel.tsx | 31 ++--- .../api/generated/remoteSurface.ts | 4 +- .../peer-device/PeerConnectionManager.ts | 3 + src/web-ui/src/locales/en-US/common.json | 1 + src/web-ui/src/locales/zh-CN/common.json | 1 + src/web-ui/src/locales/zh-TW/common.json | 1 + .../createManualTerminalSession.test.ts | 34 +++++- .../services/createManualTerminalSession.ts | 31 +++-- .../terminal/services/TerminalService.test.ts | 38 ++++++ .../terminal/services/TerminalService.ts | 21 +++- .../src/tools/terminal/types/session.ts | 9 +- 15 files changed, 274 insertions(+), 47 deletions(-) diff --git a/src/apps/desktop/src/api/terminal_api.rs b/src/apps/desktop/src/api/terminal_api.rs index c50b2b9cc5..e3cd98cde2 100644 --- a/src/apps/desktop/src/api/terminal_api.rs +++ b/src/apps/desktop/src/api/terminal_api.rs @@ -2,7 +2,7 @@ use log::{error, warn}; use serde::{Deserialize, Serialize}; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::Arc; use tauri::{AppHandle, Emitter, State}; use tokio::sync::Mutex; @@ -104,18 +104,27 @@ impl Default for TerminalState { } } +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HostTerminalWorkspaceTarget { + pub root_path: String, + pub connection_id: Option, +} + #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CreateSessionRequest { #[serde(default)] pub workspace_id: Option, + /// A workspace snapshot to validate before opening a PTY on the host itself. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub host_workspace_target: Option, pub session_id: Option, pub name: Option, pub shell_type: Option, pub shell_id: Option, pub working_directory: Option, - /// When set, open a remote PTY on this SSH connection without requiring a - /// registered remote workspace (used by Relay Deploy wizard). + /// Explicit SSH connection without a workspace, or an empty string for the host. pub connection_id: Option, pub env: Option>, pub cols: Option, @@ -550,6 +559,32 @@ async fn spawn_remote_pty_session( Ok(response) } +fn resolve_terminal_workspace_target( + request: &mut CreateSessionRequest, + root_path: &Path, + connection_id: Option<&str>, +) -> Result<(), String> { + if let Some(expected) = &request.host_workspace_target { + if expected.root_path != root_path.to_string_lossy() + || expected.connection_id.as_deref() != connection_id + { + return Err("Terminal owner workspace changed".into()); + } + request.connection_id = Some(String::new()); + if connection_id.is_some() { + // The workspace's directory is on SSH. Use the host shell's default directory. + request.working_directory = None; + return Ok(()); + } + } else { + request.connection_id = Some(connection_id.unwrap_or_default().to_owned()); + } + request + .working_directory + .get_or_insert_with(|| root_path.to_string_lossy().into_owned()); + Ok(()) +} + #[tauri::command] pub async fn terminal_create( _app: AppHandle, @@ -564,18 +599,17 @@ pub async fn terminal_create( .require_workspace(id) .await .map_err(|e| e.to_string())?; - request.connection_id = match workspace.workspace_kind { + let connection_id = match workspace.workspace_kind { openbitfun_core::service::workspace::WorkspaceKind::Remote => Some( workspace .remote_ssh_connection_id() - .ok_or("Remote workspace is missing its saved SSH connection ID")? - .to_owned(), + .ok_or("Remote workspace is missing its saved SSH connection ID")?, ), - _ => Some(String::new()), + _ => None, }; - request - .working_directory - .get_or_insert_with(|| workspace.root_path.to_string_lossy().into_owned()); + resolve_terminal_workspace_target(&mut request, &workspace.root_path, connection_id)?; + } else if request.host_workspace_target.is_some() { + return Err("Host terminal workspace ID is required".into()); } else if request.connection_id.is_none() { // Upgrade-only pre-ID terminal payload. Never infer a target from cwd. let service = openbitfun_core::service::workspace::get_global_workspace_service() @@ -1098,7 +1132,59 @@ pub fn start_terminal_event_loop(terminal_state: TerminalState, app_handle: AppH #[cfg(test)] mod tests { - use super::remote_terminal_signal_bytes; + use super::{ + remote_terminal_signal_bytes, resolve_terminal_workspace_target, CreateSessionRequest, + }; + use serde_json::json; + use std::path::Path; + + #[test] + fn terminal_workspace_target_rejects_rebound_connection_or_root() { + for (root, connection) in [ + ("/repo", Some("ssh-b")), + ("/new-repo", Some("ssh-a")), + ("/repo", None), + ] { + let mut request: CreateSessionRequest = serde_json::from_value(json!({ + "workspaceId": "workspace-1", + "hostWorkspaceTarget": { "rootPath": "/repo", "connectionId": "ssh-a" }, + })) + .unwrap(); + let error = + resolve_terminal_workspace_target(&mut request, Path::new(root), connection) + .unwrap_err(); + assert_eq!(error, "Terminal owner workspace changed"); + } + } + + #[test] + fn ssh_workspace_auth_terminal_uses_the_host_and_discards_the_remote_directory() { + let mut request: CreateSessionRequest = serde_json::from_value(json!({ + "workspaceId": "workspace-1", + "hostWorkspaceTarget": { "rootPath": "/repo", "connectionId": "ssh-a" }, + "workingDirectory": "/repo/src", + })) + .unwrap(); + resolve_terminal_workspace_target(&mut request, Path::new("/repo"), Some("ssh-a")).unwrap(); + assert_eq!(request.connection_id.as_deref(), Some("")); + assert!(request.working_directory.is_none()); + assert_eq!(request.workspace_id.as_deref(), Some("workspace-1")); + } + + #[test] + fn legacy_workspace_terminal_still_routes_over_ssh() { + let mut request: CreateSessionRequest = serde_json::from_value(json!({ + "workspaceId": "workspace-1", + })) + .unwrap(); + assert!(serde_json::to_value(&request) + .unwrap() + .get("hostWorkspaceTarget") + .is_none()); + resolve_terminal_workspace_target(&mut request, Path::new("/repo"), Some("ssh-a")).unwrap(); + assert_eq!(request.connection_id.as_deref(), Some("ssh-a")); + assert_eq!(request.working_directory.as_deref(), Some("/repo")); + } #[test] fn maps_supported_remote_terminal_signals_to_control_bytes() { diff --git a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json index 8dba063c7c..4311a732aa 100644 --- a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json +++ b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "digest": "fnv1a64:c080137dac4b6d2e", + "digest": "fnv1a64:8732d7ca210f7cf2", "retiredCommandPrefixes": [ { "prefix": "lsp_", @@ -47,6 +47,7 @@ "cancel_tool", "tool_catalog", "review_platform_v1", + "host_terminal_workspace_v1", "chat_mcp_catalog_v1", "workspace_icon_v1", "workspace_id_references_v1", @@ -101,6 +102,7 @@ "cancel_tool", "tool_catalog", "review_platform_v1", + "host_terminal_workspace_v1", "chat_mcp_catalog_v1", "workspace_icon_v1", "workspace_id_references_v1", diff --git a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs index c71ae3b80d..980052416c 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs @@ -99,6 +99,8 @@ pub enum PeerHostCapability { ToolCatalog, /// Workspace-backed pull request context and detail pages are implemented. ReviewPlatformV1, + /// `terminal_create` can validate an owning workspace and pin the PTY to the host. + HostTerminalWorkspaceV1, /// Mode/workspace-scoped `get_chat_mcp_catalog` is implemented. ChatMcpCatalogV1, /// Workspace references can carry the owning host's persisted ID. @@ -173,6 +175,7 @@ impl PeerHostCapability { Self::CancelTool, Self::ToolCatalog, Self::ReviewPlatformV1, + Self::HostTerminalWorkspaceV1, Self::ChatMcpCatalogV1, Self::WorkspaceIconV1, Self::WorkspaceIdReferencesV1, @@ -230,6 +233,7 @@ impl PeerHostCapability { Self::CancelTool => "cancel_tool", Self::ToolCatalog => "tool_catalog", Self::ReviewPlatformV1 => "review_platform_v1", + Self::HostTerminalWorkspaceV1 => "host_terminal_workspace_v1", Self::ChatMcpCatalogV1 => "chat_mcp_catalog_v1", Self::WorkspaceIconV1 => "workspace_icon_v1", Self::WorkspaceIdReferencesV1 => "workspace_id_references_v1", @@ -294,6 +298,7 @@ const DESKTOP_CAPABILITIES: &[PeerHostCapability] = &[ PeerHostCapability::CancelTool, PeerHostCapability::ToolCatalog, PeerHostCapability::ReviewPlatformV1, + PeerHostCapability::HostTerminalWorkspaceV1, PeerHostCapability::ChatMcpCatalogV1, PeerHostCapability::WorkspaceIconV1, PeerHostCapability::WorkspaceIdReferencesV1, @@ -458,10 +463,15 @@ mod tests { assert!(!cli.contains_key("product_control_presentation_v1")); assert!(!cli.contains_key("whole_session_copy_v1")); assert!(!cli.contains_key("review_platform_v1")); + assert!(!cli.contains_key("host_terminal_workspace_v1")); assert_eq!( capability_map(PeerHostKind::Desktop).get("review_platform_v1"), Some(&Value::Bool(true)) ); + assert_eq!( + capability_map(PeerHostKind::Desktop).get("host_terminal_workspace_v1"), + Some(&Value::Bool(true)) + ); assert_eq!( capability_map(PeerHostKind::Desktop).get("whole_session_copy_v1"), Some(&Value::Bool(true)) diff --git a/src/web-ui/src/app/components/panels/review-platform/ReviewPlatformPanel.test.tsx b/src/web-ui/src/app/components/panels/review-platform/ReviewPlatformPanel.test.tsx index c2a0369941..160f22fe44 100644 --- a/src/web-ui/src/app/components/panels/review-platform/ReviewPlatformPanel.test.tsx +++ b/src/web-ui/src/app/components/panels/review-platform/ReviewPlatformPanel.test.tsx @@ -540,12 +540,16 @@ describe('Gitee panel state and asynchronous request ordering', () => { mocks.state.activeSessionId = 'chat'; }); - it('copies the login command and opens the returned session in the owning workspace', async () => { + it('opens a host login terminal owned by the SSH workspace', async () => { await mountAuthPanel(); expect(authDialogState()).not.toBeNull(); await clickOpenTerminal(); expect(mocks.setClipboard).toHaveBeenCalledExactlyOnceWith('gh auth login --hostname github.com'); - expect(terminal.create).toHaveBeenCalledExactlyOnceWith({ workspaceId: owningId, workspacePath: owningPath }); + expect(terminal.create).toHaveBeenCalledExactlyOnceWith({ + workspaceId: owningId, + workspacePath: undefined, + hostWorkspaceTarget: { rootPath: owningPath, connectionId: 'ssh-owner' }, + }); expect(terminal.open).toHaveBeenCalledExactlyOnceWith({ sessionId: 'terminal-42', sessionName: 'Shell 7', scope: { surfaceId: 'local', workspaceId: owningId, workspacePath: owningPath, remoteConnectionId: 'ssh-owner' }, @@ -589,11 +593,16 @@ describe('Gitee panel state and asynchronous request ordering', () => { }); it('starts at the owner root when the panel path belongs to another workspace', async () => { + workspaces.opened.set(owningId, { rootPath: owningPath, workspaceKind: 'normal' }); await mountAuthPanel('/canvas-fallback-workspace'); await clickOpenTerminal(); - expect(terminal.create).toHaveBeenCalledExactlyOnceWith({ workspaceId: owningId, workspacePath: owningPath }); + expect(terminal.create).toHaveBeenCalledExactlyOnceWith({ + workspaceId: owningId, + workspacePath: owningPath, + hostWorkspaceTarget: { rootPath: owningPath }, + }); expect(terminal.open).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ - scope: { surfaceId: 'local', workspaceId: owningId, workspacePath: owningPath, remoteConnectionId: 'ssh-owner' }, + scope: { surfaceId: 'local', workspaceId: owningId, workspacePath: owningPath }, })); expect(mocks.notify.success).toHaveBeenCalledOnce(); }); @@ -602,7 +611,11 @@ describe('Gitee panel state and asynchronous request ordering', () => { workspaces.opened.set(owningId, { rootPath: owningPath, workspaceKind: 'normal' }); await mountAuthPanel(`${owningPath}/src`); await clickOpenTerminal(); - expect(terminal.create).toHaveBeenCalledExactlyOnceWith({ workspaceId: owningId, workspacePath: `${owningPath}/src` }); + expect(terminal.create).toHaveBeenCalledExactlyOnceWith({ + workspaceId: owningId, + workspacePath: `${owningPath}/src`, + hostWorkspaceTarget: { rootPath: owningPath }, + }); const { scope } = terminal.open.mock.calls[0][0] as { scope: Record }; expect(scope).toEqual({ surfaceId: 'local', workspaceId: owningId, workspacePath: owningPath }); expect(scope).not.toHaveProperty('remoteConnectionId'); @@ -614,8 +627,6 @@ describe('Gitee panel state and asynchronous request ordering', () => { mocks.setClipboard.mockReturnValueOnce(clipboard.promise); await mountAuthPanel(); await clickOpenTerminal(); - // The panel is still current, so only the owner check can stop this; the - // service would otherwise create the PTY on the new connection. workspaces.opened.set(owningId, { rootPath: owningPath, workspaceKind: 'remote', connectionId: 'ssh-reconnected' }); await act(async () => clipboard.resolve()); expect(terminal.create).not.toHaveBeenCalled(); diff --git a/src/web-ui/src/app/components/panels/review-platform/ReviewPlatformPanel.tsx b/src/web-ui/src/app/components/panels/review-platform/ReviewPlatformPanel.tsx index d9cd0ca58a..86d1450ecd 100644 --- a/src/web-ui/src/app/components/panels/review-platform/ReviewPlatformPanel.tsx +++ b/src/web-ui/src/app/components/panels/review-platform/ReviewPlatformPanel.tsx @@ -317,7 +317,7 @@ function ownerWorkspaceRecord(workspaceId?: string) { ?? null; } -function resolveAuthTerminalOwner(surfaceId: DeviceSurfaceId, workspaceId: string): ContentResourceScope { +function resolveAuthTerminalOwner(surfaceId: DeviceSurfaceId, workspaceId: string) { const owner = ownerWorkspaceRecord(workspaceId); if (!owner) throw new Error('Terminal owner workspace is unavailable'); const remote = owner.workspaceKind === 'remote'; @@ -331,14 +331,13 @@ function resolveAuthTerminalOwner(surfaceId: DeviceSurfaceId, workspaceId: strin } /** - * A restored `review-platform` panel can carry the canvas fallback path rather - * than its owner's, so only a cwd inside the owner root is kept as the terminal - * directory; anything else starts at the root instead of another workspace. + * Local owners can keep a cwd inside their root. SSH owners use the host shell's + * default directory because their repository path belongs to another machine. */ -function ownerTerminalDirectory(scope: ContentResourceScope, workspacePath?: string): string { - const root = scope.workspacePath ?? ''; - const remote = Boolean(scope.remoteConnectionId); - return workspacePath && isTerminalPathInside(workspacePath, root, remote) ? workspacePath : root; +function ownerTerminalDirectory(scope: ReturnType, workspacePath?: string): string | undefined { + if (scope.remoteConnectionId) return undefined; + const root = scope.workspacePath; + return workspacePath && isTerminalPathInside(workspacePath, root) ? workspacePath : root; } /** A created PTY stays with its host; this only decides whether its tab opens here. */ @@ -1937,12 +1936,16 @@ function ReviewPlatformContent({ const workingDirectory = ownerTerminalDirectory(ownerScope, workspacePath); await systemAPI.setClipboard(command); if (!isPanelCurrent()) return; - // The clipboard write is already an await: an owner that moved to another - // connection meanwhile must fail before the PTY is created on the new one. assertAuthTerminalOwner(ownerScope); - // The host owns the PTY, so it is created once here and never killed when - // this panel goes away; only opening its tab belongs to this panel. - const session = await createManualTerminalSession({ workspaceId, workspacePath: workingDirectory }); + // The review backend runs gh on the OpenBitFun host, even when Git runs over SSH. + const session = await createManualTerminalSession({ + workspaceId, + workspacePath: workingDirectory, + hostWorkspaceTarget: { + rootPath: ownerScope.workspacePath, + connectionId: ownerScope.remoteConnectionId, + }, + }); if (!isPanelCurrent()) return; // Creation awaits again, so the owner is re-checked before its PTY is shown. assertAuthTerminalOwner(ownerScope); @@ -2742,7 +2745,7 @@ function ReviewPlatformContent({ } /> {selectedRemote?.platform === 'github' ? ( - +
{`gh auth login --hostname ${selectedRemote.host}`}
{authError && }
diff --git a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts index 927f57496c..66cd38780f 100644 --- a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts +++ b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate-interactive-capabilities.mjs; do not edit. // Source: openbitfun_product_domains::remote_surface (Product Operation Registry). -export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:c080137dac4b6d2e" as const; +export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:8732d7ca210f7cf2" as const; /** * Registered Tauri commands the Peer Device controller keeps on the controller @@ -202,6 +202,7 @@ export const PEER_HOST_CAPABILITY_IDS = [ "cancel_tool", "tool_catalog", "review_platform_v1", + "host_terminal_workspace_v1", "chat_mcp_catalog_v1", "workspace_icon_v1", "workspace_id_references_v1", @@ -263,6 +264,7 @@ export const PEER_HOST_ADVERTISED_CAPABILITIES: Readonly< "cancel_tool", "tool_catalog", "review_platform_v1", + "host_terminal_workspace_v1", "chat_mcp_catalog_v1", "workspace_icon_v1", "workspace_id_references_v1", diff --git a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts index 164fcf7050..448c257b23 100644 --- a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts +++ b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts @@ -116,6 +116,7 @@ export interface PeerHostCapabilities { readonly toolCatalog: boolean | null; /** Missing on older hosts: Desktop implements PR details, CLI does not. */ readonly reviewPlatformV1?: boolean | null; + readonly hostTerminalWorkspaceV1?: boolean; /** Scoped MCP choices must be explicitly advertised by the host. */ readonly chatMcpCatalogV1?: boolean; readonly sessionReferenceBrowseV1?: boolean; @@ -268,6 +269,7 @@ const NO_CAPABILITIES: PeerHostCapabilities = { cancelTool: null, toolCatalog: null, reviewPlatformV1: null, + hostTerminalWorkspaceV1: false, chatMcpCatalogV1: false, sessionReferenceBrowseV1: false, workspaceIconV1: false, @@ -740,6 +742,7 @@ export class PeerConnectionManager { cancelTool, toolCatalog, reviewPlatformV1: caps?.review_platform_v1 === undefined ? null : caps.review_platform_v1 === true, + hostTerminalWorkspaceV1: caps?.host_terminal_workspace_v1 === true, chatMcpCatalogV1: caps?.chat_mcp_catalog_v1 === true, sessionReferenceBrowseV1: caps?.session_reference_browse_v1 === true, workspaceIconV1: caps?.workspace_icon_v1 === true, diff --git a/src/web-ui/src/locales/en-US/common.json b/src/web-ui/src/locales/en-US/common.json index 683373bdf5..ddea38852a 100644 --- a/src/web-ui/src/locales/en-US/common.json +++ b/src/web-ui/src/locales/en-US/common.json @@ -2189,6 +2189,7 @@ "copyAuthFailed": "Failed to copy GitHub CLI login command.", "unresolvedPullRequest": "This pull request could not be resolved from the remotes of the current workspace.", "ghAuthRequired": "GitHub CLI authentication required", + "ghAuthHostTerminal": "Run this command in the OpenBitFun host terminal, finish signing in, then retry.", "tokenRequiredTitle": "Token required", "tokenScopeTitle": "Token permissions required", "tokenUpdateTitle": "Token update required", diff --git a/src/web-ui/src/locales/zh-CN/common.json b/src/web-ui/src/locales/zh-CN/common.json index 7b48e34488..dfa95e3cc9 100644 --- a/src/web-ui/src/locales/zh-CN/common.json +++ b/src/web-ui/src/locales/zh-CN/common.json @@ -2189,6 +2189,7 @@ "copyAuthFailed": "复制 GitHub CLI 登录命令失败。", "unresolvedPullRequest": "无法从当前工作区的远程仓库中找到此拉取请求。", "ghAuthRequired": "需要 GitHub CLI 认证", + "ghAuthHostTerminal": "请在运行 OpenBitFun 的主机终端中执行此命令,完成登录后重试。", "tokenRequiredTitle": "需要令牌", "tokenScopeTitle": "需要令牌权限", "tokenUpdateTitle": "需要更新令牌", diff --git a/src/web-ui/src/locales/zh-TW/common.json b/src/web-ui/src/locales/zh-TW/common.json index 63182e411b..fb41501ae4 100644 --- a/src/web-ui/src/locales/zh-TW/common.json +++ b/src/web-ui/src/locales/zh-TW/common.json @@ -2189,6 +2189,7 @@ "copyAuthFailed": "複製 GitHub CLI 登入命令失敗。", "unresolvedPullRequest": "無法從目前工作區的遠端儲存庫中找到此提取請求。", "ghAuthRequired": "需要 GitHub CLI 驗證", + "ghAuthHostTerminal": "請在執行 OpenBitFun 的主機終端中執行此命令,完成登入後再試。", "tokenRequiredTitle": "需要權杖", "tokenScopeTitle": "需要權杖權限", "tokenUpdateTitle": "需要更新權杖", diff --git a/src/web-ui/src/shared/services/createManualTerminalSession.test.ts b/src/web-ui/src/shared/services/createManualTerminalSession.test.ts index 3dac0e2984..1044554bcc 100644 --- a/src/web-ui/src/shared/services/createManualTerminalSession.test.ts +++ b/src/web-ui/src/shared/services/createManualTerminalSession.test.ts @@ -6,12 +6,13 @@ const mocks = vi.hoisted(() => ({ getAvailableShells: vi.fn(), createSession: vi.fn(), getConfig: vi.fn(), + remoteWorkspace: { id: 'workspace-remote', workspaceKind: 'remote', connectionId: 'ssh-1', rootPath: '/ssh/repo' }, })); vi.mock('@/infrastructure/services/business/workspaceManager', () => ({ workspaceManager: { getState: () => ({ openedWorkspaces: new Map([ ['workspace-main', { id: 'workspace-main', workspaceKind: 'normal', connectionId: 'dirty-legacy-hint' }], - ['workspace-remote', { id: 'workspace-remote', workspaceKind: 'remote', connectionId: 'ssh-1' }], + ['workspace-remote', mocks.remoteWorkspace], ]), recentWorkspaces: [], }) } })); @@ -33,6 +34,7 @@ import { createManualTerminalSession } from './createManualTerminalSession'; describe('createManualTerminalSession', () => { beforeEach(() => { vi.clearAllMocks(); + mocks.remoteWorkspace.connectionId = 'ssh-1'; mocks.connect.mockResolvedValue(undefined); mocks.getConfig.mockResolvedValue({ default_shell: 'C:\\Program Files\\Git\\bin\\bash.exe' }); mocks.getAvailableShells.mockResolvedValue([ @@ -80,6 +82,36 @@ describe('createManualTerminalSession', () => { }); }); + it('uses the host shell and omits the SSH working directory for a host terminal', async () => { + const hostWorkspaceTarget = { rootPath: '/ssh/repo', connectionId: 'ssh-1' }; + await createManualTerminalSession({ workspaceId: 'workspace-remote', workspacePath: '/ssh/repo', hostWorkspaceTarget }); + + expect(mocks.createSession).toHaveBeenCalledExactlyOnceWith({ + workspaceId: 'workspace-remote', + hostWorkspaceTarget, + workingDirectory: undefined, + name: 'Shell 2', + shellId: 'bash:c:/program files/git/bin/bash.exe', + shellType: 'Bash', + source: 'manual', + }); + }); + + it('does not dispatch PTY creation if the workspace rebinds while listing sessions', async () => { + const sessions = Promise.withResolvers<[]>(); + mocks.listSessions.mockReturnValueOnce(sessions.promise); + const creation = createManualTerminalSession({ + workspaceId: 'workspace-remote', + hostWorkspaceTarget: { rootPath: '/ssh/repo', connectionId: 'ssh-1' }, + }); + await vi.waitFor(() => expect(mocks.listSessions).toHaveBeenCalledOnce()); + mocks.remoteWorkspace.connectionId = 'ssh-2'; + sessions.resolve([]); + + await expect(creation).rejects.toThrow('Terminal owner workspace changed'); + expect(mocks.createSession).not.toHaveBeenCalled(); + }); + it('uses automatic shell selection when no default shell is configured', async () => { mocks.getConfig.mockResolvedValue({ default_shell: '' }); diff --git a/src/web-ui/src/shared/services/createManualTerminalSession.ts b/src/web-ui/src/shared/services/createManualTerminalSession.ts index 51ade02943..a4766aa808 100644 --- a/src/web-ui/src/shared/services/createManualTerminalSession.ts +++ b/src/web-ui/src/shared/services/createManualTerminalSession.ts @@ -2,12 +2,13 @@ import { workspaceManager } from '@/infrastructure/services/business/workspaceMa import { configManager } from '@/infrastructure/config/services/ConfigManager'; import type { TerminalConfig } from '@/infrastructure/config/types'; import { getTerminalService } from '@/tools/terminal/services/TerminalService'; -import type { CreateSessionRequest, SessionResponse } from '@/tools/terminal/types/session'; +import type { CreateSessionRequest, HostTerminalWorkspaceTarget, SessionResponse } from '@/tools/terminal/types/session'; import { getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; export interface CreateManualTerminalSessionOptions { workspaceId: string; workspacePath?: string; + hostWorkspaceTarget?: HostTerminalWorkspaceTarget; shellType?: string; shellId?: string; name?: string; @@ -45,25 +46,39 @@ async function resolveDefaultShellSelection( export async function createManualTerminalSession( options: CreateManualTerminalSessionOptions, ): Promise { - const state = workspaceManager.getState(); - const workspace = state.openedWorkspaces.get(options.workspaceId) - || state.recentWorkspaces.find(record => record.id === options.workspaceId); - if (!workspace) throw new Error('Terminal workspace ID is unavailable'); + const { workspaceId, hostWorkspaceTarget } = options; + const requireWorkspace = () => { + const state = workspaceManager.getState(); + const workspace = state.openedWorkspaces.get(workspaceId) + ?? state.recentWorkspaces.find(record => record.id === workspaceId); + if (!workspace) throw new Error('Terminal workspace ID is unavailable'); + if (hostWorkspaceTarget && (workspace.rootPath !== hostWorkspaceTarget.rootPath + || (workspace.workspaceKind === 'remote' + ? !workspace.connectionId || workspace.connectionId !== hostWorkspaceTarget.connectionId + : hostWorkspaceTarget.connectionId !== undefined))) { + throw new Error('Terminal owner workspace changed'); + } + return workspace; + }; + const workspace = requireWorkspace(); const service = getTerminalService(); const scope = getActiveSurfaceScope(); await service.connect(); scope.assertCurrent('create manual terminal'); + const usesSsh = !hostWorkspaceTarget && workspace.workspaceKind === 'remote'; const [sessions, shellSelection] = await Promise.all([ service.listSessions(), - workspace.workspaceKind === 'remote' ? Promise.resolve({}) : resolveDefaultShellSelection(service), + usesSsh ? Promise.resolve({}) : resolveDefaultShellSelection(service), ]); scope.assertCurrent('create manual terminal'); + if (hostWorkspaceTarget) requireWorkspace(); const manualCount = sessions.filter((session) => session.source === 'manual').length; return service.createSession({ - workspaceId: options.workspaceId, - workingDirectory: options.workspacePath, + workspaceId, + ...(hostWorkspaceTarget && { hostWorkspaceTarget }), + workingDirectory: hostWorkspaceTarget?.connectionId ? undefined : options.workspacePath, name: options.name ?? `Shell ${manualCount + 1}`, sessionId: options.sessionId, ...(options.shellId ? { shellId: options.shellId, shellType: options.shellType } diff --git a/src/web-ui/src/tools/terminal/services/TerminalService.test.ts b/src/web-ui/src/tools/terminal/services/TerminalService.test.ts index 03cc7b70ec..3b7582f2cf 100644 --- a/src/web-ui/src/tools/terminal/services/TerminalService.test.ts +++ b/src/web-ui/src/tools/terminal/services/TerminalService.test.ts @@ -142,6 +142,44 @@ describe('TerminalService device surface switching', () => { expect(invokeMock).not.toHaveBeenCalled(); }); + describe('host terminal for a workspace', () => { + const request = { + workspaceId: 'workspace-1', + hostWorkspaceTarget: { rootPath: '/ssh/repo', connectionId: 'ssh-1' }, + workingDirectory: '/ssh/repo', + }; + + it('sends the expected workspace to a peer that supports guarded host terminals', async () => { + activateSurface('peer-host'); + hostMock.capabilities = { hostKind: 'desktop', hostTerminalWorkspaceV1: true }; + invokeMock.mockResolvedValueOnce({ id: 'pty-1', workspaceId: 'workspace-1' }); + + await freshTerminalService().createSession(request); + + expect(invokeMock).toHaveBeenCalledExactlyOnceWith('terminal_create', { request }); + }); + + it('uses the explicit host route on older desktop peers', async () => { + activateSurface('peer-host'); + hostMock.capabilities = { hostKind: 'desktop', workspaceIdReferencesV1: true }; + invokeMock.mockResolvedValueOnce({ id: 'pty-1', cwd: '/home/host' }); + + const session = await freshTerminalService().createSession(request); + + expect(invokeMock).toHaveBeenCalledExactlyOnceWith('terminal_create', { request: { connectionId: '' } }); + expect(session.workspaceId).toBe('workspace-1'); + expect(session.initialCwd).toBe('/home/host'); + }); + + it('refuses the desktop-only legacy request on CLI peers', async () => { + activateSurface('peer-host'); + hostMock.capabilities = { hostKind: 'cli' }; + + await expect(freshTerminalService().createSession(request)).rejects.toThrow('unavailable on this device'); + expect(invokeMock).not.toHaveBeenCalled(); + }); + }); + describe('terminal cursor replay', () => { async function connectToHost(capabilities: Record | null = { terminalCursorReplayV1: true }): Promise { hostMock.capabilities = capabilities; diff --git a/src/web-ui/src/tools/terminal/services/TerminalService.ts b/src/web-ui/src/tools/terminal/services/TerminalService.ts index 57447b6433..5615f81581 100644 --- a/src/web-ui/src/tools/terminal/services/TerminalService.ts +++ b/src/web-ui/src/tools/terminal/services/TerminalService.ts @@ -11,6 +11,7 @@ import { createLogger } from '@/shared/utils/logger'; import { getActiveSurfaceScope, getActiveSurfaceId, + isLocalSurface, type SurfaceScope, } from '@/infrastructure/peer-device/deviceSurface'; import type { @@ -342,17 +343,31 @@ export class TerminalService { async createSession(request: CreateSessionRequest): Promise { const { surfaceId } = getActiveSurfaceScope(); + const { workspaceId, hostWorkspaceTarget, ...terminalOptions } = request; + const workingDirectory = hostWorkspaceTarget?.connectionId ? undefined : terminalOptions.workingDirectory; try { const session = await invokePrepared('terminal_create', async () => { - if (!request.workspaceId) return { request }; - const reference = await workspaceIdRequest(request.workspaceId, 'workspacePath'); + if (hostWorkspaceTarget) { + if (!workspaceId?.trim()) throw new Error('Host terminal workspace ID is required'); + if (isLocalSurface(surfaceId)) return { request }; + const capabilities = peerConnectionManager.get(surfaceId)?.getState().capabilities; + if (capabilities?.hostTerminalWorkspaceV1) return { request }; + if (capabilities?.hostKind !== 'desktop') { + throw new Error('Host terminals for workspaces are unavailable on this device'); + } + // Older Desktop hosts accept an explicit host target without a workspace ID. + // Including the ID could cause them to route the PTY to the workspace's SSH host. + return { request: { ...terminalOptions, workingDirectory, connectionId: '' } }; + } + if (!workspaceId) return { request }; + const reference = await workspaceIdRequest(workspaceId, 'workspacePath'); return 'workspaceId' in reference ? { request } : { request: { ...request, workspaceId: undefined, connectionId: reference.remoteConnectionId ?? '' } }; }); log.debug('Session created', { sessionId: session.id }); return this.projectSession(surfaceId, { - ...session, workspaceId: session.workspaceId || request.workspaceId, initialCwd: session.initialCwd || request.workingDirectory || session.cwd, + ...session, workspaceId: session.workspaceId || workspaceId, initialCwd: session.initialCwd || workingDirectory || session.cwd, }); } catch (error) { log.error('Failed to create session', error); diff --git a/src/web-ui/src/tools/terminal/types/session.ts b/src/web-ui/src/tools/terminal/types/session.ts index c775973337..6fb97eb11c 100644 --- a/src/web-ui/src/tools/terminal/types/session.ts +++ b/src/web-ui/src/tools/terminal/types/session.ts @@ -14,15 +14,22 @@ export type ShellType = | 'Fish' | 'Sh'; +export interface HostTerminalWorkspaceTarget { + rootPath: string; + connectionId?: string; +} + export interface CreateSessionRequest { workspaceId?: string; + /** Validate the workspace snapshot, then run the PTY on the OpenBitFun host. */ + hostWorkspaceTarget?: HostTerminalWorkspaceTarget; sessionId?: string; name?: string; shellType?: ShellType | string; /** Stable identifier for an exact discovered shell executable. */ shellId?: string; workingDirectory?: string; - /** Open a remote PTY on this SSH connection without a registered workspace. */ + /** Explicit SSH connection without a workspace, or an empty string for the host. */ connectionId?: string; env?: Record; cols?: number;