refactor(workspace): migrate from per-folder windows to single-window workspace

Replace the legacy folder + welcome routes with a unified /workspace route
that hosts all folders, conversations, tabs, and terminals in one window.

- Persist opened tabs to the database (opened_tabs entity + migration)
  so tab layout survives restarts and deep-link bootstrap restores state
- Replace FolderContext shim with AppWorkspaceProvider, ActiveFolderProvider,
  and TabProvider; expose both opened (folders) and full DB (allFolders)
  listings via list_all_folder_details
- Return conversations across all non-deleted folders from list_all when
  no folder filter is given, so the sidebar can show every folder's history
- Add ConversationContextBar above the chat input with folder picker
  (auto-opens unopened folders on select), branch picker, and commit /
  push / merge / stash entries to restore BranchDropdown functionality
- Rework sidebar with stats header, search, flat / folder-grouped view
  modes (localStorage-persisted), reveal-in-sidebar event subscriber,
  and per-folder context menu (focus, close tabs, remove from workspace);
  indent conversations under folder headers in grouped mode
- Gate terminal creation on active folder and show folder context
- Remove deprecated BranchDropdown, FolderNameDropdown, welcome route,
  and per-folder window commands
- Localize all new strings across 10 locales
This commit is contained in:
xintaofei
2026-04-20 21:22:36 +08:00
parent 10801bf393
commit d9323d7399
89 changed files with 3701 additions and 2743 deletions

View File

@@ -23,8 +23,8 @@ pub enum Relation {
#[sea_orm(has_many = "super::conversation::Entity")]
Conversations,
#[sea_orm(has_many = "super::folder_opened_conversation::Entity")]
OpenedConversations,
#[sea_orm(has_many = "super::opened_tab::Entity")]
OpenedTabs,
#[sea_orm(has_many = "super::folder_command::Entity")]
FolderCommands,
@@ -36,9 +36,9 @@ impl Related<super::conversation::Entity> for Entity {
}
}
impl Related<super::folder_opened_conversation::Entity> for Entity {
impl Related<super::opened_tab::Entity> for Entity {
fn to() -> RelationDef {
Relation::OpenedConversations.def()
Relation::OpenedTabs.def()
}
}

View File

@@ -6,6 +6,6 @@ pub mod chat_channel_sender_context;
pub mod conversation;
pub mod folder;
pub mod folder_command;
pub mod folder_opened_conversation;
pub mod model_provider;
pub mod opened_tab;
pub mod prelude;

View File

@@ -1,16 +1,16 @@
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "folder_opened_conversation")]
#[sea_orm(table_name = "opened_tab")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub folder_id: i32,
pub conversation_id: i32,
pub conversation_id: Option<i32>,
pub agent_type: String,
pub position: i32,
pub is_active: bool,
pub is_pinned: bool,
pub agent_type: String,
pub created_at: DateTimeUtc,
pub updated_at: DateTimeUtc,
}

View File

@@ -8,5 +8,5 @@ pub use super::chat_channel_sender_context::Entity as ChatChannelSenderContext;
pub use super::conversation::Entity as Conversation;
pub use super::folder::Entity as Folder;
pub use super::folder_command::Entity as FolderCommand;
pub use super::folder_opened_conversation::Entity as FolderOpenedConversation;
pub use super::model_provider::Entity as ModelProvider;
pub use super::opened_tab::Entity as OpenedTab;

View File

