Skip to content

Commit 82b6dbd

Browse files
laststylebender14autofix-ci[bot]tusharmath
authored
feat(workspace): add workspace init command (tailcallhq#2413)
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> Co-authored-by: Tushar Mathur <tusharmath@gmail.com>
1 parent 4269d6a commit 82b6dbd

7 files changed

Lines changed: 150 additions & 3 deletions

File tree

‎crates/forge_api/src/api.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,9 @@ pub trait API: Sync + Send {
220220
/// Create new authentication credentials
221221
async fn create_auth_credentials(&self) -> Result<forge_domain::WorkspaceAuth>;
222222

223+
/// Initialize a new empty workspace
224+
async fn init_workspace(&self, path: PathBuf) -> Result<forge_domain::WorkspaceId>;
225+
223226
/// Migrate environment variable-based credentials to file-based
224227
/// credentials. This is a one-time migration that runs only if the
225228
/// credentials file doesn't exist.

‎crates/forge_api/src/forge_api.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,10 @@ impl<
370370
self.services.init_auth_credentials().await
371371
}
372372

373+
async fn init_workspace(&self, path: PathBuf) -> Result<forge_domain::WorkspaceId> {
374+
self.services.init_workspace(path).await
375+
}
376+
373377
async fn migrate_env_credentials(&self) -> Result<Option<forge_domain::MigrationResult>> {
374378
Ok(self.services.migrate_env_credentials().await?)
375379
}

‎crates/forge_app/src/services.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,9 @@ pub trait WorkspaceService: Send + Sync {
318318

319319
/// Create new authentication credentials
320320
async fn init_auth_credentials(&self) -> anyhow::Result<WorkspaceAuth>;
321+
322+
/// Initialize a workspace without syncing files
323+
async fn init_workspace(&self, path: PathBuf) -> anyhow::Result<WorkspaceId>;
321324
}
322325

323326
#[async_trait::async_trait]
@@ -1121,4 +1124,8 @@ impl<I: Services> WorkspaceService for I {
11211124
async fn init_auth_credentials(&self) -> anyhow::Result<WorkspaceAuth> {
11221125
self.workspace_service().init_auth_credentials().await
11231126
}
1127+
1128+
async fn init_workspace(&self, path: PathBuf) -> anyhow::Result<WorkspaceId> {
1129+
self.workspace_service().init_workspace(path).await
1130+
}
11241131
}

‎crates/forge_domain/src/error.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use derive_more::From;
44
use forge_json_repair::JsonRepairError;
55
use thiserror::Error;
66

7-
use crate::{AgentId, ConversationId, ProviderId};
7+
use crate::{AgentId, ConversationId, ProviderId, WorkspaceId};
88

99
// NOTE: Deriving From for error is a really bad idea. This is because you end
1010
// up converting errors incorrectly without much context. For eg: You don't want
@@ -96,6 +96,9 @@ pub enum Error {
9696
#[error("Workspace not found")]
9797
WorkspaceNotFound,
9898

99+
#[error("Workspace already initialized with id: {0}")]
100+
WorkspaceAlreadyInitialized(WorkspaceId),
101+
99102
#[error("No default provider set.")]
100103
NoDefaultProvider,
101104

‎crates/forge_main/src/cli.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,13 @@ pub enum WorkspaceCommand {
281281
#[arg(short, long)]
282282
porcelain: bool,
283283
},
284+
285+
/// Initialize an empty workspace for the provided directory
286+
Init {
287+
/// Path to the directory to initialize as a workspace
288+
#[arg(default_value = ".")]
289+
path: PathBuf,
290+
},
284291
}
285292

286293
/// Command group for listing resources.

‎crates/forge_main/src/ui.rs‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -639,6 +639,9 @@ impl<A: API + ConsoleWriter + 'static, F: Fn() -> A + Send + Sync> UI<A, F> {
639639
crate::cli::WorkspaceCommand::Status { path, porcelain } => {
640640
self.on_workspace_status(path, porcelain).await?;
641641
}
642+
crate::cli::WorkspaceCommand::Init { path } => {
643+
self.on_workspace_init(path).await?;
644+
}
642645
}
643646
return Ok(());
644647
}
@@ -3600,6 +3603,26 @@ impl<A: API + ConsoleWriter + 'static, F: Fn() -> A + Send + Sync> UI<A, F> {
36003603
Ok(())
36013604
}
36023605

