1package daemon
2
3import (
4 "context"
5 "path/filepath"
6 "strings"
7
8 "github.com/bnema/vev/internal/domain"
9 "github.com/bnema/vev/internal/usecase/layout"
10)
11
12// floatingState describes the lifecycle of a tab's independent floating pane.
13// A floating slot is always guarded by its owning tab.mu.
14type floatingState uint8
15
16const (
17 floatingUninitialized floatingState = iota
18 floatingWarming
19 floatingHidden
20 floatingVisible
21)
22
23// floatingSlot holds the runtime which is deliberately outside tab.tree and
24// tab.panes. generation identifies an asynchronous launch and its installed
25// pane, preventing stale launch completions and exits from changing new state.
26type floatingSlot struct {
27 state floatingState
28 pane *pane
29 desiredVisible bool
30 generation uint64
31}
32
33// beginFloatingWarmLocked starts a single background launch. The caller must
34// hold tb.mu and must only call it for an uninitialized slot.
35func (tb *tab) beginFloatingWarmLocked(desiredVisible bool) uint64 {
36 if tb == nil || tb.floating.state != floatingUninitialized {
37 return 0
38 }
39 tb.floating.generation++
40 tb.floating.state = floatingWarming
41 tb.floating.desiredVisible = desiredVisible
42 return tb.floating.generation
43}
44
45// floatingTransferableLocked reports whether a tab's floating lifecycle can
46// cross an ownership commit. A warming Open remains registered to its source
47// session until installation or failure, so moves must reject only that state.
48// The caller must hold tb.mu.
49func (tb *tab) floatingTransferableLocked() bool {
50 return tb != nil && tb.floating.state != floatingWarming
51}
52
53// toggleFloatingLocked applies the user action. Its result says whether a new
54// PTY launch is required and returns the generation associated with that launch
55// or current slot.
56func (tb *tab) toggleFloatingLocked() (bool, uint64) {
57 if tb == nil {
58 return false, 0
59 }
60 switch tb.floating.state {
61 case floatingUninitialized:
62 generation := tb.beginFloatingWarmLocked(true)
63 return generation != 0, generation
64 case floatingWarming:
65 tb.floating.desiredVisible = !tb.floating.desiredVisible
66 case floatingHidden:
67 tb.floating.state = floatingVisible
68 case floatingVisible:
69 tb.floating.state = floatingHidden
70 }
71 return false, tb.floating.generation
72}
73
74// installFloatingLocked installs a completed launch only when it is still the
75// current warming generation. Stale completions must close their PTY elsewhere.
76func (tb *tab) installFloatingLocked(p *pane, generation uint64) bool {
77 if tb == nil || p == nil || tb.floating.state != floatingWarming || tb.floating.generation != generation {
78 return false
79 }
80 tb.floating.pane = p
81 if tb.floating.desiredVisible {
82 tb.floating.state = floatingVisible
83 } else {
84 tb.floating.state = floatingHidden
85 }
86 return true
87}
88
89// failFloatingLocked clears only the current warming launch. It deliberately
90// leaves generation intact; the next launch advances it.
91func (tb *tab) failFloatingLocked(generation uint64) bool {
92 if tb == nil || tb.floating.state != floatingWarming || tb.floating.generation != generation {
93 return false
94 }
95 tb.floating.state = floatingUninitialized
96 tb.floating.pane = nil
97 tb.floating.desiredVisible = false
98 return true
99}
100
101// clearFloatingLocked clears a matching installed runtime. Matching both pane
102// identity and generation prevents an old reader from reaping a newer pane.
103func (tb *tab) clearFloatingLocked(p *pane, generation uint64) bool {
104 if tb == nil || p == nil || tb.floating.pane != p || tb.floating.generation != generation ||
105 (tb.floating.state != floatingHidden && tb.floating.state != floatingVisible) {
106 return false
107 }
108 tb.takeFloatingLocked()
109 return true
110}
111
112// takeFloatingLocked invalidates the slot and detaches its installed pane. The
113// caller must hold tb.mu and must close the returned pane after unlocking.
114func (tb *tab) takeFloatingLocked() *pane {
115 if tb == nil {
116 return nil
117 }
118 p := tb.floating.pane
119 tb.floating.generation++
120 tb.floating.state = floatingUninitialized
121 tb.floating.pane = nil
122 tb.floating.desiredVisible = false
123 return p
124}
125
126// terminalTargetLocked chooses the visible floating terminal ahead of the
127// normal layout target. The caller must hold tb.mu.
128func (tb *tab) terminalTargetLocked() *pane {
129 if tb != nil && tb.floating.state == floatingVisible && tb.floating.pane != nil {
130 return tb.floating.pane
131 }
132 return tb.focusedPane()
133}
134
135// visibleFloatingSnapshotLocked captures the visible popup and its current
136// geometry under the tab lock, so input cannot mix a pane from one state with
137// coordinates from another. The caller must hold tb.mu.
138func (tb *tab) visibleFloatingSnapshotLocked(cfg domain.FloatingConfig) (*pane, floatingGeometry, bool) {
139 if tb == nil || tb.floating.state != floatingVisible || tb.floating.pane == nil {
140 return nil, floatingGeometry{}, false
141 }
142 p := tb.floating.pane
143 desired := calculateContentFloatingGeometry(domain.Size{Cols: tb.size.Cols, Rows: tb.size.Rows}, cfg)
144 p.mu.Lock()
145 geometry := p.committedFloatingGeometryLocked(desired)
146 p.mu.Unlock()
147 if !geometry.committable() {
148 return nil, floatingGeometry{}, false
149 }
150 return p, geometry, true
151}
152
153// ensureFloatingWarm starts the background prewarm exactly once for a tab.
154func (d *Daemon) ensureFloatingWarm(sess *session, tb *tab) {
155 if d == nil || sess == nil || tb == nil || d.ptys == nil {
156 return
157 }
158 d.startFloating(sess, tb, false)
159}
160
161// activateTab performs the work associated with making a tab the destination.
162// It is deliberately idempotent: every tab transition can use this single
163// hook, while inactive restored tabs remain cold until actually selected.
164func (d *Daemon) activateTab(sess *session, tb *tab) bool {
165 return d.activateTabAfterResize(sess, tb, false)
166}
167
168// activateTabAfterResize retains tab activation's warmup work while avoiding a
169// second resize when a synchronous outer resize request was already accepted.
170func (d *Daemon) activateTabAfterResize(sess *session, tb *tab, outerResizeAccepted bool) bool {
171 return d.activateTabAfterResizeForLease(sess, tb, outerResizeAccepted, nil, nil)
172}
173
174// activateTabAfterResizeForLease keeps transition-owned resize effects bound to
175// the exact coordinator incarnation. A nil lease preserves direct/headless
176// activation behavior.
177func (d *Daemon) activateTabAfterResizeForLease(sess *session, tb *tab, outerResizeAccepted bool, ac *attachedClient, lease *attachmentLease) bool {
178 if d == nil || sess == nil || tb == nil {
179 return false
180 }
181 // A headless session has no attachment-local copy mode to clear. Keep its
182 // geometry work session-wide instead of choosing an arbitrary attachment.
183 if rc := sess.renderCoordinator(); rc != nil && rc.opts.onActivateTabAfterResize != nil {
184 rc.opts.onActivateTabAfterResize(lease != nil)
185 }
186 if lease != nil {
187 rc := sess.renderCoordinator()
188 if rc == nil || !rc.leaseCurrent(lease, true) {
189 return false
190 }
191 }
192 d.ensureFloatingWarm(sess, tb)
193 if ac == nil {
194 for _, attachment := range sess.snapshotAttachments() {
195 d.exitCopyMode(attachment)
196 }
197 if outerResizeAccepted {
198 return false
199 }
200 tb.mu.Lock()
201 hasFloating := tb.floating.pane != nil
202 size := domain.Size{Cols: tb.size.Cols, Rows: tb.size.Rows + 2}
203 tb.mu.Unlock()
204 if hasFloating {
205 return sess.geometry.requestResize(d, sess, nil, size, true)
206 }
207 return false
208 }
209 d.exitCopyMode(ac)
210 if outerResizeAccepted {
211 return false
212 }
213 tb.mu.Lock()
214 hasFloating := tb.floating.pane != nil
215 size := domain.Size{Cols: tb.size.Cols, Rows: tb.size.Rows + 2}
216 tb.mu.Unlock()
217 if hasFloating {
218 if lease != nil {
219 return sess.geometry.requestResizeForLease(d, sess, ac, lease, size, true)
220 }
221 return sess.geometry.requestResize(d, sess, ac, size, true)
222 }
223 return false
224}
225
226// toggleFloating changes only this tab's slot. Opening an uninitialized slot
227// launches asynchronously; installed slots are retained when hidden.
228func (d *Daemon) toggleFloating(sess *session, ac *attachedClient) error {
229 if d == nil || sess == nil {
230 return domain.UserErr(domain.NoticeFloatingSpawn, "couldn't open floating pane: no active session", nil)
231 }
232 tb := sess.tabForAttachment(ac)
233 if ac == nil {
234 tb = sess.firstTab()
235 }
236 if tb == nil {
237 return domain.UserErr(domain.NoticeFloatingSpawn, "couldn't open floating pane: no active tab", layout.ErrNotFound)
238 }
239 cfg := d.currentFloatingConfig()
240 tb.mu.Lock()
241 wasVisible := tb.floating.state == floatingVisible
242 start, generation := tb.toggleFloatingLocked()
243 // desiredVisible is meaningful only while a launch is warming. Installed
244 // slots derive their resize and paint work from the resulting slot state.
245 visible := tb.floating.state == floatingVisible
246 hidden := wasVisible && tb.floating.state == floatingHidden
247 tb.mu.Unlock()
248 if start {
249 d.launchFloating(sess, tb, cfg, generation, true)
250 if ac != nil {
251 d.invalidateRender(sess, ac, true, "floating.go")
252 }
253 return nil
254 }
255 if hidden {
256 d.invalidateRender(sess, ac, true, "floating.go")
257 return nil
258 }
259 if visible {
260 tb.mu.Lock()
261 size := domain.Size{Cols: tb.size.Cols, Rows: tb.size.Rows + 2}
262 tb.mu.Unlock()
263 sess.geometry.requestResize(d, sess, ac, size, true)
264 }
265 return nil
266}
267
268// startFloating starts a prewarm if its slot remains uninitialized.
269func (d *Daemon) startFloating(sess *session, tb *tab, visible bool) {
270 cfg := d.currentFloatingConfig()
271 tb.mu.Lock()
272 generation := tb.beginFloatingWarmLocked(visible)
273 tb.mu.Unlock()
274 if generation != 0 {
275 d.launchFloating(sess, tb, cfg, generation, visible)
276 }
277}
278
279// floatingLaunchSpec is an immutable snapshot of one launch. It is built
280// before the worker starts so config reloads cannot affect that launch.
281// floatingLaunch owns one worker from queueing through installation or stale
282// result cleanup. Its done channel lets session teardown reap an in-flight
283// Open before returning.
284type floatingLaunch struct {
285 done chan struct{}
286}
287
288func (sess *session) registerFloatingLaunch() (*floatingLaunch, bool) {
289 launch := &floatingLaunch{done: make(chan struct{})}
290 sess.floatingLaunchMu.Lock()
291 defer sess.floatingLaunchMu.Unlock()
292 if sess.floatingLaunchStopping {
293 return nil, false
294 }
295 if sess.floatingLaunches == nil {
296 sess.floatingLaunches = make(map[*floatingLaunch]struct{})
297 }
298 sess.floatingLaunches[launch] = struct{}{}
299 return launch, true
300}
301
302func (sess *session) finishFloatingLaunch(launch *floatingLaunch) {
303 sess.floatingLaunchMu.Lock()
304 delete(sess.floatingLaunches, launch)
305 close(launch.done)
306 sess.floatingLaunchMu.Unlock()
307}
308
309func (sess *session) stopFloatingLaunches() {
310 sess.floatingLaunchMu.Lock()
311 sess.floatingLaunchStopping = true
312 sess.floatingLaunchMu.Unlock()
313}
314
315type floatingLaunchSpec struct {
316 sessionName string
317 cwd string
318 size domain.Size
319 ptyGeometry domain.Geometry
320 geometry floatingGeometry
321 paneStableID string
322 env []string
323 command string
324 args []string
325 fallback string
326 parentCtx context.Context
327 userOpen bool
328}
329
330// launchFloating snapshots launch inputs, then accounts for a worker through
331// Open, pane initialization, publication, and reader/coordinator startup.
332func (d *Daemon) launchFloating(sess *session, tb *tab, cfg domain.FloatingConfig, generation uint64, userOpen bool) {
333 spec, err := d.newFloatingLaunchSpec(sess, tb, cfg, userOpen)
334 if err != nil {
335 d.failFloatingLaunch(sess, tb, generation, userOpen, spec.sessionName, err)
336 return
337 }
338 launch, ok := sess.registerFloatingLaunch()
339 if !ok {
340 d.failFloatingLaunch(sess, tb, generation, userOpen, spec.sessionName, context.Canceled)
341 return
342 }
343 // Count the launch before its goroutine starts. It remains counted through
344 // install, including the reader/coordinator Adds, so shutdown cannot return
345 // before a late Open completion has either been rejected or fully joined.
346 d.sessWg.Go(func() {
347 defer sess.finishFloatingLaunch(launch)
348 d.openAndInstallFloating(sess, tb, spec, generation)
349 })
350}
351
352func (d *Daemon) newFloatingLaunchSpec(sess *session, tb *tab, cfg domain.FloatingConfig, userOpen bool) (floatingLaunchSpec, error) {
353 sess.mu.Lock()
354 name, cwd, sessCtx := sess.name, sess.cwd, sess.ctx
355 env := copyEnvironment(sess.env)
356 sess.mu.Unlock()
357 tb.mu.Lock()
358 geometry := calculateContentFloatingGeometry(domain.Size{Cols: tb.size.Cols, Rows: tb.size.Rows}, cfg)
359 size := rectSize(geometry.ptyRect())
360 focused := tb.focusedPane()
361 tabStableID, tabCtx := tb.stableID, tb.ctx
362 tb.mu.Unlock()
363 if focused != nil && d.procCwd != nil && focused.pty != nil {
364 if live, err := d.procCwd(focused.pty.Pid()); err == nil && live != "" {
365 cwd = live
366 }
367 }
368 if d.dirOrHome != nil {
369 cwd = d.dirOrHome(cwd)
370 }
371 paneStableID, err := newStableID("p")
372 if err != nil {
373 return floatingLaunchSpec{sessionName: name}, err
374 }
375 if tabCtx == nil {
376 tabCtx = sessCtx
377 }
378 if tabCtx == nil {
379 tabCtx = context.Background()
380 }
381 launch := d.shellLaunch(env)
382 if cfg.Command != "" {
383 launch.args = []string{"-lc", cfg.Command}
384 }
385 return floatingLaunchSpec{
386 sessionName: name,
387 cwd: cwd,
388 size: size,
389 ptyGeometry: sess.geometry.paneGeometry(size),
390 geometry: geometry,
391 paneStableID: paneStableID,
392 env: childEnvFrom(env, name, tabStableID, paneStableID),
393 command: launch.command,
394 args: launch.args,
395 fallback: floatingCommandFallback(cfg.Command, launch.command),
396 parentCtx: tabCtx,
397 userOpen: userOpen,
398 }, nil
399}
400
401// openAndInstallFloating runs entirely in the launch worker. No PTY operation
402// occurs under tb.mu; the pane is fully initialized before publication.
403func (d *Daemon) openAndInstallFloating(sess *session, tb *tab, spec floatingLaunchSpec, generation uint64) {
404 // Open is context-aware and is intentionally called without any daemon,
405 // session, tab, or launch-ownership lock. Cancellation makes teardown
406 // bounded even if the adapter is waiting to create the child.
407 if err := spec.parentCtx.Err(); err != nil {
408 return
409 }
410 lifetime := d.newPaneProcessLifetime(spec.parentCtx, sess.ctx)
411 ownedByPane := false
412 defer func() {
413 if !ownedByPane {
414 lifetime.abort()
415 }
416 }()
417 pty, err := d.ptys.Open(lifetime.ctx, spec.command, spec.args, spec.env, spec.cwd, spec.ptyGeometry)
418 if err != nil {
419 // Open retains ownership of a nonnil PTY only on success. Some factory
420 // implementations can return a partially opened PTY with an error, so
421 // release both resources before publishing the launch failure.
422 lifetime.abort()
423 if pty != nil {
424 _ = pty.Close()
425 }
426 d.failFloatingLaunch(sess, tb, generation, spec.userOpen, spec.sessionName, err)
427 return
428 }
429 ptyGeometry := spec.ptyGeometry
430 p := newPaneWithStableIDAndTitle(layout.PaneID("floating"), spec.paneStableID, pty, spec.size, spec.fallback, d.currentHistoryConfig())
431 p.geometry = ptyGeometry
432 setScreenGeometry(p.screen, ptyGeometry)
433 p.rect = spec.geometry.ptyRect()
434 p.popupGeometry = spec.geometry
435 if !lifetime.publish(p) {
436 _ = pty.Close()
437 d.failFloatingLaunch(sess, tb, generation, spec.userOpen, spec.sessionName, lifetime.ctx.Err())
438 return
439 }
440 ownedByPane = true
441 // The reader may run as soon as install returns; make its exit policy
442 // immutable before publishing the pane to the slot. Installed panes resolve
443 // their owner dynamically so a transferred tab never reaps through source
444 // session pointers captured by its launch.
445 p.onExit = func() { d.reapInstalledFloating(p) }
446 d.installFloating(sess, tb, p, generation)
447}
448
449func (d *Daemon) failFloatingLaunch(sess *session, tb *tab, generation uint64, userOpen bool, sessionName string, err error) {
450 tb.mu.Lock()
451 current := tb.failFloatingLocked(generation)
452 tb.mu.Unlock()
453 if current {
454 kind := "background-prewarm"
455 if userOpen {
456 kind = "user-open"
457 }
458 d.log.Warn("floating pty spawn failed", "err", err, "session", sessionName, "kind", kind)
459 // A background prewarm is speculative: the user never asked for it, so
460 // a toast here would be confusing noise. Only a user-initiated open
461 // (the user pressed the toggle-floating key) earns a toast; if a
462 // prewarm failure matters, the user's later open attempt will fail
463 // too and surface then.
464 if userOpen {
465 d.reportError(sess, domain.UserErr(domain.NoticeFloatingSpawn,
466 "couldn't open floating pane: command failed to start", err))
467 }
468 }
469}
470
471// installFloating installs only the current generation. A stale successful
472// launch is cancelled and closed outside the tab lock.
473func (d *Daemon) installFloating(sess *session, tb *tab, p *pane, generation uint64) {
474 if sess == nil || tb == nil || p == nil {
475 closeFloatingPane(p)
476 return
477 }
478 tb.mu.Lock()
479 installable := tb.floating.state == floatingWarming && tb.floating.generation == generation
480 if installable {
481 // Publish under pane.mu before the slot becomes hidden or visible. The
482 // tab-to-pane lock order also linearizes owner and slot publication.
483 publishPaneOwner(p, sess, tb, generation)
484 }
485 installed := installable && tb.installFloatingLocked(p, generation)
486 visible := installed && tb.floating.state == floatingVisible
487 tb.mu.Unlock()
488 if !installed {
489 closeFloatingPane(p)
490 return
491 }
492 d.reapplyThemeSession(sess)
493 d.startPaneGoroutines(sess, tb, p)
494 if visible {
495 attachments := sess.snapshotAttachments()
496 if len(attachments) == 0 {
497 // A headless resize may commit while Open is warming. Reconcile the
498 // visible floating geometry even without an attachment callback.
499 sess.geometry.applyVisibleFloatingLayout(d, sess, tb, nil)
500 return
501 }
502 tb.mu.Lock()
503 size := domain.Size{Cols: tb.size.Cols, Rows: tb.size.Rows + 2}
504 tb.mu.Unlock()
505 for _, ac := range attachments {
506 sess.geometry.requestResize(d, sess, ac, size, true)
507 }
508 }
509}
510
511// reapInstalledFloating resolves the pane's current immutable owner on every
512// attempt. If ownership changes before the tab lock is acquired, retrying the
513// lookup routes exit through the destination. The owner pointer and floating
514// slot generation are then checked together under tb.mu so an old exit can
515// never clear a reused slot.
516func (d *Daemon) reapInstalledFloating(p *pane) {
517 if p == nil {
518 return
519 }
520 for {
521 owner := p.ownerSnapshot()
522 if owner == nil || owner.session == nil || owner.tab == nil || owner.floatingSlotGeneration == 0 {
523 return
524 }
525 sess, tb, generation := owner.session, owner.tab, owner.floatingSlotGeneration
526 tb.mu.Lock()
527 if p.ownerSnapshot() != owner {
528 tb.mu.Unlock()
529 continue
530 }
531 visible := tb.floating.state == floatingVisible && tb.floating.pane == p && tb.floating.generation == generation
532 cleared := tb.clearFloatingLocked(p, generation)
533 tb.mu.Unlock()
534 if !cleared {
535 return
536 }
537 closeFloatingPane(p)
538 attachments := sess.snapshotAttachments()
539 copyCleared := false
540 for _, ac := range attachments {
541 ac.pruneCaptureFrames(p)
542 copyCleared = ac.overlays.clearCopyModeForPane(p) || copyCleared
543 if visible || copyCleared {
544 d.invalidateRender(sess, ac, true, "floating.go")
545 }
546 }
547 return
548 }
549}
550
551// teardownFloating invalidates first, then releases resources outside tb.mu.
552func (d *Daemon) teardownFloating(tb *tab, ac *attachedClient) {
553 if tb == nil {
554 return
555 }
556 tb.mu.Lock()
557 p := tb.takeFloatingLocked()
558 tb.mu.Unlock()
559 if ac != nil {
560 ac.overlays.clearCopyModeForPane(p)
561 ac.pruneCaptureFrames(p)
562 }
563 closeFloatingPane(p)
564}
565
566// closeFloatingPane releases a floating runtime at most once. It is called
567// only after a generation/identity check has detached the pane from its slot.
568func closeFloatingPane(p *pane) {
569 closePaneProcess(p)
570}
571
572func floatingCommandFallback(command, shell string) string {
573 if fields := strings.Fields(command); len(fields) > 0 {
574 return filepath.Base(fields[0])
575 }
576 return filepath.Base(shell)
577}