Skip to repository content

tenant.openagents/omega

No repository description is available.

OpenAgents Git authority 2026-07-28T05:01:32.750Z Public web read
NIP-34 coordinate30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omega
MaintainersHidden in public view
References2 branches · 1 tag
Read-only clonegit clone https://openagents.com/git/tenant.openagents/omega.git
Browse files

model.rs

485 lines · 15.5 KB · rust
1use super::{SerializedAxis, SerializedWindowBounds};
2use crate::{
3    Member, Pane, PaneAxis, SerializableItemRegistry, Workspace, WorkspaceId, item::ItemHandle,
4    multi_workspace::SerializedProjectGroupState, path_list::PathList,
5};
6use anyhow::{Context, Result};
7use async_recursion::async_recursion;
8use collections::IndexSet;
9use db::sqlez::{
10    bindable::{Bind, Column, StaticColumnCount},
11    statement::Statement,
12};
13use gpui::{AsyncWindowContext, Entity, WeakEntity, WindowId};
14
15use language::{Toolchain, ToolchainScope};
16use project::{
17    Project, ProjectGroupKey, bookmark_store::SerializedBookmark,
18    debugger::breakpoint_store::SourceBreakpoint,
19};
20use remote::RemoteConnectionOptions;
21use serde::{Deserialize, Serialize};
22use std::{
23    collections::BTreeMap,
24    path::{Path, PathBuf},
25    sync::Arc,
26};
27use util::{ResultExt, path_list::SerializedPathList};
28use uuid::Uuid;
29
30#[derive(
31    Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, serde::Serialize, serde::Deserialize,
32)]
33pub(crate) struct RemoteConnectionId(pub u64);
34
35#[derive(Debug, PartialEq, Eq, Clone, Copy)]
36pub(crate) enum RemoteConnectionKind {
37    Ssh,
38    Wsl,
39    Docker,
40}
41
42#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
43pub enum SerializedWorkspaceLocation {
44    Local,
45    Remote(RemoteConnectionOptions),
46}
47
48impl SerializedWorkspaceLocation {
49    /// Get sorted paths
50    pub fn sorted_paths(&self) -> Arc<Vec<PathBuf>> {
51        unimplemented!()
52    }
53}
54
55/// A workspace entry from a previous session, containing all the info needed
56/// to restore it including which window it belonged to (for MultiWorkspace grouping).
57#[derive(Debug, PartialEq, Clone)]
58pub struct SessionWorkspace {
59    pub workspace_id: WorkspaceId,
60    pub location: SerializedWorkspaceLocation,
61    pub paths: PathList,
62    pub window_id: Option<WindowId>,
63}
64
65#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
66pub struct SerializedProjectGroup {
67    pub path_list: SerializedPathList,
68    pub(crate) location: SerializedWorkspaceLocation,
69    #[serde(default = "default_expanded")]
70    pub expanded: bool,
71}
72
73fn default_expanded() -> bool {
74    true
75}
76
77impl SerializedProjectGroup {
78    pub fn from_group(key: &ProjectGroupKey, expanded: bool) -> Self {
79        Self {
80            path_list: key.path_list().serialize(),
81            location: match key.host() {
82                Some(host) => SerializedWorkspaceLocation::Remote(host),
83                None => SerializedWorkspaceLocation::Local,
84            },
85            expanded,
86        }
87    }
88
89    pub fn into_restored_state(self) -> SerializedProjectGroupState {
90        let path_list = PathList::deserialize(&self.path_list);
91        let host = match self.location {
92            SerializedWorkspaceLocation::Local => None,
93            SerializedWorkspaceLocation::Remote(opts) => Some(opts),
94        };
95        SerializedProjectGroupState {
96            key: ProjectGroupKey::new(host, path_list),
97            expanded: self.expanded,
98        }
99    }
100}
101
102impl From<SerializedProjectGroup> for ProjectGroupKey {
103    fn from(value: SerializedProjectGroup) -> Self {
104        value.into_restored_state().key
105    }
106}
107
108/// Per-window state for a MultiWorkspace, persisted to KVP.
109#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
110pub struct MultiWorkspaceState {
111    pub active_workspace_id: Option<WorkspaceId>,
112    pub sidebar_open: bool,
113    #[serde(alias = "project_group_keys")]
114    pub project_groups: Vec<SerializedProjectGroup>,
115    #[serde(default)]
116    pub sidebar_state: Option<String>,
117}
118
119/// The serialized state of a single MultiWorkspace window from a previous session:
120/// the active workspace to restore plus window-level state (project group keys,
121/// sidebar).
122#[derive(Debug, Clone)]
123pub struct SerializedMultiWorkspace {
124    pub active_workspace: SessionWorkspace,
125    pub state: MultiWorkspaceState,
126}
127
128#[derive(Debug, PartialEq, Clone)]
129pub(crate) struct SerializedWorkspace {
130    pub(crate) id: WorkspaceId,
131    pub(crate) location: SerializedWorkspaceLocation,
132    pub(crate) paths: PathList,
133    /// The workspace's main worktree paths at the time this workspace was saved.
134    ///
135    /// These paths are used for grouping, deduping, and display in recent-workspace
136    /// UIs. They are not authoritative for reopening the workspace, because they may
137    /// become stale if the repository layout changes after the save. Use `paths` when
138    /// reopening the workspace.
139    pub(crate) identity_paths: Option<PathList>,
140    pub(crate) center_group: SerializedPaneGroup,
141    pub(crate) window_bounds: Option<SerializedWindowBounds>,
142    pub(crate) centered_layout: bool,
143    pub(crate) display: Option<Uuid>,
144    pub(crate) docks: DockStructure,
145    pub(crate) session_id: Option<String>,
146    pub(crate) bookmarks: BTreeMap<Arc<Path>, Vec<SerializedBookmark>>,
147    pub(crate) breakpoints: BTreeMap<Arc<Path>, Vec<SourceBreakpoint>>,
148    pub(crate) user_toolchains: BTreeMap<ToolchainScope, IndexSet<Toolchain>>,
149    pub(crate) window_id: Option<u64>,
150}
151
152#[derive(Debug, PartialEq, Clone, Default, Serialize, Deserialize)]
153pub struct DockStructure {
154    pub left: DockData,
155    pub right: DockData,
156    pub bottom: DockData,
157}
158
159impl RemoteConnectionKind {
160    pub(crate) fn serialize(&self) -> &'static str {
161        match self {
162            RemoteConnectionKind::Ssh => "ssh",
163            RemoteConnectionKind::Wsl => "wsl",
164            RemoteConnectionKind::Docker => "docker",
165        }
166    }
167
168    pub(crate) fn deserialize(text: &str) -> Option<Self> {
169        match text {
170            "ssh" => Some(Self::Ssh),
171            "wsl" => Some(Self::Wsl),
172            "docker" => Some(Self::Docker),
173            _ => None,
174        }
175    }
176}
177
178impl Column for DockStructure {
179    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
180        let (left, next_index) = DockData::column(statement, start_index)?;
181        let (right, next_index) = DockData::column(statement, next_index)?;
182        let (bottom, next_index) = DockData::column(statement, next_index)?;
183        Ok((
184            DockStructure {
185                left,
186                right,
187                bottom,
188            },
189            next_index,
190        ))
191    }
192}
193
194impl Bind for DockStructure {
195    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
196        let next_index = statement.bind(&self.left, start_index)?;
197        let next_index = statement.bind(&self.right, next_index)?;
198        statement.bind(&self.bottom, next_index)
199    }
200}
201
202#[derive(Debug, PartialEq, Clone, Default, Serialize, Deserialize)]
203pub struct DockData {
204    pub visible: bool,
205    pub active_panel: Option<String>,
206    pub zoom: bool,
207}
208
209impl Column for DockData {
210    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
211        let (visible, next_index) = Option::<bool>::column(statement, start_index)?;
212        let (active_panel, next_index) = Option::<String>::column(statement, next_index)?;
213        let (zoom, next_index) = Option::<bool>::column(statement, next_index)?;
214        Ok((
215            DockData {
216                visible: visible.unwrap_or(false),
217                active_panel,
218                zoom: zoom.unwrap_or(false),
219            },
220            next_index,
221        ))
222    }
223}
224
225impl Bind for DockData {
226    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
227        let next_index = statement.bind(&self.visible, start_index)?;
228        let next_index = statement.bind(&self.active_panel, next_index)?;
229        statement.bind(&self.zoom, next_index)
230    }
231}
232
233#[derive(Debug, PartialEq, Clone)]
234pub(crate) enum SerializedPaneGroup {
235    Group {
236        axis: SerializedAxis,
237        flexes: Option<Vec<f32>>,
238        children: Vec<SerializedPaneGroup>,
239    },
240    Pane(SerializedPane),
241}
242
243#[cfg(test)]
244impl Default for SerializedPaneGroup {
245    fn default() -> Self {
246        Self::Pane(SerializedPane {
247            children: vec![SerializedItem::default()],
248            active: false,
249            pinned_count: 0,
250        })
251    }
252}
253
254impl SerializedPaneGroup {
255    #[async_recursion(?Send)]
256    pub(crate) async fn deserialize(
257        self,
258        project: &Entity<Project>,
259        workspace_id: WorkspaceId,
260        workspace: WeakEntity<Workspace>,
261        cx: &mut AsyncWindowContext,
262    ) -> Option<(
263        Member,
264        Option<Entity<Pane>>,
265        Vec<Option<Box<dyn ItemHandle>>>,
266    )> {
267        match self {
268            SerializedPaneGroup::Group {
269                axis,
270                children,
271                flexes,
272            } => {
273                let mut current_active_pane = None;
274                let mut members = Vec::new();
275                let mut items = Vec::new();
276                for child in children {
277                    if let Some((new_member, active_pane, new_items)) = child
278                        .deserialize(project, workspace_id, workspace.clone(), cx)
279                        .await
280                    {
281                        members.push(new_member);
282                        items.extend(new_items);
283                        current_active_pane = current_active_pane.or(active_pane);
284                    }
285                }
286
287                if members.is_empty() {
288                    return None;
289                }
290
291                if members.len() == 1 {
292                    return Some((members.remove(0), current_active_pane, items));
293                }
294
295                Some((
296                    Member::Axis(PaneAxis::load(axis.0, members, flexes)),
297                    current_active_pane,
298                    items,
299                ))
300            }
301            SerializedPaneGroup::Pane(serialized_pane) => {
302                let pane = workspace
303                    .update_in(cx, |workspace, window, cx| {
304                        workspace.add_pane(window, cx).downgrade()
305                    })
306                    .log_err()?;
307                let active = serialized_pane.active;
308                let new_items = serialized_pane
309                    .deserialize_to(project, &pane, workspace_id, workspace.clone(), cx)
310                    .await
311                    .context("Could not deserialize pane)")
312                    .log_err()?;
313
314                if pane
315                    .read_with(cx, |pane, _| pane.items_len() != 0)
316                    .log_err()?
317                {
318                    let pane = pane.upgrade()?;
319                    Some((
320                        Member::Pane(pane.clone()),
321                        active.then_some(pane),
322                        new_items,
323                    ))
324                } else {
325                    let pane = pane.upgrade()?;
326                    workspace
327                        .update_in(cx, |workspace, window, cx| {
328                            workspace.force_remove_pane(&pane, &None, window, cx)
329                        })
330                        .log_err()?;
331                    None
332                }
333            }
334        }
335    }
336}
337
338#[derive(Debug, PartialEq, Eq, Default, Clone)]
339pub struct SerializedPane {
340    pub(crate) active: bool,
341    pub(crate) children: Vec<SerializedItem>,
342    pub(crate) pinned_count: usize,
343}
344
345impl SerializedPane {
346    pub fn new(children: Vec<SerializedItem>, active: bool, pinned_count: usize) -> Self {
347        SerializedPane {
348            children,
349            active,
350            pinned_count,
351        }
352    }
353
354    pub async fn deserialize_to(
355        &self,
356        project: &Entity<Project>,
357        pane: &WeakEntity<Pane>,
358        workspace_id: WorkspaceId,
359        workspace: WeakEntity<Workspace>,
360        cx: &mut AsyncWindowContext,
361    ) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
362        let mut item_tasks = Vec::new();
363        let mut active_item_index = None;
364        let mut preview_item_index = None;
365        for (index, item) in self.children.iter().enumerate() {
366            let project = project.clone();
367            item_tasks.push(pane.update_in(cx, |_, window, cx| {
368                SerializableItemRegistry::deserialize(
369                    &item.kind,
370                    project,
371                    workspace.clone(),
372                    workspace_id,
373                    item.item_id,
374                    window,
375                    cx,
376                )
377            })?);
378            if item.active {
379                active_item_index = Some(index);
380            }
381            if item.preview {
382                preview_item_index = Some(index);
383            }
384        }
385
386        let mut items = Vec::new();
387        for item_handle in futures::future::join_all(item_tasks).await {
388            let item_handle = item_handle.log_err();
389            items.push(item_handle.clone());
390
391            if let Some(item_handle) = item_handle {
392                pane.update_in(cx, |pane, window, cx| {
393                    pane.add_item(item_handle.clone(), true, true, None, window, cx);
394                })?;
395            }
396        }
397
398        if let Some(active_item_index) = active_item_index {
399            pane.update_in(cx, |pane, window, cx| {
400                pane.activate_item(active_item_index, false, false, window, cx);
401            })?;
402        }
403
404        if let Some(preview_item_index) = preview_item_index {
405            pane.update(cx, |pane, cx| {
406                if let Some(item) = pane.item_for_index(preview_item_index) {
407                    pane.set_preview_item_id(Some(item.item_id()), cx);
408                }
409            })?;
410        }
411        pane.update(cx, |pane, _| {
412            pane.set_pinned_count(self.pinned_count.min(items.len()));
413        })?;
414
415        anyhow::Ok(items)
416    }
417}
418
419pub type GroupId = i64;
420pub type PaneId = i64;
421pub type ItemId = u64;
422
423#[derive(Debug, PartialEq, Eq, Clone)]
424pub struct SerializedItem {
425    pub kind: Arc<str>,
426    pub item_id: ItemId,
427    pub active: bool,
428    pub preview: bool,
429}
430
431impl SerializedItem {
432    pub fn new(kind: impl AsRef<str>, item_id: ItemId, active: bool, preview: bool) -> Self {
433        Self {
434            kind: Arc::from(kind.as_ref()),
435            item_id,
436            active,
437            preview,
438        }
439    }
440}
441
442#[cfg(test)]
443impl Default for SerializedItem {
444    fn default() -> Self {
445        SerializedItem {
446            kind: Arc::from("Terminal"),
447            item_id: 100000,
448            active: false,
449            preview: false,
450        }
451    }
452}
453
454impl StaticColumnCount for SerializedItem {
455    fn column_count() -> usize {
456        4
457    }
458}
459impl Bind for &SerializedItem {
460    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
461        let next_index = statement.bind(&self.kind, start_index)?;
462        let next_index = statement.bind(&self.item_id, next_index)?;
463        let next_index = statement.bind(&self.active, next_index)?;
464        statement.bind(&self.preview, next_index)
465    }
466}
467
468impl Column for SerializedItem {
469    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
470        let (kind, next_index) = Arc::<str>::column(statement, start_index)?;
471        let (item_id, next_index) = ItemId::column(statement, next_index)?;
472        let (active, next_index) = bool::column(statement, next_index)?;
473        let (preview, next_index) = bool::column(statement, next_index)?;
474        Ok((
475            SerializedItem {
476                kind,
477                item_id,
478                active,
479                preview,
480            },
481            next_index,
482        ))
483    }
484}
485
Served at tenant.openagents/omega Member data and write actions are omitted.