3606+
/// Initialize workspace for a directory without syncing files
3607+
async fn on_workspace_init(&mut self, path: std::path::PathBuf) -> anyhow::Result<()> {
3608+
self.spinner.start(Some("Initializing workspace"))?;
3609+
3610+
let workspace_id = self.api.init_workspace(path.clone()).await?;
3611+
3612+
self.spinner.stop(None)?;
3613+
3614+
// Resolve and display the path
3615+
let canonical_path = path.canonicalize().unwrap_or_else(|_| path.clone());
3616+
3617+
self.writeln_title(
3618+
TitleFormat::info("Workspace initialized successfully")
3619+
.sub_title(format!("Path: {}", canonical_path.display()))
3620+
.sub_title(format!("Workspace ID: {}", workspace_id)),
3621+
)?;
3622+
3623+
Ok(())
3624+
}
3625+
36033626
/// Handle credential migration
36043627
async fn handle_migrate_credentials(&mut self) -> Result<()> {
36053628
// Perform the migration

‎crates/forge_services/src/context_engine.rs‎

Lines changed: 102 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ use forge_app::{
1111
WorkspaceStatus, compute_hash,
1212
};
1313
use forge_domain::{
14-
AuthCredential, AuthDetails, FileHash, FileNode, ProviderId, ProviderRepository, SyncProgress,
15-
UserId, WorkspaceId, WorkspaceIndexRepository, WorkspaceRepository,
14+
AuthCredential, AuthDetails, Error, FileHash, FileNode, ProviderId, ProviderRepository,
15+
SyncProgress, UserId, WorkspaceId, WorkspaceIndexRepository, WorkspaceRepository,
1616
};
1717
use forge_stream::MpscStream;
1818
use futures::future::join_all;
@@ -725,6 +725,43 @@ impl<
725725

726726
Ok(auth)
727727
}
728+
729+
async fn init_workspace(&self, path: PathBuf) -> Result<WorkspaceId> {
730+
let (token, user_id) = self.get_workspace_credentials().await?;
731+
let path = path
732+
.canonicalize()
733+
.with_context(|| format!("Failed to resolve path: {}", path.display()))?;
734+
735+
// Find workspace by exact match or ancestor
736+
let workspace = self.find_workspace_by_path(path.clone(), &user_id).await?;
737+
738+
// Check if workspace already exists
739+
if let Some(workspace) = workspace {
740+
if workspace.user_id == user_id {
741+
// Workspace already exists for this user
742+
return Err(Error::WorkspaceAlreadyInitialized(workspace.workspace_id).into());
743+
} else {
744+
// Found workspace but different user - delete old one
745+
if let Err(e) = self.infra.delete(&workspace.workspace_id).await {
746+
warn!(error = %e, "Failed to delete old workspace entry from local database");
747+
}
748+
}
749+
}
750+
751+
// Create new workspace on server
752+
let workspace_id = self
753+
.with_retry(|| self.infra.create_workspace(&path, &token))
754+
.await
755+
.context("Failed to create workspace on server")?;
756+
757+
// Save workspace in database
758+
self.infra
759+
.upsert(&workspace_id, &user_id, &path)
760+
.await
761+
.context("Failed to save workspace")?;
762+
763+
Ok(workspace_id)
764+
}
728765
}
729766

730767
#[cfg(test)]
@@ -1552,6 +1589,69 @@ mod tests {
15521589
);
15531590
}
15541591

1592+
#[tokio::test]
1593+
async fn test_init_workspace_creates_new_workspace() {
1594+
let mock = MockInfra {
1595+
files: [("src/main.rs", "fn main() {}")]
1596+
.iter()
1597+
.map(|(p, c)| (p.to_string(), c.to_string()))
1598+
.collect(),
1599+
workspace: None, // No workspace yet
1600+
ancestor_workspace: None,
1601+
authenticated: true,
1602+
..Default::default()
1603+
};
1604+
1605+
let service = ForgeWorkspaceService::new(Arc::new(mock.clone()));
1606+
1607+
// Initialize workspace without syncing
1608+
let workspace_id = service
1609+
.init_workspace(std::env::current_dir().unwrap())
1610+
.await
1611+
.unwrap();
1612+
1613+
// Verify we got a valid workspace ID
1614+
assert!(!workspace_id.to_string().is_empty());
1615+
}
1616+
1617+
#[tokio::test]
1618+
async fn test_init_workspace_reuses_existing_workspace() {
1619+
let current_dir = std::env::current_dir().unwrap();
1620+
let user_id = UserId::generate();
1621+
let existing_workspace_id = WorkspaceId::generate();
1622+
1623+
let existing_workspace = Workspace {
1624+
workspace_id: existing_workspace_id.clone(),
1625+
user_id: user_id.clone(),
1626+
path: current_dir.clone(),
1627+
created_at: chrono::Utc::now(),
1628+
updated_at: None,
1629+
};
1630+
1631+
let mock = MockInfra {
1632+
files: [("src/main.rs", "fn main() {}")]
1633+
.iter()
1634+
.map(|(p, c)| (p.to_string(), c.to_string()))
1635+
.collect(),
1636+
workspace: Some(existing_workspace),
1637+
ancestor_workspace: None,
1638+
authenticated: true,
1639+
..Default::default()
1640+
};
1641+
1642+
let service = ForgeWorkspaceService::new(Arc::new(mock.clone()));
1643+
1644+
// Initialize workspace - should reuse existing
1645+
let result = service.init_workspace(current_dir).await;
1646+
assert!(result.is_err());
1647+
let err = result.unwrap_err();
1648+
let domain_error = err.downcast_ref::<Error>();
1649+
assert!(matches!(
1650+
domain_error,
1651+
Some(Error::WorkspaceAlreadyInitialized(id)) if id == &existing_workspace_id
1652+
));
1653+
}
1654+
15551655
#[tokio::test]
15561656
async fn test_sync_prefers_exact_match_over_ancestor() {
15571657
// Use current directory as exact match

0 commit comments

Comments
 (0)