返回 DeepSeek-Reasonix
tabs.go
根目录 / desktop / tabs.go
1 package main
2
3 import (
4 "context"
5 "crypto/rand"
6 "crypto/sha256"
7 "encoding/hex"
8 "encoding/json"
9 "errors"
10 "fmt"
11 "log/slog"
12 "maps"
13 "os"
14 "path/filepath"
15 "reasonix/internal/agent"
16 "reasonix/internal/billing"
17 "reasonix/internal/boot"
18 "reasonix/internal/config"
19 "reasonix/internal/control"
20 "reasonix/internal/event"
21 "reasonix/internal/eventwire"
22 "reasonix/internal/extension/providerext"
23 "reasonix/internal/fileutil"
24 "reasonix/internal/notify"
25 "reasonix/internal/provider"
26 "reasonix/internal/session"
27 "reasonix/internal/sessiontitle"
28 "reasonix/internal/store"
29 "reasonix/internal/turnevent"
30 "slices"
31 "sort"
32 "strings"
33 "sync"
34 "sync/atomic"
35 "time"
36 "unicode"
37 )
38
39 // WorkspaceTab
40
41 // tabDisplayState follows one live runtime across visible, detached, and
42 // reattached WorkspaceTab wrappers. Keeping one shared state pointer closes the
43 // handoff window where an event already routed to the old wrapper could append
44 // after a clone copied its buffers.
45 type tabDisplayState struct {
46 mu sync.Mutex
47 planner displayTurnBuffer
48 executor displayTurnBuffer
49 pendingWrites []*pendingDisplayWrite
50 persistRunning bool
51 }
52
53 const displayPersistRetryLimit = 4
54
55 var errNoDesktopChatModel = errors.New("no desktop chat model is available; add a chat-capable provider in Settings > Model > Access")
56
57 func resolveDraftCreateModelStrict(cfg *config.Config, model string) (string, error) {
58 if providerext.PluginRefOwner(model) != "" {
59 return model, nil
60 }
61 resolved, ok := cfg.ResolveModel(model)
62 if !ok {
63 return "", fmt.Errorf("%w: %q", boot.ErrUnknownModel, model)
64 }
65 return resolved.Name + "/" + resolved.Model, nil
66 }
67
68 type pendingDisplayWrite struct {
69 dir string
70 sessionPath string
71 userContent string
72 messages []HistoryMessage
73 persist func(string, string, string, []HistoryMessage) error
74 onPersisted func()
75 onRetry func()
76 }
77
78 // WorkspaceTab is one open conversation tab in the desktop. Each tab owns an
79 // independent controller (its own agent, session, tool registry, plugin host,
80 // memory, permissions) scoped to a workspace root, so multiple projects and
81 // topics can be active concurrently without interfering.
82 type WorkspaceTab struct {
83 ID string // stable random id
84 Scope string // "project" | "global"
85 WorkspaceRoot string // project root dir (empty for global)
86 SessionWorkspace desktopTabWorkspace // stable Workspace registry identity
87 SharedHostKey string // opaque key for the shared plugin host (set by buildTabController)
88 TopicID string // topic within the project
89 TopicTitle string // display title
90 topicTitleSource string // auto or manual; controls localization at API boundaries
91 SessionPath string // exact .jsonl file this tab continues
92 SessionID string // immutable v3 identity; empty for legacy/read-only tabs
93 nativeSessionSelection
94 PendingCreateOperationID string // durable create reservation used before the first turn
95 draftAdmission *draftAdmissionProfile
96 persistenceExtra map[string]json.RawMessage // unknown desktop-tabs.json fields retained across rewrites
97 SessionGeneration uint64 // bumps on session rotation (clear/new); frontend hydrate identity
98 ReadOnly bool // true for external channel transcripts opened for browsing
99 Takeover struct{ Spectator bool } // handoff state grouped by its cross-runtime lifetime
100 Ctrl control.SessionAPI // nil while booting / on error
101 Label string // model label (for the tab badge)
102 Ready bool // true once boot.Build completes
103 StartupErr string // build error, surfaced to the frontend
104 HistoricalSource *SessionSourceRef // immutable, pending explicit preparation after restore
105 StartupErrLeaseHeld bool // true when StartupErr can be retried after a session lease releases
106 modelApplication tabModelApplicationState // guarded by App.mu; never persisted
107 runtimeID string // process-local SessionRuntime registry identity
108 sessionLease *agent.SessionLease
109 sessionLeaseMu sync.Mutex
110 sessionLeaseKey atomic.Pointer[string] // lock-free mirror; updated with sessionLease under sessionLeaseMu
111 sink *tabEventSink // routes events with this tab's ID
112 buildCancel context.CancelFunc // cancels in-flight boot for tabs removed before Ready
113 buildGeneration uint64 // identifies the current in-flight build
114 // buildDone is closed exactly once when the build that owns buildDoneGen
115 // terminates (success, failure, or superseded abandon). Topic-activation
116 // completions wait on it to learn that the controller build finished
117 // without polling. Guarded by App.mu alongside buildGeneration; always
118 // nil-ed after close so a replacement build can install a fresh channel.
119 buildDone chan struct{}
120 buildDoneGen uint64
121 buildExecution *tabBuildExecution // actual completion, never closed by supersession
122 buildExecutions map[*tabBuildExecution]struct{} // includes superseded builds until actual exit
123 removed bool // set when the visible tab is pruned/closed before build completes
124 reconcileMu sync.Mutex // serializes stale controller workspace repair for this tab
125 turnStartMu sync.Mutex // serializes foreground turn admission for this tab
126
127 ActivityStatus string // transient project-tree status for the in-flight turn
128
129 saveMu sync.Mutex
130 saving bool
131 saveAgain bool
132 saveFailures int
133 // lastAutosaveWarnAt debounces the user-facing autosave-failure notice:
134 // a persistently failing disk (AV hold, full volume) otherwise emits a
135 // chat warning for every completed turn. Logs are never debounced.
136 lastAutosaveWarnAt time.Time
137
138 // closing is set under saveMu when the tab is being torn down. Once set,
139 // tabSnapshotLoop stops taking new snapshot work and CloseTab waits on
140 // saveCond until any in-flight snapshot finishes - so no background
141 // snapshot can write a session file back to disk after CloseTab returns.
142 // Without this, deleting a just-closed session races that write and the
143 // session "resurrects" (#4384).
144 closing bool
145 saveCond *sync.Cond
146
147 // readTelemetry tracks files read during this tab's session.
148 readTelemetry []readFileRecord
149 usageTelemetry sessionUsageStats
150 // runtimeCostQuote is an automatic wallet-currency hint for the live tab.
151 // It is deliberately outside usageTelemetry so it cannot be persisted into
152 // telemetry/history or become configuration. Guarded by telemMu.
153 runtimeCostDisplayCurrency string
154 runtimeCostQuote *billing.CostQuote
155 runtimeCostGeneration uint64 // invalidates stale wallet responses
156 // telemetrySessionKey is the sessionRuntimeKey the telemetry above belongs
157 // to. Controller-side session rotations (typed /new, bot /reset) bypass the
158 // App bindings, so telemetry writers and readers re-key through
159 // syncTelemetryToSession before trusting the in-memory totals — otherwise a
160 // previous session's cost keeps accumulating under the new session and gets
161 // persisted into its sidecar (#5850).
162 telemetrySessionKey string
163 telemMu sync.Mutex
164
165 // Display-only output belongs to the live runtime, not a particular visible
166 // tab wrapper. detach/reattach paths share this state before rebinding the
167 // event sink so output cannot fall into a discarded wrapper.
168 displayStateMu sync.Mutex
169 displayState *tabDisplayState
170
171 model string // active model ref (for meta)
172 effort *string
173 qualityFloor string // fixed standard compatibility value
174 mode string // "normal" | "plan" | "yolo" | "plan-yolo"; yolo/full access is runtime-only
175 goal string
176 toolApprovalMode string
177 disabledMCP map[string]ServerView
178 mcpOrder []string
179 lastBuildResult *boot.BuildResult // incremental extension reload
180
181 PinnedFiles []string
182 pendingLegacyPinnedFiles []string // round-tripped until the session sidecar publishes
183 pinnedFilesMu sync.RWMutex
184
185 // metaExtras caches the expensive MetaForTab fields (git branch, image
186 // input capability) computed off the request path by
187 // refreshTabMetaExtras. Lock-free reads keep MetaForTab synchronous and
188 // cheap; refresh dedup goes through metaExtrasRefreshing.
189 metaExtras atomic.Pointer[tabMetaExtras]
190 metaExtrasRefreshing atomic.Bool
191 }
192
193 const (
194 topicStatusThinking = "thinking"
195 topicStatusStreaming = "streaming"
196 topicStatusWaitingConfirmation = "waiting_confirmation"
197 topicStatusBackgroundJob = "background_job"
198 topicStatusPaused = "paused"
199 topicStatusError = "error"
200 // topicStatusDivergedRecovery marks a topic holding two or more independent
201 // recovery branches. It is informational: the user picks which to keep, so
202 // it must not gate archiving the way live runtime states do.
203 topicStatusDivergedRecovery = "diverged_recovery"
204 )
205
206 type readFileRecord struct {
207 Path string `json:"path"`
208 Turn int `json:"turn"`
209 Time int64 `json:"time"`
210 Offset int `json:"offset,omitempty"`
211 Limit int `json:"limit,omitempty"`
212 Truncated bool `json:"truncated,omitempty"`
213 }
214
215 type sessionUsageStats struct {
216 PromptTokens int `json:"promptTokens"`
217 CompletionTokens int `json:"completionTokens"`
218 TotalTokens int `json:"totalTokens"`
219 ReasoningTokens int `json:"reasoningTokens"`
220 CacheHitTokens int `json:"cacheHitTokens"`
221 CacheMissTokens int `json:"cacheMissTokens"`
222 CacheWriteTokens int `json:"cacheWriteTokens,omitempty"`
223 // CacheWriteBilledTokens preserves provider-specific cache-write pricing
224 // across persisted telemetry repricing without changing hit-rate totals.
225 CacheWriteBilledTokens float64 `json:"cacheWriteBilledTokens,omitempty"`
226 Estimated bool `json:"estimated,omitempty"`
227 // LastUsedTokens is the executor-reported context fill (prompt+completion)
228 // from the most recent turn. It is persisted so the status bar / context
229 // panel can show a meaningful fill percentage after a session rebind
230 // rebuilds the controller (which resets the in-memory executor state).
231 LastUsedTokens int `json:"lastUsedTokens,omitempty"`
232 // Per-turn token breakdown from the most recent turn. Persisted separately
233 // from the cumulative totals above so the context-panel donut chart and
234 // type breakdown survive a session rebind (which resets executor.LastUsage).
235 LastPromptTokens int `json:"lastPromptTokens,omitempty"`
236 LastCompletionTokens int `json:"lastCompletionTokens,omitempty"`
237 LastReasoningTokens int `json:"lastReasoningTokens,omitempty"`
238 LastCacheHitTokens int `json:"lastCacheHitTokens,omitempty"`
239 LastCacheMissTokens int `json:"lastCacheMissTokens,omitempty"`
240 LastEstimated bool `json:"lastEstimated,omitempty"`
241 RequestCount int `json:"requestCount"`
242 ElapsedMs int64 `json:"elapsedMs"`
243 SessionCost float64 `json:"sessionCost,omitempty"`
244 SessionCurrency string `json:"sessionCurrency,omitempty"`
245 SessionCostUsd float64 `json:"sessionCostUsd,omitempty"`
246 // SessionCostComplete is false when any entry lacks a shared display valuation.
247 SessionCostComplete bool `json:"sessionCostComplete,omitempty"`
248 // CostLedger stores occurrence-time quotes keyed by model+source+fingerprint+rateDate.
249 CostLedger *billing.Ledger `json:"costLedger,omitempty"`
250 // SessionCostQuote is the aggregate quote for the current display currency.
251 SessionCostQuote *billing.CostQuote `json:"sessionCostQuote,omitempty"`
252 Sources map[string]usageSourceStats `json:"sources,omitempty"`
253
254 activeTurnStartedAt int64
255 sourceSessionCache map[string]sourceSessionCacheCounters
256 }
257
258 type usageSourceStats struct {
259 PromptTokens int `json:"promptTokens"`
260 CompletionTokens int `json:"completionTokens"`
261 TotalTokens int `json:"totalTokens"`
262 ReasoningTokens int `json:"reasoningTokens"`
263 CacheHitTokens int `json:"cacheHitTokens"`
264 CacheMissTokens int `json:"cacheMissTokens"`
265 CacheWriteTokens int `json:"cacheWriteTokens,omitempty"`
266 CacheWriteBilledTokens float64 `json:"cacheWriteBilledTokens,omitempty"`
267 Estimated bool `json:"estimated,omitempty"`
268 RequestCount int `json:"requestCount"`
269 SessionCost float64 `json:"sessionCost,omitempty"`
270 SessionCurrency string `json:"sessionCurrency,omitempty"`
271 SessionCostUsd float64 `json:"sessionCostUsd,omitempty"`
272 }
273
274 type sourceSessionCacheCounters struct {
275 Hit int
276 Miss int
277 }
278
279 func cloneSessionUsageStats(in sessionUsageStats) sessionUsageStats {
280 out := in
281 if len(in.Sources) > 0 {
282 out.Sources = make(map[string]usageSourceStats, len(in.Sources))
283 maps.Copy(out.Sources, in.Sources)
284 }
285 if len(in.sourceSessionCache) > 0 {
286 out.sourceSessionCache = make(map[string]sourceSessionCacheCounters, len(in.sourceSessionCache))
287 maps.Copy(out.sourceSessionCache, in.sourceSessionCache)
288 }
289 return out
290 }
291
292 func (s *sessionUsageStats) cacheTokenDelta(source string, u *provider.Usage, sessionHit, sessionMiss int) (hit, miss int) {
293 if u != nil {
294 hit = u.CacheHitTokens
295 miss = u.CacheMissTokens
296 }
297 if source != event.UsageSourceExecutor && source != event.UsageSourcePlanner {
298 return hit, miss
299 }
300 if sessionHit+sessionMiss <= 0 {
301 return hit, miss
302 }
303 if s.sourceSessionCache == nil {
304 s.sourceSessionCache = map[string]sourceSessionCacheCounters{}
305 }
306 prev, ok := s.sourceSessionCache[source]
307 s.sourceSessionCache[source] = sourceSessionCacheCounters{Hit: sessionHit, Miss: sessionMiss}
308 if !ok {
309 return sessionHit, sessionMiss
310 }
311 if sessionHit < prev.Hit || sessionMiss < prev.Miss {
312 if hit+miss > 0 {
313 return hit, miss
314 }
315 return sessionHit, sessionMiss
316 }
317 return sessionHit - prev.Hit, sessionMiss - prev.Miss
318 }
319
320 type tabTelemetrySnapshot struct {
321 Version int `json:"version"`
322 ReadFiles []readFileRecord `json:"readFiles"`
323 Usage sessionUsageStats `json:"usage"`
324 }
325
326 func cloneStringPtr(v *string) *string {
327 if v == nil {
328 return nil
329 }
330 cp := *v
331 return &cp
332 }
333
334 func cloneServerViewMap(in map[string]ServerView) map[string]ServerView {
335 out := make(map[string]ServerView, len(in))
336 for name, view := range in {
337 view.EnvKeys = append([]string(nil), view.EnvKeys...)
338 view.HeaderKeys = append([]string(nil), view.HeaderKeys...)
339 out[name] = view
340 }
341 return out
342 }
343
344 func (t *WorkspaceTab) currentSessionPath() string {
345 if t == nil {
346 return ""
347 }
348 tabPath := strings.TrimSpace(t.SessionPath)
349 // Recovery handoff is two-phase: the desktop callback acquires the new
350 // lease and updates SessionPath before Controller commits its own path. The
351 // lease-backed tab path is authoritative during that window; otherwise a
352 // concurrent, newer tab-layout save can overwrite the recovery anchor with
353 // the controller's old path. Outside a handoff, keep the controller-first
354 // behavior so an unleased/stale tab field cannot mask the live runtime.
355 if tabPath != "" && sessionRuntimeKey(tabPath) == t.sessionLeaseRuntimeKey() {
356 return tabPath
357 }
358 if t.Ctrl != nil {
359 if path := strings.TrimSpace(t.Ctrl.SessionPath()); path != "" {
360 return path
361 }
362 }
363 return tabPath
364 }
365
366 func (t *WorkspaceTab) currentSessionIdentity() string {
367 if t == nil {
368 return ""
369 }
370 if id := strings.TrimSpace(t.SessionID); id != "" {
371 return remoteSessionIDRoutePrefix + id
372 }
373 return t.currentSessionPath()
374 }
375
376 func (t *WorkspaceTab) hasActiveRuntimeWork() bool {
377 if t == nil || t.Ctrl == nil {
378 return false
379 }
380 status := t.Ctrl.RuntimeStatus()
381 return status.Running || status.PendingPrompt || status.BackgroundJobs > 0
382 }
383
384 // sessionRuntimeKey is the comparison/map key for "same session" checks. It
385 // layers agent.CanonicalSessionPath on top of the desktop path normalization
386 // so the key matches the form held by session leases (lowercased on Windows).
387 // Comparing a lease's Path() against a raw tab path without this fold made
388 // every rebuild on Windows look like a foreign holder (self-lock, #5999).
389 // Keys are identities only — never use them as display or file paths.
390 func sessionRuntimeKey(path string) string {
391 locator := classifySessionLocator(path)
392 switch locator.kind {
393 case sessionLocatorCanonical:
394 return sessionRoute(locator.ref.SessionID)
395 case sessionLocatorLegacy:
396 path, ok, err := legacySessionPathForFileAccess(string(locator.legacyPath))
397 if err != nil || !ok {
398 return ""
399 }
400 return agent.CanonicalSessionPath(string(path))
401 default:
402 return ""
403 }
404 }
405
406 var sessionLeaseAcquireHookForTest func()
407
408 func (t *WorkspaceTab) ensureSessionLease(path string) error {
409 if t == nil || t.ReadOnly {
410 return nil
411 }
412 legacyPath, ok, err := legacySessionPathForFileAccess(path)
413 if err != nil {
414 return err
415 }
416 if !ok {
417 return nil
418 }
419 key := sessionRuntimeKey(string(legacyPath))
420 t.sessionLeaseMu.Lock()
421 if t.sessionLease != nil && sessionRuntimeKey(t.sessionLease.Path()) == key {
422 t.storeSessionLeaseRuntimeKey(key)
423 t.sessionLeaseMu.Unlock()
424 return nil
425 }
426 lease, err := agent.TryAcquireSessionLease(string(legacyPath))
427 if err != nil {
428 t.sessionLeaseMu.Unlock()
429 return err
430 }
431 if hook := sessionLeaseAcquireHookForTest; hook != nil {
432 hook()
433 }
434 old := t.sessionLease
435 t.sessionLease = lease
436 t.storeSessionLeaseRuntimeKey(key)
437 t.sessionLeaseMu.Unlock()
438 if old != nil {
439 old.Release()
440 }
441 return nil
442 }
443
444 func (t *WorkspaceTab) releaseSessionLease() {
445 if t == nil {
446 return
447 }
448 t.sessionLeaseMu.Lock()
449 lease := t.sessionLease
450 t.sessionLease = nil
451 t.storeSessionLeaseRuntimeKey("")
452 t.sessionLeaseMu.Unlock()
453 if lease != nil {
454 lease.Release()
455 }
456 }
457
458 // takeSessionLease removes and returns the tab's current lease WITHOUT
459 // releasing it, so ownership can transfer to another holder. All access to
460 // t.sessionLease must go through sessionLeaseMu; never read or assign the
461 // field directly outside these helpers.
462 func (t *WorkspaceTab) takeSessionLease() *agent.SessionLease {
463 if t == nil {
464 return nil
465 }
466 t.sessionLeaseMu.Lock()
467 lease := t.sessionLease
468 t.sessionLease = nil
469 t.storeSessionLeaseRuntimeKey("")
470 t.sessionLeaseMu.Unlock()
471 return lease
472 }
473
474 // adoptSessionLease installs lease as the tab's session lease, releasing any
475 // previously held lease unless it is the very same lease. A nil tab releases
476 // the lease immediately so ownership is never dropped on the floor.
477 func (t *WorkspaceTab) adoptSessionLease(lease *agent.SessionLease) {
478 if t == nil {
479 if lease != nil {
480 lease.Release()
481 }
482 return
483 }
484 t.sessionLeaseMu.Lock()
485 old := t.sessionLease
486 t.sessionLease = lease
487 key := ""
488 if lease != nil {
489 key = sessionRuntimeKey(lease.Path())
490 }
491 t.storeSessionLeaseRuntimeKey(key)
492 t.sessionLeaseMu.Unlock()
493 if old != nil && old != lease {
494 old.Release()
495 }
496 }
497
498 func (t *WorkspaceTab) storeSessionLeaseRuntimeKey(key string) {
499 if t == nil || key == "" {
500 if t != nil {
501 t.sessionLeaseKey.Store(nil)
502 }
503 return
504 }
505 stored := key
506 t.sessionLeaseKey.Store(&stored)
507 }
508
509 // sessionLeaseRuntimeKey reports the runtime key of the currently held lease,
510 // or "" when no lease is held. The mirror is lock-free so callers holding
511 // App.mu never wait on a concurrent lease acquisition (whose test hook and
512 // platform file operations run under sessionLeaseMu).
513 func (t *WorkspaceTab) sessionLeaseRuntimeKey() string {
514 if t == nil {
515 return ""
516 }
517 key := t.sessionLeaseKey.Load()
518 if key == nil {
519 return ""
520 }
521 return *key
522 }
523
524 // releaseSessionLeaseForKey releases the tab's lease only when it is bound to
525 // key. Superseded builds clean up with this instead of releaseSessionLease:
526 // on a removed tab the keys match and the lease is released as before, but
527 // when a session rebind superseded the build, the rebind's replacement build
528 // holds a lease for a *different* session key (rebind early-returns on equal
529 // keys), and releasing that here would strip the live session's protection.
530 func (t *WorkspaceTab) releaseSessionLeaseForKey(key string) {
531 if t == nil || key == "" {
532 return
533 }
534 t.sessionLeaseMu.Lock()
535 lease := t.sessionLease
536 if lease == nil || sessionRuntimeKey(lease.Path()) != key {
537 t.sessionLeaseMu.Unlock()
538 return
539 }
540 t.sessionLease = nil
541 t.storeSessionLeaseRuntimeKey("")
542 t.sessionLeaseMu.Unlock()
543 lease.Release()
544 }
545
546 func detachedRuntimeTabID(key string) string {
547 sum := sha256.Sum256([]byte(key))
548 return "detached_" + hex.EncodeToString(sum[:8])
549 }
550
551 func (a *App) ensureDetachedSessionsLocked() {
552 if a.detachedSessions == nil {
553 a.detachedSessions = map[string]*WorkspaceTab{}
554 }
555 }
556
557 func (a *App) runtimeTabsLocked() []*WorkspaceTab {
558 seen := map[*WorkspaceTab]bool{}
559 out := make([]*WorkspaceTab, 0, len(a.tabs)+len(a.detachedSessions))
560 for _, tab := range a.tabs {
561 if tab != nil && !seen[tab] {
562 seen[tab] = true
563 out = append(out, tab)
564 }
565 }
566 for _, tab := range a.detachedSessions {
567 if tab != nil && !seen[tab] {
568 seen[tab] = true
569 out = append(out, tab)
570 }
571 }
572 return out
573 }
574
575 func (a *App) tabByEventSinkIDLocked(tabID string) *WorkspaceTab {
576 if tab := a.tabs[tabID]; tab != nil {
577 return tab
578 }
579 for _, tab := range a.detachedSessions {
580 if tab != nil && tab.ID == tabID {
581 return tab
582 }
583 }
584 return nil
585 }
586
587 func (a *App) detachSessionRuntime(tab *WorkspaceTab) bool {
588 if tab == nil {
589 return false
590 }
591 a.mu.RLock()
592 ctrl := tab.Ctrl
593 fallbackIdentity := strings.TrimSpace(tab.currentSessionIdentity())
594 sink := tab.sink
595 a.mu.RUnlock()
596 identity := fallbackIdentity
597 if ctrl != nil && tab.SessionID == "" {
598 if p := strings.TrimSpace(ctrl.SessionPath()); p != "" {
599 identity = p
600 }
601 }
602 key := sessionRuntimeKey(identity)
603 if key == "" {
604 return false
605 }
606 if sink != nil {
607 sink.clearContext()
608 }
609 a.mu.Lock()
610 setTabSessionIdentity(tab, identity)
611 a.registerDetachedRuntimeLocked(tab)
612 a.mu.Unlock()
613 return true
614 }
615
616 func setTabSessionIdentity(tab *WorkspaceTab, identity string) {
617 if tab == nil {
618 return
619 }
620 tab.HistoricalSource = nil
621 locator := classifySessionLocator(identity)
622 if locator.kind == sessionLocatorCanonical {
623 tab.SessionID = locator.ref.SessionID
624 tab.SessionPath = ""
625 tab.SessionHeadID = ""
626 return
627 }
628 tab.SessionID = ""
629 if locator.kind == sessionLocatorLegacy {
630 tab.SessionPath = canonicalTabSessionPath(string(locator.legacyPath))
631 } else {
632 tab.SessionPath = ""
633 }
634 }
635
636 // cloneDetachedRuntimeTab copies a running tab's runtime state into a fresh
637 // detached tab. Callers must hold a.mu: the copied fields (Ctrl, Ready,
638 // ActivityStatus, disabledMCP, ...) are written under a.mu by bound methods
639 // and the event sink, and the disabledMCP map read would otherwise race those
640 // writers. The session lease is transferred separately by the caller through
641 // the sessionLeaseMu helpers. key is the runtime identity (map key / tab id
642 // hash); path is the real session path — keys are case-folded on Windows and
643 // must not leak into SessionPath, which is displayed and persisted.
644 func cloneDetachedRuntimeTab(tab *WorkspaceTab, key, path string) *WorkspaceTab {
645 if tab == nil {
646 return nil
647 }
648 tab.telemMu.Lock()
649 readTelemetry := append([]readFileRecord(nil), tab.readTelemetry...)
650 usageTelemetry := cloneSessionUsageStats(tab.usageTelemetry)
651 telemetrySessionKey := tab.telemetrySessionKey
652 tab.telemMu.Unlock()
653 pinnedFiles, pendingLegacyPinnedFiles := tab.pinnedFilesState()
654
655 detached := &WorkspaceTab{
656 ID: detachedRuntimeTabID(key),
657 Scope: tab.Scope,
658 WorkspaceRoot: tab.WorkspaceRoot,
659 SessionWorkspace: tab.SessionWorkspace,
660 SharedHostKey: tab.SharedHostKey,
661 TopicID: tab.TopicID,
662 TopicTitle: tab.TopicTitle,
663 topicTitleSource: tab.topicTitleSource,
664 Ctrl: tab.Ctrl,
665 Label: tab.Label,
666 Ready: tab.Ready,
667 StartupErr: tab.StartupErr,
668 StartupErrLeaseHeld: tab.StartupErrLeaseHeld,
669 modelApplication: tab.modelApplication,
670 lastBuildResult: tab.lastBuildResult,
671 runtimeID: tab.runtimeID,
672 sink: tab.sink,
673 ActivityStatus: tab.ActivityStatus,
674 readTelemetry: readTelemetry,
675 usageTelemetry: usageTelemetry,
676 telemetrySessionKey: telemetrySessionKey,
677 displayState: tab.displayBufferState(),
678 model: tab.model,
679 effort: cloneStringPtr(tab.effort),
680 qualityFloor: tab.qualityFloor,
681 mode: tab.mode,
682 goal: tab.goal,
683 toolApprovalMode: tab.toolApprovalMode,
684 disabledMCP: cloneServerViewMap(tab.disabledMCP),
685 mcpOrder: append([]string(nil), tab.mcpOrder...),
686 PinnedFiles: pinnedFiles,
687 pendingLegacyPinnedFiles: pendingLegacyPinnedFiles,
688 }
689 if tab.SessionID != "" {
690 setTabSessionIdentity(detached, sessionRoute(tab.SessionID))
691 } else {
692 setTabSessionIdentity(detached, path)
693 detached.SessionHeadID = tab.SessionHeadID
694 }
695 return detached
696 }
697
698 func (a *App) detachRuntimeForReplacement(tab *WorkspaceTab) bool {
699 if tab == nil {
700 return false
701 }
702 // One a.mu critical section covers the membership check, the field
703 // snapshot, the lease/sink handover, and the re-publication:
704 // - the clone reads fields that bound methods and the event sink write
705 // under a.mu (ActivityStatus every event, disabledMCP is a map);
706 // - inserting the clone without re-checking a.tabs would resurrect a
707 // runtime that DeleteSession/TrashTopic/RemoveWorkspace already
708 // unlinked and closed (the "session resurrects" class, #4384);
709 // - publishing before the lease/sink handover would let a concurrent
710 // attachExistingSessionRuntime claim a half-initialized clone.
711 // The lease transfer stays deadlock-safe here: neither side holds a lease
712 // to release, so no lease I/O runs under a.mu.
713 a.mu.Lock()
714 detached := a.detachRuntimeForReplacementLocked(tab)
715 a.mu.Unlock()
716 return detached
717 }
718
719 // detachRuntimeForReplacementLocked transfers a visible tab's live runtime to
720 // the detached registry without closing its controller or releasing its lease.
721 // Callers must hold App.mu. The transfer itself performs no file or host I/O.
722 func (a *App) detachRuntimeForReplacementLocked(tab *WorkspaceTab) bool {
723 if tab == nil {
724 return false
725 }
726 if tab.removed || a.tabs[tab.ID] != tab {
727 return false
728 }
729 sourceIdentity := tab.currentSessionIdentity()
730 key := sessionRuntimeKey(sourceIdentity)
731 if key == "" {
732 return false
733 }
734 detached := cloneDetachedRuntimeTab(tab, key, tab.currentSessionPath())
735 if detached == nil {
736 return false
737 }
738 // Transfer lease ownership through the locked helpers: a concurrent
739 // ensureSessionLease (blank-session boot, recovery callback) must never
740 // observe a torn pointer or have its freshly acquired lease clobbered.
741 detached.adoptSessionLease(tab.takeSessionLease())
742 if rt := a.runtimeForTabLocked(tab); rt != nil {
743 rt.Owner = detached
744 detached.runtimeID = rt.ID
745 tab.runtimeID = ""
746 }
747 if detached.sink != nil {
748 detached.sink.setBinding(detached.ID, nil)
749 // clearContext (locked nil + drain the queued emitter), not a bare
750 // ctx=nil: the latter both data-races s.ctx and leaves already-queued
751 // events to flush onto the rebound tab after this session is backgrounded
752 // (#5352 — stale "AI 不断输出" on the now-visible session).
753 detached.sink.clearContext()
754 }
755 a.registerDetachedRuntimeLocked(detached)
756 return true
757 }
758
759 // applyRuntimeTab moves source's runtime (controller, sink, lease, telemetry)
760 // onto target. path is the real session path for display/persistence; the
761 // case-folded runtime key must never be written into SessionPath.
762 func applyRuntimeTab(target, source *WorkspaceTab, path string, appCtx context.Context, app *App) {
763 if target == nil || source == nil {
764 return
765 }
766 if app != nil && target.ID != source.ID {
767 // Detached owners can acquire browser grants too. Retire the previous
768 // surface's grant before publishing the runtime's new binding.
769 app.forgetBrowserExecutorLocked(source.ID)
770 }
771 source.telemMu.Lock()
772 readTelemetry := append([]readFileRecord(nil), source.readTelemetry...)
773 usageTelemetry := cloneSessionUsageStats(source.usageTelemetry)
774 telemetrySessionKey := source.telemetrySessionKey
775 source.telemMu.Unlock()
776 pinnedFiles, pendingLegacyPinnedFiles := source.pinnedFilesState()
777
778 // Share the runtime-owned display state before rebinding the sink. An event
779 // already routed to source and one arriving on target after setBinding then
780 // append under the same state lock instead of straddling two buffers.
781 target.adoptDisplayState(source.displayBufferState())
782 if source.sink != nil {
783 source.sink.setBinding(target.ID, app)
784 source.sink.setSessionGeneration(target.SessionGeneration)
785 source.sink.setContext(appCtx)
786 }
787
788 target.Ctrl = source.Ctrl
789 target.modelApplication.failure = source.modelApplication.failure
790 target.lastBuildResult = source.lastBuildResult
791 target.sink = source.sink
792 target.adoptSessionLease(source.takeSessionLease())
793 if source.SessionID != "" {
794 target.SessionID = source.SessionID
795 target.SessionPath = ""
796 target.SessionHeadID = ""
797 } else {
798 setTabSessionIdentity(target, path)
799 target.SessionHeadID = source.SessionHeadID
800 }
801 target.SharedHostKey = source.SharedHostKey
802 target.Label = source.Label
803 target.Ready = source.Ready && source.Ctrl != nil
804 clearTabStartupError(target)
805 target.ActivityStatus = source.ActivityStatus
806 target.model = source.model
807 target.effort = cloneStringPtr(source.effort)
808 target.qualityFloor = control.QualityFloorStandard
809 target.mode = source.mode
810 target.goal = source.goal
811 target.toolApprovalMode = source.toolApprovalMode
812 target.disabledMCP = cloneServerViewMap(source.disabledMCP)
813 target.mcpOrder = append([]string(nil), source.mcpOrder...)
814 target.setPinnedFilesState(pinnedFiles, pendingLegacyPinnedFiles)
815 target.replaceTelemetry(tabTelemetrySnapshot{ReadFiles: readTelemetry, Usage: usageTelemetry}, telemetrySessionKey)
816 if app != nil {
817 key := sessionRuntimeKey(path)
818 rt := app.runtimeForTabLocked(source)
819 targetRuntime := app.runtimeForTabLocked(target)
820 if rt == nil {
821 rt = targetRuntime
822 }
823 if rt == nil {
824 rt = app.newSessionRuntimeLocked(source, key)
825 } else if targetRuntime != nil && targetRuntime != rt {
826 app.removeSessionRuntimeMappingsLocked(targetRuntime)
827 target.runtimeID = ""
828 }
829 if source.Ctrl != nil && source.Ready {
830 rt.Phase = sessionRuntimeReady
831 rt.Issue = nil
832 closeRuntimeReadyChannelLocked(rt)
833 }
834 rt.Owner = target
835 if rt.Key != "" && rt.Key != key && app.runtimeBySessionKey[rt.Key] == rt {
836 delete(app.runtimeBySessionKey, rt.Key)
837 }
838 rt.Key = key
839 app.runtimeBySessionKey[key] = rt
840 target.runtimeID = rt.ID
841 source.runtimeID = ""
842 if target.sink != nil {
843 target.sink.setRuntimeEpoch(rt.Epoch)
844 }
845 }
846 }
847
848 func (a *App) attachExistingSessionRuntimeCore(tab *WorkspaceTab, path string, appCtx context.Context) bool {
849 key := sessionRuntimeKey(path)
850 if tab == nil || key == "" {
851 return false
852 }
853
854 a.mu.Lock()
855 if tab.removed || a.tabs[tab.ID] != tab {
856 a.mu.Unlock()
857 return false
858 }
859 if rt := a.runtimeBySessionKey[key]; rt != nil && !a.runtimeOwnerLiveLocked(rt) {
860 a.removeSessionRuntimeMappingsLocked(rt)
861 }
862 registered := a.runtimeBySessionKey[key]
863 if registered != nil && registered.Phase == sessionRuntimeStarting && registered.Owner != tab {
864 // A starting runtime owns only an admission placeholder; its controller,
865 // lease, and sink have not been published yet. Moving that tab would
866 // supersede the owner build while the attaching build closes its own
867 // candidate, leaving the session permanently starting with no controller.
868 // claimSessionRuntime waits on readyCh and retries the attach after the
869 // owner publishes a terminal phase. The owner itself may still adopt a
870 // usable legacy runtime that predates the registry.
871 a.mu.Unlock()
872 return false
873 }
874 attachable := func(source *WorkspaceTab) bool {
875 if source == nil || source.Ctrl == nil {
876 return false
877 }
878 if rt := a.runtimeForTabLocked(source); rt != nil {
879 return rt.Phase == sessionRuntimeReady
880 }
881 // Compatibility for visible/detached runtimes constructed before the
882 // process-local registry existed.
883 return source.Ready
884 }
885 detached := a.liveRuntimeTabMatchingLocked(tab, path)
886 if detached != nil && a.tabs[detached.ID] == detached {
887 detached = nil
888 }
889 if detached == nil && key != "" {
890 if rt := a.runtimeBySessionKey[key]; rt != nil && rt.Owner != nil && rt.Owner != tab {
891 detached = rt.Owner
892 if a.tabs[detached.ID] == detached {
893 detached = nil
894 }
895 }
896 }
897 if detached != nil {
898 if !attachable(detached) {
899 a.mu.Unlock()
900 return false
901 }
902 a.unregisterDetachedRuntimeLocked(detached)
903 applyRuntimeTab(tab, detached, runtimeAttachIdentity(detached, path), appCtx, a)
904 if current := a.tabs[tab.ID]; current == tab {
905 a.saveTabsLocked()
906 }
907 attachedCtrl := tab.Ctrl
908 attachedSink := tab.sink
909 attachedEpoch := a.runtimeEpochForTabLocked(tab)
910 a.mu.Unlock()
911 a.replayPendingPromptsAfterRuntimeAttach(tab.ID, attachedSink, attachedCtrl, attachedEpoch)
912 return true
913 }
914
915 source := a.liveRuntimeTabMatchingLocked(tab, path)
916 if source == nil && key != "" {
917 if rt := a.runtimeBySessionKey[key]; rt != nil && rt.Owner != nil && rt.Owner != tab {
918 source = rt.Owner
919 }
920 }
921 if source == nil {
922 a.mu.Unlock()
923 return false
924 }
925 if !attachable(source) {
926 a.mu.Unlock()
927 return false
928 }
929 delete(a.tabs, source.ID)
930 a.removeTabOrderLocked(source.ID)
931 if a.activeTabID == source.ID {
932 a.activeTabID = tab.ID
933 }
934 applyRuntimeTab(tab, source, runtimeAttachIdentity(source, path), appCtx, a)
935 a.saveTabsLocked()
936 attachedCtrl := tab.Ctrl
937 attachedSink := tab.sink
938 attachedEpoch := a.runtimeEpochForTabLocked(tab)
939 a.mu.Unlock()
940 if path != "" && !tab.ReadOnly {
941 a.attachTakeoverMirror(tab.ID, path)
942 go a.adoptSessionFromLocalServe(tab.ID, path)
943 }
944
945 a.replayPendingPromptsAfterRuntimeAttach(tab.ID, attachedSink, attachedCtrl, attachedEpoch)
946 return true
947 }
948
949 func (t *WorkspaceTab) recordReadFile(rec readFileRecord) {
950 t.telemMu.Lock()
951 t.readTelemetry = append(t.readTelemetry, rec)
952 t.telemMu.Unlock()
953 }
954
955 func (t *WorkspaceTab) recordTurnDone(now int64) {
956 t.telemMu.Lock()
957 if started := t.usageTelemetry.activeTurnStartedAt; started > 0 && now >= started {
958 t.usageTelemetry.ElapsedMs += now - started
959 t.usageTelemetry.activeTurnStartedAt = 0
960 }
961 t.telemMu.Unlock()
962 }
963
964 // contextTelemetryFromUsage returns the latest-attempt context shape for
965 // rebind-surviving Last* telemetry fields. Prefer Context* when set (multi-
966 // attempt sampling recovery); otherwise fall back to billable totals / the
967 // per-event cache delta already computed for this Usage event.
968 //
969 // When a Context shape is present, ContextCacheHit/Miss are kept even if both
970 // are zero — many providers omit cache splits, and falling back to the
971 // event's aggregated cache would re-inflate multi-attempt totals.
972 func contextTelemetryFromUsage(u *provider.Usage, eventCacheHit, eventCacheMiss int) (prompt, completion, reasoning, hit, miss int) {
973 if u == nil {
974 return 0, 0, 0, eventCacheHit, eventCacheMiss
975 }
976 if u.ContextPromptTokens > 0 || u.ContextCompletionTokens > 0 {
977 return u.ContextPromptTokens, u.ContextCompletionTokens, u.ContextReasoningTokens,
978 u.ContextCacheHitTokens, u.ContextCacheMissTokens
979 }
980 return u.PromptTokens, u.CompletionTokens, u.ReasoningTokens, eventCacheHit, eventCacheMiss
981 }
982
983 func (t *WorkspaceTab) recordUsage(e event.Event) {
984 if e.Usage == nil {
985 return
986 }
987 u := e.Usage
988 source := strings.TrimSpace(e.UsageSource)
989 if source == "" {
990 source = event.UsageSourceExecutor
991 }
992 t.telemMu.Lock()
993 t.usageTelemetry.PromptTokens += u.PromptTokens
994 t.usageTelemetry.CompletionTokens += u.CompletionTokens
995 t.usageTelemetry.TotalTokens += u.TotalTokens
996 t.usageTelemetry.ReasoningTokens += u.ReasoningTokens
997 cacheHitTokens, cacheMissTokens := t.usageTelemetry.cacheTokenDelta(source, u, e.SessionHit, e.SessionMiss)
998 t.usageTelemetry.CacheHitTokens += cacheHitTokens
999 t.usageTelemetry.CacheMissTokens += cacheMissTokens
1000 t.usageTelemetry.CacheWriteTokens += u.CacheWriteTokens
1001 t.usageTelemetry.CacheWriteBilledTokens += u.CacheWriteBilledTokens
1002 t.usageTelemetry.Estimated = t.usageTelemetry.Estimated || u.Estimated
1003 requestCount := u.RequestCount
1004 if requestCount <= 0 {
1005 requestCount = 1
1006 }
1007 t.usageTelemetry.RequestCount += requestCount
1008 if source == event.UsageSourceExecutor {
1009 // Persist the latest-attempt context shape for rebind fallback — never
1010 // the multi-attempt billable aggregate (PromptTokens/CompletionTokens
1011 // after stream recovery). ContextSnapshot semantics are latest
1012 // prompt+completion; Context* fields carry that shape.
1013 prompt, completion, reasoning, hit, miss := contextTelemetryFromUsage(u, cacheHitTokens, cacheMissTokens)
1014 t.usageTelemetry.LastUsedTokens = prompt + completion
1015 t.usageTelemetry.LastPromptTokens = prompt
1016 t.usageTelemetry.LastCompletionTokens = completion
1017 t.usageTelemetry.LastReasoningTokens = reasoning
1018 t.usageTelemetry.LastCacheHitTokens = hit
1019 t.usageTelemetry.LastCacheMissTokens = miss
1020 t.usageTelemetry.LastEstimated = u.Estimated
1021 }
1022 if t.usageTelemetry.Sources == nil {
1023 t.usageTelemetry.Sources = map[string]usageSourceStats{}
1024 }
1025 src := t.usageTelemetry.Sources[source]
1026 src.PromptTokens += u.PromptTokens
1027 src.CompletionTokens += u.CompletionTokens
1028 src.TotalTokens += u.TotalTokens
1029 src.ReasoningTokens += u.ReasoningTokens
1030 src.CacheHitTokens += cacheHitTokens
1031 src.CacheMissTokens += cacheMissTokens
1032 src.CacheWriteTokens += u.CacheWriteTokens
1033 src.CacheWriteBilledTokens += u.CacheWriteBilledTokens
1034 src.Estimated = src.Estimated || u.Estimated
1035 src.RequestCount += requestCount
1036 // Prefer the middleware CostQuote; fall back only when older emitters omit it.
1037 q := e.CostQuote
1038 if q == nil && e.Pricing != nil {
1039 q = event.EnsureCostQuote(e, nil)
1040 }
1041 if q != nil {
1042 if t.usageTelemetry.CostLedger == nil {
1043 t.usageTelemetry.CostLedger = billing.NewLedger()
1044 }
1045 tokens := billing.UsageTokens{
1046 PromptTokens: u.PromptTokens,
1047 CompletionTokens: u.CompletionTokens,
1048 CacheHitTokens: cacheHitTokens,
1049 CacheMissTokens: cacheMissTokens,
1050 CacheWriteTokens: u.CacheWriteTokens,
1051 CacheWriteBilledTokens: u.CacheWriteBilledTokens,
1052 Estimated: u.Estimated,
1053 }
1054 t.usageTelemetry.CostLedger.Add(*q, tokens, time.Now().UTC())
1055 display := billing.NormalizeCurrency(t.runtimeCostDisplayCurrency)
1056 if display == "" {
1057 display = billing.NormalizeCurrency(t.usageTelemetry.SessionCurrency)
1058 }
1059 if display == "" && q.Selected != nil {
1060 display = billing.NormalizeCurrency(q.Selected.Currency)
1061 }
1062 if display == "" {
1063 display = billing.NormalizeCurrency(q.Original.Currency)
1064 }
1065 total := t.usageTelemetry.CostLedger.Total(display)
1066 if t.runtimeCostDisplayCurrency != "" {
1067 t.runtimeCostQuote = &total
1068 } else {
1069 t.usageTelemetry.SessionCostQuote = &total
1070 t.usageTelemetry.SessionCostComplete = total.Complete
1071 }
1072 if total.Selected != nil {
1073 if t.runtimeCostDisplayCurrency == "" {
1074 t.usageTelemetry.SessionCost = total.Selected.Float64()
1075 t.usageTelemetry.SessionCurrency = total.LegacyCurrencyCode()
1076 t.usageTelemetry.SessionCostUsd = t.usageTelemetry.SessionCost
1077 }
1078 src.SessionCost += q.LegacyCostFloat()
1079 src.SessionCostUsd = src.SessionCost
1080 src.SessionCurrency = total.LegacyCurrencySymbol()
1081 } else {
1082 // Incomplete: never invent a zero total by wiping prior costs.
1083 if t.runtimeCostDisplayCurrency == "" {
1084 t.usageTelemetry.SessionCostComplete = false
1085 t.usageTelemetry.SessionCost = 0
1086 t.usageTelemetry.SessionCurrency = ""
1087 t.usageTelemetry.SessionCostUsd = 0
1088 }
1089 if q.Selected == nil {
1090 src.SessionCurrency = billing.CurrencySymbol(q.Original.Currency)
1091 }
1092 }
1093 }
1094 t.usageTelemetry.Sources[source] = src
1095 t.telemMu.Unlock()
1096 }
1097
1098 func (a *App) repriceTabUsageForCurrentCurrency(tab *WorkspaceTab) {
1099 if a == nil || tab == nil {
1100 return
1101 }
1102 a.mu.RLock()
1103 root := tab.WorkspaceRoot
1104 a.mu.RUnlock()
1105 cfg, err := config.LoadForRoot(root)
1106 if err != nil {
1107 return
1108 }
1109 // Display preference only — automatic mode remains unresolved until a
1110 // wallet-aware surface supplies a session hint.
1111 display := cfg.ExplicitDisplayCurrency()
1112 if !tab.selectDisplayCurrency(display) {
1113 return
1114 }
1115 if identity := tab.currentSessionIdentity(); identity != "" {
1116 _ = saveTelemetryFor(identity, tab.telemetrySnapshot())
1117 }
1118 }
1119
1120 func (t *WorkspaceTab) telemetrySnapshot() tabTelemetrySnapshot {
1121 t.telemMu.Lock()
1122 defer t.telemMu.Unlock()
1123 return t.telemetrySnapshotLocked()
1124 }
1125
1126 func (t *WorkspaceTab) telemetrySnapshotLocked() tabTelemetrySnapshot {
1127 records := make([]readFileRecord, len(t.readTelemetry))
1128 copy(records, t.readTelemetry)
1129 usage := t.usageTelemetry
1130 if started := usage.activeTurnStartedAt; started > 0 {
1131 now := time.Now().UnixMilli()
1132 if now >= started {
1133 usage.ElapsedMs += now - started
1134 }
1135 }
1136 if len(t.usageTelemetry.Sources) > 0 {
1137 usage.Sources = make(map[string]usageSourceStats, len(t.usageTelemetry.Sources))
1138 maps.Copy(usage.Sources, t.usageTelemetry.Sources)
1139 }
1140 usage.activeTurnStartedAt = 0
1141 usage.sourceSessionCache = nil
1142 return tabTelemetrySnapshot{Version: 3, ReadFiles: records, Usage: usage}
1143 }
1144
1145 // displayTelemetrySnapshot overlays the live wallet hint onto a copy used by
1146 // UI reads. The persisted snapshot remains the occurrence-time/original view.
1147 func (t *WorkspaceTab) displayTelemetrySnapshot() tabTelemetrySnapshot {
1148 t.telemMu.Lock()
1149 defer t.telemMu.Unlock()
1150 return t.displayTelemetrySnapshotLocked()
1151 }
1152
1153 func (t *WorkspaceTab) displayTelemetrySnapshotLocked() tabTelemetrySnapshot {
1154 snapshot := t.telemetrySnapshotLocked()
1155 quote := t.runtimeCostQuote
1156 if quote == nil {
1157 return snapshot
1158 }
1159 snapshot.Usage.SessionCostQuote = quote
1160 snapshot.Usage.SessionCostComplete = quote.Complete
1161 if quote.Selected != nil {
1162 snapshot.Usage.SessionCost = quote.Selected.Float64()
1163 snapshot.Usage.SessionCurrency = quote.LegacyCurrencyCode()
1164 snapshot.Usage.SessionCostUsd = snapshot.Usage.SessionCost
1165 } else {
1166 snapshot.Usage.SessionCostComplete = false
1167 snapshot.Usage.SessionCost = 0
1168 snapshot.Usage.SessionCurrency = ""
1169 snapshot.Usage.SessionCostUsd = 0
1170 }
1171 return snapshot
1172 }
1173
1174 func (t *WorkspaceTab) resetTelemetry(sessionPath string) {
1175 t.telemMu.Lock()
1176 t.readTelemetry = nil
1177 t.usageTelemetry = sessionUsageStats{}
1178 t.runtimeCostDisplayCurrency = ""
1179 t.runtimeCostQuote = nil
1180 t.runtimeCostGeneration++
1181 t.telemetrySessionKey = sessionRuntimeKey(sessionPath)
1182 t.telemMu.Unlock()
1183 }
1184
1185 // syncTelemetryToSession keys the in-memory telemetry to the runtime's current
1186 // session. When the runtime rotated to a different session underneath the tab
1187 // (typed /new routes through Controller.Submit and never reaches App.NewSession),
1188 // the previous session's totals must not bleed into the new one: swap in the
1189 // new session's persisted sidecar, or start from zero when none exists. The
1190 // sidecar is rewritten on every recorded event, so a reload never loses more
1191 // than the sub-second in-memory delta of an in-flight record.
1192 func (t *WorkspaceTab) syncTelemetryToSession(sessionPath string) {
1193 key := sessionRuntimeKey(sessionPath)
1194 if key == "" {
1195 return
1196 }
1197 t.telemMu.Lock()
1198 same := t.telemetrySessionKey == key
1199 t.telemMu.Unlock()
1200 if same {
1201 return
1202 }
1203 // File I/O stays outside telemMu; re-check the key after reacquiring in
1204 // case a concurrent sync or reset re-keyed the tab first.
1205 snapshot := loadTelemetryFor(sessionPath)
1206 t.telemMu.Lock()
1207 if t.telemetrySessionKey != key {
1208 t.readTelemetry = snapshot.ReadFiles
1209 t.usageTelemetry = snapshot.Usage
1210 t.runtimeCostDisplayCurrency = ""
1211 t.runtimeCostQuote = nil
1212 t.runtimeCostGeneration++
1213 t.telemetrySessionKey = key
1214 }
1215 t.telemMu.Unlock()
1216 }
1217
1218 func (t *WorkspaceTab) resetDisplayTurn() {
1219 state := t.displayBufferState()
1220 state.mu.Lock()
1221 state.planner.ResetToolsIfEmpty()
1222 state.executor.ResetToolsIfEmpty()
1223 state.mu.Unlock()
1224 }
1225
1226 func (t *WorkspaceTab) recordDisplayEvent(e event.Event) {
1227 state := t.displayBufferState()
1228 state.mu.Lock()
1229 defer state.mu.Unlock()
1230 buffer := &state.executor
1231 if strings.TrimSpace(e.Source) == event.UsageSourcePlanner {
1232 buffer = &state.planner
1233 }
1234 recordHistoryDisplayEvent(buffer, e)
1235 }
1236
1237 func (t *WorkspaceTab) displayBufferState() *tabDisplayState {
1238 t.displayStateMu.Lock()
1239 defer t.displayStateMu.Unlock()
1240 if t.displayState == nil {
1241 t.displayState = &tabDisplayState{}
1242 }
1243 return t.displayState
1244 }
1245
1246 func (t *WorkspaceTab) adoptDisplayState(state *tabDisplayState) {
1247 if t == nil || state == nil {
1248 return
1249 }
1250 t.displayStateMu.Lock()
1251 t.displayState = state
1252 t.displayStateMu.Unlock()
1253 }
1254
1255 func recoverPendingTurnProjections(tab *WorkspaceTab, ctrl control.SessionAPI) {
1256 if tab == nil || ctrl == nil {
1257 return
1258 }
1259 projectionCtrl, ok := ctrl.(interface {
1260 PendingTurnProjections() []turnevent.PendingProjection
1261 AcknowledgeTurnProjection(string) error
1262 })
1263 if !ok {
1264 return
1265 }
1266 pending := projectionCtrl.PendingTurnProjections()
1267 if len(pending) == 0 {
1268 return
1269 }
1270 users := make([]string, 0)
1271 for _, message := range ctrl.History() {
1272 if agent.IsUserAuthoredTurnMessage(message) {
1273 if text := strings.TrimSpace(agent.UserMessageText(message)); text != "" {
1274 users = append(users, text)
1275 }
1276 }
1277 }
1278 firstUser := len(users) - len(pending)
1279 for i, projection := range pending {
1280 messages := displayMessagesFromProjection(projection)
1281 if len(messages) == 0 {
1282 if err := projectionCtrl.AcknowledgeTurnProjection(projection.TurnID); err != nil {
1283 slog.Warn("desktop: acknowledge empty recovered projection", "err", err)
1284 }
1285 continue
1286 }
1287 userIndex := firstUser + i
1288 if userIndex < 0 || userIndex >= len(users) {
1289 slog.Warn("desktop: retain unacknowledged projection without matching user turn")
1290 continue
1291 }
1292 turnID := projection.TurnID
1293 persistOrEnqueueDisplayWrite(tab.displayBufferState(), &pendingDisplayWrite{
1294 dir: controllerSessionDir(ctrl), sessionPath: ctrl.SessionPath(), userContent: users[userIndex], messages: messages,
1295 persist: func(dir, sessionPath, userContent string, messages []HistoryMessage) error {
1296 return recordSessionPlannerDisplayForTurn(dir, sessionPath, turnID, userContent, messages)
1297 },
1298 onPersisted: func() {
1299 if err := projectionCtrl.AcknowledgeTurnProjection(turnID); err != nil {
1300 slog.Warn("desktop: acknowledge recovered turn projection", "err", err)
1301 }
1302 },
1303 onRetry: func() {
1304 if observer, ok := ctrl.(interface{ ObserveTurnProjectionRetry() }); ok {
1305 observer.ObserveTurnProjectionRetry()
1306 }
1307 },
1308 })
1309 }
1310 }
1311
1312 func plannerToolResultDisplay(content string, failed bool) (display, errPreview string) {
1313 if strings.TrimSpace(content) == "" {
1314 return "", ""
1315 }
1316 if failed || historyToolResultFailed(content) {
1317 display = clipHistoryToolPreview(strings.TrimSpace(content))
1318 return display, display
1319 }
1320 return "", ""
1321 }
1322
1323 func (t *WorkspaceTab) takeDisplayTurn(cancelled bool) []HistoryMessage {
1324 state := t.displayBufferState()
1325 state.mu.Lock()
1326 defer state.mu.Unlock()
1327 out := state.planner.materialize()
1328 if !cancelled {
1329 out = append(out, state.executor.resultMessages()...)
1330 }
1331 if cancelled {
1332 out = append(out, state.executor.materialize()...)
1333 if len(out) > 0 {
1334 out = append(out, HistoryMessage{
1335 Role: "notice",
1336 Level: "info",
1337 Code: event.NoticeCodeCancelledTurn,
1338 Content: "This turn was interrupted. Partial output is kept for reference; only completed tool pairs and a bounded recovery summary enter the next model turn. Inspect the workspace before continuing or reverting changes.",
1339 })
1340 }
1341 }
1342 state.planner.reset()
1343 state.executor.reset()
1344 return out
1345 }
1346
1347 func enqueuePendingDisplayWrite(state *tabDisplayState, write *pendingDisplayWrite) {
1348 if state == nil || write == nil || write.persist == nil {
1349 return
1350 }
1351 state.mu.Lock()
1352 state.pendingWrites = append(state.pendingWrites, write)
1353 if state.persistRunning {
1354 state.mu.Unlock()
1355 return
1356 }
1357 state.persistRunning = true
1358 state.mu.Unlock()
1359 go retryPendingDisplayWrites(state)
1360 }
1361
1362 func persistOrEnqueueDisplayWrite(state *tabDisplayState, write *pendingDisplayWrite) bool {
1363 if state == nil || write == nil || write.persist == nil {
1364 return true
1365 }
1366 state.mu.Lock()
1367 hasPending := len(state.pendingWrites) > 0
1368 state.mu.Unlock()
1369 if hasPending {
1370 enqueuePendingDisplayWrite(state, write)
1371 return false
1372 }
1373 if err := write.persist(write.dir, write.sessionPath, write.userContent, write.messages); err != nil {
1374 slog.Warn("desktop: persist display-only turn history; queued for retry", "err", err)
1375 if write.onRetry != nil {
1376 write.onRetry()
1377 }
1378 enqueuePendingDisplayWrite(state, write)
1379 return false
1380 }
1381 if write.onPersisted != nil {
1382 write.onPersisted()
1383 }
1384 return true
1385 }
1386
1387 func retryPendingDisplayWrites(state *tabDisplayState) {
1388 failures := 0
1389 for {
1390 state.mu.Lock()
1391 if len(state.pendingWrites) == 0 {
1392 state.persistRunning = false
1393 state.mu.Unlock()
1394 return
1395 }
1396 write := state.pendingWrites[0]
1397 state.mu.Unlock()
1398
1399 if failures > 0 {
1400 time.Sleep(time.Duration(failures*failures) * 50 * time.Millisecond)
1401 }
1402 if err := write.persist(write.dir, write.sessionPath, write.userContent, write.messages); err != nil {
1403 if write.onRetry != nil {
1404 write.onRetry()
1405 }
1406 failures++
1407 if failures < displayPersistRetryLimit {
1408 continue
1409 }
1410 state.mu.Lock()
1411 state.persistRunning = false
1412 state.mu.Unlock()
1413 slog.Warn("desktop: display-only turn history remains pending after retries", "err", err)
1414 return
1415 }
1416
1417 state.mu.Lock()
1418 if len(state.pendingWrites) > 0 && state.pendingWrites[0] == write {
1419 state.pendingWrites[0] = nil
1420 state.pendingWrites = state.pendingWrites[1:]
1421 }
1422 state.mu.Unlock()
1423 if write.onPersisted != nil {
1424 write.onPersisted()
1425 }
1426 failures = 0
1427 }
1428 }
1429
1430 // tabEventSink wraps a parent event.Sink and prepends a tabId to every wire
1431 // event so the frontend can route it to the correct tab's reducer.
1432 //
1433 // tabID and app are rebound while the controller keeps emitting when a running
1434 // session is detached to the background or reattached to another tab, so they
1435 // live under mu like ctx does (a bare field write would data-race Emit). Read
1436 // them via binding(), write via setBinding().
1437 type tabEventSink struct {
1438 tabID string
1439 app *App
1440 mu sync.RWMutex
1441 ctx context.Context
1442 runtimeEpoch string
1443 sessionGeneration uint64 // source session binding generation
1444 runtimeEvents asyncRuntimeEmitter
1445 botSink event.Sink // optional: when set, events are also forwarded here
1446 botSinkGen uint64
1447 turn turnSubmissionState // stays reserved through the end of TurnDone fan-out
1448 // takeoverMirror, when set, forwards every event to the serve that used to
1449 // own this session so the remote tab keeps rendering after a local
1450 // takeover. Atomic so Emit reads it without the sink lock.
1451 takeoverMirror atomic.Pointer[takeoverMirror]
1452 }
1453
1454 // setTakeoverMirror installs (or clears) the session-takeover frame mirror.
1455 func (s *tabEventSink) setTakeoverMirror(m *takeoverMirror) {
1456 if s == nil {
1457 return
1458 }
1459 s.takeoverMirror.Store(m)
1460 }
1461
1462 type closeableEventSink interface {
1463 Close()
1464 }
1465
1466 // binding snapshots the sink's current tab routing under the sink lock.
1467 func (s *tabEventSink) binding() (string, *App) {
1468 if s == nil {
1469 return "", nil
1470 }
1471 s.mu.RLock()
1472 defer s.mu.RUnlock()
1473 return s.tabID, s.app
1474 }
1475
1476 func (s *tabEventSink) runtimeEpochSnapshot() string {
1477 if s == nil {
1478 return ""
1479 }
1480 s.mu.RLock()
1481 defer s.mu.RUnlock()
1482 return s.runtimeEpoch
1483 }
1484
1485 func (s *tabEventSink) Emit(e event.Event) {
1486 // Typed-nil sinks can appear as non-nil event.Sink interfaces when a tab
1487 // controller is built before the tab sink binding is installed.
1488 if s == nil {
1489 return
1490 }
1491 if e.Kind == event.TurnStarted || e.Kind == event.TurnDone {
1492 s.mu.Lock()
1493 s.turn.phase = turnSubmissionActive
1494 s.mu.Unlock()
1495 }
1496 tabID, app := s.binding()
1497 var turnStartedAt int64
1498 if app != nil {
1499 if e.Kind == event.TurnDone {
1500 // Keep the legacy completion as a cheap missed-event safety net. The
1501 // hub owns the actual resource invalidation and coalesces this probe.
1502 app.reconcileWorkspaceForTab(tabID)
1503 }
1504 switch e.Kind {
1505 case event.TurnStarted:
1506 s.resetDisplayTurn()
1507 turnStartedAt = s.recordTurnStarted()
1508 case event.Usage:
1509 s.recordUsageTelemetry(e)
1510 case event.TurnDone:
1511 s.recordTurnDone()
1512 }
1513 if e.Kind == event.TurnDone {
1514 s.recordDisplay(e)
1515 s.flushDisplay(e.TurnID, e.Cancelled)
1516 }
1517 if m := app.metrics.Load(); m != nil {
1518 m.observe(e)
1519 persistMetricsEvent(app, m, tabID, e)
1520 }
1521 }
1522 s.emitRuntimeEvent(eventChannel, toWireTabWithSubmission(e, tabID, s.runtimeEpochSnapshot(), s.submissionIDSnapshot(), turnStartedAt, s.sessionGenerationSnapshot()))
1523 if m := s.takeoverMirror.Load(); m != nil {
1524 m.forwardEvent(e)
1525 }
1526 if app != nil {
1527 if status, update := topicActivityStatusFromEvent(e); update {
1528 changed := app.setTabActivityStatus(tabID, status)
1529 if changed || isBackgroundJobLifecycleNotice(e) {
1530 // Runtime status is an in-memory projection, not catalog metadata.
1531 // Publish it directly so a turn never fans out into one catalog read
1532 // per expanded project folder.
1533 app.emitProjectTreeRuntimeChangedWithLegacy()
1534 }
1535 }
1536 }
1537 // Record read_file successes in the tab's telemetry.
1538 if e.Kind == event.ToolResult && e.Tool.Name == "read_file" && e.Tool.Err == "" {
1539 s.recordReadTelemetry(e)
1540 }
1541 if app != nil && e.Kind != event.TurnDone {
1542 s.recordDisplay(e)
1543 }
1544 // Persist after each turn so a force-kill loses at most the in-flight prompt.
1545 if e.Kind == event.TurnDone && app != nil {
1546 app.scheduleTabSnapshot(tabID)
1547 }
1548 // Forward event to bot channels when a bot forwarder is attached.
1549 // Read the sink under the read lock so SetBotSink can safely swap it
1550 // from another goroutine.
1551 bs, botSinkGen := s.botSinkSnapshot()
1552 if bs != nil {
1553 bs.Emit(e)
1554 // Detach the forwarder after TurnDone so subsequent turns on the
1555 // same tab do not keep pushing to bot channels.
1556 if e.Kind == event.TurnDone {
1557 s.clearBotSink(botSinkGen)
1558 }
1559 }
1560 // Unlike the transient botSink above, the bridge observes every tab for
1561 // its whole lifetime (god view: /desktop status, watch subscriptions,
1562 // remote approvals). observe only does in-memory bookkeeping and queueing.
1563 if app != nil && app.botBridge != nil {
1564 app.botBridge.observe(tabID, e)
1565 }
1566 if e.Kind == event.TurnDone {
1567 s.mu.Lock()
1568 s.turn = turnSubmissionState{}
1569 s.mu.Unlock()
1570 }
1571 }
1572
1573 // SetBotSink atomically sets or clears the bot event forwarder on this sink.
1574 // It is safe to call concurrently with Emit.
1575 func (s *tabEventSink) SetBotSink(sink event.Sink) uint64 {
1576 s.mu.Lock()
1577 old := s.botSink
1578 s.botSink = sink
1579 s.botSinkGen++
1580 generation := s.botSinkGen
1581 s.mu.Unlock()
1582 if old != nil && old != sink {
1583 if closer, ok := old.(closeableEventSink); ok {
1584 closer.Close()
1585 }
1586 }
1587 return generation
1588 }
1589
1590 func (s *tabEventSink) botSinkSnapshot() (event.Sink, uint64) {
1591 s.mu.RLock()
1592 defer s.mu.RUnlock()
1593 return s.botSink, s.botSinkGen
1594 }
1595
1596 // clearBotSink clears only the forwarder generation observed by the finishing
1597 // turn. A delayed TurnDone must not detach a replacement installed meanwhile.
1598 func (s *tabEventSink) clearBotSink(generation uint64) {
1599 s.mu.Lock()
1600 if s.botSinkGen != generation {
1601 s.mu.Unlock()
1602 return
1603 }
1604 old := s.botSink
1605 s.botSink = nil
1606 s.botSinkGen++
1607 s.mu.Unlock()
1608 if closer, ok := old.(closeableEventSink); ok {
1609 closer.Close()
1610 }
1611 }
1612
1613 // tryBeginTurn reserves the tab until its TurnDone has finished fan-out. The
1614 // controller clears RuntimeStatus().Running before it emits TurnDone, so the
1615 // controller status alone leaves a window where a new turn can inherit the old
1616 // turn's forwarder or have its replacement cleared by the old completion.
1617 func (s *tabEventSink) tryBeginTurn(submissionID ...string) bool {
1618 s.mu.Lock()
1619 defer s.mu.Unlock()
1620 if s.turn.phase != turnSubmissionIdle {
1621 return false
1622 }
1623 s.turn = turnSubmissionState{phase: turnSubmissionReserved, submissionID: firstSubmissionID(submissionID)}
1624 return true
1625 }
1626
1627 func (s *tabEventSink) cancelTurnStart() {
1628 s.mu.Lock()
1629 // A management command can finish after queued work has started. Only its
1630 // provisional reservation may be released; TurnDone owns a started turn.
1631 if s.turn.phase == turnSubmissionReserved {
1632 s.turn = turnSubmissionState{}
1633 }
1634 s.mu.Unlock()
1635 }
1636
1637 func (s *tabEventSink) setContext(ctx context.Context) {
1638 s.mu.Lock()
1639 s.ctx = ctx
1640 s.mu.Unlock()
1641 }
1642
1643 func (s *tabEventSink) context() context.Context {
1644 s.mu.RLock()
1645 defer s.mu.RUnlock()
1646 return s.ctx
1647 }
1648
1649 func (s *tabEventSink) emitRuntimeEvent(name string, payload ...any) {
1650 if s == nil {
1651 return
1652 }
1653 ctx := s.context()
1654 if ctx == nil {
1655 return
1656 }
1657 s.runtimeEvents.Emit(ctx, name, payload...)
1658 }
1659
1660 type runtimeEventEmitFunc func(context.Context, string, ...any)
1661
1662 type runtimeEventEnvelope struct {
1663 ctx context.Context
1664 name string
1665 payload []any
1666 }
1667
1668 // asyncRuntimeEmitter decouples the host event bridge from agent emission.
1669 // Emit can block when the event channel backs up; callers enqueue in-order
1670 // work and return without holding the agent event lock.
1671 // runtimeEventsEmitFallback is the emit used when no per-instance override is
1672 // installed. Production replaces it with the host RPC server emit in
1673 // runHostRPC; the test binary swaps in a no-op via TestMain.
1674 var runtimeEventsEmitFallback runtimeEventEmitFunc = func(_ context.Context, name string, _ ...any) {
1675 slog.Debug("desktop: runtime event dropped without a host shell", "name", name)
1676 }
1677
1678 type asyncRuntimeEmitter struct {
1679 mu sync.Mutex
1680 emit runtimeEventEmitFunc
1681 queue []runtimeEventEnvelope
1682 head int
1683 running bool
1684 configWarningsRevision atomic.Uint64
1685 }
1686
1687 func (e *asyncRuntimeEmitter) Emit(ctx context.Context, name string, payload ...any) {
1688 if ctx == nil {
1689 return
1690 }
1691 item := runtimeEventEnvelope{
1692 ctx: ctx,
1693 name: name,
1694 payload: append([]any(nil), payload...),
1695 }
1696 e.mu.Lock()
1697 e.queue = append(e.queue, item)
1698 if !e.running {
1699 e.running = true
1700 go e.run()
1701 }
1702 e.mu.Unlock()
1703 }
1704
1705 func (e *asyncRuntimeEmitter) Clear() {
1706 e.mu.Lock()
1707 clear(e.queue)
1708 e.queue = nil
1709 e.head = 0
1710 e.mu.Unlock()
1711 }
1712
1713 func (e *asyncRuntimeEmitter) run() {
1714 for {
1715 e.mu.Lock()
1716 if e.head >= len(e.queue) {
1717 clear(e.queue)
1718 e.queue = nil
1719 e.head = 0
1720 e.running = false
1721 e.mu.Unlock()
1722 return
1723 }
1724 item := e.queue[e.head]
1725 var zero runtimeEventEnvelope
1726 e.queue[e.head] = zero
1727 e.head++
1728 if e.head > 64 && e.head*2 >= len(e.queue) {
1729 e.queue = append([]runtimeEventEnvelope(nil), e.queue[e.head:]...)
1730 e.head = 0
1731 }
1732 emit := e.emit
1733 if emit == nil {
1734 emit = runtimeEventsEmitFallback
1735 }
1736 e.mu.Unlock()
1737
1738 emit(item.ctx, item.name, item.payload...)
1739 }
1740 }
1741
1742 func topicActivityStatusFromEvent(e event.Event) (string, bool) {
1743 switch e.Kind {
1744 case event.TurnStarted, event.Reasoning, event.ToolDispatch, event.ToolProgress, event.ToolResultPreview, event.ToolResult, event.CompactionStarted, event.Retrying:
1745 return topicStatusThinking, true
1746 // A manual /compact runs outside a turn, so no TurnDone follows to clear it;
1747 // any other trigger compacts inside a running turn, which is still thinking.
1748 case event.CompactionDone:
1749 if e.Compaction.Trigger == agent.CompactionTriggerManual {
1750 return "", true
1751 }
1752 return topicStatusThinking, true
1753 case event.Text, event.Message:
1754 return topicStatusStreaming, true
1755 case event.ApprovalRequest, event.AskRequest:
1756 return topicStatusWaitingConfirmation, true
1757 case event.TurnDone:
1758 if status, ok := topicStatusFromTurnDone(e.Outcome); ok {
1759 return status, true
1760 }
1761 if e.Err != nil {
1762 return topicStatusError, true
1763 }
1764 return "", true
1765 case event.Notice:
1766 if isBackgroundJobLifecycleNotice(e) {
1767 return "", true
1768 }
1769 return "", false
1770 default:
1771 return "", false
1772 }
1773 }
1774
1775 func isBackgroundJobLifecycleNotice(e event.Event) bool {
1776 if e.Kind != event.Notice {
1777 return false
1778 }
1779 text := strings.TrimSpace(e.Text)
1780 return strings.HasPrefix(text, "background ") &&
1781 (strings.Contains(text, " started: ") ||
1782 strings.Contains(text, " finished: ") ||
1783 strings.Contains(text, " failed: ") ||
1784 strings.Contains(text, " killed: "))
1785 }
1786
1787 // notifyTabRuntimeRebuilt tells the frontend a tab's controller was replaced
1788 // in place (model/effort/token-mode switch, clear-while-running). A rebuilt
1789 // controller restarts its approval/ask id counter at "1", so tab-scoped
1790 // frontend state keyed by prompt id (the attention-chime dedupe) must reset —
1791 // unlike agent:ready, this event carries no reload semantics, so emitting it
1792 // on every swap adds no hydration churn.
1793 //
1794 // Ordering matters: the reset must reach the frontend BEFORE the rebuilt
1795 // controller's first approval/ask event, or the stale key still mutes it. The
1796 // tab's agent events ride the tab sink's own async queue, so the notice goes
1797 // through THAT queue — same lane, FIFO, guaranteed to arrive first. The
1798 // App-level queue is only the fallback when the sink cannot deliver (no sink,
1799 // or its webview context is cleared); it cannot order against sink traffic,
1800 // but an unordered notice still beats none.
1801 func (a *App) notifyTabRuntimeRebuilt(tab *WorkspaceTab) {
1802 if tab == nil {
1803 return
1804 }
1805 a.mu.Lock()
1806 epoch := a.advanceSessionRuntimeEpochLocked(tab)
1807 a.mu.Unlock()
1808 a.notifyTabRuntimeRebuiltAtEpoch(tab, epoch)
1809 }
1810
1811 // notifyTabRuntimeRebuiltAtEpoch emits the rebuild fence for a transaction
1812 // that advanced its epoch inside the controller/path/lease commit. Keeping the
1813 // chosen epoch avoids a second generation bump after publication.
1814 func (a *App) notifyTabRuntimeRebuiltAtEpoch(tab *WorkspaceTab, epoch string) {
1815 if tab == nil {
1816 return
1817 }
1818 a.mu.RLock()
1819 sink := tab.sink
1820 tabID := tab.ID
1821 ctrl, _ := tab.Ctrl.(*control.Controller)
1822 a.mu.RUnlock()
1823 if ctrl != nil {
1824 go ctrl.NotifyInboxRuntimeReady()
1825 }
1826 if sink != nil && sink.context() != nil {
1827 sink.emitRuntimeEvent("runtime:rebuilt", tabID, epoch)
1828 return
1829 }
1830 a.emitRuntimeEvent("runtime:rebuilt", tabID, epoch)
1831 }
1832
1833 // replayPendingPromptsAfterRuntimeAttach publishes the runtime generation on
1834 // the tab sink before asking the same controller to replay. Both events use the
1835 // sink's FIFO queue, so the frontend cannot reject a valid prompt as belonging
1836 // to the runtime that was just replaced.
1837 func (a *App) replayPendingPromptsAfterRuntimeAttach(tabID string, sink *tabEventSink, ctrl control.SessionAPI, epoch string) {
1838 if ctrl == nil {
1839 return
1840 }
1841 if sink != nil && sink.context() != nil {
1842 // Use the sink captured in the same App.mu commit as ctrl. Re-reading the
1843 // tab here would let a concurrent replacement put the fence on a newer
1844 // sink while this older controller replays on the transferred one.
1845 sink.emitRuntimeEvent("runtime:rebuilt", tabID, epoch)
1846 } else {
1847 a.emitRuntimeEvent("runtime:rebuilt", tabID, epoch)
1848 }
1849 ctrl.ReplayPendingPrompts()
1850 }
1851
1852 func (a *App) emitReady(ctx context.Context, tabID ...string) {
1853 a.mu.RLock()
1854 hook := a.readyHook
1855 a.mu.RUnlock()
1856 if hook != nil {
1857 hook()
1858 return
1859 }
1860 if ctx != nil {
1861 if len(tabID) > 0 && strings.TrimSpace(tabID[0]) != "" {
1862 a.runtimeEvents.Emit(ctx, "agent:ready", strings.TrimSpace(tabID[0]))
1863 return
1864 }
1865 a.runtimeEvents.Emit(ctx, "agent:ready")
1866 }
1867 }
1868
1869 func (s *tabEventSink) recordReadTelemetry(e event.Event) {
1870 tabID, app := s.binding()
1871 if app == nil {
1872 return
1873 }
1874 app.mu.RLock()
1875 tab := app.tabByEventSinkIDLocked(tabID)
1876 var ctrl control.SessionAPI
1877 if tab != nil {
1878 ctrl = tab.Ctrl
1879 }
1880 app.mu.RUnlock()
1881 if tab == nil {
1882 return
1883 }
1884 turn := 0
1885 if ctrl != nil {
1886 turn = ctrl.Turn()
1887 }
1888
1889 // Parse read_file args: {"path": "...", "offset": N, "limit": N}
1890 var args struct {
1891 Path string `json:"path"`
1892 Offset int `json:"offset"`
1893 Limit int `json:"limit"`
1894 }
1895 path := e.Tool.Args
1896 offset := 0
1897 limit := 0
1898 if err := json.Unmarshal([]byte(e.Tool.Args), &args); err == nil && args.Path != "" {
1899 path = args.Path
1900 offset = args.Offset
1901 limit = args.Limit
1902 }
1903
1904 truncated := e.Tool.Truncated || strings.Contains(e.Tool.Output, "truncated") ||
1905 strings.Contains(e.Tool.Output, "File truncated")
1906
1907 _, sp := s.telemetryTab()
1908 if sp != "" {
1909 tab.syncTelemetryToSession(sp)
1910 }
1911 tab.recordReadFile(readFileRecord{
1912 Path: path,
1913 Turn: turn,
1914 Time: time.Now().UnixMilli(),
1915 Offset: offset,
1916 Limit: limit,
1917 Truncated: truncated,
1918 })
1919 if sp != "" {
1920 _ = saveTelemetryFor(sp, tab.telemetrySnapshot())
1921 }
1922 }
1923
1924 func (s *tabEventSink) recordTurnStarted() int64 {
1925 tab, sp := s.telemetryTab()
1926 if tab == nil {
1927 return 0
1928 }
1929 if sp != "" {
1930 tab.syncTelemetryToSession(sp)
1931 }
1932 startedAt := tab.recordTurnStarted(time.Now().UnixMilli())
1933 if sp != "" {
1934 _ = saveTelemetryFor(sp, tab.telemetrySnapshot())
1935 }
1936 return startedAt
1937 }
1938
1939 func (s *tabEventSink) recordTurnDone() {
1940 tab, sp := s.telemetryTab()
1941 if tab == nil {
1942 return
1943 }
1944 if sp != "" {
1945 tab.syncTelemetryToSession(sp)
1946 }
1947 tab.recordTurnDone(time.Now().UnixMilli())
1948 if sp != "" {
1949 _ = saveTelemetryFor(sp, tab.telemetrySnapshot())
1950 }
1951 }
1952
1953 func (s *tabEventSink) recordUsageTelemetry(e event.Event) {
1954 tab, sp := s.telemetryTab()
1955 if tab == nil {
1956 return
1957 }
1958 if sp != "" {
1959 tab.syncTelemetryToSession(sp)
1960 }
1961 tab.recordUsage(e)
1962 if sp != "" {
1963 _ = saveTelemetryFor(sp, tab.telemetrySnapshot())
1964 }
1965 }
1966
1967 func (s *tabEventSink) resetDisplayTurn() {
1968 tab, _ := s.eventTabAndController()
1969 if tab != nil {
1970 tab.resetDisplayTurn()
1971 }
1972 }
1973
1974 func (s *tabEventSink) recordDisplay(e event.Event) {
1975 tab, _ := s.eventTabAndController()
1976 if tab != nil {
1977 tab.recordDisplayEvent(e)
1978 }
1979 }
1980
1981 func (s *tabEventSink) flushDisplay(turnID string, cancelRequested bool) bool {
1982 tab, ctrl := s.eventTabAndController()
1983 if tab == nil || ctrl == nil {
1984 return false
1985 }
1986 history := ctrl.History()
1987 keepExecutorDisplay := cancelRequested && (lastHistoryMessageIsUser(history) || hasPendingInterruptedRecovery(history))
1988 messages := tab.takeDisplayTurn(keepExecutorDisplay)
1989 if len(messages) == 0 {
1990 acknowledgeProjectionForController(ctrl, turnID)
1991 return true
1992 }
1993 sessionPath := ctrl.SessionPath()
1994 if sessionPath == "" {
1995 return false
1996 }
1997 userContent := lastUserMessageContent(history)
1998 if strings.TrimSpace(userContent) == "" {
1999 return false
2000 }
2001 return persistOrEnqueueDisplayWrite(tab.displayBufferState(), &pendingDisplayWrite{
2002 dir: controllerSessionDir(ctrl),
2003 sessionPath: sessionPath,
2004 userContent: userContent,
2005 messages: messages,
2006 persist: func(dir, sessionPath, userContent string, messages []HistoryMessage) error {
2007 return recordSessionPlannerDisplayForTurn(dir, sessionPath, turnID, userContent, messages)
2008 },
2009 onPersisted: func() { acknowledgeProjectionForController(ctrl, turnID) },
2010 onRetry: func() { observeProjectionRetryForController(ctrl) },
2011 })
2012 }
2013
2014 func observeProjectionRetryForController(ctrl control.SessionAPI) {
2015 if ctrl == nil {
2016 return
2017 }
2018 if observer, ok := ctrl.(interface{ ObserveTurnProjectionRetry() }); ok {
2019 observer.ObserveTurnProjectionRetry()
2020 }
2021 }
2022
2023 func acknowledgeProjectionForController(ctrl control.SessionAPI, turnID string) {
2024 if ctrl == nil || strings.TrimSpace(turnID) == "" {
2025 return
2026 }
2027 if ack, ok := ctrl.(interface{ AcknowledgeTurnProjection(string) error }); ok {
2028 if err := ack.AcknowledgeTurnProjection(turnID); err != nil {
2029 slog.Warn("desktop: acknowledge turn display projection", "err", err)
2030 }
2031 }
2032 }
2033
2034 func lastHistoryMessageIsUser(history []provider.Message) bool {
2035 return len(history) > 0 && agent.IsUserAuthoredTurnMessage(history[len(history)-1])
2036 }
2037
2038 func hasPendingInterruptedRecovery(history []provider.Message) bool {
2039 for _, v := range slices.Backward(history) {
2040 m := v
2041 if m.LocalOnly && m.InterruptedTurn != nil {
2042 return m.InterruptedTurn.Pending
2043 }
2044 if agent.IsUserAuthoredTurnMessage(m) {
2045 return false
2046 }
2047 }
2048 return false
2049 }
2050
2051 func (s *tabEventSink) eventTabAndController() (*WorkspaceTab, control.SessionAPI) {
2052 tabID, app := s.binding()
2053 if app == nil {
2054 return nil, nil
2055 }
2056 app.mu.RLock()
2057 defer app.mu.RUnlock()
2058 tab := app.tabByEventSinkIDLocked(tabID)
2059 if tab == nil {
2060 return nil, nil
2061 }
2062 return tab, tab.Ctrl
2063 }
2064
2065 func lastUserMessageContent(msgs []provider.Message) string {
2066 for _, v := range slices.Backward(msgs) {
2067 if agent.IsUserAuthoredTurnMessage(v) {
2068 return agent.UserMessageText(v)
2069 }
2070 }
2071 return ""
2072 }
2073
2074 func (s *tabEventSink) telemetryTab() (*WorkspaceTab, string) {
2075 tabID, app := s.binding()
2076 if app == nil {
2077 return nil, ""
2078 }
2079 app.mu.RLock()
2080 tab := app.tabByEventSinkIDLocked(tabID)
2081 var ctrl control.SessionAPI
2082 if tab != nil {
2083 ctrl = tab.Ctrl
2084 }
2085 app.mu.RUnlock()
2086 if tab == nil {
2087 return nil, ""
2088 }
2089 if ctrl == nil {
2090 return tab, ""
2091 }
2092 if sp := ctrl.SessionPath(); sp != "" {
2093 return tab, sp
2094 }
2095 if lifecycle, ok := ctrl.(control.IdentityLifecycle); ok {
2096 if ref, ok := lifecycle.SessionRef(); ok {
2097 return tab, sessionRoute(ref.SessionID)
2098 }
2099 }
2100 return tab, ""
2101 }
2102
2103 // wire event with tab
2104
2105 func toWireTab(e event.Event, tabID string, runtimeEpoch ...string) wireEventTab {
2106 w := eventwire.ToWire(e)
2107 epoch := ""
2108 if len(runtimeEpoch) > 0 {
2109 epoch = runtimeEpoch[0]
2110 }
2111 return wireEventTab{
2112 Event: w,
2113 TabID: tabID,
2114 RuntimeEpoch: epoch,
2115 SessionHitTokens: e.SessionHit,
2116 SessionMissTokens: e.SessionMiss,
2117 SessionCost: 0, // filled by frontend accumulator per tab
2118 SessionCurrency: "",
2119 SessionCostUsd: 0, // deprecated compatibility alias
2120 }
2121 }
2122
2123 // wireEventTab extends the shared event wire with tab routing info. The frontend reducer
2124 // uses tabId to dispatch to the correct per-tab state.
2125 type wireEventTab struct {
2126 eventwire.Event
2127 TabID string `json:"tabId"`
2128 RuntimeEpoch string `json:"runtimeEpoch,omitempty"`
2129 SessionGeneration uint64 `json:"sessionGeneration,omitempty"`
2130 TurnStartedAt int64 `json:"turnStartedAt,omitempty"`
2131 // Session-cumulative tokens per tab.
2132 SessionHitTokens int `json:"sessionHitTokens,omitempty"`
2133 SessionMissTokens int `json:"sessionMissTokens,omitempty"`
2134 // SessionCost is filled by the frontend's per-tab accumulator.
2135 SessionCost float64 `json:"sessionCost,omitempty"`
2136 SessionCurrency string `json:"sessionCurrency,omitempty"`
2137 // SessionCostUsd is a deprecated compatibility alias. It mirrors
2138 // SessionCost and does not imply USD.
2139 SessionCostUsd float64 `json:"sessionCostUsd,omitempty"`
2140 }
2141
2142 // Tab management on App
2143
2144 func enrichTabMeta(meta TabMeta) TabMeta {
2145 if meta.Active {
2146 meta.GitBranch = workspaceGitBranchForMeta(meta.WorkspaceRoot, meta.repo)
2147 }
2148 return meta
2149 }
2150
2151 func enrichTabMetas(metas []TabMeta) []TabMeta {
2152 for i := range metas {
2153 if metas[i].Active {
2154 metas[i].GitBranch = workspaceGitBranchForMeta(metas[i].WorkspaceRoot, metas[i].repo)
2155 }
2156 }
2157 return metas
2158 }
2159
2160 func (a *App) tabMeta(tab *WorkspaceTab, active bool) TabMeta {
2161 runtimeView := a.sessionRuntimeViewLocked(tab)
2162 sessionPath := tab.currentSessionPath()
2163 sessionRevision, sessionDigest := a.tabHistoryFingerprint(tab, sessionPath)
2164 floor := derivedQualityFloor(tab)
2165 m := TabMeta{
2166 ID: tab.ID,
2167 Scope: tab.Scope,
2168 WorkspaceRoot: tab.WorkspaceRoot,
2169 WorkspaceID: tab.SessionWorkspace.ID,
2170 WorkspaceName: workspaceName(tab.WorkspaceRoot),
2171 WorkspacePath: tab.WorkspaceRoot,
2172 TopicID: tab.TopicID,
2173 TopicTitle: a.localizedTopicTitle(tab.TopicTitle, tab.topicTitleSource),
2174 SessionPath: sessionPath,
2175 SessionID: tab.SessionID,
2176 SessionRevision: sessionRevision,
2177 SessionDigest: sessionDigest,
2178 SessionGeneration: tab.SessionGeneration,
2179 ReadOnly: tab.ReadOnly,
2180 TakenOver: tab.Takeover.Spectator,
2181 Label: tab.Label,
2182 Ready: runtimeView.Phase == sessionRuntimeReady && tab.Ctrl != nil,
2183 Runtime: runtimeView,
2184 TurnStartedAt: tab.turnStartedAt(),
2185 Mode: currentTabMode(tab),
2186 CollaborationMode: currentTabCollaborationMode(tab),
2187 ToolApprovalMode: currentTabToolApprovalMode(tab),
2188 QualityFloor: floor.floor,
2189 FloorInferred: floor.inferred,
2190 AgentPreset: agentPresetForFloor(floor.floor),
2191 TokenMode: tokenModeForFloor(floor.floor),
2192 Goal: currentTabGoal(tab),
2193 GoalStatus: currentTabGoalStatus(tab),
2194 StartupErr: tab.StartupErr,
2195 HistoricalSource: tabHistoricalSourceLocked(tab),
2196 Active: active,
2197 Cwd: tab.WorkspaceRoot,
2198 IsolatedWorktree: floor.isolated,
2199 }
2200 if repo, ok := sessionWorkspaceRepo(tab.Ctrl, tab.WorkspaceRoot); ok {
2201 m.repo = repo
2202 }
2203 if strings.TrimSpace(tab.SessionID) != "" {
2204 m.Session = &session.SessionRef{HostID: "local", SessionID: strings.TrimSpace(tab.SessionID)}
2205 }
2206 switch tab.Scope {
2207 case "global":
2208 m.ProjectColor = globalProjectColor()
2209 m.WorkspaceName = globalProjectTitle()
2210 case "project":
2211 m.ProjectColor = projectColor(tab.WorkspaceRoot)
2212 }
2213 if tab.Ctrl != nil {
2214 m.setAuthenticationMeta(tab)
2215 status := tab.Ctrl.RuntimeStatus()
2216 if reader, ok := tab.Ctrl.(control.RuntimeStateReader); ok {
2217 m.GoalView = reader.RuntimeStateSnapshot().Goal
2218 }
2219 m.Running = status.Running || status.PendingPrompt || status.BackgroundJobs > 0
2220 m.PendingPrompt = status.PendingPrompt
2221 m.BackgroundJobs = status.BackgroundJobs
2222 m.CancelRequested = status.CancelRequested
2223 m.Cancellable = status.Cancellable
2224 m.TurnID = status.TurnID
2225 m.TurnStatus = string(status.Status)
2226 m.TurnEventSeq = status.TurnEventSeq
2227 m.TurnReplayAfter = status.ReplayAfterSeq
2228 }
2229 if a.botBridge != nil {
2230 m.RemoteControlled = a.botBridge.remoteControlledTabs()[tab.ID]
2231 }
2232 legacyMetaPath, legacyMetaOK := validatedLegacySessionPathForRead(tab.currentSessionPath())
2233 if legacyMetaOK {
2234 if meta, ok, err := agent.LoadBranchMeta(string(legacyMetaPath)); err == nil && ok {
2235 m.VersionKind = string(meta.EffectiveVersionKind())
2236 m.VersionState = string(meta.EffectiveVersionState())
2237 m.ParentVersionID = meta.ParentVersionID
2238 if meta.Recovered {
2239 m.Recovered = true
2240 m.RecoveryReason = meta.RecoveryReason
2241 m.RecoveryDigest = meta.RecoveryDigest
2242 m.RecoveryParentID = string(meta.ParentID)
2243 }
2244 }
2245 }
2246 return m
2247 }
2248
2249 // ListTabs returns every open view container's metadata for the frontend chrome and sidebar.
2250 func (a *App) ListTabs() []TabMeta {
2251 a.mu.RLock()
2252 out := make([]TabMeta, 0, len(a.tabs))
2253 ordered, needsRepair := a.orderedTabIDsSnapshotLocked()
2254 for _, id := range ordered {
2255 if tab := a.tabs[id]; tab != nil {
2256 out = append(out, a.tabMeta(tab, tab.ID == a.activeTabID))
2257 }
2258 }
2259 a.mu.RUnlock()
2260 if !needsRepair {
2261 return a.listTabsWithRemote(out)
2262 }
2263
2264 a.mu.Lock()
2265 out = make([]TabMeta, 0, len(a.tabs))
2266 for _, id := range a.orderedTabIDsLocked() {
2267 if tab := a.tabs[id]; tab != nil {
2268 out = append(out, a.tabMeta(tab, tab.ID == a.activeTabID))
2269 }
2270 }
2271 a.mu.Unlock()
2272 return a.listTabsWithRemote(out)
2273 }
2274
2275 // syncTabWorkspaceRootSpellings repoints visible and detached project runtimes
2276 // at the registry spelling. Registry writes may adopt the caller's spelling,
2277 // while the frontend compares roots exactly. Callers must not hold a.mu.
2278 func (a *App) syncTabWorkspaceRootSpellings() {
2279 projects := loadProjectsFile().Projects
2280 a.mu.Lock()
2281 changed := false
2282 for _, tab := range a.tabs {
2283 changed = syncRuntimeWorkspaceRootSpelling(tab, projects) || changed
2284 }
2285 for _, tab := range a.detachedSessions {
2286 changed = syncRuntimeWorkspaceRootSpelling(tab, projects) || changed
2287 }
2288 if changed {
2289 a.saveTabsLocked()
2290 }
2291 a.mu.Unlock()
2292 if changed {
2293 a.emitProjectTreeMetadataChanged()
2294 }
2295 }
2296
2297 // OpenProjectTab builds a controller scoped to workspaceRoot and opens the
2298 // session selected by the given topic. Topic selection resolves to a concrete
2299 // session path first; the visible tab is then attached to that session runtime.
2300 func (a *App) OpenProjectTab(workspaceRoot, topicID string) (TabMeta, error) {
2301 return a.openProjectTab(workspaceRoot, topicID)
2302 }
2303
2304 func (a *App) openProjectTab(workspaceRoot, topicID string) (TabMeta, error) {
2305 if workspaceRoot == "" {
2306 return TabMeta{}, fmt.Errorf("workspaceRoot is required")
2307 }
2308 if abs, err := filepath.Abs(workspaceRoot); err == nil {
2309 workspaceRoot = abs
2310 }
2311
2312 sessionPath, err := a.resolveTopicOpenPath("project", workspaceRoot, topicID)
2313 if err != nil {
2314 return TabMeta{}, err
2315 }
2316 return a.openTopicTabWithActivation("project", workspaceRoot, topicID, sessionPath, true)
2317 }
2318
2319 func (a *App) openTopicTab(scope, workspaceRoot, topicID, sessionPath string) (TabMeta, error) {
2320 return a.openTopicTabPreferLiveActivation(scope, workspaceRoot, topicID, sessionPath, true)
2321 }
2322
2323 func (a *App) openProjectTabInactive(workspaceRoot, topicID string) (TabMeta, error) {
2324 if workspaceRoot == "" {
2325 return TabMeta{}, fmt.Errorf("workspaceRoot is required")
2326 }
2327 if abs, err := filepath.Abs(workspaceRoot); err == nil {
2328 workspaceRoot = abs
2329 }
2330
2331 sessionPath, err := a.resolveTopicOpenPath("project", workspaceRoot, topicID)
2332 if err != nil {
2333 return TabMeta{}, err
2334 }
2335 return a.openTopicTabWithActivation("project", workspaceRoot, topicID, sessionPath, false)
2336 }
2337
2338 func (a *App) openGlobalTabInactive(topicID string) (TabMeta, error) {
2339 globalRoot := globalWorkspaceRoot()
2340 if err := os.MkdirAll(globalRoot, 0o755); err != nil {
2341 return TabMeta{}, fmt.Errorf("create global workspace: %w", err)
2342 }
2343
2344 sessionPath, err := a.resolveTopicOpenPath("global", "", topicID)
2345 if err != nil {
2346 return TabMeta{}, err
2347 }
2348 return a.openTopicTabWithActivation("global", "", topicID, sessionPath, false)
2349 }
2350
2351 func (a *App) openTopicTabWithActivation(scope, workspaceRoot, topicID, sessionPath string, activate bool, navigation ...uint64) (TabMeta, error) {
2352 return a.openTopicTabWithHead(scope, workspaceRoot, topicID, sessionPath, "", activate, navigation...)
2353 }
2354
2355 func (a *App) openTopicTabWithHead(scope, workspaceRoot, topicID, sessionPath, headID string, activate bool, navigation ...uint64) (TabMeta, error) {
2356 if err := a.validatePlaceholderTopicOpen(topicID, sessionPath); err != nil {
2357 return TabMeta{}, err
2358 }
2359 target, canonical, err := a.canonicalTopicOpen(sessionPath)
2360 if err != nil {
2361 return TabMeta{}, err
2362 }
2363 var actualRoot string
2364 if canonical != nil {
2365 scope, workspaceRoot, topicID = target.Scope, target.WorkspaceRoot, target.TopicID
2366 actualRoot = desktopWorkspaceRoot(scope, workspaceRoot)
2367 } else {
2368 actualRoot, sessionPath = a.resolveOpenTopicSessionPath(scope, workspaceRoot, sessionPath)
2369 }
2370 releaseAdmission, err := a.beginProjectRuntimeAdmission(scope, actualRoot)
2371 if err != nil {
2372 return TabMeta{}, err
2373 }
2374 defer releaseAdmission()
2375 if strings.TrimSpace(scope) == "project" {
2376 saveWorkspace(actualRoot)
2377 if err := a.registerProjectRoot(actualRoot); err != nil {
2378 return TabMeta{}, err
2379 }
2380 }
2381 targetKey := sessionRuntimeKey(sessionPath)
2382
2383 a.mu.Lock()
2384 if len(navigation) != 0 && a.desktopSessions.navigationSeq.Load() != navigation[0] {
2385 a.mu.Unlock()
2386 return TabMeta{}, errSessionNavigationSuperseded
2387 }
2388 if err := a.validateNativeHeadLocked(sessionPath, headID); err != nil {
2389 a.mu.Unlock()
2390 return TabMeta{}, err
2391 }
2392 if targetKey != "" {
2393 for _, tab := range a.tabs {
2394 if !topicTabReusableLocked(tab) {
2395 continue
2396 }
2397 if sessionRuntimeKeysOverlap(tab, sessionPath) {
2398 if activate {
2399 a.activeTabID = tab.ID
2400 }
2401 meta := a.tabMeta(tab, tab.ID == a.activeTabID)
2402 a.saveTabsLocked()
2403 a.mu.Unlock()
2404 return enrichTabMeta(meta), nil
2405 }
2406 }
2407 }
2408
2409 for _, tab := range a.tabs {
2410 if targetKey == "" && topicTabReusableLocked(tab) && tabMatchesTopicTarget(tab, scope, workspaceRoot, topicID) {
2411 if activate {
2412 a.activeTabID = tab.ID
2413 }
2414 meta := a.tabMeta(tab, tab.ID == a.activeTabID)
2415 a.saveTabsLocked()
2416 a.mu.Unlock()
2417 // This branch only admits an empty target key, so the matched topic
2418 // already identifies the session. No continuation rebind is needed.
2419 return enrichTabMeta(meta), nil
2420 }
2421 }
2422 source := a.liveRuntimeTabMatchingLocked(nil, sessionPath)
2423 if source == nil && targetKey == "" {
2424 source = a.liveRuntimeTabMatchingTopicLocked(nil, scope, workspaceRoot, topicID)
2425 }
2426 if source != nil && a.tabs[source.ID] == source {
2427 source = nil
2428 }
2429
2430 tab := a.newTopicTabLocked(scope, workspaceRoot, actualRoot, topicID, sessionPath, canonical)
2431 tab.SessionHeadID = headID
2432 tabID := tab.ID
2433
2434 a.tabs[tabID] = tab
2435 a.tabOrder = append(a.tabOrder, tabID)
2436 if activate {
2437 a.activeTabID = tabID
2438 }
2439 a.saveTabsLocked()
2440 meta := a.tabMeta(tab, tab.ID == a.activeTabID)
2441 a.mu.Unlock()
2442
2443 if source != nil {
2444 if a.attachExistingSessionRuntime(tab, runtimeAttachIdentity(source, sessionPath), a.ctx) {
2445 a.mu.RLock()
2446 meta = a.tabMeta(tab, tab.ID == a.activeTabID)
2447 a.mu.RUnlock()
2448 if scope == "project" {
2449 a.emitProjectTreeRuntimeChangedWithLegacy()
2450 }
2451 return enrichTabMeta(meta), nil
2452 }
2453 }
2454 a.startTabControllerBuild(tab)
2455 if scope == "project" {
2456 a.emitProjectTreeRuntimeChangedWithLegacy()
2457 }
2458 return enrichTabMeta(meta), nil
2459 }
2460
2461 // OpenGlobalTab opens a new global-scope tab (no project root). The global
2462 // workspace root is the reasonix user config directory.
2463 func (a *App) OpenGlobalTab(topicID string) (TabMeta, error) {
2464 return a.openGlobalTab(topicID)
2465 }
2466
2467 func (a *App) openGlobalTab(topicID string) (TabMeta, error) {
2468 globalRoot := globalWorkspaceRoot()
2469 if err := os.MkdirAll(globalRoot, 0o755); err != nil {
2470 return TabMeta{}, fmt.Errorf("create global workspace: %w", err)
2471 }
2472
2473 sessionPath, err := a.resolveTopicOpenPath("global", "", topicID)
2474 if err != nil {
2475 return TabMeta{}, err
2476 }
2477 return a.openTopicTabWithActivation("global", "", topicID, sessionPath, true)
2478 }
2479
2480 // OpenTopicSession opens a concrete saved session from the sidebar. Unlike
2481 // OpenProjectTab/OpenGlobalTab, it does not resolve the topic to the latest
2482 // session first; sessionPath is the runtime identity being selected.
2483 func (a *App) OpenTopicSession(scope, workspaceRoot, topicID, sessionPath string) (TabMeta, error) {
2484 return a.openTopicSession(scope, workspaceRoot, topicID, sessionPath)
2485 }
2486
2487 func (a *App) openTopicSession(scope, workspaceRoot, topicID, sessionPath string) (TabMeta, error) {
2488 return a.openTopicSessionWithNavigation(scope, workspaceRoot, topicID, sessionPath, a.desktopSessions.navigationSeq.Add(1))
2489 }
2490
2491 func (a *App) openTopicSessionWithNavigation(scope, workspaceRoot, topicID, sessionPath string, navigation uint64) (TabMeta, error) {
2492 if a.desktopSessions.navigationSeq.Load() != navigation {
2493 return TabMeta{}, errSessionNavigationSuperseded
2494 }
2495 if strings.HasPrefix(sessionPath, "bot-session:") {
2496 if !strings.HasPrefix(sessionPath, embeddedBotSessionPrefix) {
2497 return TabMeta{}, fmt.Errorf("invalid bot session identity")
2498 }
2499 path, err := a.embeddedBotSessionPath(scope, workspaceRoot, sessionPath)
2500 if err != nil {
2501 return TabMeta{}, err
2502 }
2503 meta, err := a.openTopicTabWithActivation(scope, workspaceRoot, topicID, path, true, navigation)
2504 if err != nil {
2505 return TabMeta{}, err
2506 }
2507 a.setTabReadOnly(meta.ID, true)
2508 meta.ReadOnly = true
2509 return meta, nil
2510 }
2511 validatedSource := false
2512 headID := ""
2513 if source, err := parseSessionSourceRoute(sessionPath); err != nil {
2514 return TabMeta{}, err
2515 } else if source != nil {
2516 target, err := a.resolveSessionTarget(SessionSelector{Source: source})
2517 if err != nil {
2518 return TabMeta{}, err
2519 }
2520 if target.Source != nil && strings.TrimSpace(target.Source.Path) != "" {
2521 scope, workspaceRoot, topicID = target.Scope, target.WorkspaceRoot, target.TopicID
2522 sessionPath = target.Source.Path
2523 validatedSource = true
2524 headID = target.Source.HeadID
2525 } else {
2526 sessionPath = target.SessionPath
2527 }
2528 }
2529 if _, ok := parseSessionRoute(sessionPath); ok {
2530 return a.openTopicTabWithActivation(scope, workspaceRoot, topicID, sessionPath, true, navigation)
2531 }
2532 if !validatedSource {
2533 if ref, adopted, err := a.legacyCanonicalRef(a.bootContext(), sessionPath); err != nil {
2534 return TabMeta{}, err
2535 } else if adopted {
2536 return a.openTopicTabWithActivation(scope, workspaceRoot, topicID, sessionRoute(ref.SessionID), true, navigation)
2537 }
2538 }
2539 if validatedSource {
2540 if info, statErr := os.Stat(sessionPath); statErr == nil && info.IsDir() && hasHistoricalSessionArtifacts(sessionPath) {
2541 return a.openTopicTabWithActivation(scope, workspaceRoot, topicID, sessionPath, true, navigation)
2542 }
2543 }
2544 scope = strings.TrimSpace(scope)
2545 if scope != "project" {
2546 scope = "global"
2547 workspaceRoot = ""
2548 }
2549 if scope == "project" {
2550 workspaceRoot = normalizeProjectRoot(workspaceRoot)
2551 if workspaceRoot == "" {
2552 return TabMeta{}, fmt.Errorf("workspaceRoot is required")
2553 }
2554 }
2555 _, validPath, err := a.sessionDirForPath(sessionPath)
2556 if err != nil {
2557 return TabMeta{}, err
2558 }
2559 return a.openTopicTabWithHead(scope, workspaceRoot, topicID, validPath, headID, true, navigation)
2560 }
2561
2562 // ActivateTopic opens a topic into the single visible conversation surface used
2563 // by layouts without a tab strip. It delegates the actual open/reuse behavior to
2564 // the classic tab path, then prunes every non-active visible tab so historical
2565 // clicks do not accumulate hidden startup work.
2566 //
2567 // Interop with StartTopicActivation: a legacy ActivateTopic call supersedes any
2568 // pending ticketed activation (its background completion becomes a no-op and a
2569 // "cancelled" event is emitted for the old requestId), and ticketed
2570 // activations supersede each other the same way. The synchronous return
2571 // contract — TabMeta after the prune — is unchanged.
2572 func (a *App) ActivateTopic(scope, workspaceRoot, topicID, sessionPath string) (TabMeta, error) {
2573 navigation := a.desktopSessions.navigationSeq.Add(1)
2574 a.singleSurfaceMu.Lock()
2575 defer a.singleSurfaceMu.Unlock()
2576 return a.activateTopicLocked(scope, workspaceRoot, topicID, sessionPath, navigation)
2577 }
2578
2579 func (a *App) activateTopicLocked(scope, workspaceRoot, topicID, sessionPath string, navigation uint64) (TabMeta, error) {
2580 if a.desktopSessions.navigationSeq.Load() != navigation {
2581 return TabMeta{}, errSessionNavigationSuperseded
2582 }
2583
2584 var meta TabMeta
2585 var err error
2586 if strings.TrimSpace(sessionPath) != "" {
2587 meta, err = a.openTopicSessionWithNavigation(scope, workspaceRoot, topicID, sessionPath, navigation)
2588 } else if strings.TrimSpace(scope) == "project" {
2589 meta, err = a.openProjectTab(workspaceRoot, topicID)
2590 } else {
2591 meta, err = a.openGlobalTab(topicID)
2592 }
2593 if err != nil {
2594 return TabMeta{}, err
2595 }
2596 // A legacy activation supersedes any pending ticketed activation: its
2597 // completion must not prune or publish after this call's own prune.
2598 if reqID, tabID := a.supersedePendingTopicActivation(meta.ID); reqID != "" {
2599 a.emitTopicActivation(TopicActivationEvent{RequestID: reqID, TabID: tabID, Phase: topicActivationPhaseCancelled})
2600 }
2601 return a.keepOnlyVisibleTab(meta.ID)
2602 }
2603
2604 // EnsureBlankSurface mirrors EnsureBlankTab for no-tab-strip layouts: after
2605 // creating or reusing a blank session, it removes other visible tabs while
2606 // preserving running runtimes as detached background sessions.
2607 func (a *App) EnsureBlankSurface(scope, workspaceRoot string) (TabMeta, error) {
2608 return a.ensureBlankSurface(scope, workspaceRoot)
2609 }
2610
2611 func (a *App) ensureBlankSurface(scope, workspaceRoot string) (TabMeta, error) {
2612 navigation := a.desktopSessions.navigationSeq.Add(1)
2613 a.singleSurfaceMu.Lock()
2614 defer a.singleSurfaceMu.Unlock()
2615 if a.desktopSessions.navigationSeq.Load() != navigation {
2616 return TabMeta{}, errSessionNavigationSuperseded
2617 }
2618
2619 meta, err := a.ensureBlankTab(scope, workspaceRoot)
2620 if err != nil {
2621 return TabMeta{}, err
2622 }
2623 // Same interop rule as ActivateTopic: this synchronous surface switch
2624 // supersedes any pending ticketed activation.
2625 if reqID, tabID := a.supersedePendingTopicActivation(meta.ID); reqID != "" {
2626 a.emitTopicActivation(TopicActivationEvent{RequestID: reqID, TabID: tabID, Phase: topicActivationPhaseCancelled})
2627 }
2628 return a.keepOnlyVisibleTab(meta.ID)
2629 }
2630
2631 func tabMatchesTopicTarget(tab *WorkspaceTab, scope, workspaceRoot, topicID string) bool {
2632 if tab == nil || tab.Scope != scope || tab.TopicID != topicID {
2633 return false
2634 }
2635 if scope == "global" {
2636 return true
2637 }
2638 return sameProjectRoot(tab.WorkspaceRoot, workspaceRoot)
2639 }
2640
2641 func tabInWorkspace(tab *WorkspaceTab, workspaceRoot string) bool {
2642 return tab != nil &&
2643 tab.Scope == "project" &&
2644 sameProjectRoot(tab.WorkspaceRoot, workspaceRoot)
2645 }
2646
2647 // EnsureBlankTab activates the existing blank tab for the target scope, or
2648 // creates one if none exists. Reusing a blank tab keeps repeated "new session"
2649 // clicks from piling up empty conversations.
2650 func (a *App) EnsureBlankTab(scope, workspaceRoot string) (TabMeta, error) {
2651 return a.ensureBlankTab(scope, workspaceRoot)
2652 }
2653
2654 func (a *App) ensureBlankTab(scope, workspaceRoot string) (TabMeta, error) {
2655 scope = strings.TrimSpace(scope)
2656 if scope != "project" {
2657 scope = "global"
2658 }
2659
2660 globalRoot := ""
2661 if scope == "project" {
2662 workspaceRoot = strings.TrimSpace(workspaceRoot)
2663 if workspaceRoot == "" {
2664 return TabMeta{}, fmt.Errorf("workspaceRoot is required")
2665 }
2666 if abs, err := filepath.Abs(workspaceRoot); err == nil {
2667 workspaceRoot = abs
2668 }
2669 } else {
2670 workspaceRoot = ""
2671 globalRoot = globalWorkspaceRoot()
2672 if err := os.MkdirAll(globalRoot, 0o755); err != nil {
2673 return TabMeta{}, fmt.Errorf("create global workspace: %w", err)
2674 }
2675 }
2676
2677 var created *WorkspaceTab
2678 // Compute actual root early — both the indexed-topic fallback and the
2679 // new-topic path need it when constructing the tab below.
2680 actualRoot := workspaceRoot
2681 if scope == "global" {
2682 actualRoot = globalRoot
2683 }
2684 releaseAdmission, err := a.beginProjectRuntimeAdmission(scope, actualRoot)
2685 if err != nil {
2686 return TabMeta{}, err
2687 }
2688 defer releaseAdmission()
2689 if scope == "project" {
2690 saveWorkspace(workspaceRoot)
2691 if err := a.registerProjectRoot(workspaceRoot); err != nil {
2692 return TabMeta{}, err
2693 }
2694 }
2695 defaultModel, defaultToolApprovalMode := desktopNewSessionDefaults(scope, actualRoot)
2696
2697 a.mu.Lock()
2698 var reusable *WorkspaceTab
2699 for _, id := range a.orderedTabIDsLocked() {
2700 tab := a.tabs[id]
2701 if a.blankTabMatchesTargetLocked(tab, scope, workspaceRoot) {
2702 if err := resetReusableBlankTabTitle(tab, scope, workspaceRoot); err != nil {
2703 a.mu.Unlock()
2704 return TabMeta{}, err
2705 }
2706 reusable = tab
2707 break
2708 }
2709 }
2710 if reusable != nil {
2711 a.mu.Unlock()
2712 if err := a.alignReusableBlankTabModel(reusable, defaultModel); err != nil {
2713 return TabMeta{}, err
2714 }
2715 a.mu.Lock()
2716 if reusable.removed || a.tabs[reusable.ID] != reusable {
2717 a.mu.Unlock()
2718 return TabMeta{}, fmt.Errorf("blank session changed while applying the default model; retry")
2719 }
2720 a.activeTabID = reusable.ID
2721 meta := a.tabMeta(reusable, true)
2722 a.saveTabsLocked()
2723 a.mu.Unlock()
2724 return enrichTabMeta(meta), nil
2725 }
2726
2727 // New blank sessions start from global defaults for model and approval
2728 // posture, keeping execution-local settings (effort/floor/MCP) from the
2729 // active tab without letting it override global defaults (#4019).
2730 inheritedModel := defaultModel
2731 var inheritedEffort *string
2732 inheritedFloor := tabQualityFloor(workspaceRoot, a.activeTabLocked().qualityFloorSafe())
2733 inheritedMode := tabModeFromAxes(false, defaultToolApprovalMode == control.ToolApprovalDangerFullAccess)
2734 inheritedToolApprovalMode := defaultToolApprovalMode
2735 inheritedDisabledMCP := map[string]ServerView{}
2736 var inheritedMCPOrder []string
2737 if active := a.activeTabLocked(); active != nil {
2738 inheritedEffort = cloneStringPtr(active.effort)
2739 inheritedDisabledMCP = cloneServerViewMap(active.disabledMCP)
2740 inheritedMCPOrder = append([]string(nil), active.mcpOrder...)
2741 }
2742
2743 if topicID := a.indexedBlankTopicIDLocked(scope, workspaceRoot); topicID != "" {
2744 // Reuse a previously-indexed but unused blank topic instead of
2745 // creating a new one. Build it inline (not via OpenProjectTab /
2746 // OpenGlobalTab) so it inherits settings from the active tab.
2747 if loadTopicCreatedAt(topicTitleRoot(scope, workspaceRoot), topicID) <= 0 {
2748 createdAt := topicIDCreatedAt(topicID)
2749 if createdAt <= 0 {
2750 createdAt = time.Now().UnixMilli()
2751 }
2752 _ = setTopicCreatedAt(topicTitleRoot(scope, workspaceRoot), topicID, createdAt)
2753 }
2754 tabID := a.newUniqueTabIDLocked()
2755 topicTitle := topicTitleForTab(scope, workspaceRoot, topicID)
2756 created = &WorkspaceTab{
2757 ID: tabID,
2758 Scope: scope,
2759 WorkspaceRoot: actualRoot,
2760 TopicID: topicID,
2761 TopicTitle: topicTitle,
2762 topicTitleSource: loadTopicTitleSource(topicTitleRoot(scope, workspaceRoot), topicID),
2763 model: inheritedModel,
2764 effort: inheritedEffort,
2765 qualityFloor: inheritedFloor,
2766 mode: inheritedMode,
2767 toolApprovalMode: inheritedToolApprovalMode,
2768 disabledMCP: inheritedDisabledMCP,
2769 mcpOrder: inheritedMCPOrder,
2770 }
2771 created.sink = &tabEventSink{tabID: tabID, app: a}
2772 a.tabs[tabID] = created
2773 a.tabOrder = append(a.tabOrder, tabID)
2774 a.activeTabID = tabID
2775 a.saveTabsLocked()
2776 a.mu.Unlock()
2777
2778 // A new-session command returns an executable immutable identity. Build
2779 // and publish it before returning instead of exposing a pathless tab whose
2780 // eventual asynchronous startup could race a second create/delete action.
2781 return a.startCreatedSessionTab(created, actualRoot)
2782 }
2783
2784 topicID := newTopicID()
2785 topicTitle := defaultTopicTitle
2786 createdAt := time.Now().UnixMilli()
2787 if err := createTopicState(workspaceRoot, topicID, topicTitle, topicTitleSourceAuto, createdAt); err != nil {
2788 a.mu.Unlock()
2789 return TabMeta{}, err
2790 }
2791 _ = prependTopicInProjectsFile(workspaceRoot, topicID, false)
2792
2793 tabID := a.newUniqueTabIDLocked()
2794 created = &WorkspaceTab{
2795 ID: tabID,
2796 Scope: scope,
2797 WorkspaceRoot: actualRoot,
2798 TopicID: topicID,
2799 TopicTitle: topicTitleForTab(scope, workspaceRoot, topicID),
2800 topicTitleSource: topicTitleSourceAuto,
2801 model: inheritedModel,
2802 effort: inheritedEffort,
2803 qualityFloor: inheritedFloor,
2804 mode: inheritedMode,
2805 toolApprovalMode: inheritedToolApprovalMode,
2806 disabledMCP: inheritedDisabledMCP,
2807 mcpOrder: inheritedMCPOrder,
2808 }
2809 created.sink = &tabEventSink{tabID: tabID, app: a}
2810 a.tabs[tabID] = created
2811 a.tabOrder = append(a.tabOrder, tabID)
2812 a.activeTabID = tabID
2813 a.saveTabsLocked()
2814 a.mu.Unlock()
2815
2816 return a.startCreatedSessionTab(created, actualRoot)
2817 }
2818
2819 func (a *App) startCreatedSessionTab(created *WorkspaceTab, actualRoot string) (TabMeta, error) {
2820 a.buildTabController(created)
2821 a.mu.RLock()
2822 meta := a.tabMeta(created, true)
2823 startupErr := created.StartupErr
2824 ready := created.Ctrl != nil && created.SessionID != ""
2825 a.mu.RUnlock()
2826 if !ready {
2827 return TabMeta{}, fmt.Errorf("create session runtime: %s", startupErr)
2828 }
2829 a.emitProjectTreeChangedForSessionDirs(desktopSessionDir(actualRoot))
2830 return enrichTabMeta(meta), nil
2831 }
2832
2833 // blankTabMatchesTargetLocked returns true if tab is a reusable blank tab
2834 // matching the given scope/project root — no running controller, no real history.
2835 func (a *App) blankTabMatchesTargetLocked(tab *WorkspaceTab, scope, workspaceRoot string) bool {
2836 if tab == nil || tab.Scope != scope {
2837 return false
2838 }
2839 if scope == "project" && !sameProjectRoot(tab.WorkspaceRoot, workspaceRoot) {
2840 return false
2841 }
2842 if tab.Ctrl == nil {
2843 return blankTabSessionPathHasNoContent(tab)
2844 }
2845 if tab.hasActiveRuntimeWork() {
2846 return false
2847 }
2848 return !messagesHaveConversationContent(tab.Ctrl.History())
2849 }
2850
2851 func createEmptySessionFile(dir, model string) (string, error) {
2852 dir = strings.TrimSpace(dir)
2853 if dir == "" {
2854 return "", fmt.Errorf("session dir is required")
2855 }
2856 if err := os.MkdirAll(dir, 0o755); err != nil {
2857 return "", err
2858 }
2859 for range 3 {
2860 path := agent.NewSessionPath(dir, model)
2861 f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o644)
2862 if err == nil {
2863 if closeErr := f.Close(); closeErr != nil {
2864 return "", closeErr
2865 }
2866 // Ensure branch meta exists for topic ownership; Auto Guard no longer
2867 // stores a per-session toggle (it is built into Auto).
2868 _, _ = agent.EnsureBranchMeta(path)
2869 return path, nil
2870 }
2871 if os.IsExist(err) {
2872 continue
2873 }
2874 return "", err
2875 }
2876 return "", fmt.Errorf("create empty session file: exhausted filename retries")
2877 }
2878
2879 func pinNewEmptySessionBranchMeta(path, scope, workspaceRoot, topicID, topicTitle string) error {
2880 if err := pinSessionBranchMeta(path, scope, workspaceRoot, topicID, topicTitle); err != nil {
2881 pinErr := fmt.Errorf("pin empty session metadata: %w", err)
2882 if cleanupErr := removeDesktopSessionArtifacts(path); cleanupErr != nil {
2883 return errors.Join(pinErr, fmt.Errorf("clean up unbound empty session: %w", cleanupErr))
2884 }
2885 return pinErr
2886 }
2887 return nil
2888 }
2889
2890 // pinSessionBranchMeta stores the workspace scope, root, and topic on a newly
2891 // created session before a controller can reconcile the tab against it.
2892 func pinSessionBranchMeta(sessionPath, scope, workspaceRoot, topicID, topicTitle string) error {
2893 unlock, err := agent.LockSessionMetaPath(sessionPath)
2894 if err != nil {
2895 return err
2896 }
2897 defer unlock()
2898 m, err := agent.EnsureBranchMetaLocked(sessionPath)
2899 if err != nil {
2900 return err
2901 }
2902 if strings.TrimSpace(scope) == "project" {
2903 workspaceRoot = normalizeProjectRoot(workspaceRoot)
2904 if workspaceRoot == "" {
2905 return fmt.Errorf("project workspace root is required")
2906 }
2907 scope = "project"
2908 } else {
2909 scope = "global"
2910 workspaceRoot = ""
2911 }
2912 m.Scope = scope
2913 m.WorkspaceRoot = workspaceRoot
2914 m.TopicID = topicID
2915 m.TopicTitle = topicTitle
2916 return agent.SaveBranchMetaPreserveUpdatedLocked(sessionPath, m)
2917 }
2918
2919 func blankTabSessionPathHasNoContent(tab *WorkspaceTab) bool {
2920 if tab == nil {
2921 return false
2922 }
2923 if strings.TrimSpace(tab.SessionPath) == "" {
2924 return true
2925 }
2926 return sessionPathHasNoContent(tabSessionDir(tab), tab.SessionPath)
2927 }
2928
2929 func sessionPathHasNoContent(sessionDir, sessionPath string) bool {
2930 if strings.TrimSpace(sessionPath) == "" {
2931 return true
2932 }
2933 path, ok := pinnedTabSessionPath(sessionDir, sessionPath)
2934 if !ok {
2935 return false
2936 }
2937 info, err := os.Stat(path)
2938 if err != nil {
2939 return false
2940 }
2941 if info.IsDir() {
2942 return false
2943 }
2944 if info.Size() == 0 {
2945 return true
2946 }
2947 session, err := agent.LoadSession(path)
2948 if err != nil {
2949 return false
2950 }
2951 return !session.HasContent()
2952 }
2953
2954 func resetReusableBlankTabTitle(tab *WorkspaceTab, scope, workspaceRoot string) error {
2955 if tab == nil {
2956 return nil
2957 }
2958 topicID := strings.TrimSpace(tab.TopicID)
2959 if topicID == "" {
2960 return nil
2961 }
2962 titleRoot := topicTitleRoot(scope, workspaceRoot)
2963 if source := loadTopicTitleSource(titleRoot, topicID); source != topicTitleSourceAuto {
2964 return nil
2965 }
2966 if err := setTopicTitleWithSource(titleRoot, topicID, defaultTopicTitle, topicTitleSourceAuto); err != nil {
2967 return err
2968 }
2969 _ = deleteTopicAutoTitleMeta(titleRoot, topicID)
2970 tab.TopicTitle = defaultTopicTitle
2971 tab.topicTitleSource = topicTitleSourceAuto
2972 return nil
2973 }
2974
2975 // indexedBlankTopicIDLocked finds a blank topic ID that is indexed on disk
2976 // but not open in any tab — for reusing without creating a new topic.
2977 func (a *App) indexedBlankTopicIDLocked(scope, workspaceRoot string) string {
2978 titleRoot := topicTitleRoot(scope, workspaceRoot)
2979 titles := loadTopicTitles(titleRoot)
2980 f := loadProjectsFile()
2981
2982 var topicIDs []string
2983 if scope == "global" {
2984 topicIDs = orderedTopicIDs(f.GlobalTopics, titles)
2985 } else if i := projectIndexByRoot(f.Projects, workspaceRoot); i >= 0 {
2986 topicIDs = orderedTopicIDs(f.Projects[i].Topics, titles)
2987 }
2988 if len(topicIDs) == 0 {
2989 return ""
2990 }
2991 // Blank-tab reuse is an automatic write path: the reused ID flows into
2992 // ensureTopicIndexed, whose intentional single-topic prepend clears delete
2993 // tombstones. Picking a tombstoned topic here (its default title can
2994 // linger title-only after a delete raced a scan save) would therefore
2995 // fully resurrect a topic the user removed — skip them.
2996 deletedTopics := make(map[string]bool, len(f.DeletedTopics))
2997 for _, id := range f.DeletedTopics {
2998 deletedTopics[id] = true
2999 }
3000
3001 openTopics := map[string]bool{}
3002 for _, tab := range a.tabs {
3003 if tab == nil || tab.Scope != scope || strings.TrimSpace(tab.TopicID) == "" {
3004 continue
3005 }
3006 if scope == "project" && !sameProjectRoot(tab.WorkspaceRoot, workspaceRoot) {
3007 continue
3008 }
3009 openTopics[tab.TopicID] = true
3010 }
3011 seenSessionDirs := map[string]bool{}
3012 sessionIndexes := []topicSessionDirIndex{}
3013 addSessionIndex := func(dir string) {
3014 dir = cleanDesktopPath(dir)
3015 if dir == "" {
3016 return
3017 }
3018 if seenSessionDirs[dir] {
3019 return
3020 }
3021 seenSessionDirs[dir] = true
3022 if index, err := topicSessionIndexForDir(dir); err == nil {
3023 sessionIndexes = append(sessionIndexes, index)
3024 }
3025 }
3026 if scope == "project" {
3027 addSessionIndex(desktopSessionDir(workspaceRoot))
3028 } else {
3029 addSessionIndex(config.SessionDir())
3030 addSessionIndex(desktopSessionDir(globalWorkspaceRoot()))
3031 }
3032 for _, topicID := range topicIDs {
3033 if deletedTopics[topicID] || openTopics[topicID] {
3034 continue
3035 }
3036 if topicTitleForTab(scope, workspaceRoot, topicID) != defaultTopicTitle {
3037 continue
3038 }
3039 hasSession := false
3040 leaseHeld := false
3041 for _, index := range sessionIndexes {
3042 if topicSessionIndexHasContentTopic(index, topicID) {
3043 hasSession = true
3044 break
3045 }
3046 if topicSessionIndexHasForeignLeaseTopic(index, topicID) {
3047 leaseHeld = true
3048 }
3049 }
3050 if hasSession || leaseHeld {
3051 continue
3052 }
3053 return topicID
3054 }
3055 return ""
3056 }
3057
3058 // ReorderTabs persists the full local+remote strip while keeping each
3059 // registry's internal order independent.
3060 func (a *App) ReorderTabs(tabIDs []string) error {
3061 a.remoteTabMu.Lock()
3062 remoteCount := len(a.remoteTabs)
3063 a.remoteTabMu.Unlock()
3064 a.mu.Lock()
3065 if len(tabIDs) != len(a.tabs)+remoteCount {
3066 a.mu.Unlock()
3067 return fmt.Errorf("tab order length mismatch")
3068 }
3069 seen := make(map[string]bool, len(tabIDs))
3070 next := make([]string, 0, len(a.tabs))
3071 nextRemote := make([]string, 0, remoteCount)
3072 for _, id := range tabIDs {
3073 if seen[id] {
3074 a.mu.Unlock()
3075 return fmt.Errorf("duplicate tab %q", id)
3076 }
3077 seen[id] = true
3078 if _, ok := a.tabs[id]; ok {
3079 next = append(next, id)
3080 } else {
3081 nextRemote = append(nextRemote, id)
3082 }
3083 }
3084 if len(next) != len(a.tabs) {
3085 a.mu.Unlock()
3086 return fmt.Errorf("tab order is missing local tabs")
3087 }
3088 a.remoteTabMu.Lock()
3089 remoteOK := len(nextRemote) == len(a.remoteTabs)
3090 if remoteOK {
3091 for _, id := range nextRemote {
3092 if a.remoteTabs[id] == nil {
3093 remoteOK = false
3094 break
3095 }
3096 }
3097 }
3098 if !remoteOK {
3099 a.remoteTabMu.Unlock()
3100 a.mu.Unlock()
3101 return fmt.Errorf("tab order is missing remote tabs")
3102 }
3103 a.remoteTabLayout.order = append([]string(nil), nextRemote...)
3104 a.remoteTabLayout.stripOrder = append([]string(nil), tabIDs...)
3105 a.remoteTabMu.Unlock()
3106 a.tabOrder = next
3107 dir, entries, activeID, version := a.saveTabsCollectLocked()
3108 a.mu.Unlock()
3109 a.saveTabsWrite(dir, entries, activeID, version)
3110 return nil
3111 }
3112
3113 // CloseTab removes a visible tab. If the tab's session still has foreground or
3114 // background work, the controller is detached so closing a view does not destroy
3115 // the session runtime.
3116 func (a *App) CloseTab(tabID string) error {
3117 return a.closeTab(tabID, true)
3118 }
3119
3120 func (a *App) closeTabRuntime(tabID string, allowDetach bool) error {
3121 defer a.lockRuntimeMutation("close-tab")()
3122 a.sessionRemovalMu.Lock()
3123 defer a.sessionRemovalMu.Unlock()
3124 // The runtime mutation barrier is acquired before sessionRemovalMu. This waits
3125 // for a turn whose admission is already in progress, blocks later turns/builds,
3126 // and leaves the tab visible until an earlier MCP Host-wide gate completes.
3127
3128 a.mu.Lock()
3129 tab, ok := a.tabs[tabID]
3130 if !ok {
3131 a.mu.Unlock()
3132 return fmt.Errorf("tab %q not found", tabID)
3133 }
3134 a.mu.Unlock()
3135
3136 // Snapshot while the tab binding is still present, but outside a.mu because
3137 // snapshot recovery can re-enter App and acquire a.mu. sessionRemovalMu keeps
3138 // DeleteSession/topic/workspace removal from trashing the same files while
3139 // this save is in flight.
3140 if err := a.snapshotTab(tab); err != nil {
3141 slog.Warn("desktop: snapshot before closing tab failed", "tab", tabID, "err", err)
3142 return fmt.Errorf("save current session before closing tab: %w", err)
3143 }
3144 if err := a.saveTabSessionMetaForCurrentSession(tab); err != nil {
3145 slog.Warn("desktop: session metadata before closing tab failed", "tab", tabID, "err", err)
3146 return fmt.Errorf("save current session metadata before closing tab: %w", err)
3147 }
3148 // A terminal belongs to the visible chat tab, even when another tab points
3149 // at the same project. Reap its PTY before removing the tab binding.
3150 if a.terminals != nil {
3151 a.terminals.closeForTab(tabID)
3152 }
3153
3154 // Claim the mirror's farewell while this tab still owns its writer; a close
3155 // that returns early keeps the writer and hands the claim back.
3156 closingMirror, releaseMirrorClaim := a.claimTakeoverMirrorFarewell(a.currentSessionPathFor(tab))
3157 defer releaseMirrorClaim()
3158
3159 a.mu.Lock()
3160 if current := a.tabs[tabID]; current != tab {
3161 a.mu.Unlock()
3162 if current == nil {
3163 return fmt.Errorf("tab %q not found", tabID)
3164 }
3165 return fmt.Errorf("tab %q changed while closing", tabID)
3166 }
3167 if !allowDetach && tab.hasActiveRuntimeWork() {
3168 a.mu.Unlock()
3169 return fmt.Errorf("task still has active work")
3170 }
3171 if tab.Ctrl == nil || !tab.hasActiveRuntimeWork() {
3172 a.markTabRemovedLocked(tab)
3173 }
3174
3175 ordered := a.orderedTabIDsLocked()
3176 closedIndex := -1
3177 for i, id := range ordered {
3178 if id == tabID {
3179 closedIndex = i
3180 break
3181 }
3182 }
3183 delete(a.tabs, tabID)
3184 a.removeTabOrderLocked(tabID)
3185 wasActive := a.activeTabID == tabID
3186 if wasActive {
3187 a.activeTabID = ""
3188 if len(a.tabOrder) > 0 {
3189 nextIndex := max(closedIndex, 0)
3190 if nextIndex >= len(a.tabOrder) {
3191 nextIndex = len(a.tabOrder) - 1
3192 }
3193 a.activeTabID = a.tabOrder[nextIndex]
3194 }
3195 }
3196 a.saveTabsLocked()
3197 // Snapshot the teardown targets while still holding the lock: the tab is
3198 // no longer reachable from a.tabs after this section, but locked writers
3199 // holding stale pointers (rememberTabSessionPath, applySessionBindingToTab)
3200 // can still write its fields under a.mu.
3201 closeCtrl := tab.Ctrl
3202 closeSink := tab.sink
3203 a.mu.Unlock()
3204 if a.workspaceHub != nil {
3205 a.workspaceHub.reconcileRoots()
3206 }
3207
3208 // Tear down outside App.mu while retaining the lifecycle barrier acquired
3209 // before the tab binding was removed.
3210 discardPath, discardTransientBlank := a.transientBlankSessionArtifactPath(tab)
3211 if closeCtrl != nil {
3212 if allowDetach && controllerHasActiveRuntimeWork(closeCtrl) && a.detachSessionRuntime(tab) {
3213 // Detached runtimes keep running and must keep saving: do not
3214 // clear the path or drain for them.
3215 return nil
3216 }
3217 closeCtrl.SetSessionPath("") // future snapshots become no-ops
3218 a.quiesceTabAutosave(tab) // wait for any in-flight snapshot to finish
3219 closeCtrl.Cancel()
3220 closeCtrl.Close()
3221 // Release the shared plugin host reference. The host stays alive as
3222 // long as any other tab for the same workspace root holds a reference;
3223 // on the last release the host is closed and its subprocesses exit.
3224 a.releaseTabSharedHost(tab)
3225 tab.releaseSessionLease()
3226 }
3227 // The writer is released: tell Serve now so it hands the session straight
3228 // back instead of waiting for the writer to drop.
3229 a.endTakeoverMirrorForClosedTab(closingMirror)
3230 if closeSink != nil {
3231 closeSink.clearContext() // stop further emissions (nil ctx -> Emit becomes no-op)
3232 }
3233 if discardTransientBlank {
3234 if discardTransientBlankSessionArtifacts(discardPath) {
3235 a.removeSessionCatalogPath(discardPath, "transient_blank_discarded")
3236 }
3237 }
3238 return nil
3239 }
3240
3241 func (a *App) applySingleSurfaceTabPolicy() error {
3242 a.singleSurfaceMu.Lock()
3243 defer a.singleSurfaceMu.Unlock()
3244
3245 a.mu.RLock()
3246 tabID := a.activeTabID
3247 if tabID == "" || a.tabs[tabID] == nil {
3248 for _, id := range a.tabOrder {
3249 if a.tabs[id] != nil {
3250 tabID = id
3251 break
3252 }
3253 }
3254 if tabID == "" {
3255 for id := range a.tabs {
3256 tabID = id
3257 break
3258 }
3259 }
3260 }
3261 a.mu.RUnlock()
3262 if tabID == "" {
3263 return nil
3264 }
3265 _, err := a.keepOnlyVisibleTab(tabID)
3266 return err
3267 }
3268
3269 func (a *App) removeVisibleTabRuntimeAdmissionHeld(tab *WorkspaceTab) {
3270 if tab == nil {
3271 return
3272 }
3273 a.mu.RLock()
3274 ctrl := tab.Ctrl
3275 a.mu.RUnlock()
3276 if ctrl != nil && controllerHasActiveRuntimeWork(ctrl) && a.detachSessionRuntime(tab) {
3277 return
3278 }
3279 if err := a.snapshotTab(tab); err != nil {
3280 slog.Warn("desktop: snapshot before removing visible tab runtime failed", "tab", tab.ID, "err", err)
3281 }
3282 discardPath, discardTransientBlank := a.transientBlankSessionArtifactPath(tab)
3283 a.markTabRemoved(tab)
3284 a.closeTabRuntimeAdmissionHeld(tab)
3285 if discardTransientBlank {
3286 if discardTransientBlankSessionArtifacts(discardPath) {
3287 a.removeSessionCatalogPath(discardPath, "transient_blank_discarded")
3288 }
3289 }
3290 }
3291
3292 // transientBlankSessionArtifactPath reports the artifact path to discard when
3293 // closing a still-blank tab. It snapshots the racy tab fields under a.mu and
3294 // keeps the file probe (sessionPathHasNoContent) outside the lock. Callers
3295 // must not hold a.mu.
3296 func (a *App) transientBlankSessionArtifactPath(tab *WorkspaceTab) (string, bool) {
3297 if tab == nil {
3298 return "", false
3299 }
3300 snap := a.tabRuntimeSnapshot(tab)
3301 if snap.readOnly || strings.TrimSpace(snap.topicID) != "" || controllerHasActiveRuntimeWork(snap.ctrl) {
3302 return "", false
3303 }
3304 if strings.TrimSpace(snap.sessionPath) == "" {
3305 return "", false
3306 }
3307 dir := sessionDirForSnapshot(snap)
3308 if !sessionPathHasNoContent(dir, snap.sessionPath) {
3309 return "", false
3310 }
3311 path, ok := pinnedTabSessionPath(dir, snap.sessionPath)
3312 if !ok {
3313 return "", false
3314 }
3315 return path, true
3316 }
3317
3318 func (a *App) markTabRemoved(tab *WorkspaceTab) {
3319 a.mu.Lock()
3320 a.markTabRemovedLocked(tab)
3321 a.mu.Unlock()
3322 }
3323
3324 func (a *App) markTabRemovedLocked(tab *WorkspaceTab) {
3325 if tab == nil {
3326 return
3327 }
3328 tab.removed = true
3329 if tab.buildCancel != nil {
3330 tab.buildCancel()
3331 tab.buildCancel = nil
3332 }
3333 }
3334
3335 // tabBuildSupersededLocked reports whether an in-flight build lost ownership
3336 // of its tab: the tab was removed/replaced, or a session rebind bumped
3337 // buildGeneration to invalidate it. Generation 0 marks the synchronous
3338 // rebuild paths, which serialize through runtimeRebuildMu instead and are
3339 // never superseded by generation bumps. Callers must hold a.mu.
3340 func (a *App) tabBuildSupersededLocked(tab *WorkspaceTab, generation uint64) bool {
3341 if tab == nil || tab.removed || a.shuttingDown.Load() || a.tabs[tab.ID] != tab {
3342 return true
3343 }
3344 return generation != 0 && tab.buildGeneration != generation
3345 }
3346
3347 func (a *App) tabBuildSuperseded(tab *WorkspaceTab, generation uint64) bool {
3348 if tab == nil {
3349 return true
3350 }
3351 a.mu.RLock()
3352 defer a.mu.RUnlock()
3353 return a.tabBuildSupersededLocked(tab, generation)
3354 }
3355
3356 // supersedeTabBuildLocked invalidates any in-flight startup build and cancels
3357 // its context. A synchronous rebuild (model/effort/token switch) that has
3358 // already installed its controller calls this so a slower blank-session build
3359 // cannot finish afterward, overwrite tab.Ctrl, and release or steal the
3360 // session lease the switch just bound. Callers must hold a.mu.
3361 func (a *App) supersedeTabBuildLocked(tab *WorkspaceTab) {
3362 if tab == nil {
3363 return
3364 }
3365 tab.buildGeneration++
3366 if tab.buildCancel != nil {
3367 tab.buildCancel()
3368 tab.buildCancel = nil
3369 }
3370 }
3371
3372 // abandonSupersededBuild cleans up after a build that lost tab ownership
3373 // mid-flight (removed tab, or a session rebind bumped the generation). It
3374 // releases only what THIS build acquired — its controller, its own
3375 // shared-host reference (rootKey), and the session lease bound to its own
3376 // path (leaseKey) — and never reads or clears the tab's SharedHostKey or
3377 // lease outright: on a live rebound tab the replacement build may already
3378 // have published its own key and lease there, and taking those would leak
3379 // the new runtime's host reference (or close a host still in use) and strip
3380 // the new session's lease. Callers must not hold a.mu.
3381 func (a *App) abandonSupersededBuild(tab *WorkspaceTab, ctrl control.SessionAPI, rootKey, leaseKey string) {
3382 if ctrl != nil {
3383 ctrl.Close()
3384 }
3385 if rootKey != "" {
3386 a.releaseSharedHost(rootKey)
3387 }
3388 tab.releaseSessionLeaseForKey(leaseKey)
3389 }
3390
3391 func (a *App) clearTabBuildCancel(tab *WorkspaceTab, generation uint64, cancel context.CancelFunc, keepContext bool) {
3392 if cancel == nil {
3393 return
3394 }
3395 if !keepContext {
3396 defer cancel()
3397 }
3398 if tab == nil {
3399 return
3400 }
3401 a.mu.Lock()
3402 if tab.buildGeneration == generation {
3403 tab.buildCancel = nil
3404 }
3405 a.mu.Unlock()
3406 }
3407
3408 func (a *App) closeTabRuntimeAdmissionHeld(tab *WorkspaceTab) {
3409 if tab == nil {
3410 return
3411 }
3412 a.mu.RLock()
3413 ctrl := tab.Ctrl
3414 sink := tab.sink
3415 a.mu.RUnlock()
3416 if ctrl != nil {
3417 ctrl.SetSessionPath("") // future snapshots become no-ops
3418 a.quiesceTabAutosave(tab)
3419 ctrl.Cancel()
3420 ctrl.Close()
3421 a.releaseTabSharedHost(tab)
3422 }
3423 if sink != nil {
3424 sink.clearContext()
3425 }
3426 tab.releaseSessionLease()
3427 a.mu.Lock()
3428 a.releaseSessionRuntimeLocked(tab)
3429 a.mu.Unlock()
3430 }
3431
3432 // buildTabController assembles a controller for a tab in the background, the
3433 // same way buildController works for the single-controller App. On success it
3434 // wires the controller and flips Ready; on failure it stores StartupErr.
3435 func (a *App) startTabControllerBuild(tab *WorkspaceTab) {
3436 a.startTabControllerBuildMode(tab, false)
3437 }
3438
3439 func (a *App) startTabControllerBuildMode(tab *WorkspaceTab, async bool) {
3440 buildCtx, cancel := context.WithCancel(a.bootContext())
3441 a.mu.Lock()
3442 // Historical shells are not ordinary dormant tabs. Only explicit
3443 // preparation may replace their source identity before a runtime starts.
3444 if tab == nil || tab.removed || tab.HistoricalSource != nil || a.shuttingDown.Load() {
3445 a.mu.Unlock()
3446 cancel()
3447 return
3448 }
3449 tab.buildGeneration++
3450 generation := tab.buildGeneration
3451 tab.buildCancel = cancel
3452 if tab.buildDone != nil {
3453 // Defensive: the owning build's terminal defer nils buildDone after
3454 // closing it, so a non-nil channel here means that build never ran its
3455 // defer. Close it anyway so activation completions never wait forever.
3456 close(tab.buildDone)
3457 }
3458 tab.buildDone = make(chan struct{})
3459 tab.buildDoneGen = generation
3460 execution := &tabBuildExecution{done: make(chan struct{}), cancel: cancel, generation: generation}
3461 tab.buildExecution = execution
3462 if tab.buildExecutions == nil {
3463 tab.buildExecutions = make(map[*tabBuildExecution]struct{})
3464 }
3465 tab.buildExecutions[execution] = struct{}{}
3466 a.mu.Unlock()
3467 run := func() {
3468 defer a.finishTabBuildExecution(tab, execution)
3469 a.buildTabControllerWithContext(tab, loadedTabSession{}, buildCtx, generation, cancel)
3470 }
3471 if a.ctx == nil && !async {
3472 run()
3473 return
3474 }
3475 go run()
3476 }
3477
3478 func (a *App) buildTabController(tab *WorkspaceTab) {
3479 a.buildTabControllerWithLoadedSession(tab, loadedTabSession{})
3480 }
3481
3482 type loadedTabSession struct {
3483 Path string
3484 Session *agent.Session
3485 }
3486
3487 func (s loadedTabSession) matches(path string) bool {
3488 return s.Session != nil && sessionRuntimeKey(s.Path) != "" && sessionRuntimeKey(s.Path) == sessionRuntimeKey(path)
3489 }
3490
3491 func (a *App) buildTabControllerWithLoadedSession(tab *WorkspaceTab, loadedSession loadedTabSession) {
3492 a.buildTabControllerWithContext(tab, loadedSession, a.bootContext(), 0, nil)
3493 }
3494
3495 func (a *App) desktopNotificationSender() notify.Sender {
3496 if a == nil {
3497 return notify.NewPlatformSender()
3498 }
3499 a.notificationSenderOnce.Do(func() {
3500 if a.notificationSender == nil {
3501 a.notificationSender = notify.NewPlatformSender()
3502 }
3503 })
3504 return a.notificationSender
3505 }
3506
3507 func (a *App) desktopControllerSink(inner event.Sink, cfg config.NotificationsConfig) event.Sink {
3508 if !cfg.Enabled {
3509 return inner
3510 }
3511 sender := a.desktopNotificationSender()
3512 if sender == nil {
3513 return inner
3514 }
3515 return notify.NewSink(inner, sender, cfg)
3516 }
3517
3518 // closeTabBuildDone signals waiters (topic-activation completions) that the
3519 // build owning buildGeneration has terminated. Every build funnels through
3520 // buildTabControllerWithContextCore, whose deferred call guarantees
3521 // the channel startTabControllerBuild created is closed exactly once, on every
3522 // terminal path — success, failure, and superseded abandon alike. Synchronous
3523 // rebuild paths pass generation 0 and never created a channel.
3524 func (a *App) closeTabBuildDone(tab *WorkspaceTab, buildGeneration uint64) {
3525 if tab == nil || buildGeneration == 0 {
3526 return
3527 }
3528 a.mu.Lock()
3529 if tab.buildDoneGen == buildGeneration && tab.buildDone != nil {
3530 close(tab.buildDone)
3531 tab.buildDone = nil
3532 }
3533 a.mu.Unlock()
3534 }
3535
3536 func (a *App) buildTabControllerWithContext(tab *WorkspaceTab, loadedSession loadedTabSession, buildCtx context.Context, buildGeneration uint64, buildCancel context.CancelFunc) {
3537 a.buildTabControllerWithContextCore(tab, loadedSession, buildCtx, buildGeneration, buildCancel)
3538 }
3539
3540 // buildTabControllerWithContextCore performs configuration, session routing,
3541 // and extension boot outside runtimeAdmissionMu. Only publication enters the
3542 // lifecycle barrier.
3543 func (a *App) buildTabControllerWithContextCore(tab *WorkspaceTab, loadedSession loadedTabSession, buildCtx context.Context, buildGeneration uint64, buildCancel context.CancelFunc) {
3544 defer a.recoverToPending("buildTabController")
3545 keepBuildContext := false
3546 defer func() {
3547 a.clearTabBuildCancel(tab, buildGeneration, buildCancel, keepBuildContext)
3548 }()
3549 defer a.closeTabBuildDone(tab, buildGeneration)
3550 if hook := a.tabBuildStartHook; hook != nil && tab != nil {
3551 // Test-only gate: lets activation-ordering tests hold builds in flight
3552 // and release them out of order. Runs even for already-superseded
3553 // builds so the test can observe every build it started.
3554 hook(tab.ID)
3555 }
3556 appCtx := a.ctx
3557 a.reportManualBuildStage(tab, buildGeneration, "building_runtime")
3558 if a.tabBuildSuperseded(tab, buildGeneration) {
3559 return
3560 }
3561 if !a.prepareTabControllerWorkspace(tab, buildCtx, buildGeneration, appCtx) {
3562 return
3563 }
3564
3565 // Snapshot the identity/profile fields under a.mu before the off-lock
3566 // stretch: session rebinding, recovery, and topic assignment write them
3567 // under the lock while this goroutine builds.
3568 a.mu.RLock()
3569 tabWorkspaceRoot := tab.WorkspaceRoot
3570 tabScope := tab.Scope
3571 tabTopicID := tab.TopicID
3572 tabSeedTitle := canonicalSeedTitle(tab.TopicTitle, tab.topicTitleSource)
3573 tabSessionPath := tab.SessionPath
3574 tabSessionID := tab.SessionID
3575 tabSessionHeadID := tab.SessionHeadID
3576 tabModel := tab.model
3577 tabSink := tab.sink
3578 tabCreateOperationID := tab.PendingCreateOperationID
3579 a.mu.RUnlock()
3580
3581 root := tabWorkspaceRoot
3582 if root == "" {
3583 if wd, err := os.Getwd(); err == nil {
3584 root = wd
3585 }
3586 }
3587
3588 // Load config for this tab's workspace root.
3589 _ = config.MigrateLegacyCredentialsForRoot(root)
3590 cfg, err := config.LoadForRoot(root)
3591 if err != nil {
3592 a.recordTabStartupFailure(tab, buildGeneration, appCtx, err)
3593 return
3594 }
3595
3596 if a.tabBuildSuperseded(tab, buildGeneration) {
3597 return
3598 }
3599 if tabSink != nil {
3600 tabSink.setContext(appCtx)
3601 }
3602
3603 sessionDir, startupSessionPath, storedLegacyDir := a.nativeStartupSource(tab, root, tabScope, tabWorkspaceRoot, tabTopicID, tabSessionPath)
3604 model := strings.TrimSpace(tabModel)
3605 // The v3 event projection owns model selection. desktop-tabs.json only
3606 // remembers which immutable session to open, so stale UI state cannot select
3607 // a different provider when the process restarts.
3608 if strings.TrimSpace(tabSessionID) != "" && strings.TrimSpace(tabCreateOperationID) == "" {
3609 service := a.desktopSessionService(sessionDir)
3610 ref := session.SessionRef{HostID: service.HostID(), SessionID: strings.TrimSpace(tabSessionID)}
3611 if view, openErr := service.OpenSession(buildCtx, ref); openErr == nil && strings.TrimSpace(view.Recent.ModelRef) != "" {
3612 model = strings.TrimSpace(view.Recent.ModelRef)
3613 }
3614 } else if model == "" {
3615 // A legacy sidecar is an import hint only. An explicit tab selection wins,
3616 // and migration never writes the source metadata back.
3617 if sessionModel, ok := agent.LoadSessionModel(startupSessionPath); ok {
3618 config.NormalizeLegacyMimoCustomProvidersForRefs(cfg, sessionModel)
3619 if _, ok := cfg.ResolveModel(sessionModel); ok {
3620 model = sessionModel
3621 }
3622 }
3623 }
3624 if model == "" {
3625 if def := strings.TrimSpace(cfg.DefaultModel); providerext.PluginRefOwner(def) != "" {
3626 // A plugin-namespaced default_model belongs to an extension
3627 // sidecar: the config catalog can never resolve it, but boot's
3628 // merged resolver can. Pass it through untouched.
3629 model = def
3630 } else {
3631 resolved, _, ok := cfg.ResolveDesktopNewSessionModel()
3632 if !ok {
3633 a.recordTabStartupFailure(tab, buildGeneration, appCtx, errNoDesktopChatModel)
3634 return
3635 }
3636 model = resolved
3637 }
3638 }
3639 config.NormalizeLegacyMimoCustomProvidersForRefs(cfg, model)
3640 requestedModel := model
3641 if strings.TrimSpace(tabCreateOperationID) != "" {
3642 resolved, resolveErr := resolveDraftCreateModelStrict(cfg, model)
3643 if resolveErr != nil {
3644 a.recordTabStartupFailure(tab, buildGeneration, appCtx, resolveErr)
3645 return
3646 }
3647 model = resolved
3648 } else if providerext.PluginRefOwner(model) == "" {
3649 // Plugin refs skip the config fallback: rerouting an unavailable
3650 // extension model onto a config provider would silently change the
3651 // session; boot's unknown-model error is the honest failure.
3652 if resolved, fallback, ok := cfg.ResolveModelWithFallback(model); ok {
3653 if fallback && strings.TrimSpace(tabModel) != "" {
3654 a.noticeForTab(tab.ID, fmt.Sprintf("model %q is no longer available; switched to %s", requestedModel, resolved))
3655 }
3656 model = resolved
3657 }
3658 }
3659
3660 // Acquire a shared plugin host for this workspace root so MCP processes
3661 // are launched once per root, not once per tab. SharedHostKey is an a.mu-
3662 // guarded field (takeTabSharedHostKey reads it under the lock during
3663 // teardown), so publish it under the lock alongside the model. Capture the
3664 // tab-local runtime profile here too: bound methods (SetModeForTab,
3665 // SetGoalForTab, SetEffortForTab, ...) write these under a.mu, so the
3666 // off-lock boot.Build below must read a locked snapshot, not the live tab.
3667 rootKey := tabWorkspaceRoot
3668 if rootKey == "" {
3669 rootKey = "__global__" // stable key for global workspace tabs
3670 }
3671 a.mu.Lock()
3672 if a.tabBuildSupersededLocked(tab, buildGeneration) {
3673 a.mu.Unlock()
3674 return
3675 }
3676 tab.rebindEffortModel(cfg, model)
3677 tab.Label = model
3678 tab.SharedHostKey = rootKey
3679 buildEffort := cloneStringPtr(tab.effort)
3680 buildTokenMode := currentTabTokenMode(tab)
3681 buildMode := tab.mode
3682 buildToolApprovalMode := tab.toolApprovalMode
3683 buildDisabledMCP := cloneServerViewMap(tab.disabledMCP)
3684 buildGoal := tab.goal
3685 buildSink := tab.sink
3686 a.saveTabsLocked()
3687 a.mu.Unlock()
3688 buildRuntime := (tabRuntimeSnapshot{
3689 tokenMode: buildTokenMode,
3690 mode: buildMode,
3691 goal: buildGoal,
3692 toolApprovalMode: buildToolApprovalMode,
3693 }).normalizedRuntime()
3694 // Capture the extension generation before the shared host is mutated by
3695 // boot.Build. A concurrent plugin delete/update/reauth bumps the counter;
3696 // if it moves before publication we abandon this controller rather than
3697 // resurrecting removed tools on the shared host.
3698 extensionGen := a.currentExtensionGeneration()
3699 sharedHost := a.acquireSharedHost(rootKey)
3700 sink := a.desktopControllerSink(buildSink, cfg.Notifications)
3701 buildSessionService, serviceErr := a.sessionServiceForSource(sessionDir, tabSessionID, startupSessionPath, storedLegacyDir)
3702 if serviceErr != nil {
3703 a.recordTabStartupFailure(tab, buildGeneration, appCtx, serviceErr)
3704 a.releaseSharedHost(rootKey)
3705 return
3706 }
3707 booted := a.bootTabControllerWithModelFallback(buildCtx, tab, cfg, sharedHost, boot.Options{
3708 Model: model,
3709 RequireKey: false,
3710 StatsSource: "desktop",
3711 TaskStore: a.taskStore(),
3712 OnConfigLoadWarnings: a.configLoadWarningsHandler(),
3713 Sink: sink,
3714 WorkspaceRoot: root,
3715 SessionDir: sessionDir,
3716 SessionService: buildSessionService,
3717 NativeLegacySession: storedLegacyDir == "" && strings.TrimSpace(tabSessionID) == "" && strings.TrimSpace(startupSessionPath) != "",
3718 EffortOverride: cloneStringPtr(buildEffort),
3719 SharedHost: sharedHost, BrowserExecutor: a.browserExecutorForRuntime(tab.ID, buildSink),
3720 CleanupPendingReconciler: reconcileDesktopCleanupPending,
3721 SubagentParentLive: a.subagentParentProbeForBuild(tab),
3722 SessionRecoveryMeta: a.tabSessionRecoveryMeta(tab),
3723 PinnedContextLoader: pinnedContextLoader(root),
3724 OnSessionRecovered: a.handleTabSessionRecovered(tab),
3725 OnSessionTransition: a.handleTabSessionTransition(tab),
3726 BeforeInboxDispatch: a.beforeInboxDispatch,
3727 OnSessionTitleChanged: a.onSessionTitleChanged,
3728 }, extensionGen, buildGeneration, tabSessionID, requestedModel)
3729 buildCtx, registration := booted.ctx, booted.registration
3730 defer func() { registration.rollback() }()
3731 ctrl, err := booted.controller, booted.err
3732 model, modelFallback := booted.model, booted.fallback
3733 if a.handleTabControllerBootError(tab, registration, rootKey, buildGeneration, appCtx, err) {
3734 return
3735 }
3736 defer finishUnpublishedTabController(ctrl, buildGeneration, &keepBuildContext)
3737 if a.tabBuildSuperseded(tab, buildGeneration) {
3738 registration.rollback()
3739 a.abandonSupersededBuild(tab, ctrl, rootKey, "")
3740 return
3741 }
3742 if a.currentExtensionGeneration() != extensionGen {
3743 registration.rollback()
3744 a.abandonSupersededBuild(tab, ctrl, rootKey, "")
3745 a.scheduleDeferredStartupBuild(tab.ID)
3746 return
3747 }
3748 a.bindControllerDisplayRecorder(ctrl)
3749 configureControllerRuntime(ctrl, nil, buildRuntime)
3750 if strings.HasPrefix(tabCreateOperationID, "draft-op-") {
3751 for name := range buildDisabledMCP {
3752 ctrl.UnregisterMCPServerTools(name)
3753 }
3754 }
3755
3756 acquiredLeaseKey := ""
3757 restoredRuntime := buildRuntime
3758 identity, usesExclusiveV3 := ctrl.(control.IdentityLifecycle)
3759 if usesExclusiveV3 && identity.UsesExclusiveSession() && storedLegacyDir != "" {
3760 if !a.bindNativeDirectoryForTab(buildCtx, tab, ctrl, storedLegacyDir, rootKey, buildGeneration) {
3761 return
3762 }
3763 } else if usesExclusiveV3 && identity.UsesExclusiveSession() {
3764 bound, bindErr := a.bindTabCanonicalSessionTopic(
3765 buildCtx, identity, cfg, tabScope, tabWorkspaceRoot, tabSessionID, startupSessionPath, model, modelFallback, tabTopicID, tabSeedTitle,
3766 )
3767 if bindErr != nil {
3768 a.recordTabStartupFailure(tab, buildGeneration, appCtx, friendlySessionLoadError(bindErr))
3769 ctrl.Close()
3770 a.releaseSharedHost(rootKey)
3771 return
3772 }
3773 a.mu.Lock()
3774 if a.tabBuildSupersededLocked(tab, buildGeneration) {
3775 a.mu.Unlock()
3776 a.abandonSupersededBuild(tab, ctrl, rootKey, "")
3777 return
3778 }
3779 bound.applyLocked(tab)
3780 a.mu.Unlock()
3781 // Local Desktop restores its canonical session choice from the Desktop
3782 // preset store. OpenSession publishes the session default, so restore the
3783 // selected preset after binding the target identity.
3784 applyTabToolApprovalModeToController(ctrl, buildRuntime.toolApprovalMode)
3785 tab.replaceTelemetry(loadTelemetryFor(sessionRoute(bound.ref.SessionID)), sessionRuntimeKey(remoteSessionIDRoutePrefix+bound.ref.SessionID))
3786 } else if dir := ctrl.SessionDir(); dir != "" {
3787 // Refresh the topic/session locals under the lock: a rebind or the
3788 // recovery callback may have rewritten them since the early snapshot.
3789 a.mu.RLock()
3790 tabTopicID = strings.TrimSpace(tab.TopicID)
3791 tabSessionPath = tab.SessionPath
3792 a.mu.RUnlock()
3793 var path string
3794 var resumeSession *agent.Session
3795 var resumeLoadErr error
3796 // Prefer the exact session file persisted for this tab. Topic lookup is a
3797 // compatibility fallback for older desktop-tabs.json files that only stored
3798 // topicId and could pick the wrong session when one topic had multiple files.
3799 if loaded, pinnedPath, ok, loadErr := loadPinnedTabSessionContext(buildCtx, dir, tabSessionPath, loadedSession, false); loadErr != nil {
3800 resumeLoadErr = loadErr
3801 } else if ok {
3802 path = pinnedPath
3803 resumeSession = loaded
3804 }
3805 if resumeLoadErr == nil && path == "" && tabTopicID != "" {
3806 existingPath := a.catalogSessionPathForTopic(tabScope, tabWorkspaceRoot, tabTopicID)
3807 if existingPath != "" {
3808 if loaded, err := loadResumableSessionContext(buildCtx, existingPath); err == nil {
3809 path = existingPath
3810 resumeSession = loaded
3811 } else {
3812 resumeLoadErr = err
3813 }
3814 }
3815 }
3816 if resumeLoadErr == nil && path != "" && tabSessionHeadID != "" {
3817 resumeSession, resumeLoadErr = agent.LoadSessionHeadReadOnlyContext(buildCtx, path, tabSessionHeadID)
3818 }
3819 if resumeLoadErr != nil {
3820 resumeLoadErr = friendlySessionLoadError(resumeLoadErr)
3821 a.mu.Lock()
3822 if a.tabBuildSupersededLocked(tab, buildGeneration) {
3823 a.mu.Unlock()
3824 a.abandonSupersededBuild(tab, ctrl, rootKey, "")
3825 return
3826 }
3827 leaseHeld, save := a.markTabStartupFailureLocked(tab, resumeLoadErr, suppressStartupRestore)
3828 hostKey := takeTabSharedHostKey(tab)
3829 tab.releaseSessionLease()
3830 a.mu.Unlock()
3831 a.writeTabsSaveRequest(save)
3832 ctrl.Close()
3833 if hostKey != "" {
3834 a.releaseSharedHost(hostKey)
3835 }
3836 if leaseHeld {
3837 a.scheduleDeferredStartupBuild(tab.ID)
3838 }
3839 a.emitReady(appCtx, tab.ID)
3840 return
3841 }
3842 if path == "" {
3843 path = agent.NewSessionPath(dir, ctrl.Label())
3844 }
3845 // Write/update scope/session meta.
3846 if path != "" {
3847 if a.claimSessionRuntime(tab, path, buildCtx) {
3848 ctrl.Close()
3849 a.releaseSharedHost(rootKey)
3850 a.emitReady(appCtx, tab.ID)
3851 return
3852 }
3853 preLeaseKey := tab.sessionLeaseRuntimeKey()
3854 if err := a.ensureTabSessionLeaseForRebuild(tab, path, ""); err != nil {
3855 a.mu.Lock()
3856 if a.tabBuildSupersededLocked(tab, buildGeneration) {
3857 a.mu.Unlock()
3858 a.abandonSupersededBuild(tab, ctrl, rootKey, "")
3859 return
3860 }
3861 leaseHeld, save := a.markTabStartupFailureLocked(tab, err, suppressStartupRestore)
3862 hostKey := takeTabSharedHostKey(tab)
3863 // Release only a lease bound to THIS build's session: a failed
3864 // ensure leaves any prior lease untouched, and that lease may
3865 // belong to a runtime a concurrent switch just installed.
3866 tab.releaseSessionLeaseForKey(sessionRuntimeKey(path))
3867 a.mu.Unlock()
3868 a.writeTabsSaveRequest(save)
3869 ctrl.Close()
3870 if hostKey != "" {
3871 a.releaseSharedHost(hostKey)
3872 }
3873 if leaseHeld {
3874 a.scheduleDeferredStartupBuild(tab.ID)
3875 }
3876 a.emitReady(appCtx, tab.ID)
3877 return
3878 }
3879 // Remember which lease THIS build bound: if the build is later
3880 // superseded, only a lease still carrying this key may be
3881 // released (see abandonSupersededBuild). A fast-path reuse means
3882 // the lease existed before this build (bound by a concurrent
3883 // switch or recovery) — it is not ours to release.
3884 if key := sessionRuntimeKey(path); key != preLeaseKey {
3885 acquiredLeaseKey = key
3886 }
3887 // Re-check ownership right after the (potentially slow) lease
3888 // bind: a rebind that superseded this build while ensure was in
3889 // flight has already retargeted the tab, and continuing into
3890 // Resume/persistTabSessionPath would write the stale session
3891 // path back onto the rebound tab.
3892 if a.tabBuildSuperseded(tab, buildGeneration) {
3893 a.abandonSupersededBuild(tab, ctrl, rootKey, acquiredLeaseKey)
3894 return
3895 }
3896 var restoreErr error
3897 restoredRuntime, restoreErr = resumeControllerRuntimeWithSession(ctrl, resumeSession, path, buildRuntime)
3898 if restoreErr != nil {
3899 a.mu.Lock()
3900 if a.tabBuildSupersededLocked(tab, buildGeneration) {
3901 a.mu.Unlock()
3902 a.abandonSupersededBuild(tab, ctrl, rootKey, acquiredLeaseKey)
3903 return
3904 }
3905 leaseHeld, save := a.markTabStartupFailureLocked(tab, restoreErr, suppressStartupRestore)
3906 hostKey := takeTabSharedHostKey(tab)
3907 tab.releaseSessionLeaseForKey(sessionRuntimeKey(path))
3908 a.mu.Unlock()
3909 a.writeTabsSaveRequest(save)
3910 ctrl.Close()
3911 if hostKey != "" {
3912 a.releaseSharedHost(hostKey)
3913 }
3914 if leaseHeld {
3915 a.scheduleDeferredStartupBuild(tab.ID)
3916 }
3917 a.emitReady(appCtx, tab.ID)
3918 return
3919 }
3920 a.persistTabSessionPath(tab, path)
3921 a.mu.RLock()
3922 indexScope := tab.Scope
3923 indexRoot := tab.WorkspaceRoot
3924 indexTopicID := strings.TrimSpace(tab.TopicID)
3925 indexTopicTitle := tab.TopicTitle
3926 a.mu.RUnlock()
3927 if indexTopicID != "" {
3928 if err := ensureTopicIndexed(indexScope, indexRoot, indexTopicID, indexTopicTitle, loadTopicTitleSource(topicTitleRoot(indexScope, indexRoot), indexTopicID)); err == nil {
3929 a.emitProjectTreeChangedForSessionDirs(ctrl.SessionDir())
3930 }
3931 }
3932 // Key telemetry to the session this build binds: restore its
3933 // persisted sidecar, or start from zero when none exists (fresh
3934 // session, CLI-created session, pre-telemetry session). Keeping
3935 // the previous session's totals here made 会话费用 accumulate
3936 // across sessions and persisted the stale totals into the new
3937 // session's sidecar on the next event (#5850).
3938 snapshot := loadTelemetry(path + ".telemetry.json")
3939 tab.replaceTelemetry(snapshot, sessionRuntimeKey(path))
3940 }
3941 }
3942
3943 // Lifecycle admission protects only the compare-and-publish boundary. Slow
3944 // config, history, lease, and extension work above remains cancellable and
3945 // cannot prevent shutdown from acquiring the write side.
3946 a.reportManualBuildStage(tab, buildGeneration, "publishing_controller")
3947 releaseDraftPublication, draftPublicationErr := a.lockDraftRuntimePublication(tabCreateOperationID)
3948 if draftPublicationErr != nil {
3949 registration.rollback()
3950 a.abandonSupersededBuild(tab, ctrl, rootKey, acquiredLeaseKey)
3951 a.recordTabStartupFailure(tab, buildGeneration, appCtx, draftPublicationErr)
3952 return
3953 }
3954 defer releaseDraftPublication()
3955 releasePublication, extensionsCurrent := a.lockTabControllerPublication(extensionGen, tabScope, tabWorkspaceRoot)
3956 if !extensionsCurrent {
3957 registration.rollback()
3958 a.abandonSupersededBuild(tab, ctrl, rootKey, acquiredLeaseKey)
3959 a.scheduleDeferredStartupBuild(tab.ID)
3960 return
3961 }
3962 defer releasePublication()
3963 if a.rejectStaleStartupModelSettings(tab, ctrl, buildGeneration, appCtx, func() {
3964 registration.rollback()
3965 a.abandonSupersededBuild(tab, ctrl, rootKey, acquiredLeaseKey)
3966 }) {
3967 return
3968 }
3969 a.mu.Lock()
3970 if a.tabBuildSupersededLocked(tab, buildGeneration) {
3971 a.mu.Unlock()
3972 a.abandonSupersededBuild(tab, ctrl, rootKey, acquiredLeaseKey)
3973 return
3974 }
3975 // Commit the scope while the final tab-generation check is still guarded.
3976 // It only takes the plugin Host leaf lock and cannot call back into App.
3977 if !a.commitStartupWriteAuthorityLocked(tab, ctrl, registration, rootKey, acquiredLeaseKey, appCtx) {
3978 return
3979 }
3980 tab.Ctrl = ctrl
3981 tab.Label = ctrl.Label()
3982 applyNormalizedRuntimeToTabLocked(tab, restoredRuntime)
3983 tab.Ready = true
3984 clearTabStartupError(tab)
3985 a.bindSessionRuntimeKeyLocked(tab, tab.currentSessionIdentity())
3986 a.advanceSessionRuntimeEpochLocked(tab)
3987 keepBuildContext = true
3988 a.mu.Unlock()
3989 a.finishStartupPublication(tab, ctrl, appCtx)
3990 }
3991
3992 type sessionBinding struct {
3993 path string
3994 scope string
3995 workspaceRoot string
3996 topicID string
3997 topicTitle string
3998 hasMeta bool
3999 meta agent.BranchMeta
4000 }
4001
4002 func (a *App) reconcileTabWithPinnedSessionMeta(tab *WorkspaceTab) (string, bool) {
4003 if tab == nil {
4004 return "", false
4005 }
4006 a.mu.RLock()
4007 current := a.tabs[tab.ID]
4008 path := strings.TrimSpace(tab.SessionPath)
4009 ctrl := tab.Ctrl
4010 scope := tab.Scope
4011 workspaceRoot := tab.WorkspaceRoot
4012 a.mu.RUnlock()
4013 if current != tab {
4014 return "", false
4015 }
4016 if path != "" {
4017 if resolved, ok := a.reconcileTabWithSessionPath(tab, path); ok {
4018 return resolved, true
4019 }
4020 }
4021 if ctrl == nil {
4022 return "", false
4023 }
4024 path = strings.TrimSpace(ctrl.SessionPath())
4025 if path == "" {
4026 return "", false
4027 }
4028 binding, ok := a.resolveSessionBinding(path)
4029 if !ok {
4030 return "", false
4031 }
4032 if scope == "project" && binding.scope != "project" && normalizeProjectRoot(workspaceRoot) != "" {
4033 if root, ok := safeControllerWorkspaceRoot(ctrl); ok && sameProjectRoot(root, workspaceRoot) {
4034 return "", false
4035 }
4036 }
4037 a.applySessionBindingToTab(tab, binding)
4038 return binding.path, true
4039 }
4040
4041 func (a *App) reconcileTabWithSessionPath(tab *WorkspaceTab, sessionPath string) (string, bool) {
4042 if tab == nil || strings.TrimSpace(sessionPath) == "" {
4043 return "", false
4044 }
4045 binding, ok := a.resolveSessionBinding(sessionPath)
4046 if !ok {
4047 return "", false
4048 }
4049 a.applySessionBindingToTab(tab, binding)
4050 return binding.path, true
4051 }
4052
4053 func (a *App) applySessionBindingToTab(tab *WorkspaceTab, binding sessionBinding) {
4054 if tab == nil || binding.path == "" {
4055 return
4056 }
4057 var terminalSessions []*terminalSession
4058 reopenTerminalGate := false
4059 scope := binding.scope
4060 workspaceRoot := binding.workspaceRoot
4061 if scope == "" {
4062 scope = "global"
4063 }
4064 if scope == "project" {
4065 workspaceRoot = normalizeProjectRoot(workspaceRoot)
4066 if workspaceRoot == "" {
4067 return
4068 }
4069 releaseAdmission, err := a.beginRegisteredProjectRuntimeAdmission(tab, scope, workspaceRoot)
4070 if err != nil {
4071 return
4072 }
4073 defer releaseAdmission()
4074 } else {
4075 scope = "global"
4076 workspaceRoot = globalTabWorkspaceRoot()
4077 }
4078 topicID := strings.TrimSpace(binding.topicID)
4079 topicTitle := strings.TrimSpace(binding.topicTitle)
4080 if topicTitle == "" && topicID != "" {
4081 topicTitle = topicTitleForTab(scope, workspaceRoot, topicID)
4082 }
4083 topicSource := ""
4084 if topicID != "" {
4085 topicSource = loadTopicTitleSource(topicTitleRoot(scope, workspaceRoot), topicID)
4086 }
4087 pinnedState, preservePendingLegacy := pinnedContextStateForSessionBinding(tab, binding.path)
4088
4089 a.mu.Lock()
4090 current := a.tabs[tab.ID]
4091 if current != nil && current != tab {
4092 a.mu.Unlock()
4093 return
4094 }
4095 oldScope := tab.Scope
4096 oldWorkspaceRoot := tab.WorkspaceRoot
4097 changed := tab.Scope != scope ||
4098 tab.WorkspaceRoot != workspaceRoot ||
4099 canonicalTabSessionPath(tab.SessionPath) != canonicalTabSessionPath(binding.path)
4100 // Spelling-only root updates still persist above, but an equivalent root is
4101 // the same workspace — do not warn the user about a switch.
4102 workspaceChanged := tab.Scope != scope || !sameProjectRoot(tab.WorkspaceRoot, workspaceRoot)
4103 if workspaceChanged && current == tab && a.terminals != nil {
4104 // A session binding can move a visible tab to another project. Invalidate
4105 // the old terminal scope before publishing the new root so an in-flight
4106 // shell start cannot register against the old workspace after this
4107 // transition. Reopen only after the new binding is visible.
4108 terminalSessions = a.terminals.detachForTab(tab.ID)
4109 reopenTerminalGate = !tab.ReadOnly && !tab.removed
4110 }
4111 applyPinnedContextSessionBinding(tab, pinnedState, preservePendingLegacy)
4112 tab.Scope = scope
4113 tab.WorkspaceRoot = workspaceRoot
4114 tab.SessionPath = canonicalTabSessionPath(binding.path)
4115 if topicID != "" {
4116 changed = changed || tab.TopicID != topicID
4117 tab.TopicID = topicID
4118 tab.topicTitleSource = topicSource
4119 }
4120 if topicTitle != "" {
4121 changed = changed || tab.TopicTitle != topicTitle
4122 tab.TopicTitle = topicTitle
4123 }
4124 if changed && current == tab {
4125 a.saveTabsLocked()
4126 }
4127 sink := tab.sink
4128 a.mu.Unlock()
4129 if workspaceChanged && a.workspaceHub != nil {
4130 a.workspaceHub.reconcileRoots()
4131 }
4132 if reopenTerminalGate {
4133 a.terminals.reopenForTab(tab.ID)
4134 }
4135 if len(terminalSessions) > 0 {
4136 a.terminals.closeSessions(terminalSessions)
4137 }
4138 if workspaceChanged && sink != nil {
4139 sink.Emit(event.Event{
4140 Kind: event.Notice,
4141 Level: event.LevelWarn,
4142 Text: sessionBindingWorkspaceNotice(oldScope, oldWorkspaceRoot, scope, workspaceRoot),
4143 })
4144 }
4145 }
4146
4147 func sessionBindingWorkspaceNotice(oldScope, oldWorkspaceRoot, scope, workspaceRoot string) string {
4148 return "Session belongs to " + describeSessionBindingWorkspace(scope, workspaceRoot) +
4149 "; switched tab from " + describeSessionBindingWorkspace(oldScope, oldWorkspaceRoot) +
4150 " to match the saved session."
4151 }
4152
4153 func describeSessionBindingWorkspace(scope, workspaceRoot string) string {
4154 if strings.TrimSpace(scope) == "project" && strings.TrimSpace(workspaceRoot) != "" {
4155 // %q escapes Windows separators, which turns a user-facing path into
4156 // C:\\Users\\... in the notice. Preserve native separators while escaping
4157 // only the delimiters that can appear in a Unix path.
4158 root := strings.ReplaceAll(strings.TrimSpace(workspaceRoot), `"`, `\"`)
4159 return `project workspace "` + root + `"`
4160 }
4161 return "global workspace"
4162 }
4163
4164 func (a *App) resolveSessionBinding(sessionPath string) (sessionBinding, bool) {
4165 legacyPath, ok := validatedLegacySessionPathForRead(sessionPath)
4166 if !ok {
4167 return sessionBinding{}, false
4168 }
4169 sessionPath = string(legacyPath)
4170 for _, dir := range a.knownSessionDirs() {
4171 if binding, ok := sessionBindingInDir(dir, sessionPath); ok {
4172 return binding, true
4173 }
4174 }
4175 if !filepath.IsAbs(sessionPath) {
4176 return sessionBinding{}, false
4177 }
4178 path, err := filepath.Abs(sessionPath)
4179 if err != nil {
4180 return sessionBinding{}, false
4181 }
4182 meta, ok, err := agent.LoadBranchMeta(path)
4183 if err != nil || !ok {
4184 return sessionBinding{}, false
4185 }
4186 for _, dir := range sessionBindingCandidateDirs(meta) {
4187 if binding, ok := sessionBindingInDir(dir, path); ok {
4188 return binding, true
4189 }
4190 }
4191 return sessionBindingFromMeta(path, meta)
4192 }
4193
4194 func sessionBindingCandidateDirs(meta agent.BranchMeta) []string {
4195 if meta.DefaultScope() == "project" {
4196 if root := normalizeProjectRoot(meta.WorkspaceRoot); root != "" {
4197 return []string{desktopSessionDir(root)}
4198 }
4199 return nil
4200 }
4201 return []string{desktopSessionDir(globalWorkspaceRoot()), config.SessionDir()}
4202 }
4203
4204 func sessionBindingInDir(dir, sessionPath string) (sessionBinding, bool) {
4205 path, ok := pinnedTabSessionPath(dir, sessionPath)
4206 if !ok {
4207 return sessionBinding{}, false
4208 }
4209 meta, hasMeta, err := agent.LoadBranchMeta(path)
4210 if err != nil {
4211 return sessionBinding{}, false
4212 }
4213 scope, workspaceRoot, _, ownerOK := legacyMigrationTargetForDir(dir)
4214 if !ownerOK {
4215 if !hasMeta {
4216 return sessionBinding{}, false
4217 }
4218 return sessionBindingFromMeta(path, meta)
4219 }
4220 if scope == "global" {
4221 if !hasMeta {
4222 return sessionBinding{}, false
4223 }
4224 return sessionBindingFromMeta(path, meta)
4225 }
4226 binding := sessionBinding{
4227 path: path,
4228 scope: scope,
4229 workspaceRoot: workspaceRoot,
4230 hasMeta: hasMeta,
4231 meta: meta,
4232 }
4233 if hasMeta {
4234 binding.topicID = strings.TrimSpace(meta.TopicID)
4235 binding.topicTitle = strings.TrimSpace(meta.TopicTitle)
4236 }
4237 if binding.scope == "project" {
4238 binding.workspaceRoot = normalizeProjectRoot(binding.workspaceRoot)
4239 }
4240 return binding, true
4241 }
4242
4243 func sessionBindingFromMeta(path string, meta agent.BranchMeta) (sessionBinding, bool) {
4244 scope := meta.DefaultScope()
4245 workspaceRoot := ""
4246 if scope == "project" {
4247 workspaceRoot = normalizeProjectRoot(meta.WorkspaceRoot)
4248 if workspaceRoot == "" {
4249 return sessionBinding{}, false
4250 }
4251 } else {
4252 scope = "global"
4253 workspaceRoot = globalTabWorkspaceRoot()
4254 }
4255 return sessionBinding{
4256 path: path,
4257 scope: scope,
4258 workspaceRoot: workspaceRoot,
4259 topicID: strings.TrimSpace(meta.TopicID),
4260 topicTitle: strings.TrimSpace(meta.TopicTitle),
4261 hasMeta: true,
4262 meta: meta,
4263 }, true
4264 }
4265
4266 // active tab helpers
4267
4268 // activeTab returns the currently active tab (nil when there are no tabs).
4269 // Self-locking; safe to call from any goroutine without external lock.
4270 func (a *App) activeTab() *WorkspaceTab {
4271 a.mu.RLock()
4272 defer a.mu.RUnlock()
4273 if a.activeTabID == "" {
4274 return nil
4275 }
4276 return a.tabs[a.activeTabID]
4277 }
4278
4279 // activeTabLocked is like activeTab but assumes the caller already holds a.mu
4280 // (either RLock or Lock). Use this inside critical sections that already own
4281 // the lock to avoid double-locking a write-lock holder.
4282 func (a *App) activeTabLocked() *WorkspaceTab {
4283 if a.activeTabID == "" {
4284 return nil
4285 }
4286 return a.tabs[a.activeTabID]
4287 }
4288
4289 // activeCtrl returns the controller of the active tab, or nil.
4290 // Self-locking; safe to call from any goroutine without external lock.
4291 func (a *App) activeCtrl() control.SessionAPI {
4292 a.mu.RLock()
4293 defer a.mu.RUnlock()
4294 return a.activeCtrlLocked()
4295 }
4296
4297 // activeCtrlLocked is like activeCtrl but assumes the caller already holds a.mu.
4298 func (a *App) activeCtrlLocked() control.SessionAPI {
4299 t := a.activeTabLocked()
4300 if t == nil {
4301 return nil
4302 }
4303 return t.Ctrl
4304 }
4305
4306 func (a *App) tabByID(tabID string) *WorkspaceTab {
4307 a.mu.RLock()
4308 defer a.mu.RUnlock()
4309 return a.tabByIDLocked(tabID)
4310 }
4311
4312 func (a *App) tabByIDLocked(tabID string) *WorkspaceTab {
4313 if strings.TrimSpace(tabID) == "" {
4314 return a.activeTabLocked()
4315 }
4316 return a.tabs[tabID]
4317 }
4318
4319 func (a *App) ctrlByTabID(tabID string) control.SessionAPI {
4320 a.mu.RLock()
4321 defer a.mu.RUnlock()
4322 tab := a.tabByIDLocked(tabID)
4323 if tab == nil {
4324 return nil
4325 }
4326 return tab.Ctrl
4327 }
4328
4329 // autosave per tab
4330
4331 const maxTabSnapshotFailureRetries = 2
4332
4333 // autosaveWarnInterval rate-limits the user-facing autosave-failure notice
4334 // per tab; slog keeps recording every failure regardless.
4335 const autosaveWarnInterval = 5 * time.Minute
4336
4337 func tabSnapshotRetryDelay(failures int) time.Duration {
4338 switch {
4339 case failures <= 1:
4340 return 100 * time.Millisecond
4341 case failures == 2:
4342 return 250 * time.Millisecond
4343 default:
4344 return 500 * time.Millisecond
4345 }
4346 }
4347
4348 func (a *App) scheduleTabSnapshot(tabID string) {
4349 a.mu.RLock()
4350 tab := a.tabByEventSinkIDLocked(tabID)
4351 a.mu.RUnlock()
4352 if tab == nil {
4353 return
4354 }
4355 tab.saveMu.Lock()
4356 defer tab.saveMu.Unlock()
4357 if tab.closing {
4358 // Tab is being torn down: don't start new snapshot work that could
4359 // race DeleteSession and resurrect a trashed session file (#4384).
4360 return
4361 }
4362 if tab.saving {
4363 tab.saveAgain = true
4364 return
4365 }
4366 tab.saving = true
4367 if tab.saveCond == nil {
4368 tab.saveCond = sync.NewCond(&tab.saveMu)
4369 }
4370 tab.saveFailures = 0
4371 go a.tabSnapshotLoop(tab)
4372 }
4373
4374 // quiesceTabAutosave marks the tab as closing and blocks until any in-flight
4375 // tabSnapshotLoop has finished its current (and final) write. After it returns,
4376 // no background goroutine can call Snapshot on this tab's controller again, so
4377 // a subsequent DeleteSession cannot race a late write. Safe to call after the
4378 // controller's session path has been cleared: the loop's Snapshot becomes a
4379 // no-op and it exits on its next iteration.
4380 func (a *App) quiesceTabAutosave(tab *WorkspaceTab) {
4381 if tab == nil {
4382 return
4383 }
4384 tab.saveMu.Lock()
4385 if tab.saveCond == nil {
4386 tab.saveCond = sync.NewCond(&tab.saveMu)
4387 }
4388 tab.closing = true
4389 for tab.saving {
4390 tab.saveCond.Wait()
4391 }
4392 tab.saveMu.Unlock()
4393 }
4394
4395 func (a *App) tabSnapshotLoop(tab *WorkspaceTab) {
4396 defer a.recoverToPending("tabSnapshotLoop")
4397 for {
4398 var snapshotErr error
4399 a.mu.RLock()
4400 ctrl := tab.Ctrl
4401 a.mu.RUnlock()
4402 if ctrl != nil {
4403 if err := a.snapshotTab(tab); err == nil {
4404 a.mu.RLock()
4405 scope, workspaceRoot := tab.Scope, tab.WorkspaceRoot
4406 a.mu.RUnlock()
4407 a.requestSessionCatalogPath(scope, workspaceRoot, ctrl.SessionPath())
4408 if !a.maybeAutoTitleTopic(tab) {
4409 a.emitProjectTreeChangedForSessionDirs(ctrl.SessionDir())
4410 }
4411 } else {
4412 snapshotErr = err
4413 }
4414 }
4415 tab.saveMu.Lock()
4416 if tab.saveCond == nil {
4417 tab.saveCond = sync.NewCond(&tab.saveMu)
4418 }
4419 if snapshotErr == nil {
4420 tab.saveFailures = 0
4421 } else {
4422 tab.saveFailures++
4423 }
4424 if tab.closing {
4425 // Tab is being torn down: stop without picking up saveAgain work.
4426 tab.saving = false
4427 tab.saveCond.Broadcast()
4428 tab.saveMu.Unlock()
4429 if snapshotErr != nil {
4430 slog.Warn("desktop: session autosave failed during teardown", "tab", tab.ID, "err", snapshotErr)
4431 }
4432 return
4433 }
4434 if tab.saveAgain {
4435 tab.saveAgain = false
4436 tab.saveMu.Unlock()
4437 if snapshotErr != nil {
4438 slog.Warn("desktop: session autosave failed; newer snapshot queued", "tab", tab.ID, "err", snapshotErr)
4439 }
4440 continue
4441 }
4442 if snapshotErr != nil && tab.saveFailures <= maxTabSnapshotFailureRetries {
4443 delay := tabSnapshotRetryDelay(tab.saveFailures)
4444 attempt := tab.saveFailures
4445 tab.saveMu.Unlock()
4446 // Retries are routine (transient AV/indexer holds); tell the user
4447 // only when the whole burst gives up, not once per attempt.
4448 slog.Warn("desktop: session autosave failed; retrying", "tab", tab.ID, "attempt", attempt, "err", snapshotErr)
4449 time.Sleep(delay)
4450 continue
4451 }
4452 exhausted := snapshotErr
4453 tab.saving = false
4454 tab.saveCond.Broadcast()
4455 tab.saveMu.Unlock()
4456 if exhausted != nil {
4457 a.reportTabSnapshotError(tab, "autosave", exhausted)
4458 }
4459 return
4460 }
4461 }
4462
4463 func (a *App) maybeAutoTitleTopic(tab *WorkspaceTab) bool {
4464 if tab == nil {
4465 return false
4466 }
4467 a.lifecycleCheckpoint("before-autosave-topic-title")
4468 a.topicTitleMutationMu.Lock()
4469 defer a.topicTitleMutationMu.Unlock()
4470 // Runs on the autosave goroutine; TopicID/Scope/WorkspaceRoot/Ctrl are
4471 // written under a.mu by session switches and recovery.
4472 a.mu.RLock()
4473 if tab.removed {
4474 a.mu.RUnlock()
4475 return false
4476 }
4477 topicID := strings.TrimSpace(tab.TopicID)
4478 titleRoot := tab.WorkspaceRoot
4479 if tab.Scope == "global" {
4480 titleRoot = ""
4481 }
4482 ctrl := tab.Ctrl
4483 a.mu.RUnlock()
4484 if topicID == "" || ctrl == nil {
4485 return false
4486 }
4487 if source := loadTopicTitleSource(titleRoot, topicID); source != topicTitleSourceAuto {
4488 return false
4489 }
4490 sessionPath := ctrl.SessionPath()
4491 if sessionPath == "" {
4492 return false
4493 }
4494 if sessionHasManualDisplayTitle(sessionPath) {
4495 return false
4496 }
4497 nextTitle, updated := autoTitleTopicFromSession(titleRoot, topicID, sessionPath)
4498 if !updated {
4499 return false
4500 }
4501 if topicAutoTitleCommittedHookForTest != nil {
4502 topicAutoTitleCommittedHookForTest()
4503 }
4504 a.updateOpenTopicTitle(topicID, nextTitle, topicTitleSourceAuto)
4505 changedDirs := a.updateTopicSessionTitles(topicID, nextTitle)
4506 if len(changedDirs) > 0 {
4507 a.emitProjectTreeChangedForSessionDirs(changedDirs...)
4508 } else {
4509 a.emitProjectTreeMetadataChanged()
4510 }
4511 return true
4512 }
4513
4514 func autoTitleTopicFromSession(workspaceRoot, topicID, sessionPath string) (string, bool) {
4515 if source := loadTopicTitleSource(workspaceRoot, topicID); source != topicTitleSourceAuto {
4516 return "", false
4517 }
4518 if sessionHasManualDisplayTitle(sessionPath) {
4519 return "", false
4520 }
4521 proposal := autoTopicTitleProposalFromSession(sessionPath)
4522 if proposal.Title == "" {
4523 return "", false
4524 }
4525 if !shouldApplyAutoTopicTitle(workspaceRoot, topicID, proposal) {
4526 return "", false
4527 }
4528 nextTitle := proposal.Title
4529 sameTitle := nextTitle == strings.TrimSpace(loadTopicTitle(workspaceRoot, topicID))
4530 applied, err := applyAutoTopicTitle(workspaceRoot, topicID, nextTitle, proposal)
4531 if err != nil || !applied {
4532 return "", false
4533 }
4534 if sameTitle {
4535 return "", false
4536 }
4537 return nextTitle, true
4538 }
4539
4540 type autoTopicTitleProposal struct {
4541 Title string
4542 Stage int
4543 UserTurns int
4544 BasisHash string
4545 }
4546
4547 func autoTopicTitleProposalFromSession(path string) autoTopicTitleProposal {
4548 users := topicTitleUserTurnsFromSession(path)
4549 if len(users) == 0 {
4550 return autoTopicTitleProposal{}
4551 }
4552 stage := 1
4553 if len(users) >= 3 {
4554 stage = 3
4555 }
4556 basis := users
4557 if len(basis) > stage {
4558 basis = basis[:stage]
4559 }
4560 title := topicTitleFromUserTurns(basis)
4561 if title == "" {
4562 return autoTopicTitleProposal{}
4563 }
4564 sum := sha256.Sum256(fmt.Appendf(nil, "%d\x00%s", stage, strings.Join(basis, "\x00")))
4565 return autoTopicTitleProposal{
4566 Title: title,
4567 Stage: stage,
4568 UserTurns: len(users),
4569 BasisHash: hex.EncodeToString(sum[:8]),
4570 }
4571 }
4572
4573 func shouldApplyAutoTopicTitle(workspaceRoot, topicID string, proposal autoTopicTitleProposal) bool {
4574 if proposal.Stage <= 0 || proposal.BasisHash == "" {
4575 return false
4576 }
4577 meta := loadTopicAutoTitleMeta(workspaceRoot)[topicID]
4578 if meta.Stage > proposal.Stage {
4579 return false
4580 }
4581 if meta.Stage == proposal.Stage && meta.BasisHash == proposal.BasisHash {
4582 return false
4583 }
4584 return true
4585 }
4586
4587 func sessionHasManualDisplayTitle(sessionPath string) bool {
4588 legacyPath, ok := validatedLegacySessionPathForRead(sessionPath)
4589 if !ok {
4590 return false
4591 }
4592 sessionPath = string(legacyPath)
4593 if meta, ok, err := agent.LoadBranchMeta(sessionPath); err == nil && ok {
4594 if strings.TrimSpace(meta.CustomTitle) != "" {
4595 return true
4596 }
4597 }
4598 dir := filepath.Dir(sessionPath)
4599 if dir == "." || dir == string(filepath.Separator) {
4600 return false
4601 }
4602 return strings.TrimSpace(loadSessionTitles(dir)[filepath.Base(sessionPath)]) != ""
4603 }
4604
4605 func topicTitleFallbackForOpen(workspaceRoot, topicID, sessionPath string) (string, string, bool) {
4606 topicID = strings.TrimSpace(topicID)
4607 legacyPath, ok := validatedLegacySessionPathForRead(sessionPath)
4608 if topicID == "" || !ok {
4609 return "", "", false
4610 }
4611 sessionPath = string(legacyPath)
4612 storedTitle := strings.TrimSpace(loadTopicTitle(workspaceRoot, topicID))
4613 storedSource := strings.TrimSpace(loadTopicTitleSource(workspaceRoot, topicID))
4614 if storedTitle != "" {
4615 if storedSource == topicTitleSourceManual || !isDefaultTopicTitle(storedTitle) {
4616 return "", "", false
4617 }
4618 }
4619
4620 if storedTitle == "" {
4621 dir := filepath.Dir(sessionPath)
4622 if meta, ok, err := agent.LoadBranchMeta(sessionPath); err == nil && ok {
4623 if title := storedSessionTopicTitle(dir, sessionPath, meta); title != "" {
4624 return title, topicTitleSourceManual, true
4625 }
4626 } else if title := topicTitleFromText(loadSessionTitles(dir)[filepath.Base(sessionPath)]); title != "" {
4627 return title, topicTitleSourceManual, true
4628 }
4629 }
4630
4631 if storedSource == topicTitleSourceManual {
4632 return "", "", false
4633 }
4634 if storedSource == "" || storedSource == topicTitleSourceAuto {
4635 if title := topicTitleFromSession(sessionPath); title != "" {
4636 return title, topicTitleSourceAuto, true
4637 }
4638 }
4639 return "", "", false
4640 }
4641
4642 func topicTitleFromSession(path string) string {
4643 users := topicTitleUserTurnsFromSession(path)
4644 if len(users) == 0 {
4645 return ""
4646 }
4647 return topicTitleFromText(users[0])
4648 }
4649
4650 func topicTitleUserTurnsFromSession(path string) []string {
4651 users, _ := loadTopicTitleUserTurnsFromSession(path)
4652 return users
4653 }
4654
4655 func loadTopicTitleUserTurnsFromSession(path string) ([]string, error) {
4656 legacyPath, ok := validatedLegacySessionPathForRead(path)
4657 if !ok {
4658 return nil, &sessionLocatorError{reason: "invalid_legacy_path"}
4659 }
4660 // Event-log aware: decoding the .jsonl checkpoint directly would stop
4661 // seeing user turns after the first save, silently disabling the ≥3-turn
4662 // title upgrade.
4663 msgs, err := agent.LoadSessionUserMessages(string(legacyPath))
4664 if err != nil {
4665 return nil, err
4666 }
4667 var users []string
4668 for _, msg := range msgs {
4669 // Host-injected synthetic turns (readiness nudges, recovery retries) and
4670 // mid-turn steers are persisted as role "user" but are not user-authored:
4671 // counting them inflated userTurns past the stage-3 threshold and let
4672 // "Host final-answer readiness check failed…" become a topic title.
4673 // UserPreviewText is the canonical user-authored view: it unwraps
4674 // memory-compiler execution contracts and strips transient blocks
4675 // (and runs HandoffTask), so internal wrappers can never become a
4676 // title basis (#5666).
4677 if content := topicTitleUserText(msg.Message); content != "" {
4678 users = append(users, content)
4679 }
4680 }
4681 return users, nil
4682 }
4683
4684 func topicTitleFromUserTurns(users []string) string {
4685 type candidate struct {
4686 title string
4687 score int
4688 }
4689 best := candidate{score: -1}
4690 for i, text := range users {
4691 title := topicTitleFromText(text)
4692 if title == "" || lowSignalTopicTitle(title) {
4693 continue
4694 }
4695 runes := len([]rune(title))
4696 score := min(runes, 24)
4697 if i == 0 {
4698 score += 3
4699 }
4700 if runes < 5 {
4701 score -= 6
4702 }
4703 if score > best.score {
4704 best = candidate{title: title, score: score}
4705 }
4706 }
4707 if best.title != "" {
4708 return best.title
4709 }
4710 if len(users) > 0 {
4711 return topicTitleFromText(users[0])
4712 }
4713 return ""
4714 }
4715
4716 func lowSignalTopicTitle(title string) bool {
4717 normalized := strings.ToLower(strings.TrimSpace(title))
4718 normalized = strings.Trim(normalized, " \t\r\n,。!?;:、,.!?;:\"'`“”‘’()()[]【】")
4719 switch normalized {
4720 case "", "好", "好的", "好啊", "可以", "嗯", "对", "是的", "继续", "继续吧", "采纳建议", "采用建议", "收到", "明白", "ok", "okay", "yes", "yep", "go on", "continue", "thanks", "thank you":
4721 return true
4722 default:
4723 return false
4724 }
4725 }
4726
4727 func topicTitleFromText(text string) string {
4728 text = strings.TrimSpace(text)
4729 if text == "" {
4730 return ""
4731 }
4732 text = strings.Join(strings.Fields(text), " ")
4733 text = strings.Trim(text, " \t\r\n,。!?;:、,.!?;:\"'`“”‘’()()[]【】")
4734 if text == "" {
4735 return ""
4736 }
4737 const maxRunes = 18
4738 runes := []rune(text)
4739 if len(runes) > maxRunes {
4740 text = strings.TrimRightFunc(string(runes[:maxRunes]), unicode.IsPunct) + "…"
4741 }
4742 if isDefaultTopicTitle(text) {
4743 return ""
4744 }
4745 return text
4746 }
4747
4748 // persistence: desktop-projects.json
4749
4750 const desktopProjectsFile = "desktop-projects.json"
4751 const tabsFileName = "desktop-tabs.json"
4752 const desktopGlobalOrderToken = "__global__"
4753 const legacyProjectSidebarRecoveryMarker = "desktop-projects-legacy-recovered"
4754
4755 var desktopProjectsFileMu sync.Mutex
4756
4757 func desktopConfigDir() string {
4758 return config.ReasonixHomeDir()
4759 }
4760
4761 func (a *App) saveTabsLocked() {
4762 dir, entries, activeID, version := a.saveTabsCollectLocked()
4763 a.saveTabsWrite(dir, entries, activeID, version)
4764 }
4765
4766 // saveTabsCollectLocked gathers the tab-snapshot data under the caller's lock
4767 // (it calls orderedTabIDsLocked which requires a.mu). Returns the config dir,
4768 // the serializable entries, the active tab ID, and a monotonic snapshot version.
4769 // The write can happen outside the lock to avoid blocking the UI with disk I/O.
4770 func (a *App) saveTabsCollectLocked() (string, []desktopTabEntry, string, uint64) {
4771 dir := desktopConfigDir()
4772 var entries []desktopTabEntry
4773 for _, id := range a.orderedTabIDsLocked() {
4774 if tab := a.tabs[id]; tab != nil {
4775 if a.suppressTabStartupRestoreLocked(tab) {
4776 continue
4777 }
4778 entries = append(entries, persistedDesktopTabEntry(tab))
4779 }
4780 }
4781 a.tabsSaveVersion++
4782 return dir, entries, persistedActiveTabID(entries, a.activeTabID), a.tabsSaveVersion
4783 }
4784
4785 func (a *App) orderedTabIDsLocked() []string {
4786 ordered, needsRepair := a.orderedTabIDsSnapshotLocked()
4787 if needsRepair {
4788 a.tabOrder = append([]string(nil), ordered...)
4789 }
4790 return ordered
4791 }
4792
4793 func (a *App) orderedTabIDsSnapshotLocked() ([]string, bool) {
4794 seen := make(map[string]bool, len(a.tabs))
4795 ordered := make([]string, 0, len(a.tabs))
4796 for _, id := range a.tabOrder {
4797 if _, ok := a.tabs[id]; ok && !seen[id] {
4798 ordered = append(ordered, id)
4799 seen[id] = true
4800 }
4801 }
4802 var missing []string
4803 for id := range a.tabs {
4804 if !seen[id] {
4805 missing = append(missing, id)
4806 }
4807 }
4808 sort.Strings(missing)
4809 ordered = append(ordered, missing...)
4810 return ordered, len(ordered) != len(a.tabOrder) || len(missing) > 0
4811 }
4812
4813 func loadTabsFile() desktopTabsFile {
4814 path := filepath.Join(desktopConfigDir(), tabsFileName)
4815 b, err := readFileUTF8(path)
4816 if err != nil {
4817 return desktopTabsFile{}
4818 }
4819 var f desktopTabsFile
4820 _ = json.Unmarshal(b, &f)
4821 return f
4822 }
4823
4824 func desktopMCPMigrationRoots(tabs desktopTabsFile) []string {
4825 seen := map[string]bool{}
4826 var roots []string
4827 add := func(root string) {
4828 root = normalizeProjectRoot(root)
4829 key := projectRootKey(root)
4830 if root == "" || seen[key] {
4831 return
4832 }
4833 seen[key] = true
4834 roots = append(roots, root)
4835 }
4836 if cur := loadWorkspace(); cur != "" {
4837 add(cur)
4838 }
4839 for _, root := range loadWorkspaces() {
4840 add(root)
4841 }
4842 for _, entry := range tabs.Tabs {
4843 if entry.Scope == "project" {
4844 add(entry.WorkspaceRoot)
4845 }
4846 }
4847 for _, project := range loadProjectsFile().Projects {
4848 add(project.Root)
4849 }
4850 return roots
4851 }
4852
4853 func recoverLegacyProjectSidebarRoots(tabs desktopTabsFile) (bool, error) {
4854 markerPath := filepath.Join(desktopConfigDir(), legacyProjectSidebarRecoveryMarker)
4855 if _, err := os.Stat(markerPath); err == nil {
4856 return false, nil
4857 }
4858
4859 changed := false
4860 err := updateProjectsFilePreservingLegacyState(func(f *desktopProjectFile) (bool, error) {
4861 seen := map[string]bool{}
4862 for _, project := range f.Projects {
4863 root := normalizeProjectRoot(project.Root)
4864 if root != "" {
4865 seen[projectRootKey(root)] = true
4866 }
4867 }
4868
4869 add := func(root string) {
4870 root = normalizeProjectRoot(root)
4871 key := projectRootKey(root)
4872 if root == "" || seen[key] || !existingDirectory(root) {
4873 return
4874 }
4875 seen[key] = true
4876 f.Projects = append(f.Projects, desktopProject{Root: root})
4877 changed = true
4878 }
4879 if cur := loadWorkspace(); cur != "" {
4880 add(cur)
4881 }
4882 for _, root := range loadWorkspaces() {
4883 add(root)
4884 }
4885 for _, entry := range tabs.Tabs {
4886 if entry.Scope == "project" {
4887 add(entry.WorkspaceRoot)
4888 }
4889 }
4890 return changed, nil
4891 })
4892 if err != nil {
4893 return false, err
4894 }
4895 return changed, writeLegacyProjectSidebarRecoveryMarker(markerPath)
4896 }
4897
4898 func existingDirectory(path string) bool {
4899 info, err := os.Stat(path)
4900 return err == nil && info.IsDir()
4901 }
4902
4903 func writeLegacyProjectSidebarRecoveryMarker(path string) error {
4904 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
4905 return err
4906 }
4907 return os.WriteFile(path, []byte("ok\n"), 0o644)
4908 }
4909
4910 func loadProjectsFile() desktopProjectFile {
4911 path := filepath.Join(desktopConfigDir(), desktopProjectsFile)
4912 b, err := readFileUTF8(path)
4913 if err != nil {
4914 return desktopProjectFile{}
4915 }
4916 var f desktopProjectFile
4917 _ = json.Unmarshal(b, &f)
4918 f = normalizeProjectsFile(f)
4919 if organization, ok := loadProjectOrganizationFile(); ok {
4920 return applyProjectOrganization(f, organization)
4921 }
4922 // Upgrade existing inline organization state immediately. The sidecar is
4923 // what makes a later old-version save non-destructive.
4924 if projectsFileHasOrganization(f) {
4925 _ = saveProjectOrganizationFile(f)
4926 }
4927 return f
4928 }
4929
4930 func saveProjectsFile(f desktopProjectFile) error {
4931 dir := desktopConfigDir()
4932 if err := os.MkdirAll(dir, 0o755); err != nil {
4933 return err
4934 }
4935 f = normalizeProjectsFile(f)
4936 if err := saveProjectOrganizationFile(f); err != nil {
4937 return err
4938 }
4939 b, err := json.MarshalIndent(f, "", " ")
4940 if err != nil {
4941 return err
4942 }
4943 path := filepath.Join(dir, desktopProjectsFile)
4944 tmp := path + ".tmp"
4945 if err := os.WriteFile(tmp, b, 0o644); err != nil {
4946 return err
4947 }
4948 return fileutil.ReplaceFile(tmp, path)
4949 }
4950
4951 func updateProjectsFile(mutator func(*desktopProjectFile) (bool, error)) error {
4952 return updateProjectsFileWithCollisionAssignment(mutator, true)
4953 }
4954
4955 func updateProjectsFilePreservingLegacyState(mutator func(*desktopProjectFile) (bool, error)) error {
4956 return updateProjectsFileWithCollisionAssignment(mutator, false)
4957 }
4958
4959 func updateProjectsFileWithCollisionAssignment(mutator func(*desktopProjectFile) (bool, error), assignCollisions bool) error {
4960 desktopProjectsFileMu.Lock()
4961 defer desktopProjectsFileMu.Unlock()
4962 return updateProjectsFileLockedWithCollisionAssignment(mutator, assignCollisions)
4963 }
4964
4965 func updateProjectsFileLockedWithCollisionAssignment(mutator func(*desktopProjectFile) (bool, error), assignCollisions bool) error {
4966 release, err := acquireDesktopProjectsFileLock()
4967 if err != nil {
4968 return err
4969 }
4970 defer release()
4971 return updateProjectsFileCrossProcessLocked(mutator, assignCollisions)
4972 }
4973
4974 func prependTopicInProjectsFile(workspaceRoot, topicID string, ensureProject bool) error {
4975 // Single-topic prepends are intentional writes (topic creation, a live tab
4976 // indexing its session, restore from trash): they clear any delete
4977 // tombstone so the topic fully returns instead of landing in a half-state
4978 // where only its title resurfaces.
4979 return prependTopicsInProjectsFileOpts(workspaceRoot, []string{topicID}, ensureProject, false)
4980 }
4981
4982 func prependTopicsInProjectsFile(workspaceRoot string, topicIDs []string, ensureProject bool) error {
4983 // Batch prepends come from the legacy migration and index-repair scans:
4984 // they must respect delete tombstones so a scan never resurrects a topic
4985 // the user removed.
4986 return prependTopicsInProjectsFileOpts(workspaceRoot, topicIDs, ensureProject, true)
4987 }
4988
4989 func prependTopicsInProjectsFileOpts(workspaceRoot string, topicIDs []string, ensureProject, respectTombstones bool) error {
4990 workspaceRoot = normalizeProjectRoot(workspaceRoot)
4991 topicIDs = uniqueStrings(topicIDs)
4992 if len(topicIDs) == 0 {
4993 return nil
4994 }
4995 return updateProjectsFile(func(f *desktopProjectFile) (bool, error) {
4996 // Tombstones are checked under the projects-file lock: a DeleteTopic
4997 // that lands between a scan reading DeletedTopics and this write must
4998 // not be resurrected by the stale batch.
4999 live := topicIDs
5000 changed := false
5001 if respectTombstones {
5002 live = make([]string, 0, len(topicIDs))
5003 for _, id := range topicIDs {
5004 if !containsDesktopString(f.DeletedTopics, id) {
5005 live = append(live, id)
5006 }
5007 }
5008 if len(live) == 0 {
5009 return false, nil
5010 }
5011 } else {
5012 for _, id := range topicIDs {
5013 if next := removeString(f.DeletedTopics, id); !sameStringList(next, f.DeletedTopics) {
5014 f.DeletedTopics = next
5015 changed = true
5016 }
5017 }
5018 }
5019 if workspaceRoot == "" {
5020 next := uniqueStrings(append(append([]string(nil), live...), f.GlobalTopics...))
5021 if sameStringList(next, f.GlobalTopics) {
5022 return changed, nil
5023 }
5024 f.GlobalTopics = next
5025 return true, nil
5026 }
5027 for i, p := range f.Projects {
5028 if !sameProjectRoot(p.Root, workspaceRoot) {
5029 continue
5030 }
5031 next := uniqueStrings(append(append([]string(nil), live...), p.Topics...))
5032 if sameStringList(next, p.Topics) {
5033 return changed, nil
5034 }
5035 f.Projects[i].Topics = next
5036 return true, nil
5037 }
5038 if !ensureProject {
5039 return changed, nil
5040 }
5041 f.Projects = append(f.Projects, desktopProject{Root: workspaceRoot, Topics: live})
5042 return true, nil
5043 })
5044 }
5045
5046 func removeTopicFromProjectsFile(topicID string) error {
5047 topicID = strings.TrimSpace(topicID)
5048 if topicID == "" {
5049 return nil
5050 }
5051 desktopProjectsFileMu.Lock()
5052 defer desktopProjectsFileMu.Unlock()
5053 return removeTopicFromProjectsFileLocked(topicID)
5054 }
5055
5056 func removeTopicFromProjectsFileLocked(topicID string) error {
5057 release, err := acquireDesktopProjectsFileLock()
5058 if err != nil {
5059 return err
5060 }
5061 defer release()
5062 return removeTopicFromProjectsFileCrossProcessLocked(topicID)
5063 }
5064
5065 func removeTopicFromProjectsFileCrossProcessLocked(topicID string) error {
5066 return updateProjectsFileCrossProcessLocked(func(f *desktopProjectFile) (bool, error) {
5067 changed := false
5068 if next := removeString(f.GlobalTopics, topicID); !sameStringList(next, f.GlobalTopics) {
5069 f.GlobalTopics = next
5070 changed = true
5071 }
5072 if next := removeString(f.GlobalPinnedTopics, topicID); !sameStringList(next, f.GlobalPinnedTopics) {
5073 f.GlobalPinnedTopics = next
5074 changed = true
5075 }
5076 if next, removed := groupsWithoutTopic(f.GlobalGroups, topicID); removed {
5077 f.GlobalGroups = next
5078 f.GlobalGroupsRevision++
5079 changed = true
5080 }
5081 if next := prependUniqueString(f.DeletedTopics, topicID); !sameStringList(next, f.DeletedTopics) {
5082 f.DeletedTopics = next
5083 changed = true
5084 }
5085 for i, p := range f.Projects {
5086 if next := removeString(p.Topics, topicID); !sameStringList(next, p.Topics) {
5087 f.Projects[i].Topics = next
5088 changed = true
5089 }
5090 if next := removeString(p.PinnedTopics, topicID); !sameStringList(next, p.PinnedTopics) {
5091 f.Projects[i].PinnedTopics = next
5092 changed = true
5093 }
5094 if next, removed := groupsWithoutTopic(p.Groups, topicID); removed {
5095 f.Projects[i].Groups = next
5096 f.Projects[i].GroupsRevision++
5097 changed = true
5098 }
5099 }
5100 return changed, nil
5101 }, true)
5102 }
5103
5104 func normalizeProjectRoot(root string) string {
5105 root = strings.TrimSpace(root)
5106 if root == "" {
5107 return ""
5108 }
5109 if abs, err := filepath.Abs(root); err == nil {
5110 return abs
5111 }
5112 return root
5113 }
5114
5115 func sameProjectRoot(a, b string) bool {
5116 return newDesktopPathMatcher().sameProjectRoot(a, b)
5117 }
5118
5119 func (m desktopPathMatcher) sameProjectRoot(a, b string) bool {
5120 return m.same(normalizeProjectRoot(a), normalizeProjectRoot(b))
5121 }
5122
5123 func projectIndexByRoot(projects []desktopProject, root string) int {
5124 return newDesktopPathMatcher().projectIndexByRoot(projects, root)
5125 }
5126
5127 func (m desktopPathMatcher) projectIndexByRoot(projects []desktopProject, root string) int {
5128 root = normalizeProjectRoot(root)
5129 if root == "" {
5130 return -1
5131 }
5132 for i, project := range projects {
5133 if m.sameProjectRoot(project.Root, root) {
5134 return i
5135 }
5136 }
5137 return -1
5138 }
5139
5140 func projectRootInList(roots []string, root string) bool {
5141 return newDesktopPathMatcher().projectRootInList(roots, root)
5142 }
5143
5144 func (m desktopPathMatcher) projectRootInList(roots []string, root string) bool {
5145 root = normalizeProjectRoot(root)
5146 if root == "" {
5147 return false
5148 }
5149 for _, candidate := range roots {
5150 if m.sameProjectRoot(candidate, root) {
5151 return true
5152 }
5153 }
5154 return false
5155 }
5156
5157 func normalizeProjectsFile(f desktopProjectFile) desktopProjectFile {
5158 return newDesktopPathMatcher().normalizeProjectsFile(f)
5159 }
5160
5161 func (m desktopPathMatcher) normalizeProjectsFile(f desktopProjectFile) desktopProjectFile {
5162 out := desktopProjectFile{
5163 GlobalTitle: strings.TrimSpace(f.GlobalTitle),
5164 GlobalColor: normalizeProjectColor(f.GlobalColor),
5165 GlobalTopics: uniqueStrings(f.GlobalTopics),
5166 GlobalPinnedTopics: uniqueStrings(f.GlobalPinnedTopics),
5167 GlobalManualTopicOrder: f.GlobalManualTopicOrder,
5168 GlobalManualSessionOrder: f.GlobalManualSessionOrder,
5169 GlobalSessionOrder: uniqueStrings(f.GlobalSessionOrder),
5170 GlobalGroups: normalizeGroups(f.GlobalGroups),
5171 GlobalGroupsRevision: f.GlobalGroupsRevision,
5172 DeletedTopics: uniqueStrings(f.DeletedTopics),
5173 }
5174 for _, p := range f.Projects {
5175 root := normalizeProjectRoot(p.Root)
5176 if root == "" {
5177 continue
5178 }
5179 p.Root = root
5180 p.Title = strings.TrimSpace(p.Title)
5181 p.Color = normalizeProjectColor(p.Color)
5182 p.Topics = uniqueStrings(p.Topics)
5183 p.PinnedTopics = uniqueStrings(p.PinnedTopics)
5184 p.Groups = normalizeGroups(p.Groups)
5185 if i := m.projectIndexByRoot(out.Projects, root); i >= 0 {
5186 if out.Projects[i].Title == "" && p.Title != "" {
5187 out.Projects[i].Title = p.Title
5188 }
5189 if out.Projects[i].Color == "" && p.Color != "" {
5190 out.Projects[i].Color = p.Color
5191 }
5192 out.Projects[i].Topics = uniqueStrings(append(out.Projects[i].Topics, p.Topics...))
5193 out.Projects[i].PinnedTopics = uniqueStrings(append(out.Projects[i].PinnedTopics, p.PinnedTopics...))
5194 out.Projects[i].ManualTopicOrder = out.Projects[i].ManualTopicOrder || p.ManualTopicOrder
5195 out.Projects[i].Groups = mergeDesktopGroups(out.Projects[i].Groups, p.Groups)
5196 out.Projects[i].GroupsRevision = max(out.Projects[i].GroupsRevision, p.GroupsRevision)
5197 continue
5198 }
5199 out.Projects = append(out.Projects, p)
5200 }
5201 for _, root := range uniqueStrings(f.PinnedProjects) {
5202 root = normalizeProjectRoot(root)
5203 if i := m.projectIndexByRoot(out.Projects, root); i >= 0 && !m.projectRootInList(out.PinnedProjects, out.Projects[i].Root) {
5204 out.PinnedProjects = append(out.PinnedProjects, out.Projects[i].Root)
5205 }
5206 }
5207 out.SidebarOrder = m.normalizeSidebarOrder(f.SidebarOrder, out.Projects)
5208 return out
5209 }
5210
5211 func (m desktopPathMatcher) normalizeSidebarOrder(order []string, projects []desktopProject) []string {
5212 seenGlobal := false
5213 // Dedupe roots against a roots-only list: out also holds the global order
5214 // token, which must never be path-compared against project roots.
5215 var seenRoots []string
5216 out := make([]string, 0, len(order))
5217 for _, value := range order {
5218 value = strings.TrimSpace(value)
5219 if value == desktopGlobalOrderToken {
5220 if !seenGlobal {
5221 seenGlobal = true
5222 out = append(out, value)
5223 }
5224 continue
5225 }
5226 root := normalizeProjectRoot(value)
5227 i := m.projectIndexByRoot(projects, root)
5228 if i < 0 {
5229 continue
5230 }
5231 root = projects[i].Root
5232 if m.projectRootInList(seenRoots, root) {
5233 continue
5234 }
5235 seenRoots = append(seenRoots, root)
5236 out = append(out, root)
5237 }
5238 return out
5239 }
5240
5241 func sameProjectOrder(a, b []desktopProject) bool {
5242 if len(a) != len(b) {
5243 return false
5244 }
5245 for i := range a {
5246 if a[i].Root != b[i].Root {
5247 return false
5248 }
5249 }
5250 return true
5251 }
5252
5253 func uniqueStrings(values []string) []string {
5254 seen := make(map[string]bool, len(values))
5255 out := make([]string, 0, len(values))
5256 for _, value := range values {
5257 value = strings.TrimSpace(value)
5258 if value == "" || seen[value] {
5259 continue
5260 }
5261 seen[value] = true
5262 out = append(out, value)
5263 }
5264 return out
5265 }
5266
5267 func prependUniqueString(values []string, value string) []string {
5268 value = strings.TrimSpace(value)
5269 if value == "" {
5270 return uniqueStrings(values)
5271 }
5272 return uniqueStrings(append([]string{value}, values...))
5273 }
5274
5275 func removeString(values []string, value string) []string {
5276 value = strings.TrimSpace(value)
5277 if value == "" {
5278 return uniqueStrings(values)
5279 }
5280 out := make([]string, 0, len(values))
5281 for _, item := range uniqueStrings(values) {
5282 if item != value {
5283 out = append(out, item)
5284 }
5285 }
5286 return out
5287 }
5288
5289 func containsDesktopString(values []string, value string) bool {
5290 value = strings.TrimSpace(value)
5291 if value == "" {
5292 return false
5293 }
5294 return slices.Contains(uniqueStrings(values), value)
5295 }
5296
5297 func pinnedTopicIDs(topicIDs []string, pinned []string) []string {
5298 if len(topicIDs) == 0 || len(pinned) == 0 {
5299 return topicIDs
5300 }
5301 available := make(map[string]bool, len(topicIDs))
5302 for _, tid := range topicIDs {
5303 available[tid] = true
5304 }
5305 out := make([]string, 0, len(topicIDs))
5306 seen := make(map[string]bool, len(topicIDs))
5307 for _, tid := range uniqueStrings(pinned) {
5308 if available[tid] && !seen[tid] {
5309 out = append(out, tid)
5310 seen[tid] = true
5311 }
5312 }
5313 for _, tid := range topicIDs {
5314 if !seen[tid] {
5315 out = append(out, tid)
5316 }
5317 }
5318 return out
5319 }
5320
5321 func orderedTopicIDs(explicit []string, titleMap map[string]string) []string {
5322 seen := map[string]bool{}
5323 out := make([]string, 0, len(explicit)+len(titleMap))
5324 for _, tid := range explicit {
5325 tid = strings.TrimSpace(tid)
5326 if tid == "" || seen[tid] {
5327 continue
5328 }
5329 seen[tid] = true
5330 out = append(out, tid)
5331 }
5332 var remaining []string
5333 for tid := range titleMap {
5334 if !seen[tid] {
5335 remaining = append(remaining, tid)
5336 }
5337 }
5338 sort.Strings(remaining)
5339 return append(out, remaining...)
5340 }
5341
5342 func projectTreeOrderKey(node ProjectNode) string {
5343 switch node.Kind {
5344 case "global_folder":
5345 return desktopGlobalOrderToken
5346 case "project":
5347 return normalizeProjectRoot(node.Root)
5348 default:
5349 return ""
5350 }
5351 }
5352
5353 func applyProjectTreeOrder(nodes []ProjectNode, order []string) []ProjectNode {
5354 if len(order) == 0 {
5355 return nodes
5356 }
5357 byKey := make(map[string]ProjectNode, len(nodes))
5358 for _, node := range nodes {
5359 key := projectTreeOrderKey(node)
5360 if key != "" {
5361 byKey[key] = node
5362 }
5363 }
5364 seen := make(map[string]bool, len(nodes))
5365 out := make([]ProjectNode, 0, len(nodes))
5366 for _, value := range order {
5367 key := strings.TrimSpace(value)
5368 if key != desktopGlobalOrderToken {
5369 key = normalizeProjectRoot(key)
5370 }
5371 if key == "" || seen[key] {
5372 continue
5373 }
5374 node, ok := byKey[key]
5375 if !ok {
5376 continue
5377 }
5378 seen[key] = true
5379 out = append(out, node)
5380 }
5381 for _, node := range nodes {
5382 key := projectTreeOrderKey(node)
5383 if key != "" && seen[key] {
5384 continue
5385 }
5386 if key != "" {
5387 seen[key] = true
5388 }
5389 out = append(out, node)
5390 }
5391 return out
5392 }
5393
5394 func applyPinnedProjectOrder(nodes []ProjectNode, pinnedRoots []string) []ProjectNode {
5395 pinnedRoots = uniqueStrings(pinnedRoots)
5396 if len(pinnedRoots) == 0 {
5397 return nodes
5398 }
5399 byRoot := make(map[string]ProjectNode, len(nodes))
5400 for _, node := range nodes {
5401 if node.Kind == "project" && node.Root != "" {
5402 byRoot[normalizeProjectRoot(node.Root)] = node
5403 }
5404 }
5405 seen := make(map[string]bool, len(pinnedRoots))
5406 out := make([]ProjectNode, 0, len(nodes))
5407 for _, root := range pinnedRoots {
5408 root = normalizeProjectRoot(root)
5409 node, ok := byRoot[root]
5410 if !ok || seen[root] {
5411 continue
5412 }
5413 seen[root] = true
5414 out = append(out, node)
5415 }
5416 for _, node := range nodes {
5417 if node.Kind == "project" && node.Root != "" && seen[normalizeProjectRoot(node.Root)] {
5418 continue
5419 }
5420 out = append(out, node)
5421 }
5422 return out
5423 }
5424
5425 func projectDisplayName(p desktopProject) string {
5426 if title := strings.TrimSpace(p.Title); title != "" {
5427 return title
5428 }
5429 return workspaceName(p.Root)
5430 }
5431
5432 func normalizeProjectColor(color string) string {
5433 switch strings.TrimSpace(strings.ToLower(color)) {
5434 case "red", "orange", "amber", "green", "teal", "blue", "purple", "pink":
5435 return strings.TrimSpace(strings.ToLower(color))
5436 default:
5437 return ""
5438 }
5439 }
5440
5441 func projectColor(root string) string {
5442 root = normalizeProjectRoot(root)
5443 if root == "" {
5444 return globalProjectColor()
5445 }
5446 for _, p := range loadProjectsFile().Projects {
5447 if sameProjectRoot(p.Root, root) {
5448 return normalizeProjectColor(p.Color)
5449 }
5450 }
5451 return ""
5452 }
5453
5454 func globalProjectColor() string {
5455 return normalizeProjectColor(loadProjectsFile().GlobalColor)
5456 }
5457
5458 func globalProjectTitle() string {
5459 if title := strings.TrimSpace(loadProjectsFile().GlobalTitle); title != "" {
5460 return title
5461 }
5462 return "Global"
5463 }
5464
5465 func addProject(root, title string) error {
5466 root = normalizeProjectRoot(root)
5467 if root == "" {
5468 return fmt.Errorf("project root is required")
5469 }
5470 title = strings.TrimSpace(title)
5471 return updateProjectsFile(func(f *desktopProjectFile) (bool, error) {
5472 for i, p := range f.Projects {
5473 if sameProjectRoot(p.Root, root) {
5474 changed := false
5475 if f.Projects[i].Root != root {
5476 f.Projects[i].Root = root
5477 changed = true
5478 }
5479 if title != "" && f.Projects[i].Title != title {
5480 f.Projects[i].Title = title
5481 changed = true
5482 }
5483 if !changed {
5484 return false, nil
5485 }
5486 return true, nil
5487 }
5488 }
5489 f.Projects = append(f.Projects, desktopProject{Root: root, Title: title})
5490 return true, nil
5491 })
5492 }
5493
5494 func renameProject(root, title string) error {
5495 title = strings.TrimSpace(title)
5496 root = normalizeProjectRoot(root)
5497 return updateProjectsFile(func(f *desktopProjectFile) (bool, error) {
5498 if root == "" {
5499 if f.GlobalTitle == title {
5500 return false, nil
5501 }
5502 f.GlobalTitle = title
5503 return true, nil
5504 }
5505 for i, p := range f.Projects {
5506 if sameProjectRoot(p.Root, root) {
5507 if f.Projects[i].Root == root && f.Projects[i].Title == title {
5508 return false, nil
5509 }
5510 f.Projects[i].Root = root
5511 f.Projects[i].Title = title
5512 return true, nil
5513 }
5514 }
5515 f.Projects = append(f.Projects, desktopProject{Root: root, Title: title})
5516 return true, nil
5517 })
5518 }
5519
5520 func setProjectColor(root, color string) error {
5521 root = normalizeProjectRoot(root)
5522 color = normalizeProjectColor(color)
5523 return updateProjectsFile(func(f *desktopProjectFile) (bool, error) {
5524 if root == "" {
5525 if f.GlobalColor == color {
5526 return false, nil
5527 }
5528 f.GlobalColor = color
5529 return true, nil
5530 }
5531 for i, p := range f.Projects {
5532 if sameProjectRoot(p.Root, root) {
5533 if f.Projects[i].Root == root && f.Projects[i].Color == color {
5534 return false, nil
5535 }
5536 f.Projects[i].Root = root
5537 f.Projects[i].Color = color
5538 return true, nil
5539 }
5540 }
5541 f.Projects = append(f.Projects, desktopProject{Root: root, Color: color})
5542 return true, nil
5543 })
5544 }
5545
5546 func removeProject(root string) error {
5547 root = normalizeProjectRoot(root)
5548 return updateProjectsFile(func(f *desktopProjectFile) (bool, error) {
5549 projects := make([]desktopProject, 0, len(f.Projects))
5550 for _, p := range f.Projects {
5551 if !sameProjectRoot(p.Root, root) {
5552 projects = append(projects, p)
5553 }
5554 }
5555 if len(projects) == len(f.Projects) {
5556 return false, nil
5557 }
5558 f.Projects = projects
5559 return true, nil
5560 })
5561 }
5562
5563 // topic helpers
5564
5565 const (
5566 topicTitlesFile = "desktop-topic-titles.json"
5567 topicTitleSourcesFile = "desktop-topic-title-sources.json"
5568 topicCreatedAtsFile = "desktop-topic-created-at.json"
5569 topicAutoTitlesFile = "desktop-topic-auto-title-meta.json"
5570 defaultTopicTitle = "新的会话"
5571 defaultTopicTitleEn = "New session"
5572 defaultTopicTitleZhTW = "新的會話"
5573 topicTitleSourceAuto = "auto"
5574 topicTitleSourceManual = "manual"
5575 )
5576
5577 const (
5578 desktopLocaleUnknown int32 = iota
5579 desktopLocaleEn
5580 desktopLocaleZh
5581 desktopLocaleZhTW
5582 )
5583
5584 func (a *App) setDesktopLocale(locale string) {
5585 normalized := strings.ToLower(strings.TrimSpace(locale))
5586 switch {
5587 case strings.HasPrefix(normalized, "zh-tw"), strings.HasPrefix(normalized, "zh-hant"):
5588 a.desktopLocale.Store(desktopLocaleZhTW)
5589 case strings.HasPrefix(normalized, "zh"):
5590 a.desktopLocale.Store(desktopLocaleZh)
5591 default:
5592 a.desktopLocale.Store(desktopLocaleEn)
5593 }
5594 }
5595
5596 func (a *App) localizedDefaultTopicTitle() string {
5597 switch a.desktopLocale.Load() {
5598 case desktopLocaleZh:
5599 return defaultTopicTitle
5600 case desktopLocaleZhTW:
5601 return defaultTopicTitleZhTW
5602 case desktopLocaleEn:
5603 return defaultTopicTitleEn
5604 default:
5605 return defaultTopicTitle
5606 }
5607 }
5608
5609 func isDefaultTopicTitle(title string) bool {
5610 switch strings.TrimSpace(title) {
5611 case "", defaultTopicTitle, defaultTopicTitleEn, defaultTopicTitleZhTW,
5612 "新建会话", "新建會話", "新会话":
5613 return true
5614 default:
5615 return false
5616 }
5617 }
5618
5619 func (a *App) localizedTopicTitle(title, source string) string {
5620 if strings.TrimSpace(source) == topicTitleSourceAuto && isDefaultTopicTitle(title) {
5621 return a.localizedDefaultTopicTitle()
5622 }
5623 return title
5624 }
5625
5626 const topicFileReadTimeout = 200 * time.Millisecond
5627
5628 var readFileWithTimeoutSlots = make(chan struct{}, 16)
5629
5630 func readFileWithTimeout(path string, timeout time.Duration) ([]byte, error) {
5631 if timeout <= 0 {
5632 return readFileUTF8(path)
5633 }
5634 select {
5635 case readFileWithTimeoutSlots <- struct{}{}:
5636 default:
5637 return nil, fmt.Errorf("too many pending file reads")
5638 }
5639 type result struct {
5640 data []byte
5641 err error
5642 }
5643 ch := make(chan result, 1)
5644 go func() {
5645 data, err := readFileUTF8(path)
5646 <-readFileWithTimeoutSlots
5647 ch <- result{data: data, err: err}
5648 }()
5649 timer := time.NewTimer(timeout)
5650 defer timer.Stop()
5651 select {
5652 case r := <-ch:
5653 return r.data, r.err
5654 case <-timer.C:
5655 return nil, fmt.Errorf("timed out after %v reading %s", timeout, filepath.Base(path))
5656 }
5657 }
5658
5659 type topicAutoTitleMeta struct {
5660 Stage int `json:"stage,omitempty"`
5661 UserTurns int `json:"userTurns,omitempty"`
5662 BasisHash string `json:"basisHash,omitempty"`
5663 UpdatedAt int64 `json:"updatedAt,omitempty"`
5664 }
5665
5666 func loadStringMapForUpdate(path string) (map[string]string, error) {
5667 m := map[string]string{}
5668 b, err := readFileUTF8(path)
5669 if err != nil {
5670 if errors.Is(err, os.ErrNotExist) {
5671 return m, nil
5672 }
5673 return nil, err
5674 }
5675 if err := json.Unmarshal(b, &m); err != nil || m == nil {
5676 return map[string]string{}, nil
5677 }
5678 return m, nil
5679 }
5680
5681 func loadTopicTitlesForUpdate(workspaceRoot string) (map[string]string, error) {
5682 snapshot, err := desktopTopicState.snapshot(workspaceRoot)
5683 if err != nil {
5684 if !legacyTopicFilesExist(workspaceRoot) {
5685 return nil, err
5686 }
5687 legacy, legacyErr := loadLegacyStringMap(topicTitlesPath(workspaceRoot))
5688 if legacyErr != nil {
5689 return nil, errors.Join(err, legacyErr)
5690 }
5691 return legacy, nil
5692 }
5693 values := make(map[string]string, len(snapshot.Records))
5694 for id, record := range snapshot.Records {
5695 if record.Title != "" {
5696 values[id] = agent.UserPreviewText(record.Title)
5697 }
5698 }
5699 return values, nil
5700 }
5701
5702 func loadTopicTitleSourcesForUpdate(workspaceRoot string) (map[string]string, error) {
5703 snapshot, err := desktopTopicState.snapshot(workspaceRoot)
5704 if err != nil {
5705 if !legacyTopicFilesExist(workspaceRoot) {
5706 return nil, err
5707 }
5708 legacy, legacyErr := loadLegacyStringMap(topicTitleSourcesPath(workspaceRoot))
5709 if legacyErr != nil {
5710 return nil, errors.Join(err, legacyErr)
5711 }
5712 return legacy, nil
5713 }
5714 values := make(map[string]string, len(snapshot.Records))
5715 for id, record := range snapshot.Records {
5716 if record.TitleSource != "" {
5717 values[id] = record.TitleSource
5718 }
5719 }
5720 return values, nil
5721 }
5722
5723 func saveTopicTitles(workspaceRoot string, m map[string]string) error {
5724 return desktopTopicState.replaceTitles(workspaceRoot, m)
5725 }
5726
5727 func saveTopicTitleSources(workspaceRoot string, m map[string]string) error {
5728 return desktopTopicState.replaceSources(workspaceRoot, m)
5729 }
5730
5731 func saveTopicCreatedAts(workspaceRoot string, m map[string]int64) error {
5732 return desktopTopicState.replaceCreatedAts(workspaceRoot, m)
5733 }
5734
5735 func loadTopicTitle(workspaceRoot, topicID string) string {
5736 return loadTopicTitles(workspaceRoot)[topicID]
5737 }
5738
5739 func loadTopicTitleSource(workspaceRoot, topicID string) string {
5740 return loadTopicTitleSources(workspaceRoot)[topicID]
5741 }
5742
5743 func loadTopicCreatedAt(workspaceRoot, topicID string) int64 {
5744 return loadTopicCreatedAts(workspaceRoot)[topicID]
5745 }
5746
5747 func topicIDCreatedAt(topicID string) int64 {
5748 topicID = strings.TrimSpace(topicID)
5749 for _, prefix := range []string{"topic_", "legacy_"} {
5750 if !strings.HasPrefix(topicID, prefix) {
5751 continue
5752 }
5753 stamp := strings.TrimPrefix(topicID, prefix)
5754 if len(stamp) < len("20060102-150405") {
5755 continue
5756 }
5757 stamp = stamp[:len("20060102-150405")]
5758 t, err := time.ParseInLocation("20060102-150405", stamp, time.UTC)
5759 if err != nil {
5760 continue
5761 }
5762 return t.UnixMilli()
5763 }
5764 return 0
5765 }
5766
5767 func topicCreatedAtForTree(createdAts map[string]int64, topicID string) int64 {
5768 if createdAt := createdAts[topicID]; createdAt > 0 {
5769 return createdAt
5770 }
5771 return topicIDCreatedAt(topicID)
5772 }
5773
5774 func topicTitleForTab(scope, workspaceRoot, topicID string) string {
5775 titleRoot := topicTitleRoot(scope, workspaceRoot)
5776 if title := strings.TrimSpace(loadTopicTitle(titleRoot, topicID)); title != "" {
5777 return title
5778 }
5779 if scope == "global" {
5780 return "Global"
5781 }
5782 return defaultTopicTitle
5783 }
5784
5785 func topicTitleRoot(scope, workspaceRoot string) string {
5786 if scope == "global" {
5787 return ""
5788 }
5789 return workspaceRoot
5790 }
5791
5792 func (a *App) forkTopicTitle(title string) string {
5793 base := strings.TrimSpace(title)
5794 if base == "" || isDefaultTopicTitle(base) {
5795 switch a.desktopLocale.Load() {
5796 case desktopLocaleEn:
5797 base = defaultTopicTitleEn
5798 case desktopLocaleZhTW:
5799 base = defaultTopicTitleZhTW
5800 default:
5801 base = defaultTopicTitle
5802 }
5803 }
5804 return sessiontitle.IncreaseFork(base)
5805 }
5806
5807 type sessionRecoveryEvent struct {
5808 ConversationID string `json:"conversationId,omitempty"`
5809 ActiveVersionID string `json:"activeVersionId,omitempty"`
5810 RecoveryVersionID string `json:"recoveryVersionId,omitempty"`
5811 OriginalPath string `json:"originalPath,omitempty"`
5812 RecoveryPath string `json:"recoveryPath"`
5813 Scope string `json:"scope,omitempty"`
5814 WorkspaceRoot string `json:"workspaceRoot,omitempty"`
5815 TopicID string `json:"topicId,omitempty"`
5816 TopicTitle string `json:"topicTitle,omitempty"`
5817 RecoveryReason string `json:"recoveryReason,omitempty"`
5818 RecoveryDigest string `json:"recoveryDigest,omitempty"`
5819 RecoveryParentID string `json:"recoveryParentId,omitempty"`
5820 Existing bool `json:"existing,omitempty"`
5821 BaseRevision int64 `json:"baseRevision,omitempty"`
5822 DiskRevision int64 `json:"diskRevision,omitempty"`
5823 CanContinue bool `json:"canContinue"`
5824 RequiresChoice bool `json:"requiresChoice"`
5825 }
5826
5827 type sessionRecoveryFailedEvent struct {
5828 Reason string `json:"reason,omitempty"`
5829 ConversationID string `json:"conversationId,omitempty"`
5830 TopicID string `json:"topicId,omitempty"`
5831 RecoveryPath string `json:"recoveryPath,omitempty"`
5832 WorkspaceRoot string `json:"workspaceRoot,omitempty"`
5833 CanContinue bool `json:"canContinue"`
5834 RecoveryPending bool `json:"recoveryPending"`
5835 }
5836
5837 func (a *App) tabSessionRecoveryMeta(tab *WorkspaceTab) func(control.SessionRecoveryRequest) agent.BranchMeta {
5838 return func(req control.SessionRecoveryRequest) agent.BranchMeta {
5839 if tab == nil {
5840 return agent.BranchMeta{Name: agent.RecoveryBranchDefaultName}
5841 }
5842 // This runs on the snapshot-recovery path, which can fire from the
5843 // controller's autosave goroutine; snapshot the tab fields under a.mu so
5844 // we don't read them mid-mutation. Recovery callbacks never hold a.mu, so
5845 // taking it here can't deadlock. Controller reads happen off-lock.
5846 a.mu.RLock()
5847 ctrl := tab.Ctrl
5848 scope := strings.TrimSpace(tab.Scope)
5849 workspaceRoot := strings.TrimSpace(tab.WorkspaceRoot)
5850 topicID := tab.TopicID
5851 topicTitle := tab.TopicTitle
5852 model := strings.TrimSpace(tab.model)
5853 tokenMode := boot.TokenModeFull // deprecated dual-write compat value
5854 qualityFloor := strings.TrimSpace(tab.qualityFloor)
5855 mode := normalizeTabMode(tab.mode)
5856 toolApprovalMode := normalizeToolApprovalMode(tab.toolApprovalMode)
5857 goal := strings.TrimSpace(tab.goal)
5858 a.mu.RUnlock()
5859 if ctrl != nil {
5860 mode = tabModeFromAxes(ctrl.PlanMode(), ctrl.AutoApproveTools())
5861 toolApprovalMode = normalizeToolApprovalMode(ctrl.ToolApprovalMode())
5862 if g := strings.TrimSpace(ctrl.Goal()); g != "" && ctrl.GoalStatus() == control.GoalStatusRunning {
5863 goal = g
5864 } else {
5865 goal = ""
5866 }
5867 }
5868 if scope != "project" {
5869 scope = "global"
5870 }
5871 if scope == "global" {
5872 workspaceRoot = ""
5873 }
5874 return agent.BranchMeta{
5875 Name: agent.RecoveryBranchDefaultName,
5876 Scope: scope,
5877 WorkspaceRoot: workspaceRoot,
5878 TopicID: topicID,
5879 TopicTitle: topicTitle,
5880 Model: model,
5881 AgentPreset: currentTabAgentPreset(&WorkspaceTab{qualityFloor: qualityFloor}),
5882 QualityFloor: control.QualityFloorStandard,
5883 TokenMode: tokenMode,
5884 Mode: persistedTabMode(mode),
5885 ToolApprovalMode: persistedToolApprovalMode(toolApprovalMode),
5886 Goal: goal,
5887 }
5888 }
5889 }
5890
5891 // emitSessionRecoveredAndRefresh registers the frontend pending item before a
5892 // catalog reconcile can publish the revision that classifies it.
5893 func (a *App) emitSessionRecoveredAndRefresh(dir string, recovered sessionRecoveryEvent) {
5894 a.emitRuntimeEvent("session:recovered", recovered)
5895 a.emitProjectTreeChangedForSessionDirs(dir)
5896 }
5897
5898 func setTopicTitle(workspaceRoot, topicID, title string) error {
5899 return setTopicTitleWithSource(workspaceRoot, topicID, title, topicTitleSourceManual)
5900 }
5901
5902 func setTopicTitleWithSource(workspaceRoot, topicID, title, source string) error {
5903 return desktopTopicState.setTitle(workspaceRoot, topicID, title, source)
5904 }
5905
5906 func createTopicState(workspaceRoot, topicID, title, source string, createdAt int64) error {
5907 return desktopTopicState.createTopic(workspaceRoot, topicID, title, source, createdAt)
5908 }
5909
5910 func recordTopicAutoTitleMeta(workspaceRoot, topicID string, proposal autoTopicTitleProposal) error {
5911 topicID = strings.TrimSpace(topicID)
5912 if topicID == "" || proposal.Stage <= 0 || proposal.BasisHash == "" {
5913 return nil
5914 }
5915 value := topicAutoTitleMeta{
5916 Stage: proposal.Stage,
5917 UserTurns: proposal.UserTurns,
5918 BasisHash: proposal.BasisHash,
5919 UpdatedAt: time.Now().UnixMilli(),
5920 }
5921 return desktopTopicState.setAutoMeta(workspaceRoot, topicID, &value)
5922 }
5923
5924 func applyAutoTopicTitle(workspaceRoot, topicID, title string, proposal autoTopicTitleProposal) (bool, error) {
5925 topicID = strings.TrimSpace(topicID)
5926 if topicID == "" || proposal.Stage <= 0 || proposal.BasisHash == "" {
5927 return false, nil
5928 }
5929 return desktopTopicState.applyAutoTitle(workspaceRoot, topicID, title, topicAutoTitleMeta{
5930 Stage: proposal.Stage, UserTurns: proposal.UserTurns,
5931 BasisHash: proposal.BasisHash, UpdatedAt: time.Now().UnixMilli(),
5932 })
5933 }
5934
5935 func deleteTopicAutoTitleMeta(workspaceRoot, topicID string) error {
5936 topicID = strings.TrimSpace(topicID)
5937 if topicID == "" {
5938 return nil
5939 }
5940 return desktopTopicState.setAutoMeta(workspaceRoot, topicID, nil)
5941 }
5942
5943 func setTopicCreatedAt(workspaceRoot, topicID string, createdAt int64) error {
5944 return desktopTopicState.setCreatedAt(workspaceRoot, topicID, createdAt)
5945 }
5946
5947 func deleteTopicState(workspaceRoot, topicID string) error {
5948 return desktopTopicState.delete(workspaceRoot, topicID)
5949 }
5950
5951 // topicIndexMu serializes recovery writes to desktop-projects.json and topic
5952 // title indexes. Startup builds restored tabs concurrently, and each tab may
5953 // repair its missing index.
5954 var topicIndexMu sync.Mutex
5955
5956 // topicAutoTitleCommittedHookForTest pauses between the authoritative auto
5957 // title commit and its in-memory/session publication. Production leaves it nil.
5958 var topicAutoTitleCommittedHookForTest func()
5959
5960 func ensureTopicIndexed(scope, workspaceRoot, topicID, title, source string) error {
5961 return ensureTopicIndexedState(scope, workspaceRoot, topicID, title, source, 0)
5962 }
5963
5964 func ensureTopicIndexedWithCreatedAt(scope, workspaceRoot, topicID, title, source string, createdAt int64) error {
5965 return ensureTopicIndexedState(scope, workspaceRoot, topicID, title, source, createdAt)
5966 }
5967
5968 func ensureTopicIndexedState(scope, workspaceRoot, topicID, title, source string, createdAt int64) error {
5969 topicID = strings.TrimSpace(topicID)
5970 if topicID == "" {
5971 return fmt.Errorf("topicID is required")
5972 }
5973 topicIndexMu.Lock()
5974 defer topicIndexMu.Unlock()
5975 if strings.TrimSpace(scope) == "global" {
5976 workspaceRoot = ""
5977 } else {
5978 workspaceRoot = normalizeProjectRoot(workspaceRoot)
5979 }
5980 title = strings.TrimSpace(title)
5981 if title == "" {
5982 title = defaultTopicTitle
5983 }
5984 source = strings.TrimSpace(source)
5985 if source == "" {
5986 source = topicTitleSourceManual
5987 }
5988 wasDeleted := containsDesktopString(loadProjectsFile().DeletedTopics, topicID)
5989 if wasDeleted {
5990 // A migrated scope prunes tombstoned SQLite rows before mirroring. Clear
5991 // the tombstone first for an explicit restore; if the authoritative state
5992 // write then fails, restore the tombstone so the topic cannot be half shown.
5993 if err := prependTopicInProjectsFile(workspaceRoot, topicID, true); err != nil {
5994 return err
5995 }
5996 }
5997 var err error
5998 if createdAt > 0 {
5999 err = createTopicState(workspaceRoot, topicID, title, source, createdAt)
6000 } else {
6001 err = setTopicTitleWithSource(workspaceRoot, topicID, title, source)
6002 }
6003 if err != nil {
6004 if wasDeleted {
6005 if rollbackErr := removeTopicFromProjectsFile(topicID); rollbackErr != nil {
6006 return errors.Join(err, fmt.Errorf("restore topic tombstone: %w", rollbackErr))
6007 }
6008 }
6009 return err
6010 }
6011 if wasDeleted {
6012 return nil
6013 }
6014 return prependTopicInProjectsFile(workspaceRoot, topicID, true)
6015 }
6016
6017 // telemetry
6018
6019 func saveTelemetry(path string, snapshot tabTelemetrySnapshot) error {
6020 if snapshot.Version == 0 {
6021 snapshot.Version = 3
6022 }
6023 if snapshot.ReadFiles == nil {
6024 snapshot.ReadFiles = []readFileRecord{}
6025 }
6026 b, err := json.MarshalIndent(snapshot, "", " ")
6027 if err != nil {
6028 return err
6029 }
6030 tmp := path + ".tmp"
6031 if err := os.WriteFile(tmp, b, 0o644); err != nil {
6032 return err
6033 }
6034 return fileutil.ReplaceFile(tmp, path)
6035 }
6036
6037 func loadTelemetry(path string) tabTelemetrySnapshot {
6038 b, err := readFileUTF8(path)
6039 if err != nil {
6040 return tabTelemetrySnapshot{Version: 3, ReadFiles: []readFileRecord{}}
6041 }
6042 var snapshot tabTelemetrySnapshot
6043 if err := json.Unmarshal(b, &snapshot); err == nil && (snapshot.Version > 0 || snapshot.ReadFiles != nil) {
6044 if snapshot.ReadFiles == nil {
6045 snapshot.ReadFiles = []readFileRecord{}
6046 }
6047 if snapshot.Usage.SessionCost == 0 && snapshot.Usage.SessionCostUsd > 0 {
6048 snapshot.Usage.SessionCost = snapshot.Usage.SessionCostUsd
6049 }
6050 // Lazy-migrate pre-CostQuote telemetry: keep original amount, mark legacy.
6051 // Never reconstruct wiped mixed-currency zeros from current price tables.
6052 if snapshot.Version < 3 && snapshot.Usage.CostLedger == nil && snapshot.Usage.SessionCost > 0 {
6053 q := billing.MigrateLegacyUsage(billing.LegacyUsageRecord{
6054 SessionCost: snapshot.Usage.SessionCost,
6055 SessionCurrency: snapshot.Usage.SessionCurrency,
6056 EndedAt: time.Now().UTC(),
6057 })
6058 ledger := billing.NewLedger()
6059 ledger.Add(q, billing.UsageTokens{
6060 PromptTokens: snapshot.Usage.PromptTokens,
6061 CompletionTokens: snapshot.Usage.CompletionTokens,
6062 }, time.Now().UTC())
6063 snapshot.Usage.CostLedger = ledger
6064 total := ledger.Total(billing.NormalizeCurrency(snapshot.Usage.SessionCurrency))
6065 snapshot.Usage.SessionCostQuote = &total
6066 snapshot.Usage.SessionCostComplete = total.Complete
6067 snapshot.Version = 3
6068 } else if snapshot.Version < 3 && snapshot.Usage.SessionCost <= 0 && strings.TrimSpace(snapshot.Usage.SessionCurrency) != "" {
6069 // Explicit zero with currency: prior mixed-currency wipe — mark incomplete.
6070 q := billing.MigrateLegacyUsage(billing.LegacyUsageRecord{
6071 SessionCost: 0,
6072 SessionCurrency: snapshot.Usage.SessionCurrency,
6073 })
6074 snapshot.Usage.SessionCostQuote = &q
6075 snapshot.Usage.SessionCostComplete = false
6076 snapshot.Version = 3
6077 } else if snapshot.Version < 3 {
6078 snapshot.Version = 3
6079 }
6080 return snapshot
6081 }
6082 var records []readFileRecord
6083 if err := json.Unmarshal(b, &records); err != nil || records == nil {
6084 records = []readFileRecord{}
6085 }
6086 return tabTelemetrySnapshot{Version: 1, ReadFiles: records}
6087 }
6088
6089 // project tree
6090
6091 func normalizeTopicStatus(status string) string {
6092 switch status {
6093 case topicStatusThinking, topicStatusStreaming, topicStatusWaitingConfirmation, topicStatusBackgroundJob, topicStatusPaused, topicStatusAwaitingDelivery, topicStatusError, topicStatusDivergedRecovery:
6094 return status
6095 default:
6096 return ""
6097 }
6098 }
6099
6100 func legacySessionMetaMatchesMigrationTarget(meta agent.BranchMeta, scope, workspaceRoot string) bool {
6101 if strings.TrimSpace(meta.TopicID) != "" {
6102 return false
6103 }
6104 return legacySessionScopeMatchesMigrationTarget(meta, scope, workspaceRoot)
6105 }
6106
6107 func legacySessionScopeMatchesMigrationTarget(meta agent.BranchMeta, scope, workspaceRoot string) bool {
6108 metaScope := strings.TrimSpace(meta.Scope)
6109 if metaScope != "" && metaScope != scope {
6110 return false
6111 }
6112 metaRoot := normalizeProjectRoot(meta.WorkspaceRoot)
6113 if scope == "project" {
6114 return metaRoot == "" || sameProjectRoot(workspaceRoot, metaRoot)
6115 }
6116 return metaRoot == "" || sameProjectRoot(globalWorkspaceRoot(), metaRoot)
6117 }
6118
6119 func restoreSessionTopicIndex(dir, sessionPath string) error {
6120 sessionPath = strings.TrimSpace(sessionPath)
6121 if sessionPath == "" {
6122 return nil
6123 }
6124 meta, ok, err := agent.LoadBranchMeta(sessionPath)
6125 if err != nil {
6126 return err
6127 }
6128 if !ok || strings.TrimSpace(meta.TopicID) == "" {
6129 // The migration pass takes per-session meta locks itself, so it must
6130 // run outside the lock taken below.
6131 migrateLegacySessionsIntoGlobalTopics(dir)
6132 return nil
6133 }
6134
6135 // Read-modify-write on the branch-meta sidecar: re-read and save under the
6136 // per-path meta lock so a concurrent save's revision bump can't land in
6137 // between and get rolled back by the write at the end.
6138 unlock, err := agent.LockSessionMetaPath(sessionPath)
6139 if err != nil {
6140 return err
6141 }
6142 defer unlock()
6143 meta, ok, err = agent.LoadBranchMeta(sessionPath)
6144 if err != nil {
6145 return err
6146 }
6147 if !ok || strings.TrimSpace(meta.TopicID) == "" {
6148 return nil
6149 }
6150
6151 topicID := strings.TrimSpace(meta.TopicID)
6152 scope := strings.TrimSpace(meta.Scope)
6153 workspaceRoot := strings.TrimSpace(meta.WorkspaceRoot)
6154 if scope != "global" && scope != "project" {
6155 if workspaceRoot == "" {
6156 scope = "global"
6157 } else {
6158 scope = "project"
6159 }
6160 }
6161 if scope == "global" {
6162 workspaceRoot = ""
6163 } else {
6164 workspaceRoot = normalizeProjectRoot(workspaceRoot)
6165 if workspaceRoot == "" {
6166 scope = "global"
6167 }
6168 }
6169
6170 title := restoredSessionTopicTitle(dir, sessionPath, meta)
6171 if title == "" {
6172 title = defaultTopicTitle
6173 }
6174 if err := ensureTopicIndexed(scope, workspaceRoot, topicID, title, topicTitleSourceManual); err != nil {
6175 return err
6176 }
6177
6178 if scope == "global" {
6179 meta.Scope = "global"
6180 meta.WorkspaceRoot = ""
6181 } else {
6182 meta.Scope = "project"
6183 meta.WorkspaceRoot = workspaceRoot
6184 }
6185 meta.TopicID = topicID
6186 meta.TopicTitle = title
6187 if err := agent.SaveBranchMetaPreserveUpdatedLocked(sessionPath, meta); err != nil {
6188 return err
6189 }
6190 invalidateTopicSessionIndexForPath(sessionPath)
6191 return nil
6192 }
6193
6194 func restoredSessionTopicTitle(dir, sessionPath string, meta agent.BranchMeta) string {
6195 if title := storedSessionTopicTitle(dir, sessionPath, meta); title != "" {
6196 return title
6197 }
6198 if s, err := agent.LoadSession(sessionPath); err == nil {
6199 for _, msg := range s.Messages {
6200 if agent.IsUserAuthoredTurnMessage(msg) {
6201 if title := topicTitleFromText(agent.UserMessageText(msg)); title != "" {
6202 return title
6203 }
6204 }
6205 }
6206 }
6207 return ""
6208 }
6209
6210 func storedSessionTopicTitle(dir, sessionPath string, meta agent.BranchMeta) string {
6211 if title := topicTitleFromText(meta.TopicTitle); title != "" {
6212 return title
6213 }
6214 return topicTitleFromText(loadSessionTitles(dir)[filepath.Base(sessionPath)])
6215 }
6216
6217 func legacySessionTopicID(path string) string {
6218 return agent.LegacySessionTopicID(path)
6219 }
6220
6221 // TopicMeta describes a topic for the project tree.
6222 type TopicMeta struct {
6223 ID string `json:"id"`
6224 Title string `json:"title"`
6225 CreatedAt int64 `json:"createdAt"`
6226 }
6227
6228 // CreateTopic creates a new topic under a project workspace and returns its metadata.
6229 func (a *App) CreateTopic(scope, workspaceRoot, title string) (TopicMeta, error) {
6230 trimmedTitle := strings.TrimSpace(title)
6231 titleSource := topicTitleSourceManual
6232 if trimmedTitle == "" {
6233 trimmedTitle = defaultTopicTitle
6234 titleSource = topicTitleSourceAuto
6235 }
6236 topicID := newTopicID()
6237 createdAt := time.Now().UnixMilli()
6238 if scope == "global" {
6239 workspaceRoot = ""
6240 }
6241 if workspaceRoot != "" {
6242 if abs, err := filepath.Abs(workspaceRoot); err == nil {
6243 workspaceRoot = abs
6244 }
6245 }
6246 releaseAdmission, err := a.beginProjectRuntimeAdmission(scope, workspaceRoot)
6247 if err != nil {
6248 return TopicMeta{}, err
6249 }
6250 defer releaseAdmission()
6251 if err := createTopicState(workspaceRoot, topicID, trimmedTitle, titleSource, createdAt); err != nil {
6252 return TopicMeta{}, err
6253 }
6254 // New topics should appear first in their project/global group so the item
6255 // just created is immediately visible and selected in the sidebar.
6256 _ = prependTopicInProjectsFile(workspaceRoot, topicID, workspaceRoot != "")
6257 a.emitProjectTreeMetadataChanged()
6258 return TopicMeta{ID: topicID, Title: a.localizedTopicTitle(trimmedTitle, titleSource), CreatedAt: createdAt}, nil
6259 }
6260
6261 // RenameProject updates the sidebar-only display title for a project folder.
6262 // Empty title clears the override and falls back to the folder name.
6263 func (a *App) RenameProject(workspaceRoot, title string) error {
6264 if err := renameProject(workspaceRoot, title); err != nil {
6265 return err
6266 }
6267 a.syncTabWorkspaceRootSpellings()
6268 a.emitProjectTreeMetadataChanged()
6269 return nil
6270 }
6271
6272 // SetProjectColor updates the project-level accent color used by project topics
6273 // in the sidebar and tabs. Empty color restores the default accent.
6274 func (a *App) SetProjectColor(workspaceRoot, color string) error {
6275 if err := setProjectColor(workspaceRoot, color); err != nil {
6276 return err
6277 }
6278 a.syncTabWorkspaceRootSpellings()
6279 a.emitProjectTreeMetadataChanged()
6280 return nil
6281 }
6282
6283 // SetProjectPinned controls whether a project folder is pinned above the rest of
6284 // the desktop project tree.
6285 func (a *App) SetProjectPinned(workspaceRoot string, pinned bool) error {
6286 root := normalizeProjectRoot(workspaceRoot)
6287 if root == "" {
6288 return fmt.Errorf("workspaceRoot is required")
6289 }
6290 if err := updateProjectsFile(func(f *desktopProjectFile) (bool, error) {
6291 i := projectIndexByRoot(f.Projects, root)
6292 if i < 0 {
6293 return false, fmt.Errorf("project %q not found", root)
6294 }
6295 root = f.Projects[i].Root
6296 next := make([]string, 0, len(f.PinnedProjects))
6297 for _, pinnedRoot := range f.PinnedProjects {
6298 if !sameProjectRoot(pinnedRoot, root) {
6299 next = append(next, pinnedRoot)
6300 }
6301 }
6302 if pinned {
6303 next = prependUniqueString(next, root)
6304 }
6305 if sameStringList(next, f.PinnedProjects) {
6306 return false, nil
6307 }
6308 f.PinnedProjects = next
6309 return true, nil
6310 }); err != nil {
6311 return err
6312 }
6313 a.emitProjectTreeMetadataChanged()
6314 return nil
6315 }
6316
6317 // ReorderProjects persists the user-defined order of project folders and,
6318 // when present, the virtual Global sidebar section.
6319 func (a *App) ReorderProjects(workspaceRoots []string) error {
6320 if err := updateProjectsFile(func(f *desktopProjectFile) (bool, error) {
6321 var seenProjects []string
6322 next := make([]desktopProject, 0, len(workspaceRoots))
6323 sidebarOrder := make([]string, 0, len(workspaceRoots))
6324 hasGlobalOrder := false
6325 for _, root := range workspaceRoots {
6326 root = strings.TrimSpace(root)
6327 if root == desktopGlobalOrderToken {
6328 if hasGlobalOrder {
6329 return false, fmt.Errorf("duplicate global section")
6330 }
6331 hasGlobalOrder = true
6332 sidebarOrder = append(sidebarOrder, root)
6333 continue
6334 }
6335 root = normalizeProjectRoot(root)
6336 i := projectIndexByRoot(f.Projects, root)
6337 if i < 0 {
6338 return false, fmt.Errorf("project %q not found", root)
6339 }
6340 project := f.Projects[i]
6341 if projectRootInList(seenProjects, project.Root) {
6342 return false, fmt.Errorf("duplicate project %q", root)
6343 }
6344 seenProjects = append(seenProjects, project.Root)
6345 next = append(next, project)
6346 sidebarOrder = append(sidebarOrder, project.Root)
6347 }
6348 if len(next) != len(f.Projects) {
6349 return false, fmt.Errorf("project order length mismatch")
6350 }
6351 changed := !sameProjectOrder(next, f.Projects)
6352 f.Projects = next
6353 if hasGlobalOrder {
6354 if !sameStringList(sidebarOrder, f.SidebarOrder) {
6355 changed = true
6356 }
6357 f.SidebarOrder = sidebarOrder
6358 } else {
6359 if len(f.SidebarOrder) > 0 {
6360 changed = true
6361 }
6362 f.SidebarOrder = nil
6363 }
6364 return changed, nil
6365 }); err != nil {
6366 return err
6367 }
6368 a.emitProjectTreeMetadataChanged()
6369 return nil
6370 }
6371
6372 // RenameTopic updates a topic's display title.
6373 func (a *App) RenameTopic(topicID, title string) error {
6374 a.topicTitleMutationMu.Lock()
6375 defer a.topicTitleMutationMu.Unlock()
6376 // Keep candidate protection inside the same mutation fence used by the
6377 // cleanup worker. Otherwise a rename can mark an archive-pending candidate
6378 // as protected while that worker still proceeds to remove its index.
6379 // Same-value manual renames remain durable evidence of use.
6380 a.protectLegacyCleanupTopicMutation(topicID)
6381 if handled, err := a.updateCanonicalTopicPresentation(topicID, &title, nil); handled || err != nil {
6382 return err
6383 }
6384 trimmed := strings.TrimSpace(title)
6385 if trimmed == "" {
6386 trimmed = defaultTopicTitle
6387 }
6388 // Find which workspace this topic belongs to by scanning all project topic titles.
6389 f := loadProjectsFile()
6390 for _, p := range f.Projects {
6391 m := loadTopicTitles(p.Root)
6392 if _, ok := m[topicID]; ok {
6393 if err := setTopicTitle(p.Root, topicID, trimmed); err != nil {
6394 return err
6395 }
6396 a.updateOpenTopicTitle(topicID, trimmed, topicTitleSourceManual)
6397 changedDirs := a.updateTopicSessionTitles(topicID, trimmed)
6398 if len(changedDirs) > 0 {
6399 a.emitProjectTreeChangedForSessionDirs(changedDirs...)
6400 } else {
6401 a.emitProjectTreeMetadataChanged()
6402 }
6403 return nil
6404 }
6405 }
6406 // Check global.
6407 m := loadTopicTitles("")
6408 if _, ok := m[topicID]; ok {
6409 if err := setTopicTitle("", topicID, trimmed); err != nil {
6410 return err
6411 }
6412 a.updateOpenTopicTitle(topicID, trimmed, topicTitleSourceManual)
6413 changedDirs := a.updateTopicSessionTitles(topicID, trimmed)
6414 if len(changedDirs) > 0 {
6415 a.emitProjectTreeChangedForSessionDirs(changedDirs...)
6416 } else {
6417 a.emitProjectTreeMetadataChanged()
6418 }
6419 return nil
6420 }
6421 if scope, workspaceRoot, ok := a.findTopicLocation(topicID); ok {
6422 if err := ensureTopicIndexed(scope, workspaceRoot, topicID, trimmed, topicTitleSourceManual); err != nil {
6423 return err
6424 }
6425 a.updateOpenTopicTitle(topicID, trimmed, topicTitleSourceManual)
6426 changedDirs := a.updateTopicSessionTitles(topicID, trimmed)
6427 if len(changedDirs) > 0 {
6428 a.emitProjectTreeChangedForSessionDirs(changedDirs...)
6429 } else {
6430 a.emitProjectTreeMetadataChanged()
6431 }
6432 return nil
6433 }
6434 // Catalog-only topics (no title map entry, no open tab) persist through
6435 // renameCatalogOnlyTopic instead of failing (#9090).
6436 return a.renameCatalogOnlyTopic(topicID, trimmed)
6437 }
6438
6439 func (a *App) findTopicLocation(topicID string) (string, string, bool) {
6440 topicID = strings.TrimSpace(topicID)
6441 if topicID == "" {
6442 return "", "", false
6443 }
6444 a.mu.RLock()
6445 for _, tab := range a.tabs {
6446 if tab == nil || tab.TopicID != topicID {
6447 continue
6448 }
6449 scope := tab.Scope
6450 workspaceRoot := tab.WorkspaceRoot
6451 a.mu.RUnlock()
6452 if scope == "global" {
6453 return "global", "", true
6454 }
6455 return "project", normalizeProjectRoot(workspaceRoot), true
6456 }
6457 a.mu.RUnlock()
6458
6459 infos, err := agent.ListSessions(config.SessionDir())
6460 if err != nil {
6461 return "", "", false
6462 }
6463 for _, info := range infos {
6464 if strings.TrimSpace(info.TopicID) != topicID {
6465 continue
6466 }
6467 scope := strings.TrimSpace(info.Scope)
6468 if scope == "" {
6469 scope = "global"
6470 }
6471 if scope == "global" {
6472 return "global", "", true
6473 }
6474 return "project", normalizeProjectRoot(info.WorkspaceRoot), true
6475 }
6476 return "", "", false
6477 }
6478
6479 func (a *App) updateOpenTopicTitle(topicID, title, source string) {
6480 if strings.TrimSpace(topicID) == "" || strings.TrimSpace(title) == "" {
6481 return
6482 }
6483 a.mu.Lock()
6484 defer a.mu.Unlock()
6485 for _, tab := range a.runtimeTabsLocked() {
6486 if tab != nil && tab.TopicID == topicID {
6487 tab.TopicTitle = title
6488 tab.topicTitleSource = source
6489 }
6490 }
6491 }
6492
6493 func (a *App) updateTopicSessionTitles(topicID, title string) []string {
6494 if strings.TrimSpace(topicID) == "" || strings.TrimSpace(title) == "" {
6495 return nil
6496 }
6497 var changedDirs []string
6498 for _, dir := range a.knownSessionDirs() {
6499 changed := false
6500 for _, match := range topicSessionMatches(dir, topicID) {
6501 // Read-modify-write on the branch-meta sidecar: hold the per-path
6502 // meta lock so a concurrent save's revision bump can't land between
6503 // the load and save below and get rolled back by this write.
6504 unlock, lockErr := agent.LockSessionMetaPath(match.path)
6505 if lockErr != nil {
6506 continue
6507 }
6508 meta, ok, err := agent.LoadBranchMeta(match.path)
6509 if err != nil || !ok {
6510 unlock()
6511 continue
6512 }
6513 meta.TopicTitle = title
6514 err = agent.SaveBranchMetaPreserveUpdatedLocked(match.path, meta)
6515 unlock()
6516 if err == nil {
6517 invalidateTopicSessionIndex(dir)
6518 changed = true
6519 }
6520 }
6521 if changed {
6522 changedDirs = append(changedDirs, dir)
6523 }
6524 }
6525 return changedDirs
6526 }
6527
6528 func (a *App) emitProjectTreeChanged() {
6529 a.requestProjectTreeCatalogRefresh()
6530 a.emitProjectTreeChangedEvent()
6531 }
6532
6533 func (a *App) requestProjectTreeCatalogRefresh() {
6534 if a.projectTreeCatalogRefreshHook != nil {
6535 a.projectTreeCatalogRefreshHook()
6536 }
6537 a.requestSessionCatalogMetadataSync()
6538 for _, target := range a.sessionCatalogTargets() {
6539 a.requestSessionCatalogReconcile(target.Path)
6540 }
6541 }
6542
6543 // emitProjectTreeChangedForSessionDirs schedules only the affected catalog
6544 // directories. It never scans synchronously on the mutation or UI goroutine.
6545 func (a *App) emitProjectTreeChangedForSessionDirs(dirs ...string) {
6546 for _, dir := range dirs {
6547 a.requestSessionCatalogReconcile(dir)
6548 }
6549 a.emitProjectTreeChangedEvent()
6550 }
6551
6552 // emitProjectTreeMetadataChanged refreshes ordering, titles, pins, and runtime
6553 // status without walking session storage.
6554 func (a *App) emitProjectTreeMetadataChanged() {
6555 a.requestSessionCatalogMetadataSync()
6556 a.emitProjectTreeChangedEvent()
6557 }
6558
6559 // SetTopicPinned controls whether a topic is pinned to the top of its project
6560 // or Global section in the desktop project tree.
6561 func (a *App) SetTopicPinned(topicID string, pinned bool) error {
6562 if handled, err := a.updateCanonicalTopicPresentation(topicID, nil, &pinned); handled || err != nil {
6563 return err
6564 }
6565 topicID = strings.TrimSpace(topicID)
6566 if topicID == "" {
6567 return fmt.Errorf("topicID is required")
6568 }
6569 if err := updateProjectsFile(func(f *desktopProjectFile) (bool, error) {
6570 for i, p := range f.Projects {
6571 m := loadTopicTitles(p.Root)
6572 if _, ok := m[topicID]; !ok && !containsDesktopString(p.Topics, topicID) {
6573 continue
6574 }
6575 next := removeString(f.Projects[i].PinnedTopics, topicID)
6576 if pinned {
6577 next = prependUniqueString(f.Projects[i].PinnedTopics, topicID)
6578 }
6579 if sameStringList(next, f.Projects[i].PinnedTopics) {
6580 return false, nil
6581 }
6582 f.Projects[i].PinnedTopics = next
6583 return true, nil
6584 }
6585 globalTitles := loadTopicTitles("")
6586 if _, ok := globalTitles[topicID]; !ok && !containsDesktopString(f.GlobalTopics, topicID) {
6587 return false, fmt.Errorf("topic %q not found", topicID)
6588 }
6589 next := removeString(f.GlobalPinnedTopics, topicID)
6590 if pinned {
6591 next = prependUniqueString(f.GlobalPinnedTopics, topicID)
6592 }
6593 if sameStringList(next, f.GlobalPinnedTopics) {
6594 return false, nil
6595 }
6596 f.GlobalPinnedTopics = next
6597 return true, nil
6598 }); err != nil {
6599 return err
6600 }
6601 a.emitProjectTreeMetadataChanged()
6602 return nil
6603 }
6604
6605 // ListProjectTree builds the sidebar tree: project folders each containing
6606 // their topics, plus a Global section.
6607 // topicSummary is used by ListProjectTree and mergeSessionInfos to track
6608 // per-topic turn count and last activity.
6609 type topicSummary struct {
6610 turns int
6611 adoptedRecoveryTurns int
6612 lastActivityAt int64
6613 hasNormalSession bool
6614 hasRecoveryOnly bool
6615 hasAdoptedRecovery bool
6616 }
6617
6618 func (s topicSummary) displayTurns() int {
6619 if s.adoptedRecoveryTurns > s.turns {
6620 return s.adoptedRecoveryTurns
6621 }
6622 return s.turns
6623 }
6624
6625 // runtimeSessionStatus is one open or detached runtime session, as shown in
6626 // the sidebar tree.
6627 type runtimeSessionStatus struct {
6628 open bool
6629 running bool
6630 }
6631
6632 // topicHiddenAsRecoveryOnly keeps the legacy runtime fallback from creating a
6633 // duplicate row for an idle recovery-only topic. The catalog-backed tree now
6634 // supplies one logical row for recovery-only topics, and physical branches
6635 // remain available from History.
6636 func topicHiddenAsRecoveryOnly(summary topicSummary, pinned bool, runtimeSessions []runtimeSessionStatus) bool {
6637 if !summary.hasRecoveryOnly || summary.hasNormalSession || summary.hasAdoptedRecovery || pinned {
6638 return false
6639 }
6640 for _, session := range runtimeSessions {
6641 if session.open || session.running {
6642 return false
6643 }
6644 }
6645 return true
6646 }
6647
6648 func topicSummaryKey(scope, workspaceRoot, topicID string) string {
6649 if scope == "global" {
6650 return "global::" + topicID
6651 }
6652 // Producers key by the live tab's root spelling while the sidebar keys by
6653 // the registry's canonical spelling; fold both so runtime status never
6654 // splits across equivalent roots.
6655 return "project:" + projectRootKey(workspaceRoot) + ":" + topicID
6656 }
6657
6658 func projectSessionNodeKey(scope, sessionPath string) string {
6659 sum := sha256.Sum256([]byte(sessionRuntimeKey(sessionPath)))
6660 return scope + "_session_" + hex.EncodeToString(sum[:8])
6661 }
6662
6663 // ContextPanelInfo is the right-side panel's data for one tab.
6664 type ContextPanelInfo struct {
6665 UsedTokens int `json:"usedTokens"`
6666 WindowTokens int `json:"windowTokens"`
6667 PromptTokens int `json:"promptTokens"`
6668 CompletionTokens int `json:"completionTokens"`
6669 TotalTokens int `json:"totalTokens"`
6670 ReasoningTokens int `json:"reasoningTokens"`
6671 CacheHitTokens int `json:"cacheHitTokens"`
6672 CacheMissTokens int `json:"cacheMissTokens"`
6673 Estimated bool `json:"estimated,omitempty"`
6674 // Session-cumulative token counts (from telemetry, atomic snapshot).
6675 // Separate from the per-turn fields above so existing consumers (status bar
6676 // turn tokens, donut chart) are unaffected.
6677 SessionCacheHitTokens int `json:"sessionCacheHitTokens"`
6678 SessionCacheMissTokens int `json:"sessionCacheMissTokens"`
6679 SessionCompletionTokens int `json:"sessionCompletionTokens"`
6680 SessionEstimated bool `json:"sessionEstimated,omitempty"`
6681 RequestCount int `json:"requestCount"`
6682 ElapsedMs int64 `json:"elapsedMs"` // finished turns only
6683 ActiveTurnStartedAt int64 `json:"activeTurnStartedAt,omitempty"` // unix ms; 0 when idle
6684 SessionCost float64 `json:"sessionCost"`
6685 SessionCurrency string `json:"sessionCurrency,omitempty"`
6686 SessionCostUsd float64 `json:"sessionCostUsd,omitempty"`
6687 SessionCostComplete bool `json:"sessionCostComplete,omitempty"`
6688 SessionCostEstimated bool `json:"sessionCostEstimated,omitempty"`
6689 SessionBillingMode string `json:"sessionBillingMode,omitempty"`
6690 SessionCostQuote *billing.CostQuote `json:"sessionCostQuote,omitempty"`
6691 Sources map[string]usageSourceStats `json:"sources,omitempty"`
6692 Mock bool `json:"mock,omitempty"`
6693 ReadFiles []readFileRecord `json:"readFiles"`
6694 ChangedFiles []ChangedFileInfo `json:"changedFiles"`
6695 ContextBudget *ContextBudgetInfo `json:"contextBudget,omitempty"`
6696 }
6697
6698 type ChangedFileInfo struct {
6699 Path string `json:"path"`
6700 OldPath string `json:"oldPath,omitempty"`
6701 Sources []string `json:"sources"`
6702 GitStatus string `json:"gitStatus,omitempty"`
6703 Turns []int `json:"turns"`
6704 LatestPrompt string `json:"latestPrompt,omitempty"`
6705 LatestTime int64 `json:"latestTime,omitempty"`
6706 }
6707
6708 // ContextPanel returns the context usage, read files, and changed files for a
6709 // specific tab.
6710 func (a *App) ContextPanel(tabID string) ContextPanelInfo {
6711 if a.isRemoteTab(tabID) {
6712 used, window, ok := a.remoteContextSnapshot(tabID)
6713 if ok {
6714 return ContextPanelInfo{UsedTokens: used, WindowTokens: window, ReadFiles: []readFileRecord{}, ChangedFiles: []ChangedFileInfo{}}
6715 }
6716 return ContextPanelInfo{ReadFiles: []readFileRecord{}, ChangedFiles: []ChangedFileInfo{}}
6717 }
6718 read := a.captureContextRead(tabID)
6719 ctrl, telemetry := read.ctrl, read.telemetry
6720 if read.tab == nil {
6721 return ContextPanelInfo{ReadFiles: []readFileRecord{}, ChangedFiles: []ChangedFileInfo{}}
6722 }
6723
6724 info := ContextPanelInfo{ReadFiles: []readFileRecord{}, ChangedFiles: []ChangedFileInfo{}}
6725 if ctrl != nil {
6726 _, window := ctrl.ContextSnapshot()
6727 info.WindowTokens = window
6728 // This panel breaks the last turn down into segments, so its total must
6729 // be that turn's usage and not the live-view measurement the status-bar
6730 // gauge reports — otherwise the segments stop summing to the total.
6731 if u := ctrl.LastUsage(); u != nil {
6732 info.UsedTokens = u.PromptTokens + u.CompletionTokens
6733 }
6734 if info.UsedTokens == 0 {
6735 if snap := telemetry; snap.Usage.LastUsedTokens > 0 {
6736 info.UsedTokens = snap.Usage.LastUsedTokens
6737 }
6738 }
6739 if u := ctrl.LastUsage(); u != nil {
6740 info.PromptTokens = u.PromptTokens
6741 info.CompletionTokens = u.CompletionTokens
6742 info.ReasoningTokens = u.ReasoningTokens
6743 info.CacheHitTokens = u.CacheHitTokens
6744 info.CacheMissTokens = u.CacheMissTokens
6745 info.Estimated = u.Estimated
6746 } else {
6747 // Executor rebuilt (session rebind): fall back to the telemetry-
6748 // persisted per-turn breakdown so the donut chart and type
6749 // breakdown show the last turn's composition instead of "other".
6750 snap := telemetry
6751 info.PromptTokens = snap.Usage.LastPromptTokens
6752 info.CompletionTokens = snap.Usage.LastCompletionTokens
6753 info.ReasoningTokens = snap.Usage.LastReasoningTokens
6754 info.CacheHitTokens = snap.Usage.LastCacheHitTokens
6755 info.CacheMissTokens = snap.Usage.LastCacheMissTokens
6756 info.Estimated = snap.Usage.LastEstimated
6757 }
6758 }
6759
6760 if records := telemetry.ReadFiles; records != nil {
6761 info.ReadFiles = records
6762 }
6763 usage := telemetry.Usage
6764 info.TotalTokens = usage.TotalTokens
6765 info.RequestCount = usage.RequestCount
6766 info.ElapsedMs = read.runtime.completedMs
6767 info.ActiveTurnStartedAt = read.runtime.turnStartedAt
6768 info.SessionCost = usage.SessionCost
6769 info.SessionCurrency = usage.SessionCurrency
6770 info.SessionCostUsd = usage.SessionCostUsd
6771 info.SessionCostComplete = usage.SessionCostComplete
6772 info.SessionCostEstimated = true
6773 info.SessionCostQuote = usage.SessionCostQuote
6774 if usage.SessionCostQuote != nil {
6775 info.SessionBillingMode = usage.SessionCostQuote.BillingMode
6776 info.SessionCostEstimated = usage.SessionCostQuote.Estimated
6777 if !usage.SessionCostQuote.Complete {
6778 info.SessionCostComplete = false
6779 }
6780 }
6781 info.Sources = usage.Sources
6782 info.SessionCacheHitTokens = usage.CacheHitTokens
6783 info.SessionCacheMissTokens = usage.CacheMissTokens
6784 info.SessionCompletionTokens = usage.CompletionTokens
6785 info.SessionEstimated = usage.Estimated
6786 if ctrl != nil {
6787 if snap := ctrl.ContextMaintenanceSnapshot(); snap.ContextBudget != nil {
6788 info.ContextBudget = contextBudgetInfo(snap.ContextBudget)
6789 }
6790 }
6791
6792 // Gather workspace changes for this tab's root.
6793 if ctrl != nil && read.workspaceRoot != "" {
6794 for _, meta := range ctrl.Checkpoints() {
6795 for _, path := range meta.Paths {
6796 info.ChangedFiles = append(info.ChangedFiles, ChangedFileInfo{
6797 Path: path,
6798 Sources: []string{"session"},
6799 Turns: []int{meta.Turn},
6800 LatestPrompt: meta.Prompt,
6801 LatestTime: meta.Time.UnixMilli(),
6802 })
6803 }
6804 }
6805 }
6806
6807 if !read.current(a) {
6808 return ContextPanelInfo{ReadFiles: []readFileRecord{}, ChangedFiles: []ChangedFileInfo{}}
6809 }
6810 return info
6811 }
6812
6813 // utility
6814
6815 func (a *App) newUniqueTabIDLocked() string {
6816 for {
6817 id := newTabID()
6818 if _, exists := a.tabs[id]; !exists {
6819 return id
6820 }
6821 }
6822 }
6823
6824 func (a *App) restoredTabIDLocked(id string) string {
6825 id = strings.TrimSpace(id)
6826 if id == "" {
6827 return a.newUniqueTabIDLocked()
6828 }
6829 if _, exists := a.tabs[id]; exists {
6830 return a.newUniqueTabIDLocked()
6831 }
6832 return id
6833 }
6834
6835 func normalizeTabMode(mode string) string {
6836 switch mode {
6837 case "plan", "yolo", "plan-yolo", "yolo-plan":
6838 if mode == "yolo-plan" {
6839 return "plan-yolo"
6840 }
6841 return mode
6842 default:
6843 return "normal"
6844 }
6845 }
6846
6847 func tabModeFromAxes(plan, autoApproveTools bool) string {
6848 switch {
6849 case plan && autoApproveTools:
6850 return "plan-yolo"
6851 case plan:
6852 return "plan"
6853 case autoApproveTools:
6854 return "yolo"
6855 default:
6856 return "normal"
6857 }
6858 }
6859
6860 func tabModeHasPlan(mode string) bool {
6861 switch normalizeTabMode(mode) {
6862 case "plan", "plan-yolo":
6863 return true
6864 default:
6865 return false
6866 }
6867 }
6868
6869 func tabModeHasAutoApproveTools(mode string) bool {
6870 switch normalizeTabMode(mode) {
6871 case "yolo", "plan-yolo":
6872 return true
6873 default:
6874 return false
6875 }
6876 }
6877
6878 func currentTabMode(tab *WorkspaceTab) string {
6879 if tab == nil {
6880 return "normal"
6881 }
6882 if tab.Ctrl != nil {
6883 return tabModeFromAxes(tab.Ctrl.PlanMode(), tab.Ctrl.AutoApproveTools())
6884 }
6885 return normalizeTabMode(tab.mode)
6886 }
6887
6888 func currentTabGoal(tab *WorkspaceTab) string {
6889 if tab == nil {
6890 return ""
6891 }
6892 if tab.Ctrl != nil {
6893 return tab.Ctrl.Goal()
6894 }
6895 return strings.TrimSpace(tab.goal)
6896 }
6897
6898 func currentTabGoalStatus(tab *WorkspaceTab) string {
6899 if tab == nil {
6900 return control.GoalStatusStopped
6901 }
6902 if tab.Ctrl != nil {
6903 return tab.Ctrl.GoalStatus()
6904 }
6905 if strings.TrimSpace(tab.goal) != "" {
6906 return control.GoalStatusRunning
6907 }
6908 return control.GoalStatusStopped
6909 }
6910
6911 func currentTabCollaborationMode(tab *WorkspaceTab) string {
6912 if tab == nil {
6913 return "normal"
6914 }
6915 if tabModeHasPlan(currentTabMode(tab)) {
6916 return "plan"
6917 }
6918 if strings.TrimSpace(currentTabGoal(tab)) != "" && currentTabGoalStatus(tab) == control.GoalStatusRunning {
6919 return "goal"
6920 }
6921 return "normal"
6922 }
6923
6924 func currentTabToolApprovalMode(tab *WorkspaceTab) string {
6925 if tab == nil {
6926 return control.ToolApprovalWorkspaceWrite
6927 }
6928 if tab.Ctrl != nil {
6929 return tab.Ctrl.ToolApprovalMode()
6930 }
6931 return normalizeToolApprovalMode(tab.toolApprovalMode)
6932 }
6933
6934 // Snapshot-based forms of the currentTabX helpers, for callers that already
6935 // hold a consistent tabRuntimeSnapshot.
6936
6937 func (s tabRuntimeSnapshot) currentMode() string {
6938 if s.ctrl != nil {
6939 return tabModeFromAxes(s.ctrl.PlanMode(), s.ctrl.AutoApproveTools())
6940 }
6941 return normalizeTabMode(s.mode)
6942 }
6943
6944 func (s tabRuntimeSnapshot) currentGoal() string {
6945 if s.ctrl != nil {
6946 return s.ctrl.Goal()
6947 }
6948 return strings.TrimSpace(s.goal)
6949 }
6950
6951 func (s tabRuntimeSnapshot) currentGoalStatus() string {
6952 if s.ctrl != nil {
6953 return s.ctrl.GoalStatus()
6954 }
6955 if strings.TrimSpace(s.goal) != "" {
6956 return control.GoalStatusRunning
6957 }
6958 return control.GoalStatusStopped
6959 }
6960
6961 func (s tabRuntimeSnapshot) collaborationMode() string {
6962 if tabModeHasPlan(s.currentMode()) {
6963 return "plan"
6964 }
6965 if strings.TrimSpace(s.currentGoal()) != "" && s.currentGoalStatus() == control.GoalStatusRunning {
6966 return "goal"
6967 }
6968 return "normal"
6969 }
6970
6971 func (s tabRuntimeSnapshot) currentToolApprovalMode() string {
6972 if s.ctrl != nil {
6973 return s.ctrl.ToolApprovalMode()
6974 }
6975 return normalizeToolApprovalMode(s.toolApprovalMode)
6976 }
6977
6978 // normalizedRuntime reads live Controller state only after the App snapshot has
6979 // released a.mu. Rebuild callers hold turnStartMu while invoking it, so all
6980 // three axes and the legacy Goal fallback describe one admitted runtime state.
6981 func (s tabRuntimeSnapshot) normalizedRuntime() normalizedTabRuntime {
6982 plan := tabModeHasPlan(normalizeTabMode(s.mode))
6983 approvalMode := normalizeToolApprovalMode(s.toolApprovalMode)
6984 goal := strings.TrimSpace(s.goal)
6985 goalStatus := control.GoalStatusStopped
6986 if goal != "" {
6987 goalStatus = control.GoalStatusRunning
6988 }
6989 if s.ctrl != nil {
6990 plan = s.ctrl.PlanMode()
6991 approvalMode = normalizeToolApprovalMode(s.ctrl.ToolApprovalMode())
6992 goal = strings.TrimSpace(s.ctrl.Goal())
6993 goalStatus = s.ctrl.GoalStatus()
6994 }
6995
6996 runtime := normalizedTabRuntime{
6997 collaborationMode: "normal",
6998 toolApprovalMode: approvalMode,
6999 tokenMode: boot.NormalizeTokenMode(s.tokenMode),
7000 qualityFloor: control.QualityFloorStandard,
7001 }
7002 switch {
7003 case plan:
7004 runtime.collaborationMode = "plan"
7005 case goal != "" && goalStatus == control.GoalStatusRunning:
7006 runtime.collaborationMode = "goal"
7007 runtime.legacyGoal = goal
7008 }
7009 return runtime
7010 }
7011
7012 func (r normalizedTabRuntime) tabMode() string {
7013 return tabModeFromAxes(r.collaborationMode == "plan", r.toolApprovalMode == control.ToolApprovalDangerFullAccess)
7014 }
7015
7016 func applyNormalizedRuntimeToTabLocked(tab *WorkspaceTab, runtime normalizedTabRuntime) {
7017 if tab == nil {
7018 return
7019 }
7020 tab.mode = runtime.tabMode()
7021 tab.toolApprovalMode = normalizeToolApprovalMode(runtime.toolApprovalMode)
7022 tab.qualityFloor = runtime.qualityFloor
7023 if runtime.collaborationMode == "goal" {
7024 tab.goal = strings.TrimSpace(runtime.legacyGoal)
7025 } else {
7026 tab.goal = ""
7027 }
7028 }
7029
7030 func normalizeToolApprovalMode(mode string) string {
7031 return config.NormalizeToolApprovalMode(mode)
7032 }
7033
7034 func persistedToolApprovalMode(mode string) string {
7035 return normalizeToolApprovalMode(mode)
7036 }
7037
7038 // persistedTabMode stores only the collaboration axis. Permission now has its
7039 // own authoritative ToolApprovalMode field, so new state must never encode it
7040 // again through the legacy yolo/plan-yolo values. Legacy readers still accept
7041 // those values during migration.
7042 func persistedTabMode(mode string) string {
7043 switch normalizeTabMode(mode) {
7044 case "plan", "plan-yolo":
7045 return "plan"
7046 }
7047 return ""
7048 }
7049
7050 func newTabID() string {
7051 var b [16]byte
7052 if _, err := rand.Read(b[:]); err != nil {
7053 now := time.Now().UTC()
7054 return "tab_" + now.Format("20060102150405") + "_" + fmt.Sprintf("%09d", now.Nanosecond())
7055 }
7056 return "tab_" + hex.EncodeToString(b[:])
7057 }
7058
7059 func newTopicID() string {
7060 var b [8]byte
7061 if _, err := rand.Read(b[:]); err != nil {
7062 now := time.Now().UTC()
7063 return "topic_" + now.Format("20060102-150405") + "_" + fmt.Sprintf("%09d", now.Nanosecond())
7064 }
7065 return "topic_" + time.Now().UTC().Format("20060102-150405") + "_" + hex.EncodeToString(b[:])
7066 }
7067
7068 func globalWorkspaceRoot() string {
7069 return filepath.Join(desktopConfigDir(), "global-workspace")
7070 }
7071
7072 func ensureGlobalWorkspaceRoot() (string, error) {
7073 root := globalWorkspaceRoot()
7074 if err := os.MkdirAll(root, 0o755); err != nil {
7075 return "", err
7076 }
7077 return root, nil
7078 }
7079
7080 func globalTabWorkspaceRoot() string {
7081 root, err := ensureGlobalWorkspaceRoot()
7082 if err != nil {
7083 return globalWorkspaceRoot()
7084 }
7085 return root
7086 }
7087
7088 func loadPinnedTabSession(dir, sessionPath string) (*agent.Session, string, bool, error) {
7089 return loadPinnedTabSessionWithPreloadAndMigrationFallback(dir, sessionPath, loadedTabSession{}, true)
7090 }
7091
7092 func loadPinnedTabSessionWithPreloadAndMigrationFallback(dir, sessionPath string, preloaded loadedTabSession, allowMigrationFallback bool) (*agent.Session, string, bool, error) {
7093 return loadPinnedTabSessionContext(context.Background(), dir, sessionPath, preloaded, allowMigrationFallback)
7094 }
7095
7096 func loadPinnedTabSessionContext(ctx context.Context, dir, sessionPath string, preloaded loadedTabSession, allowMigrationFallback bool) (*agent.Session, string, bool, error) {
7097 path, ok := pinnedTabSessionPath(dir, sessionPath)
7098 if !ok && allowMigrationFallback {
7099 path, ok = migratedPinnedTabSessionPath(dir, sessionPath)
7100 }
7101 if !ok {
7102 return nil, "", false, nil
7103 }
7104 if agent.IsCleanupPending(path) {
7105 return nil, "", false, nil
7106 }
7107 if preloaded.matches(path) {
7108 if preloaded.Session != nil && len(preloaded.Session.Snapshot()) == 0 {
7109 return nil, path, true, nil
7110 }
7111 return preloaded.Session, path, true, nil
7112 }
7113 loaded, err := agent.LoadSessionContext(ctx, path)
7114 if err != nil {
7115 if os.IsNotExist(err) {
7116 return nil, path, true, nil
7117 }
7118 return nil, path, true, err
7119 }
7120 // An empty file (0 messages) is a pre-created placeholder, not a real
7121 // session to resume. Treating it as valid would make ctrl.Resume replace
7122 // the executor's live session (with system prompt) with the empty one,
7123 // causing the saved transcript to lack the agent identity contract.
7124 if len(loaded.Snapshot()) == 0 {
7125 return nil, path, true, nil
7126 }
7127 return loaded, path, true, nil
7128 }
7129
7130 func migratedPinnedTabSessionPath(dir, sessionPath string) (string, bool) {
7131 sessionPath = strings.TrimSpace(sessionPath)
7132 if sessionPath == "" || dir == "" || !filepath.IsAbs(sessionPath) {
7133 return "", false
7134 }
7135 if _, err := os.Stat(sessionPath); err == nil || !os.IsNotExist(err) {
7136 return "", false
7137 }
7138 base := filepath.Base(sessionPath)
7139 if base == "." || base == string(filepath.Separator) || !strings.HasSuffix(base, ".jsonl") {
7140 return "", false
7141 }
7142 path, _, err := validateSessionPath(dir, filepath.Join(dir, base))
7143 if err != nil {
7144 return "", false
7145 }
7146 return path, true
7147 }
7148
7149 func pinnedTabSessionPath(dir, sessionPath string) (string, bool) {
7150 sessionPath = strings.TrimSpace(sessionPath)
7151 if sessionPath == "" || dir == "" {
7152 return "", false
7153 }
7154 path, _, err := validateSessionPath(dir, sessionPath)
7155 if err != nil {
7156 if filepath.IsAbs(sessionPath) {
7157 return "", false
7158 }
7159 base := filepath.Base(sessionPath)
7160 if base == "." || base == string(filepath.Separator) || !strings.HasSuffix(base, ".jsonl") {
7161 return "", false
7162 }
7163 path, _, err = validateSessionPath(dir, filepath.Join(dir, base))
7164 if err != nil {
7165 return "", false
7166 }
7167 }
7168 return path, true
7169 }
7170
7171 func pinnedTabSessionPathForBuild(scope, workspaceRoot, targetDir, sessionPath string) (string, bool) {
7172 if path, ok := pinnedTabSessionPath(targetDir, sessionPath); ok {
7173 return path, true
7174 }
7175 // Before per-project storage, desktop tabs persisted exact paths under the
7176 // global session directory. Accept only that owned legacy root, and require
7177 // project ownership metadata before routing a project tab through it.
7178 legacyDir := config.SessionDir()
7179 path, ok := pinnedTabSessionPath(legacyDir, sessionPath)
7180 if !ok {
7181 return "", false
7182 }
7183 meta, hasMeta, err := agent.LoadBranchMeta(path)
7184 if strings.TrimSpace(scope) == "project" {
7185 if err != nil || !hasMeta || meta.Scope != "project" || !sameProjectRoot(meta.WorkspaceRoot, workspaceRoot) {
7186 return "", false
7187 }
7188 } else if err == nil && hasMeta && meta.Scope == "project" {
7189 return "", false
7190 }
7191 return path, true
7192 }
7193
7194 // saveTabSessionMeta persists the tab's scope/topic/mode fields into the
7195 // session's branch-meta sidecar at path. Tab fields are snapshotted under a.mu
7196 // (controller reads happen off-lock) so a concurrent tab mutation can't tear
7197 // the persisted record.
7198 func (a *App) saveTabSessionMeta(tab *WorkspaceTab, path string) error {
7199 if tab == nil {
7200 return nil
7201 }
7202 snap, ok, err := a.tabSessionMetaSnapshot(tab, path, false)
7203 if err != nil || !ok {
7204 return err
7205 }
7206 return a.saveTabSessionMetaSnapshotAndIndex(snap)
7207 }
7208
7209 type tabSessionMetaSnapshot struct {
7210 path legacySessionPath
7211 scope, workspaceRoot string
7212 topicID, topicTitle string
7213 tokenMode string
7214 qualityFloor string
7215 mode string
7216 toolApprovalMode string
7217 goal string
7218 }
7219
7220 func (a *App) saveTabSessionMetaForCurrentSession(tab *WorkspaceTab) error {
7221 snap, ok, err := a.tabSessionMetaSnapshotForCurrentSession(tab)
7222 if err != nil || !ok {
7223 return err
7224 }
7225 return a.saveTabSessionMetaSnapshotAndIndex(snap)
7226 }
7227
7228 func (a *App) tabSessionMetaSnapshotForCurrentSession(tab *WorkspaceTab) (tabSessionMetaSnapshot, bool, error) {
7229 return a.tabSessionMetaSnapshot(tab, "", true)
7230 }
7231
7232 type tabSessionMetaSource struct {
7233 snapshot tabSessionMetaSnapshot
7234 ctrl control.SessionAPI
7235 generation uint64
7236 sessionID, storedPath string
7237 readOnly bool
7238 }
7239
7240 func (a *App) captureTabSessionMetaSource(tab *WorkspaceTab) (tabSessionMetaSource, bool) {
7241 if tab == nil {
7242 return tabSessionMetaSource{}, false
7243 }
7244 a.mu.RLock()
7245 defer a.mu.RUnlock()
7246 if tab.ID != "" && a.tabs[tab.ID] != tab {
7247 return tabSessionMetaSource{}, false
7248 }
7249 return tabSessionMetaSource{
7250 ctrl: tab.Ctrl,
7251 generation: tab.SessionGeneration,
7252 sessionID: strings.TrimSpace(tab.SessionID),
7253 storedPath: strings.TrimSpace(tab.SessionPath),
7254 readOnly: tab.ReadOnly,
7255 snapshot: tabSessionMetaSnapshot{
7256 scope: tab.Scope, workspaceRoot: tab.WorkspaceRoot,
7257 topicID: tab.TopicID, topicTitle: tab.TopicTitle,
7258 tokenMode: currentTabTokenMode(tab), qualityFloor: control.QualityFloorStandard,
7259 mode: normalizeTabMode(tab.mode), toolApprovalMode: normalizeToolApprovalMode(tab.toolApprovalMode),
7260 goal: strings.TrimSpace(tab.goal),
7261 },
7262 }, true
7263 }
7264
7265 func canonicalTabSessionMetaDisposition(sessionID, storedPath, requestedPath string) (bool, error) {
7266 if sessionID == "" {
7267 return false, nil
7268 }
7269 if err := session.ValidateSessionID(sessionID); err != nil {
7270 return false, &sessionLocatorError{reason: "invalid_canonical_session_id"}
7271 }
7272 if locator := classifySessionLocator(storedPath); locator.kind != sessionLocatorEmpty {
7273 if locator.kind != sessionLocatorCanonical || locator.ref.SessionID != sessionID {
7274 return false, &sessionLocatorError{reason: "session_identity_conflict"}
7275 }
7276 }
7277 if requestedPath != "" {
7278 locator := classifySessionLocator(requestedPath)
7279 if locator.kind == sessionLocatorInvalid || locator.kind == sessionLocatorCanonical && locator.ref.SessionID != sessionID {
7280 return false, &sessionLocatorError{reason: "session_identity_conflict"}
7281 }
7282 }
7283 // Canonical session metadata belongs to the Session Service, workspace
7284 // registry, and desktop-tabs.json. Never dual-write a legacy sidecar.
7285 return true, nil
7286 }
7287
7288 func updateTabSessionMetaFromController(source *tabSessionMetaSource) (ctrlPath, ctrlDir string, activeWork bool) {
7289 if source.ctrl != nil {
7290 ctrlPath = strings.TrimSpace(source.ctrl.SessionPath())
7291 if dir, ok := safeControllerSessionDir(source.ctrl); ok {
7292 ctrlDir = strings.TrimSpace(dir)
7293 }
7294 status := source.ctrl.RuntimeStatus()
7295 activeWork = status.Running || status.PendingPrompt || status.BackgroundJobs > 0
7296 source.snapshot.mode = tabModeFromAxes(source.ctrl.PlanMode(), source.ctrl.AutoApproveTools())
7297 source.snapshot.toolApprovalMode = normalizeToolApprovalMode(source.ctrl.ToolApprovalMode())
7298 if source.ctrl.GoalStatus() == control.GoalStatusRunning {
7299 source.snapshot.goal = strings.TrimSpace(source.ctrl.Goal())
7300 } else {
7301 source.snapshot.goal = ""
7302 }
7303 }
7304 return ctrlPath, ctrlDir, activeWork
7305 }
7306
7307 func tabSessionMetaLegacyPath(source tabSessionMetaSource, requestedPath string, useCurrent bool, ctrlPath, ctrlDir string, activeWork bool) (legacySessionPath, bool, error) {
7308 currentPath := strings.TrimSpace(requestedPath)
7309 if useCurrent {
7310 currentPath = ctrlPath
7311 if currentPath == "" {
7312 currentPath = source.storedPath
7313 }
7314 }
7315 if currentPath == "" {
7316 return "", false, nil
7317 }
7318 locator := classifySessionLocator(currentPath)
7319 switch locator.kind {
7320 case sessionLocatorCanonical:
7321 return "", false, nil
7322 case sessionLocatorInvalid:
7323 return "", false, &sessionLocatorError{reason: locator.reason}
7324 case sessionLocatorEmpty:
7325 return "", false, nil
7326 }
7327
7328 sessionDir := desktopSessionDir("")
7329 if source.snapshot.workspaceRoot != "" {
7330 sessionDir = desktopSessionDir(source.snapshot.workspaceRoot)
7331 } else if ctrlDir != "" {
7332 sessionDir = ctrlDir
7333 }
7334 runtimeDir := sessionDir
7335 if ctrlDir != "" {
7336 if _, _, err := validateSessionPath(ctrlDir, currentPath); err == nil {
7337 runtimeDir = ctrlDir
7338 }
7339 }
7340 if source.snapshot.topicID == "" && !activeWork && source.storedPath != "" && classifySessionLocator(source.storedPath).kind == sessionLocatorLegacy && sessionPathHasNoContent(sessionDir, source.storedPath) {
7341 return "", false, nil
7342 }
7343 path, err := tabSessionMetaPathForSession(runtimeDir, sessionDir, currentPath)
7344 if err != nil {
7345 return "", false, err
7346 }
7347 return path, true, nil
7348 }
7349
7350 func (a *App) tabSessionMetaSourceCurrent(tab *WorkspaceTab, source tabSessionMetaSource) bool {
7351 a.mu.RLock()
7352 defer a.mu.RUnlock()
7353 current := tab.ID == "" || a.tabs[tab.ID] == tab
7354 return current && tab.Ctrl == source.ctrl && tab.SessionGeneration == source.generation &&
7355 strings.TrimSpace(tab.SessionID) == source.sessionID && strings.TrimSpace(tab.SessionPath) == source.storedPath
7356 }
7357
7358 func (a *App) tabSessionMetaSnapshot(tab *WorkspaceTab, requestedPath string, useCurrent bool) (tabSessionMetaSnapshot, bool, error) {
7359 source, ok := a.captureTabSessionMetaSource(tab)
7360 if !ok || source.readOnly || historicalPreview(source.ctrl) {
7361 return tabSessionMetaSnapshot{}, false, nil
7362 }
7363 canonical, err := canonicalTabSessionMetaDisposition(source.sessionID, source.storedPath, requestedPath)
7364 if err != nil || canonical {
7365 return tabSessionMetaSnapshot{}, false, err
7366 }
7367 ctrlPath, ctrlDir, activeWork := updateTabSessionMetaFromController(&source)
7368 path, ok, err := tabSessionMetaLegacyPath(source, requestedPath, useCurrent, ctrlPath, ctrlDir, activeWork)
7369 if err != nil || !ok {
7370 return tabSessionMetaSnapshot{}, false, err
7371 }
7372 // Controller reads above are intentionally off App.mu. Fence the result
7373 // before it can select a file target for a tab that has since switched.
7374 if !a.tabSessionMetaSourceCurrent(tab, source) {
7375 return tabSessionMetaSnapshot{}, false, nil
7376 }
7377 source.snapshot.path = path
7378 return source.snapshot, true, nil
7379 }
7380
7381 func saveTabSessionMetaSnapshot(snap tabSessionMetaSnapshot) error {
7382 path := string(snap.path)
7383 if strings.TrimSpace(path) == "" {
7384 return nil
7385 }
7386 // Read-modify-write on the branch-meta sidecar: hold the per-path meta lock
7387 // so agent-side writers (autosave UpdateSessionMeta, in-flight markers)
7388 // can't interleave and drop fields.
7389 unlock, err := agent.LockSessionMetaPath(path)
7390 if err != nil {
7391 return err
7392 }
7393 defer unlock()
7394 m, err := agent.EnsureBranchMetaLocked(path)
7395 if err != nil {
7396 return err
7397 }
7398 scope := snap.scope
7399 workspaceRoot := snap.workspaceRoot
7400 if ownerScope, ownerRoot, _, ok := legacyMigrationTargetForDir(filepath.Dir(path)); ok {
7401 if ownerScope == "project" {
7402 scope = ownerScope
7403 workspaceRoot = ownerRoot
7404 }
7405 }
7406 if scope == "project" {
7407 workspaceRoot = normalizeProjectRoot(workspaceRoot)
7408 } else {
7409 scope = "global"
7410 workspaceRoot = ""
7411 }
7412 m.Scope = scope
7413 m.WorkspaceRoot = workspaceRoot
7414 m.TopicID = snap.topicID
7415 m.TopicTitle = snap.topicTitle
7416 m.QualityFloor, m.TokenMode, m.AgentPreset = control.QualityFloorStandard, boot.TokenModeFull, boot.AgentPresetStandard
7417 m.Mode = persistedTabMode(snap.mode)
7418 m.ToolApprovalMode = persistedToolApprovalMode(snap.toolApprovalMode)
7419 m.Goal = strings.TrimSpace(snap.goal)
7420 if err := agent.SaveBranchMetaPreserveUpdatedLocked(path, m); err != nil {
7421 return err
7422 }
7423 invalidateTopicSessionIndexForPath(path)
7424 return nil
7425 }
7426
7427 func tabSessionMetaPathForSession(runtimeDir, sessionDir, sessionPath string) (legacySessionPath, error) {
7428 return resolveLegacySessionPath(sessionPath, runtimeDir, sessionDir)
7429 }
7430
7431 type tabSessionProfile struct {
7432 tokenMode, qualityFloor, mode string
7433 toolApprovalMode, goal string
7434 }
7435
7436 func defaultTabSessionProfile() tabSessionProfile {
7437 return tabSessionProfile{
7438 tokenMode: boot.TokenModeFull,
7439 qualityFloor: control.QualityFloorStandard,
7440 mode: "normal",
7441 toolApprovalMode: control.ToolApprovalWorkspaceWrite,
7442 }
7443 }
7444
7445 func tabSessionProfileFromMeta(sessionPath string, meta agent.BranchMeta) tabSessionProfile {
7446 profile := defaultTabSessionProfile()
7447 // Retired role fields remain readable but no longer affect execution.
7448 profile.tokenMode = boot.TokenModeFull
7449 profile.qualityFloor = control.QualityFloorStandard
7450 profile.mode = normalizeTabMode(meta.Mode)
7451 profile.toolApprovalMode = normalizeToolApprovalMode(meta.ToolApprovalMode)
7452 if profile.toolApprovalMode == control.ToolApprovalReadOnly && tabModeHasAutoApproveTools(meta.Mode) {
7453 profile.toolApprovalMode = control.ToolApprovalWorkspaceWrite
7454 }
7455 profile.goal = runningTabSessionGoal(sessionPath, meta.Goal)
7456 return profile
7457 }
7458
7459 func loadTabSessionProfile(sessionPath string) tabSessionProfile {
7460 legacyPath, valid := validatedLegacySessionPathForRead(sessionPath)
7461 if !valid {
7462 return defaultTabSessionProfile()
7463 }
7464 sessionPath = string(legacyPath)
7465 meta, ok, err := agent.LoadBranchMeta(sessionPath)
7466 if err != nil || !ok {
7467 return defaultTabSessionProfile()
7468 }
7469 return tabSessionProfileFromMeta(sessionPath, meta)
7470 }
7471
7472 func applyTabSessionProfile(tab *WorkspaceTab, profile tabSessionProfile) {
7473 if tab == nil {
7474 return
7475 }
7476 tab.qualityFloor = profile.qualityFloor
7477 tab.mode = normalizeTabMode(profile.mode)
7478 tab.toolApprovalMode = normalizeToolApprovalMode(profile.toolApprovalMode)
7479 if tab.toolApprovalMode == control.ToolApprovalReadOnly && tabModeHasAutoApproveTools(tab.mode) {
7480 tab.toolApprovalMode = control.ToolApprovalWorkspaceWrite
7481 }
7482 tab.mode = tabModeFromAxes(tabModeHasPlan(tab.mode), tab.toolApprovalMode == control.ToolApprovalDangerFullAccess)
7483 tab.goal = strings.TrimSpace(profile.goal)
7484 }
7485
7486 func persistedTabGoal(tab *WorkspaceTab) string {
7487 goal := strings.TrimSpace(currentTabGoal(tab))
7488 if goal == "" || currentTabGoalStatus(tab) != control.GoalStatusRunning {
7489 return ""
7490 }
7491 return goal
7492 }
7493
7494 type tabSessionGoalState struct {
7495 Goal string `json:"goal,omitempty"`
7496 Status string `json:"status,omitempty"`
7497 }
7498
7499 func runningTabSessionGoal(sessionPath, fallback string) string {
7500 fallback = strings.TrimSpace(fallback)
7501 if fallback == "" {
7502 return ""
7503 }
7504 legacyPath, ok := validatedLegacySessionPathForRead(sessionPath)
7505 if !ok {
7506 return fallback
7507 }
7508 sessionPath = string(legacyPath)
7509 data, err := readFileUTF8(store.SessionGoalState(sessionPath))
7510 if err != nil {
7511 return fallback
7512 }
7513 var state tabSessionGoalState
7514 if err := json.Unmarshal(data, &state); err != nil {
7515 return fallback
7516 }
7517 switch state.Status {
7518 case control.GoalStatusRunning:
7519 if goal := strings.TrimSpace(state.Goal); goal != "" {
7520 return goal
7521 }
7522 return fallback
7523 case "", control.GoalStatusStopped:
7524 return ""
7525 default:
7526 return ""
7527 }
7528 }
7529
7530 func canonicalTabSessionPath(path string) string {
7531 locator := classifySessionLocator(path)
7532 if locator.kind != sessionLocatorLegacy {
7533 return ""
7534 }
7535 path = string(locator.legacyPath)
7536 if validPath, _, err := validateSessionPath(config.SessionDir(), path); err == nil {
7537 return validPath
7538 }
7539 // Project-scope sessions live outside config.SessionDir(). Their absolute
7540 // transcript path still has to pass the same filename and link-escape
7541 // checks before it can reach runtime identity or file helpers.
7542 if filepath.IsAbs(path) {
7543 if validPath, _, err := validateSessionPath(filepath.Dir(path), path); err == nil {
7544 return validPath
7545 }
7546 }
7547 return ""
7548 }
7549
7550 func (a *App) rememberTabSessionPath(tab *WorkspaceTab, path string) {
7551 if tab == nil {
7552 return
7553 }
7554 locator := classifySessionLocator(path)
7555 if locator.kind == sessionLocatorInvalid || locator.kind == sessionLocatorEmpty {
7556 return
7557 }
7558 if locator.kind == sessionLocatorLegacy {
7559 path = canonicalTabSessionPath(path)
7560 if path == "" {
7561 return
7562 }
7563 }
7564 a.mu.Lock()
7565 if current := a.tabs[tab.ID]; current == tab {
7566 setTabSessionIdentity(tab, path)
7567 a.saveTabsLocked()
7568 } else {
7569 setTabSessionIdentity(tab, path)
7570 }
7571 a.mu.Unlock()
7572 }
7573
7574 func (a *App) persistTabSessionPath(tab *WorkspaceTab, path string) {
7575 locator := classifySessionLocator(path)
7576 if tab == nil || locator.kind == sessionLocatorEmpty || locator.kind == sessionLocatorInvalid {
7577 return
7578 }
7579 if locator.kind == sessionLocatorCanonical {
7580 a.rememberTabSessionPath(tab, sessionRoute(locator.ref.SessionID))
7581 return
7582 }
7583 path = canonicalTabSessionPath(path)
7584 if path == "" {
7585 return
7586 }
7587 // A tab restored from the short-lived tab-scoped implementation may not
7588 // have had a session path when startup loaded its legacy pins. Publish that
7589 // one-time migration before reconcile loads the new session-owned sidecar.
7590 migratePendingLegacyPinnedFiles(tab, path)
7591 if reconciled, ok := a.reconcileTabWithSessionPath(tab, path); ok {
7592 path = canonicalTabSessionPath(reconciled)
7593 }
7594 _ = a.saveTabSessionMeta(tab, path)
7595 a.rememberTabSessionPath(tab, path)
7596 }
7597
7598 func (a *App) knownSessionDirs() []string {
7599 seen := map[string]bool{}
7600 out := []string{}
7601 add := func(dir string) {
7602 dir = strings.TrimSpace(dir)
7603 if dir == "" {
7604 return
7605 }
7606 if abs, err := filepath.Abs(dir); err == nil {
7607 dir = abs
7608 }
7609 if seen[dir] {
7610 return
7611 }
7612 seen[dir] = true
7613 out = append(out, dir)
7614 }
7615 add(config.SessionDir()) // legacy/global sessions from earlier desktop builds
7616 add(desktopSessionDir(globalWorkspaceRoot()))
7617 for _, project := range loadProjectsFile().Projects {
7618 dir := desktopSessionDir(project.Root)
7619 if _, err := os.Stat(dir); os.IsNotExist(err) {
7620 continue // project dir removed or external volume unmounted
7621 }
7622 add(dir)
7623 }
7624 a.mu.RLock()
7625 for _, tab := range a.tabs {
7626 add(tabSessionDir(tab))
7627 }
7628 for _, tab := range a.detachedSessions {
7629 add(tabSessionDir(tab))
7630 }
7631 a.mu.RUnlock()
7632 return out
7633 }
7634
7635 func topicSessionMatchMatchesTarget(match topicSessionMatch, scope, workspaceRoot string) bool {
7636 if scope == "project" {
7637 return match.scope == "project" && sameProjectRoot(match.workspaceRoot, workspaceRoot)
7638 }
7639 return match.scope == "" || match.scope == "global"
7640 }
7641
7642 func (a *App) findTopicSessionForTarget(scope, workspaceRoot, topicID string) (string, string) {
7643 return a.findTopicSessionForTargetByContent(scope, workspaceRoot, topicID, false)
7644 }
7645
7646 func (a *App) findTopicContentSessionForTarget(scope, workspaceRoot, topicID string) (string, string) {
7647 return a.findTopicSessionForTargetByContent(scope, workspaceRoot, topicID, true)
7648 }
7649
7650 func (a *App) findTopicSessionForTargetByContent(scope, workspaceRoot, topicID string, requireContent bool) (string, string) {
7651 topicID = strings.TrimSpace(topicID)
7652 if topicID == "" {
7653 return "", ""
7654 }
7655 type candidate struct {
7656 match topicSessionMatch
7657 dir string
7658 }
7659 var candidates []candidate
7660 for _, dir := range a.knownSessionDirs() {
7661 for _, match := range topicSessionMatches(dir, topicID) {
7662 if !topicSessionMatchMatchesTarget(match, scope, workspaceRoot) {
7663 continue
7664 }
7665 candidates = append(candidates, candidate{match: match, dir: dir})
7666 }
7667 }
7668 sort.Slice(candidates, func(i, j int) bool {
7669 a, b := candidates[i].match, candidates[j].match
7670 if !a.updatedAt.Equal(b.updatedAt) {
7671 return a.updatedAt.After(b.updatedAt)
7672 }
7673 return a.path < b.path
7674 })
7675 // Content-bearing sessions outrank content-free ones regardless of
7676 // updatedAt: a freshly created empty session must not hijack the topic
7677 // from the conversation the user actually had (#7305). The content probe
7678 // reads session files, so it walks newest-first and stops at the first
7679 // hit — the common case checks one file.
7680 for _, c := range candidates {
7681 if sessionFileHasConversationContent(c.match.path) {
7682 return c.match.path, c.dir
7683 }
7684 }
7685 if requireContent || len(candidates) == 0 {
7686 return "", ""
7687 }
7688 return candidates[0].match.path, candidates[0].dir
7689 }
7690
7691 type topicSessionFileSignature struct {
7692 Name string `json:"name"`
7693 Size int64 `json:"size"`
7694 ModTime int64 `json:"mod_time"`
7695 }
7696
7697 type topicSessionMatch struct {
7698 path string
7699 updatedAt time.Time
7700 scope string
7701 workspaceRoot string
7702 }
7703
7704 type topicSessionDirIndex struct {
7705 signature []topicSessionFileSignature
7706 byTopic map[string][]topicSessionMatch
7707 }
7708
7709 // mergeSessionInfos merges one directory's session listing into the maps used by
7710 // ListProjectTree. The result collection loop calls it serially.
7711 func mergeSessionInfos(dir string, infos []agent.SessionInfo, titles map[string]string, sessionInfos map[string]agent.SessionInfo, sessionTitles map[string]string, topicSummaries map[string]topicSummary) {
7712 for _, info := range infos {
7713 sessionKey := sessionRuntimeKey(info.Path)
7714 if sessionKey != "" {
7715 sessionInfos[sessionKey] = info
7716 title := strings.TrimSpace(info.CustomTitle)
7717 if title == "" {
7718 title = titles[filepath.Base(info.Path)]
7719 }
7720 sessionTitles[sessionKey] = title
7721 }
7722 if strings.TrimSpace(info.TopicID) == "" {
7723 continue
7724 }
7725 key := topicSummaryKey(info.Scope, info.WorkspaceRoot, info.TopicID)
7726 summary := topicSummaries[key]
7727 lastActivityAt := info.LastActivityAt.UnixMilli()
7728 if sessionInfoIsAutomaticRecovery(info) {
7729 // A covered conflict copy duplicates its parent, so its turns must not
7730 // be added. Any branch with unique content keeps the topic visible.
7731 if sessionInfoIsUnmodifiedRecoveryCopy(info, dir) {
7732 summary.hasRecoveryOnly = true
7733 } else {
7734 summary.hasAdoptedRecovery = true
7735 if info.Turns > summary.adoptedRecoveryTurns {
7736 summary.adoptedRecoveryTurns = info.Turns
7737 }
7738 }
7739 if lastActivityAt > summary.lastActivityAt {
7740 summary.lastActivityAt = lastActivityAt
7741 }
7742 topicSummaries[key] = summary
7743 continue
7744 }
7745 summary.hasNormalSession = true
7746 summary.turns += info.Turns
7747 if lastActivityAt > summary.lastActivityAt {
7748 summary.lastActivityAt = lastActivityAt
7749 }
7750 topicSummaries[key] = summary
7751 }
7752 }
7753
7754 var topicSessionIndexCache = struct {
7755 sync.Mutex
7756 byDir map[string]topicSessionDirIndex
7757 }{byDir: map[string]topicSessionDirIndex{}}
7758
7759 func topicSessionDirKey(dir string) string {
7760 dir = strings.TrimSpace(dir)
7761 if dir == "" {
7762 return ""
7763 }
7764 if abs, err := filepath.Abs(dir); err == nil {
7765 return abs
7766 }
7767 return dir
7768 }
7769
7770 func topicSessionDirSnapshot(dir string) ([]topicSessionFileSignature, []string, error) {
7771 entries, err := os.ReadDir(dir)
7772 if err != nil {
7773 return nil, nil, err
7774 }
7775 signature := []topicSessionFileSignature{}
7776 sessionNames := []string{}
7777 for _, entry := range entries {
7778 name := entry.Name()
7779 if entry.IsDir() {
7780 continue
7781 }
7782 isSession := store.IsSessionTranscriptName(name)
7783 isMeta := strings.HasSuffix(name, ".jsonl.meta")
7784 if !isSession && !isMeta {
7785 continue
7786 }
7787 info, err := entry.Info()
7788 if err != nil {
7789 continue
7790 }
7791 signature = append(signature, topicSessionFileSignature{
7792 Name: name,
7793 Size: info.Size(),
7794 ModTime: info.ModTime().UnixNano(),
7795 })
7796 if isSession {
7797 sessionNames = append(sessionNames, name)
7798 }
7799 }
7800 sort.Slice(signature, func(i, j int) bool {
7801 return signature[i].Name < signature[j].Name
7802 })
7803 sort.Strings(sessionNames)
7804 return signature, sessionNames, nil
7805 }
7806
7807 func topicSessionSignaturesEqual(a, b []topicSessionFileSignature) bool {
7808 if len(a) != len(b) {
7809 return false
7810 }
7811 for i := range a {
7812 if a[i] != b[i] {
7813 return false
7814 }
7815 }
7816 return true
7817 }
7818
7819 func topicSessionIndexForDir(dir string) (topicSessionDirIndex, error) {
7820 key := topicSessionDirKey(dir)
7821 if key == "" {
7822 return topicSessionDirIndex{}, nil
7823 }
7824 signature, sessionNames, err := topicSessionDirSnapshot(key)
7825 if err != nil {
7826 if os.IsNotExist(err) {
7827 return topicSessionDirIndex{}, nil
7828 }
7829 return topicSessionDirIndex{}, err
7830 }
7831 topicSessionIndexCache.Lock()
7832 cached, ok := topicSessionIndexCache.byDir[key]
7833 if ok && topicSessionSignaturesEqual(cached.signature, signature) {
7834 topicSessionIndexCache.Unlock()
7835 return cached, nil
7836 }
7837 topicSessionIndexCache.Unlock()
7838
7839 index := topicSessionDirIndex{
7840 signature: signature,
7841 byTopic: map[string][]topicSessionMatch{},
7842 }
7843 scope, root := "global", ""
7844 for _, project := range loadProjectsFile().Projects {
7845 if sameDesktopPath(key, desktopSessionDir(project.Root)) {
7846 scope, root = "project", project.Root
7847 break
7848 }
7849 }
7850 for _, name := range sessionNames {
7851 path := filepath.Join(key, name)
7852 meta, _, err := agent.LoadBranchMeta(path)
7853 if err != nil {
7854 continue
7855 }
7856 topicID := strings.TrimSpace(meta.TopicID)
7857 if topicID == "" {
7858 // Discovery assigns this identity without rewriting old metadata.
7859 // Explicit operations must resolve exactly the same source identity.
7860 topicID = legacySessionTopicID(path)
7861 }
7862 matchScope, matchRoot := scope, root
7863 if meta.Scope != "" {
7864 matchScope, matchRoot = meta.DefaultScope(), meta.WorkspaceRoot
7865 }
7866 index.byTopic[topicID] = append(index.byTopic[topicID], topicSessionMatch{
7867 path: path,
7868 updatedAt: meta.UpdatedAt,
7869 scope: matchScope,
7870 workspaceRoot: matchRoot,
7871 })
7872 }
7873
7874 topicSessionIndexCache.Lock()
7875 topicSessionIndexCache.byDir[key] = index
7876 topicSessionIndexCache.Unlock()
7877 return index, nil
7878 }
7879
7880 func topicSessionIndexHasContentTopic(index topicSessionDirIndex, topicID string) bool {
7881 matches := index.byTopic[strings.TrimSpace(topicID)]
7882 for _, match := range matches {
7883 if sessionFileHasConversationContent(match.path) {
7884 return true
7885 }
7886 }
7887 return false
7888 }
7889
7890 // topicSessionIndexHasForeignLeaseTopic reports whether any session file
7891 // indexed under topicID is currently lease-held by a runtime other than this
7892 // process. A blank topic can still be lease-held — its session lease keeper
7893 // keeps a leftover blank tab's lease alive across a hide-to-tray close, and a
7894 // stale-but-live holder blocks a genuinely new session from ever settling on
7895 // this path. Reusing it anyway would make the "new" tab collide with that
7896 // holder: every lease-gated switch (effort/model/token mode) would fail as if
7897 // a foreign window owned it, and creating another "new" conversation would
7898 // keep re-picking the same stuck topic (#6028, #6109).
7899 func topicSessionIndexHasForeignLeaseTopic(index topicSessionDirIndex, topicID string) bool {
7900 matches := index.byTopic[strings.TrimSpace(topicID)]
7901 for _, match := range matches {
7902 if agent.SessionLeaseHeldByOtherRuntime(match.path) {
7903 return true
7904 }
7905 }
7906 return false
7907 }
7908
7909 func topicSessionMatches(dir, topicID string) []topicSessionMatch {
7910 index, err := topicSessionIndexForDir(dir)
7911 if err != nil {
7912 return nil
7913 }
7914 matches := index.byTopic[strings.TrimSpace(topicID)]
7915 if len(matches) == 0 {
7916 return nil
7917 }
7918 out := make([]topicSessionMatch, 0, len(matches))
7919 for _, match := range matches {
7920 if agent.IsCleanupPending(match.path) {
7921 continue
7922 }
7923 out = append(out, match)
7924 }
7925 if len(out) == 0 {
7926 return nil
7927 }
7928 return out
7929 }
7930
7931 func invalidateTopicSessionIndex(dir string) {
7932 key := topicSessionDirKey(dir)
7933 if key == "" {
7934 return
7935 }
7936 topicSessionIndexCache.Lock()
7937 delete(topicSessionIndexCache.byDir, key)
7938 topicSessionIndexCache.Unlock()
7939 }
7940
7941 func invalidateTopicSessionIndexForPath(path string) {
7942 path = strings.TrimSpace(path)
7943 if path == "" {
7944 return
7945 }
7946 invalidateTopicSessionIndex(filepath.Dir(path))
7947 }
7948
7949 // findTopicSession returns the most recently updated .jsonl file whose .meta
7950 // carries the given topicID, using a directory-level sidecar index cache.
7951 func findTopicSession(dir, topicID string) string {
7952 if topicID == "" || dir == "" {
7953 return ""
7954 }
7955 var bestPath string
7956 var bestTime time.Time
7957 for _, match := range topicSessionMatches(dir, topicID) {
7958 if match.updatedAt.After(bestTime) {
7959 bestTime = match.updatedAt
7960 bestPath = match.path
7961 }
7962 }
7963 return bestPath
7964 }
7965
7965 lines GO