@@ -0,0 +1,132 @@
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(
Table::drop()
.table(FolderOpenedConversation::Table)
.if_exists()
.to_owned(),
)
.await?;
manager
.create_table(
Table::create()
.table(OpenedTab::Table)
.if_not_exists()
.col(
ColumnDef::new(OpenedTab::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(ColumnDef::new(OpenedTab::FolderId).integer().not_null())
.col(ColumnDef::new(OpenedTab::ConversationId).integer().null())
.col(ColumnDef::new(OpenedTab::AgentType).string().not_null())
.col(ColumnDef::new(OpenedTab::Position).integer().not_null())
.col(
ColumnDef::new(OpenedTab::IsActive)
.boolean()
.not_null()
.default(false),
)
.col(
ColumnDef::new(OpenedTab::IsPinned)
.boolean()
.not_null()
.default(false),
)
.col(
ColumnDef::new(OpenedTab::CreatedAt)
.timestamp_with_time_zone()
.not_null(),
)
.col(
ColumnDef::new(OpenedTab::UpdatedAt)
.timestamp_with_time_zone()
.not_null(),
)
.foreign_key(
ForeignKey::create()
.from(OpenedTab::Table, OpenedTab::FolderId)
.to(Folder::Table, Folder::Id)
.on_delete(ForeignKeyAction::Cascade),
)
.foreign_key(
ForeignKey::create()
.from(OpenedTab::Table, OpenedTab::ConversationId)
.to(Conversation::Table, Conversation::Id)
.on_delete(ForeignKeyAction::Cascade),
)
.to_owned(),
)
.await?;
manager
.create_index(
Index::create()
.name("idx_opened_tabs_folder_id")
.table(OpenedTab::Table)
.col(OpenedTab::FolderId)
.to_owned(),
)
.await?;
manager
.create_index(
Index::create()
.name("idx_opened_tabs_position")
.table(OpenedTab::Table)
.col(OpenedTab::Position)
.to_owned(),
)
.await?;
Ok(())
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(OpenedTab::Table).if_exists().to_owned())
.await?;
Ok(())
}
}
#[derive(DeriveIden)]
enum OpenedTab {
Table,
Id,
FolderId,
ConversationId,
AgentType,
Position,
IsActive,
IsPinned,
CreatedAt,
UpdatedAt,
}
#[derive(DeriveIden)]
enum FolderOpenedConversation {
Table,
}
#[derive(DeriveIden)]
enum Folder {
Table,
Id,
}
#[derive(DeriveIden)]
enum Conversation {
Table,
Id,
}

View File

@@ -9,6 +9,7 @@ mod m20260330_000001_chat_channel;
mod m20260401_000001_chat_channel_sender_context;
mod m20260404_000001_model_provider;
mod m20260406_000001_agent_setting_model_provider;
mod m20260420_000001_opened_tabs;
pub struct Migrator;
#[async_trait::async_trait]
@@ -24,6 +25,7 @@ impl MigratorTrait for Migrator {
Box::new(m20260401_000001_chat_channel_sender_context::Migration),
Box::new(m20260404_000001_model_provider::Migration),
Box::new(m20260406_000001_agent_setting_model_provider::Migration),
Box::new(m20260420_000001_opened_tabs::Migration),
]
}
}

View File

@@ -4,7 +4,7 @@ use sea_orm::{
QueryFilter, QueryOrder, Set,
};
use crate::db::entities::conversation;
use crate::db::entities::{conversation, folder};
use crate::db::error::DbError;
use crate::models::{AgentType, DbConversationSummary};
@@ -195,3 +195,68 @@ pub async fn list_by_folder(
Ok(summaries)
}
/// List conversations across folders. When `folder_ids` is `None`, queries all
/// When `folder_ids` is provided, results are scoped to that set. Otherwise
/// returns conversations across every non-deleted folder (open or not).
pub async fn list_all(
conn: &DatabaseConnection,
folder_ids: Option<Vec<i32>>,
agent_type: Option<AgentType>,
search: Option<String>,
sort_by: Option<String>,
status: Option<String>,
) -> Result<Vec<DbConversationSummary>, DbError> {
let mut query = conversation::Entity::find()
.filter(conversation::Column::DeletedAt.is_null());
match folder_ids {
Some(ids) if !ids.is_empty() => {
query = query.filter(conversation::Column::FolderId.is_in(ids));
}
_ => {
// Exclude conversations whose folder was soft-deleted.
let active_folder_ids: Vec<i32> = folder::Entity::find()
.filter(folder::Column::DeletedAt.is_null())
.all(conn)
.await?
.into_iter()
.map(|m| m.id)
.collect();
if active_folder_ids.is_empty() {
return Ok(Vec::new());
}
query = query.filter(conversation::Column::FolderId.is_in(active_folder_ids));
}
}
if let Some(ref at) = agent_type {
let at_str = serde_json::to_value(at)
.ok()
.and_then(|v| v.as_str().map(String::from))
.unwrap_or_default();
query = query.filter(conversation::Column::AgentType.eq(at_str));
}
if let Some(ref s) = search {
if !s.is_empty() {
query = query.filter(conversation::Column::Title.contains(s));
}
}
if let Some(ref st) = status {
if let Ok(status_enum) = serde_json::from_value::<conversation::ConversationStatus>(
serde_json::Value::String(st.clone()),
) {
query = query.filter(conversation::Column::Status.eq(status_enum));
}
}
query = match sort_by.as_deref() {
Some("oldest") => query.order_by_asc(conversation::Column::UpdatedAt),
_ => query.order_by_desc(conversation::Column::UpdatedAt),
};
let rows = query.all(conn).await?;
Ok(rows.into_iter().map(conv_to_summary).collect())
}

