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 d.requestTransactionalResize(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 d.requestTransactionalResizeForLease(sess, ac, lease, size, true)
220 }
221 return d.requestTransactionalResize(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 d.requestTransactionalResize(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 geometry floatingGeometry
320 paneStableID string
321 env []string
322 command string
323 args []string
324 fallback string
325 parentCtx context.Context
326 userOpen bool
327}
328
329// launchFloating snapshots launch inputs, then accounts for a worker through
330// Open, pane initialization, publication, and reader/coordinator startup.
331func (d *Daemon) launchFloating(sess *session, tb *tab, cfg domain.FloatingConfig, generation uint64, userOpen bool) {
332 spec, err := d.newFloatingLaunchSpec(sess, tb, cfg, userOpen)
333 if err != nil {
334 d.failFloatingLaunch(sess, tb, generation, userOpen, spec.sessionName, err)
335 return
336 }
337 launch, ok := sess.registerFloatingLaunch()
338 if !ok {
339 d.failFloatingLaunch(sess, tb, generation, userOpen, spec.sessionName, context.Canceled)
340 return
341 }
342 // Count the launch before its goroutine starts. It remains counted through
343 // install, including the reader/coordinator Adds, so shutdown cannot return
344 // before a late Open completion has either been rejected or fully joined.
345 d.sessWg.Go(func() {
346 defer sess.finishFloatingLaunch(launch)
347 d.openAndInstallFloating(sess, tb, spec, generation)
348 })
349}
350
351func (d *Daemon) newFloatingLaunchSpec(sess *session, tb *tab, cfg domain.FloatingConfig, userOpen bool) (floatingLaunchSpec, error) {
352 sess.mu.Lock()
353 name, cwd, term, sessCtx := sess.name, sess.cwd, sess.terminal, sess.ctx
354 env := copyEnvironment(sess.env)
355 sess.mu.Unlock()
356 tb.mu.Lock()
357 geometry := calculateContentFloatingGeometry(domain.Size{Cols: tb.size.Cols, Rows: tb.size.Rows}, cfg)
358 size := rectSize(geometry.ptyRect())
359 focused := tb.focusedPane()
360 tabStableID, tabCtx := tb.stableID, tb.ctx
361 tb.mu.Unlock()
362 if focused != nil && d.procCwd != nil && focused.pty != nil {
363 if live, err := d.procCwd(focused.pty.Pid()); err == nil && live != "" {
364 cwd = live
365 }
366 }
367 if d.dirOrHome != nil {
368 cwd = d.dirOrHome(cwd)
369 }
370 paneStableID, err := newStableID("p")
371 if err != nil {
372 return floatingLaunchSpec{sessionName: name}, err
373 }
374 if tabCtx == nil {
375 tabCtx = sessCtx
376 }
377 if tabCtx == nil {
378 tabCtx = context.Background()
379 }
380 launch := d.shellLaunch(env)
381 if cfg.Command != "" {
382 launch.args = []string{"-lc", cfg.Command}
383 }
384 return floatingLaunchSpec{
385 sessionName: name,
386 cwd: cwd,
387 size: size,
388 geometry: geometry,
389 paneStableID: paneStableID,
390 env: childEnvFrom(env, name, tabStableID, paneStableID, term),
391 command: launch.command,
392 args: launch.args,
393 fallback: floatingCommandFallback(cfg.Command, launch.command),
394 parentCtx: tabCtx,
395 userOpen: userOpen,
396 }, nil
397}
398
399// openAndInstallFloating runs entirely in the launch worker. No PTY operation
400// occurs under tb.mu; the pane is fully initialized before publication.
401func (d *Daemon) openAndInstallFloating(sess *session, tb *tab, spec floatingLaunchSpec, generation uint64) {
402 // Open is context-aware and is intentionally called without any daemon,
403 // session, tab, or launch-ownership lock. Cancellation makes teardown
404 // bounded even if the adapter is waiting to create the child.
405 if err := spec.parentCtx.Err(); err != nil {
406 return
407 }
408 lifetime := d.newPaneProcessLifetime(spec.parentCtx, sess.ctx)
409 ownedByPane := false
410 defer func() {
411 if !ownedByPane {
412 lifetime.abort()
413 }
414 }()
415 pty, err := d.ptys.Open(lifetime.ctx, spec.command, spec.args, spec.env, spec.cwd, spec.size)
416 if err != nil {
417 // Open retains ownership of a nonnil PTY only on success. Some factory
418 // implementations can return a partially opened PTY with an error, so
419 // release both resources before publishing the launch failure.
420 lifetime.abort()
421 if pty != nil {
422 _ = pty.Close()
423 }
424 d.failFloatingLaunch(sess, tb, generation, spec.userOpen, spec.sessionName, err)
425 return
426 }
427 p := newPaneWithStableIDAndTitle(layout.PaneID("floating"), spec.paneStableID, pty, spec.size, spec.fallback)
428 p.rect = spec.geometry.ptyRect()
429 p.popupGeometry = spec.geometry
430 if !lifetime.publish(p) {
431 _ = pty.Close()
432 d.failFloatingLaunch(sess, tb, generation, spec.userOpen, spec.sessionName, lifetime.ctx.Err())
433 return
434 }
435 ownedByPane = true
436 // The reader may run as soon as install returns; make its exit policy
437 // immutable before publishing the pane to the slot. Installed panes resolve
438 // their owner dynamically so a transferred tab never reaps through source
439 // session pointers captured by its launch.
440 p.onExit = func() { d.reapInstalledFloating(p) }
441 d.installFloating(sess, tb, p, generation)
442}
443
444func (d *Daemon) failFloatingLaunch(sess *session, tb *tab, generation uint64, userOpen bool, sessionName string, err error) {
445 tb.mu.Lock()
446 current := tb.failFloatingLocked(generation)
447 tb.mu.Unlock()
448 if current {
449 kind := "background-prewarm"
450 if userOpen {
451 kind = "user-open"
452 }
453 d.log.Warn("floating pty spawn failed", "err", err, "session", sessionName, "kind", kind)
454 // A background prewarm is speculative: the user never asked for it, so
455 // a toast here would be confusing noise. Only a user-initiated open
456 // (the user pressed the toggle-floating key) earns a toast; if a
457 // prewarm failure matters, the user's later open attempt will fail
458 // too and surface then.
459 if userOpen {
460 d.reportError(sess, domain.UserErr(domain.NoticeFloatingSpawn,
461 "couldn't open floating pane: command failed to start", err))
462 }
463 }
464}
465
466// installFloating installs only the current generation. A stale successful
467// launch is cancelled and closed outside the tab lock.
468func (d *Daemon) installFloating(sess *session, tb *tab, p *pane, generation uint64) {
469 if sess == nil || tb == nil || p == nil {
470 closeFloatingPane(p)
471 return
472 }
473 tb.mu.Lock()
474 installable := tb.floating.state == floatingWarming && tb.floating.generation == generation
475 if installable {
476 // Publish under pane.mu before the slot becomes hidden or visible. The
477 // tab-to-pane lock order also linearizes owner and slot publication.
478 publishPaneOwner(p, sess, tb, generation)
479 }
480 installed := installable && tb.installFloatingLocked(p, generation)
481 visible := installed && tb.floating.state == floatingVisible
482 tb.mu.Unlock()
483 if !installed {
484 closeFloatingPane(p)
485 return
486 }
487 d.reapplyThemeSession(sess)
488 d.startPaneGoroutines(sess, tb, p)
489 if visible {
490 attachments := sess.snapshotAttachments()
491 if len(attachments) == 0 {
492 // A headless resize may commit while Open is warming. Reconcile the
493 // visible floating geometry even without an attachment callback.
494 d.applyVisibleFloatingLayout(sess, tb, nil)
495 return
496 }
497 tb.mu.Lock()
498 size := domain.Size{Cols: tb.size.Cols, Rows: tb.size.Rows + 2}
499 tb.mu.Unlock()
500 for _, ac := range attachments {
501 d.requestTransactionalResize(sess, ac, size, true)
502 }
503 }
504}
505
506// reapInstalledFloating resolves the pane's current immutable owner on every
507// attempt. If ownership changes before the tab lock is acquired, retrying the
508// lookup routes exit through the destination. The owner pointer and floating
509// slot generation are then checked together under tb.mu so an old exit can
510// never clear a reused slot.
511func (d *Daemon) reapInstalledFloating(p *pane) {
512 if p == nil {
513 return
514 }
515 for {
516 owner := p.ownerSnapshot()
517 if owner == nil || owner.session == nil || owner.tab == nil || owner.floatingSlotGeneration == 0 {
518 return
519 }
520 sess, tb, generation := owner.session, owner.tab, owner.floatingSlotGeneration
521 tb.mu.Lock()
522 if p.ownerSnapshot() != owner {
523 tb.mu.Unlock()
524 continue
525 }
526 visible := tb.floating.state == floatingVisible && tb.floating.pane == p && tb.floating.generation == generation
527 cleared := tb.clearFloatingLocked(p, generation)
528 tb.mu.Unlock()
529 if !cleared {
530 return
531 }
532 closeFloatingPane(p)
533 attachments := sess.snapshotAttachments()
534 copyCleared := false
535 for _, ac := range attachments {
536 ac.pruneCaptureFrames(p)
537 copyCleared = ac.overlays.clearCopyModeForPane(p) || copyCleared
538 if visible || copyCleared {
539 d.invalidateRender(sess, ac, true, "floating.go")
540 }
541 }
542 return
543 }
544}
545
546// teardownFloating invalidates first, then releases resources outside tb.mu.
547func (d *Daemon) teardownFloating(tb *tab, ac *attachedClient) {
548 if tb == nil {
549 return
550 }
551 tb.mu.Lock()
552 p := tb.takeFloatingLocked()
553 tb.mu.Unlock()
554 if ac != nil {
555 ac.overlays.clearCopyModeForPane(p)
556 ac.pruneCaptureFrames(p)
557 }
558 closeFloatingPane(p)
559}
560
561// closeFloatingPane releases a floating runtime at most once. It is called
562// only after a generation/identity check has detached the pane from its slot.
563func closeFloatingPane(p *pane) {
564 closePaneProcess(p)
565}
566
567func floatingCommandFallback(command, shell string) string {
568 if fields := strings.Fields(command); len(fields) > 0 {
569 return filepath.Base(fields[0])
570 }
571 return filepath.Base(shell)
572}