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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 97 additions & 11 deletions src/apps/desktop/src/api/terminal_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateSessionRequest {
#[serde(default)]
pub workspace_id: Option<String>,
/// 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<HostTerminalWorkspaceTarget>,
pub session_id: Option<String>,
pub name: Option<String>,
pub shell_type: Option<String>,
pub shell_id: Option<String>,
pub working_directory: Option<String>,
/// 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<String>,
pub env: Option<std::collections::HashMap<String, String>>,
pub cols: Option<u16>,
Expand Down Expand Up @@ -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,
Expand All @@ -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()
Expand Down Expand Up @@ -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() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"schemaVersion": 1,
"digest": "fnv1a64:c080137dac4b6d2e",
"digest": "fnv1a64:8732d7ca210f7cf2",
"retiredCommandPrefixes": [
{
"prefix": "lsp_",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -173,6 +175,7 @@ impl PeerHostCapability {
Self::CancelTool,
Self::ToolCatalog,
Self::ReviewPlatformV1,
Self::HostTerminalWorkspaceV1,
Self::ChatMcpCatalogV1,
Self::WorkspaceIconV1,
Self::WorkspaceIdReferencesV1,
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -294,6 +298,7 @@ const DESKTOP_CAPABILITIES: &[PeerHostCapability] = &[
PeerHostCapability::CancelTool,
PeerHostCapability::ToolCatalog,
PeerHostCapability::ReviewPlatformV1,
PeerHostCapability::HostTerminalWorkspaceV1,
PeerHostCapability::ChatMcpCatalogV1,
PeerHostCapability::WorkspaceIconV1,
PeerHostCapability::WorkspaceIdReferencesV1,
Expand Down Expand Up @@ -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))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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' },
Expand Down Expand Up @@ -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();
});
Expand All @@ -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<string, unknown> };
expect(scope).toEqual({ surfaceId: 'local', workspaceId: owningId, workspacePath: owningPath });
expect(scope).not.toHaveProperty('remoteConnectionId');
Expand All @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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<typeof resolveAuthTerminalOwner>, 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. */
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -2742,7 +2745,7 @@ function ReviewPlatformContent({
} />
{selectedRemote?.platform === 'github' ? (
<Stack gap="3">
<Alert role="status" message="Run this command in the integrated terminal, finish the GitHub CLI flow, then retry." />
<Alert role="status" message={t('common:reviewPlatform.messages.ghAuthHostTerminal')} />
<pre tabIndex={0} className="review-platform__ci-log-block">{`gh auth login --hostname ${selectedRemote.host}`}</pre>
{authError && <Alert tone="error" message={authError} />}
</Stack>
Expand Down
4 changes: 3 additions & 1 deletion src/web-ui/src/infrastructure/api/generated/remoteSurface.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -268,6 +269,7 @@ const NO_CAPABILITIES: PeerHostCapabilities = {
cancelTool: null,
toolCatalog: null,
reviewPlatformV1: null,
hostTerminalWorkspaceV1: false,
chatMcpCatalogV1: false,
sessionReferenceBrowseV1: false,
workspaceIconV1: false,
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading