返回 DeepSeek-Reasonix
session_catalog.go
根目录 / desktop / session_catalog.go
1 package main
2
3 import (
4 "context"
5 "errors"
6 "log/slog"
7 "os"
8 "path/filepath"
9 "strings"
10 "time"
11
12 "reasonix/internal/agent"
13 "reasonix/internal/history"
14 "reasonix/internal/sessioncatalog"
15 "reasonix/internal/stats"
16 "reasonix/internal/taskcatalog"
17 )
18
19 const sessionCatalogMetadataSyncTimeout = 30 * time.Second
20
21 const desktopSessionCatalogPersistObserverKey = "desktop-session-catalog"
22
23 type desktopSessionCatalogPersistObserver struct{ app *App }
24
25 func (observer desktopSessionCatalogPersistObserver) EnqueueSessionPersist(event agent.SessionPersistEvent) bool {
26 a := observer.app
27 if a == nil || a.shuttingDown.Load() || strings.TrimSpace(event.Path) == "" {
28 return false
29 }
30 catalog := a.sessionCatalog.Load()
31 if catalog == nil {
32 return false
33 }
34 path := filepath.Clean(event.Path)
35 if event.Removed {
36 go func() {
37 ctx, cancel := context.WithTimeout(a.bootContext(), 5*time.Second)
38 defer cancel()
39 _ = catalog.RemoveSession(ctx, path, "authoritative_persist_removed")
40 }()
41 return true
42 }
43 // IndexSessionPath loads authoritative branch metadata, correcting this
44 // global fallback to the real project scope. Exact-path requests also make
45 // bot/controller saves visible without waiting for the directory sweep.
46 return catalog.RequestIndexSession(sessioncatalog.DirectoryTarget{
47 Path: filepath.Dir(path), Scope: "global",
48 }, path)
49 }
50
51 type SessionCatalogStatus struct {
52 State string `json:"state"`
53 Mode string `json:"mode"`
54 Revision uint64 `json:"revision"`
55 Indexed int64 `json:"indexed"`
56 Total int64 `json:"total"`
57 RepairPending int64 `json:"repairPending"`
58 RepairActive int64 `json:"repairActive"`
59 RepairDeferred int64 `json:"repairDeferred"`
60 RepairBlocked int64 `json:"repairBlocked"`
61 NextRepairAt int64 `json:"nextRepairAt,omitempty"`
62 CanRebuild bool `json:"canRebuild"`
63 LastError string `json:"lastError,omitempty"`
64 QuarantinedPath string `json:"quarantinedPath,omitempty"`
65 }
66
67 type ProjectTreeSnapshot struct {
68 Revision uint64 `json:"revision"`
69 WorkspaceGeneration *uint64 `json:"workspaceGeneration,omitempty"`
70 Projects []ProjectNode `json:"projects"`
71 Catalog SessionCatalogStatus `json:"catalog"`
72 Indexed int64 `json:"indexed"`
73 Total int64 `json:"total"`
74 IndexingDone bool `json:"indexingDone"`
75 }
76
77 type ProjectTopicPageRequest struct {
78 Scope string `json:"scope"`
79 WorkspaceRoot string `json:"workspaceRoot,omitempty"`
80 Cursor string `json:"cursor,omitempty"`
81 Limit int `json:"limit,omitempty"`
82 Query string `json:"query,omitempty"`
83 TimeFilter string `json:"timeFilter,omitempty"`
84 SortMode string `json:"sortMode,omitempty"`
85 GroupFilter string `json:"groupFilter,omitempty"`
86 GroupID string `json:"groupId,omitempty"`
87 ExcludePinned bool `json:"excludePinned,omitempty"`
88
89 groupIncludeJSON string
90 groupExcludeJSON string
91 groupCursorBind string
92 groupInclude map[string]struct{}
93 groupExclude map[string]struct{}
94 groupSelected *desktopGroup
95 groupAll []desktopGroup
96 pinnedOnly bool
97 timeCutoff int64
98 readContext context.Context
99 metadataSnapshot *[]ProjectNode
100 readAllSources bool
101 readAvailability *catalogWorkspaceAvailability
102 }
103
104 type ProjectTopicKey struct {
105 Scope string `json:"scope"`
106 WorkspaceRoot string `json:"workspaceRoot,omitempty"`
107 TopicID string `json:"topicId"`
108 // Path optionally binds topic-wide recovery actions to one physical lineage.
109 // Older frontends omit it and remain compatible when the topic has one group.
110 Path string `json:"path,omitempty"`
111 // RecordClassification is set only by the recovery-event coordinator after
112 // a catalog revision. Ordinary History reads remain diagnostic-free.
113 RecordClassification bool `json:"recordClassification,omitempty"`
114 }
115
116 type ProjectTopicPage struct {
117 SnapshotID string `json:"snapshotId,omitempty"`
118 SnapshotExpiresAt int64 `json:"snapshotExpiresAt,omitempty"`
119 Items []ProjectNode `json:"items"`
120 NextCursor string `json:"nextCursor,omitempty"`
121 Revision uint64 `json:"revision"`
122 Complete bool `json:"complete"`
123 ReadyDirectories int `json:"readyDirectories"`
124 PendingDirectories int `json:"pendingDirectories"`
125 FailedDirectories int `json:"failedDirectories"`
126 }
127
128 type ProjectTreeChangedV2 struct {
129 Revision uint64 `json:"revision"`
130 Roots []string `json:"roots"`
131 Reason string `json:"reason"`
132 }
133
134 // ProjectRuntimeTopic is one process-local runtime projected onto its stable
135 // logical topic identity. The catalog remains the authority for persisted
136 // history; this projection is the authority for what this process is running.
137 type ProjectRuntimeTopic struct {
138 Scope string `json:"scope"`
139 WorkspaceRoot string `json:"workspaceRoot,omitempty"`
140 Node ProjectNode `json:"node"`
141 }
142
143 // ProjectTreeRuntimeSnapshot is a replace-all, idempotent runtime projection.
144 // Its revision is independent from the session catalog revision so clients can
145 // order ownership/status changes without reloading any catalog page.
146 type ProjectTreeRuntimeSnapshot struct {
147 Revision uint64 `json:"revision"`
148 Topics []ProjectRuntimeTopic `json:"topics"`
149 }
150
151 func flushDesktopDerivedCatalogs(ctx context.Context) error {
152 var first error
153 if err := history.FlushSharedCatalog(ctx); err != nil && first == nil {
154 first = err
155 }
156 if err := history.CloseSharedCatalog(ctx); err != nil && first == nil {
157 first = err
158 }
159 if err := stats.CloseUsageCatalogs(ctx); err != nil && first == nil {
160 first = err
161 }
162 if err := taskcatalog.ShutdownShared(ctx); err != nil && first == nil {
163 first = err
164 }
165 return first
166 }
167
168 func sessionCatalogStatus(status sessioncatalog.Status) SessionCatalogStatus {
169 return SessionCatalogStatus{
170 State: string(status.State),
171 Mode: string(status.Mode),
172 Revision: status.Revision,
173 Indexed: status.Indexed,
174 Total: status.Total,
175 RepairPending: status.RepairPending,
176 RepairActive: status.RepairActive,
177 RepairDeferred: status.RepairDeferred,
178 RepairBlocked: status.RepairBlocked,
179 NextRepairAt: status.NextRepairAt,
180 CanRebuild: status.RepairActive == 0 && (status.State == sessioncatalog.StateDegraded ||
181 (status.State == sessioncatalog.StateReady && strings.TrimSpace(status.LastError) != "")),
182 LastError: status.LastError,
183 QuarantinedPath: status.QuarantinedPath,
184 }
185 }
186
187 func (a *App) currentSessionCatalogStatus() SessionCatalogStatus {
188 if a == nil {
189 return SessionCatalogStatus{State: string(sessioncatalog.StateDegraded), Mode: string(sessioncatalog.ModeMemory)}
190 }
191 if catalog := a.sessionCatalog.Load(); catalog != nil {
192 status := sessionCatalogStatus(catalog.Status())
193 if a.catalogRebuilding.Load() {
194 status.State = string(sessioncatalog.StateRebuilding)
195 status.CanRebuild = false
196 }
197 return status
198 }
199 if a.catalogRebuilding.Load() {
200 return SessionCatalogStatus{State: string(sessioncatalog.StateRebuilding)}
201 }
202 return SessionCatalogStatus{State: string(sessioncatalog.StateOpening)}
203 }
204
205 func (a *App) startSessionCatalog() {
206 if a == nil || a.shuttingDown.Load() {
207 return
208 }
209 a.catalogLifecycleMu.Lock()
210 if a.catalogCancel != nil {
211 a.catalogLifecycleMu.Unlock()
212 return
213 }
214 ctx, cancel := context.WithCancel(a.bootContext())
215 done := make(chan struct{})
216 initialReconcileDone := make(chan struct{})
217 metadataRequests := make(chan struct{}, 1)
218 a.catalogCancel = cancel
219 a.catalogDone = done
220 a.catalogInitialReconcileDone = initialReconcileDone
221 a.catalogMetadataRequests = metadataRequests
222 a.catalogLifecycleMu.Unlock()
223 history.RegisterSessionPersistObserver(desktopSessionCatalogPersistObserverKey, desktopSessionCatalogPersistObserver{app: a})
224
225 go func() {
226 defer close(done)
227 a.runSessionCatalog(ctx, initialReconcileDone, metadataRequests)
228 }()
229 }
230
231 // sessionCatalogClose is one stop's release of the catalog handles it took.
232 type sessionCatalogClose struct {
233 done chan struct{}
234 err error
235 }
236
237 // stopSessionCatalog reports whether every catalog handle this App opened is
238 // released. A close that outlives its deadline keeps running and stays owed:
239 // the next stop waits for it rather than reporting a handle it has forgotten.
240 func (a *App) stopSessionCatalog(timeout time.Duration) bool {
241 if a == nil {
242 return true
243 }
244 deadline := time.Now().Add(timeout)
245 closing := &sessionCatalogClose{done: make(chan struct{})}
246 a.catalogLifecycleMu.Lock()
247 cancel := a.catalogCancel
248 done := a.catalogDone
249 earlier := a.catalogClosing
250 a.catalogCancel = nil
251 a.catalogDone = nil
252 a.catalogInitialReconcileDone = nil
253 a.catalogMetadataRequests = nil
254 a.catalogClosing = closing
255 if cancel != nil {
256 cancel()
257 }
258 catalog := a.sessionCatalog.Swap(nil)
259 // Pair nil publication with the request-side locked recheck. Keep the
260 // lifecycle lock through detachment so replacement publication cannot
261 // enter this retired-job snapshot.
262 a.catalogReconcileMu.Lock()
263 reconcileDone := make([]<-chan struct{}, 0, len(a.catalogReconcileJobs))
264 for _, job := range a.catalogReconcileJobs {
265 job.cancel()
266 reconcileDone = append(reconcileDone, job.done)
267 }
268 clear(a.catalogReconcileJobs)
269 a.catalogReconcileMu.Unlock()
270 a.catalogLifecycleMu.Unlock()
271 go func() {
272 defer close(closing.done)
273 // Cancellation releases queued discovery waits. Bound any synchronous
274 // admission still in flight by the original close deadline.
275 for _, reconciled := range reconcileDone {
276 if !waitChannelBefore(reconciled, deadline) {
277 break
278 }
279 }
280 if catalog != nil {
281 closing.err = catalog.Close(context.Background())
282 }
283 if done != nil {
284 <-done
285 }
286 if earlier != nil {
287 <-earlier.done
288 }
289 }()
290 return waitChannelBefore(closing.done, deadline) && closing.err == nil
291 }
292
293 func waitChannelBefore(done <-chan struct{}, deadline time.Time) bool {
294 remaining := time.Until(deadline)
295 if remaining <= 0 {
296 return false
297 }
298 timer := time.NewTimer(remaining)
299 defer timer.Stop()
300 select {
301 case <-done:
302 return true
303 case <-timer.C:
304 return false
305 }
306 }
307
308 func (a *App) cancelAllTabBuilds() {
309 if a == nil {
310 return
311 }
312 a.mu.Lock()
313 for _, tab := range a.tabs {
314 a.supersedeTabBuildLocked(tab)
315 }
316 for _, tab := range a.detachedSessions {
317 a.supersedeTabBuildLocked(tab)
318 }
319 a.mu.Unlock()
320 }
321
322 func listCatalogSessionsForDirectory(ctx context.Context, catalog *sessioncatalog.Catalog,
323 target sessioncatalog.DirectoryTarget, directory string) ([]sessioncatalog.SessionRecord, error) {
324 for range 2 {
325 records := []sessioncatalog.SessionRecord{}
326 cursor := ""
327 for {
328 page, err := catalog.ListSessions(ctx, sessioncatalog.SessionPageRequest{Scope: target.Scope,
329 WorkspaceRoot: target.WorkspaceRoot, Directory: directory, Cursor: cursor, Limit: sessioncatalog.MaxLimit})
330 if err != nil {
331 return nil, err
332 }
333 if page.StaleCursor {
334 break
335 }
336 records = append(records, page.Items...)
337 if page.NextCursor == "" {
338 return records, nil
339 }
340 cursor = page.NextCursor
341 }
342 }
343 return []sessioncatalog.SessionRecord{}, nil
344 }
345
346 // Metadata-only projection bounds each writer slice inside the catalog. A
347 // whole-observation timeout would repeatedly restart large registries at their
348 // first batch. Older catalog modes retain their whole-transaction deadline.
349 func (a *App) syncSessionCatalogMetadataBounded(ctx context.Context, catalog *sessioncatalog.Catalog) error {
350 if catalog.MetadataOnly() {
351 return a.syncSessionCatalogMetadata(ctx, catalog)
352 }
353 ctx, cancel := context.WithTimeout(ctx, sessionCatalogMetadataSyncTimeout)
354 defer cancel()
355 return a.syncSessionCatalogMetadata(ctx, catalog)
356 }
357
358 func (a *App) syncSessionCatalogMetadata(ctx context.Context, catalog *sessioncatalog.Catalog) error {
359 f := loadProjectsFile()
360 deleted := map[string]bool{}
361 for _, topicID := range f.DeletedTopics {
362 deleted[topicID] = true
363 }
364 projects := []sessioncatalog.ProjectRecord{{
365 Scope: "global", Title: strings.TrimSpace(f.GlobalTitle), Color: normalizeProjectColor(f.GlobalColor),
366 }}
367 if projects[0].Title == "" {
368 projects[0].Title = "Global"
369 }
370 topics := []sessioncatalog.TopicMetadata{}
371 appendTopics := func(scope, root string, ids, pinnedIDs []string, manualOrder bool) {
372 titles := loadTopicTitles(root)
373 sources := loadTopicTitleSources(root)
374 created := loadTopicCreatedAts(root)
375 ordered := pinnedTopicIDs(orderedTopicIDs(ids, titles), pinnedIDs)
376 for index, topicID := range ordered {
377 if deleted[topicID] {
378 continue
379 }
380 title := strings.TrimSpace(titles[topicID])
381 if title == "" {
382 title = defaultTopicTitle
383 }
384 sortOrder := -1
385 if manualOrder {
386 sortOrder = index
387 }
388 topics = append(topics, sessioncatalog.TopicMetadata{
389 Scope: scope, WorkspaceRoot: root, TopicID: topicID, Title: title,
390 TitleSource: sources[topicID], Pinned: containsDesktopString(pinnedIDs, topicID),
391 SortOrder: sortOrder, CreatedAt: topicCreatedAtForTree(created, topicID),
392 })
393 }
394 }
395 appendTopics("global", "", f.GlobalTopics, f.GlobalPinnedTopics, f.GlobalManualTopicOrder)
396 for index, project := range f.Projects {
397 title := strings.TrimSpace(project.Title)
398 if title == "" {
399 title = workspaceName(project.Root)
400 }
401 projects = append(projects, sessioncatalog.ProjectRecord{
402 Scope: "project", WorkspaceRoot: project.Root, Title: title, Color: project.Color,
403 Pinned: containsDesktopString(f.PinnedProjects, project.Root), SortOrder: index,
404 })
405 appendTopics("project", project.Root, project.Topics, project.PinnedTopics, project.ManualTopicOrder)
406 }
407 return catalog.SyncMetadata(ctx, projects, topics)
408 }
409
410 func (a *App) emitProjectTreeChangedV2(revision uint64, roots []string, reason string) {
411 if roots == nil {
412 roots = []string{}
413 }
414 a.emitRuntimeEvent("project-tree:changed-v2", ProjectTreeChangedV2{Revision: a.unifiedProjectRevision(revision), Roots: roots, Reason: reason})
415 // One-release compatibility event. Its wrapper is catalog-only, so legacy
416 // frontends refresh without making current frontends rebuild the whole tree
417 // after they already consumed the targeted v2 revision.
418 a.emitRuntimeEvent("project-tree:changed", map[string]string{"reason": "catalog-v2"})
419 }
420
421 type desktopCatalogReconcileJob struct {
422 target sessioncatalog.DirectoryTarget
423 dirty bool
424 catalog *sessioncatalog.Catalog
425 ctx context.Context
426 cancel context.CancelFunc
427 done chan struct{}
428 }
429
430 func (a *App) requestSessionCatalogReconcile(dir string) bool {
431 catalog := a.sessionCatalog.Load()
432 if catalog == nil || a.shuttingDown.Load() || strings.TrimSpace(dir) == "" {
433 return false
434 }
435 clean := filepath.Clean(dir)
436 key := projectRootKey(clean)
437 target := sessioncatalog.DirectoryTarget{Path: clean, Scope: "global"}
438 for _, candidate := range a.sessionCatalogTargets() {
439 if sameDesktopPath(candidate.Path, clean) {
440 target = candidate
441 break
442 }
443 }
444 a.catalogReconcileMu.Lock()
445 if a.sessionCatalog.Load() != catalog || a.shuttingDown.Load() {
446 a.catalogReconcileMu.Unlock()
447 return false
448 }
449 if a.catalogReconcileJobs == nil {
450 a.catalogReconcileJobs = map[string]*desktopCatalogReconcileJob{}
451 }
452 if job := a.catalogReconcileJobs[key]; job != nil && job.catalog == catalog && job.ctx.Err() == nil {
453 job.target = target
454 job.dirty = true
455 a.catalogReconcileMu.Unlock()
456 return true
457 }
458 ctx, cancel := context.WithCancel(a.bootContext())
459 job := &desktopCatalogReconcileJob{target: target, catalog: catalog, ctx: ctx, cancel: cancel, done: make(chan struct{})}
460 a.catalogReconcileJobs[key] = job
461 a.catalogReconcileMu.Unlock()
462 go a.runSessionCatalogReconcile(key, job)
463 return true
464 }
465
466 func (a *App) runSessionCatalogReconcile(key string, job *desktopCatalogReconcileJob) {
467 defer func() {
468 job.cancel()
469 a.catalogReconcileMu.Lock()
470 if a.catalogReconcileJobs[key] == job {
471 delete(a.catalogReconcileJobs, key)
472 }
473 a.catalogReconcileMu.Unlock()
474 close(job.done)
475 }()
476 for {
477 a.catalogReconcileMu.Lock()
478 if a.catalogReconcileJobs[key] != job || job.ctx.Err() != nil || a.shuttingDown.Load() {
479 a.catalogReconcileMu.Unlock()
480 return
481 }
482 target := job.target
483 job.dirty = false
484 a.catalogReconcileMu.Unlock()
485 if a.catalogReconcileHook != nil {
486 a.catalogReconcileHook(target)
487 }
488 // Discovery projects metadata only. Retired or invalidated owners cannot
489 // settle paused tokens, so bind scheduling and completion to this job.
490 if job.ctx.Err() == nil && a.sessionCatalog.Load() == job.catalog {
491 select {
492 case <-job.catalog.Invalidated():
493 job.cancel()
494 default:
495 if settled, accepted := job.catalog.ScheduleReconcile(target); accepted {
496 select {
497 case <-settled:
498 case <-job.ctx.Done():
499 case <-job.catalog.Invalidated():
500 job.cancel()
501 }
502 }
503 }
504 }
505
506 a.catalogReconcileMu.Lock()
507 if a.catalogReconcileJobs[key] == job && job.dirty && job.ctx.Err() == nil &&
508 a.sessionCatalog.Load() == job.catalog && !a.shuttingDown.Load() {
509 a.catalogReconcileMu.Unlock()
510 continue
511 }
512 if a.catalogReconcileJobs[key] == job {
513 delete(a.catalogReconcileJobs, key)
514 }
515 a.catalogReconcileMu.Unlock()
516 if a.catalogReconcileDoneHook != nil {
517 a.catalogReconcileDoneHook(target)
518 }
519 return
520 }
521 }
522
523 func sessionDirectoryForPath(path string) string {
524 path = strings.TrimSpace(path)
525 if path == "" {
526 return ""
527 }
528 clean := filepath.Clean(path)
529 if clean == "." || filepath.Base(clean) == clean {
530 return ""
531 }
532 return filepath.Dir(clean)
533 }
534
535 func (a *App) saveTabSessionMetaSnapshotAndIndex(snap tabSessionMetaSnapshot) error {
536 if err := saveTabSessionMetaSnapshot(snap); err != nil {
537 return err
538 }
539 // Transcript saves index through the observer; enqueue again after the
540 // sidecar commit so scope and title changes are visible without a full scan.
541 a.requestSessionCatalogIndexPath(snap.scope, snap.workspaceRoot, string(snap.path))
542 return nil
543 }
544
545 func discardTransientBlankSessionArtifacts(path string) bool {
546 if strings.TrimSpace(path) == "" {
547 return false
548 }
549 if err := removeDesktopSessionArtifacts(path); err != nil {
550 slog.Warn("desktop: discard transient blank session artifacts failed", "path", path, "err", err)
551 return false
552 }
553 return true
554 }
555
556 func (a *App) requestSessionCatalogPath(scope, workspaceRoot, path string) {
557 if strings.TrimSpace(path) != "" {
558 _ = history.PersistObserver().EnqueueSessionPersist(agent.SessionPersistEvent{Path: path, Rewrite: true})
559 }
560 a.requestSessionCatalogIndexPath(scope, workspaceRoot, path)
561 }
562
563 // requestSessionCatalogIndexPath publishes one committed session/sidecar
564 // change without walking its directory. A saturated exact-path queue falls
565 // back to a scoped reconcile so the disposable projection still converges.
566 func (a *App) requestSessionCatalogIndexPath(scope, workspaceRoot, path string) {
567 catalog := a.sessionCatalog.Load()
568 if catalog == nil || a.shuttingDown.Load() || strings.TrimSpace(path) == "" {
569 return
570 }
571 target := sessioncatalog.DirectoryTarget{
572 Path: sessionDirectoryForPath(path), Scope: scope, WorkspaceRoot: workspaceRoot,
573 }
574 if !catalog.RequestIndexSession(target, path) {
575 a.requestSessionCatalogReconcile(target.Path)
576 }
577 }
578
579 func (a *App) removeSessionCatalogPath(path, reason string) {
580 if strings.TrimSpace(path) == "" {
581 return
582 }
583 _ = history.PersistObserver().EnqueueSessionPersist(agent.SessionPersistEvent{Path: path, Removed: true})
584 catalog := a.sessionCatalog.Load()
585 if catalog == nil {
586 return
587 }
588 ctx, cancel := context.WithTimeout(a.bootContext(), 150*time.Millisecond)
589 defer cancel()
590 if err := catalog.RemoveSession(ctx, path, reason); err != nil && !errors.Is(err, context.Canceled) {
591 slog.Debug("desktop: remove session catalog row", "err", err)
592 }
593 }
594
595 func (a *App) requestSessionCatalogMetadataSync() {
596 if a.shuttingDown.Load() {
597 return
598 }
599 a.catalogLifecycleMu.Lock()
600 requests := a.catalogMetadataRequests
601 a.catalogLifecycleMu.Unlock()
602 // Every source shares the watcher's worker, including user edits. A nil
603 // channel before startup/after shutdown simply has no receiver to wake.
604 select {
605 case requests <- struct{}{}:
606 default:
607 }
608 }
609
610 func (a *App) GetProjectTreeSnapshot() (ProjectTreeSnapshot, error) {
611 // Membership/visibility and its generation come from one verified registry
612 // snapshot. Never silently replace it with legacy membership on read failure.
613 state, versions, err := a.workspaceRegistry().LoadProjectionWithVersions(a.bootContext())
614 if err != nil {
615 return ProjectTreeSnapshot{Projects: []ProjectNode{}}, err
616 }
617 f := loadProjectsFile()
618 deleted := make(map[string]bool, len(f.DeletedTopics))
619 for _, topicID := range f.DeletedTopics {
620 deleted[topicID] = true
621 }
622 projects := []ProjectNode{}
623 if strings.TrimSpace(f.GlobalTitle) != "" || len(f.GlobalTopics) > 0 || len(f.Projects) == 0 {
624 label := strings.TrimSpace(f.GlobalTitle)
625 if label == "" {
626 label = "Global"
627 }
628 projects = append(projects, ProjectNode{
629 Key: "global_folder", Kind: "global_folder", Label: label,
630 Root: globalWorkspaceRoot(), ProjectColor: normalizeProjectColor(f.GlobalColor),
631 Children: a.pinnedTopicShells("global", "", f.GlobalTopics, f.GlobalPinnedTopics, f.GlobalColor, deleted),
632 })
633 }
634 for _, project := range f.Projects {
635 label := strings.TrimSpace(project.Title)
636 if label == "" {
637 label = workspaceName(project.Root)
638 }
639 projects = append(projects, ProjectNode{
640 Key: "project_" + project.Root, Kind: "project", Label: label,
641 Root: project.Root, ProjectColor: project.Color,
642 Pinned: containsDesktopString(f.PinnedProjects, project.Root),
643 Children: a.pinnedTopicShells("project", project.Root, project.Topics, project.PinnedTopics, project.Color, deleted),
644 })
645 }
646 // Remote projects (pinned via the connection wizard) render as project
647 // groups too; the Remote ref swaps the folder icon for a cloud icon.
648 if remoteNodes, err := a.remoteProjectNodes(); err == nil {
649 projects = append(projects, remoteNodes...)
650 }
651 projects = a.mergeCanonicalWorkspaceShellsFromProjection(projects, state, versions)
652 projects = applyPinnedProjectOrder(applyProjectTreeOrder(projects, f.SidebarOrder), f.PinnedProjects)
653 status := a.currentSessionCatalogStatus()
654 return ProjectTreeSnapshot{
655 Revision: status.Revision + state.Generation, WorkspaceGeneration: &state.Generation, Projects: projects, Catalog: status,
656 Indexed: status.Indexed, Total: status.Total,
657 IndexingDone: a.catalogIndexingDone(status),
658 }, nil
659 }
660
661 // pinnedTopicShells keeps pinned conversations available in the metadata-only
662 // project snapshot. Ordinary topic pages remain lazy, but a collapsed folder
663 // must not hide its pinned conversations until the user expands it.
664 func (a *App) pinnedTopicShells(scope, workspaceRoot string, topicIDs, pinnedIDs []string, projectColor string, deleted map[string]bool) []ProjectNode {
665 if len(pinnedIDs) == 0 {
666 return []ProjectNode{}
667 }
668 titles := loadTopicTitles(workspaceRoot)
669 sources := loadTopicTitleSources(workspaceRoot)
670 created := loadTopicCreatedAts(workspaceRoot)
671 available := make(map[string]bool, len(topicIDs)+len(titles))
672 for _, topicID := range orderedTopicIDs(topicIDs, titles) {
673 available[topicID] = true
674 }
675 kind := "topic"
676 if scope != "project" {
677 kind = "global_topic"
678 }
679 out := make([]ProjectNode, 0, len(pinnedIDs))
680 for _, topicID := range uniqueStrings(pinnedIDs) {
681 if !available[topicID] || deleted[topicID] {
682 continue
683 }
684 title := strings.TrimSpace(titles[topicID])
685 if title == "" {
686 title = defaultTopicTitle
687 }
688 out = append(out, ProjectNode{
689 Key: kind + "_" + topicID, Kind: kind,
690 Label: a.localizedTopicTitle(title, sources[topicID]), Root: workspaceRoot,
691 TopicID: topicID, ProjectColor: normalizeProjectColor(projectColor),
692 CreatedAt: topicCreatedAtForTree(created, topicID), Pinned: true,
693 TurnsState: string(sessioncatalog.TurnsUnknown), Health: string(sessioncatalog.HealthOK),
694 Children: []ProjectNode{},
695 })
696 }
697 return out
698 }
699
700 func (a *App) catalogIndexingDone(status SessionCatalogStatus) bool {
701 if status.State != string(sessioncatalog.StateReady) || status.RepairActive > 0 {
702 return false
703 }
704 catalog := a.sessionCatalog.Load()
705 if catalog == nil {
706 return false
707 }
708 ctx, cancel := a.catalogReadContext()
709 defer cancel()
710 targets := a.sessionCatalogTargets()
711 if len(targets) == 0 {
712 return false
713 }
714 sawExisting := false
715 for _, target := range targets {
716 if _, err := os.Stat(target.Path); os.IsNotExist(err) {
717 continue
718 }
719 sawExisting = true
720 if !catalog.DirectoryScanReady(ctx, target.Path) {
721 return false
722 }
723 }
724 return sawExisting
725 }
726
726 lines GO