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

@@ -2,7 +2,7 @@
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["welcome", "folder-*", "commit-*", "merge-*", "stash-*", "push-*", "settings", "project-boot"],
"windows": ["main", "commit-*", "merge-*", "stash-*", "push-*", "settings", "project-boot"],
"permissions": [
"core:default",
"core:window:default",

View File

@@ -6,8 +6,7 @@
"linux"
],
"windows": [
"welcome",
"folder-*",
"main",
"commit-*",
"merge-*",
"stash-*",

View File

@@ -19,15 +19,38 @@ use crate::parsers::{path_eq_for_matching, AgentParser, ParseError};
#[cfg(feature = "tauri-runtime")]
#[cfg_attr(feature = "tauri-runtime", tauri::command)]
pub async fn list_folder_conversations(
pub async fn list_all_conversations(
db: tauri::State<'_, AppDatabase>,
folder_id: i32,
folder_ids: Option<Vec<i32>>,
agent_type: Option<AgentType>,
search: Option<String>,
sort_by: Option<String>,
status: Option<String>,
) -> Result<Vec<DbConversationSummary>, AppCommandError> {
conversation_service::list_by_folder(&db.conn, folder_id, agent_type, search, sort_by, status)
conversation_service::list_all(&db.conn, folder_ids, agent_type, search, sort_by, status)
.await
.map_err(AppCommandError::from)
}
#[cfg(feature = "tauri-runtime")]
#[cfg_attr(feature = "tauri-runtime", tauri::command)]
pub async fn list_opened_tabs(
db: tauri::State<'_, AppDatabase>,
) -> Result<Vec<OpenedTab>, AppCommandError> {
use crate::db::service::tab_service;
tab_service::list_all_tabs(&db.conn)
.await
.map_err(AppCommandError::from)
}
#[cfg(feature = "tauri-runtime")]
#[cfg_attr(feature = "tauri-runtime", tauri::command)]
pub async fn save_opened_tabs(
db: tauri::State<'_, AppDatabase>,
items: Vec<OpenedTab>,
) -> Result<(), AppCommandError> {
use crate::db::service::tab_service;
tab_service::save_all_tabs(&db.conn, items)
.await
.map_err(AppCommandError::from)
}

View File

@@ -23,7 +23,7 @@ use crate::db::service::folder_service;
use crate::db::AppDatabase;
use crate::models::GitCredentials;
#[cfg(feature = "tauri-runtime")]
use crate::models::{FolderDetail, FolderHistoryEntry, OpenedConversation};
use crate::models::{FolderDetail, FolderHistoryEntry};
use crate::web::event_bridge::EventEmitter;
/// Configure a git command for remote operations:
@@ -526,12 +526,52 @@ pub async fn remove_folder_from_history(
#[cfg(feature = "tauri-runtime")]
#[cfg_attr(feature = "tauri-runtime", tauri::command)]
pub async fn save_folder_opened_conversations(
pub async fn list_open_folder_details(
db: tauri::State<'_, AppDatabase>,
) -> Result<Vec<FolderDetail>, AppCommandError> {
folder_service::list_open_folder_details(&db.conn)
.await
.map_err(AppCommandError::from)
}
#[cfg(feature = "tauri-runtime")]
#[cfg_attr(feature = "tauri-runtime", tauri::command)]
pub async fn list_all_folder_details(
db: tauri::State<'_, AppDatabase>,
) -> Result<Vec<FolderDetail>, AppCommandError> {
folder_service::list_all_folder_details(&db.conn)
.await
.map_err(AppCommandError::from)
}
#[cfg(feature = "tauri-runtime")]
#[cfg_attr(feature = "tauri-runtime", tauri::command)]
pub async fn open_folder_by_id(
db: tauri::State<'_, AppDatabase>,
folder_id: i32,
items: Vec<OpenedConversation>,
) -> Result<(), DbError> {
folder_service::save_opened_conversations(&db.conn, folder_id, items).await
) -> Result<FolderDetail, AppCommandError> {
folder_service::set_folder_open(&db.conn, folder_id, true)
.await
.map_err(AppCommandError::from)?;
folder_service::get_folder_by_id(&db.conn, folder_id)
.await
.map_err(AppCommandError::from)?
.ok_or_else(|| AppCommandError::not_found(format!("Folder {folder_id} not found")))
}
#[cfg(feature = "tauri-runtime")]
#[cfg_attr(feature = "tauri-runtime", tauri::command)]
pub async fn remove_folder_from_workspace(
db: tauri::State<'_, AppDatabase>,
folder_id: i32,
) -> Result<(), AppCommandError> {
use crate::db::service::tab_service;
tab_service::delete_tabs_for_folder(&db.conn, folder_id)
.await
.map_err(AppCommandError::from)?;
folder_service::set_folder_open(&db.conn, folder_id, false)
.await
.map_err(AppCommandError::from)
}
#[cfg_attr(feature = "tauri-runtime", tauri::command)]

View File

@@ -10,7 +10,7 @@ use tauri::{AppHandle, Manager, WebviewUrl, WebviewWindowBuilder};
use crate::app_error::AppCommandError;
use crate::db::AppDatabase;
use crate::db::service::app_metadata_service;
use crate::models::FolderHistoryEntry;
use crate::models::FolderDetail;
/// Base traffic-light position (logical px) at 100 % zoom.
#[cfg(target_os = "macos")]
@@ -85,10 +85,6 @@ pub struct CommitWindowState {
owner_by_commit_label: Mutex<HashMap<String, String>>,
}
pub fn folder_window_label(folder_id: i32) -> String {
format!("folder-{folder_id}")
}
/// Detect macOS system dark mode via `defaults read`.
/// Result is cached for the process lifetime via `OnceLock`.
#[cfg(target_os = "macos")]
@@ -288,13 +284,6 @@ impl CommitWindowState {
}
}
fn get_folder_id_from_window(window: &tauri::WebviewWindow) -> Option<i32> {
let url = window.url().ok()?;
url.query_pairs()
.find(|(key, _)| key == "id")
.and_then(|(_, value)| value.parse::<i32>().ok())
}
fn resolve_settings_route(section: Option<&str>) -> &'static str {
match section {
Some("appearance") => "settings/appearance",
@@ -331,103 +320,36 @@ fn resolve_settings_target(section: Option<&str>, agent_type: Option<&str>) -> S
route.to_string()
}
#[cfg(feature = "tauri-runtime")]
#[cfg_attr(feature = "tauri-runtime", tauri::command)]
pub async fn list_open_folders(
app: AppHandle,
db: tauri::State<'_, AppDatabase>,
) -> Result<Vec<FolderHistoryEntry>, AppCommandError> {
let windows = app.webview_windows();
let mut folder_ids: Vec<i32> = Vec::new();
for (label, window) in &windows {
if label.starts_with("folder-") {
if let Some(id) = get_folder_id_from_window(window) {
folder_ids.push(id);
}
}
}
let all_folders = crate::db::service::folder_service::list_folders(&db.conn)
.await
.map_err(AppCommandError::from)?;
let open_folders: Vec<FolderHistoryEntry> = all_folders
.into_iter()
.filter(|f| folder_ids.contains(&f.id))
.collect();
Ok(open_folders)
}
#[cfg(feature = "tauri-runtime")]
#[cfg_attr(feature = "tauri-runtime", tauri::command)]
pub async fn focus_folder_window(app: AppHandle, folder_id: i32) -> Result<(), AppCommandError> {
let windows = app.webview_windows();
for (label, window) in &windows {
if label.starts_with("folder-") {
if let Some(id) = get_folder_id_from_window(window) {
if id == folder_id {
window.set_focus().map_err(|e| {
AppCommandError::window("Failed to focus folder window", e.to_string())
})?;
return Ok(());
}
}
}
}
Err(
AppCommandError::not_found(format!("No open window for folder {folder_id}"))
.with_detail(format!("folder_id={folder_id}")),
)
}
#[cfg(feature = "tauri-runtime")]
#[cfg_attr(feature = "tauri-runtime", tauri::command)]
pub async fn open_folder_window(
app: AppHandle,
db: tauri::State<'_, AppDatabase>,
path: String,
) -> Result<(), AppCommandError> {
// Add to history via DB
) -> Result<FolderDetail, AppCommandError> {
// Single-window workspace: upsert the folder (is_open = true), close any
// legacy project-boot window, and return the full detail for the frontend
// to add to its workspace state.
let entry = crate::db::service::folder_service::add_folder(&db.conn, &path)
.await
.map_err(AppCommandError::from)?;
let label = folder_window_label(entry.id);
if let Some(existing) = app.get_webview_window(&label) {
post_window_setup(&existing);
let _ = existing.unminimize();
existing
.set_focus()
.map_err(|e| AppCommandError::window("Failed to focus folder window", e.to_string()))?;
if let Some(w) = app.get_webview_window("welcome") {
let _ = w.close();
}
if let Some(w) = app.get_webview_window("project-boot") {
let _ = w.close();
}
return Ok(());
}
let url = WebviewUrl::App(format!("folder?id={}", entry.id).into());
let builder = WebviewWindowBuilder::new(&app, &label, url)
.title(&entry.name)
.inner_size(1260.0, 860.0)
.min_inner_size(900.0, 600.0);
let folder_window = apply_platform_window_style(builder)
.build()
.map_err(|e| AppCommandError::window("Failed to open folder window", e.to_string()))?;
post_window_setup(&folder_window);
// Close welcome and project-boot windows
if let Some(w) = app.get_webview_window("welcome") {
let _ = w.close();
}
if let Some(w) = app.get_webview_window("project-boot") {
let _ = w.close();
}
Ok(())
let folder = crate::db::service::folder_service::get_folder_by_id(&db.conn, entry.id)
.await
.map_err(AppCommandError::from)?
.ok_or_else(|| AppCommandError::not_found("Folder not found after add"))?;
// Bring the main window to focus if it exists
if let Some(main) = app.get_webview_window("main") {
let _ = main.unminimize();
let _ = main.set_focus();
}
Ok(folder)
}
#[cfg(feature = "tauri-runtime")]
@@ -714,24 +636,6 @@ pub async fn cleanup_dangling_merge(app: &AppHandle, merge_window_label: &str) {
}
}
pub fn open_welcome_window(app: &AppHandle) -> Result<(), AppCommandError> {
if let Some(existing) = app.get_webview_window("welcome") {
post_window_setup(&existing);
return Ok(());
}
let url = WebviewUrl::App("welcome".into());
let builder = WebviewWindowBuilder::new(app, "welcome", url)
.title("Codeg")
.inner_size(800.0, 520.0)
.min_inner_size(600.0, 400.0)
.center();
let welcome_window = apply_platform_window_style(builder)
.build()
.map_err(|e| AppCommandError::window("Failed to open welcome window", e.to_string()))?;
post_window_setup(&welcome_window);
Ok(())
}
#[cfg(feature = "tauri-runtime")]
#[cfg_attr(feature = "tauri-runtime", tauri::command)]
pub async fn open_stash_window(
@@ -818,18 +722,13 @@ pub async fn open_project_boot_window(
app: AppHandle,
source: Option<String>,
) -> Result<(), AppCommandError> {
let _ = source;
if let Some(existing) = app.get_webview_window("project-boot") {
post_window_setup(&existing);
let _ = existing.unminimize();
existing.set_focus().map_err(|e| {
AppCommandError::window("Failed to focus project boot window", e.to_string())
})?;
// Close welcome if opened from welcome
if source.as_deref() == Some("welcome") {
if let Some(w) = app.get_webview_window("welcome") {
let _ = w.close();
}
}
return Ok(());
}
@@ -846,13 +745,6 @@ pub async fn open_project_boot_window(
})?;
post_window_setup(&window);
// Close welcome if opened from welcome
if source.as_deref() == Some("welcome") {
if let Some(w) = app.get_webview_window("welcome") {
let _ = w.close();
}
}
Ok(())
}

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(())
}

View File

@@ -34,14 +34,6 @@ mod tauri_app {
static APP_QUITTING: AtomicBool = AtomicBool::new(false);
fn get_folder_id_from_url(window: &tauri::Window) -> Option<i32> {
let webview = window.get_webview_window(window.label())?;
let url = webview.url().ok()?;
url.query_pairs()
.find(|(key, _)| key == "id")
.and_then(|(_, value)| value.parse::<i32>().ok())
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
if let Err(err) = fix_path_env::fix() {
@@ -128,26 +120,18 @@ mod tauri_app {
});
}
// Restore previously open folders or show welcome
let db = app.state::<db::AppDatabase>();
let open_folders = tauri::async_runtime::block_on(
db::service::folder_service::list_open_folders(&db.conn),
)
.unwrap_or_default();
if open_folders.is_empty() {
let _ = windows::open_welcome_window(app.handle());
} else {
for entry in &open_folders {
let label = windows::folder_window_label(entry.id);
let url = tauri::WebviewUrl::App(format!("folder?id={}", entry.id).into());
let builder = tauri::WebviewWindowBuilder::new(app, &label, url)
.title(&entry.name)
.inner_size(1260.0, 860.0)
.min_inner_size(900.0, 600.0);
if let Ok(w) = windows::apply_platform_window_style(builder).build() {
windows::post_window_setup(&w);
}
// Single-window workspace: ensure the main window exists.
// Workspace state (open folders, opened tabs, active tab) is
// restored by the frontend via `list_open_folder_details` /
// `list_opened_tabs` inside the main window.
if app.get_webview_window("main").is_none() {
let url = tauri::WebviewUrl::App("workspace".into());
let builder = tauri::WebviewWindowBuilder::new(app, "main", url)
.title("Codeg")
.inner_size(1260.0, 860.0)
.min_inner_size(900.0, 600.0);
if let Ok(w) = windows::apply_platform_window_style(builder).build() {
windows::post_window_setup(&w);
}
}
@@ -197,70 +181,31 @@ mod tauri_app {
});
}
if label == "project-boot"
&& matches!(
event,
tauri::WindowEvent::CloseRequested { .. } | tauri::WindowEvent::Destroyed
)
if label == "main"
&& matches!(event, tauri::WindowEvent::CloseRequested { .. })
{
let app = window.app_handle();
if !APP_QUITTING.load(Ordering::Relaxed) {
let has_other = app
.webview_windows()
.keys()
.any(|l| *l != label && *l != "settings");
if !has_other {
let _ = windows::open_welcome_window(app);
}
if let Some(cm) = app.try_state::<ConnectionManager>() {
let disconnected = tauri::async_runtime::block_on(
cm.disconnect_by_owner_window(&label),
);
eprintln!(
"[ACP] main window closing disconnected_connections={}",
disconnected
);
}
}
if let tauri::WindowEvent::CloseRequested { .. } = event {
if label.starts_with("folder-") {
let app = window.app_handle();
if let Some(cm) = app.try_state::<ConnectionManager>() {
let disconnected = tauri::async_runtime::block_on(
cm.disconnect_by_owner_window(&label),
);
eprintln!(
"[ACP] folder window closing label={} disconnected_connections={}",
label, disconnected
);
}
if !APP_QUITTING.load(Ordering::Relaxed) {
if let Some(folder_id) = get_folder_id_from_url(window) {
if let Some(db) = app.try_state::<db::AppDatabase>() {
let _ = tauri::async_runtime::block_on(
db::service::folder_service::set_folder_open(
&db.conn, folder_id, false,
),
);
}
}
}
if let Some(tm) = app.try_state::<TerminalManager>() {
let killed = tm.kill_by_owner_window(&label);
eprintln!(
"[TERM] folder window closing label={} killed_terminals={}",
label, killed
);
}
let has_other_folder = app
.webview_windows()
.keys()
.any(|l| l.starts_with("folder-") && *l != label);
if !has_other_folder && !APP_QUITTING.load(Ordering::Relaxed) {
let _ = windows::open_welcome_window(app);
}
if let Some(tm) = app.try_state::<TerminalManager>() {
let killed = tm.kill_by_owner_window(&label);
eprintln!("[TERM] main window closing killed_terminals={}", killed);
}
}
})
.invoke_handler(tauri::generate_handler![
conversations::list_conversations,
conversations::get_conversation,
conversations::list_folder_conversations,
conversations::list_all_conversations,
conversations::list_opened_tabs,
conversations::save_opened_tabs,
conversations::import_local_conversations,
conversations::get_folder_conversation,
conversations::list_folders,
@@ -273,6 +218,10 @@ mod tauri_app {
conversations::delete_conversation,
folders::load_folder_history,
folders::get_folder,
folders::list_open_folder_details,
folders::list_all_folder_details,
folders::open_folder_by_id,
folders::remove_folder_from_workspace,
folders::add_folder_to_history,
folders::set_folder_parent_branch,
folders::remove_folder_from_history,
@@ -322,7 +271,6 @@ mod tauri_app {
folders::git_resolve_conflict,
folders::git_abort_operation,
folders::git_continue_operation,
folders::save_folder_opened_conversations,
workspace_state_commands::start_workspace_state_stream,
workspace_state_commands::stop_workspace_state_stream,
workspace_state_commands::get_workspace_snapshot,
@@ -342,8 +290,6 @@ mod tauri_app {
windows::open_folder_window,
windows::open_commit_window,
windows::open_settings_window,
windows::list_open_folders,
windows::focus_folder_window,
windows::open_merge_window,
windows::open_stash_window,
windows::open_push_window,

View File

@@ -20,12 +20,13 @@ pub struct FolderDetail {
pub parent_branch: Option<String>,
pub default_agent_type: Option<AgentType>,
pub last_opened_at: DateTime<Utc>,
pub opened_conversations: Vec<OpenedConversation>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpenedConversation {
pub conversation_id: i32,
pub struct OpenedTab {
pub id: i32,
pub folder_id: i32,
pub conversation_id: Option<i32>,
pub agent_type: AgentType,
pub position: i32,
pub is_active: bool,

View File

@@ -14,7 +14,7 @@ pub use conversation::{
DbConversationDetail, DbConversationSummary, FolderInfo, ImportResult, SessionStats,
SidebarData,
};
pub use folder::{FolderCommandInfo, FolderDetail, FolderHistoryEntry, OpenedConversation};
pub use folder::{FolderCommandInfo, FolderDetail, FolderHistoryEntry, OpenedTab};
pub use message::{
AgentExecutionStats, AgentToolCall, ContentBlock, MessageRole, MessageTurn, TurnRole,
TurnUsage, UnifiedMessage,

View File

@@ -9,24 +9,24 @@ use crate::commands::conversations as conv_commands;
use crate::db::service::{conversation_service, folder_service, import_service};
use crate::models::*;
#[derive(Deserialize)]
#[derive(Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ListFolderConversationsParams {
pub folder_id: i32,
pub struct ListAllConversationsParams {
pub folder_ids: Option<Vec<i32>>,
pub agent_type: Option<AgentType>,
pub search: Option<String>,
pub sort_by: Option<String>,
pub status: Option<String>,
}
pub async fn list_folder_conversations(
pub async fn list_all_conversations(
Extension(state): Extension<Arc<AppState>>,
Json(params): Json<ListFolderConversationsParams>,
Json(params): Json<ListAllConversationsParams>,
) -> Result<Json<Vec<DbConversationSummary>>, AppCommandError> {
let db = &state.db;
let result = conversation_service::list_by_folder(
let result = conversation_service::list_all(
&db.conn,
params.folder_id,
params.folder_ids,
params.agent_type,
params.search,
params.sort_by,
@@ -37,6 +37,35 @@ pub async fn list_folder_conversations(
Ok(Json(result))
}
pub async fn list_opened_tabs(
Extension(state): Extension<Arc<AppState>>,
) -> Result<Json<Vec<OpenedTab>>, AppCommandError> {
use crate::db::service::tab_service;
let db = &state.db;
let result = tab_service::list_all_tabs(&db.conn)
.await
.map_err(AppCommandError::from)?;
Ok(Json(result))
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SaveOpenedTabsParams {
pub items: Vec<OpenedTab>,
}
pub async fn save_opened_tabs(
Extension(state): Extension<Arc<AppState>>,
Json(params): Json<SaveOpenedTabsParams>,
) -> Result<Json<()>, AppCommandError> {
use crate::db::service::tab_service;
let db = &state.db;
tab_service::save_all_tabs(&db.conn, params.items)
.await
.map_err(AppCommandError::from)?;
Ok(Json(()))
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListConversationsParams {

View File

@@ -53,45 +53,71 @@ pub struct AddFolderParams {
pub path: String,
}
/// Web equivalent of `open_folder_window`: adds the folder to DB and returns its ID.
/// The web client then navigates to `/folder?id=N` itself.
pub async fn open_folder_window(
/// Add the folder to the workspace (upsert + set is_open=true) and return its full detail.
/// Previously this spawned a new window; the new single-window workspace model
/// simply returns the folder info so the client can update its local state.
pub async fn open_folder(
Extension(state): Extension<Arc<AppState>>,
Json(params): Json<AddFolderParams>,
) -> Result<Json<FolderHistoryEntry>, AppCommandError> {
) -> Result<Json<FolderDetail>, AppCommandError> {
let db = &state.db;
let entry = folder_service::add_folder(&db.conn, &params.path)
.await
.map_err(AppCommandError::from)?;
Ok(Json(entry))
let folder = folder_service::get_folder_by_id(&db.conn, entry.id)
.await
.map_err(AppCommandError::from)?
.ok_or_else(|| AppCommandError::not_found("Folder not found after add"))?;
Ok(Json(folder))
}
pub async fn close_folder_window(
// --- New workspace handlers ---
pub async fn list_open_folder_details(
Extension(state): Extension<Arc<AppState>>,
) -> Result<Json<Vec<FolderDetail>>, AppCommandError> {
let db = &state.db;
let result = folder_service::list_open_folder_details(&db.conn)
.await
.map_err(AppCommandError::from)?;
Ok(Json(result))
}
pub async fn list_all_folder_details(
Extension(state): Extension<Arc<AppState>>,
) -> Result<Json<Vec<FolderDetail>>, AppCommandError> {
let db = &state.db;
let result = folder_service::list_all_folder_details(&db.conn)
.await
.map_err(AppCommandError::from)?;
Ok(Json(result))
}
pub async fn open_folder_by_id(
Extension(state): Extension<Arc<AppState>>,
Json(params): Json<FolderIdParams>,
) -> Result<Json<FolderDetail>, AppCommandError> {
let db = &state.db;
folder_service::set_folder_open(&db.conn, params.folder_id, true)
.await
.map_err(AppCommandError::from)?;
let folder = folder_service::get_folder_by_id(&db.conn, params.folder_id)
.await
.map_err(AppCommandError::from)?
.ok_or_else(|| AppCommandError::not_found("Folder not found"))?;
Ok(Json(folder))
}
pub async fn remove_folder_from_workspace(
Extension(state): Extension<Arc<AppState>>,
Json(params): Json<FolderIdParams>,
) -> Result<Json<()>, AppCommandError> {
use crate::db::service::tab_service;
let db = &state.db;
folder_service::set_folder_open(&db.conn, params.folder_id, false)
tab_service::delete_tabs_for_folder(&db.conn, params.folder_id)
.await
.map_err(AppCommandError::from)?;
Ok(Json(()))
}
// --- New handlers below ---
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SaveFolderOpenedConversationsParams {
pub folder_id: i32,
pub items: Vec<OpenedConversation>,
}
pub async fn save_folder_opened_conversations(
Extension(state): Extension<Arc<AppState>>,
Json(params): Json<SaveFolderOpenedConversationsParams>,
) -> Result<Json<()>, AppCommandError> {
let db = &state.db;
folder_service::save_opened_conversations(&db.conn, params.folder_id, params.items)
folder_service::set_folder_open(&db.conn, params.folder_id, false)
.await
.map_err(AppCommandError::from)?;
Ok(Json(()))

View File

@@ -34,13 +34,21 @@ pub fn build_router(state: Arc<AppState>, token: String, static_dir: std::path::
post(handlers::conversations::get_conversation),
)
.route(
"/list_folder_conversations",
post(handlers::conversations::list_folder_conversations),
"/list_all_conversations",
post(handlers::conversations::list_all_conversations),
)
.route(
"/get_folder_conversation",
post(handlers::conversations::get_folder_conversation),
)
.route(
"/list_opened_tabs",
post(handlers::conversations::list_opened_tabs),
)
.route(
"/save_opened_tabs",
post(handlers::conversations::save_opened_tabs),
)
.route(
"/import_local_conversations",
post(handlers::conversations::import_local_conversations),
@@ -81,13 +89,22 @@ pub fn build_router(state: Arc<AppState>, token: String, static_dir: std::path::
post(handlers::folders::list_open_folders),
)
.route(
"/close_folder_window",
post(handlers::folders::close_folder_window),
"/list_open_folder_details",
post(handlers::folders::list_open_folder_details),
)
.route(
"/list_all_folder_details",
post(handlers::folders::list_all_folder_details),
)
.route("/get_folder", post(handlers::folders::get_folder))
.route("/open_folder", post(handlers::folders::open_folder))
.route(
"/open_folder_window",
post(handlers::folders::open_folder_window),
"/open_folder_by_id",
post(handlers::folders::open_folder_by_id),
)
.route(
"/remove_folder_from_workspace",
post(handlers::folders::remove_folder_from_workspace),
)
.route(
"/add_folder_to_history",
@@ -105,10 +122,6 @@ pub fn build_router(state: Arc<AppState>, token: String, static_dir: std::path::
"/create_folder_directory",
post(handlers::folders::create_folder_directory),
)
.route(
"/save_folder_opened_conversations",
post(handlers::folders::save_folder_opened_conversations),
)
.route("/get_git_branch", post(handlers::folders::get_git_branch))
.route(
"/get_home_directory",