View File

@@ -1,14 +1,14 @@
use chrono::Utc;
use sea_orm::DatabaseConnection;
use sea_orm::{
ActiveModelTrait, ActiveValue::NotSet, ColumnTrait, ConnectionTrait, DbBackend, EntityTrait,
IntoActiveModel, QueryFilter, QueryOrder, Set, Statement,
ActiveModelTrait, ActiveValue::NotSet, ColumnTrait, EntityTrait, IntoActiveModel, QueryFilter,
QueryOrder, Set,
};
use crate::db::entities::{folder, folder_opened_conversation};
use crate::db::entities::folder;
use crate::db::error::DbError;
use crate::models::agent::AgentType;
use crate::models::{FolderDetail, FolderHistoryEntry, OpenedConversation};
use crate::models::{FolderDetail, FolderHistoryEntry};
fn to_entry(m: folder::Model) -> FolderHistoryEntry {
FolderHistoryEntry {
@@ -24,7 +24,7 @@ fn parse_agent_type(s: &Option<String>) -> Option<AgentType> {
.and_then(|v| serde_json::from_value(serde_json::Value::String(v.to_string())).ok())
}
fn to_detail(m: folder::Model, opened: Vec<OpenedConversation>) -> FolderDetail {
fn to_detail(m: folder::Model) -> FolderDetail {
let default_agent_type = parse_agent_type(&m.default_agent_type);
FolderDetail {
id: m.id,
@@ -34,7 +34,6 @@ fn to_detail(m: folder::Model, opened: Vec<OpenedConversation>) -> FolderDetail
parent_branch: m.parent_branch,
default_agent_type,
last_opened_at: m.last_opened_at,
opened_conversations: opened,
}
}
@@ -47,13 +46,7 @@ pub async fn get_folder_by_id(
.one(conn)
.await?;
match row {
None => Ok(None),
Some(folder_model) => {
let opened = load_opened_conversations(conn, folder_model.id).await?;
Ok(Some(to_detail(folder_model, opened)))
}
}
Ok(row.map(to_detail))
}
pub async fn add_folder(
@@ -126,80 +119,6 @@ pub async fn remove_folder(conn: &DatabaseConnection, path: &str) -> Result<(),
Ok(())
}
pub async fn save_opened_conversations(
conn: &DatabaseConnection,
folder_id: i32,
items: Vec<OpenedConversation>,
) -> Result<(), DbError> {
// Delete all existing opened conversations for this folder
folder_opened_conversation::Entity::delete_many()
.filter(folder_opened_conversation::Column::FolderId.eq(folder_id))
.exec(conn)
.await?;
if items.is_empty() {
return Ok(());
}
// Batch insert with raw SQL for efficiency
let now = Utc::now();
let now_str = now.format("%Y-%m-%d %H:%M:%S %:z").to_string();
let mut values = Vec::with_capacity(items.len());
for item in &items {
let agent_str = serde_json::to_value(item.agent_type)
.ok()
.and_then(|v| v.as_str().map(|s| s.to_string()))
.unwrap_or_default();
values.push(format!(
"({}, {}, {}, {}, {}, '{}', '{}', '{}')",
folder_id,
item.conversation_id,
item.position,
item.is_active as i32,
item.is_pinned as i32,
agent_str,
now_str,
now_str,
));
}
let sql = format!(
"INSERT INTO folder_opened_conversation (folder_id, conversation_id, position, is_active, is_pinned, agent_type, created_at, updated_at) VALUES {}",
values.join(", ")
);
conn.execute(Statement::from_string(DbBackend::Sqlite, sql))
.await?;
Ok(())
}
async fn load_opened_conversations(
conn: &DatabaseConnection,
folder_id: i32,
) -> Result<Vec<OpenedConversation>, DbError> {
let rows = folder_opened_conversation::Entity::find()
.filter(folder_opened_conversation::Column::FolderId.eq(folder_id))
.order_by_asc(folder_opened_conversation::Column::Position)
.all(conn)
.await?;
Ok(rows
.into_iter()
.filter_map(|r| {
let agent_type = parse_agent_type(&Some(r.agent_type))?;
Some(OpenedConversation {
conversation_id: r.conversation_id,
agent_type,
position: r.position,
is_active: r.is_active,
is_pinned: r.is_pinned,
})
})
.collect())
}
pub async fn set_folder_parent_branch(
conn: &DatabaseConnection,
folder_id: i32,
@@ -244,3 +163,28 @@ pub async fn list_open_folders(
Ok(rows.into_iter().map(to_entry).collect())
}
pub async fn list_open_folder_details(
conn: &DatabaseConnection,
) -> Result<Vec<FolderDetail>, DbError> {
let rows = folder::Entity::find()
.filter(folder::Column::DeletedAt.is_null())
.filter(folder::Column::IsOpen.eq(true))
.order_by_desc(folder::Column::LastOpenedAt)
.all(conn)
.await?;
Ok(rows.into_iter().map(to_detail).collect())
}
pub async fn list_all_folder_details(
conn: &DatabaseConnection,
) -> Result<Vec<FolderDetail>, DbError> {
let rows = folder::Entity::find()
.filter(folder::Column::DeletedAt.is_null())
.order_by_desc(folder::Column::LastOpenedAt)
.all(conn)
.await?;
Ok(rows.into_iter().map(to_detail).collect())
}

View File

@@ -8,3 +8,4 @@ pub mod folder_service;
pub mod import_service;
pub mod model_provider_service;
pub mod sender_context_service;
pub mod tab_service;

View File

@@ -0,0 +1,97 @@
use chrono::Utc;
use sea_orm::{
ActiveModelTrait, ActiveValue::NotSet, ConnectionTrait, DatabaseConnection, DbBackend,
EntityTrait, QueryOrder, Set, Statement,
};
use crate::db::entities::opened_tab;
use crate::db::error::DbError;
use crate::models::agent::AgentType;
use crate::models::OpenedTab;
fn parse_agent_type(s: &str) -> Option<AgentType> {
serde_json::from_value(serde_json::Value::String(s.to_string())).ok()
}
pub async fn list_all_tabs(conn: &DatabaseConnection) -> Result<Vec<OpenedTab>, DbError> {
let rows = opened_tab::Entity::find()
.order_by_asc(opened_tab::Column::Position)
.all(conn)
.await?;
Ok(rows
.into_iter()
.filter_map(|r| {
let agent_type = parse_agent_type(&r.agent_type)?;
Some(OpenedTab {
id: r.id,
folder_id: r.folder_id,
conversation_id: r.conversation_id,
agent_type,
position: r.position,
is_active: r.is_active,
is_pinned: r.is_pinned,
})
})
.collect())
}
/// Replace all tabs with the given list (full replacement).
/// Ensures exactly one `is_active = true` (first active wins; others forced false).
pub async fn save_all_tabs(
conn: &DatabaseConnection,
items: Vec<OpenedTab>,
) -> Result<(), DbError> {
opened_tab::Entity::delete_many().exec(conn).await?;
if items.is_empty() {
return Ok(());
}
let now = Utc::now();
let mut active_seen = false;
for item in items {
let agent_str = serde_json::to_value(item.agent_type)
.ok()
.and_then(|v| v.as_str().map(|s| s.to_string()))
.unwrap_or_default();
let is_active = if item.is_active && !active_seen {
active_seen = true;
true
} else {
false
};
let active = opened_tab::ActiveModel {
id: NotSet,
folder_id: Set(item.folder_id),
conversation_id: Set(item.conversation_id),
agent_type: Set(agent_str),
position: Set(item.position),
is_active: Set(is_active),
is_pinned: Set(item.is_pinned),
created_at: Set(now),
updated_at: Set(now),
};
active.insert(conn).await?;
}
Ok(())
}
/// Delete all tabs that belong to a given folder (used when removing a folder
/// from the workspace).
pub async fn delete_tabs_for_folder(
conn: &DatabaseConnection,
folder_id: i32,
) -> Result<(), DbError> {
let sql = format!(
"DELETE FROM opened_tab WHERE folder_id = {}",
folder_id
);
conn.execute(Statement::from_string(DbBackend::Sqlite, sql))
.await?;
Ok(())
}