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
14 changes: 12 additions & 2 deletions src/apps/cli/src/peer_host/commands/workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use std::path::PathBuf;

use openbitfun_core::service::workspace::{
remote_workspace_connection_conflict_message, RemoteConnectionRebind,
remote_workspace_connection_conflict_message, RemoteConnectionRebind, WorkspaceCreateOptions,
};
use openbitfun_runtime_ports::SessionStoragePathRequest;
use serde_json::{json, Value};
Expand Down Expand Up @@ -98,6 +98,8 @@ pub(crate) async fn open_workspace(state: &PeerHostState, args: &Value) -> Resul
}
// Explicit new-folder/old-protocol ingress. Existing-workspace selection uses ID.
let path = get_string(request, "path")?;
let create_local = optional_bool(request, "createLocal").unwrap_or(false);
let promote_if_opened = optional_bool(request, "promoteIfOpened").unwrap_or(create_local);
state
.compatibility
.ensure_workspace_runtime_ownership(&SessionStoragePathRequest {
Expand All @@ -108,7 +110,13 @@ pub(crate) async fn open_workspace(state: &PeerHostState, args: &Value) -> Resul
.map_err(|error| format!("Agent Runtime ownership is unavailable: {error}"))?;
let info = state
.workspace_service
.open_workspace(PathBuf::from(path))
.open_workspace_with_options(
PathBuf::from(path),
WorkspaceCreateOptions {
promote_if_opened,
..Default::default()
},
)
.await
.map_err(|e| format!("Failed to open workspace: {e}"))?;

Expand Down Expand Up @@ -137,6 +145,7 @@ pub(crate) async fn open_remote_workspace(
} else {
RemoteConnectionRebind::Reject
};
let promote_if_opened = optional_bool(request, "promoteIfOpened").unwrap_or(true);
let coordinator = openbitfun_core::agentic::coordination::get_global_coordinator()
.ok_or("Conversation coordinator is unavailable")?;
let info = coordinator
Expand All @@ -146,6 +155,7 @@ pub(crate) async fn open_remote_workspace(
&connection_id,
host.as_deref(),
rebind,
promote_if_opened,
)
.await
.map_err(|e| {
Expand Down
32 changes: 32 additions & 0 deletions src/apps/desktop/src/api/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,10 @@ pub struct OpenWorkspaceRequest {
pub remote_connection_id: Option<String>,
}

fn default_promote_if_opened() -> bool {
true
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OpenRemoteWorkspaceRequest {
Expand All @@ -394,6 +398,11 @@ pub struct OpenRemoteWorkspaceRequest {
/// connection to `connection_id`.
#[serde(default)]
pub rebind_connection: bool,
/// Move an already-opened record to the front of the project section.
/// Legacy callers omit this field and keep the explicit-open default (`true`);
/// background SSH restore sets `false` so reconnecting does not reorder rows.
#[serde(default = "default_promote_if_opened")]
pub promote_if_opened: bool,
}

#[derive(Debug, Deserialize, Default)]
Expand Down Expand Up @@ -1492,6 +1501,7 @@ pub async fn open_remote_workspace(
},
auto_set_current: true,
add_to_recent: true,
promote_if_opened: request.promote_if_opened,
workspace_kind: WorkspaceKind::Remote,
assistant_id: None,
display_name: Some(display_name),
Expand Down Expand Up @@ -1874,6 +1884,28 @@ mod assistant_workspace_delete_tests {
Ok(AssistantWorkspaceDirectoryPlan::RegistryEntryOnly)
);
}

#[test]
fn open_remote_workspace_request_defaults_promote_if_opened_for_legacy_payloads() {
let legacy: super::OpenRemoteWorkspaceRequest = serde_json::from_value(serde_json::json!({
"remotePath": "/srv/app",
"connectionId": "ssh-prod",
"connectionName": "Prod",
}))
.expect("legacy payload should deserialize");
assert!(legacy.promote_if_opened);
assert!(!legacy.rebind_connection);

let background_restore: super::OpenRemoteWorkspaceRequest =
serde_json::from_value(serde_json::json!({
"remotePath": "/srv/app",
"connectionId": "ssh-prod",
"connectionName": "Prod",
"promoteIfOpened": false,
}))
.expect("background restore payload should deserialize");
assert!(!background_restore.promote_if_opened);
}
}

#[tauri::command]
Expand Down
47 changes: 36 additions & 11 deletions src/apps/server/src/rpc_dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,17 +55,42 @@ pub async fn dispatch(
// ── Workspace ────────────────────────────────────────
"open_workspace" => {
let request = extract_request(&params)?;
let path: String = serde_json::from_value(
request
.get("path")
.cloned()
.ok_or_else(|| anyhow!("Missing path"))?,
)?;
let info = state
.workspace_service
.open_workspace(path.into())
.await
.map_err(|e| anyhow!("{}", e))?;
let create_local = request
.get("createLocal")
.and_then(|value| value.as_bool())
.unwrap_or(false);
let info = if let Some(workspace_id) = request
.get("workspaceId")
.and_then(|value| value.as_str())
.map(str::trim)
.filter(|value| !value.is_empty())
{
state
.workspace_service
.open_workspace_by_id(workspace_id)
.await
.map_err(|e| anyhow!("{}", e))?
} else {
let path: String = serde_json::from_value(
request
.get("path")
.cloned()
.ok_or_else(|| anyhow!("Missing path"))?,
)?;
if create_local {
state
.workspace_service
.open_workspace(path.into())
.await
.map_err(|e| anyhow!("{}", e))?
} else {
state
.workspace_service
.upgrade_legacy_workspace_open(path.into(), None, None)
.await
.map_err(|e| anyhow!("{}", e))?
}
};
*state.workspace_path.write().await = Some(info.root_path.clone());
Ok(serde_json::to_value(&info).unwrap_or_default())
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2640,6 +2640,7 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet
connection_id: &str,
ssh_host: Option<&str>,
remote_connection_rebind: RemoteConnectionRebind,
promote_if_opened: bool,
) -> OpenBitFunResult<WorkspaceInfo> {
let workspace = workspace_service
.prepare_remote_workspace(path, connection_id, ssh_host)
Expand All @@ -2653,7 +2654,11 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet
.and_then(|host| host.as_str()),
)?;
workspace_service
.open_known_remote_workspace_with_rebind(&workspace, remote_connection_rebind)
.open_known_remote_workspace_with_rebind(
&workspace,
remote_connection_rebind,
promote_if_opened,
)
.await
}

Expand Down
11 changes: 10 additions & 1 deletion src/crates/assembly/core/src/service/workspace/legacy_compat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,16 @@ impl WorkspaceService {
self.open_workspace_by_id(&known.id).await
};
}
match self.open_workspace(path).await {
match self
.open_workspace_with_options(
path,
super::service::WorkspaceCreateOptions {
promote_if_opened: false,
..Default::default()
},
)
.await
{
Ok(info) => Ok(info),
Err(error) => {
let message = error.to_string();
Expand Down
151 changes: 147 additions & 4 deletions src/crates/assembly/core/src/service/workspace/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,10 @@ pub struct WorkspaceOpenOptions {
pub scan_options: ScanOptions,
pub auto_set_current: bool,
pub add_to_recent: bool,
/// When `true` (default for explicit folder opens), opening an already-open
/// project workspace promotes it to the first project slot. Selection by ID,
/// legacy upgrade paths, and background SSH restore pass `false`.
pub promote_if_opened: bool,
pub workspace_kind: WorkspaceKind,
pub assistant_id: Option<String>,
pub display_name: Option<String>,
Expand All @@ -212,6 +216,7 @@ impl Default for WorkspaceOpenOptions {
scan_options: ScanOptions::default(),
auto_set_current: true,
add_to_recent: true,
promote_if_opened: true,
workspace_kind: WorkspaceKind::Normal,
assistant_id: None,
display_name: None,
Expand Down Expand Up @@ -1072,7 +1077,11 @@ impl WorkspaceManager {
}
}
if keep_opened {
self.ensure_workspace_open(&workspace_id);
if options.promote_if_opened {
self.promote_workspace_open(&workspace_id);
} else {
self.ensure_workspace_open(&workspace_id);
}
}
if options.auto_set_current {
self.set_current_workspace_with_recent_policy(
Expand Down Expand Up @@ -1504,8 +1513,9 @@ impl WorkspaceManager {
}

/// Ensures a workspace is in the opened list. A newly opened workspace goes
/// first; an already opened one keeps its place, so activating a workspace
/// never reorders the list users arrange (recency lives in the recent list).
/// to the front of its section (projects skip leading assistants); an
/// already opened one keeps its place, so activating a workspace never
/// reorders the list users arrange (recency lives in the recent list).
fn ensure_workspace_open(&mut self, workspace_id: &str) {
if self
.opened_workspace_ids
Expand All @@ -1514,8 +1524,68 @@ impl WorkspaceManager {
{
return;
}
let is_assistant = self
.workspaces
.get(workspace_id)
.is_some_and(|workspace| workspace.workspace_kind == WorkspaceKind::Assistant);
let insert_at = if is_assistant {
0
} else {
self.opened_workspace_ids
.iter()
.position(|id| {
self.workspaces.get(id).is_none_or(|workspace| {
workspace.workspace_kind != WorkspaceKind::Assistant
})
})
.unwrap_or(self.opened_workspace_ids.len())
};
self.opened_workspace_ids
.insert(0, workspace_id.to_string());
.insert(insert_at, workspace_id.to_string());
}

/// Ensures a workspace is open and, when it is a project workspace, places
/// it at the front of the project slots while leaving assistant slots in place.
fn promote_workspace_open(&mut self, workspace_id: &str) {
let is_assistant = self
.workspaces
.get(workspace_id)
.is_some_and(|workspace| workspace.workspace_kind == WorkspaceKind::Assistant);
if is_assistant
|| !self
.opened_workspace_ids
.iter()
.any(|id| id == workspace_id)
{
self.ensure_workspace_open(workspace_id);
return;
}

let workspaces = &self.workspaces;
let mut projects: Vec<String> = self
.opened_workspace_ids
.iter()
.filter(|id| {
id.as_str() != workspace_id
&& workspaces.get(*id).is_none_or(|workspace| {
workspace.workspace_kind != WorkspaceKind::Assistant
})
})
.cloned()
.collect();
projects.insert(0, workspace_id.to_string());

let mut project_iter = projects.into_iter();
for slot in &mut self.opened_workspace_ids {
let is_project_slot = workspaces
.get(slot.as_str())
.is_none_or(|workspace| workspace.workspace_kind != WorkspaceKind::Assistant);
if is_project_slot {
if let Some(next) = project_iter.next() {
*slot = next;
}
}
}
}

/// Returns manager statistics.
Expand Down Expand Up @@ -1949,4 +2019,77 @@ mod tests {
vec!["avatar".to_string()]
);
}

#[tokio::test]
async fn opening_project_promotes_to_first_project_slot_without_moving_assistants() {
use super::{
WorkspaceInfo, WorkspaceInfoRuntimeExt, WorkspaceKind, WorkspaceManager,
WorkspaceManagerConfig, WorkspaceOpenOptions,
};

let temp = tempfile::tempdir().expect("temp assistant dir");
let mut manager = WorkspaceManager::new(WorkspaceManagerConfig::default());
let assistant = WorkspaceInfo::new_without_worktree(
temp.path().to_path_buf(),
WorkspaceOpenOptions {
workspace_kind: WorkspaceKind::Assistant,
..Default::default()
},
)
.await
.unwrap();
manager
.workspaces
.insert(assistant.id.clone(), assistant.clone());
manager.opened_workspace_ids = vec![assistant.id.clone()];

let remote = |promote_if_opened: bool| WorkspaceOpenOptions {
workspace_kind: WorkspaceKind::Remote,
remote_connection_id: Some("ssh-dev".into()),
remote_ssh_host: Some("dev.example".into()),
promote_if_opened,
..Default::default()
};

let proj_a = manager
.open_workspace_with_options("/srv/proj-a".into(), remote(true))
.await
.unwrap();
let proj_b = manager
.open_workspace_with_options("/srv/proj-b".into(), remote(true))
.await
.unwrap();
assert_eq!(
manager.opened_workspace_ids,
vec![assistant.id.clone(), proj_b.id.clone(), proj_a.id.clone()]
);

// Background restore (`promote_if_opened: false`) preserves existing order.
manager
.open_workspace_with_options("/srv/proj-a".into(), remote(false))
.await
.unwrap();
assert_eq!(
manager.opened_workspace_ids,
vec![assistant.id.clone(), proj_b.id.clone(), proj_a.id.clone()]
);

// Explicit open (`promote_if_opened: true`) moves proj-a to the first project slot,
// keeping the leading assistant untouched.
manager
.open_workspace_with_options("/srv/proj-a".into(), remote(true))
.await
.unwrap();
assert_eq!(
manager.opened_workspace_ids,
vec![assistant.id.clone(), proj_a.id.clone(), proj_b.id.clone()]
);

// Ordinary activation keeps existing order.
manager.set_active_workspace(&proj_b.id).unwrap();
assert_eq!(
manager.opened_workspace_ids,
vec![assistant.id.clone(), proj_a.id.clone(), proj_b.id.clone()]
);
}
}
Loading
Loading